@sequenzy/mcp 0.0.159 → 0.0.161

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{AsyncLocalStorage as ir}from"node:async_hooks";var Le={name:"@sequenzy/mcp",version:"0.0.159",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 --packages=external",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/server":"2.0.0"},devDependencies:{"@modelcontextprotocol/client":"2.0.0","@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"}};class Y extends Error{statusCode;rawDetails;code;context;constructor(t,e,n,i,s){super(t);this.statusCode=e;this.rawDetails=n;this.code=i;this.context=s;this.name="McpApiError"}}function er(t){if(t instanceof Y)return{message:t.message,statusCode:t.statusCode,code:t.code,rawDetails:t.rawDetails,context:t.context};if(t instanceof Error)return{message:t.message};return{message:String(t)}}function tr(t){let e=t.match(/api key is missing required scopes?:\s*(.+)$/i);if(!e?.[1])return[];return[...new Set(e[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function nr(t){let e=er(t),n=e.message.trim()||"Unknown error",i=n.toLowerCase(),s=e.rawDetails?.trim()||n;if(e.context?.title||e.context?.description||e.context?.howToFix||e.context?.docsUrl)return{title:e.context.title??(e.statusCode===409?"Request conflict":"API request failed"),description:e.context.description??n,howToFix:e.context.howToFix??"Review the details below, adjust the tool input, and retry.",docsUrl:e.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp",details:s};if(e.code==="MCP_AUTH_REQUIRED"||i.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:s};if(e.statusCode===401||e.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:s};if(e.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:s};let r=tr(n);if(r.length>0){let o=r.map((m)=>`\`${m}\``).join(", "),d=r.every((m)=>m.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions",c=r.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 ${r.length===1?"scope":"scopes"}: ${o}.`,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 ${o}. 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 ${o}, or a preset covering all of them (${d}). 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.${c}`,docsUrl:"https://docs.sequenzy.com/concepts/mcp",details:s}}if(e.statusCode===403||i.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:s};if(i.includes("no company available")||i.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:s};if(e.statusCode===404||i.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:s};if(i.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:s};if(e.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:s};if(e.code==="AB_TEST_VARIANT_CONTENT_EDIT"||i.includes("update_ab_test_variant")&&(i.includes("a/b test")||i.includes("ab test")))return{title:"A/B variant copy cannot be edited here",description:n,howToFix:"Call `update_ab_test_variant` with `abTestId` and `variantId` from `get_sequence.sequence.emails[].abTest.variants` (or `get_ab_test`). Repeat once per variant for a whole-step rewrite. If the sequence is live or the test has activity, pass `confirmLiveChange: true`. Needs `ab_tests:write` and `sequences:write`, both on Safer agent access. If `update_ab_test_variant` is not in the MCP tool list, enable it on the Sequenzy connector - do not retry with `update_template`, `update_sequence_node`, or another email tool.",docsUrl:"https://docs.sequenzy.com/concepts/mcp#editing-the-content-of-a-sequence-ab-step",details:s};if(e.statusCode===429||i.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:s};if(e.code==="NETWORK_ERROR"||i.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:s};if(i.includes("unknown tool")||i.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:s};if(i.includes("is required")||i.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:s};if(e.statusCode&&e.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:s};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:s}}function ne(t){let e=nr(t);return[`Sequenzy MCP error: ${e.title}`,`Description: ${e.description}`,`How to fix: ${e.howToFix}`,`Docs: ${e.docsUrl}`,`Details: ${e.details}`].join(`
3
- `)}var sr="https://api.sequenzy.com",rr=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),Pe=new ir,_n=!1;function vn(){_n=!0}function $e(){return _n}var In=null;function ie(){let t=Pe.getStore();if(t)return t.selectedCompanyId??null;return In}function Ee(t){let e=Pe.getStore();if(e){e.selectedCompanyId=t;return}In=t}function mt(t,e){return Pe.run(t,e)}function kn(){return Pe.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??sr}function Sn(){return Pe.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function qn(t,e,n){let i=Sn();if(!i)throw new Y("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let s={"Content-Type":t,Authorization:`Bearer ${i}`,"x-sequenzy-client":`mcp/${Le.version}`},r=e===null?null:e??ie();if(r)s["x-company-id"]=r;return Object.assign(s,n),s}function Tn(){if(Sn())return;console.error(ne(new Y("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function N(t,e){let n=t[e];return typeof n==="string"&&n.trim()!==""?n.trim():void 0}function or(t){if(t===void 0)return;if(typeof t==="string")return t.trim()||void 0;return JSON.stringify(t)}function Pn(t){if(!t.trim())return{message:"Request failed"};try{let e=JSON.parse(t);if(typeof e==="string")return{message:e};let n=typeof e.error==="object"&&e.error!==null?e.error:void 0,i=N(e,"code")??(n?N(n,"code"):void 0),s=(typeof e.error==="string"?e.error:void 0)??(n?N(n,"message"):void 0)??N(e,"message")??N(e,"error")??t,r=N(e,"howToFix")??N(e,"resolution"),o={...N(e,"title")?{title:N(e,"title")}:{},...N(e,"description")?{description:N(e,"description")}:{},...r?{howToFix:r}:{},...N(e,"docsUrl")?{docsUrl:N(e,"docsUrl")}:{}},d=or(e.details);if(Object.keys(o).length>0||d)return{message:s,...i?{code:i}:{},...d?{details:d}:{},...Object.keys(o).length>0?{context:o}:{}};if(typeof e.error==="string")return{message:e.error,...i?{code:i}:{}};if(n)return{message:s,...i?{code:i}:{}};return{message:s,...i?{code:i}:{}}}catch{return{message:t}}}async function a(t,e,n,i,s){let r=qn("application/json",i,s),o;try{o=await fetch(`${kn()}${e}`,{method:t,headers:r,body:n?JSON.stringify(n):void 0})}catch(d){throw new Y(d instanceof Error?d.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!o.ok){let d=await o.text(),c=Pn(d);throw new Y(c.message,o.status,c.details??d,c.code,c.context)}return o.json()}async function En(t,e,n,i){let s=new URL(kn()).origin,r=new URL(t,`${s}/`);if(r.origin!==s){if(!rr.has(r.pathname))throw new Y("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");r=new URL(`${r.pathname}${r.search}`,`${s}/`)}let o;try{o=await fetch(r,{method:"PUT",headers:qn(n,i),body:e})}catch(d){throw new Y(d instanceof Error?d.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!o.ok){let d=await o.text(),c=Pn(d);throw new Y(c.message,o.status,c.details??d,c.code,c.context)}}import{McpServer as Oo}from"@modelcontextprotocol/server";var ht=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],xn={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}",account:"/dashboard/company/{companyId}/account",subscription:"/dashboard/company/{companyId}/account?tab=subscription",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 ar(t){let n=(t??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return n.length>0?n:"https://sequenzy.com"}function G(t){let e=t?.trim();return e?e:void 0}function J(t){return encodeURIComponent(t)}function C(t,e){return`${t}${e}`}function D(t,e=""){return`/dashboard/company/${J(t)}${e}`}function Cn(t,e,n){return C(t,`${D(e,"/settings")}?tab=${encodeURIComponent(n)}`)}function dr(t,e){let n=ht.map((i)=>[i,e?Cn(t,e,i):""]);return Object.fromEntries(n)}function Q(t={},e){let n=ar(e),i=G(t.companyId),s={},r=dr(n,i);if(!i)return{appUrl:n,routeTemplates:xn,settingsTabValues:ht,urls:s,settingsUrls:r};s.dashboard=C(n,D(i)),s.campaigns=C(n,D(i,"/campaign")),s.landingPages=C(n,D(i,"/landing-pages")),s.sequences=C(n,D(i,"/sequences")),s.account=C(n,D(i,"/account")),s.subscription=`${s.account}?tab=subscription`,s.settings=C(n,D(i,"/settings")),s.emails=C(n,D(i,"/emails")),s.subscribers=C(n,D(i,"/subscribers")),s.sentEmails=C(n,D(i,"/sent-emails")),s.segments=C(n,D(i,"/segments")),s.metrics=C(n,D(i,"/metrics")),s.transactional=C(n,D(i,"/transactional"));let o=G(t.campaignId);if(o)s.campaign=C(n,D(i,`/campaign/${J(o)}`)),s.campaignPreview=`${s.campaign}?step=review`;let d=G(t.landingPageId);if(d)s.landingPage=C(n,D(i,`/landing-pages/${J(d)}`));let c=G(t.sequenceId);if(c)s.sequence=C(n,D(i,`/sequences/${J(c)}`));let m=G(t.emailId)??G(t.templateId);if(m)s.email=C(n,D(i,`/emails/${J(m)}`)),s.template=s.email;let f=G(t.transactionalId);if(f)s.transactionalEmail=C(n,D(i,`/transactional/${J(f)}`));let w=G(t.emailSendId);if(w)s.emailSend=C(n,D(i,`/sent-emails/${J(w)}`));let g=G(t.domainId);if(g)s.domain=C(n,D(i,`/settings/domain/${J(g)}`)),s.domainVerify=`${s.domain}/verify`;let _=G(t.status);if(_)s.campaignList=C(n,D(i,`/campaign/list/${J(_)}`)),s.sequenceList=C(n,D(i,`/sequences/list/${J(_)}`));let q=G(t.settingsTab);if(q)s.settingsTab=q==="billing"||q==="subscription"?s.subscription:Cn(n,i,q);return{appUrl:n,routeTemplates:xn,settingsTabValues:ht,urls:s,settingsUrls:r}}var Dn=[{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, including persisted structural group blocks",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 Rn(t){try{let e;switch(t){case"sequenzy://dashboard":e=await a("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let n=await a("GET","/api/v1/account"),i=ie()??n.currentCompanyId;if(!i)throw Error("No company available. Create or select a company first.");e=await a("GET",`/api/v1/companies/${i}`);break}case"sequenzy://campaigns/recent":e=await a("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":e=await a("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":e=await a("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":e=await a("GET","/api/v1/sequences");break;case"sequenzy://templates":e=await a("GET","/api/v1/templates");break;case"sequenzy://segments":e=await a("GET","/api/v1/segments");break;case"sequenzy://tags":e=await a("GET","/api/v1/tags");break;case"sequenzy://health":e=await a("GET","/api/v1/health/deliverability");break;case"sequenzy://email-blocks":e=await a("GET","/api/v1/email-blocks");break;case"sequenzy://app-routes":e=Q();break;default:throw Error(`Unknown resource: ${t}`)}return{contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(e,null,2)}]}}catch(e){return{contents:[{uri:t,mimeType:"text/plain",text:ne(e)}]}}}function I(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function l(t,e){let n=t[e];if(typeof n!=="string")return;let i=n.trim();return i.length>0?i:void 0}function yt(t,e,n){let i=e[n];if(i===void 0||i===null)return[];if(typeof i==="string"){let r=i.trim();return r.length>0?[r]:[]}if(!Array.isArray(i))throw Error(`\`${n}\` must be an array of strings when calling \`${t}\`.`);let s=[];return i.forEach((r,o)=>{if(typeof r!=="string")throw Error(`\`${n}\` item ${o+1} must be a string when calling \`${t}\`.`);let d=r.trim();if(d.length>0&&!s.includes(d))s.push(d)}),s}function u(t,e,n){let i=l(e,n);if(i===void 0)throw Error(`\`${n}\` is required when calling \`${t}\`.`);return i}var Fe=' 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. If that tool is not in the MCP tool list, enable it on the Sequenzy connector rather than inferring fields from live HTML; the same reference is also at `sequenzy://email-blocks` (MCP resource), `GET /api/v1/email-blocks` (API), and `sequenzy blocks <type>` (CLI).';var gt=' 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.',ft=' 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.',bt=' 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" }.',wt=' A YouTube video block can override its still with { "type": "video", "videoUrl": "https://www.youtube.com/watch?v=...", "thumbnailUrl": "https://cdn.example.com/cover.jpg", "alt": "Watch the product tour" }. Replacing the blocks array without `thumbnailUrl` restores YouTube\'s own thumbnail; the video destination remains `videoUrl`.',_t="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.",He=" 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.",R=`${_t}${He}`,ze=' 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.',se='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`.',vt=" `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.",It="Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Recolor body copy with `styles.textColor` (or the top-level `textColor` alias), not with an inline `style` on `<p>` or `<span>`. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `textColor`, `textAlign`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`.",ae=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",M=`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. ${It} Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${He}${gt}${vt}${ae}${ft}${bt}${wt}${Fe}`,Be=" 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.",cr=` For action_email:${Be}`,Z=`Replacement Sequenzy email blocks. ${It}${He}${gt}${vt}${ae}${ft}${bt}${wt}${Fe}`,he=`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. ${It} Blocks can include repeat blocks over array variables such as items.${He}${gt}${vt}${ae}${ft}${bt}${wt}${Fe}`,de="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.",ce="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.",xe="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. Each block carries a `slot`, and slots render in order: `top` (full-width band above the hero, for announcement bars or banner images), `hero`, `form` (the card beside the hero), `body`, `footer`. A `video` block embeds a pasted YouTube URL with `url`, `title`, and an optional `aspectRatio` of 16:9, 4:3, 1:1, or 9:16 - other providers and direct video files are not supported. Button and pricing CTA URLs accept an external https URL or an in-page anchor: `#form` scrolls to the page's form block, `#section-<sectionId>` and `#block-<blockId>` scroll to any section or block, and `#top` returns to the top. Anchor CTAs stay in the same tab, so one form plus repeated CTAs is the way to build a single opt-in page. Scroll reveal is set on `theme`: `sectionAnimation` is one of none, fade, slide-up, zoom-in (default none) and `sectionAnimationSpeed` is one of slow, normal, fast (default normal). The reveal plays on the published page and is skipped for visitors who prefer reduced motion.",An="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.",kt=500,St=500,We=["is","contains","gt","gte","lt","lte","is_not_empty"],L={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},Ce=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],De=Ce.join(", "),le="Send Time Optimization is not a company or sequence setting. It is campaign-only: audit with list_campaigns or get_campaign (sendTimeOptimization, sendTimeWindowHours, default 12h window). Change a draft with update_campaign, or apply it when calling schedule_campaign. Sequences use sendingWindow (allowed local hours/days), which is a shared gate, not per-subscriber predicted send times.",qt="Deliver each recipient at their predicted best open hour within sendTimeWindowHours of scheduledAt (default 12h). Campaign-only: there is no company or sequence STO toggle. Sequences use sendingWindow instead. spreadOverHours takes precedence and turns STO off; sendInRecipientTimezone also turns it off.",Tt="STO delivery window in hours from scheduledAt (integer 1-24, default 12). Only used when sendTimeOptimization is true. Recipients whose predicted hour falls outside the window are snapped to the nearest edge. Sequences have no equivalent.",On="Each item also carries delivery pacing so an account-wide STO audit does not need one get_campaign call each: sendTimeOptimization, sendTimeWindowHours, spreadOverHours, sendInRecipientTimezone, and scheduledTimezone. STO is campaign-only; sequences use sendingWindow.",Pt="Delivery pacing: sendTimeOptimization is per-campaign Send Time Optimization (not a company or sequence setting). sendTimeWindowHours is that window in hours (default 12, max 24). spreadOverHours is a linear spread that turns STO off. sendInRecipientTimezone is a third mutually exclusive mode. Sequences use sendingWindow, which is an allowed-hours gate, not per-subscriber optimization.",Ge={type:"object",description:"Optional send window for every email step in the sequence. This is not Send Time Optimization: it is a shared allowed-hours gate, not per-subscriber predicted send times. STO is campaign-only (list_campaigns, get_campaign, update_campaign, schedule_campaign). 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},lr={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},ye={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:lr,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},ge={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},fe={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},Et={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",description:"Outer canvas behind the email."},content:{type:"string",description:"Inner content card the blocks sit on. Omit to preserve its current value; when no content color is stored, the card follows background."},surface:{type:"string",description:"Nested cards and tinted tiles."},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}};var pr={type:["object","null"],description:"Visual theme override for this step's linked email only; the company-wide default is left untouched, as is every other email. Partial update: the patch merges into this email's current theme, so `{ colors: { background: '#f3f4f6' } }` repaints the outer canvas and keeps its fonts, spacing, and other colors; use colors.content for the inner card and colors.surface for nested cards. A step with no override merges into the company theme rather than the platform preset. Pass null to drop the override so the step follows the company theme again. Numeric values are clamped to supported ranges. Use update_company to change the account-wide default instead.",properties:Et,additionalProperties:!1},Ke=pr,xt={type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails with supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded for branded chrome. This does not change the company-wide default and is not `style`, which is a prompt-generation hint valid only with `prompt`. 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."},Ct={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, emailTheme (per-email colors/typography/layout override - patch { colors: { background: '#ffffff' } } to repaint one step without touching the company default, or null to inherit it again), 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.${cr}`,properties:{emailTheme:Ke,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},Ve={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:Ct,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},be=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],we=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","campaign.sent","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","subscriber_import.completed","sequence.finished","sequence.failed","poll.answered"];var ur=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","get_attio_mapping","list_web_tracking_keys","get_web_tracking_key","list_integration_capabilities","list_integration_activity","get_event_schema","get_email_block_schema","list_sender_profiles","get_notification_preferences","get_tracking_settings","get_email_design_system","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","list_campaign_goals","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","list_popups","get_popup","get_popup_embed","get_recipient_suppression","list_recipient_suppressions","list_landing_pages","get_landing_page","get_landing_page_stats","render_landing_page","list_sequences","get_sequence","simulate_sequence","list_sequence_enrollments","get_sequence_enrollment","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","get_sms_usage"]),mr=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","update_tracking_settings","update_email_design_system","update_sms_number_label","release_sms_number","resume_sending","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","set_integration_list_targeting","sync_integration","activate_integration_pixel","update_attio_settings","create_web_tracking_key","update_web_tracking_key","delete_web_tracking_key","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","import_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","select_ab_test_winner","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","remove_landing_page_domain","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_campaign_goal","update_campaign_goal","delete_campaign_goal","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"]),hr=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","remove_landing_page_domain","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","get_attio_mapping","update_attio_settings","enable_sequence","unarchive_sequence","resume_sequence_enrollments","move_sequence_enrollments","send_email","select_ab_test_winner","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),yr=new Set(["revoke_api_key","delete_api_key","remove_subscriber","delete_subscriber_note","delete_product","delete_web_tracking_key","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","remove_landing_page_domain","unpublish_landing_page","delete_popup","set_integration_sync_enabled","set_integration_list_targeting","disable_sequence","archive_sequence","delete_campaign_goal","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","release_sms_number"]);function gr(t){let e=ur.has(t),n=mr.has(t);if(e===n)throw Error(`MCP tool "${t}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:e,destructiveHint:e?!1:yr.has(t),openWorldHint:hr.has(t)}}var fr={ab:"A/B",ai:"AI",api:"API",html:"HTML",id:"ID",mcp:"MCP",nps:"NPS",sms:"SMS",url:"URL",urls:"URLs",utm:"UTM"};function br(t){return t.split("_").filter(Boolean).map((e)=>fr[e]??e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Un(t){return{...t,annotations:{...t.annotations,title:t.annotations?.title??br(t.name),...gr(t.name)}}}var Dt={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"]},wr=Object.entries(Dt).map(([t,e])=>`${t}: ${e.join(", ")}`).join("; "),Rt={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>\`, an email-type scope via \`marketing:<timeRange>\` (marketing-policy campaign, automation, and Send API traffic) or \`transactional:<timeRange>\` (transactional-policy sends), or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${se}`},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: ${wr}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Array-of-object attributes use wildcard paths such as \`history_events[].eventvenue_id:2103\`; AND-ing two such positive filters on the same \`foo[]\` prefix matches one shared element (negative filters like is_not/not_contains/is_empty stay independent). 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), \`marketing:7d\` / \`transactional:30d\` to scope by email type (marketing includes marketing-policy campaign, automation, and Send API traffic; policy scopes require a send-time policy snapshot, so ambiguous older events remain unscoped; email-type values work with is/is_not and the emailBounced subtype operators, e.g. emailSent is_not \`marketing:7d\` = no captured marketing email in the last 7 days), 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). ${se}`}},required:["field","operator","value"],additionalProperties:!1},At={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 Ye(t){if(!Array.isArray(t))return t;return t.map((e)=>{if(typeof e!=="object"||e===null)return e;let n=e;if(typeof n.id==="string"&&n.id.trim()!=="")return n;return{...n,id:crypto.randomUUID()}})}function Je(t){if(typeof t!=="object"||t===null)return t;let e=t;if(e.kind==="filter"||"field"in e||"operator"in e||"value"in e){let n=Ye([e]);return Array.isArray(n)?n[0]:e}if(e.kind!=="group")return t;return{...e,id:typeof e.id==="string"&&e.id.trim()!==""?e.id:crypto.randomUUID(),children:Array.isArray(e.children)?e.children.map(Je):[]}}function _r(t){let e=t.indexOf(":");return e!==-1&&t.substring(0,e).trim().length>0}function vr(t){let e=t.indexOf(":");return e!==-1&&t.substring(e+1).trim().length>0}function _e(t){if(t==="all")return!0;let e=t.match(/^(\d+)d$/);if(!e?.[1])return!1;let n=Number.parseInt(e[1],10);return Number.isInteger(n)&&n>0}var Ir=new Set(["emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained"]);function kr(t,e){let n=e.trim(),i=t==="at_least"||t==="less_than_count";if(n.startsWith("campaign:")){if(i)return"Campaign-specific engagement values cannot be combined with count operators.";return n.slice(9).trim()?null:'Campaign-specific engagement filters must use "campaign:<campaignId>".'}if(n.startsWith("marketing:")||n.startsWith("transactional:")){if(i)return"Email-type engagement values cannot be combined with count operators.";let s=n.indexOf(":");return _e(n.slice(s+1).trim())?null:'Email-type engagement filters must use "marketing:<timeRange>" or "transactional:<timeRange>", like "marketing:7d".'}if(i){if(_e(n))return null;let s=n.indexOf(":"),r=n.slice(0,s).trim(),o=Number.parseInt(r,10),d=n.slice(s+1).trim();return s>0&&/^\d+$/.test(r)&&Number.isInteger(o)&&o>0&&_e(d)?null:'Engagement count filters must use "count:timeRange", like "10:30d" or "10:all".'}return _e(n)?null:'Engagement filters must use a time range like "30d" or "all", "campaign:<campaignId>", or an email-type scope like "marketing:7d" or "transactional:7d".'}function Sr(t,e){let n=e.split(":");if(t==="at_least"||t==="less_than_count"){if(n.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let r=n.slice(0,-2).join(":").trim(),o=n.at(-2),d=n.at(-1),c=o===void 0?Number.NaN:Number.parseInt(o,10);return r&&Number.isInteger(c)&&c>0&&d!==void 0&&_e(d)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(n.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let i=n.slice(0,-1).join(":").trim(),s=n.at(-1);return i&&s!==void 0&&_e(s)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function qr(t){let e=t.indexOf(":");if(e===-1)return{productId:t,subfilter:null,rawValue:null};let n=t.substring(0,e),i=t.substring(e+1),s=i.indexOf(":");if(s===-1)return{productId:n,subfilter:i,rawValue:null};return{productId:n,subfilter:i.substring(0,s),rawValue:i.substring(s+1)}}function Tr(t){return t.trim().toLowerCase().replace(/[-\s]+/g,"_")}function Pr(t){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(t)}function Er(t,e){if(e==="cancels_at"||e==="cancel_at"||e==="cancellation_at")return!0;if(t==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(e);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(e)}function xr(t){return["is","is_not","gte","lte","gt","lt"].includes(t)}function Cr(t,e,n){if(t==="stripeProduct"){if(e!=="at_least"&&e!=="less_than_count")return null;let d=n.indexOf(":");if(d===-1)return null;let c=n.substring(0,d).trim(),m=Number.parseInt(n.substring(d+1).trim(),10);return c&&Number.isInteger(m)&&m>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(t!=="stripeCurrentProduct"&&t!=="stripeTrialProduct")return null;let{productId:i,subfilter:s,rawValue:r}=qr(n);if(!i.trim())return"Stripe product filters must include a product ID.";if(!s)return e==="is"||e==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let o=Tr(s);if(Pr(o))return e==="is"||e==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!Er(t,o))return`Unsupported Stripe product subfilter "${s}".`;if(!xr(e))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return r?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var jn=new Set(["shopify","woocommerce","api"]);function Dr(t,e){let n=e.trim(),i=n.indexOf(":");if(i!==-1&&jn.has(n.substring(0,i).trim()))n=n.substring(i+1).trim();if(!n)return'Purchased Product filters must include a product ID, like "shopify:42".';if(t!=="at_least"&&t!=="less_than_count")return null;let s=n.lastIndexOf(":");if(s===-1)return null;let r=n.substring(0,s).trim(),o=Number.parseInt(n.substring(s+1).trim(),10);return r&&Number.isInteger(o)&&o>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function Rr(t,e){let n=e.trim(),i=n.indexOf(":");if(i!==-1&&jn.has(n.substring(0,i).trim()))n=n.substring(i+1).trim();if(!n)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(t!=="at_least"&&t!=="less_than_count")return null;let s=n.lastIndexOf(":");if(s===-1)return null;let r=n.substring(0,s).trim(),o=Number.parseInt(n.substring(s+1).trim(),10);return r&&Number.isInteger(o)&&o>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function Ar(t){let e;try{e=JSON.parse(t)}catch{return`Poll response filters must use valid JSON. ${se}`}if(!I(e)||e.v!==1||typeof e.campaignId!=="string"||!e.campaignId.trim()||typeof e.blockId!=="string"||!e.blockId.trim()||!I(e.match))return`Poll response filter context is invalid. ${se}`;let n=e.match;if(n.kind==="answer"&&typeof n.value==="string"&&n.value.length>0)return null;if(n.kind==="npsBucket"&&(n.bucket==="promoters"||n.bucket==="passives"||n.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${se}`}function Qe(t){if(typeof t!=="object"||t===null)return"Segment filters must be objects.";let e=t,n=e.field,i=e.operator,s=e.value;if(typeof n!=="string"||!(n in Dt))return`Unsupported segment filter field "${String(n)}".`;if(typeof i!=="string")return`Segment filter "${n}" must include an operator.`;let r=Dt[n];if(!r.includes(i))return`Operator "${i}" is not supported for ${n} filters. Use one of: ${r.join(", ")}.`;if(i!=="is_empty"&&i!=="is_not_empty"&&(typeof s!=="string"||s.trim().length===0))return`Segment filter "${n}" must include a value.`;if(n==="attribute"){if(typeof s!=="string")return'Attribute filters must include a value: "attributeName:value", or "attributeName:" for empty checks.';if(!_r(s))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(i!=="is_empty"&&i!=="is_not_empty"&&!vr(s))return'Attribute filters must include a value after "attributeName:".'}if(n==="event"&&typeof s==="string"){let o=Sr(i,s);if(o)return o}if(Ir.has(n)&&typeof s==="string"){let o=kr(i,s);if(o)return o}if(n==="pollResponse"&&typeof s==="string"){let o=Ar(s);if(o)return o}if((n==="stripeProduct"||n==="stripeCurrentProduct"||n==="stripeTrialProduct")&&typeof s==="string"){let o=Cr(n,i,s);if(o)return o}if(n==="commerceProduct"&&typeof s==="string"){let o=Dr(i,s);if(o)return o}if(n==="commerceCollection"&&typeof s==="string"){let o=Rr(i,s);if(o)return o}if(n==="tag"&&(i==="contains"||i==="not_contains")){if(!(typeof s==="string"&&s.split(",").map((d)=>d.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function Ze(t){if(typeof t!=="object"||t===null)return[];let e=t;if(e.kind==="filter"||"field"in e||"operator"in e||"value"in e){let n=Qe(e);return n?[n]:[]}if(Array.isArray(e.children))return e.children.flatMap(Ze);return[]}function F(t,e,n){if(e.html!==void 0&&e.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${t}\`, not both.`);if(e.blocks!==void 0&&!Array.isArray(e.blocks))throw Error(`\`blocks\` must be an array when calling \`${t}\`.`);if(n?.requireContent&&e.html===void 0&&e.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${t}\`.`)}function X(t,e){if(e.labels===void 0)return;if(!Array.isArray(e.labels))throw Error(`\`labels\` must be an array when calling \`${t}\`.`);if(e.labels.some((n)=>typeof n!=="string"||n.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${t}\`.`)}function Ft(t,e,n={}){if(Or(t,e,n),e.listScope===void 0)return;if(e.listId!==void 0||e.listIds!==void 0)throw Error(`Provide either listId/listIds or listScope when calling ${t}, not both.`);if((e.trigger??n.defaultTrigger)!=="contact_added")throw Error(`listScope only applies to a contact_added trigger when calling ${t}.`)}function Or(t,e,n={}){let i=e.trigger??n.defaultTrigger;for(let[s,r]of[["listIds","contact_added"],["tagNames","tag_added"]]){let o=e[s];if(o===void 0)continue;if(!Array.isArray(o)||o.length===0)throw Error(`\`${s}\` must be a non-empty array of strings when calling \`${t}\`.`);if(o.some((d)=>typeof d!=="string"||d.trim()===""))throw Error(`\`${s}\` must contain only non-empty strings when calling \`${t}\`.`);if(i!==void 0&&i!==r)throw Error(`\`${s}\` only applies to a ${r} trigger when calling \`${t}\`.`)}}function Ln(t){let e=t.filters!==void 0,n=t.root!==void 0;if(e&&n)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!e&&!n)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(e){if(!Array.isArray(t.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(t.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(n&&(typeof t.root!=="object"||t.root===null))throw Error("`root` must be an object when calling `create_segment`.");let i=e?t.filters.flatMap((s)=>{let r=Qe(s);return r?[r]:[]}):Ze(t.root);if(i.length>0)throw Error(i[0]??"Invalid segment filter in `create_segment`.")}function $n(t){let e=t.filters!==void 0,n=t.root!==void 0;if(e&&n)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(t.name===void 0&&t.filterJoinOperator===void 0&&!e&&!n)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(e){if(!Array.isArray(t.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(t.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(n&&(typeof t.root!=="object"||t.root===null))throw Error("`root` must be an object when calling `update_segment`.");let i=e?t.filters.flatMap((s)=>{let r=Qe(s);return r?[r]:[]}):n?Ze(t.root):[];if(i.length>0)throw Error(i[0]??"Invalid segment filter in `update_segment`.")}var Ot=["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","defaultSubscriberListIds"];function Ut(t,e,n){if(e[n]!==void 0&&!I(e[n]))throw Error(`\`${n}\` must be an object when calling \`${t}\`.`)}function Nn(t,e,n){if(e[n]!==void 0&&!Array.isArray(e[n]))throw Error(`\`${n}\` must be an array when calling \`${t}\`.`)}function Fn(t){let e=new Set(["companyId",...Ot]),n=Object.keys(t).filter((s)=>!e.has(s));if(n.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${n.length===1?"":"s"}: ${n.map((s)=>`\`${s}\``).join(", ")}.`);let i={};for(let s of Ot)if(t[s]!==void 0)i[s]=t[s];if(Object.keys(i).length===0)throw Error(`Provide at least one of ${Ot.map((s)=>`\`${s}\``).join(", ")} when calling \`update_company\`.`);for(let s of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailDesignPrompt","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(t[s]!==void 0&&typeof t[s]!=="string")throw Error(`\`${s}\` must be a string when calling \`update_company\`.`);if(Ut("update_company",t,"brandColors"),Ut("update_company",t,"socialLinks"),Ut("update_company",t,"pricing"),t.emailTheme!==void 0&&t.emailTheme!==null&&!I(t.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");if(Nn("update_company",t,"valueProps"),Nn("update_company",t,"testimonials"),t.defaultSubscriberListIds!==void 0&&t.defaultSubscriberListIds!==null){if(!Array.isArray(t.defaultSubscriberListIds))throw Error("`defaultSubscriberListIds` must be an array of list IDs, null for every list, or [] for no list when calling `update_company`.");if(t.defaultSubscriberListIds.some((s)=>typeof s!=="string"||s.trim()===""))throw Error("`defaultSubscriberListIds` must contain non-empty list IDs when calling `update_company`.")}for(let s of["replyTrackingEnabled","forwardReplies"])if(t[s]!==void 0&&typeof t[s]!=="boolean")throw Error(`\`${s}\` must be a boolean when calling \`update_company\`.`);if(t.replyTrackingDomainMode!==void 0&&t.replyTrackingDomainMode!=="sequenzy"&&t.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof t.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(t.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let s of["fromEmail","replyTo"]){let r=t[s];if(typeof r==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r.trim()))throw Error(`\`${s}\` must be a valid email address when calling \`update_company\`.`)}return i}var jt=["openTrackingEnabled","clickTrackingEnabled","transactionalOpenTrackingEnabled","transactionalClickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","doubleOptInRedirectUrl","autoUtmEnabled","autoUtmSettings"],Nt=["source","medium","campaign","content","term"];function Hn(t){let e=new Set(["companyId",...jt]),n=Object.keys(t).filter((s)=>!e.has(s));if(n.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${n.length===1?"":"s"}: ${n.map((s)=>`\`${s}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let i={};for(let s of jt)if(t[s]!==void 0)i[s]=t[s];if(Object.keys(i).length===0)throw Error(`Provide at least one of ${jt.map((s)=>`\`${s}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let s of["openTrackingEnabled","clickTrackingEnabled","transactionalOpenTrackingEnabled","transactionalClickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(t[s]!==void 0&&typeof t[s]!=="boolean")throw Error(`\`${s}\` must be a boolean when calling \`update_tracking_settings\`.`);if(t.defaultAttributionWindowHours!==void 0&&(typeof t.defaultAttributionWindowHours!=="number"||!Number.isInteger(t.defaultAttributionWindowHours)||t.defaultAttributionWindowHours<1||t.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(t.doubleOptInRedirectUrl!==void 0&&t.doubleOptInRedirectUrl!==null&&typeof t.doubleOptInRedirectUrl!=="string")throw Error("`doubleOptInRedirectUrl` must be a URL string or null when calling `update_tracking_settings`.");if(t.autoUtmSettings!==void 0&&t.autoUtmSettings!==null&&!I(t.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(I(t.autoUtmSettings)){let s=t.autoUtmSettings,r=Object.keys(s).filter((o)=>!Nt.includes(o));if(r.length>0)throw Error(`\`autoUtmSettings\` accepts only ${Nt.map((o)=>`\`${o}\``).join(", ")}. Unsupported: ${r.map((o)=>`\`${o}\``).join(", ")}.`);for(let o of Nt){let d=s[o];if(d!==void 0&&d!==null&&typeof d!=="string")throw Error(`\`autoUtmSettings.${o}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return i}var Xe={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},Lt={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function Ur(t){let{profileKey:e,emailKey:n,nameKey:i}=t.pair;if(t.nameHasStepOverride)return`To keep \`${e}\` and still change the display name, send \`${e}\` on its own and set \`${i}\` on each email step, where it applies as a per-step display-name override. To change the address instead, omit \`${e}\` and send \`${n}\` (optionally with \`${i}\`).`;return`To use a different address or display name, omit \`${e}\` and send \`${n}\` (optionally with \`${i}\`) instead.`}function $t(t){let{profileKey:e,emailKey:n,nameKey:i,addressLabel:s}=t.pair,r=t.args[e]!==void 0,o=t.args[n]!==void 0,d=t.args[i]!==void 0,c=t.location?`for ${t.location} when calling \`${t.toolName}\``:`when calling \`${t.toolName}\``,m=`\`${e}\` already sets both the ${s} address and the display name, so send it without \`${n}\`${t.nameIsOverride?"":` and \`${i}\``}.`,f=Ur({pair:t.pair,nameHasStepOverride:t.nameHasStepOverride}),w=`For a per-email display name, set \`${i}\` on the email steps instead.`;if(r&&o){let[g,_]=t.profileFirst?[e,n]:[n,e],q=d&&t.nameHasStepOverride?` ${w}`:"";throw Error(`Provide either \`${g}\` or \`${_}\` ${c}, not both. ${m}${q}`)}if(r&&d&&!t.nameIsOverride)throw Error(`\`${i}\` cannot be combined with \`${e}\` ${c}. ${m} ${f}`);if(d&&!o&&!t.nameIsOverride)throw Error(`\`${i}\` requires \`${n}\` ${c}. Send \`${i}\` with the \`${n}\` it names, or send \`${e}\` on its own to use an existing profile's address and name.${t.nameHasStepOverride?` ${w}`:""}`)}function re(t,e,n){let i=n?.replyFirst?[Lt,Xe]:[Xe,Lt];for(let s of i)$t({toolName:t,args:e,pair:s,nameHasStepOverride:n?.hasEmailSteps===!0&&s===Xe})}var zn=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function jr(t){return zn.some((e)=>t[e]!==void 0)}function Nr(t){if(typeof t.nodeType==="string")return t.nodeType==="action_email";return t.type===void 0||t.type==="email"}function et(t,e,n){for(let i of zn){let s=n[i];if(s!==void 0&&typeof s!=="string")throw Error(`\`${i}\` must be a string for ${e} when calling \`${t}\`.`)}$t({toolName:t,args:n,pair:Xe,location:e,profileFirst:!0,nameIsOverride:!0}),$t({toolName:t,args:n,pair:Lt,location:e,profileFirst:!0})}function Ht(t,e,n){if(jr(n)&&!Nr(n))throw Error(`Sender identity fields are only supported for email steps at ${e} when calling \`${t}\`.`);et(t,e,n)}function Mn(t,e,n){if(!Array.isArray(n))return;n.forEach((i,s)=>{if(I(i))et(t,`${e}[${s}]`,i)})}function Mt(t,e,n){if(!Array.isArray(n))return;n.forEach((i,s)=>{if(I(i))Ht(t,`${e}[${s}]`,i)})}function Mr(t){if(Mn("update_sequence","emails",t.emails),Mn("update_sequence","steps",t.steps),I(t.insertSteps))Mt("update_sequence","insertSteps.steps",t.insertSteps.steps);if(!I(t.branch))return;if(Array.isArray(t.branch.branches))t.branch.branches.forEach((n,i)=>{if(I(n))Mt("update_sequence",`branch.branches[${i}].steps`,n.steps)});Mt("update_sequence","branch.elseSteps",t.branch.elseSteps)}function Bn(t){X("update_sequence",t);let e=["listId","listIds","listScope","tagName","tagNames","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(t.trigger===void 0&&e.some((i)=>t[i]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(Ft("update_sequence",t),re("update_sequence",t,{hasEmailSteps:!0}),t.clearEnrollmentFieldPath===!0&&t.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(t.clearSendingWindow===!0&&t.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(t.clearBccEmails===!0&&t.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(t.branch!==void 0&&t.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");Mr(t);let n={...t};if(delete n.clearEnrollmentFieldPath,delete n.clearSendingWindow,delete n.clearBccEmails,t.clearEnrollmentFieldPath===!0)n.enrollmentFieldPath=null;if(t.clearSendingWindow===!0)n.sendingWindow=null;if(t.clearBccEmails===!0)n.bccEmails=null;return n}function Wn(t,e){let n=e.triggerType??"event";if(n==="event"){if(typeof e.triggerEventName!=="string"||e.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${t}\` with an event goal (the default \`triggerType\`).`);return}if(n==="tag_added"){if(typeof e.triggerTagName!=="string"||e.triggerTagName.trim().length===0)throw Error(`\`triggerTagName\` is required when calling \`${t}\` with \`triggerType: "tag_added"\`.`);return}if(typeof e.attributePath!=="string"||e.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${t}\` with \`triggerType: "attribute_change"\`.`);let i=e.attributeCondition??"changed",s=typeof e.attributeValue==="string"&&e.attributeValue.trim().length>0,r=typeof e.attributePreviousValue==="string"&&e.attributePreviousValue.trim().length>0;if((i==="changed_to"||i==="changed_from_to")&&!s)throw Error(`\`attributeValue\` is required when calling \`${t}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(i==="changed_from_to"&&!r)throw Error(`\`attributePreviousValue\` is required when calling \`${t}\` with \`attributeCondition: "changed_from_to"\`.`)}function Gn(t){Wn("create_sequence_goal",t)}function Kn(t){Wn("create_campaign_goal",t)}function Vn(t){Jn("update_sequence_goal",t)}function Yn(t){Jn("update_campaign_goal",t)}function Jn(t,e){if(typeof e.triggerEventName==="string"&&e.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` must be a non-empty string when provided to \`${t}\`.`);if(typeof e.attributePath==="string"&&e.attributePath.trim().length===0)throw Error(`\`attributePath\` must be a non-empty string when provided to \`${t}\`.`);if(typeof e.triggerTagName==="string"&&e.triggerTagName.trim().length===0)throw Error(`\`triggerTagName\` must be a non-empty string when provided to \`${t}\`.`)}function ni(t,e,n){let i=u(t,e,"nodeId");if(!I(e.changes)||Object.keys(e.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${n} when calling \`${t}\`.`);let s=u(t,e,"expectedUpdatedAt");return{nodeId:i,changes:e.changes,expectedUpdatedAt:s}}function ii(t){let e=ni("update_sequence_node",t,"the node update");return{...t.confirmLiveChange!==void 0&&{confirmLiveChange:t.confirmLiveChange},nodeUpdates:[e]}}function si(t){if(!Array.isArray(t.updates)||t.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let e=new Set,n=t.updates.map((i,s)=>{if(!I(i))throw Error(`\`updates[${s}]\` must be an object when calling \`update_sequence_nodes\`.`);let r=ni("update_sequence_nodes",i,`updates[${s}]`),o=String(r.nodeId);if(e.has(o))throw Error(`\`updates[${s}]\` targets duplicate nodeId '${o}' when calling \`update_sequence_nodes\`.`);return e.add(o),r});return{...t.confirmLiveChange!==void 0&&{confirmLiveChange:t.confirmLiveChange},nodeUpdates:n}}function ri(t){let e=u("edit_sequence_graph",t,"action"),n=u("edit_sequence_graph",t,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(e))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let s=l(t,"nodeId"),r=l(t,"afterNodeId"),o=l(t,"beforeNodeId"),d=t.edges;if(e!=="replace_edges"&&!s)throw Error(`\`nodeId\` is required for ${e} when calling \`edit_sequence_graph\`.`);if(e==="replace_edges"&&s)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let c=e==="move_node"||e==="duplicate_node";if(c&&(r?1:0)+(o?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${e} when calling \`edit_sequence_graph\`.`);if(!c&&(r||o))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${e} when calling \`edit_sequence_graph\`.`);if((e==="replace_edges"||e==="delete_node"&&d!==void 0)&&(!Array.isArray(d)||d.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${e} when calling \`edit_sequence_graph\`.`);if((e==="move_node"||e==="duplicate_node")&&d!==void 0)throw Error(`\`edges\` is not used with ${e} when calling \`edit_sequence_graph\`.`);let m=Array.isArray(d)?d.map((f,w)=>{if(!I(f))throw Error(`\`edges\` item ${w+1} must be an object when calling \`edit_sequence_graph\`.`);let g=u("edit_sequence_graph",f,"sourceNodeId"),_=u("edit_sequence_graph",f,"targetNodeId");if(f.condition!==void 0&&f.condition!==null&&!I(f.condition))throw Error(`\`edges\` item ${w+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:g,targetNodeId:_,...I(f.condition)?{condition:f.condition}:{}}}):void 0;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},graphEdit:{action:e,expectedRevision:n,...s?{nodeId:s}:{},...r?{afterNodeId:r}:{},...o?{beforeNodeId:o}:{},...m?{edges:m}:{}}}}function Lr(t,e,n){if((t==="has_tag"||t==="does_not_have_tag")&&!l(e,"tagId")&&!l(e,"tagName"))throw Error(`\`${n}\` must provide \`tagId\` or \`tagName\` for ${t} when calling \`insert_sequence_step\`.`);if(t==="in_list"&&!l(e,"listId"))throw Error(`\`${n}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(t==="in_segment"&&!l(e,"segmentId"))throw Error(`\`${n}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(t==="event_received"&&!l(e,"eventName"))throw Error(`\`${n}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(t.startsWith("field_")&&(!l(e,"fieldName")||!l(e,"fieldValue")))throw Error(`\`${n}\` must provide \`fieldName\` and \`fieldValue\` for ${t} when calling \`insert_sequence_step\`.`)}var $r=["conditionType","tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"];function oi(t){let e=l(t,"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(e))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(e==="logic_wait_for_event"){let o=u("insert_sequence_step",t,"eventName"),d=t.timeoutDays,c=d===void 0?7:d;if(typeof c!=="number"||!Number.isInteger(c)||c<1||c>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let m=l(t,"timeoutAction")??"continue";if(m!=="continue"&&m!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let f={steps:[{nodeType:"logic_wait_for_event",config:{label:l(t,"label")??`Wait for ${o}`,eventName:o,timeoutDays:c,timeoutAction:m}}]},w=l(t,"afterNodeId");if(w)f.afterNodeId=w;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},insertSteps:f}}if(e==="logic_branch"){let o=u("insert_sequence_step",t,"afterNodeId");if(!Array.isArray(t.branches)||t.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let d=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"]),c=l(t,"splitMode")??"condition";if(c!=="condition"&&c!=="random")throw Error("`splitMode` must be `condition` or `random` when inserting `logic_branch` with `insert_sequence_step`.");let m=c==="random";if(m){if(!Array.isArray(t.randomPercentages)||t.randomPercentages.length!==t.branches.length)throw Error("`randomPercentages` must contain one percentage per entry in `branches` when `splitMode` is `random`.");if(t.randomPercentages.some((x)=>typeof x!=="number"||!Number.isFinite(x)||x<0))throw Error("`randomPercentages` must contain non-negative numbers when `splitMode` is `random`.");let E=t.randomPercentages.reduce((x,A)=>x+A,0);if(Math.abs(E-100)>0.001)throw Error(`\`randomPercentages\` must sum to 100 when \`splitMode\` is \`random\`, received ${E}.`);if(Array.isArray(t.elseSteps)&&t.elseSteps.length>0||l(t,"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(t.randomPercentages!==void 0)throw Error("`randomPercentages` is only valid when `splitMode` is `random`.");let f=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],w=t.allowEmptyPaths===!0,g=t.branches.map((E,x)=>{if(!I(E))throw Error(`\`branches[${x}]\` must be an object when calling \`insert_sequence_step\`.`);let A=`branches[${x}]`;if(m){let U=$r.find((ue)=>E[ue]!==void 0);if(U)throw Error(`\`${A}.${U}\` must be omitted when \`splitMode\` is \`random\`, because the path is chosen by percentage rather than by evaluating the subscriber.`)}else{let U=u("insert_sequence_step",E,"conditionType");if(!d.has(U))throw Error(`\`branches[${x}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);Lr(U,E,A)}if(E.steps!==void 0&&!Array.isArray(E.steps))throw Error(`\`branches[${x}].steps\` must be an array when calling \`insert_sequence_step\`.`);let ee=l(E,"targetNodeId"),te=Array.isArray(E.steps)&&E.steps.length>0;if(!ee&&!te&&!w)throw Error(`\`branches[${x}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(f.flatMap((U)=>E[U]===void 0?[]:[[U,E[U]]]))});if(t.elseSteps!==void 0&&!Array.isArray(t.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let _=l(t,"elseTargetNodeId"),q=Array.isArray(t.elseSteps)&&t.elseSteps.length>0;if(!m&&!_&&!q&&!w)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},branch:{afterNodeId:o,...l(t,"label")?{label:l(t,"label")}:{},...m?{splitMode:c,randomPercentages:t.randomPercentages}:{},branches:g,...Array.isArray(t.elseSteps)?{elseSteps:t.elseSteps}:{},..._?{elseTargetNodeId:_}:{},...w?{allowEmptyPaths:!0}:{}}}}if(e==="delay"||e==="create_discount"||e==="update_subscriber"||e==="condition"||e==="add_tag"||e==="remove_tag"||e==="add_to_list"||e==="remove_from_list"||e==="webhook"||e==="ai"){let o;if(e==="delay"){o={type:"delay"};for(let m of["delay","delayMs","waitUntil","waitUntilWeekday"])if(t[m]!==void 0)o[m]=t[m];if(o.delay===void 0&&o.delayMs===void 0&&o.waitUntil===void 0&&o.waitUntilWeekday===void 0)throw Error("Provide `delay`, `delayMs`, `waitUntil`, or `waitUntilWeekday` when inserting a delay step.")}else if(e==="create_discount"){o={type:"create_discount"};for(let m of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(t[m]!==void 0)o[m]=t[m]}else if(e==="update_subscriber"){if(!I(t.config))throw Error("`config` is required when inserting an update_subscriber step.");o={type:"update_subscriber",nodeType:"action_update_attributes",config:t.config}}else if(e==="webhook"){let m=l(t,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(m))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if(t.headers!==void 0&&(!I(t.headers)||Object.values(t.headers).some((_)=>typeof _!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let f=l(t,"onError");if(f&&!["continue","exit","fail"].includes(f))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(t.body!==void 0&&typeof t.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(t.resultKey!==void 0&&typeof t.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let w=l(t,"body"),g=l(t,"resultKey");o={type:"webhook",nodeType:"action_webhook",config:{label:l(t,"label")??"Webhook",url:u("insert_sequence_step",t,"url"),method:m,...t.headers!==void 0?{headers:t.headers}:{},...w?{body:w}:{},...g?{resultKey:g}:{},...f?{onError:f}:{}}}}else if(e==="ai"){let m=l(t,"onError");if(m&&!["continue","exit","fail"].includes(m))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting an ai step.");if(!Array.isArray(t.outputFields)||t.outputFields.length===0)throw Error("`outputFields` is required when inserting an ai step, e.g. [{ key: 'subject_line', fallback: 'We miss you' }].");if(t.includeAttributes!==void 0){if(!Array.isArray(t.includeAttributes)||t.includeAttributes.some((f)=>typeof f!=="string"))throw Error("`includeAttributes` must be an array of attribute names when inserting an ai step.")}if(t.recentEventLimit!==void 0&&typeof t.recentEventLimit!=="number")throw Error("`recentEventLimit` must be a number between 1 and 50 when inserting an ai step.");o={type:"ai",nodeType:"action_ai",config:{label:l(t,"label")??"Ask AI",prompt:u("insert_sequence_step",t,"prompt"),resultKey:u("insert_sequence_step",t,"resultKey"),outputFields:t.outputFields,...t.includeTags!==void 0?{includeTags:t.includeTags===!0}:{},...t.includeEventProperties!==void 0?{includeEventProperties:t.includeEventProperties===!0}:{},...t.includeRecentEvents!==void 0?{includeRecentEvents:t.includeRecentEvents===!0}:{},...t.recentEventLimit!==void 0?{recentEventLimit:t.recentEventLimit}:{},...t.includeAttributes!==void 0?{includeAttributes:t.includeAttributes}:{},...m?{onError:m}:{}}}}else if(e==="condition"){let m=u("insert_sequence_step",t,"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(m))throw Error("`conditionType` is not supported for condition steps.");if((m==="has_tag"||m==="does_not_have_tag")&&!l(t,"tagId")&&!l(t,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(m==="in_list"&&!l(t,"listId"))throw Error("`listId` is required for an in_list condition.");if(m==="in_segment"&&!l(t,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(m==="event_received"&&!l(t,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(m.startsWith("field_")&&(!l(t,"fieldName")||!l(t,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let w={label:l(t,"label")??"Condition",conditionType:m};for(let g of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(t[g]!==void 0)w[g]=t[g];o={type:"condition",nodeType:"logic_condition",config:w}}else{let m=e==="add_tag"||e==="remove_tag",f=e==="add_tag"?"action_add_tag":e==="remove_tag"?"action_remove_tag":e==="add_to_list"?"action_add_to_list":"action_remove_from_list",w={label:l(t,"label")??(e==="add_tag"?"Add Tag":e==="remove_tag"?"Remove Tag":e==="add_to_list"?"Add to List":"Remove from List")};if(m){let g=l(t,"tagId"),_=l(t,"tagName");if(!g&&!_)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(g)w.tagId=g;if(_)w.tagName=_}else{w.listId=u("insert_sequence_step",t,"listId");let g=l(t,"listName");if(g)w.listName=g}o={nodeType:f,config:w}}for(let m of["delay","delayMs","waitUntil","waitUntilWeekday"])if(e!=="delay"&&t[m]!==void 0)o[m]=t[m];let d={steps:[o]},c=l(t,"afterNodeId");if(c)d.afterNodeId=c;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},insertSteps:d}}let i=e==="sms",s;if(i){Ht("insert_sequence_step","SMS step",t);let o=l(t,"text"),d=Array.isArray(t.blocks)&&t.blocks.length>0;if(o===void 0&&!d)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");s={type:"sms"};for(let c of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil","waitUntilWeekday"])if(t[c]!==void 0)s[c]=t[c]}else{F("insert_sequence_step",t,{requireContent:!0}),et("insert_sequence_step","email step",t),s={subject:u("insert_sequence_step",t,"subject")};for(let o of["name","previewText","html","blocks","delay","delayMs","waitUntil","waitUntilWeekday","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(t[o]!==void 0)s[o]=t[o]}let r={steps:[s]};if(t.afterNodeId!==void 0)r.afterNodeId=t.afterNodeId;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},insertSteps:r}}function Qn(t,e){let n=t[e];if(n===void 0)return[];if(!Array.isArray(n))throw Error(`\`${e}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let i=n.map((s)=>typeof s==="string"?s.trim():"").filter((s)=>s.length>0);if(n.some((s)=>typeof s!=="string")||i.length===0)throw Error(`\`${e}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return i}function Zn(t,e){let n=t[e];if(n===void 0)return[];if(!Array.isArray(n))throw Error(`\`${e}\` must be an array when calling \`realign_sequence_enrollments\`.`);let i=n.map((s)=>typeof s==="string"?s.trim():"").filter((s)=>s.length>0);if(n.some((s)=>typeof s!=="string")||i.length===0)throw Error(`\`${e}\` must contain at least one non-empty string when calling \`realign_sequence_enrollments\`.`);return i}function ai(t){let e=Zn(t,"nodeIds"),n=Zn(t,"subscriberIds"),i=l(t,"cursor");if(t.dryRun!==void 0&&typeof t.dryRun!=="boolean")throw Error("`dryRun` must be a boolean when calling `realign_sequence_enrollments`.");return{...e.length>0&&{nodeIds:e},...n.length>0&&{subscriberIds:n},...i!==void 0&&{cursor:i},...typeof t.dryRun==="boolean"&&{dryRun:t.dryRun}}}function di(t){let e=l(t,"subscriberId"),n=Qn(t,"subscriberIds"),i=Qn(t,"fieldValues");if(t.cancelAll!==void 0&&typeof t.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let s=t.cancelAll===!0;if((e!==void 0?1:0)+(n.length>0?1:0)+(i.length>0?1:0)+(s?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let o=l(t,"fieldPath"),d=l(t,"reason");return{...s&&{cancelAll:!0},...e!==void 0&&{subscriberId:e},...n.length>0&&{subscriberIds:n},...o!==void 0&&{fieldPath:o},...i.length>0&&{fieldValues:i},...typeof t.dryRun==="boolean"&&{dryRun:t.dryRun},...d!==void 0&&{reason:d}}}var Xn=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function ei(t,e){let n=t[e];if(n===void 0||n===null)return;let i=typeof n==="string"?Number(n):n,s=e==="dailyLimit"?0:1;if(typeof i!=="number"||!Number.isSafeInteger(i)||i<s)throw Error(`\`${e}\` must be an integer of at least ${s} when calling \`move_sequence_enrollments\`.`);return i}function ti(t,e){let n=t[e];if(n===void 0)return[];if(!Array.isArray(n)||n.some((s)=>typeof s!=="string"))throw Error(`\`${e}\` must be an array of strings when calling \`move_sequence_enrollments\`.`);let i=n.map((s)=>s.trim()).filter((s)=>s.length>0);if(i.length===0)throw Error(`\`${e}\` must contain at least one non-empty string when calling \`move_sequence_enrollments\`.`);return i}function ci(t){let e=u("move_sequence_enrollments",t,"fromNodeId"),n=l(t,"targetNodeId"),i=l(t,"reason"),s=l(t,"sort");if(s!==void 0&&!Xn.includes(s))throw Error(`\`sort\` must be one of ${Xn.join(", ")} when calling \`move_sequence_enrollments\`.`);let r=ti(t,"subscriberIds"),o=ti(t,"tags"),d=ei(t,"limit"),c=ei(t,"dailyLimit");return{fromNodeId:e,...n!==void 0&&{targetNodeId:n},...d!==void 0&&{limit:d},...c!==void 0&&{dailyLimit:c},...s!==void 0&&{sort:s},...r.length>0&&{subscriberIds:r},...o.length>0&&{tags:o},...i!==void 0&&{reason:i},...typeof t.dryRun==="boolean"&&{dryRun:t.dryRun}}}function li(t){F("create_campaign",t),X("create_campaign",t);let e=l(t,"prompt")!==void 0,n=t.html!==void 0,i=t.blocks!==void 0,s=t.templateId!==void 0;if(t.prompt!==void 0&&!e)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(e&&(n||i||s))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!e&&(t.style!==void 0||t.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(zt("create_campaign",t),!e&&l(t,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function zt(t,e){if(e.emailPreset===void 0)return;if(e.emailPreset!=="branded"&&e.emailPreset!=="minimal")throw Error(`\`emailPreset\` must be branded or minimal when calling \`${t}\`.`);if(e.html!==void 0)throw Error(`\`emailPreset\` is only supported for native Sequenzy blocks and cannot be combined with \`html\` when calling \`${t}\`.`)}function pi(t){F("create_template",t),X("create_template",t);let e=l(t,"prompt")!==void 0,n=[e,t.html!==void 0,t.blocks!==void 0].filter(Boolean).length;if(t.prompt!==void 0&&!e)throw Error("`prompt` cannot be empty when calling `create_template`.");if(n!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!e&&(t.style!==void 0||t.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!e&&l(t,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function Bt(t,e){if(e.sendTimeOptimization!==void 0&&typeof e.sendTimeOptimization!=="boolean")throw Error(`\`sendTimeOptimization\` must be a boolean when calling \`${t}\`.`);if(e.sendTimeWindowHours!==void 0){if(typeof e.sendTimeWindowHours!=="number"||!Number.isInteger(e.sendTimeWindowHours)||e.sendTimeWindowHours<1||e.sendTimeWindowHours>24)throw Error(`\`sendTimeWindowHours\` must be an integer between 1 and 24 when calling \`${t}\`.`)}}function ui(t){if(l(t,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(t.targetLists!==void 0&&!I(t.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(t.listIds!==void 0&&t.targetLists!==void 0)throw Error("Provide either `listIds` or `targetLists` when calling `schedule_campaign`, not both.");if(t.listIds!==void 0&&(!Array.isArray(t.listIds)||t.listIds.length===0||t.listIds.some((e)=>typeof e!=="string")))throw Error("`listIds` must be a non-empty array of list ID strings when calling `schedule_campaign`.");if(Bt("schedule_campaign",t),t.spreadOverHours!==void 0){if(typeof t.spreadOverHours!=="number"||!Number.isInteger(t.spreadOverHours)||t.spreadOverHours<1||t.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(t.sendInRecipientTimezone!==void 0&&typeof t.sendInRecipientTimezone!=="boolean")throw Error("`sendInRecipientTimezone` must be a boolean when calling `schedule_campaign`.");if(t.scheduledTimezone!==void 0&&(typeof t.scheduledTimezone!=="string"||t.scheduledTimezone.trim()===""))throw Error("`scheduledTimezone` must be a non-empty IANA timezone string (e.g. America/New_York) when calling `schedule_campaign`.");if(t.sendInRecipientTimezone===!0&&t.scheduledTimezone===void 0)throw Error("`scheduledTimezone` is required when `sendInRecipientTimezone` is true - it is the IANA zone the scheduledAt wall-clock time refers to.");if(t.recurringInterval!==void 0&&t.recurringInterval!=="weekly"&&t.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function tt(t,e,n){let i=new Set(["companyId","landingPageId","name","slug","content"]),s=Object.keys(e).filter((r)=>!i.has(r));if(s.length>0)throw Error(`\`${t}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${s.length===1?"":"s"}: ${s.map((r)=>`\`${r}\``).join(", ")}.`);if(n.requireUpdate&&e.name===void 0&&e.slug===void 0&&e.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${t}\`.`);return{...e.name!==void 0&&{name:e.name},...e.slug!==void 0&&{slug:e.slug},...e.content!==void 0&&{content:e.content}}}function mi(t){let e=new Set(["companyId","domain","landingPageId","verify"]),n=Object.keys(t).filter((i)=>!e.has(i));if(n.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`landingPageId\`, \`domain\`, and \`verify\`. Unsupported field${n.length===1?"":"s"}: ${n.map((i)=>`\`${i}\``).join(", ")}.`);if(t.domain===void 0&&t.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...t.domain!==void 0&&{domain:t.domain},...typeof t.verify==="boolean"&&{verify:t.verify}}}function hi(t){F("create_transactional_email",t);let e=l(t,"prompt")!==void 0,n=t.html!==void 0,i=t.blocks!==void 0;if(t.prompt!==void 0&&!e)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(e&&(n||i))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!e&&(t.style!==void 0||t.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!e&&!n&&!i)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!e&&l(t,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var ve={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},Fr={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:{...ve.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},Re={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."}},Ae={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:Fr,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:he,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:fe,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:ye,waitUntilWeekday:ge,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.${ze}`,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},Wt={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:Ae}},additionalProperties:!1},Gt="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.",Kt={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."},Vt={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 yi(t){if(!t||typeof t!=="object")return null;let e=t;if(e.success!==!1)return null;if(typeof e.error==="string")return Error(e.error);if(e.error&&typeof e.error==="object"&&typeof e.error.message==="string")return Error(e.error.message);if(typeof e.message==="string")return Error(e.message);return Error("The tool returned an unsuccessful response.")}var Yt=1000,Jt=1000,Qt=Yt*Jt-1;function Zt(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function Xt(t,e){let{attributes:n,customAttributes:i}=e,s=n!==void 0;if(s&&i!==void 0)throw Error(`Provide either \`attributes\` or \`customAttributes\` when calling \`${t}\`, not both. They are the same field; the REST API names it customAttributes.`);let o=s?n:i;if(o===void 0)return;if(!I(o))throw Error(`\`attributes\` (REST: customAttributes) must be an object when calling \`${t}\`.`);return{value:o,source:s?"attributes":"customAttributes"}}function Hr(t,e){let n=l(e,"attribute"),i=l(e,"attributeValue"),s=S(t,e,"attributeOperator",We);if(!n){if(i!==void 0||s!==void 0)throw Error(`\`attributeValue\` and \`attributeOperator\` require \`attribute\` when calling \`${t}\`.`);return{}}let r=s??"is",o;if(i!==void 0)o=`${n}:${i}`;else if(n.includes(":"))o=n;else if(r==="is_not_empty")o=`${n}:`;else throw Error(`Provide \`attributeValue\` (or use \`attribute: "name:value"\`) when \`attributeOperator\` is \`${r}\` in \`${t}\`. Only \`is_not_empty\` may omit a value.`);return{attribute:o,attributeOperator:r}}function zr(t){let e=new URLSearchParams;if(typeof t.query==="string"&&t.query.trim()!=="")e.set("query",t.query.trim());if(Array.isArray(t.tags)&&t.tags.length>0)e.set("tags",t.tags.filter((n)=>typeof n==="string"&&n.trim()!=="").join(","));if(typeof t.list==="string"&&t.list.trim()!=="")e.set("list",t.list.trim());if(typeof t.listId==="string"&&t.listId.trim()!=="")e.set("listId",t.listId.trim());if(typeof t.listName==="string"&&t.listName.trim()!=="")e.set("listName",t.listName.trim());if(typeof t.segmentId==="string"&&t.segmentId.trim()!=="")e.set("segmentId",t.segmentId);if(typeof t.status==="string"&&t.status.trim()!=="")e.set("status",t.status.trim());if(typeof t.unsubscribedAfter==="string"&&t.unsubscribedAfter.trim()!=="")e.set("unsubscribedAfter",t.unsubscribedAfter.trim());if(typeof t.unsubscribedBefore==="string"&&t.unsubscribedBefore.trim()!=="")e.set("unsubscribedBefore",t.unsubscribedBefore.trim());if(t.attribute){if(e.set("attribute",t.attribute),t.attributeOperator)e.set("attributeOperator",t.attributeOperator)}if(t.cursor)e.set("cursor",t.cursor);else e.set("page",String(t.page));if(e.set("limit",String(t.pageSize)),t.includeTotal===!1)e.set("includeTotal","false");return e}async function bi(t,e){let i=_i("search_subscribers",t,"limit"),s=l(t,"cursor"),r=s?Br("search_subscribers",t):Wr("search_subscribers",t,i),o=i===void 0?void 0:r+i,d=Math.min(Yt,Math.max(1,o??Yt)),c=Hr("search_subscribers",t),m=[],f=1,w=s,g,_=null,q=0,E=!1,x=!1;while(!0){let ue=o===void 0?void 0:o-m.length,me=w?Math.min(d,Math.max(1,ue??d)):d,Ne=zr({query:t.query,tags:t.tags,list:t.list,listId:t.listId,listName:t.listName,segmentId:t.segmentId,status:t.status,unsubscribedAfter:t.unsubscribedAfter,unsubscribedBefore:t.unsubscribedBefore,attribute:c.attribute,attributeOperator:c.attributeOperator,page:f,pageSize:me,cursor:w}),O=await a("GET",`/api/v1/subscribers?${Ne.toString()}`,void 0,e);if(q===0)_=O.pagination?.total??null;q+=1,m.push(...O.subscribers??[]);let z=(O.subscribers??[]).length,B=O.pagination?.nextCursor??void 0;g=B;let Me=o!==void 0&&m.length>=o,W;if(B)W=!1;else if(O.pagination?.hasMore!==void 0)W=!O.pagination.hasMore;else if(O.pagination?.totalPages!==void 0&&O.pagination.totalPages!==null)W=f>=O.pagination.totalPages;else W=z<me;if(W||z===0&&!B){E=!0;break}if(Me)break;if(q>=Jt){x=!0;break}if(B)w=B;else if(w)break;else f+=1}if(x&&(m.length<r||m.length===r&&g===void 0))throw Error(`Could not reach offset ${r} within ${Jt} requests because too few matches were returned per page. Start without \`offset\` and follow \`pagination.nextCursor\` instead.`);if(_===null&&E&&!s)_=m.length;let A=m.slice(r,o),ee=E?!1:_!==null?r+A.length<_:!E||m.length>r+A.length,te=g!==void 0&&m.length===r+A.length,U=r+A.length;return{success:!0,subscribers:A,pagination:{page:i===void 0?1:Math.floor(r/i)+1,limit:i??d,offset:r,total:_,totalPages:_===null?null:Math.ceil(_/(i??d)),fetchedPages:q,hasMore:ee,nextOffset:ee&&!s&&U<=Qt?U:null,nextCursor:ee&&te?g??null:null},returned:A.length,truncated:ee}}function Br(t,e){if(e.offset!==void 0||e.page!==void 0)throw Error(`\`cursor\` cannot be combined with \`offset\` or \`page\` when calling \`${t}\`. Keep following \`pagination.nextCursor\` instead.`);return 0}function Wr(t,e,n){let i=wi(t,e,"offset"),s=_i(t,e,"page");if(i!==void 0&&s!==void 0)throw Error(`Provide either \`offset\` or \`page\` when calling \`${t}\`, not both.`);if(s!==void 0){if(n===void 0)throw Error(`\`page\` requires \`limit\` when calling \`${t}\` so the page size is defined. Omit both to fetch every match in one call.`);return gi(t,(s-1)*n)}return gi(t,i??0)}function gi(t,e){if(e>Qt)throw Error(`\`offset\` must be ${Qt} or less when calling \`${t}\`. Use \`cursor\` to continue beyond that point.`);return e}function wi(t,e,n){let i=e[n];if(i===void 0||i===null)return;if(typeof i!=="number"||!Number.isInteger(i)||i<0)throw Error(`\`${n}\` must be a non-negative integer when calling \`${t}\`.`);return i}function _i(t,e,n){let i=wi(t,e,n);if(i!==void 0&&i<1)throw Error(`\`${n}\` must be 1 or greater when calling \`${t}\`.`);return i}function en(t){let e=typeof t.email==="string"&&t.email.trim()!==""?t.email.trim():void 0,n=typeof t.externalId==="string"&&t.externalId.trim()!==""?t.externalId.trim():void 0;return{...e?{email:e}:{},...n?{externalId:n}:{}}}function K(t,e){let n=en(e);if(!n.email&&!n.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${t}\`.`);return n}function nt(t,e){let n=new URLSearchParams;if(e?.includeMachineEngagement)n.set("includeMachineEngagement","true");let i=n.toString(),s=i?`?${i}`:"";if(t.email)return`/api/v1/subscribers/${encodeURIComponent(t.email)}${s}`;return n.set("externalId",String(t.externalId)),`/api/v1/subscribers/external?${n.toString()}`}function tn(t){if(t.email)return`/api/v1/subscribers/${encodeURIComponent(t.email)}/notes`;let e=new URLSearchParams;return e.set("externalId",String(t.externalId)),`/api/v1/subscribers/external/notes?${e.toString()}`}async function Oe(t,e,n){return a("GET",nt(t,n),void 0,e)}function S(t,e,n,i){let s=l(e,n);if(s===void 0)return;if(!i.includes(s))throw Error(`\`${n}\` must be one of ${i.join(", ")} when calling \`${t}\`.`);return s}function Ue(t,e,n,i){let s=u(t,e,n);if(!i.includes(s))throw Error(`\`${n}\` must be one of ${i.join(", ")} when calling \`${t}\`.`);return s}function P(t,e,n,i,s){let r=e[n];if(r===void 0)return;if(typeof r!=="number"||!Number.isInteger(r)||r<i||r>s)throw Error(`\`${n}\` must be an integer between ${i} and ${s} when calling \`${t}\`.`);return r}function Gr(t,e){let n=[],i=S(t,e,"eventType",Ce);if(i)n.push(i);if(e.eventTypes!==void 0){if(!Array.isArray(e.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${t}\`.`);e.eventTypes.forEach((s,r)=>{if(typeof s!=="string")throw Error(`\`eventTypes\` item ${r+1} must be a string when calling \`${t}\`.`);let o=s.trim();if(!Ce.includes(o))throw Error(`\`eventTypes\` item ${r+1} must be one of ${Ce.join(", ")} when calling \`${t}\`.`);n.push(o)})}return[...new Set(n)]}function nn(t,e){let n=new URLSearchParams,i=Gr(t,e);if(i.length>0)n.set("eventTypes",i.join(","));let s=S(t,e,"period",["1h","24h","7d","30d","90d"]);if(s)n.set("period",s);let r=l(e,"start");if(r)n.set("start",r);let o=l(e,"end");if(o)n.set("end",o);let d=P(t,e,"page",1,1e6);if(d!==void 0)n.set("page",String(d));let c=P(t,e,"limit",1,500);if(c!==void 0)n.set("limit",String(c));if(e.includeMachineEngagement===!0)n.set("includeMachineEngagement","true");return n}function sn(t,e){if(e.events===void 0)return;if(!Array.isArray(e.events))throw Error(`\`events\` must be an array when calling \`${t}\`.`);let n=e.events.map((i,s)=>{if(typeof i!=="string"||!we.includes(i))throw Error(`\`events\` item ${s+1} must be one of ${we.join(", ")} when calling \`${t}\`.`);return i});if(n.length===0)throw Error(`\`events\` must include at least one event type when calling \`${t}\`.`);return n}function rn(t,e){if(!Array.isArray(e.emails))throw Error(`\`emails\` must be an array when calling \`${t}\`.`);let n=[];if(e.emails.forEach((i,s)=>{if(typeof i!=="string")throw Error(`\`emails\` item ${s+1} must be a string when calling \`${t}\`.`);let r=i.trim();if(r.length>0)n.push(r)}),n.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${t}\`.`);if(n.length>kt)throw Error(`\`emails\` must include no more than ${kt} email addresses when calling \`${t}\`. Split larger batches into multiple calls.`);return n}function fi(t,e,n,i){let s=e[n];if(s===void 0)return;if(!Array.isArray(s))throw Error(`\`${n}\` must be an array when calling \`${t}\`.`);let r=[];if(s.forEach((o,d)=>{if(typeof o!=="string")throw Error(`\`${n}\` item ${d+1} must be a string when calling \`${t}\`.`);let c=o.trim();if(c.length>0)r.push(c)}),r.length===0)throw Error(`\`${n}\` must include at least one ${i} when calling \`${t}\`.`);return r}function vi(t){let n=fi("enroll_subscribers_in_sequence",t,"emails","email address"),i=fi("enroll_subscribers_in_sequence",t,"subscriberIds","subscriber ID"),s=(n?.length??0)+(i?.length??0);if(s===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(s>St)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${St} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let r=l(t,"targetNodeId");return{...n!==void 0&&{emails:n},...i!==void 0&&{subscriberIds:i},...r!==void 0&&{targetNodeId:r}}}function it(t,e){let n=t[e];if(n===void 0||n===null)return;if(typeof n==="string"){let r=n.trim();return r.length>0?r:void 0}if(!Array.isArray(n))throw Error(`\`${e}\` must be an email address or an array of email addresses when calling \`send_email\`.`);if(n.length>50)throw Error(`\`${e}\` accepts at most 50 email addresses when calling \`send_email\`.`);let i=new Set,s=[];return n.forEach((r,o)=>{if(typeof r!=="string")throw Error(`\`${e}\` item ${o+1} must be an email address when calling \`send_email\`.`);let d=r.trim();if(d.length===0)throw Error(`\`${e}\` item ${o+1} must be a non-empty email address when calling \`send_email\`.`);let c=d.toLowerCase();if(i.has(c))return;i.add(c),s.push(d)}),s.length>0?s:void 0}function on(t){if(t===void 0)return 0;return typeof t==="string"?1:t.length}function an(t){if(t===void 0)return[];return typeof t==="string"?[t]:t}function Ii(t,e){if(e.length===0)return;return typeof t==="string"?e[0]:e}function ki(t){let e=new Set(an(t.to).map((s)=>s.toLowerCase())),n=an(t.cc).filter((s)=>{let r=s.toLowerCase();if(e.has(r))return!1;return e.add(r),!0}),i=an(t.bcc).filter((s)=>{let r=s.toLowerCase();if(e.has(r))return!1;return e.add(r),!0});return{to:t.to,cc:Ii(t.cc,n),bcc:Ii(t.bcc,i)}}function Si(t){let e=on(t.to),n=on(t.cc),i=on(t.bcc),s=e>1||n>0||i>0;if(t.emailType==="marketing"&&s)throw Error("Marketing sends accept exactly one `to` address and do not support `cc` or `bcc` when calling `send_email`. Use the default `transactional` emailType to send one email to several recipients.");if((typeof t.subscriberExternalId==="string"?t.subscriberExternalId.trim().length>0:t.subscriberExternalId!==void 0&&t.subscriberExternalId!==null)&&s)throw Error("`subscriberExternalId` is only supported for single-recipient sends when calling `send_email`. Drop it to send to several recipients, or send one email per subscriber.")}import{readFileSync as Kr,statSync as Vr}from"node:fs";import{basename as Yr}from"node:path";var Jr={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 Qr(t){let e=t.split(".").pop()?.toLowerCase()??"";return Jr[e]??null}var Zr=104857600;async function qi(t,e){if(!$e())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 n=Qr(t);if(!n)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let i=Vr(t).size;if(i>Zr)throw Error(`File is too large (${Math.round(i/1048576)}MB). Delivery files must be 100MB or smaller.`);let s=Kr(t),r=await a("POST","/api/v1/products/delivery/upload-url",{filename:Yr(t),contentType:n,fileSizeBytes:i},e),o=await fetch(r.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:s});if(!o.ok)throw Error(`File upload failed (${o.status})`);return{url:r.publicUrl,fileName:r.fileName,fileSizeBytes:i,mimeType:n}}async function st(t){let e=l(t,"companyId");if(e)return e;let n=ie();if(n)return n;try{return(await a("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function Se(t,e){let n=await st(e);if(!n)throw Error(`A company is required when calling \`${t}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return n}function ke(t,e){if(!I(t)||!e)return t;return{...t,url:e}}function Ti(t,e){if(!I(t))return t;return{...t,...e.campaign!==void 0&&{url:e.campaign},...e.campaignPreview!==void 0&&{previewUrl:e.campaignPreview}}}function Ie(t,e,n){if(!Array.isArray(t)||!e)return t;return t.map((i)=>{if(!I(i))return i;let s=l(i,"id");if(!s)return i;let r=Q({companyId:e,...n==="campaign"&&{campaignId:s},...n==="landingPage"&&{landingPageId:s},...n==="sequence"&&{sequenceId:s},...n==="template"&&{emailId:s},...n==="transactional"&&{transactionalId:s},...n==="emailSend"&&{emailSendId:s}});if(n==="campaign")return Ti(i,r.urls);let o=n==="sequence"?r.urls.sequence:n==="landingPage"?r.urls.landingPage:n==="template"?r.urls.email:n==="transactional"?r.urls.transactionalEmail:r.urls.emailSend;return ke(i,o)})}function Xr(t){if(!Array.isArray(t))return t;return t.map((e)=>{if(!I(e))return e;let n=l(e,"id");if(!n)return e;let i=Q({companyId:n});return{...e,url:i.urls.dashboard,settingsUrl:i.urls.settings,subscriptionUrl:i.urls.subscription}})}var dn=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","get_landing_page_stats","render_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","simulate_sequence","get_sequence_enrollment","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","select_ab_test_winner","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 Pi(t,e,n){if(!I(n)||!dn.has(t))return n;let i=I(n.company)?n.company:void 0,r=l(n,"selectedCompanyId")??l(n,"currentCompanyId")??l(n,"companyId")??(i?l(i,"id"):void 0)??(i?l(i,"companyId"):void 0)??await st(e);if(!r)return n;let o=I(n.campaign)?n.campaign:void 0,d=I(n.sequence)?n.sequence:void 0,c=I(n.landingPage)?n.landingPage:void 0,m=I(n.template)?n.template:void 0,f=I(n.transactional)&&!Array.isArray(n.transactional)?n.transactional:void 0,w={companyId:r,campaignId:l(e,"campaignId")??l(n,"campaignId")??(o?l(o,"id"):void 0),landingPageId:l(e,"landingPageId")??l(n,"landingPageId")??(c?l(c,"id"):void 0),sequenceId:l(e,"sequenceId")??l(n,"sequenceId")??(d?l(d,"id"):void 0),emailId:l(n,"templateId")??(m?l(m,"id"):void 0)??(f?l(f,"emailId"):void 0)??l(e,"templateId"),transactionalId:l(e,"transactionalId")??(f?l(f,"id"):void 0)??l(e,"idOrSlug"),emailSendId:l(e,"emailSendId")??l(n,"emailSendId")??(I(n.emailSend)?l(n.emailSend,"id"):void 0),status:l(e,"status")},g=Q(w),_=i?Q({companyId:r}):void 0;return{...n,...Array.isArray(n.companies)&&{companies:Xr(n.companies)},...Array.isArray(n.campaigns)&&{campaigns:Ie(n.campaigns,r,"campaign")},...Array.isArray(n.landingPages)&&{landingPages:Ie(n.landingPages,r,"landingPage")},...Array.isArray(n.sequences)&&{sequences:Ie(n.sequences,r,"sequence")},...Array.isArray(n.templates)&&{templates:Ie(n.templates,r,"template")},...Array.isArray(n.transactional)&&{transactional:Ie(n.transactional,r,"transactional")},...Array.isArray(n.emailSends)&&{emailSends:Ie(n.emailSends,r,"emailSend")},...i&&_!==void 0&&{company:{...i,url:_.urls.dashboard,settingsUrl:_.urls.settings,subscriptionUrl:_.urls.subscription}},...o&&g.urls.campaign!==void 0&&{campaign:Ti(o,g.urls)},...d&&g.urls.sequence!==void 0&&{sequence:ke(d,g.urls.sequence)},...c&&g.urls.landingPage!==void 0&&{landingPage:ke(c,g.urls.landingPage)},...m&&g.urls.email!==void 0&&{template:ke(m,g.urls.email)},...f&&g.urls.transactionalEmail!==void 0&&{transactional:ke(f,g.urls.transactionalEmail)},...I(n.emailSend)&&g.urls.emailSend!==void 0&&{emailSend:ke(n.emailSend,g.urls.emailSend)},appUrls:g.urls}}import{readFileSync as eo,statSync as to}from"node:fs";import{basename as no,extname as xi}from"node:path";var ln=5242880,io=Math.ceil(ln/3)*4,so=Math.ceil(io*1.05)+256,Ci={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},ro=new Set(Object.values(Ci));function cn(t){return t?.split(";")[0]?.trim().toLowerCase()||void 0}function oo(t){return Ci[xi(t).toLowerCase()]}function ao(t){let e=xi(t);return(e?t.slice(0,-e.length):t).replace(/[-_]+/g," ").trim()||"Image"}function co(t){if(t.length>so)throw Error("Image assets must be 5MB or smaller.")}function lo(t){let e=0,n=0;for(let s=0;s<t.length;s+=1){let r=t.charCodeAt(s);if(r===9||r===10||r===11||r===12||r===13||r===32)continue;e+=1,n=r===61?n+1:0}if(Math.floor(e*3/4)-Math.min(n,2)>ln)throw Error("Image assets must be 5MB or smaller.")}function po(t){co(t);let e=t.trim(),n=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(e),i=n?.[2]??e;lo(i);let s=i.replace(/\s+/g,"");if(s.length===0||s.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(s))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(s,"base64"),...n?.[1]?{dataUrlContentType:cn(n[1])}:{}}}function Ei(t){if(t<=0)throw Error("The image file is empty.");if(t>ln)throw Error("Image assets must be 5MB or smaller.")}function uo(t){let e=oo(t.filename)??cn(t.explicitContentType)??cn(t.dataUrlContentType);if(!e||!ro.has(e))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return e}function mo(t){let e,n,i;if(t.filePath!==void 0){if(!$e())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 r=to(t.filePath).size;Ei(r),e=eo(t.filePath),n=t.filename??no(t.filePath)}else{if(!t.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!t.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let r=po(t.imageBase64);e=r.bytes,i=r.dataUrlContentType,n=t.filename,Ei(e.byteLength)}let s=uo({filename:n,explicitContentType:t.contentType,dataUrlContentType:i});return{bytes:e,filename:n,contentType:s,altText:t.altText??ao(n)}}async function Di(t){let e=mo(t),n=e.bytes.byteLength,i=await a("POST","/api/v1/media/upload-url",{filename:e.filename,contentType:e.contentType,fileSizeBytes:n},t.companyId);return await En(i.uploadUrl,e.bytes,e.contentType,t.companyId),(await a("POST","/api/v1/media/complete-upload",{key:i.key,filename:i.fileName,contentType:e.contentType,fileSizeBytes:n,...t.sourceWidth!==void 0&&{width:t.sourceWidth},...t.sourceHeight!==void 0&&{height:t.sourceHeight},altText:e.altText},t.companyId)).asset}var qe={type:"boolean",description:"Whether the Sequenzy operation succeeded."},H={type:"string",description:"Human-readable status, confirmation, or next-step message."},pn={type:"string",description:"Additional context about the result."};function y(t){return{type:"object",description:t,additionalProperties:!0}}function j(t){return{type:"array",description:t,items:y("One item in the returned collection.")}}function p(t){return{type:"string",description:t}}function V(t){return{type:["object","null"],description:t,additionalProperties:!0}}function T(t){return{type:["string","null"],description:t}}function b(t){return{type:"number",description:t}}function Ri(t){return{type:["number","null"],description:t}}function v(t){return{type:"boolean",description:t}}function ho(t){return{type:["boolean","null"],description:t}}function Ai(t,e){return{type:["array","null"],description:t,items:e}}function h(t){return y(`The ${t} record returned by Sequenzy.`)}function k(t){return j(`List of ${t} records returned by Sequenzy.`)}var oe="`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`.",Oi="The subscriber import record: status, totalRows, emailCount, duplicateRows, addedCount, updatedCount, skippedCount, failedCount, processedCount, chunk progress, and the reason maps skippedReasons, failedReasons, and failedChunkReasons. Every excluded row is explained: skippedReasons sums to skippedCount and failedReasons sums to failedCount. Report a shortfall with the import ID instead of guessing which rows are missing.",ji="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.",yo="Email numbering: emails[].stepNumber and nodes[].config.stepNumber are legacy stored ordinals retained for compatibility. Prefer emails[].structuralStepNumber and nodes[].structuralStepNumber when explaining the visible sequence position. Structural numbers are graph-derived; emails in parallel branches intentionally share a depth.",pe=y(`The sequence record returned by Sequenzy. ${ji} ${yo} Sequences use sendingWindow for allowed local hours/days; they do not have Send Time Optimization. STO is per-campaign (list_campaigns / get_campaign sendTimeOptimization).`),go=j(`List of sequence records returned by Sequenzy. ${ji}`),rt={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:v("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:v("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:p("One plain-language sentence describing the run state, safe to show a user verbatim.")},Ui={...pe,properties:{migratedRecipientCount:b("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:b("Recipients completed because a deleted step had no surviving successor.")}},fo={appUrls:y("Dashboard URLs for relevant Sequenzy resources."),url:p("Primary dashboard URL for this result."),settingsUrl:p("Company settings URL when available."),subscriptionUrl:p("Owner-facing subscription, upgrade, and billing-management URL when available.")},bo={success:qe,message:H,note:pn,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:p("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:y("One returned item.")},value:y("Fallback object wrapper used only when a tool returns a non-object value.")},wo={get_account:{account:h("account"),companies:k("company"),apiKeyPermissions:y("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, `canSendLive` plus `missingLiveDeliveryScopes` (delivery this key cannot perform, e.g. `transactional:send` for `send_email`; check before composing anything meant to be sent) and `liveDeliveryBlockedByRole` (a viewer role blocks sending no matter the scopes, so widening the key will not help), and the API Keys management URL."),currentCompanyId:p("Company ID selected by the authenticated API key, when available."),selectedCompanyId:p("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:p("Selected company ID."),companyName:p("Selected company name.")},get_app_urls:{dashboard:p("Company dashboard URL."),account:p("Company account URL."),subscription:p("Owner-facing subscription, upgrade, and billing-management URL."),settings:p("Company settings URL."),campaign:p("Campaign editor URL."),landingPage:p("Landing page editor URL."),sequence:p("Sequence editor URL."),email:p("Email editor URL."),transactionalEmail:p("Transactional email URL."),emailSend:p("Sent email detail URL."),domain:p("Sending domain settings URL."),urls:y("All generated URLs keyed by resource type.")},create_company:{company:h("company"),autoSelected:v("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:h("company")},get_company:{company:h("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:y("One sync rule.")},isDefault:v("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:y("One sync rule.")},isDefault:v("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_email_design_system:{designSystem:y("The effective email design system parsed from the direction text: designCode (visual grammar tokens), compositionSpine, and source (derived | custom)."),directionText:{type:["string","null"],description:"The raw emailDesignPrompt direction text the tokens were parsed from; null when the company has none yet."},isDefault:v("True while the identity is purely derived from brand context.")},update_email_design_system:{message:H,designSystem:y("The email design system now in effect after the update or reset."),directionText:{type:["string","null"],description:"The rewritten direction text now stored on the company; null after a reset."},isDefault:v("True when the resulting identity is the pure brand-derived one - after an explicit reset, or when an adjustment resolved to the derived defaults.")},get_shopify_automation_settings:{browseAbandonment:y("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:y("Effective cart-abandonment settings (defaults applied)."),priceDrop:y("Effective price-drop settings (defaults applied)."),shopDomain:p("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:y("Effective browse-abandonment settings after the update."),cartAbandonment:y("Effective cart-abandonment settings after the update."),priceDrop:y("Effective price-drop settings after the update."),shopDomain:p("Connected Shopify store domain.")},create_api_key:{apiKey:y("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:p("Newly created API key if the API response uses the short key field.")},request_api_key_handoff:{handoff:y("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:p("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:p("One step in the handoff.")}},list_api_keys:{apiKeys:k("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:h("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:h("revoked non-secret API key metadata")},delete_api_key:{apiKey:h("deleted non-secret API key metadata")},list_websites:{websites:k("sending domain, including DNS verification and readyToSend sending readiness")},list_integrations:{integrations:k("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:y("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:V("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:j("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:p("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:p("Event name never seen account-wide.")},activity:y("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),ingestion:y("What this integration does to the contact list: bulkSyncEnabled, supportsListTargeting, listTargeting (`company_default`, `none`, `specific`, or null when the provider ignores targeting), listIds (null means the workspace default lists), lists with their names, missingListIds for configured lists that have since been deleted and are therefore skipped, and a summary. When supportsListTargeting is false, the summary names defaultSubscriberListIds on get_company/update_company as the live-ingestion write path (null = every list, [] = none) and identifies provider-specific backfill exceptions such as PostHog history imports. Neither setting stops the provider's live webhook creating contacts."),pixel:V("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:j("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:p("Available action id.")}},list_integration_capabilities:{providers:k("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?, fields? }. `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; a field's own `fields` holds the shape of an object field, such as a repeat block's `productSource`.",items:y("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:y("Single-type mode: the full reference for the requested type, including a minimal valid `example` and authoring `notes`."),conditionFields:{type:"array",description:'The per-field table for block conditions - the `conditions` array every block takes, and the `conditions` of a `conditional-group`. Present when listing every type, when the requested type is `conditional-group`, and when conditionFields: true was passed; otherwise `conditionFieldsHint` says how to ask for it. Each entry is { field, label, operators, values?, valueFormat, serverEvaluated, previewSupport, example }. `operators` is the only set that field accepts: the `field` and `operator` enums inside a block\'s own reference pool every field\'s operators together, so they show `is` for `tag` even though a tag condition is rejected with it. `valueFormat` gives the shape of the value string, which differs per field ("attributeName:value" for attribute, a tag name for tag, an id for segment, "eventName:timeRange" for event). `serverEvaluated` marks the fields read from stored subscriber state rather than from the send\'s merge data, and `previewSupport` says what render_email needs before it can evaluate one: "any_contact", "inline_tags_or_stored_subscriber" (tag), or "stored_subscriber". A condition a render cannot evaluate is not an error - it renders as false and is listed in that render\'s unevaluatedConditions.',items:y("One condition field: its allowed operators, value format, and what a preview needs to evaluate it.")},conditionFieldsHint:{type:"string",description:"Present on a single-type response that omitted `conditionFields`, saying that conditions are per-field and how to get the table. The table is several times the size of one block type's reference, so a targeted lookup does not carry it unless conditions are that type's purpose or you asked for it."}},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:y("An event: eventName, documented, label, category, description, documentedProviders, and (single-event mode) providers, mergeTagPrefix, and notes.")},note:pn},list_integration_activity:{activity:k("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:pn},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:p("URL to configure in the provider's webhook settings with the same secret. Empty for Attio, which is outbound-only. For other providers, always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:v("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:v("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog and Segment 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:p("The integration that was updated."),provider:p("Provider of the updated integration."),syncEnabled:v("Bulk import and backfill state after the update. This is not the provider's live webhook, which keeps creating contacts either way."),listTargeting:T("Where contacts created by this integration land: `company_default`, `none`, or `specific`. Null for providers that ignore per-integration list targeting."),listIds:Ai("Configured target lists. Null means new contacts follow the workspace default lists.",p("List ID.")),changed:v("False when the integration was already in the requested state."),changedFields:{type:"array",description:"Which controls actually moved.",items:p("Field name.")},message:H},set_integration_list_targeting:{integrationId:p("The integration that was updated."),provider:p("Provider of the updated integration."),syncEnabled:v("Bulk import and backfill state. Unchanged by this tool."),listTargeting:T("Where contacts created by this integration land after the update: `company_default`, `none`, or `specific`. Null for providers that ignore per-integration list targeting."),listIds:Ai("Configured target lists after the update. Null means new contacts follow the workspace default lists.",p("List ID.")),changed:v("False when the integration was already in the requested state."),changedFields:{type:"array",description:"Which controls actually moved.",items:p("Field name.")},message:H},get_integration_pixel:{integrationId:p("The Shopify integration inspected."),provider:p("Always `shopify`."),shopDomain:p("Store the pixel was read from."),pixel:y("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:p("Pixel-dependent event name.")},message:H},activate_integration_pixel:{integrationId:p("The Shopify integration updated."),provider:p("Always `shopify`."),shopDomain:p("Store the pixel was installed on."),pixel:y("Pixel state after activation."),changed:v("False when the pixel was already installed and reporting to this account."),created:v("True when a new pixel was installed."),updated:v("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:p("Pixel-dependent event name.")},message:H},sync_integration:{integrationId:p("The integration being synced."),provider:p("Provider of the synced integration."),jobId:T("Background job id for the queued sync, when one was created."),syncStatus:p("Sync status after queueing. Poll get_integration to watch it progress."),syncTarget:V("For Supabase, the project ref, schema, and table the backfill reads. Absent for providers whose sync has no configurable source."),message:H},get_attio_mapping:{integrationId:p("The Attio integration inspected."),provider:p("Always `attio`."),listMap:y("Saved Sequenzy list id → Attio list UUID or api slug. Empty when nothing is mapped."),mappedListCount:b("Number of saved mappings whose Sequenzy source and Attio target lists both still exist. Stale saved entries remain in listMap but are not counted. Zero means list joins are not synced."),syncCompanyFromDomain:v("Whether a company is upserted from the person's non-free-mail email domain."),sequenzyLists:{type:"array",description:"This company's Sequenzy lists (id and name).",items:y("A Sequenzy list: id and name.")},attioLists:{type:"array",description:"Attio people-lists the stored token can write, read live from Attio (id, apiSlug, name).",items:y("An Attio people-list: id, apiSlug, and name.")},message:H},update_attio_settings:{integrationId:p("The Attio integration updated."),provider:p("Always `attio`."),listMap:y("Saved Sequenzy list id → Attio list UUID or api slug after the update."),mappedListCount:b("Number of saved mappings whose Sequenzy source and Attio target lists both still exist after the update. Stale preserved entries are not counted."),syncCompanyFromDomain:v("Whether company matching from work-email domains is on after the update."),sequenzyLists:{type:"array",description:"This company's Sequenzy lists (id and name).",items:y("A Sequenzy list: id and name.")},attioLists:{type:"array",description:"Attio people-lists the stored token can write, read live from Attio (id, apiSlug, name).",items:y("An Attio people-list: id, apiSlug, and name.")},changed:v("False when the integration was already in the requested state."),changedFields:{type:"array",description:"Which settings actually moved: listMap and/or syncCompanyFromDomain.",items:p("Field name.")},message:H},list_web_tracking_keys:{success:qe,keys:{type:"array",description:"Publishable keys for the browser tracking SDK, newest first. A key with lastUsedAt null has not successfully authenticated an event yet; check deployment, instrumentation or traffic, and the origin allowlist.",items:y("One key: id, name, publicKey, allowedOrigins, isActive, unrestricted, lastUsedAt, installSnippet, endpoint, and warning when unrestricted.")}},get_web_tracking_key:{success:qe,key:y("The key, including the paste-ready installSnippet and the ingest endpoint.")},create_web_tracking_key:{success:qe,key:y("The created key. installSnippet is the exact HTML snippet to paste into every page; it embeds both the publishable key and the workspace id and queues calls made while the async SDK loads."),message:H},update_web_tracking_key:{success:qe,key:y("The key after the update.")},delete_web_tracking_key:{success:qe,message:H},list_sender_profiles:{senderProfiles:k("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether the address is fully ready to send"),replyProfiles:k("reply-to profile"),defaultSenderProfileId:T("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:T("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:h("renamed sender (From) profile, present when type was sender"),replyProfile:h("renamed reply-to profile, present when type was reply"),renamed:v("False when the profile already carried that name, so nothing changed.")},get_notification_preferences:{notificationPreferences:j("One entry per notification event with its current mode: off, instant, daily, or weekly. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:y("Modes each event accepts, keyed by event. form_submitted and campaign_completed do not accept daily; weekly_report accepts only off or weekly."),defaults:y("Mode each event uses when the user has never configured it.")},update_notification_preferences:{notificationPreferences:j("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:y("Modes each event accepts, keyed by event. form_submitted and campaign_completed do not accept daily; weekly_report accepts only off or weekly."),defaults:y("Mode each event uses when the user has never configured it.")},get_sending_status:{status:p("Company-level sending state: active, paused, or suspended. Anything other than active blocks every send, including test sends."),pauseReason:T("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:T("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:T("ISO timestamp when sending was paused. Null when sending is active."),selfResume:y("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:V("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:y("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:y("Ordered steps for the current state, plus supportEmail, docsUrl, and the dashboard URL. Relay these verbatim instead of improvising recovery advice.")},resume_sending:{resumed:v("True when this call restored sending. False when sending was already active."),message:H,status:p("Sending state after the request. active on success."),selfResume:y("Self-resume state after the request, including the automated review status and how many gates remain."),metricsWindow:y("Enforcement watermarks after the resume. bounceResetAt moves to now, so the paused rate is recalculated from later sends."),remediation:y("Steps to keep sending healthy after the resume, plus supportEmail and docsUrl.")},get_tracking_settings:{tracking:y("Account-wide open/click flags, transactionalOpenTrackingEnabled and transactionalClickTrackingEnabled defaults for Transactional API sends, unsubscribe tracking, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:y("Signup consent settings: doubleOptInEnabled, doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled), and doubleOptInRedirectUrl for where the hosted confirmation page sends subscribers after confirming (null keeps them on the branded confirmation page)."),autoUtm:y("Automatic UTM tagging state and its configured parameters."),trackingDomain:V("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:y("Inbound reply tracking configuration.")},update_tracking_settings:{message:H,tracking:y("Account-wide open/click flags, transactionalOpenTrackingEnabled and transactionalClickTrackingEnabled defaults for Transactional API sends, unsubscribe tracking, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:y("Signup consent settings after the update: doubleOptInEnabled, doubleOptInEmailId for the confirmation email (provisioned automatically the first time double opt-in is enabled), and doubleOptInRedirectUrl for the post-confirmation redirect (null keeps subscribers on the branded confirmation page)."),autoUtm:y("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:V("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:y("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:h("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:h("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:h("sending domain with separate DNS verification and readyToSend sending readiness; readiness.reason explains a domain that cannot send yet"),ready:v("Whether the sender website is ready."),status:p("Current processing or verification status.")},verify_sending_domain:{website:h("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:v("Whether the sending domain passed the fresh DNS verification check. Correct DNS alone does not mean the domain can send yet."),readyToSend:v("Whether DNS and the selected home transport are both ready for sending."),message:p("Verification result summary.")},get_integration_guide:{guide:h("integration guide"),code:p("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:y("One setup step.")}},add_subscriber:{subscriber:h("subscriber")},create_subscriber_import:{import:y(Oi),deduplicated:v("Present and true when idempotencyKey matched an already-queued import. Nothing new was queued; `import` is the original import.")},get_subscriber_import:{import:y(Oi)},update_subscriber:{subscriber:h("subscriber")},remove_subscriber:{subscriber:h("subscriber"),hardDeleted:v("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:h("subscriber")},list_subscriber_notes:{notes:k("subscriber note")},add_subscriber_note:{note:h("subscriber note")},delete_subscriber_note:{id:p("Deleted subscriber note ID."),deleted:v("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:h("subscriber"),event:h("Live event with its name and whether the event definition was created. Historical responses use `events` instead."),duplicate:v("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:v("Present and true when occurredAt selected the historical import path."),events:k("Historical events, each with id, name, and occurredAt."),inserted:b("Historical event rows inserted by this request."),duplicates:b("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:p("One failed side effect.")}},trigger_subscriber_events:{subscriber:h("subscriber"),events:k("recorded event")},import_subscriber_events:{total:b("Events submitted in this request."),recorded:b("Events recorded by this request."),duplicates:b("Events skipped because their eventId was already recorded."),failed:b("Events that failed to record."),sideEffectFailed:b("Receipt rows whose downstream side effects or historical automation shielding failed. This is orthogonal to receipt accounting and may accompany either a newly recorded or duplicate row during recovery."),subscribers:b("Distinct subscriber identities in the request."),failures:{type:"array",description:"Failed events by input index. Recorded events are kept, so treat an error as partial success and retry with the same eventIds.",items:{type:"object",description:"One failed event.",properties:{index:b("Index into the submitted events array."),error:p("Why this event failed.")}}},sideEffectFailures:{type:"array",description:"Post-write failures by input index. The receipt exists (new or duplicate); use the stages and optional error for recovery, then retry with the same eventId.",items:{type:"object",description:"One event receipt (new or duplicate) with failed downstream work.",properties:{index:b("Index into the submitted events array."),stages:{type:"array",description:"Downstream stages that failed.",items:{type:"string",description:"Failed stage name."}},error:p("Optional recovery guidance.")}}},error:p("The first row-level failure message when any event failed.")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:p("One tag name.")},requested:b("Identifiers supplied in the request."),matched:b("Existing subscribers resolved."),updated:b("Subscribers whose tags actually changed."),unchanged:b("Subscribers that already carried every tag."),failed:b("Subscribers whose update failed."),notFound:y("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:k("per-subscriber failure (up to 50)"),triggeredAutomations:v("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:p("One tag name.")},requested:b("Identifiers supplied in the request."),matched:b("Existing subscribers resolved."),updated:b("Subscribers whose tags actually changed."),unchanged:b("Subscribers that did not carry any of the tags."),failed:b("Subscribers whose update failed."),notFound:y("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:k("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:k("subscriber"),pagination:y("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:b("Number of subscribers returned."),truncated:v("Whether matches remain beyond the returned window. Same as pagination.hasMore.")},list_products:{products:k("product"),pagination:y("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:k("product"),created:b("Number of products created."),updated:b("Number of products updated.")},delete_product:{productId:p("Deleted product ID.")},attach_product_file:{product:h("product"),delivery:h("digital delivery file")},remove_product_file:{product:h("product")},upload_image_asset:{asset:h("hosted image asset"),imageBlock:y("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:h("product sync job"),jobId:p("Queued product sync job ID.")},list_tags:{tags:k("tag")},create_tag:{tag:h("tag")},update_tag:{tag:h("tag")},delete_tag:{tagId:p("Deleted tag ID.")},list_lists:{lists:j("Subscriber lists. Each entry includes id, name, description, isPrivate, createdAt, subscriberCount (current members of any status), and activeSubscriberCount (current members with status=active). Memberships with unsubscribedAt set are excluded.")},create_list:{list:h("list")},update_list:{list:h("list")},delete_list:{listId:p("Deleted list ID.")},add_subscribers_to_list:{list:h("list"),added:b("Number of subscribers added to the list."),skipped:b("Number of subscribers skipped.")},remove_subscribers_from_list:{list:h("list"),removed:b("Number of subscribers removed from the list."),skipped:b("Number of subscribers skipped.")},list_segments:{segments:k("segment")},create_segment:{segment:h("segment")},update_segment:{segment:h("segment")},delete_segment:{segmentId:p("Deleted segment ID.")},get_segment_count:{count:b("Number of subscribers matching the segment."),segmentId:p("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:k("audience sync")},list_ad_accounts:{adAccounts:k("ad account")},create_audience_sync:{audienceSync:h("audience sync")},update_audience_sync:{audienceSync:h("audience sync")},delete_audience_sync:{audienceSyncId:p("Deleted audience sync ID.")},sync_audience_now:{audienceSync:h("audience sync"),job:h("audience sync job"),jobId:p("Queued audience sync job ID.")},list_templates:{templates:k("email template"),pagination:y("Pagination metadata: limit, offset, count (this page), total (every email body) and hasMore. Page with offset when hasMore is true.")},get_template:{template:h("email template")},create_template:{template:h("email template")},update_template:{template:h("email template")},set_template_localization:{templateId:p("Localized template ID."),localization:h("template localization")},sync_template_localizations:{templateId:p("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:p("One queued locale code.")},queuedVariantCount:b("Number of localized variants queued for translation.")},delete_template:{templateId:p("Deleted template ID.")},list_email_components:{components:k("email component")},get_email_component:{component:h("email component")},get_default_email_component:{component:h("default email component for the slot")},set_default_email_component:{component:h("saved default email component")},create_email_component:{component:h("email component")},update_email_component:{component:h("email component")},delete_email_component:{id:p("Deleted email component ID.")},list_ab_tests:{abTests:k("A/B test")},get_ab_test:{abTest:h("A/B test")},get_ab_test_stats:{abTest:h("A/B test"),stats:h("A/B test statistics")},restart_ab_test:{abTest:h("A/B test")},select_ab_test_winner:{abTest:h("A/B test with the selected winner")},update_ab_test_variant:{abTest:h("A/B test"),variant:h("A/B test variant")},update_ab_test:{abTest:h("A/B test")},create_ab_test:{abTest:h("A/B test")},add_ab_test_variant:{abTest:h("A/B test"),variant:h("A/B test variant")},delete_ab_test_variant:{abTest:h("A/B test"),variantId:p("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:p("Deleted A/B test ID.")},list_campaigns:{campaigns:j(`List of campaign records returned by Sequenzy. ${Pt}`),pagination:y("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:y(`The campaign record returned by Sequenzy. ${Pt}`)},get_campaign_audience:{campaignId:p("Campaign the audience was resolved for."),campaignName:p("Campaign name."),status:p("Campaign status."),audience:y("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:b("Number of subscribers matching the effective targeting right now."),targetLists:V("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:h("email send, including copied-recipient identity and primary email send ID when applicable"),events:k("email delivery event")},list_email_sends:{emailSends:k("email send"),pagination:h("email send pagination"),retentionDays:b("Number of days sent-email rows remain queryable in this collection.")},list_recipient_suppressions:{suppressions:k("suppressed recipient, with suppressionType, reason, scope and whether it can be removed"),total:b("Total suppressed recipients matching the filter."),page:b("1-based page number returned."),limit:b("Entries per page."),hasMore:v("Whether another page is available."),sortBy:p("Sort field actually applied: suppressedAt, email or status. An unrecognized `sort` falls back to suppressedAt, so read this rather than assuming the requested order took effect."),sortOrder:p("Sort direction applied: asc or desc.")},get_recipient_suppression:{suppression:h("recipient suppression status")},remove_recipient_suppression:{removed:v("Whether a workspace soft-bounce escalation was removed."),removedLocalBounce:v("Whether the workspace-local soft-bounce escalation was removed."),removedSesRegions:{type:"array",description:"Always empty. Sequenzy suppresses solely from its own bounce table and neither reads nor writes the email provider's suppression list. Retained for response compatibility.",items:p("Unused; this array is always empty.")},remainingSuppression:h("recipient suppression status after cleanup")},create_campaign:{campaign:h("campaign")},update_campaign:{campaign:h("campaign")},schedule_campaign:{campaign:h("campaign"),scheduledAt:p("Scheduled send timestamp.")},unschedule_campaign:{campaign:h("draft campaign")},share_campaign:{shareUrl:p("Public anonymized view-in-browser URL for the campaign."),shareToken:p("Capability token embedded in the URL."),created:v("False when an already-active link was returned instead of minted.")},unshare_campaign:{revoked:v("False when the campaign had no active public link.")},share_template:{shareUrl:p("Public anonymized view-in-browser URL for the email."),shareToken:p("Capability token embedded in the URL."),created:v("False when an already-active link was returned instead of minted.")},unshare_template:{revoked:v("False when the email had no active public link.")},send_test_email:{emailSendId:p("Durable test email delivery ID."),recipientEmail:p("Test email recipient.")},send_test_sms:{smsSendId:p("Created test SMS send ID."),toPhone:p("Normalized E.164 destination phone.")},update_sms_number_label:{number:h("updated SMS number (label + brandPrefix override)")},release_sms_number:{number:h("released SMS number (id + status)")},cancel_campaign:{campaign:h("campaign")},pause_campaign:{campaign:h("campaign")},resume_campaign:{campaign:h("campaign")},delete_campaign:{campaignId:p("Deleted campaign ID.")},duplicate_campaign:{campaign:h("duplicated campaign")},resend_campaign_to_non_openers:{campaign:h("non-opener resend draft campaign"),estimatedNonOpenerCount:b("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:k("saved form")},create_form:{form:h("saved form"),embed:y("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:h("saved form"),embed:y("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:h("saved form"),embed:y("Public action URL plus JavaScript, native form, and fetch snippets.")},list_popups:{popups:k("saved popup")},get_popup:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},create_popup:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},update_popup:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},get_popup_embed:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets.")},duplicate_popup:{popup:h("popup copy, created as a draft")},delete_popup:{popupId:p("Deleted popup ID.")},list_landing_pages:{landingPages:k("landing page")},get_landing_page:{landingPage:h("landing page")},get_landing_page_stats:{stats:y("Landing page analytics for the requested window: visits, uniqueVisits, clicks, subscribes, conversionRate (subscribes / uniqueVisits), botVisits, dataAvailableFrom, a daily histogram, referrers, and UTM sources. Default counts exclude known crawlers. Preview URLs and the editor are never counted.")},render_landing_page:{previewUrl:p("Signed, unlisted visitor-facing preview of the current page content. Works for drafts. Not indexed. Share this URL to review layout and copy without publishing."),publicUrl:T("Public visitor URL, or null until the page is published."),landingPageId:p("Landing page ID."),name:p("Landing page name."),status:p("draft or published. Drafts are only visible at previewUrl."),published:v("Whether the page is live on publicUrl. False for drafts."),title:p("Visitor-facing title from SEO metadata or the first heading.")},create_landing_page:{landingPage:h("landing page")},update_landing_page:{landingPage:h("landing page")},duplicate_landing_page:{landingPage:h("landing page")},delete_landing_page:{landingPageId:p("Deleted landing page ID.")},publish_landing_page:{landingPage:h("landing page")},unpublish_landing_page:{landingPage:h("landing page")},connect_landing_page_domain:{landingPage:h("landing page"),domain:p("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:h("landing page"),domain:p("Landing page domain.")},remove_landing_page_domain:{domain:h("landing page domain state")},list_sequences:{sequences:go,pagination:y("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:pe},list_sequence_enrollments:{sequenceId:p("Sequence ID these enrollments belong to."),sequenceName:p("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},stopCondition:y("The sequence's single configured stop condition: `type` (`none` when unset), `value`, and nullable `matchConfig` containing event-property filters, a field comparison, or entry_audience resolution. For entry_audience, value is null and audience identifies the enrolling tag or list resolved per contact. Stop conditions are re-evaluated when an enrollment next runs a step, not when their event arrives."),stopConditionMatchEvaluatedCount:b("How many enrollments in this page were actually evaluated for a current stop-condition match. 0 when stopConditionMatch was not requested, the sequence has no stop condition, or no returned enrollment was still active or waiting."),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:p("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:p("Sequence ID."),subscriberId:p("Subscriber ID."),email:T("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:T("Subscriber first name, or null when unset."),lastName:T("Subscriber last name, or null when unset."),subscriberStatus:T("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:p("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:p("Sequence node this enrollment is currently sitting on."),currentNodeType:p("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:p("Current sequence node label or email subject when available."),currentNodeMissing:v("Whether the current node no longer exists in the sequence graph."),enrollmentKey:p("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:p("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:T("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:p("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:T("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:T("Step this enrollment was released from by move_sequence_enrollments, or null when it reached its current step on its own."),movedAt:T("ISO 8601 timestamp of that release, or null when the enrollment was never moved."),moveReason:T("Note recorded with that release, or null when none was given."),stopConditionMatches:ho("Whether the sequence's stop condition matches for this contact right now. Null when it was not determined: stopConditionMatch was not requested, the sequence has no stop condition, this enrollment is no longer active or waiting, or it fell outside the evaluated window. Null never means `does not match`. This is a non-atomic snapshot: the worker re-checks before a future step, but the condition can change and a step already past its stop check may still finish."),stopConditionMatchReason:T("Human-readable reason the stop condition matches, such as the stop event or tag that satisfied it. Null when stopConditionMatches is not true."),enteredVia:{type:"object",description:"What put this contact into the sequence. Use this to distinguish which list or tag matched a multi-value trigger.",properties:{kind:p("Entry source kind: list, tag, segment, event, inactivity, frequency, manual, test_run, or unknown."),value:T("Raw list ID, tag name, segment ID, event name, or monitored event name. Null for manual, test_run, and unknown."),name:T("Resolved display name for list and segment sources, or null when not applicable or deleted."),description:p("Ready-to-display description of the entry source.")},required:["kind","value","name","description"],additionalProperties:!0},entryContext:{type:"object",description:"Event or manual-enrollment context captured at entry. Property keys only; values are never returned.",properties:{triggerType:T("Stored entryTriggerType, such as event_received or manual_enrollment. Null when never stamped."),eventId:T("Durable ID of the enrolling event, or null."),eventName:T("Enrolling event name, or null."),hasEventProperties:v("Whether any event property keys were stored on this enrollment."),eventPropertyKeys:{type:"array",description:"Keys present on the enrolling event payload. Values are omitted.",items:{type:"string",description:"Event property key."}},hasFieldSnapshots:v("Whether subscriber field snapshots were stored at enrollment."),fieldSnapshotKeys:{type:"array",description:"Subscriber field paths snapshotted at enrollment. Values are omitted.",items:{type:"string",description:"Field path."}}},additionalProperties:!0},branchDecisions:{type:"array",description:"Bounded redacted if/else and random-split verdicts, oldest first within the retained window. Compared values are summaries (missing, empty, nonempty, equals_expected), never the raw field or event-property value. Empty on enrollments recorded before this field existed; use get_sequence_enrollment to reconstruct those from ClickHouse.",items:y("One branch or condition decision, including selectedPath and per-branch evaluations.")},branchDecisionCount:b("Total branch and condition decisions taken, including decisions omitted from the bounded array."),branchDecisionsTruncated:v("Whether older decisions were omitted from branchDecisions.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:y("Pagination metadata.")},get_sequence_enrollment:{sequenceId:p("Sequence ID."),sequenceName:p("Sequence name."),stopCondition:y("The sequence's single configured stop condition."),enrollment:y("The enrollment token: enteredVia, entryContext (event keys, never values), and branchDecisions (redacted)."),nodeHistory:j("ClickHouse graph-walk events for this token, oldest first. Each item may include a redacted branchDecision reconstructed from stored metadata when the token itself has none."),nodeHistoryTruncated:v("Whether additional node events exist beyond the returned bounded history."),nodeHistoryLimit:b("Maximum number of node events returned."),historySource:p("Where the branch history came from: node_events, token_context, both, or none.")},simulate_sequence:{sequenceId:p("Sequence ID."),sequenceName:p("Sequence name."),status:p("Stored sequence status."),sendsMail:v("Always false. Simulation never sends mail or enrolls anyone."),enrollment:y("Who currently matches and the confirmation that nobody is auto-enrolled on activate. List, tag, and segment matches can still be enrolled by hand."),readiness:y("Activation checks: ready, errors that should be fixed before enable_sequence, and non-blocking warnings."),path:V("Walked graph for the optional stored subscriber, including branch verdicts, emailStepsOnPath (traversed email nodes), and emailsOnPath (emails deliverable for the subscriber's current email/status). Null when no subscriberId or email was passed.")},send_sequence_test_email:{sequenceId:p("Sequence ID."),nodeId:p("Tested sequence email-step node ID."),results:j("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:pe,eventTrackingCode:p("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:y("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:p("One required event name.")}},update_sequence:{sequence:Ui},update_sequence_node:{sequence:h("sequence")},update_sequence_nodes:{sequence:h("sequence")},edit_sequence_graph:{sequence:Ui},insert_sequence_step:{sequence:h("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:p("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:p("Inserted email template ID.")},insertedEmailCount:b("Number of email steps inserted."),addedBranchNodeId:p("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:y("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:p("Sequence ID."),status:p("Stored lifecycle status after the change."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...rt},disable_sequence:{sequenceId:p("Sequence ID."),status:p("Stored lifecycle status after the change."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...rt},duplicate_sequence:{sequence:pe,nodes:k("sequence node"),edges:k("sequence edge")},archive_sequence:{sequence:pe},unarchive_sequence:{sequence:pe},list_campaign_goals:{goals:k("campaign goal")},create_campaign_goal:{goal:h("campaign goal")},update_campaign_goal:{goal:h("campaign goal")},delete_campaign_goal:{goalId:p("Deleted campaign goal ID.")},list_sequence_goals:{goals:k("sequence goal")},create_sequence_goal:{goal:h("sequence goal")},update_sequence_goal:{goal:h("sequence goal")},delete_sequence_goal:{goalId:p("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:h("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:h("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:h("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:p("Sequence ID."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...rt},resume_sequence_enrollments:{sequenceId:p("Sequence ID."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...rt},enroll_subscribers_in_sequence:{sequence:h("sequence"),enrollments:k("sequence enrollment"),enrolled:b("Number of subscribers enrolled."),skipped:b("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:p("Sequence ID."),dryRun:v("Whether this call only reported matches instead of cancelling them."),target:y("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:b("Active/waiting enrollments matching the target when the request started."),cancelledCount:b("Enrollments cancelled by this call."),remainingCount:b("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:k("sequence enrollment sample (up to 50)"),hasMore:v("Whether more enrollments matched than the returned sample.")},move_sequence_enrollments:{sequenceId:p("Sequence ID."),dryRun:v("Whether this call only reported the batch instead of moving it."),fromNodeId:p("Step the enrollments were taken from."),targetNodeId:p("Step the enrollments were moved onto, resolved from the source step's next step when not supplied."),sort:p("Order the batch was selected in."),requestedLimit:b("limit as requested."),effectiveLimit:b("How many this call was allowed to move after the daily guardrail was applied."),matchedCount:b("Movable enrollments parked on fromNodeId when the request started."),movedCount:b("Enrollments moved by this call."),remainingCount:b("Movable enrollments still on fromNodeId. Repeat the same request while this is above zero."),skippedCount:b("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:Ri("Applied daily guardrail, or null when none was requested."),movedInWindow:b("Moves onto targetNodeId already recorded in the rolling 24-hour window."),dailyRemaining:Ri("How many more can be moved onto targetNodeId today, or null when no dailyLimit was requested."),enqueuedCount:b("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:y("One tokenId with its enqueue error.")},tagResult:V("Tagging outcome for the moved contacts: tags, updated, unchanged, failed, failures. Null when no tags were requested."),enrollments:k("moved (or, on a dry run, would-move) sequence enrollment sample (up to 50)"),hasMore:v("Whether more enrollments matched than the returned sample.")},realign_sequence_enrollments:{sequenceId:p("Sequence ID."),dryRun:v("Whether this call only previewed the new wait times instead of writing them."),sendingWindow:V("The sequence sending window realignment anchored on (timezone, startTime, endTime, days), or null when only per-step weekday gates applied."),scannedCount:b("Waiting enrollments inspected by this call."),realignedCount:b("Waiting enrollments moved earlier (or that would move, on a dry run)."),unchangedCount:b("Waiting enrollments left exactly as they were."),unchangedReasons:y("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:b("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:k("realigned enrollment sample (up to 50) with waitUntil, newWaitUntil, and movedEarlierMinutes"),hasMore:v("Whether a per-call cap stopped the scan early. Continue with nextCursor while this is true."),nextCursor:p("Opaque continuation cursor to pass as cursor on the next call when hasMore is true."),status:p("For an applied request, queued while the background job is pending."),jobId:p("Background job ID to pass to get_sequence_enrollment_realignment.")},get_sequence_enrollment_realignment:{sequenceId:p("Sequence ID."),dryRun:v("Always false for an applied job."),status:p("queued, running, completed, or failed."),jobId:p("Background realignment job ID."),result:V("Completed realignment result, including counts, changes, hasMore, and nextCursor; null until completion."),error:T("Safe recovery guidance when the job failed, otherwise null.")},delete_sequence:{sequenceId:p("Deleted sequence ID.")},list_transactional_emails:{transactional:k("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:h("transactional email")},create_transactional_email:{transactional:h("transactional email")},update_transactional_email:{transactional:h("transactional email")},delete_transactional_email:{deleted:y("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:p("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},to:{type:["string","array"],items:p("One accepted To address."),description:"Accepted primary recipients, lowercased. A string for a single-recipient send, an array when several addresses share the email."},cc:{type:"array",items:p("One accepted Cc address."),description:"Accepted carbon-copy recipients, lowercased, with addresses already in `to` removed. Present only when the send has cc recipients."},bcc:{type:"array",items:p("One accepted Bcc address."),description:"Accepted blind-carbon-copy recipients, lowercased, with addresses already in `to` or `cc` removed. Present only when the send has bcc recipients."},transactional:h("transactional email")},get_stats:{stats:y(`Account-wide delivery funnel for the requested window. ${oe}`),emailType:p("Applied structural email type filter when one was requested."),subscriberCount:b("Live count of every stored contact in the company. Independent of period. Use this for 'how many subscribers do I have'."),activeSubscriberCount:b("Live count of contacts with status=active. Independent of period. May include phone-only contacts without an email address."),commerceForecast:h("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:h("campaign"),stats:y(`Delivery funnel for this campaign. ${oe}`),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:y("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. ${se} 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:y("One poll or NPS results summary.")},recommendations:y("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."),goals:{type:"array",description:"Conversion goals attached to this campaign, in creation order. Each entry has goalId, name, conversions attributed to this campaign, and trackedValue in minor units. Present only when the campaign has attached goals. Zero-conversion goals are included so the report can show the full funnel.",items:y("One campaign goal with goalId/name/conversions/trackedValue.")}},list_poll_responses:{campaignId:p("Campaign the responses belong to."),blockId:p("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:y("One respondent's latest answer.")},pagination:y("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:h("transactional email"),stats:y(`Delivery funnel for this transactional email. ${oe}`),complaints:h("complaint count and rate for the selected transactional email"),clickedLinks:k("clicked link with click count and percentage share"),bounceBreakdown:h("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:h("human and machine open and click counts")},get_sequence_stats:{sequence:pe,stats:y(`Delivery funnel across every email step in this sequence. ${oe}`),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. ${oe}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:b("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:p("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:T("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:y(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${oe}`),failedCount:b("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:j("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:b("Active enrollment count."),waiting:b("Waiting enrollment count."),total:b("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:p("Current sequence node ID."),currentNodeType:p("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:p("Current sequence node label or email subject when available."),currentNodeMissing:v("Whether the current node no longer exists in the sequence graph."),active:b("Active enrollment count at this node."),waiting:b("Waiting enrollment count at this node."),total:b("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:b("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:b("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:y("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:k("campaign email event"),pagination:y("Pagination metadata.")},list_sequence_events:{events:k("sequence email event"),pagination:y("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:p("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:p("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:T("Campaign ID, or null for sequence emails."),sequenceId:T("Sequence ID, or null for campaigns."),sequenceName:T("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:T("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:y(`Delivery funnel for this email alone. ${oe}`),conversions:b("Attributed conversions credited to this email."),revenueCents:b("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:y(`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". ${oe}`),pagination:y("Pagination metadata."),sort:p("Sort field the response was ordered by."),order:p("Sort order the response was ordered by."),step:b("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:p("Sequence ID.")}},get_subscriber_activity:{activity:k("subscriber activity event"),subscribers:k("subscriber"),pagination:y("Pagination metadata.")},list_team_members:{members:k("team member"),invitations:k("team invitation")},invite_team_member:{invitation:h("team invitation")},cancel_team_invitation:{invitationId:p("Cancelled invitation ID.")},list_conversations:{conversations:k("inbox conversation"),pagination:y("Pagination metadata.")},get_conversation:{conversation:h("inbox conversation"),messages:k("conversation message")},reply_to_conversation:{conversation:h("inbox conversation"),message:h("conversation message")},update_conversation_status:{conversation:h("inbox conversation")},mark_conversation_read:{conversation:h("inbox conversation")},list_webhooks:{webhooks:k("outbound webhook")},create_webhook:{webhook:h("outbound webhook")},update_webhook:{webhook:h("outbound webhook")},delete_webhook:{webhookId:p("Deleted outbound webhook ID.")},test_webhook:{webhook:h("outbound webhook"),delivery:h("test webhook delivery")},list_webhook_deliveries:{deliveries:k("webhook delivery")},replay_webhook_delivery:{delivery:h("webhook delivery"),job:h("webhook replay job")},generate_email:{email:h("generated email"),html:p("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:y("One generated email block.")},subject:p("Generated subject line."),previewText:p("Generated inbox preview text.")},generate_sequence:{sequence:h("persisted AI-generated sequence draft"),deprecated:v("Always true for this deprecated alias."),deprecationMessage:p("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:p("One generated subject line.")},variants:k("generated subject line variant")},generate_sms:{prompt:p("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:y("One generated SMS message.")}},get_sms_settings:{sms:y("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).")},get_sms_usage:{usage:j("Per-number SMS usage entries: fromNumber (E.164), totalSends, delivered, failed, creditsCharged, lastSentAt, testSends. Totals exclude test sends; test sends are counted separately.")},submit_feedback:{},render_email:{html:p("Email-safe HTML document, rendered exactly as it would be sent."),subject:p("Subject line with merge tags resolved."),previewText:T("Inbox preview text with merge tags resolved, or null when unset."),locale:p("Localization locale the render resolved to."),personalized:v("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:v("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:j(`Merge tags that did not resolve, 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. An unknown name is reported even when a default filter such as {{ subscriber.frstName | default: "there" }} supplied text in its place: the fallback then reaches every recipient, including the ones whose real value is stored, and the rendered HTML looks correct precisely because the default worked. A recognized name that is merely blank for this contact is not reported when it has a default, since that is what a default is for. 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.`),unevaluatedConditions:j('Block conditions this render could not decide, as [{ field, operator, value, description, reason, hint }]. Each was rendered as false, the same fail-closed rule a live send uses, so an else branch in the HTML is not evidence that the condition is false for a real recipient - checking the HTML alone cannot tell the two apart. reason "requires_stored_subscriber" means the field reads stored subscriber state: pass subscriberId, or for a `tag` condition pass tags on the inline subscriber, and it resolves. reason "invalid_filter" means the stored condition is malformed, which fails closed on a real send too, and hint carries the validation error. reason "evaluation_failed" means the lookup itself failed and the render is worth retrying. An empty array means every condition in the email was actually evaluated.'),entity:y("Which entity was rendered: type, id, and variantId.")}};function _o(t){let e=wo[t];if(e===void 0)throw Error(`MCP tool "${t}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${t}\` MCP tool.`,properties:{...bo,...e,...dn.has(t)?fo:{}},additionalProperties:!0}}function Ni(t){return{...t,outputSchema:_o(t.name)}}function Mi(t){if(I(t))return t;if(Array.isArray(t))return{items:t};return{value:t}}var Li=[{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, localization sync status, and settings. Sequence action_ab_test steps also expose each variant's blocks on get_sequence.sequence.emails[].abTest.variants; use this tool when you need the full test record rather than copy alone. Pass the abTestId from get_sequence.",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:L},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:"select_ab_test_winner",description:"Select a winner for a campaign A/B test that is currently testing and queue the winning variant for the remaining audience. This starts external email delivery.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"Campaign A/B test ID"},variantId:{type:"string",description:"Winning variant ID"}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update an A/B test variant, including the email body of a sequence step whose nodeType is action_ab_test - that content cannot be edited through update_sequence_node or update_template, and a change meant for the whole step has to be repeated on every variant. Take abTestId and variantId from get_sequence.sequence.emails[].abTest.variants (or get_ab_test). If this tool is not in the MCP tool list, enable it on the Sequenzy connector rather than writing through another email tool. 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. ${R}`},blocks:{type:"array",description:`${Z}${ae} 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. A conversion moves that step's copy off the sequence node and onto the test's variants: from then on update_sequence_node cannot edit its subject, previewText, or blocks, and every content change has to be applied per variant with update_ab_test_variant (get_ab_test lists them). The response echoes this in contentEditing.",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:`${Z}${ae}`,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:`${Z}${ae}`,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 $i=[{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:
2
+ import{serveStdio as $a}from"@modelcontextprotocol/server/stdio";class G extends Error{statusCode;rawDetails;code;context;constructor(t,e,n,s,i){super(t);this.statusCode=e;this.rawDetails=n;this.code=s;this.context=i;this.name="McpApiError"}}function Hn(t){if(t instanceof G)return{message:t.message,statusCode:t.statusCode,code:t.code,rawDetails:t.rawDetails,context:t.context};if(t instanceof Error)return{message:t.message};return{message:String(t)}}function Vr(t){if(!(t instanceof Error)||t instanceof G)return;let e=t.message.trim();if(!e)return;return e.replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,"[redacted email]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/g,"Bearer [redacted]").replace(/\bseq_(?:user_)?[A-Za-z0-9_-]{8,}\b/g,"[redacted key]")}function Yr(t){let e=t.match(/api key is missing required scopes?:\s*(.+)$/i);if(!e?.[1])return[];return[...new Set(e[1].match(/[a-z_]+:[a-z_]+/gi)??[])]}function Jr(t,e){let n=Hn(t),s=n.message.trim()||"Unknown error",i=s.toLowerCase();if(e&&(n.context?.title||n.context?.description||n.context?.howToFix||n.context?.docsUrl))return{title:n.context.title??(n.statusCode===409?"Request conflict":"API request failed"),description:n.context.description??"The Sequenzy API could not complete this request.",howToFix:n.context.howToFix??"Review the requested operation, adjust the tool input, and retry.",docsUrl:n.context.docsUrl??"https://docs.sequenzy.com/concepts/mcp"};if(n.code==="MCP_AUTH_REQUIRED"||i.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"};if(n.statusCode===401||n.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"};if(n.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"};let r=Yr(s);if(r.length>0){let o=r.map((m)=>`\`${m}\``).join(", "),d=r.every((m)=>m.endsWith(":read"))?"the Read-only or Safer agent access preset":"Safer agent access when it covers the task, or Custom permissions",c=r.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 ${r.length===1?"scope":"scopes"}: ${o}.`,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\` and enable ${o} on the connected key. The URL opens Account → API Keys for a personal key and workspace Settings → API Keys for a company key without returning the key's internal identity through MCP. If \`get_account\` also requires \`account:read\`, open ${"https://sequenzy.com/dashboard"} directly and choose the matching API Keys page. A company key that already holds \`api_keys:manage\` can instead call \`list_api_keys\`, find the entry where \`isCurrent\` is true, and call \`update_api_key\` with that entry's \`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 ${o}, or a preset covering all of them (${d}). 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.${c}`,docsUrl:"https://docs.sequenzy.com/concepts/mcp"}}if(n.statusCode===403||i.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"};if(i.includes("no company available")||i.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"};if(n.statusCode===404||i.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"};if(i.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"};if(n.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"};if(n.code==="AB_TEST_VARIANT_CONTENT_EDIT"||i.includes("update_ab_test_variant")&&(i.includes("a/b test")||i.includes("ab test")))return{title:"A/B variant copy cannot be edited here",description:"This sequence step stores its email copy on A/B test variants, so the attempted write target cannot update it.",howToFix:"Call `update_ab_test_variant` with `abTestId` and `variantId` from `get_sequence.sequence.emails[].abTest.variants` (or `get_ab_test`). Repeat once per variant for a whole-step rewrite. If the sequence is live or the test has activity, pass `confirmLiveChange: true`. Needs `ab_tests:write` and `sequences:write`, both on Safer agent access. If `update_ab_test_variant` is not in the MCP tool list, enable it on the Sequenzy connector - do not retry with `update_template`, `update_sequence_node`, or another email tool.",docsUrl:"https://docs.sequenzy.com/concepts/mcp#editing-the-content-of-a-sequence-ab-step"};if(n.statusCode===429||i.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"};if(n.code==="NETWORK_ERROR"||i.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"};if(i.includes("unknown tool")||i.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"};if(i.includes("is required")||i.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"};if(n.statusCode&&n.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, consult the docs before escalating.",docsUrl:"https://docs.sequenzy.com/concepts/mcp"};return{title:"Tool execution failed",description:"The MCP server could not complete the requested operation.",howToFix:"Review the tool input or credentials and retry.",docsUrl:"https://docs.sequenzy.com/concepts/mcp"}}function ne(t,e={}){let n=e.includeDetails??!0,s=Jr(t,n),i=Hn(t),r=n?i.rawDetails?.trim()||i.message.trim():Vr(t);return[`Sequenzy MCP error: ${s.title}`,`Description: ${s.description}`,`How to fix: ${s.howToFix}`,`Docs: ${s.docsUrl}`,...r?[`Details: ${r}`]:[]].join(`
3
+ `)}import{AsyncLocalStorage as Qr}from"node:async_hooks";var We={name:"@sequenzy/mcp",version:"0.0.161",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 --packages=external",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/server":"2.0.0"},devDependencies:{"@modelcontextprotocol/client":"2.0.0","@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 Xr="https://api.sequenzy.com",eo=new Set(["/api/v1/media/upload-bytes","/v1/media/upload-bytes"]),Re=new Qr,Bn=!1;function Wn(){Bn=!0}function Ge(){return Bn}var Gn=null;function ie(){let t=Re.getStore();if(t)return t.selectedCompanyId??null;return Gn}function Ae(t){let e=Re.getStore();if(e){e.selectedCompanyId=t;return}Gn=t}function kt(t,e){return Re.run(t,e)}function Kn(){return Re.getStore()?.apiUrl??process.env.SEQUENZY_API_URL??Xr}function Vn(){return Re.getStore()?.apiKey??process.env.SEQUENZY_API_KEY}function Yn(t,e,n){let s=Vn();if(!s)throw new G("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED");let i={"Content-Type":t,Authorization:`Bearer ${s}`,"x-sequenzy-client":`mcp/${We.version}`},r=e===null?null:e??ie();if(r)i["x-company-id"]=r;return Object.assign(i,n),i}function Jn(){if(Vn())return;console.error(ne(new G("SEQUENZY_API_KEY environment variable is required",401,void 0,"MCP_AUTH_REQUIRED"))),process.exit(1)}function M(t,e){let n=t[e];return typeof n==="string"&&n.trim()!==""?n.trim():void 0}function to(t){if(t===void 0)return;if(typeof t==="string")return t.trim()||void 0;return JSON.stringify(t)}function Zn(t){if(!t.trim())return{message:"Request failed"};try{let e=JSON.parse(t);if(typeof e==="string")return{message:e};let n=typeof e.error==="object"&&e.error!==null?e.error:void 0,s=M(e,"code")??(n?M(n,"code"):void 0),i=(typeof e.error==="string"?e.error:void 0)??(n?M(n,"message"):void 0)??M(e,"message")??M(e,"error")??t,r=M(e,"howToFix")??M(e,"resolution"),o={...M(e,"title")?{title:M(e,"title")}:{},...M(e,"description")?{description:M(e,"description")}:{},...r?{howToFix:r}:{},...M(e,"docsUrl")?{docsUrl:M(e,"docsUrl")}:{}},d=to(e.details);if(Object.keys(o).length>0||d)return{message:i,...s?{code:s}:{},...d?{details:d}:{},...Object.keys(o).length>0?{context:o}:{}};if(typeof e.error==="string")return{message:e.error,...s?{code:s}:{}};if(n)return{message:i,...s?{code:s}:{}};return{message:i,...s?{code:s}:{}}}catch{return{message:t}}}async function a(t,e,n,s,i){let r=Yn("application/json",s,i),o;try{o=await fetch(`${Kn()}${e}`,{method:t,headers:r,body:n?JSON.stringify(n):void 0})}catch(d){throw new G(d instanceof Error?d.message:"Failed to reach Sequenzy API",0,void 0,"NETWORK_ERROR")}if(!o.ok){let d=await o.text(),c=Zn(d);throw new G(c.message,o.status,c.details??d,c.code,c.context)}return o.json()}async function Qn(t,e,n,s){let i=new URL(Kn()).origin,r=new URL(t,`${i}/`);if(r.origin!==i){if(!eo.has(r.pathname))throw new G("The image upload URL did not point to the configured Sequenzy API.",500,void 0,"INVALID_UPLOAD_URL");r=new URL(`${r.pathname}${r.search}`,`${i}/`)}let o;try{o=await fetch(r,{method:"PUT",headers:Yn(n,s),body:e})}catch(d){throw new G(d instanceof Error?d.message:"Failed to upload image bytes",0,void 0,"NETWORK_ERROR")}if(!o.ok){let d=await o.text(),c=Zn(d);throw new G(c.message,o.status,c.details??d,c.code,c.context)}}import{McpServer as La}from"@modelcontextprotocol/server";var St=["product-info","domain","tracking","localization","integrations","products","events","tags","labels","goals","sync-rules","api-keys","widgets","team","danger"],Xn={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}",account:"/dashboard/company/{companyId}/account",subscription:"/dashboard/company/{companyId}/account?tab=subscription",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 no(t){let n=(t??process.env.SEQUENZY_APP_URL??"https://sequenzy.com").trim().replace(/\/+$/,"");return n.length>0?n:"https://sequenzy.com"}function K(t){let e=t?.trim();return e?e:void 0}function J(t){return encodeURIComponent(t)}function x(t,e){return`${t}${e}`}function R(t,e=""){return`/dashboard/company/${J(t)}${e}`}function ei(t,e,n){return x(t,`${R(e,"/settings")}?tab=${encodeURIComponent(n)}`)}function io(t,e){let n=St.map((s)=>[s,e?ei(t,e,s):""]);return Object.fromEntries(n)}function Z(t={},e){let n=no(e),s=K(t.companyId),i={},r=io(n,s);if(!s)return{appUrl:n,routeTemplates:Xn,settingsTabValues:St,urls:i,settingsUrls:r};i.dashboard=x(n,R(s)),i.campaigns=x(n,R(s,"/campaign")),i.landingPages=x(n,R(s,"/landing-pages")),i.sequences=x(n,R(s,"/sequences")),i.account=x(n,R(s,"/account")),i.subscription=`${i.account}?tab=subscription`,i.settings=x(n,R(s,"/settings")),i.emails=x(n,R(s,"/emails")),i.subscribers=x(n,R(s,"/subscribers")),i.sentEmails=x(n,R(s,"/sent-emails")),i.segments=x(n,R(s,"/segments")),i.metrics=x(n,R(s,"/metrics")),i.transactional=x(n,R(s,"/transactional"));let o=K(t.campaignId);if(o)i.campaign=x(n,R(s,`/campaign/${J(o)}`)),i.campaignPreview=`${i.campaign}?step=review`;let d=K(t.landingPageId);if(d)i.landingPage=x(n,R(s,`/landing-pages/${J(d)}`));let c=K(t.sequenceId);if(c)i.sequence=x(n,R(s,`/sequences/${J(c)}`));let m=K(t.emailId)??K(t.templateId);if(m)i.email=x(n,R(s,`/emails/${J(m)}`)),i.template=i.email;let g=K(t.transactionalId);if(g)i.transactionalEmail=x(n,R(s,`/transactional/${J(g)}`));let w=K(t.emailSendId);if(w)i.emailSend=x(n,R(s,`/sent-emails/${J(w)}`));let f=K(t.domainId);if(f)i.domain=x(n,R(s,`/settings/domain/${J(f)}`)),i.domainVerify=`${i.domain}/verify`;let _=K(t.status);if(_)i.campaignList=x(n,R(s,`/campaign/list/${J(_)}`)),i.sequenceList=x(n,R(s,`/sequences/list/${J(_)}`));let T=K(t.settingsTab);if(T)i.settingsTab=T==="billing"||T==="subscription"?i.subscription:ei(n,s,T);return{appUrl:n,routeTemplates:Xn,settingsTabValues:St,urls:i,settingsUrls:r}}var Tt=new Set(["connect_integration","create_api_key","create_webhook","list_webhook_deliveries","replay_webhook_delivery","rotate_sequence_inbound_webhook_secret"]),ti={ssn:"government identifiers",passport:"government identifiers",cvv:"payment or financial-account data",cvc:"payment or financial-account data",iban:"payment or financial-account data",diagnosis:"health or medical data",diagnoses:"health or medical data",prescription:"health or medical data",prescriptions:"health or medical data",medication:"health or medical data",medications:"health or medical data",patient:"health or medical data",biometric:"biometric or genetic data",biometrics:"biometric or genetic data",faceprint:"biometric or genetic data",voiceprint:"biometric or genetic data",genetic:"biometric or genetic data",genome:"biometric or genetic data",password:"authentication credentials or secrets",passwords:"authentication credentials or secrets",passwd:"authentication credentials or secrets",pwd:"authentication credentials or secrets",passcode:"authentication credentials or secrets",secret:"authentication credentials or secrets",secrets:"authentication credentials or secrets",token:"authentication credentials or secrets",otp:"authentication credentials or secrets",credential:"authentication credentials or secrets",credentials:"authentication credentials or secrets",ethnicity:"sensitive demographic data",religion:"sensitive demographic data",religious:"sensitive demographic data",sexual:"sensitive demographic data",political:"sensitive demographic data",disability:"sensitive demographic data",disabilities:"sensitive demographic data",latitude:"precise geolocation",longitude:"precise geolocation",lat:"precise geolocation",lng:"precise geolocation",lon:"precise geolocation",coordinates:"precise geolocation",coords:"precise geolocation",geolocation:"precise geolocation"},ni=[{category:"government identifiers",pattern:/^(ssn|socialsecurity(number)?|governmentid(number)?|nationalid(number)?|passport(number|id)?|drivers?licen[cs]e(number)?|taxid|taxidentification(number)?|tin)$/},{category:"payment or financial-account data",pattern:/^(cardnumber|creditcard(number)?|debitcard(number)?|paymentcard(number)?|pan|cvv|cvc|cardsecuritycode|bankaccount(number)?|routingnumber|iban)$/},{category:"health or medical data",pattern:/^(health|healthcondition|medical|medicalcondition|medicalhistory|mentalhealth|diagnosis|diagnoses|patientid|prescription|medication|treatment|healthinsurance|healthrecord|medicalrecord(number)?|bloodtype)$/},{category:"biometric or genetic data",pattern:/^(biometric(s)?|fingerprint|faceprint|voiceprint|retinascan|genetic(data)?|dna)$/},{category:"authentication credentials or secrets",pattern:/^(password|passcode|pin|otp|onetimepassword|mfacode|x?apikey|apisecret|personalapikey|profileapitoken|x?accesstoken|refreshtoken|x?authtoken|x?authorization|credential(s)?|secret|token|clientsecret|secretkey|privatekey|signingkey|signingsecret|x?webhooksecret|webhooksignature|privatetoken|rawkey|plainkey)$/},{category:"sensitive demographic data",pattern:/^(race|ethnicity|religion|religiousbelief|sexualorientation|genderidentity|politicalaffiliation|politicalopinion|unionmember(ship)?|disability)$/},{category:"precise geolocation",pattern:/^(lat|lng|lon|long|latitude|longitude|latlng|latlon|coordinates|coords|geocoordinates|gpscoordinates|geopoint|gps|geolocation|preciselocation)$/}],ii={"authentication credentials or secrets":new Set(["id","ids","name","type","prefix","count","at","enabled","required","status","hint","label","url","length","expires","expiry","expiration","updated","created","rotated","set","exists","present","verified","valid","masked","mask","policy","strength","permission","permissions","scope","scopes","preset"]),"payment or financial-account data":new Set(["brand","type","last4","last","network","funding","country","masked","mask"])},si=new Set(["has","is","requires","needs","can","should","allow","allows","uses","with","without","next","page","continuation","pagination","cursor","prev","previous"]),ri=[{category:"government identifiers",pattern:/\b(?:ssn|social security(?: number)?|passport(?: number)?|government id)\s*[:#-]\s*\S+/i},{category:"payment or financial-account data",pattern:/\b(?:card number|credit card|debit card|cvv|cvc|bank account|routing number|iban)\s*[:#-]\s*\S+/i},{category:"health or medical data",pattern:/\b(?:diagnosis|medical condition|health condition|patient id|prescription|medication)\s*[:#-]\s*\S+/i},{category:"biometric or genetic data",pattern:/\b(?:fingerprint|faceprint|voiceprint|retina scan|biometric|genetic data|dna)\s*[:#-]\s*\S+/i},{category:"authentication credentials or secrets",pattern:/\b(?:password|passcode|one[- ]time password|otp|mfa code|api key|access token|refresh token|client secret|authorization)\s*[:=]\s*\S+/i},{category:"authentication credentials or secrets",pattern:/\b(?:Bearer\s+[A-Za-z0-9._~+/=-]{12,}|seq_(?:user_)?[A-Za-z0-9_-]{12,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b/},{category:"sensitive demographic data",pattern:/\b(?:race|ethnicity|religion|religious belief|sexual orientation|gender identity|political (?:affiliation|opinion|party)|union membership|disability)\s*[:#-]\s*\S+/i},{category:"precise geolocation",pattern:/\b(?:latitude|longitude|lat|lng|lon|gps(?: coordinates)?|coordinates|coords|geolocation|precise location)\s*[:#=-]\s*-?\d/i},{category:"precise geolocation",pattern:/(?:^|[^\d.-])-?(?:90(?:\.0+)?|[1-8]?\d\.\d{4,})\s*,\s*-?(?:180(?:\.0+)?|1[0-7]\d\.\d{4,}|[1-9]?\d\.\d{4,})(?![\d.])/}],oi=[{label:"an email address",pattern:/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/},{label:"a UUID",pattern:/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i},{label:"a resource ID",pattern:/\b[a-z][a-z0-9]{23,}\b/}],ai=new Set(["accountid","debug","debuginfo","diagnostic","diagnostics","errordetails","errorstack","headers","internaldetails","internalid","lasterror","lastresponsebody","lastsyncerror","metadata","payload","rawdetails","rawpayload","rawrequest","rawresponse","requestbody","requestheaders","requestid","responsebody","responseheaders","sessionid","stack","stacktrace","traceid","userid"]),di=["internalid","requestid","sessionid","traceid","userid"],qt=new Set(["attribute","attributeKey","attributePath","enrollmentFieldPath","entryFieldPath","eventFieldPath","eventPropertyName","fieldName","fieldPath"]),Ke=new Set(["customAttributeKeys","entryEventPropertyKeys","eventPropertyKeys","fieldSnapshotKeys","includeAttributes"]),ci={customAttributeUpdates:"name",customFields:"name",outputFields:"key"},Pt=new Set(["attributePreviousValue","attributeValue","attributes","body","bodyHtml","bodyText","campaignData","computedLists","customAttributes","customIntegration","events","fieldMapping","fieldValue","fieldValues","filters","headers","properties","propertyFilters","reason","root","samplePayload","subscriber","subscribers","targetLists","trigger","variables"]),Et={reply_to_conversation:new Set(["subject"]),submit_feedback:new Set(["context","message"])},li=new Set(["add_subscriber_note","get_conversation","get_subscriber","list_conversations","list_poll_responses","list_subscriber_notes","reply_to_conversation"]),pi=new Set([...Pt,...qt,...Ke,"blocks","branch","branches","changes","config","content","elseSteps","emails","insertSteps","outputFields","steps","stopCondition","subscriberUpdateSteps","updates","url","variants"]),ui=new Set(["get_sequence_inbound_webhook","configure_sequence_inbound_webhook"]),mi=new Set(["create_landing_page","duplicate_landing_page","get_landing_page","list_landing_pages","publish_landing_page","render_landing_page","unpublish_landing_page","update_landing_page"]),hi="/lp/preview/",De="[redacted restricted data]";var ge="authentication credentials or secrets";function fe(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}function gi(t){let e=fe(t);if(ai.has(e))return!0;return di.some((n)=>e.endsWith(n))}function xt(t){return ni.find(({pattern:e})=>e.test(t))?.category}function so(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/([a-zA-Z])(\d)/g,"$1 $2").replace(/(\d)([a-zA-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function ro(t){if(t.length<2)return;let e=t[0]??"",n=t[t.length-1]??"",s=(i,r)=>{if(i===ge&&si.has(e))return;if(r===t.length-1)return i;return ii[i]?.has(n)?void 0:i};for(let i=0;i<t.length;i++){let r=t[i]??"",o=ti[r];if(o){let d=s(o,i);if(d)return d}for(let d of[2,3]){if(i+d>t.length)continue;let c=t.slice(i,i+d).join(""),m=xt(c);if(!m)continue;let g=s(m,i+d-1);if(g)return g}}return}function ae(t){let e=xt(fe(t));if(e)return e;for(let n of t.split(/\.|\[|\]/)){if(!n)continue;let s=xt(fe(n))??ro(so(n));if(s)return s}return}function be(t){return ri.find(({pattern:e})=>e.test(t))?.category}function Oe(t){let e=t.split(":",1)[0]?.trim();return e?ae(e):void 0}function Rt(t){let e=t.matchAll(/\{\{\{?\s*([^{}]+?)\s*\}?\}\}/g);for(let n of e){let s=n[1]?.split("|",1)[0]?.trim();if(!s)continue;let i=s.replace(/^html\./i,""),r=Oe(i);if(r)return r}return}function Ct(t){try{return decodeURIComponent(t)}catch{return t}}var oo=new Set(["auth","code","key"]);function ao(t){let e=t.trim();return be(e)===ge||/^[A-Za-z0-9._~+/=-]{24,}$/.test(e)}function yi(t,e){if(ae(t)===ge)return!0;let n=fe(t);if(oo.has(n))return e!==void 0&&ao(e);if(["sig","signature"].includes(n))return!0;return["accessid","accesskeyid","credential","securitytoken","signature"].some((s)=>n.endsWith(s))}function At(t,e=0){let n;try{n=new URL(t)}catch{return}if(n.protocol!=="http:"&&n.protocol!=="https:")return;if(n.username||n.password)return ge;let s=[n.searchParams,new URLSearchParams(n.hash.replace(/^#/,""))];for(let r of s)for(let[o,d]of r){if(yi(o,d))return ge;let c=ae(o);if(c)return c;let m=be(d);if(m)return m;if(e<2){let g=At(d,e+1);if(g)return g}}let i=n.pathname.split("/").filter(Boolean);for(let r=0;r<i.length-1;r++)if(yi(Ct(i[r]??""),Ct(i[r+1]??"")))return ge;return be(Ct(n.pathname))}var fi=/https?:\/\/[^\s<>"'`)\]]+/g;function bi(t){return t.replace(/[.,;:!?]+$/,"").replace(/&amp;/g,"&")}function wi(t){for(let e of t.match(fi)??[]){let n=At(bi(e));if(n)return n}return}function _i(t){return t.replace(fi,(e)=>{let n=e.match(/[.,;:!?]+$/)?.[0]??"";return At(bi(e))?`${De}${n}`:e})}function Dt(t,e,n){let s=(o,d)=>{if(typeof d!=="string")return;let c=Oe(d);return c?{category:c,path:`${e}.${o}`}:void 0},i=(o,d)=>{if(typeof d!=="string")return;let c=ae(d);return c?{category:c,path:`${e}.${o}`}:void 0};if(t.field==="attribute"||t.type==="field_changed"){let o=s("value",t.value);if(o)return o}if(t.type==="repeat"){let o=s("source",t.source);if(o)return o}for(let o of qt){let d=s(o,t[o]);if(d)return d}if(n==="propertyFilters"){let o=s("path",t.path);if(o)return o}if(t.kind==="form-field")for(let o of["name","label","placeholder"]){let d=i(o,t[o]);if(d)return d}let r=n?ci[n]:void 0;if(r){let o=i(r,t[r]);if(o)return o}return}function Ot(t){return{...t,description:[t.description,"Use only ordinary business, contact, marketing, and commerce data. Do not provide payment-card data, health or medical data, government identifiers (such as Social Security or passport numbers), biometric or genetic data, authentication credentials or secrets, sensitive demographic data, or precise geolocation."].filter(Boolean).join(" ")}}function vi(t){let e=t.inputSchema.properties??{};return{type:"object",properties:{companyId:e.companyId,message:Ot({...e.message,description:"The generalized product feedback. Do not include subscriber or account data, content, identifiers, credentials, tool arguments, API responses, or debug details."}),category:e.category,context:Ot({...e.context,description:"Optional generalized workflow context and tool names only. Do not include user text verbatim, identifiers, content, tool arguments, API responses, errors, or debug details."})},required:["message"],additionalProperties:!1}}function Ii(){let t=(e)=>({type:"string",description:e});return{type:"object",description:"Privacy-minimized account and company-selection data returned by get_account.",properties:{success:{type:"boolean"},message:t("User-facing status message."),note:t("User-facing recovery guidance."),currentCompanyId:{type:["string","null"]},selectedCompanyId:{type:["string","null"]},companies:{type:"array",items:{type:"object",properties:{id:t("Company ID used by select_company."),name:t("Company display name."),role:t("The connected user's workspace role."),url:t("Company dashboard URL."),settingsUrl:t("Company settings URL."),subscriptionUrl:t("Company subscription-management URL.")},required:["id","name"],additionalProperties:!1}},apiKeyPermissions:{type:"object",description:"Permission capabilities without the connected user's ID or active API-key identity.",properties:{preset:t("Current permission preset."),description:t("Human-readable permission summary."),fullAccess:{type:"boolean"},selectedScopeCount:{type:"number"},currentScopeCount:{type:"number"},scopes:{type:["array","null"],items:{type:"string"}},canDiscoverMarketingWork:{type:"boolean"},missingMarketingReadScopes:{type:"array",items:{type:"string"}},canSendLive:{type:"boolean"},missingLiveDeliveryScopes:{type:"array",items:{type:"string"}},liveDeliveryBlockedByRole:{type:"boolean"},roleRestrictedScopes:{type:"array",items:{type:"string"}},manageUrl:{type:["string","null"]}},additionalProperties:!1}},additionalProperties:!1}}function ki(t){return Ot(t)}function Si(t,e){return Pt.has(e)||Et[t]?.has(e)===!0}function Ut(t,e){if(typeof t==="string"){let i=wi(t);if(i)return{category:i,path:e.path};let r=Rt(t);if(r)return{category:r,path:e.path};if(e.key&&Ke.has(e.key)){let o=Oe(t);if(o)return{category:o,path:e.path}}if(e.textScanned){let o=be(t);if(o)return{category:o,path:e.path}}return}if(Array.isArray(t)){for(let i=0;i<t.length;i++){let r=Ut(t[i],{...e,path:`${e.path}[${i}]`});if(r)return r}return}if(t===null||typeof t!=="object")return;let n=t,s=Dt(n,e.path,e.key);if(s)return s;for(let[i,r]of Object.entries(n)){let o=`${e.path}.${i}`,d=ae(i);if(d)return{category:d,path:o};let c=Ut(r,{toolName:e.toolName,path:o,key:i,textScanned:e.textScanned||Si(e.toolName,i)});if(c)return c}return}function co(t){return Error(`Restricted personal data was blocked in ${t.path} (${t.category}). Remove it and retry with ordinary business, contact, marketing, or commerce data only.`)}function lo(t,e){return Error(`Feedback on this MCP surface must not include subscriber or account identifiers, but ${t} contains ${e}. Remove it and describe the issue in general terms.`)}function Ti(t){if(Tt.has(t.name))return null;let e=t.name==="submit_feedback"?vi(t):{...t.inputSchema,properties:{...t.inputSchema.properties}};if(t.name!=="submit_feedback"){let s=e.properties??{};for(let[i,r]of Object.entries(s)){if(!pi.has(i)&&Et[t.name]?.has(i)!==!0)continue;if(r===null||typeof r!=="object")continue;let o=ki(r);s[i]=t.name==="cancel_sequence_enrollments"&&i==="fieldValues"?{...o,description:`${o.description??""} On this MCP surface, fieldPath is required whenever fieldValues is provided.`}:o}e={...e,properties:s}}if(t.name==="render_email"){let s={...e.properties};delete s.subscriberId,e={...e,properties:s}}let n={get_sequence_inbound_webhook:"Read the non-secret mapping, sample payload, setup status, and dashboard URL for a sequence inbound webhook. The credential-bearing endpoint URL is omitted from this OpenAI surface.",configure_sequence_inbound_webhook:"Create or update the mapping and sample attached to a sequence inbound_webhook trigger. The response omits the endpoint secret and credential-bearing URL; a human can copy it from the returned sequence dashboard URL.",render_email:"Render an email with a sample contact or caller-supplied, policy-checked subscriber and variables. Rendering against a stored subscriber ID is unavailable on this OpenAI surface because stored custom attributes cannot be inspected before personalization.",submit_feedback:"Send generalized product feedback to the Sequenzy team only when the user explicitly asks. Tell the user where it goes before calling. Include no subscriber or account data, content, identifiers, credentials, raw tool calls, API responses, errors, or debug payloads."};return{...t,...n[t.name]?{description:n[t.name]}:{},inputSchema:e,...t.name==="get_account"?{outputSchema:Ii()}:{}}}function qi(t,e){if(t==="render_email"&&e.subscriberId!==void 0)throw Error("`subscriberId` is unavailable on this MCP surface. Use a policy-compliant inline `subscriber`, or omit it to render with sample data.");if(t==="cancel_sequence_enrollments"&&e.fieldValues!==void 0&&(typeof e.fieldPath!=="string"||!e.fieldPath.trim()))throw Error("`fieldPath` is required with `fieldValues` on this MCP surface so restricted personal-data selectors can be checked before cancellation.");let n=Ut(e,{toolName:t,path:t,textScanned:!1});if(n)throw co(n);if(t==="submit_feedback")for(let s of["message","context"]){let i=e[s];if(typeof i!=="string")continue;let r=oi.find(({pattern:o})=>o.test(i));if(r)throw lo(`${t}.${s}`,r.label)}}var Ve=Symbol("omit-sanitized-value");function po(t){try{return new URL(t).pathname.startsWith(hi)}catch{return!1}}function jt(t,e){if(typeof t==="string"){if(Rt(t))return De;if(e.textScanned&&be(t))return De;return e.key==="previewUrl"&&mi.has(e.toolName)&&po(t)?t:_i(t)}if(Array.isArray(t))return t.flatMap((i,r)=>{let o=jt(i,{...e,path:`${e.path}[${r}]`});return o===Ve?[]:[o]});if(t===null||typeof t!=="object")return t;let n=t;if(Dt(n,e.path,e.key))return Ve;let s={};for(let[i,r]of Object.entries(n)){let o=fe(i);if(gi(i))continue;if(ui.has(e.toolName)&&e.path==="webhook"&&(o==="url"||o==="webhookurl"))continue;let d=o==="apikey"&&r!==null&&typeof r==="object";if(ae(i)&&!d)continue;if(Ke.has(i)&&Array.isArray(r)){s[i]=r.filter((g)=>typeof g!=="string"||Oe(g)===void 0);continue}let c=e.path?`${e.path}.${i}`:i,m=jt(r,{toolName:e.toolName,path:c,key:i,textScanned:e.textScanned||Si(e.toolName,i)});if(m!==Ve)s[i]=m}return s}function uo(t){if(!Array.isArray(t))return[];let e=["id","name","role","url","settingsUrl","subscriptionUrl"];return t.flatMap((n)=>{if(n===null||typeof n!=="object"||Array.isArray(n))return[];let s=n;if(typeof s.id!=="string"||typeof s.name!=="string")return[];let i={};for(let r of e)if(typeof s[r]==="string")i[r]=s[r];return[i]})}function mo(t){if(t===null||typeof t!=="object"||Array.isArray(t))return;let e=t,n=["preset","description","fullAccess","selectedScopeCount","currentScopeCount","scopes","canDiscoverMarketingWork","missingMarketingReadScopes","canSendLive","missingLiveDeliveryScopes","liveDeliveryBlockedByRole","roleRestrictedScopes","manageUrl"],s={};for(let i of n)if(e[i]!==void 0)s[i]=e[i];return s}function ho(t){if(t===null||typeof t!=="object"||Array.isArray(t))return t;let e=t,n={success:e.success===!0,companies:uo(e.companies),currentCompanyId:typeof e.currentCompanyId==="string"?e.currentCompanyId:null,selectedCompanyId:typeof e.selectedCompanyId==="string"?e.selectedCompanyId:null},s=mo(e.apiKeyPermissions);if(s)n.apiKeyPermissions=s;for(let i of["message","note"])if(typeof e[i]==="string")n[i]=e[i];return n}function Ye(t,e){let n=t==="get_account"?ho(e):e,s=jt(n,{toolName:t,path:"",textScanned:li.has(t)});return s===Ve?null:s}var Pi=[{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, including persisted structural group blocks",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 Ei(t,e={}){let n=e.profile??"standard";try{let s;switch(t){case"sequenzy://dashboard":s=await a("GET","/api/v1/metrics?period=7d");break;case"sequenzy://company":{let r=await a("GET","/api/v1/account"),o=ie()??r.currentCompanyId;if(!o)throw Error("No company available. Create or select a company first.");s=await a("GET",`/api/v1/companies/${o}`);break}case"sequenzy://campaigns/recent":s=await a("GET","/api/v1/campaigns?limit=10");break;case"sequenzy://subscribers/recent":s=await a("GET","/api/v1/subscribers?sort=createdAt&limit=20");break;case"sequenzy://subscribers/engaged":s=await a("GET","/api/v1/subscribers?sort=engagement&limit=20");break;case"sequenzy://sequences":s=await a("GET","/api/v1/sequences");break;case"sequenzy://templates":s=await a("GET","/api/v1/templates");break;case"sequenzy://segments":s=await a("GET","/api/v1/segments");break;case"sequenzy://tags":s=await a("GET","/api/v1/tags");break;case"sequenzy://health":s=await a("GET","/api/v1/health/deliverability");break;case"sequenzy://email-blocks":s=await a("GET","/api/v1/email-blocks");break;case"sequenzy://app-routes":s=Z();break;default:throw Error(`Unknown resource: ${t}`)}let i=n==="openai"?Ye(`resource:${t}`,s):s;return{contents:[{uri:t,mimeType:"application/json",text:JSON.stringify(i,null,2)}]}}catch(s){return{contents:[{uri:t,mimeType:"text/plain",text:ne(s,{includeDetails:n!=="openai"})}]}}}function I(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function l(t,e){let n=t[e];if(typeof n!=="string")return;let s=n.trim();return s.length>0?s:void 0}function Nt(t,e,n){let s=e[n];if(s===void 0||s===null)return[];if(typeof s==="string"){let r=s.trim();return r.length>0?[r]:[]}if(!Array.isArray(s))throw Error(`\`${n}\` must be an array of strings when calling \`${t}\`.`);let i=[];return s.forEach((r,o)=>{if(typeof r!=="string")throw Error(`\`${n}\` item ${o+1} must be a string when calling \`${t}\`.`);let d=r.trim();if(d.length>0&&!i.includes(d))i.push(d)}),i}function u(t,e,n){let s=l(e,n);if(s===void 0)throw Error(`\`${n}\` is required when calling \`${t}\`.`);return s}var Je=' 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. If that tool is not in the MCP tool list, enable it on the Sequenzy connector rather than inferring fields from live HTML; the same reference is also at `sequenzy://email-blocks` (MCP resource), `GET /api/v1/email-blocks` (API), and `sequenzy blocks <type>` (CLI).';var Mt=' 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.',Lt=' 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.',$t=' 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" }.',Ft=' A YouTube video block can override its still with { "type": "video", "videoUrl": "https://www.youtube.com/watch?v=...", "thumbnailUrl": "https://cdn.example.com/cover.jpg", "alt": "Watch the product tour" }. Replacing the blocks array without `thumbnailUrl` restores YouTube\'s own thumbnail; the video destination remains `videoUrl`.',zt="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.",Ze=" 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.",A=`${zt}${Ze}`,Qe=' 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.',se='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`.',Ht=" `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.",Bt="Use `styles` for per-block background, background opacity, text color, padding, border radius, border width, and border color. Recolor body copy with `styles.textColor` (or the top-level `textColor` alias), not with an inline `style` on `<p>` or `<span>`. Top-level style aliases such as `backgroundColor`, `backgroundOpacity`, `textColor`, `textAlign`, `borderColor`, `borderWidth`, and `borderRadius` are also accepted and saved under `styles`.",de=" Unsupported fields are discarded and reported in the response `warnings` array rather than rejected.",L=`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. ${Bt} Repeat blocks use { type: 'repeat', source: 'items', itemAlias: 'item', children: [...] }.${Ze}${Mt}${Ht}${de}${Lt}${$t}${Ft}${Je}`,Xe=" 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.",yo=` For action_email:${Xe}`,Q=`Replacement Sequenzy email blocks. ${Bt}${Ze}${Mt}${Ht}${de}${Lt}${$t}${Ft}${Je}`,we=`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. ${Bt} Blocks can include repeat blocks over array variables such as items.${Ze}${Mt}${Ht}${de}${Lt}${$t}${Ft}${Je}`,ce="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.",le="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.",Ue="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. Each block carries a `slot`, and slots render in order: `top` (full-width band above the hero, for announcement bars or banner images), `hero`, `form` (the card beside the hero), `body`, `footer`. A `video` block embeds a pasted YouTube URL with `url`, `title`, and an optional `aspectRatio` of 16:9, 4:3, 1:1, or 9:16 - other providers and direct video files are not supported. Button and pricing CTA URLs accept an external https URL or an in-page anchor: `#form` scrolls to the page's form block, `#section-<sectionId>` and `#block-<blockId>` scroll to any section or block, and `#top` returns to the top. Anchor CTAs stay in the same tab, so one form plus repeated CTAs is the way to build a single opt-in page. Scroll reveal is set on `theme`: `sectionAnimation` is one of none, fade, slide-up, zoom-in (default none) and `sectionAnimationSpeed` is one of slow, normal, fast (default normal). The reveal plays on the published page and is skipped for visitors who prefer reduced motion.",Ci="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.",Wt=500,Gt=500,et=["is","contains","gt","gte","lt","lte","is_not_empty"],F={type:"boolean",description:"If true, include machine-classified bot/scanner opens and clicks. Defaults to false, so metrics and activity are human-only."},je=["send","delivery","bounce","complaint","open","click","unsubscribe","delivery_delay","transport_failure"],Ne=je.join(", "),pe="Send Time Optimization is not a company or sequence setting. It is campaign-only: audit with list_campaigns or get_campaign (sendTimeOptimization, sendTimeWindowHours, default 12h window). Change a draft with update_campaign, or apply it when calling schedule_campaign. Sequences use sendingWindow (allowed local hours/days), which is a shared gate, not per-subscriber predicted send times.",Kt="Deliver each recipient at their predicted best open hour within sendTimeWindowHours of scheduledAt (default 12h). Campaign-only: there is no company or sequence STO toggle. Sequences use sendingWindow instead. spreadOverHours takes precedence and turns STO off; sendInRecipientTimezone also turns it off.",Vt="STO delivery window in hours from scheduledAt (integer 1-24, default 12). Only used when sendTimeOptimization is true. Recipients whose predicted hour falls outside the window are snapped to the nearest edge. Sequences have no equivalent.",xi="Each item also carries delivery pacing so an account-wide STO audit does not need one get_campaign call each: sendTimeOptimization, sendTimeWindowHours, spreadOverHours, sendInRecipientTimezone, and scheduledTimezone. STO is campaign-only; sequences use sendingWindow.",Yt="Delivery pacing: sendTimeOptimization is per-campaign Send Time Optimization (not a company or sequence setting). sendTimeWindowHours is that window in hours (default 12, max 24). spreadOverHours is a linear spread that turns STO off. sendInRecipientTimezone is a third mutually exclusive mode. Sequences use sendingWindow, which is an allowed-hours gate, not per-subscriber optimization.",tt={type:"object",description:"Optional send window for every email step in the sequence. This is not Send Time Optimization: it is a shared allowed-hours gate, not per-subscriber predicted send times. STO is campaign-only (list_campaigns, get_campaign, update_campaign, schedule_campaign). 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},go={type:"object",description:"Offset relative to a wait-until date.",properties:{days:{type:"number"},hours:{type:"number"},minutes:{type:"number"}},additionalProperties:!1},_e={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:go,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},ve={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},Ie={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},Jt={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",description:"Outer canvas behind the email."},content:{type:"string",description:"Inner content card the blocks sit on. Omit to preserve its current value; when no content color is stored, the card follows background."},surface:{type:"string",description:"Nested cards and tinted tiles."},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}};var fo={type:["object","null"],description:"Visual theme override for this step's linked email only; the company-wide default is left untouched, as is every other email. Partial update: the patch merges into this email's current theme, so `{ colors: { background: '#f3f4f6' } }` repaints the outer canvas and keeps its fonts, spacing, and other colors; use colors.content for the inner card and colors.surface for nested cards. A step with no override merges into the company theme rather than the platform preset. Pass null to drop the override so the step follows the company theme again. Numeric values are clamped to supported ranges. Use update_company to change the account-wide default instead.",properties:Jt,additionalProperties:!1},nt=fo,Zt={type:"string",enum:["branded","minimal"],description:"Per-email Style > Format for native Sequenzy blocks, including emails with supported custom HTML blocks. Use minimal for a direct text-forward note without the company logo and with the simple footer, or branded for branded chrome. This does not change the company-wide default and is not `style`, which is a prompt-generation hint valid only with `prompt`. 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."},Qt={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, emailTheme (per-email colors/typography/layout override - patch { colors: { background: '#ffffff' } } to repaint one step without touching the company default, or null to inherit it again), 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.${yo}`,properties:{emailTheme:nt,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},it={type:"object",properties:{nodeId:{type:"string",description:"Existing node ID from get_sequence.sequence.nodes[].id."},changes:Qt,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},ke=["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Se=["email.sent","email.delivered","email.delivery_delayed","email.bounced","email.failed","email.complained","email.opened","email.clicked","email.replied","email.unsubscribed","campaign.sent","sms.sent","sms.delivered","sms.failed","sms.opted_out","subscriber.invalid","subscriber.created","subscriber.updated","subscriber.unsubscribed","subscriber.list_subscribed","subscriber.list_unsubscribed","subscriber_import.completed","sequence.finished","sequence.failed","poll.answered"];var bo=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","get_attio_mapping","list_web_tracking_keys","get_web_tracking_key","list_integration_capabilities","list_integration_activity","get_event_schema","get_email_block_schema","list_sender_profiles","get_notification_preferences","get_tracking_settings","get_email_design_system","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","list_campaign_goals","render_email","list_email_sends","get_email_send","list_forms","get_form_embed","list_popups","get_popup","get_popup_embed","get_recipient_suppression","list_recipient_suppressions","list_landing_pages","get_landing_page","get_landing_page_stats","render_landing_page","list_sequences","get_sequence","simulate_sequence","list_sequence_enrollments","get_sequence_enrollment","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","get_sms_usage"]),wo=new Set(["select_company","create_company","update_company","update_notification_preferences","update_sender_profile","delete_sender_profile","update_tracking_settings","update_email_design_system","update_sms_number_label","release_sms_number","resume_sending","update_sync_rules","update_shopify_automation_settings","connect_integration","set_integration_sync_enabled","set_integration_list_targeting","sync_integration","activate_integration_pixel","update_attio_settings","create_web_tracking_key","update_web_tracking_key","delete_web_tracking_key","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","import_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","select_ab_test_winner","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","remove_landing_page_domain","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_campaign_goal","update_campaign_goal","delete_campaign_goal","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"]),_o=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","remove_landing_page_domain","add_sending_domain","add_website","verify_sending_domain","connect_integration","sync_integration","get_integration_pixel","activate_integration_pixel","get_attio_mapping","update_attio_settings","enable_sequence","unarchive_sequence","resume_sequence_enrollments","move_sequence_enrollments","send_email","select_ab_test_winner","invite_team_member","reply_to_conversation","create_webhook","update_webhook","test_webhook","replay_webhook_delivery","remove_recipient_suppression"]),vo=new Set(["revoke_api_key","delete_api_key","delete_sender_profile","remove_subscriber","delete_subscriber_note","delete_product","delete_web_tracking_key","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","remove_landing_page_domain","unpublish_landing_page","delete_popup","set_integration_sync_enabled","set_integration_list_targeting","disable_sequence","archive_sequence","delete_campaign_goal","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","release_sms_number"]);function Io(t){let e=bo.has(t),n=wo.has(t);if(e===n)throw Error(`MCP tool "${t}" must be classified as exactly one of read-only or mutating.`);return{readOnlyHint:e,destructiveHint:e?!1:vo.has(t),openWorldHint:_o.has(t)}}var ko={ab:"A/B",ai:"AI",api:"API",html:"HTML",id:"ID",mcp:"MCP",nps:"NPS",sms:"SMS",url:"URL",urls:"URLs",utm:"UTM"};function So(t){return t.split("_").filter(Boolean).map((e)=>ko[e]??e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Ri(t){return{...t,annotations:{...t.annotations,title:t.annotations?.title??So(t.name),...Io(t.name)}}}var Xt={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"]},To=Object.entries(Xt).map(([t,e])=>`${t}: ${e.join(", ")}`).join("; "),en={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>\`, an email-type scope via \`marketing:<timeRange>\` (marketing-policy campaign, automation, and Send API traffic) or \`transactional:<timeRange>\` (transactional-policy sends), or \`count:timeRange\` (e.g. \`10:30d\`, \`10:all\`) with at_least/less_than_count to segment by number of opens/clicks. ${se}`},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: ${To}.`},value:{type:"string",description:`Filter value. For custom attribute empty checks, use \`attributeName:\` such as \`last_logged_in:\`. Array-of-object attributes use wildcard paths such as \`history_events[].eventvenue_id:2103\`; AND-ing two such positive filters on the same \`foo[]\` prefix matches one shared element (negative filters like is_not/not_contains/is_empty stay independent). 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), \`marketing:7d\` / \`transactional:30d\` to scope by email type (marketing includes marketing-policy campaign, automation, and Send API traffic; policy scopes require a send-time policy snapshot, so ambiguous older events remain unscoped; email-type values work with is/is_not and the emailBounced subtype operators, e.g. emailSent is_not \`marketing:7d\` = no captured marketing email in the last 7 days), 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). ${se}`}},required:["field","operator","value"],additionalProperties:!1},tn={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 st(t){if(!Array.isArray(t))return t;return t.map((e)=>{if(typeof e!=="object"||e===null)return e;let n=e;if(typeof n.id==="string"&&n.id.trim()!=="")return n;return{...n,id:crypto.randomUUID()}})}function rt(t){if(typeof t!=="object"||t===null)return t;let e=t;if(e.kind==="filter"||"field"in e||"operator"in e||"value"in e){let n=st([e]);return Array.isArray(n)?n[0]:e}if(e.kind!=="group")return t;return{...e,id:typeof e.id==="string"&&e.id.trim()!==""?e.id:crypto.randomUUID(),children:Array.isArray(e.children)?e.children.map(rt):[]}}function qo(t){let e=t.indexOf(":");return e!==-1&&t.substring(0,e).trim().length>0}function Po(t){let e=t.indexOf(":");return e!==-1&&t.substring(e+1).trim().length>0}function Te(t){if(t==="all")return!0;let e=t.match(/^(\d+)d$/);if(!e?.[1])return!1;let n=Number.parseInt(e[1],10);return Number.isInteger(n)&&n>0}var Eo=new Set(["emailSent","emailDelivered","emailOpened","emailClicked","emailBounced","emailComplained"]);function Co(t,e){let n=e.trim(),s=t==="at_least"||t==="less_than_count";if(n.startsWith("campaign:")){if(s)return"Campaign-specific engagement values cannot be combined with count operators.";return n.slice(9).trim()?null:'Campaign-specific engagement filters must use "campaign:<campaignId>".'}if(n.startsWith("marketing:")||n.startsWith("transactional:")){if(s)return"Email-type engagement values cannot be combined with count operators.";let i=n.indexOf(":");return Te(n.slice(i+1).trim())?null:'Email-type engagement filters must use "marketing:<timeRange>" or "transactional:<timeRange>", like "marketing:7d".'}if(s){if(Te(n))return null;let i=n.indexOf(":"),r=n.slice(0,i).trim(),o=Number.parseInt(r,10),d=n.slice(i+1).trim();return i>0&&/^\d+$/.test(r)&&Number.isInteger(o)&&o>0&&Te(d)?null:'Engagement count filters must use "count:timeRange", like "10:30d" or "10:all".'}return Te(n)?null:'Engagement filters must use a time range like "30d" or "all", "campaign:<campaignId>", or an email-type scope like "marketing:7d" or "transactional:7d".'}function xo(t,e){let n=e.split(":");if(t==="at_least"||t==="less_than_count"){if(n.length<3)return'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".';let r=n.slice(0,-2).join(":").trim(),o=n.at(-2),d=n.at(-1),c=o===void 0?Number.NaN:Number.parseInt(o,10);return r&&Number.isInteger(c)&&c>0&&d!==void 0&&Te(d)?null:'Event count filters must use "eventName:count:timeRange", like "saas.purchase:2:30d".'}if(n.length<2)return'Event filters must use "eventName:timeRange", like "saas.purchase:30d".';let s=n.slice(0,-1).join(":").trim(),i=n.at(-1);return s&&i!==void 0&&Te(i)?null:'Event filters must use "eventName:timeRange", like "saas.purchase:30d".'}function Ro(t){let e=t.indexOf(":");if(e===-1)return{productId:t,subfilter:null,rawValue:null};let n=t.substring(0,e),s=t.substring(e+1),i=s.indexOf(":");if(i===-1)return{productId:n,subfilter:s,rawValue:null};return{productId:n,subfilter:s.substring(0,i),rawValue:s.substring(i+1)}}function Ao(t){return t.trim().toLowerCase().replace(/[-\s]+/g,"_")}function Do(t){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(t)}function Oo(t,e){if(e==="cancels_at"||e==="cancel_at"||e==="cancellation_at")return!0;if(t==="stripeCurrentProduct")return["end_at","ends_at","period_end","period_ends_at","current_period_end"].includes(e);return["start_at","started_at","trial_start","trial_started_at","end_at","ends_at","trial_end","trial_ends_at"].includes(e)}function Uo(t){return["is","is_not","gte","lte","gt","lt"].includes(t)}function jo(t,e,n){if(t==="stripeProduct"){if(e!=="at_least"&&e!=="less_than_count")return null;let d=n.indexOf(":");if(d===-1)return null;let c=n.substring(0,d).trim(),m=Number.parseInt(n.substring(d+1).trim(),10);return c&&Number.isInteger(m)&&m>=1?null:'Stripe Product threshold filters must use "productId:count" with a count of at least 1.'}if(t!=="stripeCurrentProduct"&&t!=="stripeTrialProduct")return null;let{productId:s,subfilter:i,rawValue:r}=Ro(n);if(!s.trim())return"Stripe product filters must include a product ID.";if(!i)return e==="is"||e==="is_not"?null:'Stripe current/trial date filters must use "productId:dateField:value".';let o=Ao(i);if(Do(o))return e==="is"||e==="is_not"?null:"Stripe cancellation flag filters only support is and is_not operators.";if(!Oo(t,o))return`Unsupported Stripe product subfilter "${i}".`;if(!Uo(e))return"Stripe date filters only support is, is_not, gte, lte, gt, and lt operators.";return r?.trim()?null:'Stripe date filters must include a value like "productId:end_at:2026-05-26".'}var Ai=new Set(["shopify","woocommerce","api"]);function No(t,e){let n=e.trim(),s=n.indexOf(":");if(s!==-1&&Ai.has(n.substring(0,s).trim()))n=n.substring(s+1).trim();if(!n)return'Purchased Product filters must include a product ID, like "shopify:42".';if(t!=="at_least"&&t!=="less_than_count")return null;let i=n.lastIndexOf(":");if(i===-1)return null;let r=n.substring(0,i).trim(),o=Number.parseInt(n.substring(i+1).trim(),10);return r&&Number.isInteger(o)&&o>=1?null:'Purchased Product threshold filters must use "provider:productId:count" with a count of at least 1.'}function Mo(t,e){let n=e.trim(),s=n.indexOf(":");if(s!==-1&&Ai.has(n.substring(0,s).trim()))n=n.substring(s+1).trim();if(!n)return'Purchased Collection filters must include a collection, like "shopify:summer-sale".';if(t!=="at_least"&&t!=="less_than_count")return null;let i=n.lastIndexOf(":");if(i===-1)return null;let r=n.substring(0,i).trim(),o=Number.parseInt(n.substring(i+1).trim(),10);return r&&Number.isInteger(o)&&o>=1?null:'Purchased Collection threshold filters must use "provider:collection:count" with a count of at least 1.'}function Lo(t){let e;try{e=JSON.parse(t)}catch{return`Poll response filters must use valid JSON. ${se}`}if(!I(e)||e.v!==1||typeof e.campaignId!=="string"||!e.campaignId.trim()||typeof e.blockId!=="string"||!e.blockId.trim()||!I(e.match))return`Poll response filter context is invalid. ${se}`;let n=e.match;if(n.kind==="answer"&&typeof n.value==="string"&&n.value.length>0)return null;if(n.kind==="npsBucket"&&(n.bucket==="promoters"||n.bucket==="passives"||n.bucket==="detractors"))return null;return`Poll response filter match is invalid. ${se}`}function ot(t){if(typeof t!=="object"||t===null)return"Segment filters must be objects.";let e=t,{field:n,operator:s,value:i}=e;if(typeof n!=="string"||!(n in Xt))return`Unsupported segment filter field "${String(n)}".`;if(typeof s!=="string")return`Segment filter "${n}" must include an operator.`;let r=Xt[n];if(!r.includes(s))return`Operator "${s}" is not supported for ${n} filters. Use one of: ${r.join(", ")}.`;if(s!=="is_empty"&&s!=="is_not_empty"&&(typeof i!=="string"||i.trim().length===0))return`Segment filter "${n}" must include a value.`;if(n==="attribute"){if(typeof i!=="string")return'Attribute filters must include a value: "attributeName:value", or "attributeName:" for empty checks.';if(!qo(i))return'Attribute filters must use "attributeName:value" or "attributeName:" for empty checks.';if(s!=="is_empty"&&s!=="is_not_empty"&&!Po(i))return'Attribute filters must include a value after "attributeName:".'}if(n==="event"&&typeof i==="string"){let o=xo(s,i);if(o)return o}if(Eo.has(n)&&typeof i==="string"){let o=Co(s,i);if(o)return o}if(n==="pollResponse"&&typeof i==="string"){let o=Lo(i);if(o)return o}if((n==="stripeProduct"||n==="stripeCurrentProduct"||n==="stripeTrialProduct")&&typeof i==="string"){let o=jo(n,s,i);if(o)return o}if(n==="commerceProduct"&&typeof i==="string"){let o=No(s,i);if(o)return o}if(n==="commerceCollection"&&typeof i==="string"){let o=Mo(s,i);if(o)return o}if(n==="tag"&&(s==="contains"||s==="not_contains")){if(!(typeof i==="string"&&i.split(",").map((d)=>d.trim()).some(Boolean)))return"Tag filters must include at least one tag name."}return null}function at(t){if(typeof t!=="object"||t===null)return[];let e=t;if(e.kind==="filter"||"field"in e||"operator"in e||"value"in e){let n=ot(e);return n?[n]:[]}if(Array.isArray(e.children))return e.children.flatMap(at);return[]}function z(t,e,n){if(e.html!==void 0&&e.blocks!==void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${t}\`, not both.`);if(e.blocks!==void 0&&!Array.isArray(e.blocks))throw Error(`\`blocks\` must be an array when calling \`${t}\`.`);if(n?.requireContent&&e.html===void 0&&e.blocks===void 0)throw Error(`Provide either \`html\` or \`blocks\` when calling \`${t}\`.`)}function X(t,e){if(e.labels===void 0)return;if(!Array.isArray(e.labels))throw Error(`\`labels\` must be an array when calling \`${t}\`.`);if(e.labels.some((n)=>typeof n!=="string"||n.trim().length===0))throw Error(`\`labels\` must contain only non-empty strings when calling \`${t}\`.`)}function ln(t,e,n={}){if($o(t,e,n),e.listScope===void 0)return;if(e.listId!==void 0||e.listIds!==void 0)throw Error(`Provide either listId/listIds or listScope when calling ${t}, not both.`);if((e.trigger??n.defaultTrigger)!=="contact_added")throw Error(`listScope only applies to a contact_added trigger when calling ${t}.`)}function $o(t,e,n={}){let s=e.trigger??n.defaultTrigger;for(let[i,r]of[["listIds","contact_added"],["tagNames","tag_added"]]){let o=e[i];if(o===void 0)continue;if(!Array.isArray(o)||o.length===0)throw Error(`\`${i}\` must be a non-empty array of strings when calling \`${t}\`.`);if(o.some((d)=>typeof d!=="string"||d.trim()===""))throw Error(`\`${i}\` must contain only non-empty strings when calling \`${t}\`.`);if(s!==void 0&&s!==r)throw Error(`\`${i}\` only applies to a ${r} trigger when calling \`${t}\`.`)}}function Ui(t){let e=t.filters!==void 0,n=t.root!==void 0;if(e&&n)throw Error("Provide either `filters` or `root` when calling `create_segment`, not both.");if(!e&&!n)throw Error("Provide either `filters` or `root` when calling `create_segment`.");if(e){if(!Array.isArray(t.filters))throw Error("`filters` must be an array when calling `create_segment`.");if(t.filters.length===0)throw Error("`filters` must include at least one filter when calling `create_segment`.")}if(n&&(typeof t.root!=="object"||t.root===null))throw Error("`root` must be an object when calling `create_segment`.");let s=e?t.filters.flatMap((i)=>{let r=ot(i);return r?[r]:[]}):at(t.root);if(s.length>0)throw Error(s[0]??"Invalid segment filter in `create_segment`.")}function ji(t){let e=t.filters!==void 0,n=t.root!==void 0;if(e&&n)throw Error("Provide either `filters` or `root` when calling `update_segment`, not both.");if(t.name===void 0&&t.filterJoinOperator===void 0&&!e&&!n)throw Error("Provide at least one of `name`, `filters`, `root`, or `filterJoinOperator` when calling `update_segment`.");if(e){if(!Array.isArray(t.filters))throw Error("`filters` must be an array when calling `update_segment`.");if(t.filters.length===0)throw Error("`filters` must include at least one filter when calling `update_segment`.")}if(n&&(typeof t.root!=="object"||t.root===null))throw Error("`root` must be an object when calling `update_segment`.");let s=e?t.filters.flatMap((i)=>{let r=ot(i);return r?[r]:[]}):n?at(t.root):[];if(s.length>0)throw Error(s[0]??"Invalid segment filter in `update_segment`.")}var nn=["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","defaultSubscriberListIds"];function sn(t,e,n){if(e[n]!==void 0&&!I(e[n]))throw Error(`\`${n}\` must be an object when calling \`${t}\`.`)}function Di(t,e,n){if(e[n]!==void 0&&!Array.isArray(e[n]))throw Error(`\`${n}\` must be an array when calling \`${t}\`.`)}function Ni(t){let e=new Set(["companyId",...nn]),n=Object.keys(t).filter((i)=>!e.has(i));if(n.length>0)throw Error(`\`update_company\` accepts only editable company settings. Unsupported field${n.length===1?"":"s"}: ${n.map((i)=>`\`${i}\``).join(", ")}.`);let s={};for(let i of nn)if(t[i]!==void 0)s[i]=t[i];if(Object.keys(s).length===0)throw Error(`Provide at least one of ${nn.map((i)=>`\`${i}\``).join(", ")} when calling \`update_company\`.`);for(let i of["name","description","logoUrl","founderName","primaryColor","toneVoice","companyContext","emailDesignPrompt","emailLengthPreference","privacyPolicyUrl","termsUrl","address","language","fontFamily","emailDirection","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","replyTrackingDomainMode"])if(t[i]!==void 0&&typeof t[i]!=="string")throw Error(`\`${i}\` must be a string when calling \`update_company\`.`);if(sn("update_company",t,"brandColors"),sn("update_company",t,"socialLinks"),sn("update_company",t,"pricing"),t.emailTheme!==void 0&&t.emailTheme!==null&&!I(t.emailTheme))throw Error("`emailTheme` must be an object or null when calling `update_company`.");if(Di("update_company",t,"valueProps"),Di("update_company",t,"testimonials"),t.defaultSubscriberListIds!==void 0&&t.defaultSubscriberListIds!==null){if(!Array.isArray(t.defaultSubscriberListIds))throw Error("`defaultSubscriberListIds` must be an array of list IDs, null for every list, or [] for no list when calling `update_company`.");if(t.defaultSubscriberListIds.some((i)=>typeof i!=="string"||i.trim()===""))throw Error("`defaultSubscriberListIds` must contain non-empty list IDs when calling `update_company`.")}for(let i of["replyTrackingEnabled","forwardReplies"])if(t[i]!==void 0&&typeof t[i]!=="boolean")throw Error(`\`${i}\` must be a boolean when calling \`update_company\`.`);if(t.replyTrackingDomainMode!==void 0&&t.replyTrackingDomainMode!=="sequenzy"&&t.replyTrackingDomainMode!=="custom")throw Error("`replyTrackingDomainMode` must be `sequenzy` or `custom` when calling `update_company`.");if(typeof t.primaryColor==="string"&&!/^#[0-9a-f]{6}$/i.test(t.primaryColor.trim()))throw Error("`primaryColor` must be a 6-digit hex color such as #f97316 when calling `update_company`.");for(let i of["fromEmail","replyTo"]){let r=t[i];if(typeof r==="string"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r.trim()))throw Error(`\`${i}\` must be a valid email address when calling \`update_company\`.`)}return s}var rn=["openTrackingEnabled","clickTrackingEnabled","transactionalOpenTrackingEnabled","transactionalClickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","defaultAttributionWindowHours","doubleOptInEnabled","doubleOptInRedirectUrl","autoUtmEnabled","autoUtmSettings"],on=["source","medium","campaign","content","term"];function Mi(t){let e=new Set(["companyId",...rn]),n=Object.keys(t).filter((i)=>!e.has(i));if(n.length>0)throw Error(`\`update_tracking_settings\` accepts only tracking settings. Unsupported field${n.length===1?"":"s"}: ${n.map((i)=>`\`${i}\``).join(", ")}. Reply tracking is set with \`update_company\`.`);let s={};for(let i of rn)if(t[i]!==void 0)s[i]=t[i];if(Object.keys(s).length===0)throw Error(`Provide at least one of ${rn.map((i)=>`\`${i}\``).join(", ")} when calling \`update_tracking_settings\`.`);for(let i of["openTrackingEnabled","clickTrackingEnabled","transactionalOpenTrackingEnabled","transactionalClickTrackingEnabled","strictBotFilteringEnabled","unsubscribeTrackingEnabled","doubleOptInEnabled","autoUtmEnabled"])if(t[i]!==void 0&&typeof t[i]!=="boolean")throw Error(`\`${i}\` must be a boolean when calling \`update_tracking_settings\`.`);if(t.defaultAttributionWindowHours!==void 0&&(typeof t.defaultAttributionWindowHours!=="number"||!Number.isInteger(t.defaultAttributionWindowHours)||t.defaultAttributionWindowHours<1||t.defaultAttributionWindowHours>720))throw Error("`defaultAttributionWindowHours` must be a whole number of hours between 1 and 720 when calling `update_tracking_settings`.");if(t.doubleOptInRedirectUrl!==void 0&&t.doubleOptInRedirectUrl!==null&&typeof t.doubleOptInRedirectUrl!=="string")throw Error("`doubleOptInRedirectUrl` must be a URL string or null when calling `update_tracking_settings`.");if(t.autoUtmSettings!==void 0&&t.autoUtmSettings!==null&&!I(t.autoUtmSettings))throw Error("`autoUtmSettings` must be an object or null when calling `update_tracking_settings`.");if(I(t.autoUtmSettings)){let i=t.autoUtmSettings,r=Object.keys(i).filter((o)=>!on.includes(o));if(r.length>0)throw Error(`\`autoUtmSettings\` accepts only ${on.map((o)=>`\`${o}\``).join(", ")}. Unsupported: ${r.map((o)=>`\`${o}\``).join(", ")}.`);for(let o of on){let d=i[o];if(d!==void 0&&d!==null&&typeof d!=="string")throw Error(`\`autoUtmSettings.${o}\` must be a string or null when calling \`update_tracking_settings\`.`)}}return s}var dt={profileKey:"senderProfileId",emailKey:"fromEmail",nameKey:"fromName",addressLabel:"From"},dn={profileKey:"replyProfileId",emailKey:"replyTo",nameKey:"replyToName",addressLabel:"Reply-To"};function Fo(t){let{profileKey:e,emailKey:n,nameKey:s}=t.pair;if(t.nameHasStepOverride)return`To keep \`${e}\` and still change the display name, send \`${e}\` on its own and set \`${s}\` on each email step, where it applies as a per-step display-name override. To change the address instead, omit \`${e}\` and send \`${n}\` (optionally with \`${s}\`).`;return`To use a different address or display name, omit \`${e}\` and send \`${n}\` (optionally with \`${s}\`) instead.`}function cn(t){let{profileKey:e,emailKey:n,nameKey:s,addressLabel:i}=t.pair,r=t.args[e]!==void 0,o=t.args[n]!==void 0,d=t.args[s]!==void 0,c=t.location?`for ${t.location} when calling \`${t.toolName}\``:`when calling \`${t.toolName}\``,m=`\`${e}\` already sets both the ${i} address and the display name, so send it without \`${n}\`${t.nameIsOverride?"":` and \`${s}\``}.`,g=Fo({pair:t.pair,nameHasStepOverride:t.nameHasStepOverride}),w=`For a per-email display name, set \`${s}\` on the email steps instead.`;if(r&&o){let[f,_]=t.profileFirst?[e,n]:[n,e],T=d&&t.nameHasStepOverride?` ${w}`:"";throw Error(`Provide either \`${f}\` or \`${_}\` ${c}, not both. ${m}${T}`)}if(r&&d&&!t.nameIsOverride)throw Error(`\`${s}\` cannot be combined with \`${e}\` ${c}. ${m} ${g}`);if(d&&!o&&!t.nameIsOverride)throw Error(`\`${s}\` requires \`${n}\` ${c}. Send \`${s}\` with the \`${n}\` it names, or send \`${e}\` on its own to use an existing profile's address and name.${t.nameHasStepOverride?` ${w}`:""}`)}function re(t,e,n){let s=n?.replyFirst?[dn,dt]:[dt,dn];for(let i of s)cn({toolName:t,args:e,pair:i,nameHasStepOverride:n?.hasEmailSteps===!0&&i===dt})}var Li=["senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName"];function zo(t){return Li.some((e)=>t[e]!==void 0)}function Ho(t){if(typeof t.nodeType==="string")return t.nodeType==="action_email";return t.type===void 0||t.type==="email"}function ct(t,e,n){for(let s of Li){let i=n[s];if(i!==void 0&&typeof i!=="string")throw Error(`\`${s}\` must be a string for ${e} when calling \`${t}\`.`)}cn({toolName:t,args:n,pair:dt,location:e,profileFirst:!0,nameIsOverride:!0}),cn({toolName:t,args:n,pair:dn,location:e,profileFirst:!0})}function pn(t,e,n){if(zo(n)&&!Ho(n))throw Error(`Sender identity fields are only supported for email steps at ${e} when calling \`${t}\`.`);ct(t,e,n)}function Oi(t,e,n){if(!Array.isArray(n))return;n.forEach((s,i)=>{if(I(s))ct(t,`${e}[${i}]`,s)})}function an(t,e,n){if(!Array.isArray(n))return;n.forEach((s,i)=>{if(I(s))pn(t,`${e}[${i}]`,s)})}function Bo(t){if(Oi("update_sequence","emails",t.emails),Oi("update_sequence","steps",t.steps),I(t.insertSteps))an("update_sequence","insertSteps.steps",t.insertSteps.steps);if(!I(t.branch))return;if(Array.isArray(t.branch.branches))t.branch.branches.forEach((n,s)=>{if(I(n))an("update_sequence",`branch.branches[${s}].steps`,n.steps)});an("update_sequence","branch.elseSteps",t.branch.elseSteps)}function $i(t){X("update_sequence",t);let e=["listId","listIds","listScope","tagName","tagNames","segmentId","stopOnSegmentExit","eventName","propertyFilters","integrationSlug","integrationEventKey","customIntegration","inactiveDays","inactivityBaseline","minCount","timeWindowDays"];if(t.trigger===void 0&&e.some((s)=>t[s]!==void 0))throw Error("Provide `trigger` when replacing sequence trigger configuration with `update_sequence`.");if(ln("update_sequence",t),re("update_sequence",t,{hasEmailSteps:!0}),t.clearEnrollmentFieldPath===!0&&t.enrollmentFieldPath!==void 0)throw Error("Provide either `enrollmentFieldPath` or `clearEnrollmentFieldPath` when calling `update_sequence`, not both.");if(t.clearSendingWindow===!0&&t.sendingWindow!==void 0)throw Error("Provide either `sendingWindow` or `clearSendingWindow` when calling `update_sequence`, not both.");if(t.clearBccEmails===!0&&t.bccEmails!==void 0)throw Error("Provide either `bccEmails` or `clearBccEmails` when calling `update_sequence`, not both.");if(t.branch!==void 0&&t.insertSteps!==void 0)throw Error("Provide either `branch` or `insertSteps` when calling `update_sequence`, not both.");Bo(t);let n={...t};if(delete n.clearEnrollmentFieldPath,delete n.clearSendingWindow,delete n.clearBccEmails,t.clearEnrollmentFieldPath===!0)n.enrollmentFieldPath=null;if(t.clearSendingWindow===!0)n.sendingWindow=null;if(t.clearBccEmails===!0)n.bccEmails=null;return n}function Fi(t,e){let n=e.triggerType??"event";if(n==="event"){if(typeof e.triggerEventName!=="string"||e.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` is required when calling \`${t}\` with an event goal (the default \`triggerType\`).`);return}if(n==="tag_added"){if(typeof e.triggerTagName!=="string"||e.triggerTagName.trim().length===0)throw Error(`\`triggerTagName\` is required when calling \`${t}\` with \`triggerType: "tag_added"\`.`);return}if(typeof e.attributePath!=="string"||e.attributePath.trim().length===0)throw Error(`\`attributePath\` is required when calling \`${t}\` with \`triggerType: "attribute_change"\`.`);let s=e.attributeCondition??"changed",i=typeof e.attributeValue==="string"&&e.attributeValue.trim().length>0,r=typeof e.attributePreviousValue==="string"&&e.attributePreviousValue.trim().length>0;if((s==="changed_to"||s==="changed_from_to")&&!i)throw Error(`\`attributeValue\` is required when calling \`${t}\` with \`attributeCondition\` \`changed_to\` or \`changed_from_to\`.`);if(s==="changed_from_to"&&!r)throw Error(`\`attributePreviousValue\` is required when calling \`${t}\` with \`attributeCondition: "changed_from_to"\`.`)}function zi(t){Fi("create_sequence_goal",t)}function Hi(t){Fi("create_campaign_goal",t)}function Bi(t){Gi("update_sequence_goal",t)}function Wi(t){Gi("update_campaign_goal",t)}function Gi(t,e){if(typeof e.triggerEventName==="string"&&e.triggerEventName.trim().length===0)throw Error(`\`triggerEventName\` must be a non-empty string when provided to \`${t}\`.`);if(typeof e.attributePath==="string"&&e.attributePath.trim().length===0)throw Error(`\`attributePath\` must be a non-empty string when provided to \`${t}\`.`);if(typeof e.triggerTagName==="string"&&e.triggerTagName.trim().length===0)throw Error(`\`triggerTagName\` must be a non-empty string when provided to \`${t}\`.`)}function Qi(t,e,n){let s=u(t,e,"nodeId");if(!I(e.changes)||Object.keys(e.changes).length===0)throw Error(`\`changes\` must be a non-empty object for ${n} when calling \`${t}\`.`);let i=u(t,e,"expectedUpdatedAt");return{nodeId:s,changes:e.changes,expectedUpdatedAt:i}}function Xi(t){let e=Qi("update_sequence_node",t,"the node update");return{...t.confirmLiveChange!==void 0&&{confirmLiveChange:t.confirmLiveChange},nodeUpdates:[e]}}function es(t){if(!Array.isArray(t.updates)||t.updates.length===0)throw Error("`updates` must be a non-empty array when calling `update_sequence_nodes`.");let e=new Set,n=t.updates.map((s,i)=>{if(!I(s))throw Error(`\`updates[${i}]\` must be an object when calling \`update_sequence_nodes\`.`);let r=Qi("update_sequence_nodes",s,`updates[${i}]`),o=String(r.nodeId);if(e.has(o))throw Error(`\`updates[${i}]\` targets duplicate nodeId '${o}' when calling \`update_sequence_nodes\`.`);return e.add(o),r});return{...t.confirmLiveChange!==void 0&&{confirmLiveChange:t.confirmLiveChange},nodeUpdates:n}}function ts(t){let e=u("edit_sequence_graph",t,"action"),n=u("edit_sequence_graph",t,"graphRevision");if(!new Set(["move_node","delete_node","duplicate_node","replace_edges"]).has(e))throw Error("`action` must be `move_node`, `delete_node`, `duplicate_node`, or `replace_edges` when calling `edit_sequence_graph`.");let i=l(t,"nodeId"),r=l(t,"afterNodeId"),o=l(t,"beforeNodeId"),d=t.edges;if(e!=="replace_edges"&&!i)throw Error(`\`nodeId\` is required for ${e} when calling \`edit_sequence_graph\`.`);if(e==="replace_edges"&&i)throw Error("`nodeId` is not used with `replace_edges` when calling `edit_sequence_graph`.");let c=e==="move_node"||e==="duplicate_node";if(c&&(r?1:0)+(o?1:0)!==1)throw Error(`Provide exactly one of \`afterNodeId\` or \`beforeNodeId\` for ${e} when calling \`edit_sequence_graph\`.`);if(!c&&(r||o))throw Error(`\`afterNodeId\` and \`beforeNodeId\` are not used with ${e} when calling \`edit_sequence_graph\`.`);if((e==="replace_edges"||e==="delete_node"&&d!==void 0)&&(!Array.isArray(d)||d.length===0))throw Error(`\`edges\` must contain the complete replacement topology for ${e} when calling \`edit_sequence_graph\`.`);if((e==="move_node"||e==="duplicate_node")&&d!==void 0)throw Error(`\`edges\` is not used with ${e} when calling \`edit_sequence_graph\`.`);let m=Array.isArray(d)?d.map((g,w)=>{if(!I(g))throw Error(`\`edges\` item ${w+1} must be an object when calling \`edit_sequence_graph\`.`);let f=u("edit_sequence_graph",g,"sourceNodeId"),_=u("edit_sequence_graph",g,"targetNodeId");if(g.condition!==void 0&&g.condition!==null&&!I(g.condition))throw Error(`\`edges\` item ${w+1} \`condition\` must be an object when calling \`edit_sequence_graph\`.`);return{sourceNodeId:f,targetNodeId:_,...I(g.condition)?{condition:g.condition}:{}}}):void 0;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},graphEdit:{action:e,expectedRevision:n,...i?{nodeId:i}:{},...r?{afterNodeId:r}:{},...o?{beforeNodeId:o}:{},...m?{edges:m}:{}}}}function Wo(t,e,n){if((t==="has_tag"||t==="does_not_have_tag")&&!l(e,"tagId")&&!l(e,"tagName"))throw Error(`\`${n}\` must provide \`tagId\` or \`tagName\` for ${t} when calling \`insert_sequence_step\`.`);if(t==="in_list"&&!l(e,"listId"))throw Error(`\`${n}.listId\` is required for in_list when calling \`insert_sequence_step\`.`);if(t==="in_segment"&&!l(e,"segmentId"))throw Error(`\`${n}.segmentId\` is required for in_segment when calling \`insert_sequence_step\`.`);if(t==="event_received"&&!l(e,"eventName"))throw Error(`\`${n}.eventName\` is required for event_received when calling \`insert_sequence_step\`.`);if(t.startsWith("field_")&&(!l(e,"fieldName")||!l(e,"fieldValue")))throw Error(`\`${n}\` must provide \`fieldName\` and \`fieldValue\` for ${t} when calling \`insert_sequence_step\`.`)}var Go=["conditionType","tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"];function ns(t){let e=l(t,"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(e))throw Error("`type` is not a supported dashboard sequence step when calling `insert_sequence_step`.");if(e==="logic_wait_for_event"){let o=u("insert_sequence_step",t,"eventName"),d=t.timeoutDays,c=d===void 0?7:d;if(typeof c!=="number"||!Number.isInteger(c)||c<1||c>365)throw Error("`timeoutDays` must be a whole number from 1 to 365 when inserting `logic_wait_for_event` with `insert_sequence_step`.");let m=l(t,"timeoutAction")??"continue";if(m!=="continue"&&m!=="exit")throw Error("`timeoutAction` must be `continue` or `exit` when inserting `logic_wait_for_event` with `insert_sequence_step`.");let g={steps:[{nodeType:"logic_wait_for_event",config:{label:l(t,"label")??`Wait for ${o}`,eventName:o,timeoutDays:c,timeoutAction:m}}]},w=l(t,"afterNodeId");if(w)g.afterNodeId=w;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},insertSteps:g}}if(e==="logic_branch"){let o=u("insert_sequence_step",t,"afterNodeId");if(!Array.isArray(t.branches)||t.branches.length===0)throw Error("`branches` must contain at least one typed condition when inserting `logic_branch` with `insert_sequence_step`.");let d=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"]),c=l(t,"splitMode")??"condition";if(c!=="condition"&&c!=="random")throw Error("`splitMode` must be `condition` or `random` when inserting `logic_branch` with `insert_sequence_step`.");let m=c==="random";if(m){if(!Array.isArray(t.randomPercentages)||t.randomPercentages.length!==t.branches.length)throw Error("`randomPercentages` must contain one percentage per entry in `branches` when `splitMode` is `random`.");if(t.randomPercentages.some((C)=>typeof C!=="number"||!Number.isFinite(C)||C<0))throw Error("`randomPercentages` must contain non-negative numbers when `splitMode` is `random`.");let E=t.randomPercentages.reduce((C,D)=>C+D,0);if(Math.abs(E-100)>0.001)throw Error(`\`randomPercentages\` must sum to 100 when \`splitMode\` is \`random\`, received ${E}.`);if(Array.isArray(t.elseSteps)&&t.elseSteps.length>0||l(t,"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(t.randomPercentages!==void 0)throw Error("`randomPercentages` is only valid when `splitMode` is `random`.");let g=["id","label","conditionType","tagName","tagId","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue","targetNodeId","steps"],w=t.allowEmptyPaths===!0,f=t.branches.map((E,C)=>{if(!I(E))throw Error(`\`branches[${C}]\` must be an object when calling \`insert_sequence_step\`.`);let D=`branches[${C}]`;if(m){let U=Go.find((he)=>E[he]!==void 0);if(U)throw Error(`\`${D}.${U}\` must be omitted when \`splitMode\` is \`random\`, because the path is chosen by percentage rather than by evaluating the subscriber.`)}else{let U=u("insert_sequence_step",E,"conditionType");if(!d.has(U))throw Error(`\`branches[${C}].conditionType\` is not supported when calling \`insert_sequence_step\`.`);Wo(U,E,D)}if(E.steps!==void 0&&!Array.isArray(E.steps))throw Error(`\`branches[${C}].steps\` must be an array when calling \`insert_sequence_step\`.`);let ee=l(E,"targetNodeId"),te=Array.isArray(E.steps)&&E.steps.length>0;if(!ee&&!te&&!w)throw Error(`\`branches[${C}]\` must provide \`targetNodeId\` or non-empty \`steps\` when inserting \`logic_branch\` with \`insert_sequence_step\`.`);return Object.fromEntries(g.flatMap((U)=>E[U]===void 0?[]:[[U,E[U]]]))});if(t.elseSteps!==void 0&&!Array.isArray(t.elseSteps))throw Error("`elseSteps` must be an array when calling `insert_sequence_step`.");let _=l(t,"elseTargetNodeId"),T=Array.isArray(t.elseSteps)&&t.elseSteps.length>0;if(!m&&!_&&!T&&!w)throw Error("Provide `elseTargetNodeId` or non-empty `elseSteps` when inserting `logic_branch` with `insert_sequence_step`.");return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},branch:{afterNodeId:o,...l(t,"label")?{label:l(t,"label")}:{},...m?{splitMode:c,randomPercentages:t.randomPercentages}:{},branches:f,...Array.isArray(t.elseSteps)?{elseSteps:t.elseSteps}:{},..._?{elseTargetNodeId:_}:{},...w?{allowEmptyPaths:!0}:{}}}}if(e==="delay"||e==="create_discount"||e==="update_subscriber"||e==="condition"||e==="add_tag"||e==="remove_tag"||e==="add_to_list"||e==="remove_from_list"||e==="webhook"||e==="ai"){let o;if(e==="delay"){o={type:"delay"};for(let m of["delay","delayMs","waitUntil","waitUntilWeekday"])if(t[m]!==void 0)o[m]=t[m];if(o.delay===void 0&&o.delayMs===void 0&&o.waitUntil===void 0&&o.waitUntilWeekday===void 0)throw Error("Provide `delay`, `delayMs`, `waitUntil`, or `waitUntilWeekday` when inserting a delay step.")}else if(e==="create_discount"){o={type:"create_discount"};for(let m of["discount","label","provider","discountType","percentOff","amountOff","currency","duration","durationInMonths","appliesToAllPlans","planIds","codePrefix","maxRedemptions","lockToSubscriber","expiresAt","expiresInHours"])if(t[m]!==void 0)o[m]=t[m]}else if(e==="update_subscriber"){if(!I(t.config))throw Error("`config` is required when inserting an update_subscriber step.");o={type:"update_subscriber",nodeType:"action_update_attributes",config:t.config}}else if(e==="webhook"){let m=l(t,"method")??"POST";if(!["POST","GET","PUT","PATCH","DELETE"].includes(m))throw Error("`method` must be one of POST, GET, PUT, PATCH, or DELETE when inserting a webhook step.");if(t.headers!==void 0&&(!I(t.headers)||Object.values(t.headers).some((_)=>typeof _!=="string")))throw Error("`headers` must be an object with string values when inserting a webhook step.");let g=l(t,"onError");if(g&&!["continue","exit","fail"].includes(g))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting a webhook step.");if(t.body!==void 0&&typeof t.body!=="string")throw Error("`body` must be a JSON string when inserting a webhook step.");if(t.resultKey!==void 0&&typeof t.resultKey!=="string")throw Error("`resultKey` must be a string when inserting a webhook step.");let w=l(t,"body"),f=l(t,"resultKey");o={type:"webhook",nodeType:"action_webhook",config:{label:l(t,"label")??"Webhook",url:u("insert_sequence_step",t,"url"),method:m,...t.headers!==void 0?{headers:t.headers}:{},...w?{body:w}:{},...f?{resultKey:f}:{},...g?{onError:g}:{}}}}else if(e==="ai"){let m=l(t,"onError");if(m&&!["continue","exit","fail"].includes(m))throw Error("`onError` must be `continue`, `exit`, or `fail` when inserting an ai step.");if(!Array.isArray(t.outputFields)||t.outputFields.length===0)throw Error("`outputFields` is required when inserting an ai step, e.g. [{ key: 'subject_line', fallback: 'We miss you' }].");if(t.includeAttributes!==void 0){if(!Array.isArray(t.includeAttributes)||t.includeAttributes.some((g)=>typeof g!=="string"))throw Error("`includeAttributes` must be an array of attribute names when inserting an ai step.")}if(t.recentEventLimit!==void 0&&typeof t.recentEventLimit!=="number")throw Error("`recentEventLimit` must be a number between 1 and 50 when inserting an ai step.");o={type:"ai",nodeType:"action_ai",config:{label:l(t,"label")??"Ask AI",prompt:u("insert_sequence_step",t,"prompt"),resultKey:u("insert_sequence_step",t,"resultKey"),outputFields:t.outputFields,...t.includeTags!==void 0?{includeTags:t.includeTags===!0}:{},...t.includeEventProperties!==void 0?{includeEventProperties:t.includeEventProperties===!0}:{},...t.includeRecentEvents!==void 0?{includeRecentEvents:t.includeRecentEvents===!0}:{},...t.recentEventLimit!==void 0?{recentEventLimit:t.recentEventLimit}:{},...t.includeAttributes!==void 0?{includeAttributes:t.includeAttributes}:{},...m?{onError:m}:{}}}}else if(e==="condition"){let m=u("insert_sequence_step",t,"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(m))throw Error("`conditionType` is not supported for condition steps.");if((m==="has_tag"||m==="does_not_have_tag")&&!l(t,"tagId")&&!l(t,"tagName"))throw Error("Provide `tagId` or `tagName` for this condition step.");if(m==="in_list"&&!l(t,"listId"))throw Error("`listId` is required for an in_list condition.");if(m==="in_segment"&&!l(t,"segmentId"))throw Error("`segmentId` is required for an in_segment condition.");if(m==="event_received"&&!l(t,"eventName"))throw Error("`eventName` is required for an event_received condition.");if(m.startsWith("field_")&&(!l(t,"fieldName")||!l(t,"fieldValue")))throw Error("`fieldName` and `fieldValue` are required for field conditions.");let w={label:l(t,"label")??"Condition",conditionType:m};for(let f of["tagId","tagName","listId","segmentId","segmentName","eventName","linkUrl","activityScope","fieldName","fieldValue"])if(t[f]!==void 0)w[f]=t[f];o={type:"condition",nodeType:"logic_condition",config:w}}else{let m=e==="add_tag"||e==="remove_tag",g=e==="add_tag"?"action_add_tag":e==="remove_tag"?"action_remove_tag":e==="add_to_list"?"action_add_to_list":"action_remove_from_list",w={label:l(t,"label")??(e==="add_tag"?"Add Tag":e==="remove_tag"?"Remove Tag":e==="add_to_list"?"Add to List":"Remove from List")};if(m){let f=l(t,"tagId"),_=l(t,"tagName");if(!f&&!_)throw Error("Provide `tagId` or `tagName` when inserting a tag action.");if(f)w.tagId=f;if(_)w.tagName=_}else{w.listId=u("insert_sequence_step",t,"listId");let f=l(t,"listName");if(f)w.listName=f}o={nodeType:g,config:w}}for(let m of["delay","delayMs","waitUntil","waitUntilWeekday"])if(e!=="delay"&&t[m]!==void 0)o[m]=t[m];let d={steps:[o]},c=l(t,"afterNodeId");if(c)d.afterNodeId=c;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},insertSteps:d}}let s=e==="sms",i;if(s){pn("insert_sequence_step","SMS step",t);let o=l(t,"text"),d=Array.isArray(t.blocks)&&t.blocks.length>0;if(o===void 0&&!d)throw Error("Provide `text` (or `blocks`) when inserting an SMS step with `insert_sequence_step`.");i={type:"sms"};for(let c of["text","blocks","imageUrls","label","name","ineligibleAction","delay","delayMs","waitUntil","waitUntilWeekday"])if(t[c]!==void 0)i[c]=t[c]}else{z("insert_sequence_step",t,{requireContent:!0}),ct("insert_sequence_step","email step",t),i={subject:u("insert_sequence_step",t,"subject")};for(let o of["name","previewText","html","blocks","delay","delayMs","waitUntil","waitUntilWeekday","senderProfileId","fromEmail","fromName","replyProfileId","replyTo","replyToName","isTransactional","ccEmails","bccEmails","attachments"])if(t[o]!==void 0)i[o]=t[o]}let r={steps:[i]};if(t.afterNodeId!==void 0)r.afterNodeId=t.afterNodeId;return{...t.confirmStructuralChange!==void 0&&{confirmStructuralChange:t.confirmStructuralChange},insertSteps:r}}function Ki(t,e){let n=t[e];if(n===void 0)return[];if(!Array.isArray(n))throw Error(`\`${e}\` must be an array when calling \`cancel_sequence_enrollments\`.`);let s=n.map((i)=>typeof i==="string"?i.trim():"").filter((i)=>i.length>0);if(n.some((i)=>typeof i!=="string")||s.length===0)throw Error(`\`${e}\` must contain at least one non-empty string when calling \`cancel_sequence_enrollments\`.`);return s}function Vi(t,e){let n=t[e];if(n===void 0)return[];if(!Array.isArray(n))throw Error(`\`${e}\` must be an array when calling \`realign_sequence_enrollments\`.`);let s=n.map((i)=>typeof i==="string"?i.trim():"").filter((i)=>i.length>0);if(n.some((i)=>typeof i!=="string")||s.length===0)throw Error(`\`${e}\` must contain at least one non-empty string when calling \`realign_sequence_enrollments\`.`);return s}function is(t){let e=Vi(t,"nodeIds"),n=Vi(t,"subscriberIds"),s=l(t,"cursor");if(t.dryRun!==void 0&&typeof t.dryRun!=="boolean")throw Error("`dryRun` must be a boolean when calling `realign_sequence_enrollments`.");return{...e.length>0&&{nodeIds:e},...n.length>0&&{subscriberIds:n},...s!==void 0&&{cursor:s},...typeof t.dryRun==="boolean"&&{dryRun:t.dryRun}}}function ss(t){let e=l(t,"subscriberId"),n=Ki(t,"subscriberIds"),s=Ki(t,"fieldValues");if(t.cancelAll!==void 0&&typeof t.cancelAll!=="boolean")throw Error("`cancelAll` must be a boolean when calling `cancel_sequence_enrollments`.");let i=t.cancelAll===!0;if((e!==void 0?1:0)+(n.length>0?1:0)+(s.length>0?1:0)+(i?1:0)!==1)throw Error("Provide exactly one target when calling `cancel_sequence_enrollments`: `cancelAll`, `subscriberId`, `subscriberIds`, or `fieldValues`.");let o=l(t,"fieldPath"),d=l(t,"reason");return{...i&&{cancelAll:!0},...e!==void 0&&{subscriberId:e},...n.length>0&&{subscriberIds:n},...o!==void 0&&{fieldPath:o},...s.length>0&&{fieldValues:s},...typeof t.dryRun==="boolean"&&{dryRun:t.dryRun},...d!==void 0&&{reason:d}}}var Yi=["wait_until_asc","wait_until_desc","enrolled_at_asc","enrolled_at_desc"];function Ji(t,e){let n=t[e];if(n===void 0||n===null)return;let s=typeof n==="string"?Number(n):n,i=e==="dailyLimit"?0:1;if(typeof s!=="number"||!Number.isSafeInteger(s)||s<i)throw Error(`\`${e}\` must be an integer of at least ${i} when calling \`move_sequence_enrollments\`.`);return s}function Zi(t,e){let n=t[e];if(n===void 0)return[];if(!Array.isArray(n)||n.some((i)=>typeof i!=="string"))throw Error(`\`${e}\` must be an array of strings when calling \`move_sequence_enrollments\`.`);let s=n.map((i)=>i.trim()).filter((i)=>i.length>0);if(s.length===0)throw Error(`\`${e}\` must contain at least one non-empty string when calling \`move_sequence_enrollments\`.`);return s}function rs(t){let e=u("move_sequence_enrollments",t,"fromNodeId"),n=l(t,"targetNodeId"),s=l(t,"reason"),i=l(t,"sort");if(i!==void 0&&!Yi.includes(i))throw Error(`\`sort\` must be one of ${Yi.join(", ")} when calling \`move_sequence_enrollments\`.`);let r=Zi(t,"subscriberIds"),o=Zi(t,"tags"),d=Ji(t,"limit"),c=Ji(t,"dailyLimit");return{fromNodeId:e,...n!==void 0&&{targetNodeId:n},...d!==void 0&&{limit:d},...c!==void 0&&{dailyLimit:c},...i!==void 0&&{sort:i},...r.length>0&&{subscriberIds:r},...o.length>0&&{tags:o},...s!==void 0&&{reason:s},...typeof t.dryRun==="boolean"&&{dryRun:t.dryRun}}}function os(t){z("create_campaign",t),X("create_campaign",t);let e=l(t,"prompt")!==void 0,n=t.html!==void 0,s=t.blocks!==void 0,i=t.templateId!==void 0;if(t.prompt!==void 0&&!e)throw Error("`prompt` cannot be empty when calling `create_campaign`.");if(e&&(n||s||i))throw Error("Provide either `prompt`, `html`, `blocks`, or `templateId` when calling `create_campaign`, not multiple content sources.");if(!e&&(t.style!==void 0||t.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_campaign`.");if(un("create_campaign",t),!e&&l(t,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_campaign`.")}function un(t,e){if(e.emailPreset===void 0)return;if(e.emailPreset!=="branded"&&e.emailPreset!=="minimal")throw Error(`\`emailPreset\` must be branded or minimal when calling \`${t}\`.`);if(e.html!==void 0)throw Error(`\`emailPreset\` is only supported for native Sequenzy blocks and cannot be combined with \`html\` when calling \`${t}\`.`)}function as(t){z("create_template",t),X("create_template",t);let e=l(t,"prompt")!==void 0,n=[e,t.html!==void 0,t.blocks!==void 0].filter(Boolean).length;if(t.prompt!==void 0&&!e)throw Error("`prompt` cannot be empty when calling `create_template`.");if(n!==1)throw Error("Provide exactly one of `prompt`, `html`, or `blocks` when calling `create_template`.");if(!e&&(t.style!==void 0||t.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_template`.");if(!e&&l(t,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_template`.")}function mn(t,e){if(e.sendTimeOptimization!==void 0&&typeof e.sendTimeOptimization!=="boolean")throw Error(`\`sendTimeOptimization\` must be a boolean when calling \`${t}\`.`);if(e.sendTimeWindowHours!==void 0){if(typeof e.sendTimeWindowHours!=="number"||!Number.isInteger(e.sendTimeWindowHours)||e.sendTimeWindowHours<1||e.sendTimeWindowHours>24)throw Error(`\`sendTimeWindowHours\` must be an integer between 1 and 24 when calling \`${t}\`.`)}}function ds(t){if(l(t,"scheduledAt")===void 0)throw Error("`scheduledAt` is required when calling `schedule_campaign`.");if(t.targetLists!==void 0&&!I(t.targetLists))throw Error("`targetLists` must be an object when calling `schedule_campaign`.");if(t.listIds!==void 0&&t.targetLists!==void 0)throw Error("Provide either `listIds` or `targetLists` when calling `schedule_campaign`, not both.");if(t.listIds!==void 0&&(!Array.isArray(t.listIds)||t.listIds.length===0||t.listIds.some((e)=>typeof e!=="string")))throw Error("`listIds` must be a non-empty array of list ID strings when calling `schedule_campaign`.");if(mn("schedule_campaign",t),t.spreadOverHours!==void 0){if(typeof t.spreadOverHours!=="number"||!Number.isInteger(t.spreadOverHours)||t.spreadOverHours<1||t.spreadOverHours>72)throw Error("`spreadOverHours` must be an integer between 1 and 72 when calling `schedule_campaign`.")}if(t.sendInRecipientTimezone!==void 0&&typeof t.sendInRecipientTimezone!=="boolean")throw Error("`sendInRecipientTimezone` must be a boolean when calling `schedule_campaign`.");if(t.scheduledTimezone!==void 0&&(typeof t.scheduledTimezone!=="string"||t.scheduledTimezone.trim()===""))throw Error("`scheduledTimezone` must be a non-empty IANA timezone string (e.g. America/New_York) when calling `schedule_campaign`.");if(t.sendInRecipientTimezone===!0&&t.scheduledTimezone===void 0)throw Error("`scheduledTimezone` is required when `sendInRecipientTimezone` is true - it is the IANA zone the scheduledAt wall-clock time refers to.");if(t.recurringInterval!==void 0&&t.recurringInterval!=="weekly"&&t.recurringInterval!=="monthly")throw Error("`recurringInterval` must be 'weekly' or 'monthly' when calling `schedule_campaign`.")}function lt(t,e,n){let s=new Set(["companyId","landingPageId","name","slug","content"]),i=Object.keys(e).filter((r)=>!s.has(r));if(i.length>0)throw Error(`\`${t}\` accepts only \`name\`, \`slug\`, and \`content\` update fields. Unsupported field${i.length===1?"":"s"}: ${i.map((r)=>`\`${r}\``).join(", ")}.`);if(n.requireUpdate&&e.name===void 0&&e.slug===void 0&&e.content===void 0)throw Error(`Provide at least one of \`name\`, \`slug\`, or \`content\` when calling \`${t}\`.`);return{...e.name!==void 0&&{name:e.name},...e.slug!==void 0&&{slug:e.slug},...e.content!==void 0&&{content:e.content}}}function cs(t){let e=new Set(["companyId","domain","landingPageId","verify"]),n=Object.keys(t).filter((s)=>!e.has(s));if(n.length>0)throw Error(`\`update_landing_page_domain_settings\` accepts only \`landingPageId\`, \`domain\`, and \`verify\`. Unsupported field${n.length===1?"":"s"}: ${n.map((s)=>`\`${s}\``).join(", ")}.`);if(t.domain===void 0&&t.verify!==!0)throw Error("Provide `domain` or `verify: true` when calling `update_landing_page_domain_settings`.");return{...t.domain!==void 0&&{domain:t.domain},...typeof t.verify==="boolean"&&{verify:t.verify}}}function ls(t){z("create_transactional_email",t);let e=l(t,"prompt")!==void 0,n=t.html!==void 0,s=t.blocks!==void 0;if(t.prompt!==void 0&&!e)throw Error("`prompt` cannot be empty when calling `create_transactional_email`.");if(e&&(n||s))throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`, not multiple content sources.");if(!e&&(t.style!==void 0||t.tone!==void 0))throw Error("`style` and `tone` can only be used with `prompt` when calling `create_transactional_email`.");if(!e&&!n&&!s)throw Error("Provide either `prompt`, `html`, or `blocks` when calling `create_transactional_email`.");if(!e&&l(t,"subject")===void 0)throw Error("`subject` is required unless `prompt` is provided when calling `create_transactional_email`.")}var qe={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},Ko={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:{...qe.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},Me={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."}},Le={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:Ko,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:we,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:Ie,delayMs:{type:"number",description:"Delay in milliseconds. Useful for standalone type:'delay' steps."},waitUntil:_e,waitUntilWeekday:ve,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.${Qe}`,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},hn={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:Le}},additionalProperties:!1},yn="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.",gn={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."},fn={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 ps(t){if(!t||typeof t!=="object")return null;let e=t;if(e.success!==!1)return null;if(typeof e.error==="string")return Error(e.error);if(e.error&&typeof e.error==="object"&&typeof e.error.message==="string")return Error(e.error.message);if(typeof e.message==="string")return Error(e.message);return Error("The tool returned an unsuccessful response.")}var bn=1000,wn=1000,_n=bn*wn-1;function vn(t){return t.trim().toLowerCase().replace(/\s+/g,"-")}function In(t,e){let{attributes:n,customAttributes:s}=e,i=n!==void 0;if(i&&s!==void 0)throw Error(`Provide either \`attributes\` or \`customAttributes\` when calling \`${t}\`, not both. They are the same field; the REST API names it customAttributes.`);let o=i?n:s;if(o===void 0)return;if(!I(o))throw Error(`\`attributes\` (REST: customAttributes) must be an object when calling \`${t}\`.`);return{value:o,source:i?"attributes":"customAttributes"}}function Vo(t,e){let n=l(e,"attribute"),s=l(e,"attributeValue"),i=S(t,e,"attributeOperator",et);if(!n){if(s!==void 0||i!==void 0)throw Error(`\`attributeValue\` and \`attributeOperator\` require \`attribute\` when calling \`${t}\`.`);return{}}let r=i??"is",o;if(s!==void 0)o=`${n}:${s}`;else if(n.includes(":"))o=n;else if(r==="is_not_empty")o=`${n}:`;else throw Error(`Provide \`attributeValue\` (or use \`attribute: "name:value"\`) when \`attributeOperator\` is \`${r}\` in \`${t}\`. Only \`is_not_empty\` may omit a value.`);return{attribute:o,attributeOperator:r}}function Yo(t){let e=new URLSearchParams;if(typeof t.query==="string"&&t.query.trim()!=="")e.set("query",t.query.trim());if(Array.isArray(t.tags)&&t.tags.length>0)e.set("tags",t.tags.filter((n)=>typeof n==="string"&&n.trim()!=="").join(","));if(typeof t.list==="string"&&t.list.trim()!=="")e.set("list",t.list.trim());if(typeof t.listId==="string"&&t.listId.trim()!=="")e.set("listId",t.listId.trim());if(typeof t.listName==="string"&&t.listName.trim()!=="")e.set("listName",t.listName.trim());if(typeof t.segmentId==="string"&&t.segmentId.trim()!=="")e.set("segmentId",t.segmentId);if(typeof t.status==="string"&&t.status.trim()!=="")e.set("status",t.status.trim());if(typeof t.unsubscribedAfter==="string"&&t.unsubscribedAfter.trim()!=="")e.set("unsubscribedAfter",t.unsubscribedAfter.trim());if(typeof t.unsubscribedBefore==="string"&&t.unsubscribedBefore.trim()!=="")e.set("unsubscribedBefore",t.unsubscribedBefore.trim());if(t.attribute){if(e.set("attribute",t.attribute),t.attributeOperator)e.set("attributeOperator",t.attributeOperator)}if(t.cursor)e.set("cursor",t.cursor);else e.set("page",String(t.page));if(e.set("limit",String(t.pageSize)),t.includeTotal===!1)e.set("includeTotal","false");return e}async function hs(t,e){let s=gs("search_subscribers",t,"limit"),i=l(t,"cursor"),r=i?Jo("search_subscribers",t):Zo("search_subscribers",t,s),o=s===void 0?void 0:r+s,d=Math.min(bn,Math.max(1,o??bn)),c=Vo("search_subscribers",t),m=[],g=1,w=i,f,_=null,T=0,E=!1,C=!1;while(!0){let he=o===void 0?void 0:o-m.length,ye=w?Math.min(d,Math.max(1,he??d)):d,He=Yo({query:t.query,tags:t.tags,list:t.list,listId:t.listId,listName:t.listName,segmentId:t.segmentId,status:t.status,unsubscribedAfter:t.unsubscribedAfter,unsubscribedBefore:t.unsubscribedBefore,attribute:c.attribute,attributeOperator:c.attributeOperator,page:g,pageSize:ye,cursor:w}),O=await a("GET",`/api/v1/subscribers?${He.toString()}`,void 0,e);if(T===0)_=O.pagination?.total??null;T+=1,m.push(...O.subscribers??[]);let H=(O.subscribers??[]).length,B=O.pagination?.nextCursor??void 0;f=B;let Be=o!==void 0&&m.length>=o,W;if(B)W=!1;else if(O.pagination?.hasMore!==void 0)W=!O.pagination.hasMore;else if(O.pagination?.totalPages!==void 0&&O.pagination.totalPages!==null)W=g>=O.pagination.totalPages;else W=H<ye;if(W||H===0&&!B){E=!0;break}if(Be)break;if(T>=wn){C=!0;break}if(B)w=B;else if(w)break;else g+=1}if(C&&(m.length<r||m.length===r&&f===void 0))throw Error(`Could not reach offset ${r} within ${wn} requests because too few matches were returned per page. Start without \`offset\` and follow \`pagination.nextCursor\` instead.`);if(_===null&&E&&!i)_=m.length;let D=m.slice(r,o),ee=E?!1:_!==null?r+D.length<_:!E||m.length>r+D.length,te=f!==void 0&&m.length===r+D.length,U=r+D.length;return{success:!0,subscribers:D,pagination:{page:s===void 0?1:Math.floor(r/s)+1,limit:s??d,offset:r,total:_,totalPages:_===null?null:Math.ceil(_/(s??d)),fetchedPages:T,hasMore:ee,nextOffset:ee&&!i&&U<=_n?U:null,nextCursor:ee&&te?f??null:null},returned:D.length,truncated:ee}}function Jo(t,e){if(e.offset!==void 0||e.page!==void 0)throw Error(`\`cursor\` cannot be combined with \`offset\` or \`page\` when calling \`${t}\`. Keep following \`pagination.nextCursor\` instead.`);return 0}function Zo(t,e,n){let s=ys(t,e,"offset"),i=gs(t,e,"page");if(s!==void 0&&i!==void 0)throw Error(`Provide either \`offset\` or \`page\` when calling \`${t}\`, not both.`);if(i!==void 0){if(n===void 0)throw Error(`\`page\` requires \`limit\` when calling \`${t}\` so the page size is defined. Omit both to fetch every match in one call.`);return us(t,(i-1)*n)}return us(t,s??0)}function us(t,e){if(e>_n)throw Error(`\`offset\` must be ${_n} or less when calling \`${t}\`. Use \`cursor\` to continue beyond that point.`);return e}function ys(t,e,n){let s=e[n];if(s===void 0||s===null)return;if(typeof s!=="number"||!Number.isInteger(s)||s<0)throw Error(`\`${n}\` must be a non-negative integer when calling \`${t}\`.`);return s}function gs(t,e,n){let s=ys(t,e,n);if(s!==void 0&&s<1)throw Error(`\`${n}\` must be 1 or greater when calling \`${t}\`.`);return s}function kn(t){let e=typeof t.email==="string"&&t.email.trim()!==""?t.email.trim():void 0,n=typeof t.externalId==="string"&&t.externalId.trim()!==""?t.externalId.trim():void 0;return{...e?{email:e}:{},...n?{externalId:n}:{}}}function V(t,e){let n=kn(e);if(!n.email&&!n.externalId)throw Error(`Provide either \`email\` or \`externalId\` when calling \`${t}\`.`);return n}function pt(t,e){let n=new URLSearchParams;if(e?.includeMachineEngagement)n.set("includeMachineEngagement","true");let s=n.toString(),i=s?`?${s}`:"";if(t.email)return`/api/v1/subscribers/${encodeURIComponent(t.email)}${i}`;return n.set("externalId",String(t.externalId)),`/api/v1/subscribers/external?${n.toString()}`}function Sn(t){if(t.email)return`/api/v1/subscribers/${encodeURIComponent(t.email)}/notes`;let e=new URLSearchParams;return e.set("externalId",String(t.externalId)),`/api/v1/subscribers/external/notes?${e.toString()}`}async function $e(t,e,n){return a("GET",pt(t,n),void 0,e)}function S(t,e,n,s){let i=l(e,n);if(i===void 0)return;if(!s.includes(i))throw Error(`\`${n}\` must be one of ${s.join(", ")} when calling \`${t}\`.`);return i}function Fe(t,e,n,s){let i=u(t,e,n);if(!s.includes(i))throw Error(`\`${n}\` must be one of ${s.join(", ")} when calling \`${t}\`.`);return i}function P(t,e,n,s,i){let r=e[n];if(r===void 0)return;if(typeof r!=="number"||!Number.isInteger(r)||r<s||r>i)throw Error(`\`${n}\` must be an integer between ${s} and ${i} when calling \`${t}\`.`);return r}function Qo(t,e){let n=[],s=S(t,e,"eventType",je);if(s)n.push(s);if(e.eventTypes!==void 0){if(!Array.isArray(e.eventTypes))throw Error(`\`eventTypes\` must be an array when calling \`${t}\`.`);e.eventTypes.forEach((i,r)=>{if(typeof i!=="string")throw Error(`\`eventTypes\` item ${r+1} must be a string when calling \`${t}\`.`);let o=i.trim();if(!je.includes(o))throw Error(`\`eventTypes\` item ${r+1} must be one of ${je.join(", ")} when calling \`${t}\`.`);n.push(o)})}return[...new Set(n)]}function Tn(t,e){let n=new URLSearchParams,s=Qo(t,e);if(s.length>0)n.set("eventTypes",s.join(","));let i=S(t,e,"period",["1h","24h","7d","30d","90d"]);if(i)n.set("period",i);let r=l(e,"start");if(r)n.set("start",r);let o=l(e,"end");if(o)n.set("end",o);let d=P(t,e,"page",1,1e6);if(d!==void 0)n.set("page",String(d));let c=P(t,e,"limit",1,500);if(c!==void 0)n.set("limit",String(c));if(e.includeMachineEngagement===!0)n.set("includeMachineEngagement","true");return n}function qn(t,e){if(e.events===void 0)return;if(!Array.isArray(e.events))throw Error(`\`events\` must be an array when calling \`${t}\`.`);let n=e.events.map((s,i)=>{if(typeof s!=="string"||!Se.includes(s))throw Error(`\`events\` item ${i+1} must be one of ${Se.join(", ")} when calling \`${t}\`.`);return s});if(n.length===0)throw Error(`\`events\` must include at least one event type when calling \`${t}\`.`);return n}function Pn(t,e){if(!Array.isArray(e.emails))throw Error(`\`emails\` must be an array when calling \`${t}\`.`);let n=[];if(e.emails.forEach((s,i)=>{if(typeof s!=="string")throw Error(`\`emails\` item ${i+1} must be a string when calling \`${t}\`.`);let r=s.trim();if(r.length>0)n.push(r)}),n.length===0)throw Error(`\`emails\` must include at least one email address when calling \`${t}\`.`);if(n.length>Wt)throw Error(`\`emails\` must include no more than ${Wt} email addresses when calling \`${t}\`. Split larger batches into multiple calls.`);return n}function ms(t,e,n,s){let i=e[n];if(i===void 0)return;if(!Array.isArray(i))throw Error(`\`${n}\` must be an array when calling \`${t}\`.`);let r=[];if(i.forEach((o,d)=>{if(typeof o!=="string")throw Error(`\`${n}\` item ${d+1} must be a string when calling \`${t}\`.`);let c=o.trim();if(c.length>0)r.push(c)}),r.length===0)throw Error(`\`${n}\` must include at least one ${s} when calling \`${t}\`.`);return r}function fs(t){let n=ms("enroll_subscribers_in_sequence",t,"emails","email address"),s=ms("enroll_subscribers_in_sequence",t,"subscriberIds","subscriber ID"),i=(n?.length??0)+(s?.length??0);if(i===0)throw Error("Provide `emails` or `subscriberIds` when calling `enroll_subscribers_in_sequence`.");if(i>Gt)throw Error(`\`emails\` and \`subscriberIds\` must include no more than ${Gt} total targets when calling \`enroll_subscribers_in_sequence\`. Split larger batches into multiple calls.`);let r=l(t,"targetNodeId");return{...n!==void 0&&{emails:n},...s!==void 0&&{subscriberIds:s},...r!==void 0&&{targetNodeId:r}}}function ut(t,e){let n=t[e];if(n===void 0||n===null)return;if(typeof n==="string"){let r=n.trim();return r.length>0?r:void 0}if(!Array.isArray(n))throw Error(`\`${e}\` must be an email address or an array of email addresses when calling \`send_email\`.`);if(n.length>50)throw Error(`\`${e}\` accepts at most 50 email addresses when calling \`send_email\`.`);let s=new Set,i=[];return n.forEach((r,o)=>{if(typeof r!=="string")throw Error(`\`${e}\` item ${o+1} must be an email address when calling \`send_email\`.`);let d=r.trim();if(d.length===0)throw Error(`\`${e}\` item ${o+1} must be a non-empty email address when calling \`send_email\`.`);let c=d.toLowerCase();if(s.has(c))return;s.add(c),i.push(d)}),i.length>0?i:void 0}function En(t){if(t===void 0)return 0;return typeof t==="string"?1:t.length}function Cn(t){if(t===void 0)return[];return typeof t==="string"?[t]:t}function bs(t,e){if(e.length===0)return;return typeof t==="string"?e[0]:e}function ws(t){let e=new Set(Cn(t.to).map((i)=>i.toLowerCase())),n=Cn(t.cc).filter((i)=>{let r=i.toLowerCase();if(e.has(r))return!1;return e.add(r),!0}),s=Cn(t.bcc).filter((i)=>{let r=i.toLowerCase();if(e.has(r))return!1;return e.add(r),!0});return{to:t.to,cc:bs(t.cc,n),bcc:bs(t.bcc,s)}}function _s(t){let e=En(t.to),n=En(t.cc),s=En(t.bcc),i=e>1||n>0||s>0;if(t.emailType==="marketing"&&i)throw Error("Marketing sends accept exactly one `to` address and do not support `cc` or `bcc` when calling `send_email`. Use the default `transactional` emailType to send one email to several recipients.");if((typeof t.subscriberExternalId==="string"?t.subscriberExternalId.trim().length>0:t.subscriberExternalId!==void 0&&t.subscriberExternalId!==null)&&i)throw Error("`subscriberExternalId` is only supported for single-recipient sends when calling `send_email`. Drop it to send to several recipients, or send one email per subscriber.")}import{readFileSync as Xo,statSync as ea}from"node:fs";import{basename as ta}from"node:path";var na={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 ia(t){let e=t.split(".").pop()?.toLowerCase()??"";return na[e]??null}var sa=104857600;async function vs(t,e){if(!Ge())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 n=ia(t);if(!n)throw Error("Unsupported file type. Use PDF, ePub, ZIP, image, audio, video, or text files.");let s=ea(t).size;if(s>sa)throw Error(`File is too large (${Math.round(s/1048576)}MB). Delivery files must be 100MB or smaller.`);let i=Xo(t),r=await a("POST","/api/v1/products/delivery/upload-url",{filename:ta(t),contentType:n,fileSizeBytes:s},e),o=await fetch(r.uploadUrl,{method:"PUT",headers:{"Content-Type":n},body:i});if(!o.ok)throw Error(`File upload failed (${o.status})`);return{url:r.publicUrl,fileName:r.fileName,fileSizeBytes:s,mimeType:n}}async function mt(t){let e=l(t,"companyId");if(e)return e;let n=ie();if(n)return n;try{return(await a("GET","/api/v1/account")).currentCompanyId??void 0}catch{return}}async function Ce(t,e){let n=await mt(e);if(!n)throw Error(`A company is required when calling \`${t}\`. Call \`get_account\`, then \`select_company\`, or pass \`companyId\` explicitly.`);return n}function Ee(t,e){if(!I(t)||!e)return t;return{...t,url:e}}function Is(t,e){if(!I(t))return t;return{...t,...e.campaign!==void 0&&{url:e.campaign},...e.campaignPreview!==void 0&&{previewUrl:e.campaignPreview}}}function Pe(t,e,n){if(!Array.isArray(t)||!e)return t;return t.map((s)=>{if(!I(s))return s;let i=l(s,"id");if(!i)return s;let r=Z({companyId:e,...n==="campaign"&&{campaignId:i},...n==="landingPage"&&{landingPageId:i},...n==="sequence"&&{sequenceId:i},...n==="template"&&{emailId:i},...n==="transactional"&&{transactionalId:i},...n==="emailSend"&&{emailSendId:i}});if(n==="campaign")return Is(s,r.urls);let o=n==="sequence"?r.urls.sequence:n==="landingPage"?r.urls.landingPage:n==="template"?r.urls.email:n==="transactional"?r.urls.transactionalEmail:r.urls.emailSend;return Ee(s,o)})}function ra(t){if(!Array.isArray(t))return t;return t.map((e)=>{if(!I(e))return e;let n=l(e,"id");if(!n)return e;let s=Z({companyId:n});return{...e,url:s.urls.dashboard,settingsUrl:s.urls.settings,subscriptionUrl:s.urls.subscription}})}var xn=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","get_landing_page_stats","render_landing_page","create_landing_page","update_landing_page","publish_landing_page","unpublish_landing_page","duplicate_landing_page","delete_landing_page","list_sequences","get_sequence","simulate_sequence","get_sequence_enrollment","send_sequence_test_email","create_sequence","generate_sequence","update_sequence","update_sequence_node","update_sequence_nodes","edit_sequence_graph","insert_sequence_step","get_sequence_inbound_webhook","configure_sequence_inbound_webhook","rotate_sequence_inbound_webhook_secret","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","select_ab_test_winner","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 ks(t,e,n){if(!I(n)||!xn.has(t))return n;let s=I(n.company)?n.company:void 0,r=l(n,"selectedCompanyId")??l(n,"currentCompanyId")??l(n,"companyId")??(s?l(s,"id"):void 0)??(s?l(s,"companyId"):void 0)??await mt(e);if(!r)return n;let o=I(n.campaign)?n.campaign:void 0,d=I(n.sequence)?n.sequence:void 0,c=I(n.landingPage)?n.landingPage:void 0,m=I(n.template)?n.template:void 0,g=I(n.transactional)&&!Array.isArray(n.transactional)?n.transactional:void 0,w={companyId:r,campaignId:l(e,"campaignId")??l(n,"campaignId")??(o?l(o,"id"):void 0),landingPageId:l(e,"landingPageId")??l(n,"landingPageId")??(c?l(c,"id"):void 0),sequenceId:l(e,"sequenceId")??l(n,"sequenceId")??(d?l(d,"id"):void 0),emailId:l(n,"templateId")??(m?l(m,"id"):void 0)??(g?l(g,"emailId"):void 0)??l(e,"templateId"),transactionalId:l(e,"transactionalId")??(g?l(g,"id"):void 0)??l(e,"idOrSlug"),emailSendId:l(e,"emailSendId")??l(n,"emailSendId")??(I(n.emailSend)?l(n.emailSend,"id"):void 0),status:l(e,"status")},f=Z(w),_=s?Z({companyId:r}):void 0;return{...n,...Array.isArray(n.companies)&&{companies:ra(n.companies)},...Array.isArray(n.campaigns)&&{campaigns:Pe(n.campaigns,r,"campaign")},...Array.isArray(n.landingPages)&&{landingPages:Pe(n.landingPages,r,"landingPage")},...Array.isArray(n.sequences)&&{sequences:Pe(n.sequences,r,"sequence")},...Array.isArray(n.templates)&&{templates:Pe(n.templates,r,"template")},...Array.isArray(n.transactional)&&{transactional:Pe(n.transactional,r,"transactional")},...Array.isArray(n.emailSends)&&{emailSends:Pe(n.emailSends,r,"emailSend")},...s&&_!==void 0&&{company:{...s,url:_.urls.dashboard,settingsUrl:_.urls.settings,subscriptionUrl:_.urls.subscription}},...o&&f.urls.campaign!==void 0&&{campaign:Is(o,f.urls)},...d&&f.urls.sequence!==void 0&&{sequence:Ee(d,f.urls.sequence)},...c&&f.urls.landingPage!==void 0&&{landingPage:Ee(c,f.urls.landingPage)},...m&&f.urls.email!==void 0&&{template:Ee(m,f.urls.email)},...g&&f.urls.transactionalEmail!==void 0&&{transactional:Ee(g,f.urls.transactionalEmail)},...I(n.emailSend)&&f.urls.emailSend!==void 0&&{emailSend:Ee(n.emailSend,f.urls.emailSend)},appUrls:f.urls}}import{readFileSync as oa,statSync as aa}from"node:fs";import{basename as da,extname as Ts}from"node:path";var An=5242880,ca=Math.ceil(An/3)*4,la=Math.ceil(ca*1.05)+256,qs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},pa=new Set(Object.values(qs));function Rn(t){return t?.split(";")[0]?.trim().toLowerCase()||void 0}function ua(t){return qs[Ts(t).toLowerCase()]}function ma(t){let e=Ts(t);return(e?t.slice(0,-e.length):t).replace(/[-_]+/g," ").trim()||"Image"}function ha(t){if(t.length>la)throw Error("Image assets must be 5MB or smaller.")}function ya(t){let e=0,n=0;for(let i=0;i<t.length;i+=1){let r=t.charCodeAt(i);if(r===9||r===10||r===11||r===12||r===13||r===32)continue;e+=1,n=r===61?n+1:0}if(Math.floor(e*3/4)-Math.min(n,2)>An)throw Error("Image assets must be 5MB or smaller.")}function ga(t){ha(t);let e=t.trim(),n=/^data:([^;,]+);base64,([\s\S]+)$/i.exec(e),s=n?.[2]??e;ya(s);let i=s.replace(/\s+/g,"");if(i.length===0||i.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(i))throw Error("`imageBase64` must contain valid base64 image bytes.");return{bytes:Buffer.from(i,"base64"),...n?.[1]?{dataUrlContentType:Rn(n[1])}:{}}}function Ss(t){if(t<=0)throw Error("The image file is empty.");if(t>An)throw Error("Image assets must be 5MB or smaller.")}function fa(t){let e=ua(t.filename)??Rn(t.explicitContentType)??Rn(t.dataUrlContentType);if(!e||!pa.has(e))throw Error("Unsupported image type. Use PNG, JPEG, GIF, or WebP.");return e}function ba(t){let e,n,s;if(t.filePath!==void 0){if(!Ge())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 r=aa(t.filePath).size;Ss(r),e=oa(t.filePath),n=t.filename??da(t.filePath)}else{if(!t.imageBase64)throw Error("Provide either `filePath` or `imageBase64` when uploading an image asset.");if(!t.filename)throw Error("`filename` is required with `imageBase64` when uploading an image asset.");let r=ga(t.imageBase64);e=r.bytes,s=r.dataUrlContentType,n=t.filename,Ss(e.byteLength)}let i=fa({filename:n,explicitContentType:t.contentType,dataUrlContentType:s});return{bytes:e,filename:n,contentType:i,altText:t.altText??ma(n)}}async function Ps(t){let e=ba(t),n=e.bytes.byteLength,s=await a("POST","/api/v1/media/upload-url",{filename:e.filename,contentType:e.contentType,fileSizeBytes:n},t.companyId);return await Qn(s.uploadUrl,e.bytes,e.contentType,t.companyId),(await a("POST","/api/v1/media/complete-upload",{key:s.key,filename:s.fileName,contentType:e.contentType,fileSizeBytes:n,...t.sourceWidth!==void 0&&{width:t.sourceWidth},...t.sourceHeight!==void 0&&{height:t.sourceHeight},altText:e.altText},t.companyId)).asset}var ue={type:"boolean",description:"Whether the Sequenzy operation succeeded."},j={type:"string",description:"Human-readable status, confirmation, or next-step message."},Dn={type:"string",description:"Additional context about the result."};function y(t){return{type:"object",description:t,additionalProperties:!0}}function N(t){return{type:"array",description:t,items:y("One item in the returned collection.")}}function p(t){return{type:"string",description:t}}function Y(t){return{type:["object","null"],description:t,additionalProperties:!0}}function q(t){return{type:["string","null"],description:t}}function b(t){return{type:"number",description:t}}function Es(t){return{type:["number","null"],description:t}}function v(t){return{type:"boolean",description:t}}function wa(t){return{type:["boolean","null"],description:t}}function Cs(t,e){return{type:["array","null"],description:t,items:e}}function h(t){return y(`The ${t} record returned by Sequenzy.`)}function k(t){return N(`List of ${t} records returned by Sequenzy.`)}var oe="`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`.",xs="The subscriber import record: status, totalRows, emailCount, duplicateRows, addedCount, updatedCount, skippedCount, failedCount, processedCount, chunk progress, and the reason maps skippedReasons, failedReasons, and failedChunkReasons. Every excluded row is explained: skippedReasons sums to skippedCount and failedReasons sums to failedCount. Report a shortfall with the import ID instead of guessing which rows are missing.",As="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.",_a="Email numbering: emails[].stepNumber and nodes[].config.stepNumber are legacy stored ordinals retained for compatibility. Prefer emails[].structuralStepNumber and nodes[].structuralStepNumber when explaining the visible sequence position. Structural numbers are graph-derived; emails in parallel branches intentionally share a depth.",me=y(`The sequence record returned by Sequenzy. ${As} ${_a} Sequences use sendingWindow for allowed local hours/days; they do not have Send Time Optimization. STO is per-campaign (list_campaigns / get_campaign sendTimeOptimization).`),va=N(`List of sequence records returned by Sequenzy. ${As}`),ht={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:v("Whether new subscribers can enter the sequence right now."),processesExistingEnrollments:v("Whether subscribers already inside the sequence keep advancing and receiving steps."),effectiveStatusSummary:p("One plain-language sentence describing the run state, safe to show a user verbatim.")},Rs={...me,properties:{migratedRecipientCount:b("Recipients moved immediately from deleted steps to their surviving successor."),completedRecipientCount:b("Recipients completed because a deleted step had no surviving successor.")}},Ia={appUrls:y("Dashboard URLs for relevant Sequenzy resources."),url:p("Primary dashboard URL for this result."),settingsUrl:p("Company settings URL when available."),subscriptionUrl:p("Owner-facing subscription, upgrade, and billing-management URL when available.")},ka={success:ue,message:j,note:Dn,warnings:{type:"array",description:"Non-fatal cautions about content, permissions, or follow-up actions.",items:p("One warning.")},items:{type:"array",description:"Fallback array wrapper used only when a tool returns a bare array.",items:y("One returned item.")},value:y("Fallback object wrapper used only when a tool returns a non-object value.")},Sa={get_account:{account:h("account"),companies:k("company"),apiKeyPermissions:y("Current API key preset and scopes, whether common marketing work is discoverable, any missing marketing read scopes, `canSendLive` plus `missingLiveDeliveryScopes` (delivery this key cannot perform, e.g. `transactional:send` for `send_email`; check before composing anything meant to be sent) `liveDeliveryBlockedByRole` (a viewer role blocks sending no matter the scopes, so widening the key will not help), `roleRestrictedScopes` (scopes the workspace role cannot use through a personal key - a marketer lists `transactional:send` here while still able to send campaigns), and the API Keys management URL."),currentCompanyId:p("Company ID selected by the authenticated API key, when available."),selectedCompanyId:p("Company ID selected locally for subsequent MCP calls, when available.")},select_company:{companyId:p("Selected company ID."),companyName:p("Selected company name.")},get_app_urls:{dashboard:p("Company dashboard URL."),account:p("Company account URL."),subscription:p("Owner-facing subscription, upgrade, and billing-management URL."),settings:p("Company settings URL."),campaign:p("Campaign editor URL."),landingPage:p("Landing page editor URL."),sequence:p("Sequence editor URL."),email:p("Email editor URL."),transactionalEmail:p("Transactional email URL."),emailSend:p("Sent email detail URL."),domain:p("Sending domain settings URL."),urls:y("All generated URLs keyed by resource type.")},create_company:{company:h("company"),autoSelected:v("Whether the new company was selected for subsequent MCP calls.")},update_company:{company:h("company")},get_company:{company:h("company")},get_sync_rules:{syncRules:{type:"array",description:"Effective sync rules for the company.",items:y("One sync rule.")},isDefault:v("Whether the company uses the inherited SaaS/ecommerce platform preset.")},update_sync_rules:{syncRules:{type:"array",description:"Effective sync rules after the update.",items:y("One sync rule.")},isDefault:v("Whether the company now uses the inherited SaaS/ecommerce platform preset.")},get_email_design_system:{designSystem:y("The effective email design system parsed from the direction text: designCode (visual grammar tokens), compositionSpine, and source (derived | custom)."),directionText:{type:["string","null"],description:"The raw emailDesignPrompt direction text the tokens were parsed from; null when the company has none yet."},isDefault:v("True while the identity is purely derived from brand context.")},update_email_design_system:{message:j,designSystem:y("The email design system now in effect after the update or reset."),directionText:{type:["string","null"],description:"The rewritten direction text now stored on the company; null after a reset."},isDefault:v("True when the resulting identity is the pure brand-derived one - after an explicit reset, or when an adjustment resolved to the derived defaults.")},get_shopify_automation_settings:{browseAbandonment:y("Effective browse-abandonment settings (defaults applied)."),cartAbandonment:y("Effective cart-abandonment settings (defaults applied)."),priceDrop:y("Effective price-drop settings (defaults applied)."),shopDomain:p("Connected Shopify store domain.")},update_shopify_automation_settings:{browseAbandonment:y("Effective browse-abandonment settings after the update."),cartAbandonment:y("Effective cart-abandonment settings after the update."),priceDrop:y("Effective price-drop settings after the update."),shopDomain:p("Connected Shopify store domain.")},create_api_key:{apiKey:y("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:p("Newly created API key if the API response uses the short key field.")},request_api_key_handoff:{handoff:y("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:p("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:p("One step in the handoff.")}},list_api_keys:{apiKeys:k("non-secret API key metadata, including ID, name, prefix, permissions, timestamps, and active-credential status")},update_api_key:{apiKey:h("updated non-secret API key metadata, including the `scopes` now in effect (null when the key has full access)")},revoke_api_key:{apiKey:h("revoked non-secret API key metadata")},delete_api_key:{apiKey:h("deleted non-secret API key metadata")},list_websites:{websites:k("sending domain, including DNS verification and readyToSend sending readiness")},list_integrations:{integrations:k("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:y("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:Y("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:N("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:p("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:p("Event name never seen account-wide.")},activity:y("Webhook and sync activity over the last 24 hours: totals by status, stalled count, last activity time, and recent failures."),ingestion:y("What this integration does to the contact list: bulkSyncEnabled, supportsListTargeting, listTargeting (`company_default`, `none`, `specific`, or null when the provider ignores targeting), listIds (null means the workspace default lists), lists with their names, missingListIds for configured lists that have since been deleted and are therefore skipped, and a summary. When supportsListTargeting is false, the summary names defaultSubscriberListIds on get_company/update_company as the live-ingestion write path (null = every list, [] = none) and identifies provider-specific backfill exceptions such as PostHog history imports. Neither setting stops the provider's live webhook creating contacts."),pixel:Y("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:N("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:p("Available action id.")}},list_integration_capabilities:{providers:k("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?, fields? }. `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; a field's own `fields` holds the shape of an object field, such as a repeat block's `productSource`.",items:y("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:y("Single-type mode: the full reference for the requested type, including a minimal valid `example` and authoring `notes`."),conditionFields:{type:"array",description:'The per-field table for block conditions - the `conditions` array every block takes, and the `conditions` of a `conditional-group`. Present when listing every type, when the requested type is `conditional-group`, and when conditionFields: true was passed; otherwise `conditionFieldsHint` says how to ask for it. Each entry is { field, label, operators, values?, valueFormat, serverEvaluated, previewSupport, example }. `operators` is the only set that field accepts: the `field` and `operator` enums inside a block\'s own reference pool every field\'s operators together, so they show `is` for `tag` even though a tag condition is rejected with it. `valueFormat` gives the shape of the value string, which differs per field ("attributeName:value" for attribute, a tag name for tag, an id for segment, "eventName:timeRange" for event). `serverEvaluated` marks the fields read from stored subscriber state rather than from the send\'s merge data, and `previewSupport` says what render_email needs before it can evaluate one: "any_contact", "inline_tags_or_stored_subscriber" (tag), or "stored_subscriber". A condition a render cannot evaluate is not an error - it renders as false and is listed in that render\'s unevaluatedConditions.',items:y("One condition field: its allowed operators, value format, and what a preview needs to evaluate it.")},conditionFieldsHint:{type:"string",description:"Present on a single-type response that omitted `conditionFields`, saying that conditions are per-field and how to get the table. The table is several times the size of one block type's reference, so a targeted lookup does not carry it unless conditions are that type's purpose or you asked for it."}},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:y("An event: eventName, documented, label, category, description, documentedProviders, and (single-event mode) providers, mergeTagPrefix, and notes.")},note:Dn},list_integration_activity:{activity:k("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:Dn},connect_integration:{integration:{type:"object",description:"The connected integration: id, provider, name, providerAccountId, sync state, and safe (non-credential) details."},webhookUrl:p("URL to configure in the provider's webhook settings with the same secret. Empty for Attio, which is outbound-only. For other providers, always relay this to the user - delivery does not start until it is configured."),revenueSyncQueued:v("Payment providers only: whether the initial revenue backfill was queued."),backfillQueued:v("Affonso only: whether the affiliate backfill was queued."),history:{type:"object",description:"PostHog and Segment 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:p("The integration that was updated."),provider:p("Provider of the updated integration."),syncEnabled:v("Bulk import and backfill state after the update. This is not the provider's live webhook, which keeps creating contacts either way."),listTargeting:q("Where contacts created by this integration land: `company_default`, `none`, or `specific`. Null for providers that ignore per-integration list targeting."),listIds:Cs("Configured target lists. Null means new contacts follow the workspace default lists.",p("List ID.")),changed:v("False when the integration was already in the requested state."),changedFields:{type:"array",description:"Which controls actually moved.",items:p("Field name.")},message:j},set_integration_list_targeting:{integrationId:p("The integration that was updated."),provider:p("Provider of the updated integration."),syncEnabled:v("Bulk import and backfill state. Unchanged by this tool."),listTargeting:q("Where contacts created by this integration land after the update: `company_default`, `none`, or `specific`. Null for providers that ignore per-integration list targeting."),listIds:Cs("Configured target lists after the update. Null means new contacts follow the workspace default lists.",p("List ID.")),changed:v("False when the integration was already in the requested state."),changedFields:{type:"array",description:"Which controls actually moved.",items:p("Field name.")},message:j},get_integration_pixel:{integrationId:p("The Shopify integration inspected."),provider:p("Always `shopify`."),shopDomain:p("Store the pixel was read from."),pixel:y("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:p("Pixel-dependent event name.")},message:j},activate_integration_pixel:{integrationId:p("The Shopify integration updated."),provider:p("Always `shopify`."),shopDomain:p("Store the pixel was installed on."),pixel:y("Pixel state after activation."),changed:v("False when the pixel was already installed and reporting to this account."),created:v("True when a new pixel was installed."),updated:v("True when an existing pixel was repointed at this account."),dependentEvents:{type:"array",description:"Event names this pixel enables.",items:p("Pixel-dependent event name.")},message:j},sync_integration:{integrationId:p("The integration being synced."),provider:p("Provider of the synced integration."),jobId:q("Background job id for the queued sync, when one was created."),syncStatus:p("Sync status after queueing. Poll get_integration to watch it progress."),syncTarget:Y("For Supabase, the project ref, schema, and table the backfill reads. Absent for providers whose sync has no configurable source."),message:j},get_attio_mapping:{integrationId:p("The Attio integration inspected."),provider:p("Always `attio`."),listMap:y("Saved Sequenzy list id → Attio list UUID or api slug. Empty when nothing is mapped."),mappedListCount:b("Number of saved mappings whose Sequenzy source and Attio target lists both still exist. Stale saved entries remain in listMap but are not counted. Zero means list joins are not synced."),syncCompanyFromDomain:v("Whether a company is upserted from the person's non-free-mail email domain."),sequenzyLists:{type:"array",description:"This company's Sequenzy lists (id and name).",items:y("A Sequenzy list: id and name.")},attioLists:{type:"array",description:"Attio people-lists the stored token can write, read live from Attio (id, apiSlug, name).",items:y("An Attio people-list: id, apiSlug, and name.")},message:j},update_attio_settings:{integrationId:p("The Attio integration updated."),provider:p("Always `attio`."),listMap:y("Saved Sequenzy list id → Attio list UUID or api slug after the update."),mappedListCount:b("Number of saved mappings whose Sequenzy source and Attio target lists both still exist after the update. Stale preserved entries are not counted."),syncCompanyFromDomain:v("Whether company matching from work-email domains is on after the update."),sequenzyLists:{type:"array",description:"This company's Sequenzy lists (id and name).",items:y("A Sequenzy list: id and name.")},attioLists:{type:"array",description:"Attio people-lists the stored token can write, read live from Attio (id, apiSlug, name).",items:y("An Attio people-list: id, apiSlug, and name.")},changed:v("False when the integration was already in the requested state."),changedFields:{type:"array",description:"Which settings actually moved: listMap and/or syncCompanyFromDomain.",items:p("Field name.")},message:j},list_web_tracking_keys:{success:ue,keys:{type:"array",description:"Publishable keys for the browser tracking SDK, newest first. A key with lastUsedAt null has not successfully authenticated an event yet; check deployment, instrumentation or traffic, and the origin allowlist.",items:y("One key: id, name, publicKey, allowedOrigins, isActive, unrestricted, lastUsedAt, installSnippet, endpoint, and warning when unrestricted.")}},get_web_tracking_key:{success:ue,key:y("The key, including the paste-ready installSnippet and the ingest endpoint.")},create_web_tracking_key:{success:ue,key:y("The created key. installSnippet is the exact HTML snippet to paste into every page; it embeds both the publishable key and the workspace id and queues calls made while the async SDK loads."),message:j},update_web_tracking_key:{success:ue,key:y("The key after the update.")},delete_web_tracking_key:{success:ue,message:j},list_sender_profiles:{senderProfiles:k("sender (From) profile, including the sending domain behind it, its DNS verification status, and whether the address is fully ready to send"),replyProfiles:k("reply-to profile"),defaultSenderProfileId:q("Company default sender profile ID. Null when no default is set."),defaultReplyProfileId:q("Company default reply-to profile ID. Null when no default is set.")},update_sender_profile:{senderProfile:h("renamed sender (From) profile, present when type was sender"),replyProfile:h("renamed reply-to profile, present when type was reply"),renamed:v("False when the profile already carried that name, so nothing changed.")},delete_sender_profile:{success:ue,deletedSenderProfileId:p("ID of the sender profile that was permanently deleted."),fallbackSenderProfileId:q("Remaining sender profile selected for the account default and eligible draft campaigns when reassignment was needed."),message:j},get_notification_preferences:{notificationPreferences:N("One entry per notification event with its current mode: off, instant, daily, or weekly. Every event is always present; an event the user has never configured reports the platform default."),supportedModes:y("Modes each event accepts, keyed by event. form_submitted and campaign_completed do not accept daily; weekly_report accepts only off or weekly."),defaults:y("Mode each event uses when the user has never configured it, resolved for their role: the workspace owner defaults to weekly_report 'weekly', invited members to 'off'.")},update_notification_preferences:{notificationPreferences:N("Every notification event with its mode after the update, not only the events that were changed."),supportedModes:y("Modes each event accepts, keyed by event. form_submitted and campaign_completed do not accept daily; weekly_report accepts only off or weekly."),defaults:y("Mode each event uses when the user has never configured it, resolved for their role: the workspace owner defaults to weekly_report 'weekly', invited members to 'off'.")},get_sending_status:{status:p("Company-level sending state: active, paused, or suspended. Anything other than active blocks every send, including test sends."),pauseReason:q("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:q("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:q("ISO timestamp when sending was paused. Null when sending is active."),selfResume:y("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:Y("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:y("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:y("Ordered steps for the current state, plus supportEmail, docsUrl, and the dashboard URL. Relay these verbatim instead of improvising recovery advice.")},resume_sending:{resumed:v("True when this call restored sending. False when sending was already active."),message:j,status:p("Sending state after the request. active on success."),selfResume:y("Self-resume state after the request, including the automated review status and how many gates remain."),metricsWindow:y("Enforcement watermarks after the resume. bounceResetAt moves to now, so the paused rate is recalculated from later sends."),remediation:y("Steps to keep sending healthy after the resume, plus supportEmail and docsUrl.")},get_tracking_settings:{tracking:y("Account-wide open/click flags, transactionalOpenTrackingEnabled and transactionalClickTrackingEnabled defaults for Transactional API sends, unsubscribe tracking, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours."),consent:y("Signup consent settings: doubleOptInEnabled, doubleOptInEmailId for the confirmation email sent to pending contacts (null when double opt-in has never been enabled), and doubleOptInRedirectUrl for where the hosted confirmation page sends subscribers after confirming (null keeps them on the branded confirmation page)."),autoUtm:y("Automatic UTM tagging state and its configured parameters."),trackingDomain:Y("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:y("Inbound reply tracking configuration.")},update_tracking_settings:{message:j,tracking:y("Account-wide open/click flags, transactionalOpenTrackingEnabled and transactionalClickTrackingEnabled defaults for Transactional API sends, unsubscribe tracking, the opt-in strictBotFilteringEnabled bot-detection flag, plus the default attribution window in hours, after the update."),consent:y("Signup consent settings after the update: doubleOptInEnabled, doubleOptInEmailId for the confirmation email (provisioned automatically the first time double opt-in is enabled), and doubleOptInRedirectUrl for the post-confirmation redirect (null keeps subscribers on the branded confirmation page)."),autoUtm:y("Automatic UTM tagging state and its configured parameters, after the update."),trackingDomain:Y("Dedicated click-tracking domain with verification and SSL status. Null when click links use the shared Sequenzy tracking domain."),replyTracking:y("Inbound reply tracking configuration. Unchanged by this tool; set it with update_company.")},add_website:{website:h("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},add_sending_domain:{website:h("Sending domain with its cohort-specific DNS records. Publish every returned record, including DMARC when present.")},check_website:{website:h("sending domain with separate DNS verification and readyToSend sending readiness; readiness.reason explains a domain that cannot send yet"),ready:v("Whether the sender website is ready."),status:p("Current processing or verification status.")},verify_sending_domain:{website:h("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:v("Whether the sending domain passed the fresh DNS verification check. Correct DNS alone does not mean the domain can send yet."),readyToSend:v("Whether DNS and the selected home transport are both ready for sending."),message:p("Verification result summary.")},get_integration_guide:{guide:h("integration guide"),code:p("Generated integration code or example."),steps:{type:"array",description:"Setup steps for the requested integration.",items:y("One setup step.")}},add_subscriber:{subscriber:h("subscriber")},create_subscriber_import:{import:y(xs),deduplicated:v("Present and true when idempotencyKey matched an already-queued import. Nothing new was queued; `import` is the original import.")},get_subscriber_import:{import:y(xs)},update_subscriber:{subscriber:h("subscriber")},remove_subscriber:{subscriber:h("subscriber"),hardDeleted:v("Whether the subscriber was permanently deleted.")},get_subscriber:{subscriber:h("subscriber")},list_subscriber_notes:{notes:k("subscriber note")},add_subscriber_note:{note:h("subscriber note")},delete_subscriber_note:{id:p("Deleted subscriber note ID."),deleted:v("Whether the subscriber note was deleted.")},trigger_subscriber_event:{subscriber:h("subscriber"),event:h("Live event with its name and whether the event definition was created. Historical responses use `events` instead."),duplicate:v("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:v("Present and true when occurredAt selected the historical import path."),events:k("Historical events, each with id, name, and occurredAt."),inserted:b("Historical event rows inserted by this request."),duplicates:b("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:p("One failed side effect.")}},trigger_subscriber_events:{subscriber:h("subscriber"),events:k("recorded event")},import_subscriber_events:{total:b("Events submitted in this request."),recorded:b("Events recorded by this request."),duplicates:b("Events skipped because their eventId was already recorded."),failed:b("Events that failed to record."),sideEffectFailed:b("Receipt rows whose downstream side effects or historical automation shielding failed. This is orthogonal to receipt accounting and may accompany either a newly recorded or duplicate row during recovery."),subscribers:b("Distinct subscriber identities in the request."),failures:{type:"array",description:"Failed events by input index. Recorded events are kept, so treat an error as partial success and retry with the same eventIds.",items:{type:"object",description:"One failed event.",properties:{index:b("Index into the submitted events array."),error:p("Why this event failed.")}}},sideEffectFailures:{type:"array",description:"Post-write failures by input index. The receipt exists (new or duplicate); use the stages and optional error for recovery, then retry with the same eventId.",items:{type:"object",description:"One event receipt (new or duplicate) with failed downstream work.",properties:{index:b("Index into the submitted events array."),stages:{type:"array",description:"Downstream stages that failed.",items:{type:"string",description:"Failed stage name."}},error:p("Optional recovery guidance.")}}},error:p("The first row-level failure message when any event failed.")},bulk_add_subscriber_tags:{tags:{type:"array",description:"Normalized tag names applied to every matched subscriber.",items:p("One tag name.")},requested:b("Identifiers supplied in the request."),matched:b("Existing subscribers resolved."),updated:b("Subscribers whose tags actually changed."),unchanged:b("Subscribers that already carried every tag."),failed:b("Subscribers whose update failed."),notFound:y("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds. These subscribers were NOT created."),failures:k("per-subscriber failure (up to 50)"),triggeredAutomations:v("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:p("One tag name.")},requested:b("Identifiers supplied in the request."),matched:b("Existing subscribers resolved."),updated:b("Subscribers whose tags actually changed."),unchanged:b("Subscribers that did not carry any of the tags."),failed:b("Subscribers whose update failed."),notFound:y("Identifiers that did not resolve, grouped as emails, externalIds, and subscriberIds."),failures:k("per-subscriber failure (up to 50)")},search_subscribers:{subscribers:k("subscriber"),pagination:y("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:b("Number of subscribers returned."),truncated:v("Whether matches remain beyond the returned window. Same as pagination.hasMore.")},list_products:{products:k("product"),pagination:y("Pagination metadata: limit, offset, count (this page), total (whole catalog) and hasMore. Page with offset when hasMore is true.")},upsert_products:{products:k("product"),created:b("Number of products created."),updated:b("Number of products updated.")},delete_product:{productId:p("Deleted product ID.")},attach_product_file:{product:h("product"),delivery:h("digital delivery file")},remove_product_file:{product:h("product")},upload_image_asset:{asset:h("hosted image asset"),imageBlock:y("Ready-to-insert Sequenzy image block using the hosted asset URL.")},sync_products:{job:h("product sync job"),jobId:p("Queued product sync job ID.")},list_tags:{tags:k("tag")},create_tag:{tag:h("tag")},update_tag:{tag:h("tag")},delete_tag:{tagId:p("Deleted tag ID.")},list_lists:{lists:N("Subscriber lists. Each entry includes id, name, description, isPrivate, createdAt, subscriberCount (current members of any status), and activeSubscriberCount (current members with status=active). Memberships with unsubscribedAt set are excluded.")},create_list:{list:h("list")},update_list:{list:h("list")},delete_list:{listId:p("Deleted list ID.")},add_subscribers_to_list:{list:h("list"),added:b("Number of subscribers added to the list."),skipped:b("Number of subscribers skipped.")},remove_subscribers_from_list:{list:h("list"),removed:b("Number of subscribers removed from the list."),skipped:b("Number of subscribers skipped.")},list_segments:{segments:k("segment")},create_segment:{segment:h("segment")},update_segment:{segment:h("segment")},delete_segment:{segmentId:p("Deleted segment ID.")},get_segment_count:{count:b("Number of subscribers matching the segment."),segmentId:p("Segment ID that was counted.")},list_audience_syncs:{audienceSyncs:k("audience sync")},list_ad_accounts:{adAccounts:k("ad account")},create_audience_sync:{audienceSync:h("audience sync")},update_audience_sync:{audienceSync:h("audience sync")},delete_audience_sync:{audienceSyncId:p("Deleted audience sync ID.")},sync_audience_now:{audienceSync:h("audience sync"),job:h("audience sync job"),jobId:p("Queued audience sync job ID.")},list_templates:{templates:k("email template"),pagination:y("Pagination metadata: limit, offset, count (this page), total (every email body) and hasMore. Page with offset when hasMore is true.")},get_template:{template:h("email template")},create_template:{template:h("email template")},update_template:{template:h("email template")},set_template_localization:{templateId:p("Localized template ID."),localization:h("template localization")},sync_template_localizations:{templateId:p("Template ID queued for localization."),queuedLocales:{type:"array",description:"Locale codes queued for AI translation.",items:p("One queued locale code.")},queuedVariantCount:b("Number of localized variants queued for translation.")},delete_template:{templateId:p("Deleted template ID.")},list_email_components:{components:k("email component")},get_email_component:{component:h("email component")},get_default_email_component:{component:h("default email component for the slot")},set_default_email_component:{component:h("saved default email component")},create_email_component:{component:h("email component")},update_email_component:{component:h("email component")},delete_email_component:{id:p("Deleted email component ID.")},list_ab_tests:{abTests:k("A/B test")},get_ab_test:{abTest:h("A/B test")},get_ab_test_stats:{abTest:h("A/B test"),stats:h("A/B test statistics")},restart_ab_test:{abTest:h("A/B test")},select_ab_test_winner:{abTest:h("A/B test with the selected winner")},update_ab_test_variant:{abTest:h("A/B test"),variant:h("A/B test variant")},update_ab_test:{abTest:h("A/B test")},create_ab_test:{abTest:h("A/B test")},add_ab_test_variant:{abTest:h("A/B test"),variant:h("A/B test variant")},delete_ab_test_variant:{abTest:h("A/B test"),variantId:p("Deleted A/B test variant ID.")},delete_ab_test:{abTestId:p("Deleted A/B test ID.")},list_campaigns:{campaigns:N(`List of campaign records returned by Sequenzy. ${Yt}`),pagination:y("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:y(`The campaign record returned by Sequenzy. ${Yt}`)},get_campaign_audience:{campaignId:p("Campaign the audience was resolved for."),campaignName:p("Campaign name."),status:p("Campaign status."),audience:y("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:b("Number of subscribers matching the effective targeting right now."),targetLists:Y("Raw stored targeting exactly as persisted on the campaign. Null when targeting has never been set.")},get_email_send:{emailSend:h("email send, including copied-recipient identity and primary email send ID when applicable"),events:k("email delivery event")},list_email_sends:{emailSends:k("email send"),pagination:h("email send pagination"),retentionDays:b("Number of days sent-email rows remain queryable in this collection.")},list_recipient_suppressions:{suppressions:k("suppressed recipient, with suppressionType, reason, scope and whether it can be removed"),total:b("Total suppressed recipients matching the filter."),page:b("1-based page number returned."),limit:b("Entries per page."),hasMore:v("Whether another page is available."),sortBy:p("Sort field actually applied: suppressedAt, email or status. An unrecognized `sort` falls back to suppressedAt, so read this rather than assuming the requested order took effect."),sortOrder:p("Sort direction applied: asc or desc.")},get_recipient_suppression:{suppression:h("recipient suppression status")},remove_recipient_suppression:{removed:v("Whether a workspace soft-bounce escalation was removed."),removedLocalBounce:v("Whether the workspace-local soft-bounce escalation was removed."),removedSesRegions:{type:"array",description:"Always empty. Sequenzy suppresses solely from its own bounce table and neither reads nor writes the email provider's suppression list. Retained for response compatibility.",items:p("Unused; this array is always empty.")},remainingSuppression:h("recipient suppression status after cleanup")},create_campaign:{campaign:h("campaign")},update_campaign:{campaign:h("campaign")},schedule_campaign:{campaign:h("campaign"),scheduledAt:p("Scheduled send timestamp.")},unschedule_campaign:{campaign:h("draft campaign")},share_campaign:{shareUrl:p("Public anonymized view-in-browser URL for the campaign."),shareToken:p("Capability token embedded in the URL."),created:v("False when an already-active link was returned instead of minted.")},unshare_campaign:{revoked:v("False when the campaign had no active public link.")},share_template:{shareUrl:p("Public anonymized view-in-browser URL for the email."),shareToken:p("Capability token embedded in the URL."),created:v("False when an already-active link was returned instead of minted.")},unshare_template:{revoked:v("False when the email had no active public link.")},send_test_email:{emailSendId:p("Durable test email delivery ID."),recipientEmail:p("Test email recipient.")},send_test_sms:{smsSendId:p("Created test SMS send ID."),toPhone:p("Normalized E.164 destination phone.")},update_sms_number_label:{number:h("updated SMS number (label + brandPrefix override)")},release_sms_number:{number:h("released SMS number (id + status)")},cancel_campaign:{campaign:h("campaign")},pause_campaign:{campaign:h("campaign")},resume_campaign:{campaign:h("campaign")},delete_campaign:{campaignId:p("Deleted campaign ID.")},duplicate_campaign:{campaign:h("duplicated campaign")},resend_campaign_to_non_openers:{campaign:h("non-opener resend draft campaign"),estimatedNonOpenerCount:b("Estimated number of subscribers who haven't opened the original campaign.")},list_forms:{forms:k("saved form")},create_form:{form:h("saved form"),embed:y("Public action URL plus JavaScript, native form, and fetch snippets.")},update_form:{form:h("saved form"),embed:y("Public action URL plus JavaScript, native form, and fetch snippets (published forms only).")},get_form_embed:{form:h("saved form"),embed:y("Public action URL plus JavaScript, native form, and fetch snippets.")},list_popups:{popups:k("saved popup")},get_popup:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},create_popup:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},update_popup:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets (published popups only).")},get_popup_embed:{popup:h("saved popup"),embed:y("Script URL plus HTML, React, WordPress, and Shopify snippets.")},duplicate_popup:{popup:h("popup copy, created as a draft")},delete_popup:{popupId:p("Deleted popup ID.")},list_landing_pages:{landingPages:k("landing page")},get_landing_page:{landingPage:h("landing page")},get_landing_page_stats:{stats:y("Landing page analytics for the requested window: visits, uniqueVisits, clicks, subscribes, conversionRate (subscribes / uniqueVisits), botVisits, dataAvailableFrom, a daily histogram, referrers, and UTM sources. Default counts exclude known crawlers. Preview URLs and the editor are never counted.")},render_landing_page:{previewUrl:p("Signed, unlisted visitor-facing preview of the current page content. Works for drafts. Not indexed. Share this URL to review layout and copy without publishing."),publicUrl:q("Public visitor URL, or null until the page is published."),landingPageId:p("Landing page ID."),name:p("Landing page name."),status:p("draft or published. Drafts are only visible at previewUrl."),published:v("Whether the page is live on publicUrl. False for drafts."),title:p("Visitor-facing title from SEO metadata or the first heading.")},create_landing_page:{landingPage:h("landing page")},update_landing_page:{landingPage:h("landing page")},duplicate_landing_page:{landingPage:h("landing page")},delete_landing_page:{landingPageId:p("Deleted landing page ID.")},publish_landing_page:{landingPage:h("landing page")},unpublish_landing_page:{landingPage:h("landing page")},connect_landing_page_domain:{landingPage:h("landing page"),domain:p("Connected landing page domain.")},update_landing_page_domain_settings:{landingPage:h("landing page"),domain:p("Landing page domain.")},remove_landing_page_domain:{domain:h("landing page domain state")},list_sequences:{sequences:va,pagination:y("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:me},list_sequence_enrollments:{sequenceId:p("Sequence ID these enrollments belong to."),sequenceName:p("Sequence name."),statuses:{type:"array",description:"Enrollment statuses included in this response. Defaults to active and waiting.",items:{type:"string",description:"Enrollment status."}},stopCondition:y("The sequence's single configured stop condition: `type` (`none` when unset), `value`, and nullable `matchConfig` containing event-property filters, a field comparison, or entry_audience resolution. For entry_audience, value is null and audience identifies the enrolling tag or list resolved per contact. Stop conditions are re-evaluated when an enrollment next runs a step, not when their event arrives."),stopConditionMatchEvaluatedCount:b("How many enrollments in this page were actually evaluated for a current stop-condition match. 0 when stopConditionMatch was not requested, the sequence has no stop condition, or no returned enrollment was still active or waiting."),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:p("Enrollment token ID. Stable identifier for this one run through the sequence."),sequenceId:p("Sequence ID."),subscriberId:p("Subscriber ID."),email:q("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:q("Subscriber first name, or null when unset."),lastName:q("Subscriber last name, or null when unset."),subscriberStatus:q("Subscriber status (active, unsubscribed, bounced), or null when the subscriber record no longer exists."),status:p("Enrollment status: active, waiting, completed, failed, or cancelled."),currentNodeId:p("Sequence node this enrollment is currently sitting on."),currentNodeType:p("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:p("Current sequence node label or email subject when available."),currentNodeMissing:v("Whether the current node no longer exists in the sequence graph."),enrollmentKey:p("Key that distinguishes concurrent enrollments of the same subscriber in this sequence."),enrollmentStartedAt:p("ISO 8601 timestamp when this enrollment entered the sequence."),waitUntil:q("ISO 8601 timestamp this enrollment is scheduled to resume, or null when nothing is scheduled."),lastUpdatedAt:p("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:q("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:q("Step this enrollment was released from by move_sequence_enrollments, or null when it reached its current step on its own."),movedAt:q("ISO 8601 timestamp of that release, or null when the enrollment was never moved."),moveReason:q("Note recorded with that release, or null when none was given."),stopConditionMatches:wa("Whether the sequence's stop condition matches for this contact right now. Null when it was not determined: stopConditionMatch was not requested, the sequence has no stop condition, this enrollment is no longer active or waiting, or it fell outside the evaluated window. Null never means `does not match`. This is a non-atomic snapshot: the worker re-checks before a future step, but the condition can change and a step already past its stop check may still finish."),stopConditionMatchReason:q("Human-readable reason the stop condition matches, such as the stop event or tag that satisfied it. Null when stopConditionMatches is not true."),enteredVia:{type:"object",description:"What put this contact into the sequence. Use this to distinguish which list or tag matched a multi-value trigger.",properties:{kind:p("Entry source kind: list, tag, segment, event, inactivity, frequency, manual, test_run, or unknown."),value:q("Raw list ID, tag name, segment ID, event name, or monitored event name. Null for manual, test_run, and unknown."),name:q("Resolved display name for list and segment sources, or null when not applicable or deleted."),description:p("Ready-to-display description of the entry source.")},required:["kind","value","name","description"],additionalProperties:!0},entryContext:{type:"object",description:"Event or manual-enrollment context captured at entry. Property keys only; values are never returned.",properties:{triggerType:q("Stored entryTriggerType, such as event_received or manual_enrollment. Null when never stamped."),eventId:q("Durable ID of the enrolling event, or null."),eventName:q("Enrolling event name, or null."),hasEventProperties:v("Whether any event property keys were stored on this enrollment."),eventPropertyKeys:{type:"array",description:"Keys present on the enrolling event payload. Values are omitted.",items:{type:"string",description:"Event property key."}},hasFieldSnapshots:v("Whether subscriber field snapshots were stored at enrollment."),fieldSnapshotKeys:{type:"array",description:"Subscriber field paths snapshotted at enrollment. Values are omitted.",items:{type:"string",description:"Field path."}}},additionalProperties:!0},branchDecisions:{type:"array",description:"Bounded redacted if/else and random-split verdicts, oldest first within the retained window. Compared values are summaries (missing, empty, nonempty, equals_expected), never the raw field or event-property value. Empty on enrollments recorded before this field existed; use get_sequence_enrollment to reconstruct those from ClickHouse.",items:y("One branch or condition decision, including selectedPath and per-branch evaluations.")},branchDecisionCount:b("Total branch and condition decisions taken, including decisions omitted from the bounded array."),branchDecisionsTruncated:v("Whether older decisions were omitted from branchDecisions.")},required:["enrollmentId","sequenceId","subscriberId","status","currentNodeId","currentNodeMissing","enrollmentStartedAt"]}},pagination:y("Pagination metadata.")},get_sequence_enrollment:{sequenceId:p("Sequence ID."),sequenceName:p("Sequence name."),stopCondition:y("The sequence's single configured stop condition."),enrollment:y("The enrollment token: enteredVia, entryContext (event keys, never values), and branchDecisions (redacted)."),nodeHistory:N("ClickHouse graph-walk events for this token, oldest first. Each item may include a redacted branchDecision reconstructed from stored metadata when the token itself has none."),nodeHistoryTruncated:v("Whether additional node events exist beyond the returned bounded history."),nodeHistoryLimit:b("Maximum number of node events returned."),historySource:p("Where the branch history came from: node_events, token_context, both, or none.")},simulate_sequence:{sequenceId:p("Sequence ID."),sequenceName:p("Sequence name."),status:p("Stored sequence status."),sendsMail:v("Always false. Simulation never sends mail or enrolls anyone."),enrollment:y("Who currently matches and the confirmation that nobody is auto-enrolled on activate. List, tag, and segment matches can still be enrolled by hand."),readiness:y("Activation checks: ready, errors that should be fixed before enable_sequence, and non-blocking warnings."),path:Y("Walked graph for the optional stored subscriber, including branch verdicts, emailStepsOnPath (traversed email nodes), and emailsOnPath (emails deliverable for the subscriber's current email/status). Null when no subscriberId or email was passed.")},send_sequence_test_email:{sequenceId:p("Sequence ID."),nodeId:p("Tested sequence email-step node ID."),results:N("Per-recipient test-send results containing recipientEmail, durable emailSendId, and legacy jobId.")},create_sequence:{sequence:me,eventTrackingCode:p("Ready-to-adapt code for sending a custom trigger event, including any matching-field property."),eventTracking:y("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:p("One required event name.")}},update_sequence:{sequence:Rs},update_sequence_node:{sequence:h("sequence")},update_sequence_nodes:{sequence:h("sequence")},edit_sequence_graph:{sequence:Rs},insert_sequence_step:{sequence:h("sequence"),insertedNodeIds:{type:"array",description:"Node IDs created for a linear inserted step, including any delay or wait-for-event node.",items:p("Inserted automation node ID.")},insertedEmailIds:{type:"array",description:"Email template IDs created for the inserted step.",items:p("Inserted email template ID.")},insertedEmailCount:b("Number of email steps inserted."),addedBranchNodeId:p("New logic_branch node ID when the inserted step is a branch."),addedBranchPathNodeIds:y("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:p("Sequence ID."),status:p("Stored lifecycle status after the change."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...ht},disable_sequence:{sequenceId:p("Sequence ID."),status:p("Stored lifecycle status after the change."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...ht},duplicate_sequence:{sequence:me,nodes:k("sequence node"),edges:k("sequence edge")},archive_sequence:{sequence:me},unarchive_sequence:{sequence:me},list_campaign_goals:{goals:k("campaign goal")},create_campaign_goal:{goal:h("campaign goal")},update_campaign_goal:{goal:h("campaign goal")},delete_campaign_goal:{goalId:p("Deleted campaign goal ID.")},list_sequence_goals:{goals:k("sequence goal")},create_sequence_goal:{goal:h("sequence goal")},update_sequence_goal:{goal:h("sequence goal")},delete_sequence_goal:{goalId:p("Deleted sequence goal ID.")},get_sequence_inbound_webhook:{webhook:h("sequence inbound webhook")},configure_sequence_inbound_webhook:{webhook:h("sequence inbound webhook")},rotate_sequence_inbound_webhook_secret:{webhook:h("sequence inbound webhook")},pause_sequence_enrollments:{sequenceId:p("Sequence ID."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...ht},resume_sequence_enrollments:{sequenceId:p("Sequence ID."),enrollmentPaused:v("Whether new sequence enrollments are paused."),...ht},enroll_subscribers_in_sequence:{sequence:h("sequence"),enrollments:k("sequence enrollment"),enrolled:b("Number of subscribers enrolled."),skipped:b("Number of subscribers skipped.")},cancel_sequence_enrollments:{sequenceId:p("Sequence ID."),dryRun:v("Whether this call only reported matches instead of cancelling them."),target:y("Resolved cancellation target: mode all, subscriber, subscribers (with notFoundSubscriberIds), or field."),matchedCount:b("Active/waiting enrollments matching the target when the request started."),cancelledCount:b("Enrollments cancelled by this call."),remainingCount:b("Enrollments still matching after this call. Repeat the same request while this is above zero."),enrollments:k("sequence enrollment sample (up to 50)"),hasMore:v("Whether more enrollments matched than the returned sample.")},move_sequence_enrollments:{sequenceId:p("Sequence ID."),dryRun:v("Whether this call only reported the batch instead of moving it."),fromNodeId:p("Step the enrollments were taken from."),targetNodeId:p("Step the enrollments were moved onto, resolved from the source step's next step when not supplied."),sort:p("Order the batch was selected in."),requestedLimit:b("limit as requested."),effectiveLimit:b("How many this call was allowed to move after the daily guardrail was applied."),matchedCount:b("Movable enrollments parked on fromNodeId when the request started."),movedCount:b("Enrollments moved by this call."),remainingCount:b("Movable enrollments still on fromNodeId. Repeat the same request while this is above zero."),skippedCount:b("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:Es("Applied daily guardrail, or null when none was requested."),movedInWindow:b("Moves onto targetNodeId already recorded in the rolling 24-hour window."),dailyRemaining:Es("How many more can be moved onto targetNodeId today, or null when no dailyLimit was requested."),enqueuedCount:b("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:y("One tokenId with its enqueue error.")},tagResult:Y("Tagging outcome for the moved contacts: tags, updated, unchanged, failed, failures. Null when no tags were requested."),enrollments:k("moved (or, on a dry run, would-move) sequence enrollment sample (up to 50)"),hasMore:v("Whether more enrollments matched than the returned sample.")},realign_sequence_enrollments:{sequenceId:p("Sequence ID."),dryRun:v("Whether this call only previewed the new wait times instead of writing them."),sendingWindow:Y("The sequence sending window realignment anchored on (timezone, startTime, endTime, days), or null when only per-step weekday gates applied."),scannedCount:b("Waiting enrollments inspected by this call."),realignedCount:b("Waiting enrollments moved earlier (or that would move, on a dry run)."),unchangedCount:b("Waiting enrollments left exactly as they were."),unchangedReasons:y("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:b("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:k("realigned enrollment sample (up to 50) with waitUntil, newWaitUntil, and movedEarlierMinutes"),hasMore:v("Whether a per-call cap stopped the scan early. Continue with nextCursor while this is true."),nextCursor:p("Opaque continuation cursor to pass as cursor on the next call when hasMore is true."),status:p("For an applied request, queued while the background job is pending."),jobId:p("Background job ID to pass to get_sequence_enrollment_realignment.")},get_sequence_enrollment_realignment:{sequenceId:p("Sequence ID."),dryRun:v("Always false for an applied job."),status:p("queued, running, completed, or failed."),jobId:p("Background realignment job ID."),result:Y("Completed realignment result, including counts, changes, hasMore, and nextCursor; null until completion."),error:q("Safe recovery guidance when the job failed, otherwise null.")},delete_sequence:{sequenceId:p("Deleted sequence ID.")},list_transactional_emails:{transactional:k("transactional email with subject, all-time delivery metrics, and dashboard URL")},get_transactional_email:{transactional:h("transactional email")},create_transactional_email:{transactional:h("transactional email")},update_transactional_email:{transactional:h("transactional email")},delete_transactional_email:{deleted:y("Deleted transactional email: id, slug, name, and emailId of the email content that was kept as a reusable template.")},send_email:{emailSendId:p("Durable email delivery ID."),emailType:{type:"string",enum:["marketing","transactional"],description:"Delivery policy accepted for the queued email."},to:{type:["string","array"],items:p("One accepted To address."),description:"Accepted primary recipients, lowercased. A string for a single-recipient send, an array when several addresses share the email."},cc:{type:"array",items:p("One accepted Cc address."),description:"Accepted carbon-copy recipients, lowercased, with addresses already in `to` removed. Present only when the send has cc recipients."},bcc:{type:"array",items:p("One accepted Bcc address."),description:"Accepted blind-carbon-copy recipients, lowercased, with addresses already in `to` or `cc` removed. Present only when the send has bcc recipients."},transactional:h("transactional email")},get_stats:{stats:y(`Account-wide delivery funnel for the requested window. ${oe}`),emailType:p("Applied structural email type filter when one was requested."),subscriberCount:b("Live count of every stored contact in the company. Independent of period. Use this for 'how many subscribers do I have'."),activeSubscriberCount:b("Live count of contacts with status=active. Independent of period. May include phone-only contacts without an email address."),commerceForecast:h("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:h("campaign"),stats:y(`Delivery funnel for this campaign. ${oe}`),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:y("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. ${se} 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:y("One poll or NPS results summary.")},recommendations:y("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."),goals:{type:"array",description:"Conversion goals attached to this campaign, in creation order. Each entry has goalId, name, conversions attributed to this campaign, and trackedValue in minor units. Present only when the campaign has attached goals. Zero-conversion goals are included so the report can show the full funnel.",items:y("One campaign goal with goalId/name/conversions/trackedValue.")}},list_poll_responses:{campaignId:p("Campaign the responses belong to."),blockId:p("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:y("One respondent's latest answer.")},pagination:y("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:h("transactional email"),stats:y(`Delivery funnel for this transactional email. ${oe}`),complaints:h("complaint count and rate for the selected transactional email"),clickedLinks:k("clicked link with click count and percentage share"),bounceBreakdown:h("permanent, transient, and undetermined bounce counts plus subtype details"),engagementBreakdown:h("human and machine open and click counts")},get_sequence_stats:{sequence:me,stats:y(`Delivery funnel across every email step in this sequence. ${oe}`),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. ${oe}`,items:{type:"object",description:"Metrics for one email step of the sequence.",properties:{step:b("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:p("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:q("Subject line of the step's email, falling back to the node label, or null when neither is set."),stats:y(`Delivery funnel for this step alone: sent, delivered, bounced, opened, clicked, replies, unsubscribed, and their rates. ${oe}`),failedCount:b("Contacts currently stuck on this step with a failed enrollment."),failedSubscribers:N("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:b("Active enrollment count."),waiting:b("Waiting enrollment count."),total:b("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:p("Current sequence node ID."),currentNodeType:p("Current sequence node type. Omitted when the node no longer exists in the graph."),currentNodeLabel:p("Current sequence node label or email subject when available."),currentNodeMissing:v("Whether the current node no longer exists in the sequence graph."),active:b("Active enrollment count at this node."),waiting:b("Waiting enrollment count at this node."),total:b("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:b("Total skipped sequence enrollments."),byReason:{type:"object",description:"Skipped enrollment counts keyed by reason, such as unsubscribed or bounced.",additionalProperties:b("Skipped enrollment count for this reason.")}},required:["count","byReason"],additionalProperties:!1},recommendations:y("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:k("campaign email event"),pagination:y("Pagination metadata.")},list_sequence_events:{events:k("sequence email event"),pagination:y("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:p("Stable identifier: the campaign ID for campaigns, the automation node ID for sequence emails."),name:p("Campaign name, or the sequence step's subject line falling back to its node label."),campaignId:q("Campaign ID, or null for sequence emails."),sequenceId:q("Sequence ID, or null for campaigns."),sequenceName:q("Name of the sequence this step belongs to, or null for campaigns."),automationNodeId:q("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:y(`Delivery funnel for this email alone. ${oe}`),conversions:b("Attributed conversions credited to this email."),revenueCents:b("Attributed revenue in minor currency units credited to this email.")},required:["emailType","emailId","name","stats"],additionalProperties:!0}},totals:y(`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". ${oe}`),pagination:y("Pagination metadata."),sort:p("Sort field the response was ordered by."),order:p("Sort order the response was ordered by."),step:b("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:p("Sequence ID.")}},get_subscriber_activity:{activity:k("subscriber activity event"),subscribers:k("subscriber"),pagination:y("Pagination metadata.")},list_team_members:{members:k("team member"),invitations:k("team invitation")},invite_team_member:{invitation:h("team invitation")},cancel_team_invitation:{invitationId:p("Cancelled invitation ID.")},list_conversations:{conversations:k("inbox conversation"),pagination:y("Pagination metadata.")},get_conversation:{conversation:h("inbox conversation"),messages:k("conversation message")},reply_to_conversation:{conversation:h("inbox conversation"),message:h("conversation message")},update_conversation_status:{conversation:h("inbox conversation")},mark_conversation_read:{conversation:h("inbox conversation")},list_webhooks:{webhooks:k("outbound webhook")},create_webhook:{webhook:h("outbound webhook")},update_webhook:{webhook:h("outbound webhook")},delete_webhook:{webhookId:p("Deleted outbound webhook ID.")},test_webhook:{webhook:h("outbound webhook"),delivery:h("test webhook delivery")},list_webhook_deliveries:{deliveries:k("webhook delivery")},replay_webhook_delivery:{delivery:h("webhook delivery"),job:h("webhook replay job")},generate_email:{email:h("generated email"),html:p("Generated HTML email body."),blocks:{type:"array",description:"Generated Sequenzy email blocks, wrapped with company branding (logo + footer) unless applyBranding was false.",items:y("One generated email block.")},subject:p("Generated subject line."),previewText:p("Generated inbox preview text.")},generate_sequence:{sequence:h("persisted AI-generated sequence draft"),deprecated:v("Always true for this deprecated alias."),deprecationMessage:p("Migration guidance directing callers to create_sequence.")},generate_subject_lines:{subjectLines:{type:"array",description:"Generated subject line variants.",items:p("One generated subject line.")},variants:k("generated subject line variant")},generate_sms:{prompt:p("The prompt the messages were generated for."),messages:{type:"array",description:"Generated SMS message variants with encoding and segment counts.",items:y("One generated SMS message.")}},get_sms_settings:{sms:y("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).")},get_sms_usage:{usage:N("Per-number SMS usage entries: fromNumber (E.164), totalSends, delivered, failed, creditsCharged, lastSentAt, testSends. Totals exclude test sends; test sends are counted separately.")},submit_feedback:{},render_email:{html:p("Email-safe HTML document, rendered exactly as it would be sent."),subject:p("Subject line with merge tags resolved."),previewText:q("Inbox preview text with merge tags resolved, or null when unset."),locale:p("Localization locale the render resolved to."),personalized:v("Whether a real contact was supplied. False means a sample contact was used, so contact-specific merge tags resolve to empty values."),trackingApplied:v("Whether auto-UTM link decoration was applied."),unresolvedMergeTags:N(`Merge tags that did not resolve, 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. An unknown name is reported even when a default filter such as {{ subscriber.frstName | default: "there" }} supplied text in its place: the fallback then reaches every recipient, including the ones whose real value is stored, and the rendered HTML looks correct precisely because the default worked. A recognized name that is merely blank for this contact is not reported when it has a default, since that is what a default is for. 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.`),unevaluatedConditions:N('Block conditions this render could not decide, as [{ field, operator, value, description, reason, hint }]. Each was rendered as false, the same fail-closed rule a live send uses, so an else branch in the HTML is not evidence that the condition is false for a real recipient - checking the HTML alone cannot tell the two apart. reason "requires_stored_subscriber" means the field reads stored subscriber state: pass subscriberId, or for a `tag` condition pass tags on the inline subscriber, and it resolves. reason "invalid_filter" means the stored condition is malformed, which fails closed on a real send too, and hint carries the validation error. reason "evaluation_failed" means the lookup itself failed and the render is worth retrying. An empty array means every condition in the email was actually evaluated.'),entity:y("Which entity was rendered: type, id, and variantId.")}};function Ta(t){let e=Sa[t];if(e===void 0)throw Error(`MCP tool "${t}" must define outputSchema properties.`);return{type:"object",description:`Structured content returned by the \`${t}\` MCP tool.`,properties:{...ka,...e,...xn.has(t)?Ia:{}},additionalProperties:!0}}function Ds(t){return{...t,outputSchema:Ta(t.name)}}function Os(t){if(I(t))return t;if(Array.isArray(t))return{items:t};return{value:t}}var Us=[{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, localization sync status, and settings. Sequence action_ab_test steps also expose each variant's blocks on get_sequence.sequence.emails[].abTest.variants; use this tool when you need the full test record rather than copy alone. Pass the abTestId from get_sequence.",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:F},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:"select_ab_test_winner",description:"Select a winner for a campaign A/B test that is currently testing and queue the winning variant for the remaining audience. This starts external email delivery.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},abTestId:{type:"string",description:"Campaign A/B test ID"},variantId:{type:"string",description:"Winning variant ID"}},required:["abTestId","variantId"],additionalProperties:!1}},{name:"update_ab_test_variant",description:"Update an A/B test variant, including the email body of a sequence step whose nodeType is action_ab_test - that content cannot be edited through update_sequence_node or update_template, and a change meant for the whole step has to be repeated on every variant. Take abTestId and variantId from get_sequence.sequence.emails[].abTest.variants (or get_ab_test). If this tool is not in the MCP tool list, enable it on the Sequenzy connector rather than writing through another email tool. 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. ${A}`},blocks:{type:"array",description:`${Q}${de} 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. A conversion moves that step's copy off the sequence node and onto the test's variants: from then on update_sequence_node cannot edit its subject, previewText, or blocks, and every content change has to be applied per variant with update_ab_test_variant (get_ab_test lists them). The response echoes this in contentEditing.",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:`${Q}${de}`,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:`${Q}${de}`,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 js=[{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:
4
4
  1. Call select_company first to choose which company to work with, OR
5
5
  2. Pass companyId explicitly in each tool call
6
6
 
7
- 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, company settings, or subscription. The response always includes the canonical owner-facing subscription URL when a company is resolved. For compatibility, settingsTab billing or subscription also resolves to that Account page rather than a nonexistent Settings tab. 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. The billing and subscription aliases return the canonical Account -> Subscription page."}}}},{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, effective email localization settings, and the read-only emailBranding entitlement. emailBranding says whether "Sent with Sequenzy" is visible, whether the owner subscription removes it, why, the current tier/status, the required upgrade or renewal action, and the canonical subscriptionUrl. Branding is injected at render/send time rather than stored in footer blocks, so a paid entitlement removes it from future sends by existing live sequences without editing their emails. Also returns defaultSubscriberListIds - the workspace default lists new contacts join when nothing targets them explicitly. A JSON null means every current and future list, not an empty selection; [] means no list at all; an array means exactly those lists. Change it with update_company. Read it before connecting an integration whose provider has no per-integration list targeting (Dodo Payments, PostHog, Polar, Paddle, and similar), because its live contacts and payment-provider backfills land there. PostHog history imports are different: contacts created by that import have no list memberships. ${le}`,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, account-wide sending identity defaults, and defaultSubscriberListIds - which lists new untargeted contacts join. That field is the write path for Dodo Payments and live PostHog events, plus every other integration without per-integration targeting: null = every current and future list (not 'no lists'), [] = no list, [ids] = exactly those lists. PostHog history imports always create contacts without list memberships. 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, reply-tracking, and defaultSubscriberListIds 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. To restyle one sequence email instead, patch that step's emailTheme with update_sequence_node.",properties:Et,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."},defaultSubscriberListIds:{type:["array","null"],items:{type:"string"},description:"Which lists new contacts join when something creates a subscriber without explicit list targeting - forms, API writes, events, tag actions, imports, and every integration that does not carry its own targeting. The three states are distinct: null means every current and future list, [] means no list at all, and a populated array means exactly those lists. Repointing this changes only later writes; nobody is moved or removed retroactively. This is the setting that decides where an integration's backfill lands when the provider has no per-integration targeting of its own, so check it with get_company before connecting a store. Unknown list IDs are rejected. In the dashboard it lives under Contacts -> Lists -> Default Lists. Requires the companies:manage scope."}}}},{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)."},expireAfterHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Hours after which an untouched tracked cart is dropped instead of being emailed about or merged into by a later add (default 72). A store can empty a cart without sending a removal - a session or reservation timing out, an inventory hold releasing, checkout finishing on another device - and past this window the cart is no longer treated as evidence the shopper still has those items. Set it below delayHours for stores whose carts expire faster than the abandonment delay; those carts are then intentionally never emailed about."}},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:"get_email_design_system",description:"Get the company's email design system: the visual identity every AI-generated email (campaigns and sequence steps) renders inside - design code (kicker style, title alignment, button shape, divider style, density, sanctioned opener treatments) plus the composition spine (hero-led | editorial | product-spec) that anchors email structure. The identity is stored as the company's emailDesignPrompt direction text; this tool returns the structured tokens parsed from that text (falling back to brand derivation per unstated token), the raw directionText, and isDefault (true while the identity is still purely derived from brand context).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_email_design_system",description:"Adjust the company's email design system (partial update - only pass the fields to change). Affects every future AI-generated email and sequence enrichment. designCode tokens: kickerStyle (chip | letterspaced | none), titleAlignment (left | center), buttonShape (rounded | pill), dividerStyle (line | space), density (airy | compact), openerTreatments (subset of hero-image, hero-color, header-hero, editorial-masthead, title-led). compositionSpine: hero-led | editorial | product-spec. The adjustment is written into the company's emailDesignPrompt direction text (the single source of truth): the new identity's sentences are prepended and any custom prose the text carried is preserved below them. Pass reset: true to clear the direction text and return to brand-derived defaults. Free-form prose edits belong on update_company's emailDesignPrompt instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},designCode:{type:"object",description:"Partial visual grammar adjustment; omitted tokens keep their current value.",properties:{kickerStyle:{type:"string",enum:["chip","letterspaced","none"],description:"How eyebrows above titles render: soft badge chips, letter-spaced uppercase text, or none."},titleAlignment:{type:"string",enum:["left","center"]},buttonShape:{type:"string",enum:["rounded","pill"]},dividerStyle:{type:"string",enum:["line","space"],description:"Thin divider lines between sections, or whitespace only."},density:{type:"string",enum:["airy","compact"]},openerTreatments:{type:"array",items:{type:"string",enum:["hero-image","hero-color","header-hero","editorial-masthead","title-led"]},description:"The opener treatments this company's emails may use, primary first."}},additionalProperties:!1},compositionSpine:{type:"string",enum:["hero-led","editorial","product-spec"],description:"Which worked-example skeleton anchors generation: designed marketing sections, typography-first editorial, or information-dense product/spec."},reset:{type:"boolean",description:"true clears the direction text and returns to brand-derived defaults. Cannot be combined with designCode or compositionSpine."}},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.
7
+ 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, company settings, or subscription. The response always includes the canonical owner-facing subscription URL when a company is resolved. For compatibility, settingsTab billing or subscription also resolves to that Account page rather than a nonexistent Settings tab. 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. The billing and subscription aliases return the canonical Account -> Subscription page."}}}},{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, effective email localization settings, and the read-only emailBranding entitlement. emailBranding says whether "Sent with Sequenzy" is visible, whether the owner subscription removes it, why, the current tier/status, the required upgrade or renewal action, and the canonical subscriptionUrl. Branding is injected at render/send time rather than stored in footer blocks, so a paid entitlement removes it from future sends by existing live sequences without editing their emails. Also returns defaultSubscriberListIds - the workspace default lists new contacts join when nothing targets them explicitly. A JSON null means every current and future list, not an empty selection; [] means no list at all; an array means exactly those lists. Change it with update_company. Read it before connecting an integration whose provider has no per-integration list targeting (Dodo Payments, PostHog, Polar, Paddle, and similar), because its live contacts and payment-provider backfills land there. PostHog history imports are different: contacts created by that import have no list memberships. ${pe}`,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, account-wide sending identity defaults, and defaultSubscriberListIds - which lists new untargeted contacts join. That field is the write path for Dodo Payments and live PostHog events, plus every other integration without per-integration targeting: null = every current and future list (not 'no lists'), [] = no list, [ids] = exactly those lists. PostHog history imports always create contacts without list memberships. 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, reply-tracking, and defaultSubscriberListIds 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. To restyle one sequence email instead, patch that step's emailTheme with update_sequence_node.",properties:Jt,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."},defaultSubscriberListIds:{type:["array","null"],items:{type:"string"},description:"Which lists new contacts join when something creates a subscriber without explicit list targeting - forms, API writes, events, tag actions, imports, and every integration that does not carry its own targeting. The three states are distinct: null means every current and future list, [] means no list at all, and a populated array means exactly those lists. Repointing this changes only later writes; nobody is moved or removed retroactively. This is the setting that decides where an integration's backfill lands when the provider has no per-integration targeting of its own, so check it with get_company before connecting a store. Unknown list IDs are rejected. In the dashboard it lives under Contacts -> Lists -> Default Lists. Requires the companies:manage scope."}}}},{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)."},expireAfterHours:{type:"number",exclusiveMinimum:0,maximum:720,description:"Hours after which an untouched tracked cart is dropped instead of being emailed about or merged into by a later add (default 72). A store can empty a cart without sending a removal - a session or reservation timing out, an inventory hold releasing, checkout finishing on another device - and past this window the cart is no longer treated as evidence the shopper still has those items. Set it below delayHours for stores whose carts expire faster than the abandonment delay; those carts are then intentionally never emailed about."}},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:"get_email_design_system",description:"Get the company's email design system: the visual identity every AI-generated email (campaigns and sequence steps) renders inside - design code (kicker style, title alignment, button shape, divider style, density, sanctioned opener treatments) plus the composition spine (hero-led | editorial | product-spec) that anchors email structure. The identity is stored as the company's emailDesignPrompt direction text; this tool returns the structured tokens parsed from that text (falling back to brand derivation per unstated token), the raw directionText, and isDefault (true while the identity is still purely derived from brand context).",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},additionalProperties:!1}},{name:"update_email_design_system",description:"Adjust the company's email design system (partial update - only pass the fields to change). Affects every future AI-generated email and sequence enrichment. designCode tokens: kickerStyle (chip | letterspaced | none), titleAlignment (left | center), buttonShape (rounded | pill), dividerStyle (line | space), density (airy | compact), openerTreatments (subset of hero-image, hero-color, header-hero, editorial-masthead, title-led). compositionSpine: hero-led | editorial | product-spec. The adjustment is written into the company's emailDesignPrompt direction text (the single source of truth): the new identity's sentences are prepended and any custom prose the text carried is preserved below them. Pass reset: true to clear the direction text and return to brand-derived defaults. Free-form prose edits belong on update_company's emailDesignPrompt instead.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},designCode:{type:"object",description:"Partial visual grammar adjustment; omitted tokens keep their current value.",properties:{kickerStyle:{type:"string",enum:["chip","letterspaced","none"],description:"How eyebrows above titles render: soft badge chips, letter-spaced uppercase text, or none."},titleAlignment:{type:"string",enum:["left","center"]},buttonShape:{type:"string",enum:["rounded","pill"]},dividerStyle:{type:"string",enum:["line","space"],description:"Thin divider lines between sections, or whitespace only."},density:{type:"string",enum:["airy","compact"]},openerTreatments:{type:"array",items:{type:"string",enum:["hero-image","hero-color","header-hero","editorial-masthead","title-led"]},description:"The opener treatments this company's emails may use, primary first."}},additionalProperties:!1},compositionSpine:{type:"string",enum:["hero-led","editorial","product-spec"],description:"Which worked-example skeleton anchors generation: designed marketing sections, typography-first editorial, or information-dense product/spec."},reset:{type:"boolean",description:"true clears the direction text and returns to brand-derived defaults. Cannot be combined with designCode or compositionSpine."}},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:"delete_sender_profile",description:"Permanently delete one sender (From) profile. This cannot be undone. Deletion is refused when this is the company's last sender or when a live campaign, active sequence (including a step-level override), or transactional email still uses it. Draft and rejected campaigns plus the account default are reassigned to the best remaining sender when needed; read fallbackSenderProfileId in the result and review that identity before sending. Reply-to profiles are not supported by this tool. Get the profile ID from list_sender_profiles. Requires the companies:manage scope.",inputSchema:{type:"object",properties:{profileId:{type:"string",description:"Sender (From) profile ID to delete, from senderProfiles in list_sender_profiles."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["profileId"]}},{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.
8
8
 
9
9
  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.
10
10
 
11
11
  IMPORTANT - there is no rolling window and no expiry. Enforcement uses all-time totals counted from a reset watermark, so a paused rate does NOT decay over time. Waiting does not restore sending. The rate only changes as real (non-test) sends accumulate or when a resume moves the watermark. Read \`metricsWindow\` for the exact watermark timestamps rather than telling the user to wait it out.
12
12
 
13
- Requires the account:read scope, so a read-only key can diagnose a blocked account. Use resume_sending once the underlying problem is fixed.`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"resume_sending",description:"Request that paused company-level sending be restored after fixing the cause. This is the supported remediation path for an account paused by the permanent-bounce rate limit - it is not a bypass and it never removes suppressions.\n\nOnly proceed when the bad source is actually fixed (import, form, or integration) and permanent bounces remain suppressed. Call get_sending_status first: for a paused workspace, resume only restores sending when `selfResume.canSelfResume` is true, which requires a hard-bounce pause reason, a cleared automated sender-health review, and no admin block. A workspace that is already active succeeds as an idempotent no-op with `resumed: false`; any other blocked state needs a support review, and the error tells you which one.\n\nYou MUST pass listSanitizationConfirmed: true, and you should only pass it after the user has confirmed the remediation - it is recorded on the account's audit trail as their statement that the list is clean. On success, sending is restored, the bounce watermark resets so the rate is recalculated from later sends, and the service attempts to requeue paused campaigns plus due sequence steps. Relay the response message: it contains support guidance if part of that queue handoff is temporarily unavailable.\n\nRequires the companies:manage scope and owner or admin access to the company.",inputSchema:{type:"object",properties:{listSanitizationConfirmed:{type:"boolean",description:"Must be true. Confirms the user has fixed the source of the invalid addresses and left every permanent bounce suppressed. Recorded on the account audit trail."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["listSanitizationConfirmed"]}},{name:"get_tracking_settings",description:"Get the company's email tracking and signup consent configuration: account-wide and Transactional API open/click defaults, unsubscribe tracking, opt-in strict bot filtering, default attribution window, automatic UTM tagging, the dedicated click-tracking domain and its verification status, inbound reply-tracking settings, and whether double opt-in is required for new contacts. Use this to audit measurement readiness, to explain why opens or clicks may not be recorded, and to check how contacts enter the list before investigating bot or alias signups.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_tracking_settings",description:"Update the company's email tracking defaults: account-wide open and click tracking, narrower open and click defaults for Transactional API sends, unsubscribe tracking, opt-in strict bot filtering, the default attribution window, and automatic UTM tagging, plus the account-wide double opt-in requirement for new contacts. Applies to emails sent afterwards; already-sent emails keep the links they were rendered with. Transactional API defaults cannot enable an account-wide setting that is off, and an individual send may opt out again. Provide at least one field. Reply tracking (inbound email, reply domain mode, reply forwarding) is on update_company, and the dedicated click-tracking domain is configured in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},openTrackingEnabled:{type:"boolean",description:"Whether to embed the open-tracking pixel. Turning this off also stops open rates from being recorded."},clickTrackingEnabled:{type:"boolean",description:"Whether to rewrite links through the click-tracking redirect. Turning this off stops click rates and click-based automation triggers."},transactionalOpenTrackingEnabled:{type:"boolean",description:"Whether Transactional API sends include the open-tracking pixel by default. This cannot enable opens when openTrackingEnabled is false; individual sends may still opt out."},transactionalClickTrackingEnabled:{type:"boolean",description:"Whether Transactional API sends rewrite links for click tracking by default. This cannot enable clicks when clickTrackingEnabled is false; individual sends may still opt out."},strictBotFilteringEnabled:{type:"boolean",description:"Opt in to aggressive bot detection: strict user-agent patterns, datacenter-IP classification, and cross-send IP sweeps. Off by default because it can also discard real engagement, lowering reported open and click rates. Enable it when the audience sits behind email-security appliances that inflate engagement."},unsubscribeTrackingEnabled:{type:"boolean",description:"Whether unsubscribe links are attributed to the email that produced them. Unsubscribe links keep working either way."},defaultAttributionWindowHours:{type:"number",description:"Default revenue attribution window in hours (1-720). Used by goals and revenue reporting when no per-goal window is set."},doubleOptInEnabled:{type:"boolean",description:"Require email confirmation before a new contact becomes subscribed. When on, contacts added by forms, the API, and integrations start pending and receive a confirmation email; they only become active after clicking it, and they are never sent marketing email while pending. This is the account-wide default that the per-write optInMode on add_subscriber overrides. Use it to stop bot and alias signups from landing in the list as active contacts. Enabling it requires a sender profile and provisions the confirmation email automatically if the account has none; it does not retroactively unsubscribe existing active contacts."},doubleOptInRedirectUrl:{type:["string","null"],description:"Where the hosted confirmation page sends subscribers after they confirm - typically a branded thank-you or welcome page on the company's own site. Must be an http(s) URL; a bare domain is normalized to https. Pass null to clear it, which keeps subscribers on the hosted confirmation page (branded with the company's name, logo, and colors)."},autoUtmEnabled:{type:"boolean",description:"Whether to append UTM parameters to outgoing links automatically. Enabling this with no stored parameters seeds the platform defaults."},autoUtmSettings:{type:["object","null"],description:"UTM templates to merge over the stored ones: source, medium, campaign, content, term. Values support placeholders such as {{email.subject}} and {{link.text}}. Pass null for a single parameter to stop emitting it, or null for the whole object to reset every parameter to the defaults.",properties:{source:{type:["string","null"]},medium:{type:["string","null"]},campaign:{type:["string","null"]},content:{type:["string","null"]},term:{type:["string","null"]}}}}}},{name:"get_notification_preferences",description:"Get the account notification settings for the API key's own user in this company: whether Sequenzy emails them when a new subscriber joins, when a form is submitted, when a campaign finishes sending, and whether they get the Monday weekly report (last week's sends, engagement, new subscribers, revenue, goals, and sequence trends versus the week before; on by default, only sent for weeks with more than 10 emails sent), and whether each arrives per-occurrence, as a daily summary, or weekly. Instant form-submission notifications stop after 50 per workspace per UTC day. Returns the supported modes and platform defaults alongside the current values. These are per-person settings - this never reads a teammate's preferences.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_notification_preferences",description:"Change which account notifications Sequenzy emails the API key's own user for this company. Requires the companies:manage scope. Useful before a bulk import or a large migration, when per-signup notifications would otherwise flood the inbox, or to turn the Monday weekly report off. Modes are 'off', 'instant' (one email per occurrence), 'daily' (one summary per day), and 'weekly' (the Monday report); 'daily' is only valid for new_subscriber, because a campaign finishes once and each form submit is its own lead, and 'weekly' is only valid for weekly_report. Instant form-submission notifications stop after 50 per workspace per UTC day. New-subscriber notifications already fall back to a daily summary automatically on high-volume days, and imports never trigger them at all.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},notificationPreferences:{type:"array",description:"Preferences to set. Events not listed keep their current value.",items:{type:"object",properties:{event:{type:"string",enum:["new_subscriber","form_submitted","campaign_completed","weekly_report"],description:"Which notification to configure."},mode:{type:"string",enum:["off","instant","daily","weekly"],description:"How to receive it. 'daily' is not supported for form_submitted or campaign_completed. weekly_report accepts only 'off' or 'weekly'."}},required:["event","mode"]}}},required:["notificationPreferences"]}},{name:"get_integration_guide",description:`Get code examples for integrating Sequenzy into your project.
13
+ Requires the account:read scope, so a read-only key can diagnose a blocked account. Use resume_sending once the underlying problem is fixed.`,inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"resume_sending",description:"Request that paused company-level sending be restored after fixing the cause. This is the supported remediation path for an account paused by the permanent-bounce rate limit - it is not a bypass and it never removes suppressions.\n\nOnly proceed when the bad source is actually fixed (import, form, or integration) and permanent bounces remain suppressed. Call get_sending_status first: for a paused workspace, resume only restores sending when `selfResume.canSelfResume` is true, which requires a hard-bounce pause reason, a cleared automated sender-health review, and no admin block. A workspace that is already active succeeds as an idempotent no-op with `resumed: false`; any other blocked state needs a support review, and the error tells you which one.\n\nYou MUST pass listSanitizationConfirmed: true, and you should only pass it after the user has confirmed the remediation - it is recorded on the account's audit trail as their statement that the list is clean. On success, sending is restored, the bounce watermark resets so the rate is recalculated from later sends, and the service attempts to requeue paused campaigns plus due sequence steps. Relay the response message: it contains support guidance if part of that queue handoff is temporarily unavailable.\n\nRequires the companies:manage scope and owner or admin access to the company.",inputSchema:{type:"object",properties:{listSanitizationConfirmed:{type:"boolean",description:"Must be true. Confirms the user has fixed the source of the invalid addresses and left every permanent bounce suppressed. Recorded on the account audit trail."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["listSanitizationConfirmed"]}},{name:"get_tracking_settings",description:"Get the company's email tracking and signup consent configuration: account-wide and Transactional API open/click defaults, unsubscribe tracking, opt-in strict bot filtering, default attribution window, automatic UTM tagging, the dedicated click-tracking domain and its verification status, inbound reply-tracking settings, and whether double opt-in is required for new contacts. Use this to audit measurement readiness, to explain why opens or clicks may not be recorded, and to check how contacts enter the list before investigating bot or alias signups.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_tracking_settings",description:"Update the company's email tracking defaults: account-wide open and click tracking, narrower open and click defaults for Transactional API sends, unsubscribe tracking, opt-in strict bot filtering, the default attribution window, and automatic UTM tagging, plus the account-wide double opt-in requirement for new contacts. Applies to emails sent afterwards; already-sent emails keep the links they were rendered with. Transactional API defaults cannot enable an account-wide setting that is off, and an individual send may opt out again. Provide at least one field. Reply tracking (inbound email, reply domain mode, reply forwarding) is on update_company, and the dedicated click-tracking domain is configured in the dashboard.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},openTrackingEnabled:{type:"boolean",description:"Whether to embed the open-tracking pixel. Turning this off also stops open rates from being recorded."},clickTrackingEnabled:{type:"boolean",description:"Whether to rewrite links through the click-tracking redirect. Turning this off stops click rates and click-based automation triggers."},transactionalOpenTrackingEnabled:{type:"boolean",description:"Whether Transactional API sends include the open-tracking pixel by default. This cannot enable opens when openTrackingEnabled is false; individual sends may still opt out."},transactionalClickTrackingEnabled:{type:"boolean",description:"Whether Transactional API sends rewrite links for click tracking by default. This cannot enable clicks when clickTrackingEnabled is false; individual sends may still opt out."},strictBotFilteringEnabled:{type:"boolean",description:"Opt in to aggressive bot detection: strict user-agent patterns, datacenter-IP classification, and cross-send IP sweeps. Off by default because it can also discard real engagement, lowering reported open and click rates. Enable it when the audience sits behind email-security appliances that inflate engagement."},unsubscribeTrackingEnabled:{type:"boolean",description:"Whether unsubscribe links are attributed to the email that produced them. Unsubscribe links keep working either way."},defaultAttributionWindowHours:{type:"number",description:"Default revenue attribution window in hours (1-720). Used by goals and revenue reporting when no per-goal window is set."},doubleOptInEnabled:{type:"boolean",description:"Require email confirmation before a new contact becomes subscribed. When on, contacts added by forms, the API, and integrations start pending and receive a confirmation email; they only become active after clicking it, and they are never sent marketing email while pending. This is the account-wide default that the per-write optInMode on add_subscriber overrides. Use it to stop bot and alias signups from landing in the list as active contacts. Enabling it requires a sender profile and provisions the confirmation email automatically if the account has none; it does not retroactively unsubscribe existing active contacts."},doubleOptInRedirectUrl:{type:["string","null"],description:"Where the hosted confirmation page sends subscribers after they confirm - typically a branded thank-you or welcome page on the company's own site. Must be an http(s) URL; a bare domain is normalized to https. Pass null to clear it, which keeps subscribers on the hosted confirmation page (branded with the company's name, logo, and colors)."},autoUtmEnabled:{type:"boolean",description:"Whether to append UTM parameters to outgoing links automatically. Enabling this with no stored parameters seeds the platform defaults."},autoUtmSettings:{type:["object","null"],description:"UTM templates to merge over the stored ones: source, medium, campaign, content, term. Values support placeholders such as {{email.subject}} and {{link.text}}. Pass null for a single parameter to stop emitting it, or null for the whole object to reset every parameter to the defaults.",properties:{source:{type:["string","null"]},medium:{type:["string","null"]},campaign:{type:["string","null"]},content:{type:["string","null"]},term:{type:["string","null"]}}}}}},{name:"get_notification_preferences",description:"Get the account notification settings for the API key's own user in this company: whether Sequenzy emails them when a new subscriber joins, when a form is submitted, when a campaign finishes sending, and whether they get the Monday weekly report (last week's sends, engagement, new subscribers, revenue, goals, and sequence trends versus the week before; on by default for the workspace owner, off by default for invited members, only sent for weeks with more than 10 emails sent), and whether each arrives per-occurrence, as a daily summary, or weekly. Instant form-submission notifications stop after 50 per workspace per UTC day. Returns the supported modes and the platform defaults for this user's role alongside the current values. These are per-person settings - this never reads a teammate's preferences.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}}}},{name:"update_notification_preferences",description:"Change which account notifications Sequenzy emails the API key's own user for this company. Requires the companies:manage scope. Useful before a bulk import or a large migration, when per-signup notifications would otherwise flood the inbox, or to turn the Monday weekly report off (it is on by default only for the workspace owner; invited members set weekly_report to 'weekly' to receive it). Modes are 'off', 'instant' (one email per occurrence), 'daily' (one summary per day), and 'weekly' (the Monday report); 'daily' is only valid for new_subscriber, because a campaign finishes once and each form submit is its own lead, and 'weekly' is only valid for weekly_report. Instant form-submission notifications stop after 50 per workspace per UTC day. New-subscriber notifications already fall back to a daily summary automatically on high-volume days, and imports never trigger them at all.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},notificationPreferences:{type:"array",description:"Preferences to set. Events not listed keep their current value.",items:{type:"object",properties:{event:{type:"string",enum:["new_subscriber","form_submitted","campaign_completed","weekly_report"],description:"Which notification to configure."},mode:{type:"string",enum:["off","instant","daily","weekly"],description:"How to receive it. 'daily' is not supported for form_submitted or campaign_completed. weekly_report accepts only 'off' or 'weekly'."}},required:["event","mode"]}}},required:["notificationPreferences"]}},{name:"get_integration_guide",description:`Get code examples for integrating Sequenzy into your project.
14
14
 
15
15
  CRITICAL - FOR SAAS/SUBSCRIPTION APPS:
16
16
  If the app uses Stripe, Polar, Paddle, Dodo, or Creem - tell the user to connect it in Sequenzy dashboard (Settings → Integrations).
@@ -28,5 +28,5 @@ Use cases:
28
28
  - 'event_tracking': Tracking CUSTOM events only (not payment events - those come from the integration)
29
29
  - 'ecommerce': Connecting a custom e-commerce platform via the Commerce API (sync products, push orders/checkouts, power abandoned cart + back-in-stock automations)
30
30
 
31
- 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 Fi=[{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 guidance. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values (minimal, branded, promotional) are freeform prompt guidance. Defaults to the company's email style preference."},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:"get_sms_usage",description:"Get per-number SMS usage for the company: sends, delivered, failed, credits charged, last-sent time, and test-send count for each phone number the workspace has sent from. Use it to compare how the workspace's numbers are performing or to check what a number was used for before releasing it.",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:"release_sms_number",description:"Release an SMS number: hand it back to the carrier and mark it released. This is IRREVERSIBLE - the number cannot be recovered afterward, any campaign/sequence still explicitly set to send from it will SKIP its SMS sends until repointed at another number, and it stops counting toward the workspace's number limit (freeing a slot for a new purchase). Use get_sms_settings to find the number ID. 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."}},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 100 test sends per company per rolling 24 hours; 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."},fromNumberId:{type:"string",description:"Active SMS number ID to send from (see get_sms_settings). Defaults to the company's oldest active number - the same default real sends use."}},required:["to"]}}];var Hi=[{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. Also returns top-level subscriberCount (every stored contact) and activeSubscriberCount (status=active) as a live audience snapshot, independent of period; use these for 'how many subscribers do I have' instead of search_subscribers pagination.total. 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:L}}},{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:L},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), attached campaign conversion goals in the top-level goals array (sent → opened → clicked → each named goal), 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:L},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:L},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: ${De}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${De}. 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:L},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: ${De}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${De}. 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:L},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:L}}},{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:L},required:[]}}];var zi=[{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"]}}];var ot={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID."}},Bi={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change","tag_added"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},triggerTagName:{type:["string","null"],description:"Required tag name for tag_added goals, e.g. customer."},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."}},Wi=[{name:"list_campaign_goals",description:"List persisted conversion goals attached to one email campaign in the dashboard. SMS campaigns are not supported. Campaign goals are attributed to recipients who were sent that campaign (last-touch open/click still wins when the recipient engaged), and appear on the campaign report as named conversion steps after sent/opened/clicked.",inputSchema:{type:"object",properties:ot,required:["campaignId"],additionalProperties:!1}},{name:"create_campaign_goal",description:"Create a persisted event, subscriber-attribute, or tag-applied conversion goal for one email campaign. SMS campaigns are not supported. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath; tag_added goals require triggerTagName. Campaign goals are attributed to recipients who were sent the campaign (opens/clicks still win when present). Use this to measure outcomes such as signup or becoming a customer on a one-off campaign. Distinct from company-wide goals and from sequence goals.",inputSchema:{type:"object",properties:{...ot,...Bi},required:["campaignId","name"],additionalProperties:!1}},{name:"update_campaign_goal",description:"Update a persisted email-campaign conversion goal, including its signal, attribution window, or active state. SMS campaigns are not supported.",inputSchema:{type:"object",properties:{...ot,goalId:{type:"string",description:"Campaign goal ID."},...Bi},required:["campaignId","goalId"],additionalProperties:!1}},{name:"delete_campaign_goal",description:"Delete one persisted email-campaign conversion goal. SMS campaigns are not supported.",inputSchema:{type:"object",properties:{...ot,goalId:{type:"string",description:"Campaign goal ID."}},required:["campaignId","goalId"],additionalProperties:!1}}];function un(t,e){return{type:e?.nullable?["object","null"]:"object",description:t,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 Gi=[{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. ${On} 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. Change draft pacing with update_campaign, or apply it when calling schedule_campaign. ${le} 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. Successful live-test and other test sends are omitted so they do not bury real deliveries; only failed, bounced, or suppressed test sends appear. Replies to those test sends show in list_conversations only when inbound reply capture is enabled; otherwise the send uses the original Reply-To and Sequenzy never sees the reply.",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. Pass `emailPreset` with native blocks to set Style > Format (minimal or branded); `style` is a prompt-generation hint only. 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. ${R}`},blocks:{type:"array",description:M,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. Only used with `prompt`; this is not Style > Format. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values (minimal, branded, promotional) are freeform prompt guidance and the company's email style preference decides. Use `emailPreset` to set branded or minimal chrome on native blocks."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},emailPreset:xt,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:un("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:de},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:ce},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's content, audience, sending identity, labels, Style > Format, or delivery pacing. Pass emailPreset to change Style > Format on native blocks without rewriting copy. sendTimeOptimization and sendTimeWindowHours persist on the draft and are used when the campaign is later scheduled unless schedule_campaign overrides them. ${le}`,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. ${R}`},blocks:{type:"array",description:M,items:{type:"object"}},emailPreset:xt,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:ce},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:de},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:un("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"}},sendTimeOptimization:{type:"boolean",description:qt},sendTimeWindowHours:{type:"number",description:Tt}},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`. The campaign must have a non-empty subject, at least one content block, and at least one audience include rule. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Send Time Optimization (sendTimeOptimization) delivers each recipient at their predicted best hour within sendTimeWindowHours of scheduledAt (default 12h, max 24); it is campaign-only and is not available on sequences. spreadOverHours takes precedence and turns STO off; sendInRecipientTimezone also turns it off. Returns dashboard edit and preview URLs; validation errors explain what must be fixed before retrying.",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:un("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:qt},sendTimeWindowHours:{type:"number",description:Tt},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."},sendInRecipientTimezone:{type:"boolean",description:"Deliver at scheduledAt's wall-clock time in each recipient's own timezone ('send when it's 8pm for the customer'). Requires `scheduledTimezone`; contacts without a stored timezone receive the campaign at scheduledAt itself. Not combinable with `recurringInterval` or `spreadOverHours`."},scheduledTimezone:{type:"string",description:"IANA timezone the scheduledAt wall-clock time refers to, for example America/New_York. Required with `sendInRecipientTimezone`."},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, and never for imported already-sent campaigns (Sequenzy has no opens for a send it did not deliver). 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 Ki=[{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 and nested objects. 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. `group` is a persisted structural type managed by the editor and is omitted by creatableOnly; request it by name when reading existing grouped content. 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`. Every block also takes a `conditions` array, and each condition field accepts only its own operators - a block\'s own `field` and `operator` enums pool every field\'s operators together, so they list `is` for `tag` even though a tag condition is rejected with it. The `conditionFields` table resolves that: the operators each condition field accepts, how its `value` string is shaped, and what render_email needs before it can evaluate the condition rather than rendering it as false. It comes back automatically when you list every type and when you ask for `conditional-group`; on any other single type pass conditionFields: true, since the table is several times the size of one block\'s reference.',inputSchema:{type:"object",properties:{blockType:{type:"string",description:'A single block type to describe, for example "list", "steps", "text", "hero", or the structural "group" type. Omit to list every block type.'},creatableOnly:{type:"boolean",description:"Only list block types an author should hand-create, hiding structural types such as group that the editor manages. Ignored when blockType is set."},conditionFields:{type:"boolean",description:"Include the per-field condition table alongside a single blockType. Only needed when you are writing a `conditions` array on that type: listing every type already includes the table, and so does asking for `conditional-group`. Responses that omit it say so in `conditionFieldsHint`."}},required:[]}}];var Vi=[{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. ${M}`,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. ${M}`,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. ${M}`,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 Yi=[{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 Ji=[{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 Qi=[{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 globally unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Layout groups use { id, kind: "group", label, layout: "stack" | "row" | "grid" | "overlay", columns (1-4), gap (0-64), padding (0-64), overlayColor (hex), overlayPosition ("top" | "center" | "bottom"), overlayShade (0-100), children: [...] }. In Overlay, gap spaces foreground children while the direct image remains the background. Overlay needs exactly one direct image; images inside subgroups only enable Overlay for that subgroup, while zero or multiple direct images fall back to Stack. Groups may nest to three levels; descendants must use the same sectionId as their group, while form-step, success-screen, and error-state remain at the root. 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].children[0].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 Zi=[{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 Xi=[{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 es=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, segment, affonso, or attio. 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. Attio is outbound-only and has no webhookUrl. For every other connectable provider 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, segment, affonso, or attio.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","segment","affonso","attio"]},apiKey:{type:"string",description:"Provider API key. Required for polar, paddle, dodo, whop, creem, chargebee, affonso, and attio. Attio uses the workspace access token from Settings → Developers."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider except attio, which is outbound-only. For Chargebee, pass the webhook's basic-auth credentials as username:password. For segment, the secret is your own choice and must be 16-153 UTF-8 bytes."},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, segment, and affonso do not use one."},settings:{type:"object",description:"PostHog and Segment: event delivery scope. New Segment connections skip automatic page/screen calls unless those names are explicitly allowlisted. Attio: listMap (Sequenzy list id → Attio list id or slug) and syncCompanyFromDomain (default true).",properties:{syncAllEvents:{type:"boolean",description:"Sync every event the provider delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these event names. Set syncAllEvents to false when using this."},listMap:{type:"object",additionalProperties:{type:"string"},description:"Attio only. Optional map of Sequenzy list id to Attio people-list UUID or api slug. When omitted, connect first and configure mappings later with update_attio_settings — do not ask the user to re-paste the access token just to map lists."},syncCompanyFromDomain:{type:"boolean",description:"Attio only. When true, upsert a company from the person's non-free-mail email domain."}}},historyImport:{type:"object",description:"PostHog and Segment only: import event history after connecting. PostHog needs region + projectId + personalApiKey (query read access) and imports the project archive. Segment needs region + spaceId + profileApiToken (Unify Profile API) and imports each existing contact's recent profile history - the Profile API serves at most the last 14 days, and contacts without a Unify profile are skipped.",properties:{region:{type:"string",enum:["us","eu"],description:"Region hosting the data: the PostHog Cloud region, or the Segment workspace's deployment."},projectId:{type:"string",description:"PostHog only: numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog only: personal API key (phx_...)."},spaceId:{type:"string",description:"Segment only: Unify space ID (spa_...)."},profileApiToken:{type:"string",description:"Segment only: Profile API access token for the space."}},required:["region"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider"]}},{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. For Attio, `details.mappedListCount` 0 and an `attio_lists_unmapped` recommendation mean list joins are not synced — use get_attio_mapping then update_attio_settings; do not reconnect for that. 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, crm, 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 integration's future bulk imports and backfills on or off. THIS DOES NOT STOP AN INTEGRATION CREATING CONTACTS: disabling sync only pauses full imports and backfills, while the provider's live webhook keeps writing every new signup or customer as it happens. To change where those contacts land, use set_integration_list_targeting; to stop them arriving at all, the integration has to be disconnected from the dashboard. 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`. Requires an API key with the `integrations:manage` scope, which agent-safe keys deliberately do not carry - without it, report the dashboard path (Settings -> Integrations) instead of retrying.",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:"set_integration_list_targeting",description:"Choose which lists the contacts a connected integration creates join. This is the tool for 'stop this integration adding people to my marketing lists' - set_integration_sync_enabled only pauses bulk backfills and leaves the provider's live webhook writing. IMPORTANT SCOPE: this changes list membership only, and it takes effect on future provider writes. It does not stop contacts being created, does not stop their attributes syncing, does not stop sync-rule tags, and does not stop `contact_added` sequences using the default `any_contact` scope, which fire precisely because the contact joined no list. Explicit `any_list` and specific-list sequences require a matching membership and do not enroll a list-less contact. Nobody is ever removed from a list and nothing is applied retroactively. Provider behavior for existing contacts differs: Wix or Webflow submissions, Shopify customer updates, and Supabase resubscriptions can add an existing contact to the new target lists; Stripe applies targeting only when its webhook creates a subscriber. If the goal is to stop `any_contact` enrollments too, pair this tool with pause_sequence_enrollments on the affected sequences. Check get_integration first - `ingestion` reports the current targeting with list names, and `availableActions` says whether this provider honors set_list_targeting. Supported for Supabase, Stripe, Shopify, Wix, and Webflow. Dodo Payments, PostHog, Polar, Paddle, and other providers without that action reject this tool; their live contacts follow defaultSubscriberListIds on get_company/update_company instead (null = every list, [] = none), which is workspace-wide. PostHog history imports are an exception and create contacts without list memberships. Idempotent: asking for the current state succeeds with `changed: false`. Requires an API key with the `integrations:manage` scope, which agent-safe keys deliberately do not carry - without it, report the dashboard path (Settings -> Integrations) instead of retrying.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},listIds:{type:["array","null"],items:{type:"string"},description:"Lists that contacts created by this integration join from now on. `null` clears the choice so they follow the workspace default lists; `[]` means they join no list at all; a populated array means exactly those lists. Every ID must belong to this company."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","listIds"]}},{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 and Segment. 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 or Segment history import: it restarts from the beginning using the stored credentials, 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 history 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"]}},{name:"get_attio_mapping",description:"Inspect a connected Attio integration's list mapping: every Sequenzy list, every Attio people-list the stored token can write (id, api slug, name), the saved listMap, mappedListCount, and whether company matching from work-email domains is on. THIS IS THE TOOL FOR 'Attio is connected but mappedListCount is 0'. Call it before update_attio_settings so you have Attio list ids or slugs instead of asking the user to paste UUIDs. Reads Attio live on every call. Credentials are never returned. Attio only; other providers return a clear error. Check get_integration first — availableActions includes update_attio_settings when mapping can be saved without reconnecting.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Attio 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:"update_attio_settings",description:"Set which Sequenzy lists sync into which Attio people-lists on an already-connected Attio integration, using the stored access token. THIS DOES NOT REQUIRE THE SECRET AGAIN: do not call connect_integration just to change mappings, and do not ask the user for the Attio access token. listMap is a full replacement — pass the complete desired map, `{}` to unmap every list, or omit listMap to leave mappings unchanged. Unmapped Sequenzy lists are not synced. Optionally set syncCompanyFromDomain. Provide at least one field. Idempotent: asking for the current state succeeds with changed: false. Does not backfill people already on a list; add-only, so unmapping does not remove anyone from Attio. Check get_attio_mapping first for Sequenzy list ids and live Attio list ids/slugs. Attio only. Requires an API key with the `integrations:manage` scope, which agent-safe keys deliberately do not carry - without it, report the dashboard path (Settings -> Integrations -> Attio -> Map lists) instead of retrying.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Attio integration ID from list_integrations or get_integration."},listMap:{type:"object",additionalProperties:{type:"string"},description:"Complete map of Sequenzy list id to Attio people-list UUID or api slug. Replaces the saved map. Pass `{}` to clear every mapping. Omit to leave mappings unchanged."},syncCompanyFromDomain:{type:"boolean",description:"When true, upsert a company from the person's non-free-mail email domain. Omit to leave the current setting unchanged."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var ts=[{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. Drafts have publicUrl and appPublicUrl set to null; previewUrl is a signed, unlisted visitor-facing preview that works before publish. Use render_landing_page when you need that preview URL called out with publish-vs-draft guidance. viewCount and conversionCount are lifetime totals; use get_landing_page_stats for unique visits, referrers, a date histogram, and whether crawlers were counted.",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:"get_landing_page_stats",description:"Get Mailchimp-style landing page analytics: visits, unique visits, clicks, subscribes, conversion rate, a daily histogram, referrers, and UTM sources. Default counts exclude known crawlers; preview URLs and the editor are never counted. Opening the public URL while building the page does count. Pass includeBots to include crawler hits in visits. period defaults to all retained events with a 90-day histogram; dataAvailableFrom identifies the beginning of retained coverage, which may be later than the page's lifetime counters.",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."},period:{type:"string",description:"Time window: 7d, 30d, 90d, or all (default: all)."},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too. Maximum range is 365 days."},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too."},includeBots:{type:"boolean",description:"Include known crawlers in visits, unique visits, clicks, referrers, and the histogram. Bot hits are always returned separately as botVisits."}},required:["landingPageId"],additionalProperties:!1}},{name:"render_landing_page",description:"Render a visitor-facing preview of a landing page without publishing it. Unlike get_landing_page, which returns builder JSON, this returns previewUrl: a signed, unlisted URL that shows the page with the same layout, theme, form, and #form button anchors visitors will see. Drafts keep publicUrl and appPublicUrl null until publish_landing_page; open previewUrl to check copy and layout on a draft instead of putting unreviewed content on the public domain. The preview is not indexed. Signup forms on a draft preview do not collect contacts. This is read-only and never publishes, unpublishes, or changes the 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 to preview."}},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:An},content:{type:"object",description:xe,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:xe,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:xe,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:xe,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain. Omit landingPageId for the legacy workspace-wide domain, or provide it to dedicate the hostname to one page at the domain root. Returns DNS and verification details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain: a subdomain (pages.example.com, needs a CNAME record) or a root domain (example.com, needs an A record to 76.76.21.21; www also redirects to the root when its CNAME points to pages.sequenzydns.com)."},landingPageId:{type:"string",description:"Optional landing page ID. When provided, the domain serves only this page from the hostname root."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update or verify landing page domain settings. Omit landingPageId for the workspace domain, or provide it for a dedicated page domain. Dedicated domains must be removed explicitly before replacement.",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."},landingPageId:{type:"string",description:"Optional dedicated landing page domain target."}},additionalProperties:!1}},{name:"remove_landing_page_domain",description:"Remove the dedicated custom domain from one landing page. The page keeps its workspace and Sequenzy fallback 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 whose dedicated domain should be removed."}},required:["landingPageId"],additionalProperties:!1}}];var ns=[{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 globally unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Layout groups use { id, kind: "group", label, layout: "stack" | "row" | "grid" | "overlay", columns (1-4), gap (0-64), padding (0-64), overlayColor (hex), overlayPosition ("top" | "center" | "bottom"), overlayShade (0-100), children: [...] }. In Overlay, gap spaces foreground children while the direct image remains the background. Overlay needs exactly one direct image; images inside subgroups only enable Overlay for that subgroup, while zero or multiple direct images fall back to Stack. Groups may nest to three levels; descendants must use the same sectionId as their group, while form-step, success-screen, and error-state remain at the root. 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].children[0].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 globally unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Layout groups use { id, kind: "group", label, layout: "stack" | "row" | "grid" | "overlay", columns (1-4), gap (0-64), padding (0-64), overlayColor (hex), overlayPosition ("top" | "center" | "bottom"), overlayShade (0-100), children: [...] }. In Overlay, gap spaces foreground children while the direct image remains the background. Overlay needs exactly one direct image; images inside subgroups only enable Overlay for that subgroup, while zero or multiple direct images fall back to Stack. Groups may nest to three levels; descendants must use the same sectionId as their group, while form-step, success-screen, and error-state remain at the root. 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].children[0].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 is=[{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 ss=[{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. For a sequence step whose nodeType is action_ab_test, also pass variantId from get_sequence.sequence.emails[].abTest.variants - that step has no email of its own and copy lives on the variants. 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. An unrecognized name is reported there even when a default filter supplied text in its place, because that fallback then reaches every recipient while the HTML looks perfectly personalized. 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. Conditional blocks are the other half of a preview: a condition on stored subscriber state (tag, segment, list, status, event, purchases, engagement) is evaluated per recipient at send time, so this render can only evaluate it for a stored subscriberId - or, for a `tag` condition, an inline subscriber that states tags. Anything it cannot evaluate renders as false, which is indistinguishable in the HTML from a condition that is genuinely false, so check unevaluatedConditions before treating a preview as proof of which branch a recipient gets. 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},tags:{type:"array",description:"Tags this ad-hoc contact carries, used to evaluate `tag` block conditions. Nothing is stored. Without it a tag condition has no tags to read and renders as false, so only the else branch of a tag split can be previewed. Every other stored-state condition (segment, list, event, engagement, purchases) still needs subscriberId.",items:{type:"string"}}},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. Required for sequence steps whose nodeType is action_ab_test: those steps have no emailId of their own, and copy lives on get_sequence.sequence.emails[].abTest.variants. Rendering a sequence variant also needs the ab_tests:read scope, the same scope get_sequence uses to return competing variant copy."},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 at={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},rs={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change","tag_added"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},triggerTagName:{type:["string","null"],description:"Required tag name for tag_added goals, e.g. customer."},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."}},os=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:at,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event, subscriber-attribute, or tag-applied conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath; tag_added goals require triggerTagName. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...at,...rs},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:{...at,goalId:{type:"string",description:"Sequence goal ID."},...rs},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...at,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var mn={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},as=[{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:mn,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:{...mn,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:mn,required:["sequenceId"],additionalProperties:!1}}];var ds=[{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, nodeType, 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. sequence.emails includes action_ab_test steps, whose copy lives on the A/B test variants rather than on the node: their subject/previewText/blocks are control variant A only. With ab_tests:read, each carries abTest with the test id, status, and one entry per variant including that variant's full blocks, so a sequence read is enough to audit CTA/promo/review copy; without that scope, test-record fields are redacted and variants is empty while the configured id and editing guidance remain available. To change the copy of an A/B step, edit each variant with update_ab_test_variant - if that tool is not in the tool list, enable it on the Sequenzy connector rather than writing through update_template or update_sequence_node. Rebuilding the step as a plain email node to reach the copy destroys the test. get_ab_test remains the dedicated A/B read for settings, localization, and stats. ${le}`,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. The response always echoes the sequence's single configured stopCondition, including matchConfig filters or comparisons. A stop condition does not cancel a waiting enrollment when its event arrives: it is re-evaluated when the enrollment next runs a step, so an enrollment parked on a delay keeps reporting `waiting` until that delay expires. Pass stopConditionMatch true to see whether each in-flight enrollment's stop condition matches right now. This is a non-atomic snapshot: a step already past its stop check may still finish. Each enrollment also reports enteredVia - the list, tag, segment, event, inactivity check, or frequency check that enrolled it - which is how you tell apart contacts entering a sequence whose trigger covers several lists or tags. entryContext adds the event id, property keys (never values), and trigger type. branchDecisions records the bounded retained if/else (or random split) verdicts, including the compared field name and a redacted value summary (missing/empty/nonempty/equals_expected); branchDecisionCount and branchDecisionsTruncated tell you when older verdicts were omitted. For the ClickHouse graph walk of one completed token, use get_sequence_enrollment. Live sequence tests do not create enrollments; they send isolated test emails and record activity on the sequence test run 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 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."},stopConditionMatch:{type:"boolean",description:"Annotate each returned active or waiting enrollment with whether the sequence's stop condition matches for that contact right now, using the same evaluation the worker runs before each step. Use this to confirm a stop event, tag, or field change registered without waiting out the current delay: a matching enrollment can still report `waiting`, so status alone cannot tell you. This is a non-atomic snapshot, not a promise of a future exit: the condition can change, a paused sequence may not run on schedule, and a step already past its stop check may still finish. Each annotated enrollment costs an evaluation, so this caps the page at 100 regardless of limit; stopConditionMatchEvaluatedCount reports how many were actually evaluated. Defaults to false."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting. Capped at 100 when stopConditionMatch is true."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"get_sequence_enrollment",description:"Read one sequence enrollment token, including how it entered and which branches it already took. Use this after list_sequence_enrollments when a completed token shows enteredVia unknown or Sequence completed with no email: nodeHistory is the bounded ClickHouse graph walk (redacted), and nodeHistoryTruncated tells you when more events exist. branchDecisionCount and branchDecisionsTruncated report whether the token's bounded decision array omitted older decisions. A legacy token whose first unmatched branch went straight to completion still reports the compared field name and a safe value summary (missing/empty/nonempty/equals_expected) rather than the raw recipient value. entryContext lists event property keys, never values. Requires sequences:read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID that owns the enrollment."},enrollmentId:{type:"string",description:"Enrollment token ID from list_sequence_enrollments (enrollmentId)."}},required:["sequenceId","enrollmentId"],additionalProperties:!1}},{name:"simulate_sequence",description:"Dry-run a sequence without sending mail or enrolling anyone. Requires sequences:read and subscribers:read because results include contact samples. Nobody is auto-enrolled when you activate. Without a subscriber this reports who currently matches (existing list/tag/segment matches are not auto-enrolled) and activation readiness errors. Frequency and inactivity current-match counts are unavailable because the hourly worker evaluates them. Pass subscriberId or email to also walk that stored contact's branch path - use this to check whether a paid user would get an upgrade email. Call this before enable_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 to simulate."},subscriberId:{type:"string",description:"Optional stored subscriber to walk through the graph. Do not pass with email."},email:{type:"string",description:"Optional stored subscriber email to walk through the graph. Do not pass with subscriberId."},limit:{type:"integer",minimum:1,maximum:25,description:"Maximum currently matching contacts to include in the sample. Defaults to 10."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved action_email step in a sequence. Call get_sequence first and pass the target sequence.emails entry's nodeId only when nodeType is action_email; action_ab_test steps are not supported by this tool - inspect variant copy on get_sequence.sequence.emails[].abTest.variants. 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:"action_email step nodeId from get_sequence. The node must belong to sequenceId. Do not pass an action_ab_test node; inspect its variants on get_sequence.sequence.emails[].abTest.variants."},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/listIds, tagName/tagNames, 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:de},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:ce},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). Omit to use listScope instead. Use listIds to trigger on several lists."},listIds:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several list IDs for a contact_added trigger. A contact joining ANY of them enrolls. Use this instead of listId when the user says 'when added to list A or list B'. Cannot be combined with listScope."},listScope:{type:"string",enum:["any_contact","any_list"],description:"For contact_added with no list at all. 'any_contact' (default) enrolls every contact added, including the list-less contacts that integrations like PostHog, Stripe, or Supabase create when no list targeting is configured. 'any_list' waits until the contact actually joins a list. Cannot be combined with listId or listIds."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger). Use tagNames to trigger on several tags."},tagNames:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several tag names for a tag_added trigger. Receiving ANY of them enrolls the contact. Use this instead of tagName when the user says 'when tagged vip or trial'."},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:Ge,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 entry_audience matching, omit this value because the enrolling tag or list is resolved per contact. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching. event_property_filter and event_property refine event_received; field_value refines field_changed. entry_audience with audience tag/list makes a does_not_have_tag/removed_from_list guard resolve the tag or list that enrolled each contact; tag requires a tag_added trigger, and list requires a contact_added trigger scoped to at least one specific list. Omit value for this mode.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value","entry_audience"]},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."},audience:{type:"string",enum:["tag","list"],description:"entry_audience mode source to resolve per enrollment."}},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:ve,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:he,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${R}`},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."},...Re,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:fe,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:ye,waitUntilWeekday:ge,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.${ze}`,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 cs=[{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. The emails/steps arrays reach action_email steps only: an action_ab_test step keeps its copy on the A/B test variants, so read variant blocks from get_sequence.sequence.emails[].abTest.variants and change each variant with update_ab_test_variant. If update_ab_test_variant is not in the tool list, enable it on the Sequenzy connector rather than writing through update_template. 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."},listIds:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several list IDs for a contact_added trigger replacement. Joining ANY of them enrolls the contact. Cannot be combined with listScope."},listScope:{type:"string",enum:["any_contact","any_list"],description:"For a contact_added trigger replacement with no list. 'any_contact' (default) enrolls every contact added, even one that joins no list; 'any_list' waits for a list membership. Cannot be combined with listId or listIds."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},tagNames:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several tag names for a tag_added trigger replacement. Receiving ANY of them enrolls the contact."},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:de},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:ce},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:Ge,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 entry_audience matching, omit this value because the enrolling tag or list is resolved per contact."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching, four shapes keyed by mode. event_property_filter and event_property refine event_received; field_value refines field_changed. entry_audience with audience tag/list makes a does_not_have_tag/removed_from_list guard resolve the tag or list that enrolled each contact; tag requires a tag_added trigger, and list requires a contact_added trigger scoped to at least one specific list. Omit value for this mode. Pass null to clear.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value","entry_audience"],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."},audience:{type:"string",enum:["tag","list"],description:"entry_audience mode source to resolve per enrollment."}},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:Kt,randomPercentages:Vt,branches:{type:"array",description:Gt,items:Wt},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path. Not valid on a random split.",items:Ae},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:Ae}},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. ${R}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${R}`},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."},emailTheme:Ke,blocks:{type:"array",description:`${Z}${Be}`,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."},...Re}}},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. ${R}`},htmlContent:{type:"string",description:`Alias for html. ${R}`},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."},emailTheme:Ke,blocks:{type:"array",description:`${Z}${Be}`,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."},...Re}}},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:ve},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. To restyle one email, patch changes:{ emailTheme:{ colors:{ background:'#ffffff' } } } on its action_email node - that overrides only this step's linked email and leaves the company-wide theme alone. 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. It also cannot edit the copy of an action_ab_test step: that content lives on the A/B test variants (get_sequence.sequence.emails[].abTest.variants includes the blocks), so change each one with update_ab_test_variant. If update_ab_test_variant is not in the tool list, enable it on the Sequenzy connector rather than writing through update_template. 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:Ve.properties.nodeId,changes:Ct,expectedUpdatedAt:Ve.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 restyling several action_email nodes at once with changes:{ emailPreset:'minimal' } or changes:{ emailTheme:{ colors:{ background:'#ffffff' } } }, 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:Ve},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:he,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${R}`},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:{...ve,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:fe,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:ye,waitUntilWeekday:ge,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:Kt,randomPercentages:Vt,branches:{type:"array",description:`logic_branch only: ${Gt}`,items:Wt},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path. Not valid on a random split.",items:Ae},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. Call simulate_sequence first to see who currently matches and whether the sequence is ready. Nobody is auto-enrolled on activate.",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 vo={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"},timezone:{type:"string",description:"IANA timezone identifier (e.g. America/New_York) used for recipient-local campaign delivery. Rows with an invalid value import without it."},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},ls=[{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. Matching sequences enroll by default (REST enrollInSequences), including tag_added when tags are set in this call, without requiring a list; pass enrollInSequences false to skip, and automations:trigger is required for enrollment. 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."},timezone:{type:"string",description:"IANA timezone identifier (e.g. America/New_York), stored as a native profile field. Enables recipient-local campaign delivery for this contact."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Same field as REST customAttributes; provide one or the other. Use firstName/lastName for names instead of attributes.",additionalProperties:!0},customAttributes:{type:"object",description:"REST name for attributes. Same custom-attribute map; provide attributes or customAttributes, not both.",additionalProperties:!0},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. Omit to let a contact this call creates follow the workspace default lists; an existing contact then keeps the memberships they already have. Pass [] to join no list."},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."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll this contact, including tag_added flows when tags are set in the same call. Same field as REST POST /api/v1/subscribers enrollInSequences. Defaults to true unless createdAt is supplied. Requires automations:trigger. Pass false to create and tag without enrollment. List membership is not required."},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:vo,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."},idempotencyKey:{type:"string",minLength:1,maxLength:255,description:"Caller-owned key (1-255 characters, not blank) that makes retrying this request safe. The key is scoped to the request content: resending the same request returns the already-queued import (deduplicated: true), while different content under the same key queues a new import. Use it whenever a timeout or retry loop could resend the same import. If two identical requests overlap, a transient 503 means to retry the same call shortly."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import. Every excluded row is explained: skippedReasons sums to skippedCount and failedReasons sums to failedCount, so a finished import can be reconciled without inspecting individual contacts. If the reason counts fall short of the totals, report it with the import ID rather than guessing what the missing rows were.",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."},timezone:{type:"string",description:"New IANA timezone identifier (e.g. America/New_York), stored as a native profile field. Pass an empty string to clear it. Enables recipient-local campaign delivery for this contact."},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 merge into the existing map. This is the legacy MCP spelling; provide attributes or customAttributes, not both. Use firstName/lastName for names instead of attributes.",additionalProperties:!0},customAttributes:{type:"object",description:"REST spelling for custom attributes. Replaces the existing public custom-attribute map, matching REST PATCH semantics; provide attributes instead when you want to retain unspecified keys. Provide attributes or customAttributes, not both.",additionalProperties:!0},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:L},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:"import_subscriber_events",description:"Record a bounded batch of events for many subscribers in one call, built for data pipeline and warehouse syncs. Each event carries its own email or externalId and a required source-owned eventId; externalId-only rows must identify an existing contact because email is required for creation. Contacts whose events are all more than an hour old are imported silently as history (including no double-opt-in email); any recent event makes that contact's whole group live. Retries preserve one receipt and idempotently re-attempt downstream recovery. Accepts at most 25 events.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},events:{type:"array",minItems:1,maxItems:25,items:{type:"object",properties:{email:{type:["string","null"],description:"Subscriber email address. Required when the event may create a new contact; null is treated as absent."},externalId:{type:["string","null"],description:"Customer-owned subscriber ID. It can be used alone only when it resolves to an existing contact; null is treated as absent."},name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:["string","null"],description:"When the event happened (ISO 8601; null is absent). Classification is per contact: only when every row for that contact is more than an hour old is the group historical; any recent row makes the whole group live."},eventId:{type:"string",minLength:1,description:"Required source-owned id for this event, making a re-run idempotent on both the live and historical paths."}},required:["name","eventId"],additionalProperties:!1},description:"Events to record. Each event identifies its own subscriber."}},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:[...We],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 hn={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:"Deprecated: accepted and ignored. It previously limited a provider-side suppression lookup, which no longer happens."}},ps=[{name:"list_recipient_suppressions",description:"List the recipients this company cannot reach: protected global invalid-recipient suppressions for addresses associated with the company, protected workspace hard bounces without conclusive invalid-inbox evidence, removable workspace soft-bounce escalations, and protected spam complaints. Each row includes a stable suppressionType, and the response echoes the applied sortBy/sortOrder. Sort by `status` to surface the suppressions you can actually remove. Start here when a customer reports missing email; use get_recipient_suppression for one exact address.",inputSchema:{type:"object",properties:{companyId:hn.companyId,search:{type:"string",description:"Case-insensitive substring filter on the recipient email address."},page:{type:"number",description:"1-based page number. Defaults to 1."},limit:{type:"number",description:"Entries per page. Defaults to 25, maximum 100."},sort:{type:"string",enum:["suppressedAt","email","status"],description:"Order the page. `suppressedAt` (default) is newest first, `email` is A-Z, and `status` lists removable workspace escalations before protected suppressions. An unrecognized value falls back to `suppressedAt`."},order:{type:"string",enum:["asc","desc"],description:"Sort direction. Defaults to `desc` for suppressedAt and status, `asc` for email."}},required:[],additionalProperties:!1}},{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards. Suppression comes solely from Sequenzy's own bounce records; the email provider's suppression list is not consulted. This exact-address lookup never exposes other recipients.",inputSchema:{type:"object",properties:hn,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove a workspace-scoped soft-bounce escalation for an exact recipient associated with the company, then reactivate bounced company subscribers. Global invalid-recipient, workspace hard-bounce, complaint, and unsubscribe suppressions are protected.",inputSchema:{type:"object",properties:hn,required:["email"],additionalProperties:!1}}];var us=[{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:[...be],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:[...be],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. Each list includes subscriberCount (current members of any status) and activeSubscriberCount (current members with status=active). Members who unsubscribed from the list are not counted. Use these fields for list audience size instead of paging search_subscribers.",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" }] }] }`. AND of two or more positive attribute filters on the same array path (e.g. `history_events[].eventvenue_id` and `history_events[].showing_date`) requires one array element to satisfy every condition — a 2010 visit at that venue plus an unrelated recent booking elsewhere does not match. Negative filters (`is_not`, `not_contains`, `is_empty`) are exempt: they assert no element matches and combine independently. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign- or delivery-policy-scoped engagement filters such as `emailOpened is marketing:all`.',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:Rt,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 marketing-open filter: [{"id":"filter-1","field":"emailOpened","operator":"is","value":"marketing:all"}]. 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:{...At,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:Rt,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...At,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. Requires the segments:delete scope; segments:write is not enough.",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 ms=[{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 hs=[{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. ${R}`},blocks:{type:"array",description:M,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`. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values are freeform prompt guidance. Defaults to the company's email style preference."},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. ${R}`},blocks:{type:"array",description:M,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\`. ${R}`},blocks:{type:"array",description:M,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 ys=[{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\`. ${R}`},blocks:{type:"array",description:`${M} 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. Only used with `prompt`. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values (minimal, branded, promotional) are freeform prompt guidance. Defaults to the company's email style preference."},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\`. ${R}`},blocks:{type:"array",description:`${Z} 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. Always provide a stable `idempotencyKey` when an agent or workflow may retry, and reuse it for the same logical email; Sequenzy returns the original send for 14 days and rejects different content under the same key. The default delivery policy is transactional. A transactional send delivers one email to several people at once: `to` takes up to 50 addresses and `cc`/`bcc` take up to 50 each, so everyone sees the same shared recipient list instead of receiving separate copies. Addresses repeated across the fields are dropped from the lower-priority one (to beats cc beats bcc). 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; marketing sends take exactly one `to` recipient and no `cc` or `bcc`. When no identity override is provided, a template send keeps its saved From and Reply-To identities, while a direct send uses the company defaults. To send as a non-default verified brand, pass `fromEmail` (and `fromName` if that address has several identities) plus optional `replyTo`/`replyToName`; you do not need profile IDs. `senderProfileId`/`replyProfileId` from `list_sender_profiles` remain available when you already have them. These fields look up existing identities and do not create profiles. `{{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. When `trackingSettings` is omitted, the company's Transactional API defaults apply. Set `clickTracking` or `openTracking` to `false` to opt out for this send only; these fields cannot enable tracking disabled by account settings. Returns a durable emailSendId, the accepted emailType, and the deduplicated recipient lists; 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","array"],items:{type:"string"},minItems:1,maxItems:50,description:"Primary recipient email address, or an array of up to 50 addresses that share one email and see each other in the To header. Marketing sends accept exactly one address."},cc:{type:["string","array"],items:{type:"string"},maxItems:50,description:"Carbon-copy email address, or an array of up to 50, visible to every recipient. Transactional sends only. Addresses already in `to` are dropped."},bcc:{type:["string","array"],items:{type:"string"},maxItems:50,description:"Blind-carbon-copy email address, or an array of up to 50, hidden from the other recipients. Transactional sends only. Addresses already in `to` or `cc` are dropped."},idempotencyKey:{type:"string",description:"Caller-owned retry key for this logical email (maximum 255 characters). Reuse the same key with the same arguments to get the original emailSendId for 14 days. Never reuse a key for different content."},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 `to` recipient, rejects `cc` and `bcc`, 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>`. Pair a bare address with `replyToName` instead of embedding the name. Mutually exclusive with `replyProfileId`. When omitted, the saved template or company default is used."},replyToName:{type:"string",description:"Display name for `replyTo`. Requires a bare `replyTo` address. Mutually exclusive with `replyProfileId`. Does not create a reply profile."},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. Mutually exclusive with fromEmail. When omitted, a template send keeps its saved sender and a direct send uses the company default."},fromEmail:{type:"string",description:"From address of an existing verified sender profile (see list_sender_profiles). Mutually exclusive with senderProfileId. If the address has several identities, pass fromName to choose one. Does not create a new sender profile."},fromName:{type:"string",description:"Display name of an existing verified sender identity on fromEmail, e.g. StudyBoost vs StudyBoost News. Requires fromEmail. Mutually exclusive with senderProfileId. Does not create a new sender profile."},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. Mutually exclusive with replyTo."},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 je={type:"string",description:"Company ID. If not provided, uses the currently selected company."},gs=[{name:"list_web_tracking_keys",description:"List the publishable keys that let a non-Shopify website send on-site events (product views, cart activity, collection views, search) into this workspace. Check this BEFORE promising that browse abandonment, cart recovery, or any product-view trigger will work on a custom site: without an installed key those events never arrive, the sequences built on them never fire, and nothing reports an error anywhere. Each key returns `allowedOrigins`, `unrestricted`, `lastUsedAt`, and a paste-ready `installSnippet`. A key with `lastUsedAt: null` has not successfully authenticated an event yet; it may be undeployed, have no instrumented traffic, or be sending requests rejected by its origin allowlist. Shopify stores do not use these keys; they use the storefront pixel, so check get_integration_pixel instead.",inputSchema:{type:"object",properties:{companyId:je}}},{name:"get_web_tracking_key",description:"Get one web tracking key with its install snippet and ingest endpoint. Use this to hand a developer the exact `<script>` tag to paste, rather than reconstructing it - the snippet embeds both the publishable key and the workspace id, and a hand-built one that gets either wrong fails silently.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Web tracking key ID from list_web_tracking_keys."},companyId:je},required:["id"]}},{name:"create_web_tracking_key",description:"Create a publishable key for the browser tracking SDK and return the install snippet. This is what turns on product views, cart activity, and browse abandonment for a site that is NOT Shopify or WooCommerce (custom storefronts, headless shops, marketplaces, SaaS marketing sites). Events start flowing once the snippet is deployed and nothing is backfilled for the period before that, so create and install it BEFORE building the sequence that depends on it. Always pass allowedOrigins: a key with none accepts anonymous events from any site. Identified events require a short-lived token minted by the customer's authenticated backend through POST /api/v1/web-tracking-identities (passing the key's publicKey or keyId), then `sequenzy.identify(email, identityToken)`; a publishable key alone can never trigger subscriber automation.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Human-readable label for this key, e.g. 'Storefront' or 'Marketing site'."},allowedOrigins:{type:"array",items:{type:"string"},description:"Origins allowed to use this key, e.g. ['https://example.com', 'https://*.example.com']. A bare domain is read as https. A `*.` wildcard matches subdomains at any depth but NOT the apex, so list the apex separately if you need it. Include the development origin (e.g. http://localhost:3000) while wiring the SDK up. Omitting this leaves the key unrestricted, which should be a deliberate choice for a native app or server-side caller."},companyId:je},required:["name"]}},{name:"update_web_tracking_key",description:"Rename a web tracking key, replace its allowed origins, or revoke it. `allowedOrigins` REPLACES the whole list rather than appending, so include the origins you want to keep. Revoking with isActive: false stops events within about a minute while preserving the key value, so the customer can still find and remove the matching snippet from their site; use delete_web_tracking_key only once the snippet is gone.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Web tracking key ID from list_web_tracking_keys."},name:{type:"string",description:"New label for the key."},allowedOrigins:{type:"array",items:{type:"string"},description:"Replacement allowed-origins list. Pass an empty array to make the key unrestricted."},isActive:{type:"boolean",description:"Set false to revoke the key, true to re-enable a revoked one."},companyId:je},required:["id"]}},{name:"delete_web_tracking_key",description:"Permanently delete a web tracking key. Cached authorization expires within one minute, after which requests from any remaining snippet are rejected; remove the snippet from the site as well. Prefer update_web_tracking_key with isActive: false when the key might be needed again.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Web tracking key ID from list_web_tracking_keys."},companyId:je},required:["id"]}}];var fs=[{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:[...we]},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:[...we]},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 dt=[...$i,...es,...Yi,...ls,...ps,...is,...us,...zi,...hs,...Ki,...Vi,...Li,...Gi,...Wi,...ss,...Qi,...ns,...ts,...Zi,...ds,...cs,...os,...as,...ys,...Hi,...ms,...Xi,...gs,...fs,...Fi,...Ji];function Io(t){if(!Array.isArray(t))return null;return t.flatMap((e)=>I(e)&&typeof e.id==="string"?[e.id]:[])}var bs={new_subscriber:["off","instant","daily"],form_submitted:["off","instant"],campaign_completed:["off","instant"],weekly_report:["off","weekly"]};function ko(t){if(!Array.isArray(t))return;for(let e of t){if(!I(e))continue;let{event:n,mode:i}=e;if(typeof n!=="string"||typeof i!=="string"||!Object.prototype.hasOwnProperty.call(bs,n))continue;let s=bs[n];if(!s.includes(i))throw Error(`Invalid mode "${i}" for ${n}. Use one of: ${s.join(", ")}.`)}}async function ws(t,e){let n;switch(t){case"get_account":{let i=await a("GET","/api/v1/account",void 0,null),s=ie(),r=Io(i.companies),o=s!==null&&r!==null&&!r.includes(s);if(o)Ee(null);n={...i,selectedCompanyId:(o?null:s)??i.currentCompanyId,...o&&{note:`The previously selected company (${s}) is no longer available to this API key and has been cleared. Call select_company with one of the companies listed above, or pass companyId explicitly.`}};break}case"select_company":{let i=e.companyId,s=await a("GET","/api/v1/account",void 0,null),r=s.companies?.find((o)=>o.id===i);if(!r)throw Error(`Company not found. Available companies: ${s.companies?.map((o)=>`${o.name} (${o.id})`).join(", ")??"none"}`);Ee(i),n={success:!0,message:`Switched to company: ${r.name}`,companyId:r.id,companyName:r.name};break}case"get_app_urls":{let i=await st(e);n={...Q({companyId:i,campaignId:l(e,"campaignId"),landingPageId:l(e,"landingPageId"),sequenceId:l(e,"sequenceId"),emailId:l(e,"emailId")??l(e,"templateId"),transactionalId:l(e,"transactionalId"),emailSendId:l(e,"emailSendId"),domainId:l(e,"domainId"),status:l(e,"status"),settingsTab:l(e,"settingsTab")}),...i===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 i=await a("POST","/api/v1/companies",{name:e.name,domain:e.domain});if(!i.success)throw Error("Failed to create company");let s=i.company.id,r=6,o=0,d=i.company.status;while(d==="processing"&&o<r){await new Promise((f)=>setTimeout(f,20000)),o++;let m=await a("GET",`/api/v1/companies/${s}`);if(m.success)d=m.company.status}Ee(s);let c=await a("GET",`/api/v1/companies/${s}`);n={success:!0,company:c.company,message:d==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${c.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let i=e.companyId;n=await a("GET",`/api/v1/companies/${i}`);break}case"update_company":{let i=await Se("update_company",e),s=Fn(e);n=await a("PATCH",`/api/v1/companies/${i}`,s);break}case"get_sync_rules":{let i=e.companyId;n=await a("GET","/api/v1/sync-rules",void 0,i);break}case"update_sync_rules":{let i=e.companyId;if(e.syncRules!==null&&!Array.isArray(e.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");n=await a("PUT","/api/v1/sync-rules",{syncRules:e.syncRules},i);break}case"get_email_design_system":{let i=e.companyId;n=await a("GET","/api/v1/email-design-system",void 0,i);break}case"update_email_design_system":{let i=e.companyId,s={};if(e.designCode!==void 0)s.designCode=e.designCode;if(e.compositionSpine!==void 0)s.compositionSpine=e.compositionSpine;if(e.reset!==void 0)s.reset=e.reset;if(Object.keys(s).length===0)throw Error("Pass at least one of `designCode`, `compositionSpine`, or `reset: true` when calling `update_email_design_system`.");n=await a("PATCH","/api/v1/email-design-system",s,i);break}case"get_shopify_automation_settings":{let i=e.companyId;n=await a("GET","/api/v1/shopify/automation-settings",void 0,i);break}case"update_shopify_automation_settings":{let i=e.companyId,s={};if(e.browseAbandonment!==void 0)s.browseAbandonment=e.browseAbandonment;if(e.cartAbandonment!==void 0)s.cartAbandonment=e.cartAbandonment;if(e.priceDrop!==void 0)s.priceDrop=e.priceDrop;if(Object.keys(s).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");n=await a("PUT","/api/v1/shopify/automation-settings",s,i);break}case"create_api_key":{let i=e.companyId,s={};if(typeof e.name==="string")s.name=e.name;if(typeof e.preset==="string")s.preset=e.preset;if(Array.isArray(e.scopes))s.scopes=e.scopes;n=await a("POST","/api/v1/api-keys",s,i);break}case"request_api_key_handoff":{let i=await Se(t,e),s={};if(typeof e.name==="string")s.name=e.name;if(typeof e.preset==="string")s.preset=e.preset;if(Array.isArray(e.scopes))s.scopes=e.scopes;if(typeof e.replaceApiKeyId==="string")s.replaceApiKeyId=e.replaceApiKeyId;n=await a("POST","/api/v1/api-key-handoff",s,i);break}case"list_api_keys":{let i=await Se(t,e);n=await a("GET","/api/v1/api-keys",void 0,i);break}case"update_api_key":{let i=await Se(t,e),s={};if(typeof e.name==="string")s.name=e.name;if(typeof e.preset==="string")s.preset=e.preset;if(Array.isArray(e.scopes))s.scopes=e.scopes;if(Object.keys(s).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");n=await a("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(e.apiKeyId))}`,s,i);break}case"revoke_api_key":case"delete_api_key":{let i=await Se(t,e);n=await a("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(e.apiKeyId))}`,void 0,i);break}case"list_websites":{let i=e.companyId;n=await a("GET","/api/v1/websites",void 0,i);break}case"add_sending_domain":case"add_website":{let i=e.companyId;n=await a("POST","/api/v1/websites",{domain:e.domain},i);break}case"check_website":{let i=e.companyId;n=await a("GET",`/api/v1/websites/${encodeURIComponent(String(e.domain))}`,void 0,i);break}case"verify_sending_domain":{let i=e.companyId;n=await a("POST",`/api/v1/websites/${encodeURIComponent(String(e.domain))}/verify`,void 0,i);break}case"list_integrations":{let i=e.companyId,s=new URLSearchParams;if(e.includeInactive===!0)s.set("includeInactive","true");let r=s.toString();n=await a("GET",`/api/v1/integrations${r?`?${r}`:""}`,void 0,i);break}case"list_sender_profiles":{let i=e.companyId;n=await a("GET","/api/v1/sender-profiles",void 0,i);break}case"update_sender_profile":{let{companyId:i,profileId:s}=e,r=e.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(s)}`:`/api/v1/sender-profiles/${encodeURIComponent(s)}`;n=await a("PATCH",r,{name:e.name},i);break}case"get_sending_status":{let i=e.companyId;n=await a("GET","/api/v1/sending-status",void 0,i);break}case"resume_sending":{let i=e.companyId;n=await a("POST","/api/v1/sending-status/resume",{listSanitizationConfirmed:e.listSanitizationConfirmed===!0},i);break}case"get_tracking_settings":{let i=e.companyId;n=await a("GET","/api/v1/tracking-settings",void 0,i);break}case"update_tracking_settings":{let i=e.companyId,s=Hn(e);n=await a("PATCH","/api/v1/tracking-settings",s,i);break}case"get_notification_preferences":{let i=e.companyId;n=await a("GET","/api/v1/notification-preferences",void 0,i);break}case"update_notification_preferences":{let i=e.companyId;ko(e.notificationPreferences),n=await a("PATCH","/api/v1/notification-preferences",{notificationPreferences:e.notificationPreferences},i);break}case"get_integration_guide":n=await a("POST","/api/v1/integration-guide",e);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function _s(t,e){let n;switch(t){case"generate_email":{let i=e.companyId;n=await a("POST","/api/v1/generate/email",e,i);break}case"generate_subject_lines":{let i=e.companyId;n=await a("POST","/api/v1/generate/subjects",e,i);break}case"generate_sms":{let i=e.companyId;n=await a("POST","/api/v1/generate/sms",e,i);break}case"get_sms_settings":{let i=e.companyId;n=await a("GET","/api/v1/sms/settings",void 0,i);break}case"get_sms_usage":{let i=e.companyId;n=await a("GET","/api/v1/sms/usage",void 0,i);break}case"update_sms_number_label":{let i=e.companyId,s=u("update_sms_number_label",e,"numberId");if(e.label!==void 0&&typeof e.label!=="string")throw Error("update_sms_number_label `label` must be a string; pass an empty string to clear it.");if(e.brandPrefix!==void 0&&typeof e.brandPrefix!=="string")throw Error("update_sms_number_label `brandPrefix` must be a string; pass an empty string to clear it.");if(e.label===void 0&&e.brandPrefix===void 0)throw Error("update_sms_number_label requires `label` and/or `brandPrefix`.");n=await a("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(s)}`,{...typeof e.label==="string"?{label:e.label.trim()||null}:{},...typeof e.brandPrefix==="string"?{brandPrefix:e.brandPrefix.trim()||null}:{}},i);break}case"release_sms_number":{let i=e.companyId,s=u("release_sms_number",e,"numberId");n=await a("DELETE",`/api/v1/sms/numbers/${encodeURIComponent(s)}`,void 0,i);break}case"send_test_sms":{let i=e.companyId,s={to:u("send_test_sms",e,"to")};for(let r of["text","imageUrls","blocks","fromNumberId"])if(e[r]!==void 0)s[r]=e[r];n=await a("POST","/api/v1/sms/test",s,i);break}case"submit_feedback":{let i=e.companyId,s={message:u("submit_feedback",e,"message"),source:"mcp"};for(let r of["category","context","userIntent","toolCalls","expected","actual","resourceIds"])if(e[r]!==void 0)s[r]=e[r];n=await a("POST","/api/v1/feedback",s,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function vs(t,e){let n;switch(t){case"list_transactional_emails":{let i=e.companyId,s=new URLSearchParams,r=l(e,"search"),o=S("list_transactional_emails",e,"status",["all","active","disabled"]),d=S("list_transactional_emails",e,"sort",["date","sends","opens","open-rate","clicks","ctr"]),c=S("list_transactional_emails",e,"order",["asc","desc"]);if(r)s.set("search",r);if(o)s.set("status",o);if(d)s.set("sort",d);if(c)s.set("order",c);if(e.includeMachineEngagement===!0)s.set("includeMachineEngagement","true");let m=s.toString();n=await a("GET",`/api/v1/transactional${m?`?${m}`:""}`,void 0,i);break}case"get_transactional_email":{let i=e.companyId;n=await a("GET",`/api/v1/transactional/${e.idOrSlug}`,void 0,i);break}case"create_transactional_email":{let i=e.companyId,s=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),r=Object.keys(e).filter((d)=>!s.has(d));if(r.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${r.length===1?"":"s"}: ${r.map((d)=>`\`${d}\``).join(", ")}.`);hi(e);let o=Object.fromEntries(Object.entries(e).filter(([d])=>d!=="companyId"));n=await a("POST","/api/v1/transactional",o,i);break}case"update_transactional_email":{let i=e.companyId,s=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),r=Object.keys(e).filter((d)=>!s.has(d));if(r.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${r.length===1?"":"s"}: ${r.map((d)=>`\`${d}\``).join(", ")}.`);if(F("update_transactional_email",e),e.name===void 0&&e.enabled===void 0&&e.subject===void 0&&e.previewText===void 0&&e.html===void 0&&e.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let o=Object.fromEntries(Object.entries(e).filter(([d])=>d!=="companyId"&&d!=="idOrSlug"));n=await a("PATCH",`/api/v1/transactional/${e.idOrSlug}`,o,i);break}case"delete_transactional_email":{let i=e.companyId,s=u("delete_transactional_email",e,"idOrSlug");n=await a("DELETE",`/api/v1/transactional/${encodeURIComponent(s)}`,void 0,i);break}case"send_email":{let i=e.companyId,s=it(e,"to");if(s===void 0)throw Error("`to` is required when calling `send_email`.");let r=ki({to:s,cc:it(e,"cc"),bcc:it(e,"bcc")}),{to:o,cc:d,bcc:c}=r,m=e.templateId===void 0?void 0:u("send_email",e,"templateId"),f=e.subject===void 0?void 0:u("send_email",e,"subject"),w=e.html===void 0?void 0:u("send_email",e,"html"),g=e.emailType===void 0?void 0:u("send_email",e,"emailType"),_=e.replyTo===void 0?void 0:u("send_email",e,"replyTo"),q=e.senderProfileId===void 0?void 0:u("send_email",e,"senderProfileId"),E=e.fromEmail===void 0?void 0:u("send_email",e,"fromEmail"),x=e.fromName===void 0?void 0:u("send_email",e,"fromName"),A=e.replyProfileId===void 0?void 0:u("send_email",e,"replyProfileId"),ee=e.replyToName===void 0?void 0:u("send_email",e,"replyToName"),te=e.idempotencyKey===void 0?void 0:u("send_email",e,"idempotencyKey"),U=typeof e.subscriberExternalId==="string"?l(e,"subscriberExternalId"):e.subscriberExternalId;if(te&&te.length>255)throw Error("`idempotencyKey` must be 255 characters or fewer when calling `send_email`.");let ue;if(e.attachments!==void 0){if(!Array.isArray(e.attachments)||e.attachments.length>10)throw Error("`attachments` must be an array with at most 10 items when calling `send_email`.");ue=e.attachments.map((O,z)=>{if(typeof O!=="object"||O===null||Array.isArray(O))throw Error(`\`attachments[${z}]\` must be an object when calling \`send_email\`.`);let B=O,Me=new Set(["filename","content","path","contentId","contentType"]);if(Object.keys(B).some((Te)=>!Me.has(Te)))throw Error(`\`attachments[${z}]\` contains an unsupported field when calling \`send_email\`.`);let W={};for(let Te of Me){let ut=B[Te];if(ut===void 0)continue;if(typeof ut!=="string")throw Error(`\`attachments[${z}].${Te}\` must be a string when calling \`send_email\`.`);W[Te]=ut}if(!W.filename)throw Error(`\`attachments[${z}].filename\` is required when calling \`send_email\`.`);let Qs=W.content!==void 0,Zs=W.path!==void 0;if(Qs===Zs)throw Error(`\`attachments[${z}]\` must provide exactly one of \`content\` or \`path\` when calling \`send_email\`.`);return W})}if(g!==void 0&&g!=="marketing"&&g!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(m!==void 0&&(f!==void 0||w!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(m===void 0&&(f===void 0||w===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");re("send_email",e),Si({emailType:g,to:o,cc:d,bcc:c,subscriberExternalId:U});let me;if(e.trackingSettings!==void 0){if(typeof e.trackingSettings!=="object"||e.trackingSettings===null||Array.isArray(e.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let O=e.trackingSettings;me={};for(let z of["clickTracking","openTracking"]){let B=O[z];if(B===void 0)continue;if(typeof B!=="boolean")throw Error(`\`trackingSettings.${z}\` must be a boolean when calling \`send_email\`.`);me[z]=B}}let Ne=Object.fromEntries(Object.entries({to:o,cc:d,bcc:c,slug:m,subject:f,body:w,variables:e.variables,subscriberExternalId:U,emailType:g,replyTo:_,senderProfileId:q,fromEmail:E,fromName:x,replyProfileId:A,replyToName:ee,attachments:ue,trackingSettings:me}).filter(([,O])=>O!==void 0));n=te?await a("POST","/api/v1/transactional/send",Ne,i,{"Idempotency-Key":te}):await a("POST","/api/v1/transactional/send",Ne,i);break}case"get_stats":{let i=e.companyId,s=e.period??"7d",r=new URLSearchParams({period:String(s)}),o=e.emailType===void 0?void 0:u("get_stats",e,"emailType");if(o!==void 0&&!["campaign","transactional","sequence"].includes(o))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(o)r.set("emailType",o);if(e.includeMachineEngagement===!0)r.set("includeMachineEngagement","true");n=await a("GET",`/api/v1/metrics?${r.toString()}`,void 0,i);break}case"get_campaign_stats":{let i=e.companyId,s=new URLSearchParams;if(typeof e.period==="string")s.set("period",e.period);if(typeof e.start==="string")s.set("start",e.start);if(typeof e.end==="string")s.set("end",e.end);if(e.includeMachineEngagement===!0)s.set("includeMachineEngagement","true");let r=s.toString();n=await a("GET",`/api/v1/metrics/campaigns/${e.campaignId}${r?`?${r}`:""}`,void 0,i);break}case"list_poll_responses":{let i=e.companyId,s=u("list_poll_responses",e,"campaignId"),r=new URLSearchParams,o=l(e,"blockId");if(o)r.set("blockId",o);for(let c of["page","limit"])if(e[c]!==void 0)r.set(c,String(e[c]));let d=r.toString();n=await a("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(s)}/poll-responses${d?`?${d}`:""}`,void 0,i);break}case"get_transactional_stats":{let i=e.companyId,s=u("get_transactional_stats",e,"idOrSlug"),r=new URLSearchParams;for(let d of["period","start","end"])if(typeof e[d]==="string"&&e[d].trim())r.set(d,e[d].trim());if(e.includeMachineEngagement===!0)r.set("includeMachineEngagement","true");let o=r.toString();n=await a("GET",`/api/v1/metrics/transactional/${encodeURIComponent(s)}${o?`?${o}`:""}`,void 0,i);break}case"get_sequence_stats":{let i=e.companyId,s=new URLSearchParams;for(let o of["period","start","end"])if(typeof e[o]==="string"&&e[o].trim())s.set(o,e[o].trim());if(e.includeMachineEngagement===!0)s.set("includeMachineEngagement","true");let r=s.toString();n=await a("GET",`/api/v1/metrics/sequences/${e.sequenceId}${r?`?${r}`:""}`,void 0,i);break}case"list_campaign_events":{let i=e.companyId,s=u("list_campaign_events",e,"campaignId"),o=nn("list_campaign_events",e).toString();n=await a("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(s)}/events${o?`?${o}`:""}`,void 0,i);break}case"list_sequence_events":{let i=e.companyId,s=u("list_sequence_events",e,"sequenceId"),r=nn("list_sequence_events",e),o=l(e,"automationNodeId");if(o)r.set("automationNodeId",o);let d=r.toString();n=await a("GET",`/api/v1/metrics/sequences/${encodeURIComponent(s)}/events${d?`?${d}`:""}`,void 0,i);break}case"list_email_metrics":{let i=e.companyId,s=new URLSearchParams,r=S("list_email_metrics",e,"emailType",["campaign","sequence"]);if(r)s.set("emailType",r);let o=yt("list_email_metrics",e,"sequenceId"),d=yt("list_email_metrics",e,"campaignId"),c=P("list_email_metrics",e,"step",1,1000);if(d.length>0&&(o.length>0||c))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(r==="campaign"&&(o.length>0||c!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(r==="sequence"&&d.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(o.length>0)s.set("sequenceId",o.join(","));if(d.length>0)s.set("campaignId",d.join(","));if(c!==void 0)s.set("step",String(c));let m=S("list_email_metrics",e,"period",["1h","24h","7d","30d","90d"]);if(m)s.set("period",m);for(let E of["start","end"]){let x=l(e,E);if(x)s.set(E,x)}let f=S("list_email_metrics",e,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(f)s.set("sort",f);let w=S("list_email_metrics",e,"order",["asc","desc"]);if(w)s.set("order",w);let g=P("list_email_metrics",e,"page",1,1e6);if(g!==void 0)s.set("page",String(g));let _=P("list_email_metrics",e,"limit",1,500);if(_!==void 0)s.set("limit",String(_));if(e.includeMachineEngagement===!0)s.set("includeMachineEngagement","true");let q=s.toString();n=await a("GET",`/api/v1/metrics/emails${q?`?${q}`:""}`,void 0,i);break}case"get_subscriber_activity":{let i=e.companyId,s=K("get_subscriber_activity",e),r=await Oe(s,i,{includeMachineEngagement:e.includeMachineEngagement===!0});n={success:r.success,email:r.subscriber.email,emailStats:r.subscriber.emailStats??null,activity:r.subscriber.activity??[],sequenceEnrollments:r.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function Is(t,e){let n;switch(t){case"list_tags":{let i=e.companyId;n=await a("GET","/api/v1/tags",void 0,i);break}case"create_tag":{let i=e.companyId,s=u("create_tag",e,"name"),r=S("create_tag",e,"color",be);n=await a("POST","/api/v1/tags",{name:s,...r!==void 0&&{color:r}},i);break}case"update_tag":{let i=e.companyId,s=u("update_tag",e,"tagId"),r=Ue("update_tag",e,"color",be);n=await a("PATCH",`/api/v1/tags/${encodeURIComponent(s)}`,{color:r},i);break}case"delete_tag":{let i=e.companyId,s=u("delete_tag",e,"tagId");n=await a("DELETE",`/api/v1/tags/${encodeURIComponent(s)}`,void 0,i);break}case"list_lists":{let i=e.companyId;n=await a("GET","/api/v1/lists",void 0,i);break}case"create_list":{let i=e.companyId;n=await a("POST","/api/v1/lists",e,i);break}case"update_list":{let i=e.companyId,s=u("update_list",e,"listId");if(e.name===void 0&&e.description===void 0&&e.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(e.name!==void 0&&l(e,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(e.description!==void 0&&e.description!==null&&typeof e.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(e.isPrivate!==void 0&&typeof e.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");n=await a("PATCH",`/api/v1/lists/${encodeURIComponent(s)}`,{...e.name!==void 0&&{name:l(e,"name")},...e.description!==void 0&&{description:e.description},...e.isPrivate!==void 0&&{isPrivate:e.isPrivate}},i);break}case"delete_list":{let i=e.companyId,s=u("delete_list",e,"listId");n=await a("DELETE",`/api/v1/lists/${encodeURIComponent(s)}`,void 0,i);break}case"add_subscribers_to_list":{let i=e.companyId,s=u("add_subscribers_to_list",e,"listId"),r=rn("add_subscribers_to_list",e),o=S("add_subscribers_to_list",e,"duplicateStrategy",["skip","merge","overwrite"])??"skip",d=S("add_subscribers_to_list",e,"optInMode",["default","confirmed","double_opt_in"])??"default";n=await a("POST",`/api/v1/lists/${encodeURIComponent(s)}/subscribers`,{emails:r,duplicateStrategy:o,enrollInSequences:e.enrollInSequences===!0,optInMode:d},i);break}case"remove_subscribers_from_list":{let i=e.companyId,s=u("remove_subscribers_from_list",e,"listId"),r=rn("remove_subscribers_from_list",e);n=await a("POST",`/api/v1/lists/${encodeURIComponent(s)}/subscribers/remove`,{emails:r},i);break}case"list_segments":{let i=e.companyId;n=await a("GET","/api/v1/segments",void 0,i);break}case"create_segment":{Ln(e);let i=e.companyId;n=await a("POST","/api/v1/segments",{...e,...e.filters!==void 0?{filters:Ye(e.filters)}:{},...e.root!==void 0?{root:Je(e.root)}:{}},i);break}case"update_segment":{$n(e);let i=e.companyId,s=u("update_segment",e,"segmentId"),r=l(e,"name"),o=S("update_segment",e,"filterJoinOperator",["and","or"]);n=await a("PATCH",`/api/v1/segments/${encodeURIComponent(s)}`,{...r!==void 0&&{name:r},...o!==void 0&&{filterJoinOperator:o},...e.filters!==void 0?{filters:Ye(e.filters)}:{},...e.root!==void 0?{root:Je(e.root)}:{}},i);break}case"delete_segment":{let i=e.companyId,s=u("delete_segment",e,"segmentId");n=await a("DELETE",`/api/v1/segments/${encodeURIComponent(s)}`,void 0,i);break}case"get_segment_count":{let i=e.companyId;n=await a("GET",`/api/v1/segments/${e.segmentId}/count`,void 0,i);break}case"list_audience_syncs":{let i=e.companyId;n=await a("GET","/api/v1/audience-syncs",void 0,i);break}case"list_ad_accounts":{let i=e.companyId;n=await a("GET","/api/v1/ad-accounts",void 0,i);break}case"create_audience_sync":{let i=e.companyId,s=l(e,"segmentId"),r=l(e,"predefinedSegmentId");if(s&&r)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!s&&!r)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");n=await a("POST","/api/v1/audience-syncs",{segmentId:s,predefinedSegmentId:r,adAccountId:u("create_audience_sync",e,"adAccountId"),audienceName:u("create_audience_sync",e,"audienceName"),...e.frequency!==void 0?{frequency:e.frequency}:{}},i);break}case"update_audience_sync":{let i=e.companyId,s=u("update_audience_sync",e,"syncId");n=await a("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(s)}`,{...e.frequency!==void 0?{frequency:e.frequency}:{},...e.isActive!==void 0?{isActive:e.isActive}:{}},i);break}case"delete_audience_sync":{let i=e.companyId,s=u("delete_audience_sync",e,"syncId");n=await a("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(s)}`,void 0,i);break}case"sync_audience_now":{let i=e.companyId,s=u("sync_audience_now",e,"syncId");n=await a("POST",`/api/v1/audience-syncs/${encodeURIComponent(s)}/sync`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function ks(t,e){let n;switch(t){case"list_templates":{let i=e.companyId,s=new URLSearchParams,r=l(e,"label");if(r)s.set("label",r);let o=P("list_templates",e,"limit",1,100);if(o!==void 0)s.set("limit",String(o));let d=P("list_templates",e,"offset",0,1e6);if(d!==void 0)s.set("offset",String(d));n=await a("GET",`/api/v1/templates${s.size>0?`?${s}`:""}`,void 0,i);break}case"get_template":{let i=e.companyId;n=await a("GET",`/api/v1/templates/${e.templateId}`,void 0,i);break}case"create_template":{let i=e.companyId;pi(e);let s=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="companyId"));n=await a("POST","/api/v1/templates",s,i);break}case"update_template":{let i=e.companyId,s=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels"]),r=Object.keys(e).filter((o)=>!s.has(o));if(r.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`labels\` update fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);if(F("update_template",e),X("update_template",e),e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&e.html===void 0&&e.blocks===void 0&&e.labels===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, or `labels` when calling `update_template`.");n=await a("PUT",`/api/v1/templates/${e.templateId}`,e,i);break}case"set_template_localization":{let i=e.companyId,s=u("set_template_localization",e,"templateId"),r=u("set_template_localization",e,"locale"),o=u("set_template_localization",e,"subject"),d=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),c=Object.keys(e).filter((f)=>!d.has(f));if(c.length>0)throw Error(`\`set_template_localization\` received unsupported field${c.length===1?"":"s"}: ${c.map((f)=>`\`${f}\``).join(", ")}.`);F("set_template_localization",e,{requireContent:!0});let m={subject:o};if(e.previewText!==void 0)m.previewText=e.previewText;if(e.html!==void 0)m.html=e.html;if(e.blocks!==void 0)m.blocks=e.blocks;n=await a("PUT",`/api/v1/templates/${encodeURIComponent(s)}/localizations/${encodeURIComponent(r)}`,m,i);break}case"sync_template_localizations":{let i=e.companyId,s=u("sync_template_localizations",e,"templateId"),r=new Set(["companyId","templateId","locales"]),o=Object.keys(e).filter((c)=>!r.has(c));if(o.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${o.length===1?"":"s"}: ${o.map((c)=>`\`${c}\``).join(", ")}.`);let d;if(e.locales!==void 0){if(!Array.isArray(e.locales)||e.locales.length===0||e.locales.some((c)=>typeof c!=="string"||c.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");d=e.locales.map((c)=>c.trim())}n=await a("POST",`/api/v1/templates/${encodeURIComponent(s)}/localizations/sync`,d===void 0?{}:{locales:d},i);break}case"delete_template":{let i=e.companyId;n=await a("DELETE",`/api/v1/templates/${e.templateId}`,void 0,i);break}case"share_template":{let i=e.companyId,s=u("share_template",e,"templateId");n=await a("POST",`/api/v1/templates/${encodeURIComponent(s)}/share-link`,void 0,i);break}case"unshare_template":{let i=e.companyId,s=u("unshare_template",e,"templateId");n=await a("DELETE",`/api/v1/templates/${encodeURIComponent(s)}/share-link`,void 0,i);break}case"list_ab_tests":{let i=e.companyId,s=new URLSearchParams,r=l(e,"sequenceId");if(r)s.set("sequenceId",r);n=await a("GET",`/api/v1/ab-tests${s.size>0?`?${s}`:""}`,void 0,i);break}case"get_ab_test":{let i=e.companyId;n=await a("GET",`/api/v1/ab-tests/${e.abTestId}`,void 0,i);break}case"get_ab_test_stats":{let i=e.companyId,s=new URLSearchParams,r=l(e,"period"),o=l(e,"start"),d=l(e,"end");if(r)s.set("period",r);if(o)s.set("start",o);if(d)s.set("end",d);if(e.includeMachineEngagement===!0)s.set("includeMachineEngagement","true");n=await a("GET",`/api/v1/ab-tests/${e.abTestId}/stats${s.size>0?`?${s}`:""}`,void 0,i);break}case"restart_ab_test":{let i=e.companyId,s=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),r=Object.keys(e).filter((m)=>!s.has(m));if(r.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${r.length===1?"":"s"}: ${r.map((m)=>`\`${m}\``).join(", ")}.`);let o=l(e,"testType");if(o!==void 0&&o!=="subject"&&o!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let d=e.winnerThreshold===void 0?void 0:Number(e.winnerThreshold);if(d!==void 0&&(!Number.isInteger(d)||d<10||d>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let c=e.variantCount===void 0?void 0:Number(e.variantCount);if(c!==void 0&&(!Number.isInteger(c)||c<2||c>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");n=await a("POST",`/api/v1/ab-tests/${e.abTestId}/restart`,{sourceVariantId:l(e,"sourceVariantId"),testType:o,winnerThreshold:d,variantCount:c},i);break}case"select_ab_test_winner":{let i=e.companyId,s=u("select_ab_test_winner",e,"abTestId"),r=u("select_ab_test_winner",e,"variantId");n=await a("POST",`/api/v1/ab-tests/${s}/select-winner`,{variantId:r},i);break}case"update_ab_test_variant":{let i=e.companyId,s=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),r=Object.keys(e).filter((o)=>!s.has(o));if(r.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);if(F("update_ab_test_variant",e),e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(e.subject===void 0&&e.previewText===void 0&&e.html===void 0&&e.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");n=await a("PATCH",`/api/v1/ab-tests/${e.abTestId}/variants/${e.variantId}`,e,i);break}case"update_ab_test":{let i=e.companyId,s=u("update_ab_test",e,"abTestId"),r=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),o=Object.keys(e).filter((_)=>!r.has(_));if(o.length>0)throw Error(`\`update_ab_test\` received unsupported field${o.length===1?"":"s"}: ${o.map((_)=>`\`${_}\``).join(", ")}.`);if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let d=l(e,"name"),c=P("update_ab_test",e,"testPercentage",5,50),m=P("update_ab_test",e,"testDurationMinutes",15,1440),f=S("update_ab_test",e,"winnerCriteria",["open_rate","click_rate"]),w=S("update_ab_test",e,"testType",["subject","content"]),g=P("update_ab_test",e,"winnerThreshold",10,1000);if(d===void 0&&c===void 0&&m===void 0&&f===void 0&&w===void 0&&g===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");n=await a("PATCH",`/api/v1/ab-tests/${encodeURIComponent(s)}`,{...d!==void 0&&{name:d},...c!==void 0&&{testPercentage:c},...m!==void 0&&{testDurationMinutes:m},...f!==void 0&&{winnerCriteria:f},...w!==void 0&&{testType:w},...g!==void 0&&{winnerThreshold:g},...e.confirmLiveChange===!0&&{confirmLiveChange:!0}},i);break}case"create_ab_test":{let i=e.companyId,s=l(e,"campaignId"),r=l(e,"automationNodeId");if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(s)===Boolean(r))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let o=l(e,"name"),d=P("create_ab_test",e,"testPercentage",5,50),c=P("create_ab_test",e,"testDurationMinutes",15,1440),m=S("create_ab_test",e,"winnerCriteria",["open_rate","click_rate"]),f=S("create_ab_test",e,"testType",["subject","content"]),w=P("create_ab_test",e,"winnerThreshold",10,1000);if(e.variants!==void 0){if(!Array.isArray(e.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");e.variants.forEach((_,q)=>{if(!I(_)||typeof _.subject!=="string"||_.subject.trim()==="")throw Error(`\`variants\` item ${q+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(_.blocks!==void 0&&!Array.isArray(_.blocks))throw Error(`\`variants\` item ${q+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let g=Array.isArray(e.variants)?e.variants:void 0;if(r!==void 0&&(!g||g.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(g&&g.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");n=await a("POST","/api/v1/ab-tests",{...s!==void 0&&{campaignId:s},...r!==void 0&&{automationNodeId:r},...e.confirmLiveChange===!0&&{confirmLiveChange:!0},...o!==void 0&&{name:o},...d!==void 0&&{testPercentage:d},...c!==void 0&&{testDurationMinutes:c},...m!==void 0&&{winnerCriteria:m},...f!==void 0&&{testType:f},...w!==void 0&&{winnerThreshold:w},...e.variants!==void 0&&{variants:e.variants}},i);break}case"add_ab_test_variant":{let i=e.companyId,s=u("add_ab_test_variant",e,"abTestId"),r=u("add_ab_test_variant",e,"subject"),o=l(e,"previewText");if(e.blocks!==void 0&&!Array.isArray(e.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");n=await a("POST",`/api/v1/ab-tests/${encodeURIComponent(s)}/variants`,{subject:r,...o!==void 0&&{previewText:o},...e.blocks!==void 0&&{blocks:e.blocks},...e.confirmLiveChange===!0&&{confirmLiveChange:!0}},i);break}case"delete_ab_test_variant":{let i=e.companyId,s=u("delete_ab_test_variant",e,"abTestId"),r=u("delete_ab_test_variant",e,"variantId");if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");n=await a("DELETE",`/api/v1/ab-tests/${encodeURIComponent(s)}/variants/${encodeURIComponent(r)}${e.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,i);break}case"delete_ab_test":{let i=e.companyId,s=u("delete_ab_test",e,"abTestId");n=await a("DELETE",`/api/v1/ab-tests/${encodeURIComponent(s)}`,void 0,i);break}case"list_campaigns":{let i=e.companyId,s=new URLSearchParams;if(e.status)s.set("status",String(e.status));let r=l(e,"label");if(r)s.set("label",r);for(let o of["limit","offset"])if(e[o]!==void 0)s.set(o,String(e[o]));n=await a("GET",`/api/v1/campaigns?${s}`,void 0,i);break}case"get_campaign":{let i=e.companyId;n=await a("GET",`/api/v1/campaigns/${e.campaignId}`,void 0,i);break}case"get_campaign_audience":{let i=e.companyId;n=await a("GET",`/api/v1/campaigns/${encodeURIComponent(String(e.campaignId))}/audience`,void 0,i);break}case"get_email_send":{let i=e.companyId;n=await a("GET",`/api/v1/email-sends/${encodeURIComponent(String(e.emailSendId))}`,void 0,i);break}case"list_email_sends":{let i=e.companyId,s=new URLSearchParams,r=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let x of r){let A=l(e,x);if(A)s.set(x,A)}let o=S("list_email_sends",e,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),d=S("list_email_sends",e,"emailType",["campaign","transactional","sequence"]),c=S("list_email_sends",e,"bounceType",["Permanent","Transient"]),m=S("list_email_sends",e,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),f=S("list_email_sends",e,"sortOrder",["asc","desc"]),w=P("list_email_sends",e,"days",1,14),g=P("list_email_sends",e,"page",1,Number.MAX_SAFE_INTEGER),_=P("list_email_sends",e,"limit",1,100),q=[["status",o],["emailType",d],["bounceType",c],["sortField",m],["sortOrder",f],["days",w],["page",g],["limit",_]];for(let[x,A]of q)if(A!==void 0)s.set(x,String(A));let E=s.toString();n=await a("GET",`/api/v1/email-sends${E?`?${E}`:""}`,void 0,i);break}case"create_campaign":{let i=e.companyId;li(e),re("create_campaign",e);let s=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="companyId"));n=await a("POST","/api/v1/campaigns",s,i);break}case"update_campaign":{let i=e.companyId,s=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","emailPreset","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","listIds","labels","sendTimeOptimization","sendTimeWindowHours"]),r=Object.keys(e).filter((o)=>!s.has(o));if(r.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, label, and delivery pacing update fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);if(F("update_campaign",e),X("update_campaign",e),zt("update_campaign",e),Bt("update_campaign",e),re("update_campaign",e,{replyFirst:!0}),[e.segmentId,e.listIds,e.targetLists].filter((o)=>o!==void 0).length>1)throw Error("Provide at most one of `segmentId`, `listIds`, or `targetLists` when calling `update_campaign`.");if(e.name===void 0&&e.subject===void 0&&e.trackingCode===void 0&&e.html===void 0&&e.blocks===void 0&&e.emailPreset===void 0&&e.fromEmail===void 0&&e.senderProfileId===void 0&&e.replyTo===void 0&&e.replyProfileId===void 0&&e.ccEmails===void 0&&e.bccEmails===void 0&&e.campaignData===void 0&&e.computedLists===void 0&&e.targetLists===void 0&&e.segmentId===void 0&&e.listIds===void 0&&e.labels===void 0&&e.sendTimeOptimization===void 0&&e.sendTimeWindowHours===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, label, or delivery pacing field when calling `update_campaign`.");n=await a("PUT",`/api/v1/campaigns/${e.campaignId}`,e,i);break}case"schedule_campaign":{let i=e.companyId,s=new Set(["companyId","campaignId","scheduledAt","targetLists","listIds","sendTimeOptimization","sendTimeWindowHours","spreadOverHours","sendInRecipientTimezone","scheduledTimezone","recurringInterval"]),r=Object.keys(e).filter((o)=>!s.has(o));if(r.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`listIds\`, \`sendTimeOptimization\`, \`sendTimeWindowHours\`, \`spreadOverHours\`, \`sendInRecipientTimezone\`, \`scheduledTimezone\`, and \`recurringInterval\`. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);ui(e),n=await a("POST",`/api/v1/campaigns/${e.campaignId}/schedule`,{scheduledAt:e.scheduledAt,...e.targetLists!==void 0&&{targetLists:e.targetLists},...e.listIds!==void 0&&{listIds:e.listIds},...e.sendTimeOptimization!==void 0&&{sendTimeOptimization:e.sendTimeOptimization},...e.sendTimeWindowHours!==void 0&&{sendTimeWindowHours:e.sendTimeWindowHours},...e.spreadOverHours!==void 0&&{spreadOverHours:e.spreadOverHours},...e.sendInRecipientTimezone!==void 0&&{sendInRecipientTimezone:e.sendInRecipientTimezone},...e.scheduledTimezone!==void 0&&{scheduledTimezone:e.scheduledTimezone},...e.recurringInterval!==void 0&&{recurringInterval:e.recurringInterval}},i);break}case"send_test_email":{let i=e.companyId;n=await a("POST",`/api/v1/campaigns/${e.campaignId}/test`,{to:e.to},i);break}case"cancel_campaign":{let i=e.companyId,s=u("cancel_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/cancel`,void 0,i);break}case"share_campaign":{let i=e.companyId,s=u("share_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/share-link`,void 0,i);break}case"unshare_campaign":{let i=e.companyId,s=u("unshare_campaign",e,"campaignId");n=await a("DELETE",`/api/v1/campaigns/${encodeURIComponent(s)}/share-link`,void 0,i);break}case"unschedule_campaign":{let i=e.companyId,s=u("unschedule_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/unschedule`,void 0,i);break}case"pause_campaign":{let i=e.companyId,s=u("pause_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/pause`,void 0,i);break}case"resume_campaign":{let i=e.companyId,s=u("resume_campaign",e,"campaignId"),r=P("resume_campaign",e,"spreadOverHours",1,72);n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/resume`,{...r!==void 0&&{spreadOverHours:r}},i);break}case"delete_campaign":{let i=e.companyId,s=u("delete_campaign",e,"campaignId");n=await a("DELETE",`/api/v1/campaigns/${encodeURIComponent(s)}`,void 0,i);break}case"duplicate_campaign":{let i=e.companyId,s=u("duplicate_campaign",e,"campaignId"),r=S("duplicate_campaign",e,"mode",["campaign","ab_test","variant"]),o=l(e,"variantId");if(r==="variant"&&o===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/duplicate`,{...r!==void 0&&{mode:r},...o!==void 0&&{variantId:o}},i);break}case"resend_campaign_to_non_openers":{let i=e.companyId,s=u("resend_campaign_to_non_openers",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(s)}/resend-to-non-openers`,void 0,i);break}case"list_campaign_goals":{let i=e.companyId,s=u(t,e,"campaignId");n=await a("GET",`/api/v1/campaigns/${encodeURIComponent(s)}/goals`,void 0,i);break}case"create_campaign_goal":case"update_campaign_goal":{let i=e.companyId,s=u(t,e,"campaignId");if(t==="create_campaign_goal")u(t,e,"name"),Kn(e);else Yn(e);let r=t==="update_campaign_goal"?u(t,e,"goalId"):void 0,o={...e};delete o.companyId,delete o.campaignId,delete o.goalId,n=await a(t==="create_campaign_goal"?"POST":"PATCH",`/api/v1/campaigns/${encodeURIComponent(s)}/goals${r?`/${encodeURIComponent(r)}`:""}`,o,i);break}case"delete_campaign_goal":{let i=e.companyId,s=u(t,e,"campaignId"),r=u(t,e,"goalId");n=await a("DELETE",`/api/v1/campaigns/${encodeURIComponent(s)}/goals/${encodeURIComponent(r)}`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function Ss(t,e){if(t!=="get_email_block_schema")return{handled:!1,result:void 0};let n=l(e,"blockType");if(n!==void 0){let r=e.conditionFields===!0?"?conditionFields=true":"";return{handled:!0,result:await a("GET",`/api/v1/email-blocks/${encodeURIComponent(n)}${r}`)}}let i=e.creatableOnly===!0?"/api/v1/email-blocks?creatableOnly=true":"/api/v1/email-blocks";return{handled:!0,result:await a("GET",i)}}function yn(t,e){let n=e.blocks;if(!Array.isArray(n))throw Error(`\`blocks\` must be an array of block objects when calling \`${t}\`.`);return n}var So=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 qs(t,e){if(!So.has(t))return{handled:!1,result:void 0};let n=l(e,"companyId");if(t==="list_email_components"){let r=new URLSearchParams,o=l(e,"type");if(o)r.set("type",o);if(e.defaultsOnly===!0)r.set("defaultsOnly","true");return{handled:!0,result:await a("GET",`/api/v1/email-components${r.size>0?`?${r}`:""}`,void 0,n)}}if(t==="get_email_component"){let r=u(t,e,"componentId");return{handled:!0,result:await a("GET",`/api/v1/email-components/${encodeURIComponent(r)}`,void 0,n)}}if(t==="get_default_email_component"){let r=u(t,e,"slot");return{handled:!0,result:await a("GET",`/api/v1/email-components/defaults/${encodeURIComponent(r)}`,void 0,n)}}if(t==="set_default_email_component"){let r=u(t,e,"slot"),d={blocks:yn(t,e)},c=l(e,"name"),m=l(e,"description");if(c!==void 0)d.name=c;if(m!==void 0)d.description=m;return{handled:!0,result:await a("PUT",`/api/v1/email-components/defaults/${encodeURIComponent(r)}`,d,n)}}if(t==="create_email_component"){let r={name:u(t,e,"name"),blocks:yn(t,e)},o=l(e,"description"),d=l(e,"componentType");if(o!==void 0)r.description=o;if(d!==void 0)r.componentType=d;return{handled:!0,result:await a("POST","/api/v1/email-components",r,n)}}if(t==="update_email_component"){let r=u(t,e,"componentId"),o={},d=l(e,"name"),c=l(e,"description"),m=l(e,"componentType");if(d!==void 0)o.name=d;if(c!==void 0)o.description=c;if(m!==void 0)o.componentType=m;if(e.blocks!==void 0)o.blocks=yn(t,e);return{handled:!0,result:await a("PATCH",`/api/v1/email-components/${encodeURIComponent(r)}`,o,n)}}let i=u(t,e,"componentId");return{handled:!0,result:await a("DELETE",`/api/v1/email-components/${encodeURIComponent(i)}`,void 0,n)}}async function Ts(t,e){if(t!=="get_event_schema")return{handled:!1,result:void 0};let n=new URLSearchParams,i=l(e,"eventName");if(i)n.set("eventName",i);let s=l(e,"provider");if(s)n.set("provider",s);let r=n.toString();return{handled:!0,result:await a("GET",`/api/v1/events/schemas${r?`?${r}`:""}`,void 0,l(e,"companyId"))}}async function Ps(t,e){let n;switch(t){case"list_forms":{let i=e.companyId;n=await a("GET","/api/v1/forms",void 0,i);break}case"create_form":{let i=e.companyId,s=u("create_form",e,"name"),r=Array.isArray(e.listIds)?e.listIds.filter((c)=>typeof c==="string").map((c)=>c.trim()).filter(Boolean):[];if(r.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let o=S("create_form",e,"duplicateStrategy",["skip","merge","overwrite"]),d={name:s,listIds:r};for(let c of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(e[c]!==void 0)d[c]=e[c];if(o!==void 0)d.duplicateStrategy=o;n=await a("POST","/api/v1/forms",d,i);break}case"update_form":{let i=e.companyId,s=u("update_form",e,"formId"),r=S("update_form",e,"duplicateStrategy",["skip","merge","overwrite"]),o={};for(let d of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(e[d]!==void 0)o[d]=e[d];if(r!==void 0)o.duplicateStrategy=r;if(Object.keys(o).length===0)throw Error("Provide at least one field to change when calling `update_form`.");n=await a("PATCH",`/api/v1/forms/${encodeURIComponent(s)}`,o,i);break}case"get_form_embed":{let i=e.companyId,s=u("get_form_embed",e,"formId");n=await a("GET",`/api/v1/forms/embed/${encodeURIComponent(s)}`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function ct(t,e,n,i,s){let r=t[e];if(r===void 0)return;if(typeof r!=="number"||!Number.isFinite(r)||r<n||r>i||s&&!Number.isInteger(r))throw Error(`\`${e}\` must be a ${s?"integer":"number"} between ${n} and ${i} when calling \`upload_image_asset\`.`);return r}async function Es(t,e){if(t!=="upload_image_asset")return{handled:!1,result:void 0};let n=l(e,"filePath"),i=l(e,"imageBase64");if(n===void 0===(i===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let s=l(e,"filename");if(i!==void 0&&s===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let r=ct(e,"sourceWidth",1,20000,!0),o=ct(e,"sourceHeight",1,20000,!0);if(r===void 0!==(o===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let d=ct(e,"displayWidthPercent",1,100,!1)??100,c=ct(e,"cropHeight",1,2000,!0),m=l(e,"objectFit");if(m!==void 0&&m!=="cover"&&m!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(m!==void 0&&c===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let f=l(e,"align");if(f!==void 0&&!["left","center","right"].includes(f))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let w=typeof e.altText==="string"?e.altText.trim():void 0;if(w!==void 0&&w.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let g=await Di({companyId:l(e,"companyId"),filePath:n,imageBase64:i,filename:s,contentType:l(e,"contentType"),altText:w,sourceWidth:r,sourceHeight:o}),_={type:"image",src:g.url,alt:g.altText??"",width:d,widthType:"percent",...c!==void 0&&{height:c,objectFit:m??"cover"},...f!==void 0&&{align:f}};return{handled:!0,result:{success:!0,asset:g,imageBlock:_,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}function xs(t,e,n){if(t===void 0)return;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`\`${e}\` must be an object when calling \`${n}\`.`);let i={};for(let[s,r]of Object.entries(t)){if(!s.trim()||typeof r!=="string"||!r.trim())throw Error(`\`${e}\` must map non-empty Sequenzy list IDs to non-empty Attio list IDs or slugs when calling \`${n}\`.`);i[s]=r}return i}async function Cs(t,e){let n=e.companyId,i;switch(t){case"connect_integration":{let s=u("connect_integration",e,"provider");if(s!=="attio")u("connect_integration",e,"webhookSecret");if(s==="attio")u("connect_integration",e,"apiKey");let r=typeof e.webhookSecret==="string"?e.webhookSecret:void 0,o=e.settings!==void 0&&typeof e.settings==="object"&&e.settings!==null&&!Array.isArray(e.settings)?e.settings:void 0,d=xs(o?.listMap,"settings.listMap","connect_integration");i=await a("POST","/api/v1/integrations/connect",{provider:s,...r?{webhookSecret:r}:{},...typeof e.apiKey==="string"&&e.apiKey?{apiKey:e.apiKey}:{},...typeof e.providerAccountId==="string"&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...o?{settings:{...typeof o.syncAllEvents==="boolean"?{syncAllEvents:o.syncAllEvents}:{},...Array.isArray(o.eventAllowlist)?{eventAllowlist:o.eventAllowlist.filter((c)=>typeof c==="string")}:{},...d!==void 0?{listMap:d}:{},...typeof o.syncCompanyFromDomain==="boolean"?{syncCompanyFromDomain:o.syncCompanyFromDomain}:{}}}:{},...e.historyImport!==void 0?{historyImport:e.historyImport}:{}},n);break}case"get_integration":{let s=u("get_integration",e,"integrationId");i=await a("GET",`/api/v1/integrations/${encodeURIComponent(s)}`,void 0,n);break}case"list_integration_capabilities":{let s=new URLSearchParams;if(typeof e.provider==="string"&&e.provider)s.set("provider",e.provider);if(typeof e.category==="string"&&e.category)s.set("category",e.category);let r=s.toString();i=await a("GET",`/api/v1/integrations/catalog${r?`?${r}`:""}`,void 0,n);break}case"list_integration_activity":{let s=new URLSearchParams;if(typeof e.integrationId==="string"&&e.integrationId)s.set("integrationId",e.integrationId);if(typeof e.provider==="string"&&e.provider)s.set("provider",e.provider);if(typeof e.status==="string"&&e.status)s.set("status",e.status);if(typeof e.limit==="number")s.set("limit",String(e.limit));let r=s.toString();i=await a("GET",`/api/v1/integrations/activity${r?`?${r}`:""}`,void 0,n);break}case"set_integration_sync_enabled":{let s=u("set_integration_sync_enabled",e,"integrationId");if(typeof e.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");i=await a("PATCH",`/api/v1/integrations/${encodeURIComponent(s)}`,{syncEnabled:e.syncEnabled},n);break}case"set_integration_list_targeting":{let s=u("set_integration_list_targeting",e,"integrationId");if(e.listIds===void 0)throw Error("`listIds` is required when calling `set_integration_list_targeting`. Pass an array of list IDs, `[]` to join no list, or null to fall back to the workspace default lists.");if(e.listIds!==null&&!Array.isArray(e.listIds))throw Error("`listIds` must be an array of list IDs, or null to fall back to the workspace default lists.");i=await a("PATCH",`/api/v1/integrations/${encodeURIComponent(s)}`,{listIds:e.listIds},n);break}case"get_integration_pixel":{let s=u("get_integration_pixel",e,"integrationId");i=await a("GET",`/api/v1/integrations/${encodeURIComponent(s)}/pixel`,void 0,n);break}case"activate_integration_pixel":{let s=u("activate_integration_pixel",e,"integrationId");i=await a("POST",`/api/v1/integrations/${encodeURIComponent(s)}/pixel`,void 0,n);break}case"sync_integration":{let s=u("sync_integration",e,"integrationId");i=await a("POST",`/api/v1/integrations/${encodeURIComponent(s)}/sync`,void 0,n);break}case"get_attio_mapping":{let s=u("get_attio_mapping",e,"integrationId");i=await a("GET",`/api/v1/integrations/${encodeURIComponent(s)}/attio`,void 0,n);break}case"update_attio_settings":{let s=u("update_attio_settings",e,"integrationId"),r=xs(e.listMap,"listMap","update_attio_settings");if(r===void 0&&typeof e.syncCompanyFromDomain!=="boolean")throw Error("Provide at least one of `listMap` or `syncCompanyFromDomain` when calling `update_attio_settings`.");i=await a("PATCH",`/api/v1/integrations/${encodeURIComponent(s)}/attio`,{...r!==void 0?{listMap:r}:{},...typeof e.syncCompanyFromDomain==="boolean"?{syncCompanyFromDomain:e.syncCompanyFromDomain}:{}},n);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:i}}async function Ds(t,e){let n;switch(t){case"list_landing_pages":{let i=e.companyId;n=await a("GET","/api/v1/landing-pages",void 0,i);break}case"get_landing_page":{let i=e.companyId;n=await a("GET",`/api/v1/landing-pages/${e.landingPageId}`,void 0,i);break}case"get_landing_page_stats":{let i=e.companyId,s=new URLSearchParams;if(typeof e.period==="string")s.set("period",e.period);if(typeof e.start==="string")s.set("start",e.start);if(typeof e.end==="string")s.set("end",e.end);if(e.includeBots===!0)s.set("includeBots","true");let r=s.toString();n=await a("GET",`/api/v1/landing-pages/${e.landingPageId}/stats${r?`?${r}`:""}`,void 0,i);break}case"render_landing_page":{let i=e.companyId;n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/render`,void 0,i);break}case"create_landing_page":{let i=e.companyId,s=new Set(["companyId","name","slug","template","content"]),r=Object.keys(e).filter((o)=>!s.has(o));if(r.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);n=await a("POST","/api/v1/landing-pages",{...e.name!==void 0&&{name:e.name},...e.slug!==void 0&&{slug:e.slug},...e.template!==void 0&&{template:e.template},...e.content!==void 0&&{content:e.content}},i);break}case"update_landing_page":{let i=e.companyId,s=tt("update_landing_page",e,{requireUpdate:!0});n=await a("PUT",`/api/v1/landing-pages/${e.landingPageId}`,s,i);break}case"publish_landing_page":{let i=e.companyId,s=tt("publish_landing_page",e,{requireUpdate:!1});n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/publish`,s,i);break}case"unpublish_landing_page":{let i=e.companyId,s=tt("unpublish_landing_page",e,{requireUpdate:!1});n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/unpublish`,s,i);break}case"duplicate_landing_page":{let i=e.companyId;n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/duplicate`,{...e.name!==void 0&&{name:e.name},...e.slug!==void 0&&{slug:e.slug}},i);break}case"delete_landing_page":{let i=e.companyId;n=await a("DELETE",`/api/v1/landing-pages/${e.landingPageId}`,void 0,i);break}case"connect_landing_page_domain":{let{companyId:i,landingPageId:s}=e;n=await a("POST",s?`/api/v1/landing-pages/${encodeURIComponent(s)}/domain`:"/api/v1/landing-pages/domain",{domain:e.domain},i);break}case"update_landing_page_domain_settings":{let i=e.companyId,s=mi(e),r=e.landingPageId;if(!r){n=await a("PUT","/api/v1/landing-pages/domain",s,i);break}let o=`/api/v1/landing-pages/${encodeURIComponent(r)}/domain`;if(e.domain!==void 0)n=await a("POST",o,{domain:e.domain},i);if(e.verify===!0)n=await a("POST",`${o}/verify`,void 0,i);break}case"remove_landing_page_domain":{let{companyId:i,landingPageId:s}=e;n=await a("DELETE",`/api/v1/landing-pages/${encodeURIComponent(s)}/domain`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}var Rs=["listIds","tagIds","headline","description","buttonText","successMessage","redirectUrl","presentation","placement","trigger","targeting","schedule","frequency","visual","theme","blocks"];async function As(t,e){let n;switch(t){case"list_popups":{let i=e.companyId,s=e.includeContent===!0;n=await a("GET",s?"/api/v1/popups?includeContent=true":"/api/v1/popups",void 0,i);break}case"get_popup":{let i=e.companyId,s=u("get_popup",e,"popupId");n=await a("GET",`/api/v1/popups/${encodeURIComponent(s)}`,void 0,i);break}case"create_popup":{let i=e.companyId,s=u("create_popup",e,"name"),r=S("create_popup",e,"duplicateStrategy",["skip","merge","overwrite"]),o=S("create_popup",e,"status",["draft","published"]),d=e.template,c={name:s};for(let m of Rs)if(e[m]!==void 0)c[m]=e[m];if(r!==void 0)c.duplicateStrategy=r;if(o!==void 0)c.status=o;if(d!==void 0)c.template=d;n=await a("POST","/api/v1/popups",c,i);break}case"update_popup":{let i=e.companyId,s=u("update_popup",e,"popupId"),r=S("update_popup",e,"duplicateStrategy",["skip","merge","overwrite"]),o=S("update_popup",e,"status",["draft","published"]),d={};if(e.name!==void 0)d.name=e.name;for(let c of Rs)if(e[c]!==void 0)d[c]=e[c];if(r!==void 0)d.duplicateStrategy=r;if(o!==void 0)d.status=o;if(Object.keys(d).length===0)throw Error("Provide at least one field to change when calling `update_popup`.");n=await a("PATCH",`/api/v1/popups/${encodeURIComponent(s)}`,d,i);break}case"get_popup_embed":{let i=e.companyId,s=u("get_popup_embed",e,"popupId");n=await a("GET",`/api/v1/popups/embed/${encodeURIComponent(s)}`,void 0,i);break}case"duplicate_popup":{let i=e.companyId,s=u("duplicate_popup",e,"popupId"),r={};if(e.name!==void 0)r.name=e.name;n=await a("POST",`/api/v1/popups/${encodeURIComponent(s)}/duplicate`,r,i);break}case"delete_popup":{let i=e.companyId,s=u("delete_popup",e,"popupId");n=await a("DELETE",`/api/v1/popups/${encodeURIComponent(s)}`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function Os(t,e){let n;switch(t){case"list_products":{let i=e.companyId,s=new URLSearchParams;if(typeof e.provider==="string"&&e.provider.trim())s.set("provider",e.provider.trim());if(typeof e.search==="string"&&e.search.trim())s.set("search",e.search.trim());let r=P("list_products",e,"limit",1,100);if(r!==void 0)s.set("limit",String(r));let o=P("list_products",e,"offset",0,Number.MAX_SAFE_INTEGER);if(o!==void 0)s.set("offset",String(o));let d=s.size>0?`?${s.toString()}`:"";n=await a("GET",`/api/v1/products${d}`,void 0,i);break}case"upsert_products":{let i=e.companyId;if(!Array.isArray(e.products)||e.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");n=await a("POST","/api/v1/products",{products:e.products},i);break}case"delete_product":{let i=e.companyId,s=u("delete_product",e,"productId");n=await a("DELETE",`/api/v1/products/${encodeURIComponent(s)}`,void 0,i);break}case"attach_product_file":{let i=e.companyId,s=u("attach_product_file",e,"productId"),r=l(e,"url"),o=l(e,"filePath");if(r===void 0===(o===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let d;if(o!==void 0){let c=await qi(o,i);d={url:c.url,source:"upload",fileName:l(e,"fileName")??c.fileName,fileSizeBytes:c.fileSizeBytes,mimeType:c.mimeType}}else{d={url:r};let c=l(e,"fileName");if(c)d.fileName=c}n=await a("PUT",`/api/v1/products/${encodeURIComponent(s)}/delivery`,d,i);break}case"remove_product_file":{let i=e.companyId,s=u("remove_product_file",e,"productId");n=await a("DELETE",`/api/v1/products/${encodeURIComponent(s)}/delivery`,void 0,i);break}case"sync_products":{let i=e.companyId,s=new URLSearchParams;if(typeof e.integrationId==="string"&&e.integrationId)s.set("integrationId",e.integrationId);let r=s.toString();n=await a("POST",`/api/v1/products/sync${r?`?${r}`:""}`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function qo(t){let e=l(t,"campaignId"),n=l(t,"sequenceId"),i=l(t,"templateId"),s=[e,n,i].filter((r)=>r!==void 0);if(s.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(s.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(e!==void 0)return`/api/v1/campaigns/${encodeURIComponent(e)}/render`;if(n!==void 0){let r=u("render_email",t,"nodeId");return`/api/v1/sequences/${encodeURIComponent(n)}/nodes/${encodeURIComponent(r)}/render`}return`/api/v1/templates/${encodeURIComponent(i)}/render`}var To=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function Us(t,e){if(t!=="render_email")return{handled:!1,result:void 0};let n=qo(e),i={};for(let r of To)if(e[r]!==void 0)i[r]=e[r];return{handled:!0,result:await a("POST",n,i,l(e,"companyId"))}}var js=80,Ns=10;function Po(t){if(!Array.isArray(t.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(t.recipients.length>Ns)throw Error(`\`recipients\` must include no more than ${Ns} email addresses when calling \`send_sequence_test_email\`.`);if(t.recipients.find((s)=>typeof s!=="string"||s.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let n=Array.from(new Set(t.recipients.map((s)=>typeof s==="string"?s.trim().toLowerCase():""))).filter(Boolean);if(n.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let i=n.find((s)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s));if(i)throw Error(`Invalid test recipient email address: \`${i}\`.`);return n}function Eo(t){let e=t.trim().replace(/\s+/g," ");if(e.length<=js)return e;return`${e.slice(0,js-3).trimEnd()}...`}async function gn(t,e){let n;switch(t){case"generate_sequence":{let i=u("generate_sequence",e,"goal"),s=typeof e.name==="string"&&e.name.trim().length>0?e.name.trim():void 0,o=(await gn("create_sequence",{...e,goal:i,name:s??Eo(i),trigger:"contact_added",durationDays:e.durationDays??14})).result;return{handled:!0,result:typeof o==="object"&&o!==null?{...o,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:o}}case"list_sequences":{let i=e.companyId,s=new URLSearchParams;for(let o of["status","search","limit","offset"])if(e[o]!==void 0)s.set(o,String(e[o]));if(Array.isArray(e.labels)&&e.labels.length>0)s.set("labels",e.labels.join(","));let r=s.size>0?`?${s.toString()}`:"";n=await a("GET",`/api/v1/sequences${r}`,void 0,i);break}case"get_sequence":{let i=e.companyId;n=await a("GET",`/api/v1/sequences/${e.sequenceId}`,void 0,i);break}case"get_sequence_enrollment":{let i=e.companyId,s=u(t,e,"sequenceId"),r=u(t,e,"enrollmentId");n=await a("GET",`/api/v1/sequences/${encodeURIComponent(s)}/enrollments/${encodeURIComponent(r)}`,void 0,i);break}case"simulate_sequence":{let i=e.companyId,s=u(t,e,"sequenceId"),r=l(e,"subscriberId"),o=l(e,"email"),d=P(t,e,"limit",1,25);if(r&&o)throw Error("Pass `subscriberId` or `email`, not both, when calling `simulate_sequence`.");let c=new URLSearchParams;if(r)c.set("subscriberId",r);if(o)c.set("email",o);if(d!==void 0)c.set("limit",String(d));let m=c.size>0?`?${c.toString()}`:"";n=await a("GET",`/api/v1/sequences/${encodeURIComponent(s)}/simulate${m}`,void 0,i);break}case"list_sequence_enrollments":{let i=e.companyId,s=u(t,e,"sequenceId"),r=new URLSearchParams;for(let d of["currentNodeId","status","subscriberId"]){let c=e[d];if(Array.isArray(c)){if(c.length>0)r.set(d,c.join(","))}else if(c!==void 0)r.set(d,String(c))}for(let d of["email","sort","limit","offset","stopConditionMatch"])if(e[d]!==void 0)r.set(d,String(e[d]));let o=r.size>0?`?${r.toString()}`:"";n=await a("GET",`/api/v1/sequences/${encodeURIComponent(s)}/enrollments${o}`,void 0,i);break}case"send_sequence_test_email":{let i=e.companyId,s=u(t,e,"sequenceId"),r=u(t,e,"nodeId"),o=Po(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(s)}/nodes/${encodeURIComponent(r)}/test`,{recipients:o},i);break}case"create_sequence":{let i=e.companyId;X("create_sequence",e),Ft("create_sequence",e,{defaultTrigger:"contact_added"}),re("create_sequence",e,{hasEmailSteps:!0});let s=Array.isArray(e.steps),r=e.goal===void 0&&e.steps===void 0,o=await a("POST","/api/v1/sequences",e,i);if(!o.success){n=o;break}let d=o.sequence.id;if(s||r){let g=await a("GET",`/api/v1/sequences/${d}`,void 0,i);if(g.success)n={...o,success:!0,sequence:g.sequence,message:`Sequence "${g.sequence.name}" created ${r?"as a blank draft":"with explicit steps"}. Review it before enabling.${o.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else n=g;break}let c=7,m=0,f="pending";while(f!=="complete"&&m<c){let g=await a("GET",`/api/v1/sequences/${d}`,void 0,i);if(g.success)f=g.sequence.enrichmentStatus;if(m++,f!=="complete"&&m<c)await new Promise((_)=>setTimeout(_,20000))}let w=await a("GET",`/api/v1/sequences/${d}`,void 0,i);if(w.success)n={...o,success:!0,sequence:w.sequence,message:w.sequence.enrichmentStatus==="complete"?`Sequence "${w.sequence.name}" created with ${w.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${o.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${w.sequence.name}" created. Email enrichment is still in progress (${w.sequence.enrichedCount}/${w.sequence.emailCount} emails generated). You can check status with get_sequence.${o.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else n=w;break}case"update_sequence":{let i=e.companyId,s=Bn(e);n=await a("PUT",`/api/v1/sequences/${e.sequenceId}`,s,i);break}case"update_sequence_node":{let i=e.companyId,s=u("update_sequence_node",e,"sequenceId"),r=ii(e);n=await a("PUT",`/api/v1/sequences/${s}`,r,i);break}case"update_sequence_nodes":{let i=e.companyId,s=u("update_sequence_nodes",e,"sequenceId"),r=si(e);n=await a("PUT",`/api/v1/sequences/${s}`,r,i);break}case"edit_sequence_graph":{let i=e.companyId,s=ri(e);n=await a("PUT",`/api/v1/sequences/${e.sequenceId}`,s,i);break}case"insert_sequence_step":{let i=e.companyId,s=oi(e),r=await a("PUT",`/api/v1/sequences/${e.sequenceId}`,s,i);if(typeof r==="object"&&r!==null){let o=r,d=o.sequence;if(typeof d==="object"&&d!==null){let c=d;n={...o,...c.insertedNodeIds!==void 0?{insertedNodeIds:c.insertedNodeIds}:{},...c.insertedEmailIds!==void 0?{insertedEmailIds:c.insertedEmailIds}:{},...c.insertedEmailCount!==void 0?{insertedEmailCount:c.insertedEmailCount}:{},...c.addedBranchNodeId!==void 0?{addedBranchNodeId:c.addedBranchNodeId}:{},...c.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:c.addedBranchPathNodeIds}:{}};break}}n=r;break}case"enable_sequence":{let i=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/enable`,void 0,i);break}case"disable_sequence":{let i=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/disable`,void 0,i);break}case"duplicate_sequence":{let i=e.companyId,s=u("duplicate_sequence",e,"sequenceId"),r=l(e,"name");n=await a("POST",`/api/v1/sequences/${encodeURIComponent(s)}/duplicate`,r===void 0?void 0:{name:r},i);break}case"archive_sequence":case"unarchive_sequence":{let i=e.companyId,s=u(t,e,"sequenceId"),r=t==="archive_sequence"?"archive":"unarchive";n=await a("POST",`/api/v1/sequences/${encodeURIComponent(s)}/${r}`,void 0,i);break}case"list_sequence_goals":{let i=e.companyId,s=u(t,e,"sequenceId");n=await a("GET",`/api/v1/sequences/${encodeURIComponent(s)}/goals`,void 0,i);break}case"create_sequence_goal":case"update_sequence_goal":{let i=e.companyId,s=u(t,e,"sequenceId");if(t==="create_sequence_goal")u(t,e,"name"),Gn(e);else Vn(e);let r=t==="update_sequence_goal"?u(t,e,"goalId"):void 0,o={...e};delete o.companyId,delete o.sequenceId,delete o.goalId,n=await a(t==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(s)}/goals${r?`/${encodeURIComponent(r)}`:""}`,o,i);break}case"delete_sequence_goal":{let i=e.companyId,s=u(t,e,"sequenceId"),r=u(t,e,"goalId");n=await a("DELETE",`/api/v1/sequences/${encodeURIComponent(s)}/goals/${encodeURIComponent(r)}`,void 0,i);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let i=e.companyId,s=u(t,e,"sequenceId");if(e.clearFieldMapping===!0&&e.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(e.clearSamplePayload===!0&&e.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let r=t==="configure_sequence_inbound_webhook",o=t==="rotate_sequence_inbound_webhook_secret",d=r?{...e.clearFieldMapping===!0?{fieldMapping:null}:e.fieldMapping!==void 0?{fieldMapping:e.fieldMapping}:{},...e.clearSamplePayload===!0?{samplePayload:null}:e.samplePayload!==void 0?{samplePayload:e.samplePayload}:{}}:void 0;n=await a(o?"POST":r?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(s)}/inbound-webhook${o?"/rotate-secret":""}`,d,i);break}case"pause_sequence_enrollments":{let i=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/pause-enrollments`,void 0,i);break}case"resume_sequence_enrollments":{let i=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/resume-enrollments`,void 0,i);break}case"enroll_subscribers_in_sequence":{let i=e.companyId,s=u("enroll_subscribers_in_sequence",e,"sequenceId"),r=vi(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(s)}/enroll`,r,i);break}case"cancel_sequence_enrollments":{let i=e.companyId,s=di(e);n=await a("POST",`/api/v1/sequences/${e.sequenceId}/enrollments/cancel`,s,i);break}case"move_sequence_enrollments":{let i=e.companyId,s=u("move_sequence_enrollments",e,"sequenceId"),r=ci(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(s)}/enrollments/move`,r,i);break}case"realign_sequence_enrollments":{let i=e.companyId,s=u("realign_sequence_enrollments",e,"sequenceId"),r=ai(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(s)}/enrollments/realign-sending-window`,r,i);break}case"get_sequence_enrollment_realignment":{let i=e.companyId,s=u(t,e,"sequenceId"),r=u(t,e,"jobId");n=await a("GET",`/api/v1/sequences/${encodeURIComponent(s)}/enrollments/realign-sending-window/jobs/${encodeURIComponent(r)}`,void 0,i);break}case"delete_sequence":{let i=e.companyId;n=await a("DELETE",`/api/v1/sequences/${e.sequenceId}`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function lt(t,e,n){let i=e[n];if(i===void 0)return;if(!Array.isArray(i))throw Error(`\`${n}\` must be an array of strings when calling \`${t}\`.`);let s=i.filter((r)=>typeof r==="string").map((r)=>r.trim()).filter((r)=>r.length>0);if(s.length!==i.length)throw Error(`\`${n}\` must contain only non-empty strings when calling \`${t}\`.`);return s}function xo(t,e){let n=lt(t,e,"tags");if(n===void 0||n.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${t}\`.`);let i=lt(t,e,"emails"),s=lt(t,e,"externalIds"),r=lt(t,e,"subscriberIds");if((i?.length??0)+(s?.length??0)+(r?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${t}\`.`);return{tags:n,...i?.length?{emails:i}:{},...s?.length?{externalIds:s}:{},...r?.length?{subscriberIds:r}:{},...t==="bulk_add_subscriber_tags"&&typeof e.triggerAutomations==="boolean"?{triggerAutomations:e.triggerAutomations}:{}}}async function Ms(t,e){let n;switch(t){case"add_subscriber":{let i=e.companyId,s=typeof e.phone==="string"&&e.phone.trim()!==""?e.phone.trim():void 0,r=s?en(e):K("add_subscriber",e),o=S("add_subscriber",e,"status",["active","unsubscribed","bounced"]),d=S("add_subscriber",e,"optInMode",["default","confirmed","double_opt_in"]);if(e.enrollInSequences!==void 0&&typeof e.enrollInSequences!=="boolean")throw Error("`enrollInSequences` must be a boolean when calling `add_subscriber`.");let c=Xt("add_subscriber",e);if(n=await a("POST","/api/v1/subscribers",{...r,...s!==void 0&&{phone:s},...typeof e.phoneCountry==="string"&&e.phoneCountry.trim()!==""&&{phoneCountry:e.phoneCountry.trim()},...typeof e.smsConsent==="boolean"&&{smsConsent:e.smsConsent},...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...typeof e.timezone==="string"&&{timezone:e.timezone.trim()||null},...c!==void 0&&{customAttributes:c.value},tags:e.tags,lists:e.listIds,...o!==void 0&&{status:o},...d!==void 0&&{optInMode:d},...typeof e.enrollInSequences==="boolean"&&{enrollInSequences:e.enrollInSequences},...e.createdAt!==void 0&&{createdAt:e.createdAt}},i),o!==void 0&&I(n)&&I(n.subscriber)&&n.subscriber.skipped===!0&&n.subscriber.status!==o)throw Error(`Existing subscriber was not changed to status '${o}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let i=e.companyId;if(!Array.isArray(e.subscribers)||e.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(e.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let o=0;o<e.subscribers.length;o+=1){let d=e.subscribers[o],c=I(d)&&typeof d.email==="string"&&d.email.trim()!=="",m=I(d)&&typeof d.phone==="string"&&d.phone.trim()!=="";if(!c&&!m)throw Error(`Subscriber record ${o} must include an email or a phone number.`)}let s=S("create_subscriber_import",e,"duplicateStrategy",["skip","merge","overwrite"]),r=S("create_subscriber_import",e,"optInMode",["default","confirmed","double_opt_in"]);n=await a("POST","/api/v1/subscribers/imports",{subscribers:e.subscribers,...s!==void 0&&{duplicateStrategy:s},...e.fileName!==void 0&&{fileName:e.fileName},...e.listIds!==void 0&&{listIds:e.listIds},...e.enrollInSequences!==void 0&&{enrollInSequences:e.enrollInSequences},...e.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:e.defaultPhoneCountry},...e.smsConsent!==void 0&&{smsConsent:e.smsConsent},...r!==void 0&&{optInMode:r},...e.idempotencyKey!==void 0&&{idempotencyKey:e.idempotencyKey}},i);break}case"get_subscriber_import":{let i=e.companyId,s=u("get_subscriber_import",e,"importId");n=await a("GET",`/api/v1/subscribers/imports/${encodeURIComponent(s)}`,void 0,i);break}case"update_subscriber":{let i=e.companyId,s=K("update_subscriber",e),r=S("update_subscriber",e,"status",["active","unsubscribed","bounced"]),o=Xt("update_subscriber",e),c=o?.source==="attributes"||e.addTags!==void 0||e.removeTags!==void 0?await Oe(s,i):null,m=Array.isArray(c?.subscriber.tags)?c.subscriber.tags.filter((q)=>typeof q==="string"):[],f=Array.isArray(e.addTags)?e.addTags.filter((q)=>typeof q==="string"&&q.trim()!=="").map(Zt):[],w=new Set(Array.isArray(e.removeTags)?e.removeTags.filter((q)=>typeof q==="string"&&q.trim()!=="").map(Zt):[]),g=m.filter((q)=>!w.has(q));for(let q of f)if(!g.includes(q))g.push(q);let _={};if(s.email&&s.externalId)_.externalId=s.externalId;if(e.firstName!==void 0)_.firstName=e.firstName;if(e.lastName!==void 0)_.lastName=e.lastName;if(typeof e.timezone==="string")_.timezone=e.timezone.trim()||null;if(typeof e.phone==="string"||e.phone===null)_.phone=e.phone;if(typeof e.phoneCountry==="string")_.phoneCountry=e.phoneCountry;if(typeof e.smsConsent==="boolean")_.smsConsent=e.smsConsent;if(r!==void 0)_.status=r;if(o!==void 0)_.customAttributes=o.source==="attributes"?{...I(c?.subscriber.customAttributes)?c.subscriber.customAttributes:{},...o.value}:o.value;if(e.addTags||e.removeTags)_.tags=g;n=await a("PATCH",nt(s),_,i);break}case"remove_subscriber":{let i=e.companyId,s=K("remove_subscriber",e),r=nt(s);if(e.hardDelete===!0)n=await a("DELETE",r,void 0,i);else n=await a("PATCH",r,{status:"unsubscribed"},i);break}case"get_subscriber":{let i=e.companyId,s=K("get_subscriber",e);n=await Oe(s,i,{includeMachineEngagement:e.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let i=e.companyId,s=K("list_subscriber_notes",e);n=await a("GET",tn(s),void 0,i);break}case"add_subscriber_note":{let i=e.companyId,s=K("add_subscriber_note",e),r=typeof e.body==="string"?e.body.trim():void 0;if(!r)throw Error("`body` is required when calling `add_subscriber_note`.");if(r.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");n=await a("POST",tn(s),{body:r},i);break}case"delete_subscriber_note":{let i=e.companyId,s=typeof e.noteId==="string"?e.noteId.trim():"";if(!s)throw Error("`noteId` is required when calling `delete_subscriber_note`.");n=await a("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(s)}`,void 0,i);break}case"trigger_subscriber_event":{let i=e.companyId,s=K("trigger_subscriber_event",e),r=u("trigger_subscriber_event",e,"event");if(e.properties!==void 0&&!I(e.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");n=await a("POST","/api/v1/subscribers/events",{...s,event:r,...e.properties!==void 0&&{properties:e.properties},...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...e.attributes!==void 0&&{customAttributes:e.attributes},...e.occurredAt!==void 0&&{occurredAt:e.occurredAt},...e.eventId!==void 0&&{eventId:e.eventId}},i);break}case"trigger_subscriber_events":{let i=e.companyId,s=K("trigger_subscriber_events",e);if(!Array.isArray(e.events)||e.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(e.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 r=0;r<e.events.length;r+=1){let o=e.events[r];if(!I(o)||typeof o.name!=="string"||o.name.trim()==="")throw Error(`Event ${r} must include a non-empty \`name\` string.`)}n=await a("POST","/api/v1/subscribers/events/bulk",{...s,events:e.events,...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...e.attributes!==void 0&&{customAttributes:e.attributes}},i);break}case"import_subscriber_events":{let i=e.companyId;if(!Array.isArray(e.events)||e.events.length===0)throw Error("`events` must be a non-empty array when calling `import_subscriber_events`.");if(e.events.length>25)throw Error("`import_subscriber_events` accepts at most 25 events per call. Split a larger import into several calls.");for(let s=0;s<e.events.length;s+=1){let r=e.events[s];if(!I(r)||typeof r.name!=="string"||r.name.trim()==="")throw Error(`Event ${s} must include a non-empty \`name\` string.`);let o=typeof r.email==="string"&&r.email.trim()!=="",d=typeof r.externalId==="string"&&r.externalId.trim()!=="";if(!o&&!d)throw Error(`Event ${s} must include an \`email\` or an \`externalId\`.`);if(typeof r.eventId!=="string"||r.eventId.trim()==="")throw Error(`Event ${s} must include a non-empty \`eventId\` so retries are safe.`)}n=await a("POST","/api/v1/subscribers/events/imports",{events:e.events},i);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let i=e.companyId,s=xo(t,e);n=await a("POST",`/api/v1/subscribers/bulk/tags/${t==="bulk_add_subscriber_tags"?"add":"remove"}`,s,i);break}case"search_subscribers":{let i=e.companyId;n=await bi(e,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function Ls(t,e){if(t==="list_recipient_suppressions"){let c=l(e,"companyId"),m=l(e,"search"),f=P(t,e,"page",1,Number.MAX_SAFE_INTEGER),w=P(t,e,"limit",1,100),g=l(e,"sort"),_=l(e,"order"),q=new URLSearchParams;if(m)q.set("search",m);if(f!==void 0)q.set("page",String(f));if(w!==void 0)q.set("limit",String(w));if(g)q.set("sort",g);if(_)q.set("order",_);let E=`/api/v1/suppressions${q.size>0?`?${q}`:""}`;return{handled:!0,result:await a("GET",E,void 0,c)}}if(t!=="get_recipient_suppression"&&t!=="remove_recipient_suppression")return{handled:!1,result:void 0};let n=l(e,"companyId"),i=u(t,e,"email"),s=l(e,"region"),r=new URLSearchParams;if(s)r.set("region",s);let o=`/api/v1/suppressions/${encodeURIComponent(i)}${r.size>0?`?${r}`:""}`;return{handled:!0,result:await a(t==="get_recipient_suppression"?"GET":"DELETE",o,void 0,n)}}async function $s(t,e){let n;switch(t){case"list_team_members":{let i=e.companyId;n=await a("GET","/api/v1/team",void 0,i);break}case"invite_team_member":{let i=e.companyId,s=u("invite_team_member",e,"email"),r=Ue("invite_team_member",e,"role",["admin","viewer","restricted"]);if(e.canManageBilling!==void 0&&typeof e.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");n=await a("POST","/api/v1/team/invitations",{email:s,role:r,...e.canManageBilling!==void 0&&{canManageBilling:e.canManageBilling}},i);break}case"cancel_team_invitation":{let i=e.companyId,s=u("cancel_team_invitation",e,"invitationId");n=await a("DELETE",`/api/v1/team/invitations/${encodeURIComponent(s)}`,void 0,i);break}case"list_conversations":{let i=e.companyId,s=new URLSearchParams,r=S("list_conversations",e,"status",["open","closed","all"]);if(r)s.set("status",r);let o=l(e,"search");if(o)s.set("search",o);if(e.unread!==void 0){if(typeof e.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(e.unread)s.set("unread","true")}if(e.page!==void 0){if(typeof e.page!=="number"||!Number.isInteger(e.page)||e.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");s.set("page",String(e.page))}let d=P("list_conversations",e,"limit",1,100);if(d!==void 0)s.set("limit",String(d));n=await a("GET",`/api/v1/conversations${s.size>0?`?${s}`:""}`,void 0,i);break}case"get_conversation":{let i=e.companyId,s=u("get_conversation",e,"conversationId");n=await a("GET",`/api/v1/conversations/${encodeURIComponent(s)}`,void 0,i);break}case"reply_to_conversation":{let i=e.companyId,s=u("reply_to_conversation",e,"conversationId"),r=S("reply_to_conversation",e,"type",["outbound","note"])??"outbound",o=l(e,"subject"),d=l(e,"bodyText"),c=l(e,"bodyHtml");if(r==="outbound"&&d===void 0&&c===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");n=await a("POST",`/api/v1/conversations/${encodeURIComponent(s)}/messages`,{type:r,...o!==void 0&&{subject:o},...d!==void 0&&{bodyText:d},...c!==void 0&&{bodyHtml:c}},i);break}case"update_conversation_status":{let i=e.companyId,s=u("update_conversation_status",e,"conversationId"),r=Ue("update_conversation_status",e,"status",["open","closed"]);n=await a("POST",`/api/v1/conversations/${encodeURIComponent(s)}/status`,{status:r},i);break}case"mark_conversation_read":{let i=e.companyId,s=u("mark_conversation_read",e,"conversationId");n=await a("POST",`/api/v1/conversations/${encodeURIComponent(s)}/read`,void 0,i);break}case"list_webhooks":{let i=e.companyId;n=await a("GET","/api/v1/webhooks",void 0,i);break}case"create_webhook":{let i=e.companyId,s=u("create_webhook",e,"name"),r=u("create_webhook",e,"url"),o=sn("create_webhook",e);n=await a("POST","/api/v1/webhooks",{name:s,url:r,...o!==void 0&&{events:o}},i);break}case"update_webhook":{let i=e.companyId,s=u("update_webhook",e,"webhookId"),r=l(e,"name"),o=l(e,"url"),d=sn("update_webhook",e),c=S("update_webhook",e,"status",["enabled","disabled"]);if(r===void 0&&o===void 0&&d===void 0&&c===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");n=await a("PATCH",`/api/v1/webhooks/${encodeURIComponent(s)}`,{...r!==void 0&&{name:r},...o!==void 0&&{url:o},...d!==void 0&&{events:d},...c!==void 0&&{status:c}},i);break}case"delete_webhook":{let i=e.companyId,s=u("delete_webhook",e,"webhookId");n=await a("DELETE",`/api/v1/webhooks/${encodeURIComponent(s)}`,void 0,i);break}case"test_webhook":{let i=e.companyId,s=u("test_webhook",e,"webhookId");n=await a("POST",`/api/v1/webhooks/${encodeURIComponent(s)}/test`,void 0,i);break}case"list_webhook_deliveries":{let i=e.companyId,s=u("list_webhook_deliveries",e,"webhookId"),r=P("list_webhook_deliveries",e,"limit",1,100),o=new URLSearchParams;if(r!==void 0)o.set("limit",String(r));n=await a("GET",`/api/v1/webhooks/${encodeURIComponent(s)}/deliveries${o.size>0?`?${o}`:""}`,void 0,i);break}case"replay_webhook_delivery":{let i=e.companyId,s=u("replay_webhook_delivery",e,"webhookId"),r=u("replay_webhook_delivery",e,"deliveryId");n=await a("POST",`/api/v1/webhooks/${encodeURIComponent(s)}/deliveries/${encodeURIComponent(r)}/replay`,void 0,i);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function Fs(t){if(!Array.isArray(t))return;return t.filter((e)=>typeof e==="string")}async function Hs(t,e){let n=e.companyId,i;switch(t){case"list_web_tracking_keys":{i=await a("GET","/api/v1/web-tracking-keys",void 0,n);break}case"get_web_tracking_key":{let s=u("get_web_tracking_key",e,"id");i=await a("GET",`/api/v1/web-tracking-keys/${encodeURIComponent(s)}`,void 0,n);break}case"create_web_tracking_key":{let s=u("create_web_tracking_key",e,"name"),r=Fs(e.allowedOrigins);i=await a("POST","/api/v1/web-tracking-keys",{name:s,...r?{allowedOrigins:r}:{}},n);break}case"update_web_tracking_key":{let s=u("update_web_tracking_key",e,"id"),r=Fs(e.allowedOrigins);if(typeof e.name!=="string"&&r===void 0&&typeof e.isActive!=="boolean")throw Error("Provide at least one of `name`, `allowedOrigins`, or `isActive` when calling `update_web_tracking_key`.");i=await a("PATCH",`/api/v1/web-tracking-keys/${encodeURIComponent(s)}`,{...typeof e.name==="string"?{name:e.name}:{},...r?{allowedOrigins:r}:{},...typeof e.isActive==="boolean"?{isActive:e.isActive}:{}},n);break}case"delete_web_tracking_key":{let s=u("delete_web_tracking_key",e,"id");i=await a("DELETE",`/api/v1/web-tracking-keys/${encodeURIComponent(s)}`,void 0,n);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:i}}var zs=[ws,Cs,Ts,Ms,Ls,Os,Is,ks,Ss,qs,Us,Ps,As,Ds,Es,gn,vs,$s,Hs,_s];var Co=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 Bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function fn(t){if(Array.isArray(t))return t.some(fn);if(!Bs(t))return!1;for(let[e,n]of Object.entries(t)){if((e==="html"||e==="htmlContent")&&typeof n==="string"&&n.trim().length>0)return!0;if(fn(n))return!0}return!1}function Ws(t,e,n){if(!Co.has(t)||!fn(e)||!Bs(n))return n;let i=Array.isArray(n.warnings)?n.warnings.filter((s)=>typeof s==="string"):[];return{...n,warnings:[...new Set([...i,_t])]}}var pt="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.",Do={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:pt,sortOrder:pt,sort:pt,order:pt,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."}},Gs=null;function Ro(t){return Gs??=new Map(dt.map((e)=>{let n=e.inputSchema.properties;return[e.name,new Set(n&&typeof n==="object"?Object.keys(n):[])]})),Gs.get(t)??null}function Ks(t,e){let n=Ro(t);if(!n)return;let i=Object.keys(e??{}).filter((d)=>!n.has(d));if(i.length===0)return;let s=Do[t]??{},r=[...new Set(i.flatMap((d)=>s[d]?[s[d]]:[]))],o=n.size>0?`Supported arguments: ${[...n].map((d)=>`\`${d}\``).join(", ")}.`:`\`${t}\` takes no arguments.`;throw Error([`Unsupported field${i.length===1?"":"s"}: ${i.map((d)=>`\`${d}\``).join(", ")}.`,`\`${t}\` rejects arguments it does not support rather than ignoring them, because ignoring them would return a result that silently does not match the request.`,o,...r].join(" "))}var Vs=dt.map(Ni).map(Un);function Ao(t,e){if(t!=="import_subscriber_events"||e===null||typeof e!=="object")return!1;let n=e;return n.success===!1&&typeof n.total==="number"&&typeof n.recorded==="number"&&typeof n.duplicates==="number"&&typeof n.failed==="number"&&typeof n.subscribers==="number"&&(n.failed>0&&Array.isArray(n.failures)||typeof n.sideEffectFailed==="number"&&n.sideEffectFailed>0&&Array.isArray(n.sideEffectFailures))}async function Ys(t,e){try{Ks(t,e);let n,i=!1;for(let r of zs){let o=await r(t,e);if(o.handled){n=o.result,i=!0;break}}if(!i)throw Error(`Unknown tool: ${t}`);let s=Ao(t,n)?null:yi(n);if(s)throw s;return n=Ws(t,e,n),n=await Pi(t,e,n),{structuredContent:Mi(n),content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(n){return{isError:!0,content:[{type:"text",text:ne(n)}]}}}var bn={ttlMs:60000,cacheScope:"public"};async function Js(t,e){let n=t.getRequestContext?.();if(!n)return e();try{return await mt(n,e)}finally{await t.onRequestContextUpdated?.(n)}}function wn(t={}){let e=new Oo({name:"sequenzy",version:Le.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!1}},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.","Sequence A/B step variant bodies are on get_sequence.sequence.emails[].abTest.variants[].blocks when the key has ab_tests:read. get_ab_test is optional for that copy audit; it still returns settings, localization, and stats. Write those bodies with update_ab_test_variant (IDs from the same variants list). If that tool is not in the tool list, enable it on the Sequenzy connector - do not write through update_template or update_sequence_node.","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(`
32
- `),cacheHints:{"tools/list":bn,"resources/list":bn,"server/discover":bn}});return e.server.setRequestHandler("tools/list",async()=>({tools:Vs})),e.server.setRequestHandler("tools/call",async(n)=>{let{name:i,arguments:s}=n.params;return Js(t,()=>Ys(i,s??{}))}),e.server.setRequestHandler("resources/list",async()=>({resources:Dn})),e.server.setRequestHandler("resources/read",async(n)=>{let{uri:i}=n.params;return Js(t,()=>Rn(i))}),e}import{serveStdio as Uo}from"@modelcontextprotocol/server/stdio";function jo(){Tn(),vn(),Uo(()=>wn()),console.error("Sequenzy MCP server running on stdio")}try{jo()}catch(t){console.error(ne(t)),process.exit(1)}export{a as apiRequest,wn as createSequenzyMcpServer,ie as getSelectedCompanyId,Ee as setSelectedCompanyId,mt as withMcpRequestContext};
31
+ 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 Ns=[{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 guidance. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values (minimal, branded, promotional) are freeform prompt guidance. Defaults to the company's email style preference."},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:"get_sms_usage",description:"Get per-number SMS usage for the company: sends, delivered, failed, credits charged, last-sent time, and test-send count for each phone number the workspace has sent from. Use it to compare how the workspace's numbers are performing or to check what a number was used for before releasing it.",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:"release_sms_number",description:"Release an SMS number: hand it back to the carrier and mark it released. This is IRREVERSIBLE - the number cannot be recovered afterward, any campaign/sequence still explicitly set to send from it will SKIP its SMS sends until repointed at another number, and it stops counting toward the workspace's number limit (freeing a slot for a new purchase). Use get_sms_settings to find the number ID. 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."}},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 100 test sends per company per rolling 24 hours; 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."},fromNumberId:{type:"string",description:"Active SMS number ID to send from (see get_sms_settings). Defaults to the company's oldest active number - the same default real sends use."}},required:["to"]}}];var Ms=[{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. Also returns top-level subscriberCount (every stored contact) and activeSubscriberCount (status=active) as a live audience snapshot, independent of period; use these for 'how many subscribers do I have' instead of search_subscribers pagination.total. 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:F}}},{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:F},required:["idOrSlug"]}},{name:"get_campaign_stats",description:"Get detailed statistics for a campaign, including replies and reply rate, attributed conversions, revenue (revenueCents), attached campaign conversion goals in the top-level goals array (sent → opened → clicked → each named goal), 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:F},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:F},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: ${Ne}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Ne}. 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:F},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: ${Ne}. Defaults to delivery.`},eventTypes:{type:"array",description:`Optional event types to include. Supported values: ${Ne}. 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:F},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:F}}},{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:F},required:[]}}];var Ls=[{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"]}}];var yt={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},campaignId:{type:"string",description:"Campaign ID."}},$s={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change","tag_added"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},triggerTagName:{type:["string","null"],description:"Required tag name for tag_added goals, e.g. customer."},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."}},Fs=[{name:"list_campaign_goals",description:"List persisted conversion goals attached to one email campaign in the dashboard. SMS campaigns are not supported. Campaign goals are attributed to recipients who were sent that campaign (last-touch open/click still wins when the recipient engaged), and appear on the campaign report as named conversion steps after sent/opened/clicked.",inputSchema:{type:"object",properties:yt,required:["campaignId"],additionalProperties:!1}},{name:"create_campaign_goal",description:"Create a persisted event, subscriber-attribute, or tag-applied conversion goal for one email campaign. SMS campaigns are not supported. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath; tag_added goals require triggerTagName. Campaign goals are attributed to recipients who were sent the campaign (opens/clicks still win when present). Use this to measure outcomes such as signup or becoming a customer on a one-off campaign. Distinct from company-wide goals and from sequence goals.",inputSchema:{type:"object",properties:{...yt,...$s},required:["campaignId","name"],additionalProperties:!1}},{name:"update_campaign_goal",description:"Update a persisted email-campaign conversion goal, including its signal, attribution window, or active state. SMS campaigns are not supported.",inputSchema:{type:"object",properties:{...yt,goalId:{type:"string",description:"Campaign goal ID."},...$s},required:["campaignId","goalId"],additionalProperties:!1}},{name:"delete_campaign_goal",description:"Delete one persisted email-campaign conversion goal. SMS campaigns are not supported.",inputSchema:{type:"object",properties:{...yt,goalId:{type:"string",description:"Campaign goal ID."}},required:["campaignId","goalId"],additionalProperties:!1}}];function On(t,e){return{type:e?.nullable?["object","null"]:"object",description:t,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 zs=[{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. ${xi} 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. Change draft pacing with update_campaign, or apply it when calling schedule_campaign. ${pe} 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. Successful live-test and other test sends are omitted so they do not bury real deliveries; only failed, bounced, or suppressed test sends appear. Replies to those test sends show in list_conversations only when inbound reply capture is enabled; otherwise the send uses the original Reply-To and Sequenzy never sees the reply.",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. Pass `emailPreset` with native blocks to set Style > Format (minimal or branded); `style` is a prompt-generation hint only. 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. ${A}`},blocks:{type:"array",description:L,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. Only used with `prompt`; this is not Style > Format. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values (minimal, branded, promotional) are freeform prompt guidance and the company's email style preference decides. Use `emailPreset` to set branded or minimal chrome on native blocks."},tone:{type:"string",description:"Prompt generation tone: professional, casual, friendly. Only used with `prompt`."},emailPreset:Zt,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:On("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:ce},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:le},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's content, audience, sending identity, labels, Style > Format, or delivery pacing. Pass emailPreset to change Style > Format on native blocks without rewriting copy. sendTimeOptimization and sendTimeWindowHours persist on the draft and are used when the campaign is later scheduled unless schedule_campaign overrides them. ${pe}`,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. ${A}`},blocks:{type:"array",description:L,items:{type:"object"}},emailPreset:Zt,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:le},fromEmail:{type:"string",description:"Set this campaign's From address. Its domain must be configured and verified."},fromName:{type:"string",description:ce},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:On("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"}},sendTimeOptimization:{type:"boolean",description:Kt},sendTimeWindowHours:{type:"number",description:Vt}},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`. The campaign must have a non-empty subject, at least one content block, and at least one audience include rule. Use `recurringInterval` for newsletters that go out on a fixed schedule instead of creating one campaign per issue. Send Time Optimization (sendTimeOptimization) delivers each recipient at their predicted best hour within sendTimeWindowHours of scheduledAt (default 12h, max 24); it is campaign-only and is not available on sequences. spreadOverHours takes precedence and turns STO off; sendInRecipientTimezone also turns it off. Returns dashboard edit and preview URLs; validation errors explain what must be fixed before retrying.",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:On("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:Kt},sendTimeWindowHours:{type:"number",description:Vt},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."},sendInRecipientTimezone:{type:"boolean",description:"Deliver at scheduledAt's wall-clock time in each recipient's own timezone ('send when it's 8pm for the customer'). Requires `scheduledTimezone`; contacts without a stored timezone receive the campaign at scheduledAt itself. Not combinable with `recurringInterval` or `spreadOverHours`."},scheduledTimezone:{type:"string",description:"IANA timezone the scheduledAt wall-clock time refers to, for example America/New_York. Required with `sendInRecipientTimezone`."},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, and never for imported already-sent campaigns (Sequenzy has no opens for a send it did not deliver). 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 Hs=[{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 and nested objects. 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. `group` is a persisted structural type managed by the editor and is omitted by creatableOnly; request it by name when reading existing grouped content. 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`. Every block also takes a `conditions` array, and each condition field accepts only its own operators - a block\'s own `field` and `operator` enums pool every field\'s operators together, so they list `is` for `tag` even though a tag condition is rejected with it. The `conditionFields` table resolves that: the operators each condition field accepts, how its `value` string is shaped, and what render_email needs before it can evaluate the condition rather than rendering it as false. It comes back automatically when you list every type and when you ask for `conditional-group`; on any other single type pass conditionFields: true, since the table is several times the size of one block\'s reference.',inputSchema:{type:"object",properties:{blockType:{type:"string",description:'A single block type to describe, for example "list", "steps", "text", "hero", or the structural "group" type. Omit to list every block type.'},creatableOnly:{type:"boolean",description:"Only list block types an author should hand-create, hiding structural types such as group that the editor manages. Ignored when blockType is set."},conditionFields:{type:"boolean",description:"Include the per-field condition table alongside a single blockType. Only needed when you are writing a `conditions` array on that type: listing every type already includes the table, and so does asking for `conditional-group`. Responses that omit it say so in `conditionFieldsHint`."}},required:[]}}];var Bs=[{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. ${L}`,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. ${L}`,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. ${L}`,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 Ws=[{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 Gs=[{name:"submit_feedback",description:"Send product feedback about Sequenzy itself to the Sequenzy team, but only when the user explicitly asks you to send it. Tell the user where the message goes before calling this tool. Include only reproduction details and resource IDs needed for that report; never include unrelated subscriber data, message content, credentials, raw API payloads, or debug data. 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. Do not include secrets or unrelated personal data."},userIntent:{type:"string",description:"For bug or 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 or wrong-outcome reports: the ordered tool calls that led to the problem. Summarize arguments; do not paste raw subscriber data, full email bodies, or secrets.",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 affected resources so the team can correlate the report with server logs. Include only IDs needed to investigate the reported issue."}},required:["message"]}}];var Ks=[{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 globally unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Layout groups use { id, kind: "group", label, layout: "stack" | "row" | "grid" | "overlay", columns (1-4), gap (0-64), padding (0-64), overlayColor (hex), overlayPosition ("top" | "center" | "bottom"), overlayShade (0-100), children: [...] }. In Overlay, gap spaces foreground children while the direct image remains the background. Overlay needs exactly one direct image; images inside subgroups only enable Overlay for that subgroup, while zero or multiple direct images fall back to Stack. Groups may nest to three levels; descendants must use the same sectionId as their group, while form-step, success-screen, and error-state remain at the root. 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].children[0].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 Vs=[{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 Ys=[{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 Js=[{name:"connect_integration",description:"Connect an API-key / webhook-secret integration: polar, paddle, dodo, whop, creem, chargebee, clerk, posthog, segment, affonso, or attio. 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. Attio is outbound-only and has no webhookUrl. For every other connectable provider 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, segment, affonso, or attio.",enum:["polar","paddle","dodo","whop","creem","chargebee","clerk","posthog","segment","affonso","attio"]},apiKey:{type:"string",description:"Provider API key. Required for polar, paddle, dodo, whop, creem, chargebee, affonso, and attio. Attio uses the workspace access token from Settings → Developers."},webhookSecret:{type:"string",description:"Signing secret of the webhook you create at the provider, pointed at the returned webhookUrl. Required for every provider except attio, which is outbound-only. For Chargebee, pass the webhook's basic-auth credentials as username:password. For segment, the secret is your own choice and must be 16-153 UTF-8 bytes."},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, segment, and affonso do not use one."},settings:{type:"object",description:"PostHog and Segment: event delivery scope. New Segment connections skip automatic page/screen calls unless those names are explicitly allowlisted. Attio: listMap (Sequenzy list id → Attio list id or slug) and syncCompanyFromDomain (default true).",properties:{syncAllEvents:{type:"boolean",description:"Sync every event the provider delivers."},eventAllowlist:{type:"array",items:{type:"string"},description:"Only sync these event names. Set syncAllEvents to false when using this."},listMap:{type:"object",additionalProperties:{type:"string"},description:"Attio only. Optional map of Sequenzy list id to Attio people-list UUID or api slug. When omitted, connect first and configure mappings later with update_attio_settings — do not ask the user to re-paste the access token just to map lists."},syncCompanyFromDomain:{type:"boolean",description:"Attio only. When true, upsert a company from the person's non-free-mail email domain."}}},historyImport:{type:"object",description:"PostHog and Segment only: import event history after connecting. PostHog needs region + projectId + personalApiKey (query read access) and imports the project archive. Segment needs region + spaceId + profileApiToken (Unify Profile API) and imports each existing contact's recent profile history - the Profile API serves at most the last 14 days, and contacts without a Unify profile are skipped.",properties:{region:{type:"string",enum:["us","eu"],description:"Region hosting the data: the PostHog Cloud region, or the Segment workspace's deployment."},projectId:{type:"string",description:"PostHog only: numeric PostHog project ID."},personalApiKey:{type:"string",description:"PostHog only: personal API key (phx_...)."},spaceId:{type:"string",description:"Segment only: Unify space ID (spa_...)."},profileApiToken:{type:"string",description:"Segment only: Profile API access token for the space."}},required:["region"]},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["provider"]}},{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. For Attio, `details.mappedListCount` 0 and an `attio_lists_unmapped` recommendation mean list joins are not synced — use get_attio_mapping then update_attio_settings; do not reconnect for that. 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, crm, 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 integration's future bulk imports and backfills on or off. THIS DOES NOT STOP AN INTEGRATION CREATING CONTACTS: disabling sync only pauses full imports and backfills, while the provider's live webhook keeps writing every new signup or customer as it happens. To change where those contacts land, use set_integration_list_targeting; to stop them arriving at all, the integration has to be disconnected from the dashboard. 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`. Requires an API key with the `integrations:manage` scope, which agent-safe keys deliberately do not carry - without it, report the dashboard path (Settings -> Integrations) instead of retrying.",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:"set_integration_list_targeting",description:"Choose which lists the contacts a connected integration creates join. This is the tool for 'stop this integration adding people to my marketing lists' - set_integration_sync_enabled only pauses bulk backfills and leaves the provider's live webhook writing. IMPORTANT SCOPE: this changes list membership only, and it takes effect on future provider writes. It does not stop contacts being created, does not stop their attributes syncing, does not stop sync-rule tags, and does not stop `contact_added` sequences using the default `any_contact` scope, which fire precisely because the contact joined no list. Explicit `any_list` and specific-list sequences require a matching membership and do not enroll a list-less contact. Nobody is ever removed from a list and nothing is applied retroactively. Provider behavior for existing contacts differs: Wix or Webflow submissions, Shopify customer updates, and Supabase resubscriptions can add an existing contact to the new target lists; Stripe applies targeting only when its webhook creates a subscriber. If the goal is to stop `any_contact` enrollments too, pair this tool with pause_sequence_enrollments on the affected sequences. Check get_integration first - `ingestion` reports the current targeting with list names, and `availableActions` says whether this provider honors set_list_targeting. Supported for Supabase, Stripe, Shopify, Wix, and Webflow. Dodo Payments, PostHog, Polar, Paddle, and other providers without that action reject this tool; their live contacts follow defaultSubscriberListIds on get_company/update_company instead (null = every list, [] = none), which is workspace-wide. PostHog history imports are an exception and create contacts without list memberships. Idempotent: asking for the current state succeeds with `changed: false`. Requires an API key with the `integrations:manage` scope, which agent-safe keys deliberately do not carry - without it, report the dashboard path (Settings -> Integrations) instead of retrying.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Integration ID from list_integrations."},listIds:{type:["array","null"],items:{type:"string"},description:"Lists that contacts created by this integration join from now on. `null` clears the choice so they follow the workspace default lists; `[]` means they join no list at all; a populated array means exactly those lists. Every ID must belong to this company."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId","listIds"]}},{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 and Segment. 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 or Segment history import: it restarts from the beginning using the stored credentials, 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 history 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"]}},{name:"get_attio_mapping",description:"Inspect a connected Attio integration's list mapping: every Sequenzy list, every Attio people-list the stored token can write (id, api slug, name), the saved listMap, mappedListCount, and whether company matching from work-email domains is on. THIS IS THE TOOL FOR 'Attio is connected but mappedListCount is 0'. Call it before update_attio_settings so you have Attio list ids or slugs instead of asking the user to paste UUIDs. Reads Attio live on every call. Credentials are never returned. Attio only; other providers return a clear error. Check get_integration first — availableActions includes update_attio_settings when mapping can be saved without reconnecting.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Attio 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:"update_attio_settings",description:"Set which Sequenzy lists sync into which Attio people-lists on an already-connected Attio integration, using the stored access token. THIS DOES NOT REQUIRE THE SECRET AGAIN: do not call connect_integration just to change mappings, and do not ask the user for the Attio access token. listMap is a full replacement — pass the complete desired map, `{}` to unmap every list, or omit listMap to leave mappings unchanged. Unmapped Sequenzy lists are not synced. Optionally set syncCompanyFromDomain. Provide at least one field. Idempotent: asking for the current state succeeds with changed: false. Does not backfill people already on a list; add-only, so unmapping does not remove anyone from Attio. Check get_attio_mapping first for Sequenzy list ids and live Attio list ids/slugs. Attio only. Requires an API key with the `integrations:manage` scope, which agent-safe keys deliberately do not carry - without it, report the dashboard path (Settings -> Integrations -> Attio -> Map lists) instead of retrying.",inputSchema:{type:"object",properties:{integrationId:{type:"string",description:"Attio integration ID from list_integrations or get_integration."},listMap:{type:"object",additionalProperties:{type:"string"},description:"Complete map of Sequenzy list id to Attio people-list UUID or api slug. Replaces the saved map. Pass `{}` to clear every mapping. Omit to leave mappings unchanged."},syncCompanyFromDomain:{type:"boolean",description:"When true, upsert a company from the person's non-free-mail email domain. Omit to leave the current setting unchanged."},companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."}},required:["integrationId"]}}];var Zs=[{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. Drafts have publicUrl and appPublicUrl set to null; previewUrl is a signed, unlisted visitor-facing preview that works before publish. Use render_landing_page when you need that preview URL called out with publish-vs-draft guidance. viewCount and conversionCount are lifetime totals; use get_landing_page_stats for unique visits, referrers, a date histogram, and whether crawlers were counted.",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:"get_landing_page_stats",description:"Get Mailchimp-style landing page analytics: visits, unique visits, clicks, subscribes, conversion rate, a daily histogram, referrers, and UTM sources. Default counts exclude known crawlers; preview URLs and the editor are never counted. Opening the public URL while building the page does count. Pass includeBots to include crawler hits in visits. period defaults to all retained events with a 90-day histogram; dataAvailableFrom identifies the beginning of retained coverage, which may be later than the page's lifetime counters.",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."},period:{type:"string",description:"Time window: 7d, 30d, 90d, or all (default: all)."},start:{type:"string",description:"Custom range start as an ISO 8601 timestamp; provide end too. Maximum range is 365 days."},end:{type:"string",description:"Custom range end as an ISO 8601 timestamp; provide start too."},includeBots:{type:"boolean",description:"Include known crawlers in visits, unique visits, clicks, referrers, and the histogram. Bot hits are always returned separately as botVisits."}},required:["landingPageId"],additionalProperties:!1}},{name:"render_landing_page",description:"Render a visitor-facing preview of a landing page without publishing it. Unlike get_landing_page, which returns builder JSON, this returns previewUrl: a signed, unlisted URL that shows the page with the same layout, theme, form, and #form button anchors visitors will see. Drafts keep publicUrl and appPublicUrl null until publish_landing_page; open previewUrl to check copy and layout on a draft instead of putting unreviewed content on the public domain. The preview is not indexed. Signup forms on a draft preview do not collect contacts. This is read-only and never publishes, unpublishes, or changes the 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 to preview."}},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:Ci},content:{type:"object",description:Ue,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:Ue,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:Ue,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:Ue,additionalProperties:!0}},required:["landingPageId"],additionalProperties:!1}},{name:"connect_landing_page_domain",description:"Connect a custom domain. Omit landingPageId for the legacy workspace-wide domain, or provide it to dedicate the hostname to one page at the domain root. Returns DNS and verification details.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},domain:{type:"string",description:"Custom domain: a subdomain (pages.example.com, needs a CNAME record) or a root domain (example.com, needs an A record to 76.76.21.21; www also redirects to the root when its CNAME points to pages.sequenzydns.com)."},landingPageId:{type:"string",description:"Optional landing page ID. When provided, the domain serves only this page from the hostname root."}},required:["domain"],additionalProperties:!1}},{name:"update_landing_page_domain_settings",description:"Update or verify landing page domain settings. Omit landingPageId for the workspace domain, or provide it for a dedicated page domain. Dedicated domains must be removed explicitly before replacement.",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."},landingPageId:{type:"string",description:"Optional dedicated landing page domain target."}},additionalProperties:!1}},{name:"remove_landing_page_domain",description:"Remove the dedicated custom domain from one landing page. The page keeps its workspace and Sequenzy fallback 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 whose dedicated domain should be removed."}},required:["landingPageId"],additionalProperties:!1}}];var Qs=[{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 globally unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Layout groups use { id, kind: "group", label, layout: "stack" | "row" | "grid" | "overlay", columns (1-4), gap (0-64), padding (0-64), overlayColor (hex), overlayPosition ("top" | "center" | "bottom"), overlayShade (0-100), children: [...] }. In Overlay, gap spaces foreground children while the direct image remains the background. Overlay needs exactly one direct image; images inside subgroups only enable Overlay for that subgroup, while zero or multiple direct images fall back to Stack. Groups may nest to three levels; descendants must use the same sectionId as their group, while form-step, success-screen, and error-state remain at the root. 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].children[0].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 globally unique "id" and a "kind", and "sectionId" ("success" or "error") moves a content block into that screen. Layout groups use { id, kind: "group", label, layout: "stack" | "row" | "grid" | "overlay", columns (1-4), gap (0-64), padding (0-64), overlayColor (hex), overlayPosition ("top" | "center" | "bottom"), overlayShade (0-100), children: [...] }. In Overlay, gap spaces foreground children while the direct image remains the background. Overlay needs exactly one direct image; images inside subgroups only enable Overlay for that subgroup, while zero or multiple direct images fall back to Stack. Groups may nest to three levels; descendants must use the same sectionId as their group, while form-step, success-screen, and error-state remain at the root. 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].children[0].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 Xs=[{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 er=[{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. For a sequence step whose nodeType is action_ab_test, also pass variantId from get_sequence.sequence.emails[].abTest.variants - that step has no email of its own and copy lives on the variants. 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. An unrecognized name is reported there even when a default filter supplied text in its place, because that fallback then reaches every recipient while the HTML looks perfectly personalized. 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. Conditional blocks are the other half of a preview: a condition on stored subscriber state (tag, segment, list, status, event, purchases, engagement) is evaluated per recipient at send time, so this render can only evaluate it for a stored subscriberId - or, for a `tag` condition, an inline subscriber that states tags. Anything it cannot evaluate renders as false, which is indistinguishable in the HTML from a condition that is genuinely false, so check unevaluatedConditions before treating a preview as proof of which branch a recipient gets. 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},tags:{type:"array",description:"Tags this ad-hoc contact carries, used to evaluate `tag` block conditions. Nothing is stored. Without it a tag condition has no tags to read and renders as false, so only the else branch of a tag split can be previewed. Every other stored-state condition (segment, list, event, engagement, purchases) still needs subscriberId.",items:{type:"string"}}},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. Required for sequence steps whose nodeType is action_ab_test: those steps have no emailId of their own, and copy lives on get_sequence.sequence.emails[].abTest.variants. Rendering a sequence variant also needs the ab_tests:read scope, the same scope get_sequence uses to return competing variant copy."},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 gt={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID."}},tr={name:{type:"string",description:"Goal name."},description:{type:["string","null"],description:"Optional goal description."},triggerType:{type:"string",enum:["event","attribute_change","tag_added"],description:"Conversion signal type. Defaults to event when creating."},triggerEventName:{type:["string","null"],description:"Required event name for event goals."},triggerTagName:{type:["string","null"],description:"Required tag name for tag_added goals, e.g. customer."},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."}},nr=[{name:"list_sequence_goals",description:"List persisted conversion goals attached to one sequence in the dashboard.",inputSchema:{type:"object",properties:gt,required:["sequenceId"],additionalProperties:!1}},{name:"create_sequence_goal",description:"Create a persisted event, subscriber-attribute, or tag-applied conversion goal for one sequence. Event goals (the default triggerType) require triggerEventName; attribute_change goals require attributePath; tag_added goals require triggerTagName. This is distinct from create_sequence.goal, which is only an AI content prompt.",inputSchema:{type:"object",properties:{...gt,...tr},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:{...gt,goalId:{type:"string",description:"Sequence goal ID."},...tr},required:["sequenceId","goalId"],additionalProperties:!1}},{name:"delete_sequence_goal",description:"Delete one persisted sequence conversion goal.",inputSchema:{type:"object",properties:{...gt,goalId:{type:"string",description:"Sequence goal ID."}},required:["sequenceId","goalId"],additionalProperties:!1}}];var Un={companyId:{type:"string",description:"Company ID. If omitted, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence with an inbound_webhook trigger."}},ir=[{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:Un,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:{...Un,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:Un,required:["sequenceId"],additionalProperties:!1}}];var sr=[{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, nodeType, 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. sequence.emails includes action_ab_test steps, whose copy lives on the A/B test variants rather than on the node: their subject/previewText/blocks are control variant A only. With ab_tests:read, each carries abTest with the test id, status, and one entry per variant including that variant's full blocks, so a sequence read is enough to audit CTA/promo/review copy; without that scope, test-record fields are redacted and variants is empty while the configured id and editing guidance remain available. To change the copy of an A/B step, edit each variant with update_ab_test_variant - if that tool is not in the tool list, enable it on the Sequenzy connector rather than writing through update_template or update_sequence_node. Rebuilding the step as a plain email node to reach the copy destroys the test. get_ab_test remains the dedicated A/B read for settings, localization, and stats. ${pe}`,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. The response always echoes the sequence's single configured stopCondition, including matchConfig filters or comparisons. A stop condition does not cancel a waiting enrollment when its event arrives: it is re-evaluated when the enrollment next runs a step, so an enrollment parked on a delay keeps reporting `waiting` until that delay expires. Pass stopConditionMatch true to see whether each in-flight enrollment's stop condition matches right now. This is a non-atomic snapshot: a step already past its stop check may still finish. Each enrollment also reports enteredVia - the list, tag, segment, event, inactivity check, or frequency check that enrolled it - which is how you tell apart contacts entering a sequence whose trigger covers several lists or tags. entryContext adds the event id, property keys (never values), and trigger type. branchDecisions records the bounded retained if/else (or random split) verdicts, including the compared field name and a redacted value summary (missing/empty/nonempty/equals_expected); branchDecisionCount and branchDecisionsTruncated tell you when older verdicts were omitted. For the ClickHouse graph walk of one completed token, use get_sequence_enrollment. Live sequence tests do not create enrollments; they send isolated test emails and record activity on the sequence test run 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 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."},stopConditionMatch:{type:"boolean",description:"Annotate each returned active or waiting enrollment with whether the sequence's stop condition matches for that contact right now, using the same evaluation the worker runs before each step. Use this to confirm a stop event, tag, or field change registered without waiting out the current delay: a matching enrollment can still report `waiting`, so status alone cannot tell you. This is a non-atomic snapshot, not a promise of a future exit: the condition can change, a paused sequence may not run on schedule, and a step already past its stop check may still finish. Each annotated enrollment costs an evaluation, so this caps the page at 100 regardless of limit; stopConditionMatchEvaluatedCount reports how many were actually evaluated. Defaults to false."},limit:{type:"number",description:"Enrollments per page, 1-500. Defaults to 50. Use the maximum when exporting. Capped at 100 when stopConditionMatch is true."},offset:{type:"number",description:"Number of enrollments to skip. Page until pagination.hasMore is false."}},required:["sequenceId"],additionalProperties:!1}},{name:"get_sequence_enrollment",description:"Read one sequence enrollment token, including how it entered and which branches it already took. Use this after list_sequence_enrollments when a completed token shows enteredVia unknown or Sequence completed with no email: nodeHistory is the bounded ClickHouse graph walk (redacted), and nodeHistoryTruncated tells you when more events exist. branchDecisionCount and branchDecisionsTruncated report whether the token's bounded decision array omitted older decisions. A legacy token whose first unmatched branch went straight to completion still reports the compared field name and a safe value summary (missing/empty/nonempty/equals_expected) rather than the raw recipient value. entryContext lists event property keys, never values. Requires sequences:read.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},sequenceId:{type:"string",description:"Sequence ID that owns the enrollment."},enrollmentId:{type:"string",description:"Enrollment token ID from list_sequence_enrollments (enrollmentId)."}},required:["sequenceId","enrollmentId"],additionalProperties:!1}},{name:"simulate_sequence",description:"Dry-run a sequence without sending mail or enrolling anyone. Requires sequences:read and subscribers:read because results include contact samples. Nobody is auto-enrolled when you activate. Without a subscriber this reports who currently matches (existing list/tag/segment matches are not auto-enrolled) and activation readiness errors. Frequency and inactivity current-match counts are unavailable because the hourly worker evaluates them. Pass subscriberId or email to also walk that stored contact's branch path - use this to check whether a paid user would get an upgrade email. Call this before enable_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 to simulate."},subscriberId:{type:"string",description:"Optional stored subscriber to walk through the graph. Do not pass with email."},email:{type:"string",description:"Optional stored subscriber email to walk through the graph. Do not pass with subscriberId."},limit:{type:"integer",minimum:1,maximum:25,description:"Maximum currently matching contacts to include in the sample. Defaults to 10."}},required:["sequenceId"],additionalProperties:!1}},{name:"send_sequence_test_email",description:"Queue a real test send for one saved action_email step in a sequence. Call get_sequence first and pass the target sequence.emails entry's nodeId only when nodeType is action_email; action_ab_test steps are not supported by this tool - inspect variant copy on get_sequence.sequence.emails[].abTest.variants. 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:"action_email step nodeId from get_sequence. The node must belong to sequenceId. Do not pass an action_ab_test node; inspect its variants on get_sequence.sequence.emails[].abTest.variants."},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/listIds, tagName/tagNames, 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:ce},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:le},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). Omit to use listScope instead. Use listIds to trigger on several lists."},listIds:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several list IDs for a contact_added trigger. A contact joining ANY of them enrolls. Use this instead of listId when the user says 'when added to list A or list B'. Cannot be combined with listScope."},listScope:{type:"string",enum:["any_contact","any_list"],description:"For contact_added with no list at all. 'any_contact' (default) enrolls every contact added, including the list-less contacts that integrations like PostHog, Stripe, or Supabase create when no list targeting is configured. 'any_list' waits until the contact actually joins a list. Cannot be combined with listId or listIds."},tagName:{type:"string",description:"Tag name to trigger on (required for tag_added trigger). Use tagNames to trigger on several tags."},tagNames:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several tag names for a tag_added trigger. Receiving ANY of them enrolls the contact. Use this instead of tagName when the user says 'when tagged vip or trial'."},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:tt,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 entry_audience matching, omit this value because the enrolling tag or list is resolved per contact. Use null or omit for type 'none'."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching. event_property_filter and event_property refine event_received; field_value refines field_changed. entry_audience with audience tag/list makes a does_not_have_tag/removed_from_list guard resolve the tag or list that enrolled each contact; tag requires a tag_added trigger, and list requires a contact_added trigger scoped to at least one specific list. Omit value for this mode.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value","entry_audience"]},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."},audience:{type:"string",enum:["tag","list"],description:"entry_audience mode source to resolve per enrollment."}},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:qe,subject:{type:"string",description:"Email subject. Required for email steps."},previewText:{type:"string",description:"Email preview text."},blocks:{type:"array",description:we,items:{type:"object"}},html:{type:"string",description:`HTML content for email steps. Use this for imported provider HTML. ${A}`},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."},...Me,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:Ie,delayMs:{type:"number",description:"Delay before this step in milliseconds. Prefer delay for readability; use delayMs when importing provider waits."},waitUntil:_e,waitUntilWeekday:ve,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.${Qe}`,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 rr=[{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. The emails/steps arrays reach action_email steps only: an action_ab_test step keeps its copy on the A/B test variants, so read variant blocks from get_sequence.sequence.emails[].abTest.variants and change each variant with update_ab_test_variant. If update_ab_test_variant is not in the tool list, enable it on the Sequenzy connector rather than writing through update_template. 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."},listIds:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several list IDs for a contact_added trigger replacement. Joining ANY of them enrolls the contact. Cannot be combined with listScope."},listScope:{type:"string",enum:["any_contact","any_list"],description:"For a contact_added trigger replacement with no list. 'any_contact' (default) enrolls every contact added, even one that joins no list; 'any_list' waits for a list membership. Cannot be combined with listId or listIds."},tagName:{type:"string",description:"Tag name required for a tag_added trigger replacement."},tagNames:{type:"array",minItems:1,maxItems:25,items:{type:"string"},description:"Several tag names for a tag_added trigger replacement. Receiving ANY of them enrolls the contact."},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:ce},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:le},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:tt,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 entry_audience matching, omit this value because the enrolling tag or list is resolved per contact."},matchConfig:{type:["object","null"],description:"Optional stop-condition matching, four shapes keyed by mode. event_property_filter and event_property refine event_received; field_value refines field_changed. entry_audience with audience tag/list makes a does_not_have_tag/removed_from_list guard resolve the tag or list that enrolled each contact; tag requires a tag_added trigger, and list requires a contact_added trigger scoped to at least one specific list. Omit value for this mode. Pass null to clear.",properties:{mode:{type:"string",enum:["event_property_filter","event_property","field_value","entry_audience"],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."},audience:{type:"string",enum:["tag","list"],description:"entry_audience mode source to resolve per enrollment."}},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:gn,randomPercentages:fn,branches:{type:"array",description:yn,items:hn},elseSteps:{type:"array",description:"Optional new steps inside the else fallback path. Not valid on a random split.",items:Le},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:Le}},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. ${A}`},htmlContent:{type:"string",description:`Alias for html for imported provider markup. ${A}`},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."},emailTheme:nt,blocks:{type:"array",description:`${Q}${Xe}`,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."},...Me}}},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. ${A}`},htmlContent:{type:"string",description:`Alias for html. ${A}`},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."},emailTheme:nt,blocks:{type:"array",description:`${Q}${Xe}`,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."},...Me}}},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:qe},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. To restyle one email, patch changes:{ emailTheme:{ colors:{ background:'#ffffff' } } } on its action_email node - that overrides only this step's linked email and leaves the company-wide theme alone. 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. It also cannot edit the copy of an action_ab_test step: that content lives on the A/B test variants (get_sequence.sequence.emails[].abTest.variants includes the blocks), so change each one with update_ab_test_variant. If update_ab_test_variant is not in the tool list, enable it on the Sequenzy connector rather than writing through update_template. 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:it.properties.nodeId,changes:Qt,expectedUpdatedAt:it.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 restyling several action_email nodes at once with changes:{ emailPreset:'minimal' } or changes:{ emailTheme:{ colors:{ background:'#ffffff' } } }, 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:it},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:we,items:{type:"object"}},html:{type:"string",description:`HTML content for an imported provider step. Provide either html or blocks, not both. ${A}`},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:{...qe,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:Ie,delayMs:{type:"number",description:"Optional wait in milliseconds before the new step. Prefer delay for readability."},waitUntil:_e,waitUntilWeekday:ve,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:gn,randomPercentages:fn,branches:{type:"array",description:`logic_branch only: ${yn}`,items:hn},elseSteps:{type:"array",description:"logic_branch only: optional new steps for the else path. Not valid on a random split.",items:Le},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. Call simulate_sequence first to see who currently matches and whether the sequence is ready. Nobody is auto-enrolled on activate.",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 qa={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"},timezone:{type:"string",description:"IANA timezone identifier (e.g. America/New_York) used for recipient-local campaign delivery. Rows with an invalid value import without it."},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},or=[{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. Matching sequences enroll by default (REST enrollInSequences), including tag_added when tags are set in this call, without requiring a list; pass enrollInSequences false to skip, and automations:trigger is required for enrollment. 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."},timezone:{type:"string",description:"IANA timezone identifier (e.g. America/New_York), stored as a native profile field. Enables recipient-local campaign delivery for this contact."},attributes:{type:"object",description:"Custom attributes (plan, company, etc.). Same field as REST customAttributes; provide one or the other. Use firstName/lastName for names instead of attributes.",additionalProperties:!0},customAttributes:{type:"object",description:"REST name for attributes. Same custom-attribute map; provide attributes or customAttributes, not both.",additionalProperties:!0},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. Omit to let a contact this call creates follow the workspace default lists; an existing contact then keeps the memberships they already have. Pass [] to join no list."},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."},enrollInSequences:{type:"boolean",description:"Whether matching sequences may enroll this contact, including tag_added flows when tags are set in the same call. Same field as REST POST /api/v1/subscribers enrollInSequences. Defaults to true unless createdAt is supplied. Requires automations:trigger. Pass false to create and tag without enrollment. List membership is not required."},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:qa,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."},idempotencyKey:{type:"string",minLength:1,maxLength:255,description:"Caller-owned key (1-255 characters, not blank) that makes retrying this request safe. The key is scoped to the request content: resending the same request returns the already-queued import (deduplicated: true), while different content under the same key queues a new import. Use it whenever a timeout or retry loop could resend the same import. If two identical requests overlap, a transient 503 means to retry the same call shortly."}},required:["subscribers"]}},{name:"get_subscriber_import",description:"Get progress, counts, skipped reasons, and failure summaries for a queued subscriber import. Every excluded row is explained: skippedReasons sums to skippedCount and failedReasons sums to failedCount, so a finished import can be reconciled without inspecting individual contacts. If the reason counts fall short of the totals, report it with the import ID rather than guessing what the missing rows were.",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."},timezone:{type:"string",description:"New IANA timezone identifier (e.g. America/New_York), stored as a native profile field. Pass an empty string to clear it. Enables recipient-local campaign delivery for this contact."},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 merge into the existing map. This is the legacy MCP spelling; provide attributes or customAttributes, not both. Use firstName/lastName for names instead of attributes.",additionalProperties:!0},customAttributes:{type:"object",description:"REST spelling for custom attributes. Replaces the existing public custom-attribute map, matching REST PATCH semantics; provide attributes instead when you want to retain unspecified keys. Provide attributes or customAttributes, not both.",additionalProperties:!0},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:F},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:"import_subscriber_events",description:"Record a bounded batch of events for many subscribers in one call, built for data pipeline and warehouse syncs. Each event carries its own email or externalId and a required source-owned eventId; externalId-only rows must identify an existing contact because email is required for creation. Contacts whose events are all more than an hour old are imported silently as history (including no double-opt-in email); any recent event makes that contact's whole group live. Retries preserve one receipt and idempotently re-attempt downstream recovery. Accepts at most 25 events.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company ID. If not provided, uses the currently selected company."},events:{type:"array",minItems:1,maxItems:25,items:{type:"object",properties:{email:{type:["string","null"],description:"Subscriber email address. Required when the event may create a new contact; null is treated as absent."},externalId:{type:["string","null"],description:"Customer-owned subscriber ID. It can be used alone only when it resolves to an existing contact; null is treated as absent."},name:{type:"string",description:"Event name"},properties:{type:"object",description:"Event properties",additionalProperties:!0},occurredAt:{type:["string","null"],description:"When the event happened (ISO 8601; null is absent). Classification is per contact: only when every row for that contact is more than an hour old is the group historical; any recent row makes the whole group live."},eventId:{type:"string",minLength:1,description:"Required source-owned id for this event, making a re-run idempotent on both the live and historical paths."}},required:["name","eventId"],additionalProperties:!1},description:"Events to record. Each event identifies its own subscriber."}},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:[...et],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 jn={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:"Deprecated: accepted and ignored. It previously limited a provider-side suppression lookup, which no longer happens."}},ar=[{name:"list_recipient_suppressions",description:"List the recipients this company cannot reach: protected global invalid-recipient suppressions for addresses associated with the company, protected workspace hard bounces without conclusive invalid-inbox evidence, removable workspace soft-bounce escalations, and protected spam complaints. Each row includes a stable suppressionType, and the response echoes the applied sortBy/sortOrder. Sort by `status` to surface the suppressions you can actually remove. Start here when a customer reports missing email; use get_recipient_suppression for one exact address.",inputSchema:{type:"object",properties:{companyId:jn.companyId,search:{type:"string",description:"Case-insensitive substring filter on the recipient email address."},page:{type:"number",description:"1-based page number. Defaults to 1."},limit:{type:"number",description:"Entries per page. Defaults to 25, maximum 100."},sort:{type:"string",enum:["suppressedAt","email","status"],description:"Order the page. `suppressedAt` (default) is newest first, `email` is A-Z, and `status` lists removable workspace escalations before protected suppressions. An unrecognized value falls back to `suppressedAt`."},order:{type:"string",enum:["asc","desc"],description:"Sort direction. Defaults to `desc` for suppressedAt and status, `asc` for email."}},required:[],additionalProperties:!1}},{name:"get_recipient_suppression",description:"Check whether one recipient is suppressed by Sequenzy's bounce/complaint safeguards. Suppression comes solely from Sequenzy's own bounce records; the email provider's suppression list is not consulted. This exact-address lookup never exposes other recipients.",inputSchema:{type:"object",properties:jn,required:["email"],additionalProperties:!1}},{name:"remove_recipient_suppression",description:"Remove a workspace-scoped soft-bounce escalation for an exact recipient associated with the company, then reactivate bounced company subscribers. Global invalid-recipient, workspace hard-bounce, complaint, and unsubscribe suppressions are protected.",inputSchema:{type:"object",properties:jn,required:["email"],additionalProperties:!1}}];var dr=[{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:[...ke],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:[...ke],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. Each list includes subscriberCount (current members of any status) and activeSubscriberCount (current members with status=active). Members who unsubscribed from the list are not counted. Use these fields for list audience size instead of paging search_subscribers.",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" }] }] }`. AND of two or more positive attribute filters on the same array path (e.g. `history_events[].eventvenue_id` and `history_events[].showing_date`) requires one array element to satisfy every condition — a 2010 visit at that venue plus an unrelated recent booking elsewhere does not match. Negative filters (`is_not`, `not_contains`, `is_empty`) are exempt: they assert no element matches and combine independently. Supports `event` and `segment` fields, Stripe product purchase/current/trial/date filters, and campaign- or delivery-policy-scoped engagement filters such as `emailOpened is marketing:all`.',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:en,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 marketing-open filter: [{"id":"filter-1","field":"emailOpened","operator":"is","value":"marketing:all"}]. 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:{...tn,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:en,minItems:1,description:"Replacement segment filters. Same shape and validation rules as create_segment. Mutually exclusive with `root`."},root:{...tn,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. Requires the segments:delete scope; segments:write is not enough.",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 cr=[{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, marketer, 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 marketer or 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","marketer","viewer","restricted"],description:"Team role. Admins can manage the workspace; marketers create, edit, and send campaigns and sequences and manage subscribers but cannot access transactional emails, settings, billing, or the team; 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 lr=[{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."},isTemplate:{type:"boolean",description:"Filter to reusable master designs (true) or everything else (false). Dashboard sequence steps and campaigns can start from these designs as independent copies. MCP does not expose a standalone-template copy operation; create_campaign accepts templateId for campaign copies."},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. Creating a standalone copy of a saved design and AI rewriting within its layout are currently dashboard-only workflows; this tool has no source-design operation, and `prompt` does not preserve an existing layout. For a campaign copy, use create_campaign with templateId.",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. ${A}`},blocks:{type:"array",description:L,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`. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values are freeform prompt guidance. Defaults to the company's email style preference."},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"}},isTemplate:{type:"boolean",description:"Save as a reusable master design. Master designs are offered first when a dashboard sequence step or campaign starts from an existing email, and starting from one always creates an independent copy."}},required:["name"]}},{name:"update_template",description:"Update an existing template. At least one of `name`, `subject`, `previewText`, `html`, `blocks`, `labels`, or `isTemplate` 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. ${A}`},blocks:{type:"array",description:L,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"}},isTemplate:{type:"boolean",description:"Mark (true) or unmark (false) this email as a reusable master design that sequence steps and campaigns can start from."}},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\`. ${A}`},blocks:{type:"array",description:L,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 pr=[{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\`. ${A}`},blocks:{type:"array",description:`${L} 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. Only used with `prompt`. Pass 'designed' or 'plain' to force the designed or plain-text email style; other values (minimal, branded, promotional) are freeform prompt guidance. Defaults to the company's email style preference."},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\`. ${A}`},blocks:{type:"array",description:`${Q} 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. Always provide a stable `idempotencyKey` when an agent or workflow may retry, and reuse it for the same logical email; Sequenzy returns the original send for 14 days and rejects different content under the same key. The default delivery policy is transactional. A transactional send delivers one email to several people at once: `to` takes up to 50 addresses and `cc`/`bcc` take up to 50 each, so everyone sees the same shared recipient list instead of receiving separate copies. Addresses repeated across the fields are dropped from the lower-priority one (to beats cc beats bcc). 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; marketing sends take exactly one `to` recipient and no `cc` or `bcc`. When no identity override is provided, a template send keeps its saved From and Reply-To identities, while a direct send uses the company defaults. To send as a non-default verified brand, pass `fromEmail` (and `fromName` if that address has several identities) plus optional `replyTo`/`replyToName`; you do not need profile IDs. `senderProfileId`/`replyProfileId` from `list_sender_profiles` remain available when you already have them. These fields look up existing identities and do not create profiles. `{{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. When `trackingSettings` is omitted, the company's Transactional API defaults apply. Set `clickTracking` or `openTracking` to `false` to opt out for this send only; these fields cannot enable tracking disabled by account settings. Returns a durable emailSendId, the accepted emailType, and the deduplicated recipient lists; 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","array"],items:{type:"string"},minItems:1,maxItems:50,description:"Primary recipient email address, or an array of up to 50 addresses that share one email and see each other in the To header. Marketing sends accept exactly one address."},cc:{type:["string","array"],items:{type:"string"},maxItems:50,description:"Carbon-copy email address, or an array of up to 50, visible to every recipient. Transactional sends only. Addresses already in `to` are dropped."},bcc:{type:["string","array"],items:{type:"string"},maxItems:50,description:"Blind-carbon-copy email address, or an array of up to 50, hidden from the other recipients. Transactional sends only. Addresses already in `to` or `cc` are dropped."},idempotencyKey:{type:"string",description:"Caller-owned retry key for this logical email (maximum 255 characters). Reuse the same key with the same arguments to get the original emailSendId for 14 days. Never reuse a key for different content."},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 `to` recipient, rejects `cc` and `bcc`, and automatically applies subscriber suppression, the standard unsubscribe footer, and RFC 8058 headers. Both modes use the Send API and require the `transactional:send` scope; a personal key held by a `marketer` cannot use this tool in either mode (see `roleRestrictedScopes` on get_account) and should send through campaigns or sequences instead."},replyTo:{type:"string",description:"Optional Reply-To address, formatted as `email@example.com` or `Name <email@example.com>`. Pair a bare address with `replyToName` instead of embedding the name. Mutually exclusive with `replyProfileId`. When omitted, the saved template or company default is used."},replyToName:{type:"string",description:"Display name for `replyTo`. Requires a bare `replyTo` address. Mutually exclusive with `replyProfileId`. Does not create a reply profile."},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. Mutually exclusive with fromEmail. When omitted, a template send keeps its saved sender and a direct send uses the company default."},fromEmail:{type:"string",description:"From address of an existing verified sender profile (see list_sender_profiles). Mutually exclusive with senderProfileId. If the address has several identities, pass fromName to choose one. Does not create a new sender profile."},fromName:{type:"string",description:"Display name of an existing verified sender identity on fromEmail, e.g. StudyBoost vs StudyBoost News. Requires fromEmail. Mutually exclusive with senderProfileId. Does not create a new sender profile."},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. Mutually exclusive with replyTo."},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 ze={type:"string",description:"Company ID. If not provided, uses the currently selected company."},ur=[{name:"list_web_tracking_keys",description:"List the publishable keys that let a non-Shopify website send on-site events (product views, cart activity, collection views, search) into this workspace. Check this BEFORE promising that browse abandonment, cart recovery, or any product-view trigger will work on a custom site: without an installed key those events never arrive, the sequences built on them never fire, and nothing reports an error anywhere. Each key returns `allowedOrigins`, `unrestricted`, `lastUsedAt`, and a paste-ready `installSnippet`. A key with `lastUsedAt: null` has not successfully authenticated an event yet; it may be undeployed, have no instrumented traffic, or be sending requests rejected by its origin allowlist. Shopify stores do not use these keys; they use the storefront pixel, so check get_integration_pixel instead.",inputSchema:{type:"object",properties:{companyId:ze}}},{name:"get_web_tracking_key",description:"Get one web tracking key with its install snippet and ingest endpoint. Use this to hand a developer the exact `<script>` tag to paste, rather than reconstructing it - the snippet embeds both the publishable key and the workspace id, and a hand-built one that gets either wrong fails silently.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Web tracking key ID from list_web_tracking_keys."},companyId:ze},required:["id"]}},{name:"create_web_tracking_key",description:"Create a publishable key for the browser tracking SDK and return the install snippet. This is what turns on product views, cart activity, and browse abandonment for a site that is NOT Shopify or WooCommerce (custom storefronts, headless shops, marketplaces, SaaS marketing sites). Events start flowing once the snippet is deployed and nothing is backfilled for the period before that, so create and install it BEFORE building the sequence that depends on it. Always pass allowedOrigins: a key with none accepts anonymous events from any site. Identified events require a short-lived token minted by the customer's authenticated backend through POST /api/v1/web-tracking-identities (passing the key's publicKey or keyId), then `sequenzy.identify(email, identityToken)`; a publishable key alone can never trigger subscriber automation.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Human-readable label for this key, e.g. 'Storefront' or 'Marketing site'."},allowedOrigins:{type:"array",items:{type:"string"},description:"Origins allowed to use this key, e.g. ['https://example.com', 'https://*.example.com']. A bare domain is read as https. A `*.` wildcard matches subdomains at any depth but NOT the apex, so list the apex separately if you need it. Include the development origin (e.g. http://localhost:3000) while wiring the SDK up. Omitting this leaves the key unrestricted, which should be a deliberate choice for a native app or server-side caller."},companyId:ze},required:["name"]}},{name:"update_web_tracking_key",description:"Rename a web tracking key, replace its allowed origins, or revoke it. `allowedOrigins` REPLACES the whole list rather than appending, so include the origins you want to keep. Revoking with isActive: false stops events within about a minute while preserving the key value, so the customer can still find and remove the matching snippet from their site; use delete_web_tracking_key only once the snippet is gone.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Web tracking key ID from list_web_tracking_keys."},name:{type:"string",description:"New label for the key."},allowedOrigins:{type:"array",items:{type:"string"},description:"Replacement allowed-origins list. Pass an empty array to make the key unrestricted."},isActive:{type:"boolean",description:"Set false to revoke the key, true to re-enable a revoked one."},companyId:ze},required:["id"]}},{name:"delete_web_tracking_key",description:"Permanently delete a web tracking key. Cached authorization expires within one minute, after which requests from any remaining snippet are rejected; remove the snippet from the site as well. Prefer update_web_tracking_key with isActive: false when the key might be needed again.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Web tracking key ID from list_web_tracking_keys."},companyId:ze},required:["id"]}}];var mr=[{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:[...Se]},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:[...Se]},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 ft=[...js,...Js,...Ws,...or,...ar,...Xs,...dr,...Ls,...lr,...Hs,...Bs,...Us,...zs,...Fs,...er,...Ks,...Qs,...Zs,...Vs,...sr,...rr,...nr,...ir,...pr,...Ms,...cr,...Ys,...ur,...mr,...Ns,...Gs];function Pa(t){if(!Array.isArray(t))return null;return t.flatMap((e)=>I(e)&&typeof e.id==="string"?[e.id]:[])}var hr={new_subscriber:["off","instant","daily"],form_submitted:["off","instant"],campaign_completed:["off","instant"],weekly_report:["off","weekly"]};function Ea(t){if(!Array.isArray(t))return;for(let e of t){if(!I(e))continue;let{event:n,mode:s}=e;if(typeof n!=="string"||typeof s!=="string"||!Object.prototype.hasOwnProperty.call(hr,n))continue;let i=hr[n];if(!i.includes(s))throw Error(`Invalid mode "${s}" for ${n}. Use one of: ${i.join(", ")}.`)}}async function yr(t,e){let n;switch(t){case"get_account":{let s=await a("GET","/api/v1/account",void 0,null),i=ie(),r=Pa(s.companies),o=i!==null&&r!==null&&!r.includes(i);if(o)Ae(null);n={...s,selectedCompanyId:(o?null:i)??s.currentCompanyId,...o&&{note:`The previously selected company (${i}) is no longer available to this API key and has been cleared. Call select_company with one of the companies listed above, or pass companyId explicitly.`}};break}case"select_company":{let s=e.companyId,i=await a("GET","/api/v1/account",void 0,null),r=i.companies?.find((o)=>o.id===s);if(!r)throw Error(`Company not found. Available companies: ${i.companies?.map((o)=>`${o.name} (${o.id})`).join(", ")??"none"}`);Ae(s),n={success:!0,message:`Switched to company: ${r.name}`,companyId:r.id,companyName:r.name};break}case"get_app_urls":{let s=await mt(e);n={...Z({companyId:s,campaignId:l(e,"campaignId"),landingPageId:l(e,"landingPageId"),sequenceId:l(e,"sequenceId"),emailId:l(e,"emailId")??l(e,"templateId"),transactionalId:l(e,"transactionalId"),emailSendId:l(e,"emailSendId"),domainId:l(e,"domainId"),status:l(e,"status"),settingsTab:l(e,"settingsTab")}),...s===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 s=await a("POST","/api/v1/companies",{name:e.name,domain:e.domain});if(!s.success)throw Error("Failed to create company");let i=s.company.id,r=6,o=0,d=s.company.status;while(d==="processing"&&o<r){await new Promise((g)=>setTimeout(g,20000)),o++;let m=await a("GET",`/api/v1/companies/${i}`);if(m.success)d=m.company.status}Ae(i);let c=await a("GET",`/api/v1/companies/${i}`);n={success:!0,company:c.company,message:d==="processing"?"Company created but still processing. You can continue using it while processing completes.":`Company '${c.company.name}' created and ready to use.`,autoSelected:!0};break}case"get_company":{let s=e.companyId;n=await a("GET",`/api/v1/companies/${s}`);break}case"update_company":{let s=await Ce("update_company",e),i=Ni(e);n=await a("PATCH",`/api/v1/companies/${s}`,i);break}case"get_sync_rules":{let s=e.companyId;n=await a("GET","/api/v1/sync-rules",void 0,s);break}case"update_sync_rules":{let s=e.companyId;if(e.syncRules!==null&&!Array.isArray(e.syncRules))throw Error("`syncRules` must be an array of rules or null when calling `update_sync_rules`.");n=await a("PUT","/api/v1/sync-rules",{syncRules:e.syncRules},s);break}case"get_email_design_system":{let s=e.companyId;n=await a("GET","/api/v1/email-design-system",void 0,s);break}case"update_email_design_system":{let s=e.companyId,i={};if(e.designCode!==void 0)i.designCode=e.designCode;if(e.compositionSpine!==void 0)i.compositionSpine=e.compositionSpine;if(e.reset!==void 0)i.reset=e.reset;if(Object.keys(i).length===0)throw Error("Pass at least one of `designCode`, `compositionSpine`, or `reset: true` when calling `update_email_design_system`.");n=await a("PATCH","/api/v1/email-design-system",i,s);break}case"get_shopify_automation_settings":{let s=e.companyId;n=await a("GET","/api/v1/shopify/automation-settings",void 0,s);break}case"update_shopify_automation_settings":{let s=e.companyId,i={};if(e.browseAbandonment!==void 0)i.browseAbandonment=e.browseAbandonment;if(e.cartAbandonment!==void 0)i.cartAbandonment=e.cartAbandonment;if(e.priceDrop!==void 0)i.priceDrop=e.priceDrop;if(Object.keys(i).length===0)throw Error("Provide `browseAbandonment`, `cartAbandonment`, and/or `priceDrop` when calling `update_shopify_automation_settings`.");n=await a("PUT","/api/v1/shopify/automation-settings",i,s);break}case"create_api_key":{let s=e.companyId,i={};if(typeof e.name==="string")i.name=e.name;if(typeof e.preset==="string")i.preset=e.preset;if(Array.isArray(e.scopes))i.scopes=e.scopes;n=await a("POST","/api/v1/api-keys",i,s);break}case"request_api_key_handoff":{let s=await Ce(t,e),i={};if(typeof e.name==="string")i.name=e.name;if(typeof e.preset==="string")i.preset=e.preset;if(Array.isArray(e.scopes))i.scopes=e.scopes;if(typeof e.replaceApiKeyId==="string")i.replaceApiKeyId=e.replaceApiKeyId;n=await a("POST","/api/v1/api-key-handoff",i,s);break}case"list_api_keys":{let s=await Ce(t,e);n=await a("GET","/api/v1/api-keys",void 0,s);break}case"update_api_key":{let s=await Ce(t,e),i={};if(typeof e.name==="string")i.name=e.name;if(typeof e.preset==="string")i.preset=e.preset;if(Array.isArray(e.scopes))i.scopes=e.scopes;if(Object.keys(i).length===0)throw Error("Provide at least one of `name`, `preset`, or `scopes` when calling `update_api_key`.");n=await a("PATCH",`/api/v1/api-keys/${encodeURIComponent(String(e.apiKeyId))}`,i,s);break}case"revoke_api_key":case"delete_api_key":{let s=await Ce(t,e);n=await a("DELETE",`/api/v1/api-keys/${encodeURIComponent(String(e.apiKeyId))}`,void 0,s);break}case"list_websites":{let s=e.companyId;n=await a("GET","/api/v1/websites",void 0,s);break}case"add_sending_domain":case"add_website":{let s=e.companyId;n=await a("POST","/api/v1/websites",{domain:e.domain},s);break}case"check_website":{let s=e.companyId;n=await a("GET",`/api/v1/websites/${encodeURIComponent(String(e.domain))}`,void 0,s);break}case"verify_sending_domain":{let s=e.companyId;n=await a("POST",`/api/v1/websites/${encodeURIComponent(String(e.domain))}/verify`,void 0,s);break}case"list_integrations":{let s=e.companyId,i=new URLSearchParams;if(e.includeInactive===!0)i.set("includeInactive","true");let r=i.toString();n=await a("GET",`/api/v1/integrations${r?`?${r}`:""}`,void 0,s);break}case"list_sender_profiles":{let s=e.companyId;n=await a("GET","/api/v1/sender-profiles",void 0,s);break}case"update_sender_profile":{let{companyId:s,profileId:i}=e,r=e.type==="reply"?`/api/v1/reply-profiles/${encodeURIComponent(i)}`:`/api/v1/sender-profiles/${encodeURIComponent(i)}`;n=await a("PATCH",r,{name:e.name},s);break}case"delete_sender_profile":{let s=e.companyId,i=u("delete_sender_profile",e,"profileId");n=await a("DELETE",`/api/v1/sender-profiles/${encodeURIComponent(i)}`,void 0,s);break}case"get_sending_status":{let s=e.companyId;n=await a("GET","/api/v1/sending-status",void 0,s);break}case"resume_sending":{let s=e.companyId;n=await a("POST","/api/v1/sending-status/resume",{listSanitizationConfirmed:e.listSanitizationConfirmed===!0},s);break}case"get_tracking_settings":{let s=e.companyId;n=await a("GET","/api/v1/tracking-settings",void 0,s);break}case"update_tracking_settings":{let s=e.companyId,i=Mi(e);n=await a("PATCH","/api/v1/tracking-settings",i,s);break}case"get_notification_preferences":{let s=e.companyId;n=await a("GET","/api/v1/notification-preferences",void 0,s);break}case"update_notification_preferences":{let s=e.companyId;Ea(e.notificationPreferences),n=await a("PATCH","/api/v1/notification-preferences",{notificationPreferences:e.notificationPreferences},s);break}case"get_integration_guide":n=await a("POST","/api/v1/integration-guide",e);break;default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function gr(t,e){let n;switch(t){case"generate_email":{let s=e.companyId;n=await a("POST","/api/v1/generate/email",e,s);break}case"generate_subject_lines":{let s=e.companyId;n=await a("POST","/api/v1/generate/subjects",e,s);break}case"generate_sms":{let s=e.companyId;n=await a("POST","/api/v1/generate/sms",e,s);break}case"get_sms_settings":{let s=e.companyId;n=await a("GET","/api/v1/sms/settings",void 0,s);break}case"get_sms_usage":{let s=e.companyId;n=await a("GET","/api/v1/sms/usage",void 0,s);break}case"update_sms_number_label":{let s=e.companyId,i=u("update_sms_number_label",e,"numberId");if(e.label!==void 0&&typeof e.label!=="string")throw Error("update_sms_number_label `label` must be a string; pass an empty string to clear it.");if(e.brandPrefix!==void 0&&typeof e.brandPrefix!=="string")throw Error("update_sms_number_label `brandPrefix` must be a string; pass an empty string to clear it.");if(e.label===void 0&&e.brandPrefix===void 0)throw Error("update_sms_number_label requires `label` and/or `brandPrefix`.");n=await a("PATCH",`/api/v1/sms/numbers/${encodeURIComponent(i)}`,{...typeof e.label==="string"?{label:e.label.trim()||null}:{},...typeof e.brandPrefix==="string"?{brandPrefix:e.brandPrefix.trim()||null}:{}},s);break}case"release_sms_number":{let s=e.companyId,i=u("release_sms_number",e,"numberId");n=await a("DELETE",`/api/v1/sms/numbers/${encodeURIComponent(i)}`,void 0,s);break}case"send_test_sms":{let s=e.companyId,i={to:u("send_test_sms",e,"to")};for(let r of["text","imageUrls","blocks","fromNumberId"])if(e[r]!==void 0)i[r]=e[r];n=await a("POST","/api/v1/sms/test",i,s);break}case"submit_feedback":{let s=e.companyId,i={message:u("submit_feedback",e,"message"),source:"mcp"};for(let r of["category","context","userIntent","toolCalls","expected","actual","resourceIds"])if(e[r]!==void 0)i[r]=e[r];n=await a("POST","/api/v1/feedback",i,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function fr(t,e){let n;switch(t){case"list_transactional_emails":{let s=e.companyId,i=new URLSearchParams,r=l(e,"search"),o=S("list_transactional_emails",e,"status",["all","active","disabled"]),d=S("list_transactional_emails",e,"sort",["date","sends","opens","open-rate","clicks","ctr"]),c=S("list_transactional_emails",e,"order",["asc","desc"]);if(r)i.set("search",r);if(o)i.set("status",o);if(d)i.set("sort",d);if(c)i.set("order",c);if(e.includeMachineEngagement===!0)i.set("includeMachineEngagement","true");let m=i.toString();n=await a("GET",`/api/v1/transactional${m?`?${m}`:""}`,void 0,s);break}case"get_transactional_email":{let s=e.companyId;n=await a("GET",`/api/v1/transactional/${e.idOrSlug}`,void 0,s);break}case"create_transactional_email":{let s=e.companyId,i=new Set(["companyId","name","slug","subject","previewText","html","blocks","prompt","style","tone","enabled"]),r=Object.keys(e).filter((d)=>!i.has(d));if(r.length>0)throw Error(`\`create_transactional_email\` accepts only \`name\`, \`slug\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`prompt\`, \`style\`, \`tone\`, and \`enabled\` fields. Unsupported field${r.length===1?"":"s"}: ${r.map((d)=>`\`${d}\``).join(", ")}.`);ls(e);let o=Object.fromEntries(Object.entries(e).filter(([d])=>d!=="companyId"));n=await a("POST","/api/v1/transactional",o,s);break}case"update_transactional_email":{let s=e.companyId,i=new Set(["companyId","idOrSlug","name","enabled","subject","previewText","html","blocks"]),r=Object.keys(e).filter((d)=>!i.has(d));if(r.length>0)throw Error(`\`update_transactional_email\` accepts only \`name\`, \`enabled\`, \`subject\`, \`previewText\`, \`html\`, and \`blocks\` update fields. Unsupported field${r.length===1?"":"s"}: ${r.map((d)=>`\`${d}\``).join(", ")}.`);if(z("update_transactional_email",e),e.name===void 0&&e.enabled===void 0&&e.subject===void 0&&e.previewText===void 0&&e.html===void 0&&e.blocks===void 0)throw Error("Provide at least one of `name`, `enabled`, `subject`, `previewText`, `html`, or `blocks` when calling `update_transactional_email`.");let o=Object.fromEntries(Object.entries(e).filter(([d])=>d!=="companyId"&&d!=="idOrSlug"));n=await a("PATCH",`/api/v1/transactional/${e.idOrSlug}`,o,s);break}case"delete_transactional_email":{let s=e.companyId,i=u("delete_transactional_email",e,"idOrSlug");n=await a("DELETE",`/api/v1/transactional/${encodeURIComponent(i)}`,void 0,s);break}case"send_email":{let s=e.companyId,i=ut(e,"to");if(i===void 0)throw Error("`to` is required when calling `send_email`.");let r=ws({to:i,cc:ut(e,"cc"),bcc:ut(e,"bcc")}),{to:o,cc:d,bcc:c}=r,m=e.templateId===void 0?void 0:u("send_email",e,"templateId"),g=e.subject===void 0?void 0:u("send_email",e,"subject"),w=e.html===void 0?void 0:u("send_email",e,"html"),f=e.emailType===void 0?void 0:u("send_email",e,"emailType"),_=e.replyTo===void 0?void 0:u("send_email",e,"replyTo"),T=e.senderProfileId===void 0?void 0:u("send_email",e,"senderProfileId"),E=e.fromEmail===void 0?void 0:u("send_email",e,"fromEmail"),C=e.fromName===void 0?void 0:u("send_email",e,"fromName"),D=e.replyProfileId===void 0?void 0:u("send_email",e,"replyProfileId"),ee=e.replyToName===void 0?void 0:u("send_email",e,"replyToName"),te=e.idempotencyKey===void 0?void 0:u("send_email",e,"idempotencyKey"),U=typeof e.subscriberExternalId==="string"?l(e,"subscriberExternalId"):e.subscriberExternalId;if(te&&te.length>255)throw Error("`idempotencyKey` must be 255 characters or fewer when calling `send_email`.");let he;if(e.attachments!==void 0){if(!Array.isArray(e.attachments)||e.attachments.length>10)throw Error("`attachments` must be an array with at most 10 items when calling `send_email`.");he=e.attachments.map((O,H)=>{if(typeof O!=="object"||O===null||Array.isArray(O))throw Error(`\`attachments[${H}]\` must be an object when calling \`send_email\`.`);let B=O,Be=new Set(["filename","content","path","contentId","contentType"]);if(Object.keys(B).some((xe)=>!Be.has(xe)))throw Error(`\`attachments[${H}]\` contains an unsupported field when calling \`send_email\`.`);let W={};for(let xe of Be){let It=B[xe];if(It===void 0)continue;if(typeof It!=="string")throw Error(`\`attachments[${H}].${xe}\` must be a string when calling \`send_email\`.`);W[xe]=It}if(!W.filename)throw Error(`\`attachments[${H}].filename\` is required when calling \`send_email\`.`);let Gr=W.content!==void 0,Kr=W.path!==void 0;if(Gr===Kr)throw Error(`\`attachments[${H}]\` must provide exactly one of \`content\` or \`path\` when calling \`send_email\`.`);return W})}if(f!==void 0&&f!=="marketing"&&f!=="transactional")throw Error("`emailType` must be `marketing` or `transactional` when calling `send_email`.");if(m!==void 0&&(g!==void 0||w!==void 0))throw Error("`templateId` cannot be combined with `subject` or `html` when calling `send_email`.");if(m===void 0&&(g===void 0||w===void 0))throw Error("Provide either `templateId` or both `subject` and `html` when calling `send_email`.");re("send_email",e),_s({emailType:f,to:o,cc:d,bcc:c,subscriberExternalId:U});let ye;if(e.trackingSettings!==void 0){if(typeof e.trackingSettings!=="object"||e.trackingSettings===null||Array.isArray(e.trackingSettings))throw Error("`trackingSettings` must be an object with optional boolean `clickTracking` and `openTracking` fields when calling `send_email`.");let O=e.trackingSettings;ye={};for(let H of["clickTracking","openTracking"]){let B=O[H];if(B===void 0)continue;if(typeof B!=="boolean")throw Error(`\`trackingSettings.${H}\` must be a boolean when calling \`send_email\`.`);ye[H]=B}}let He=Object.fromEntries(Object.entries({to:o,cc:d,bcc:c,slug:m,subject:g,body:w,variables:e.variables,subscriberExternalId:U,emailType:f,replyTo:_,senderProfileId:T,fromEmail:E,fromName:C,replyProfileId:D,replyToName:ee,attachments:he,trackingSettings:ye}).filter(([,O])=>O!==void 0));n=te?await a("POST","/api/v1/transactional/send",He,s,{"Idempotency-Key":te}):await a("POST","/api/v1/transactional/send",He,s);break}case"get_stats":{let s=e.companyId,i=e.period??"7d",r=new URLSearchParams({period:String(i)}),o=e.emailType===void 0?void 0:u("get_stats",e,"emailType");if(o!==void 0&&!["campaign","transactional","sequence"].includes(o))throw Error("`emailType` must be `campaign`, `transactional`, or `sequence` when calling `get_stats`.");if(o)r.set("emailType",o);if(e.includeMachineEngagement===!0)r.set("includeMachineEngagement","true");n=await a("GET",`/api/v1/metrics?${r.toString()}`,void 0,s);break}case"get_campaign_stats":{let s=e.companyId,i=new URLSearchParams;if(typeof e.period==="string")i.set("period",e.period);if(typeof e.start==="string")i.set("start",e.start);if(typeof e.end==="string")i.set("end",e.end);if(e.includeMachineEngagement===!0)i.set("includeMachineEngagement","true");let r=i.toString();n=await a("GET",`/api/v1/metrics/campaigns/${e.campaignId}${r?`?${r}`:""}`,void 0,s);break}case"list_poll_responses":{let s=e.companyId,i=u("list_poll_responses",e,"campaignId"),r=new URLSearchParams,o=l(e,"blockId");if(o)r.set("blockId",o);for(let c of["page","limit"])if(e[c]!==void 0)r.set(c,String(e[c]));let d=r.toString();n=await a("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(i)}/poll-responses${d?`?${d}`:""}`,void 0,s);break}case"get_transactional_stats":{let s=e.companyId,i=u("get_transactional_stats",e,"idOrSlug"),r=new URLSearchParams;for(let d of["period","start","end"])if(typeof e[d]==="string"&&e[d].trim())r.set(d,e[d].trim());if(e.includeMachineEngagement===!0)r.set("includeMachineEngagement","true");let o=r.toString();n=await a("GET",`/api/v1/metrics/transactional/${encodeURIComponent(i)}${o?`?${o}`:""}`,void 0,s);break}case"get_sequence_stats":{let s=e.companyId,i=new URLSearchParams;for(let o of["period","start","end"])if(typeof e[o]==="string"&&e[o].trim())i.set(o,e[o].trim());if(e.includeMachineEngagement===!0)i.set("includeMachineEngagement","true");let r=i.toString();n=await a("GET",`/api/v1/metrics/sequences/${e.sequenceId}${r?`?${r}`:""}`,void 0,s);break}case"list_campaign_events":{let s=e.companyId,i=u("list_campaign_events",e,"campaignId"),o=Tn("list_campaign_events",e).toString();n=await a("GET",`/api/v1/metrics/campaigns/${encodeURIComponent(i)}/events${o?`?${o}`:""}`,void 0,s);break}case"list_sequence_events":{let s=e.companyId,i=u("list_sequence_events",e,"sequenceId"),r=Tn("list_sequence_events",e),o=l(e,"automationNodeId");if(o)r.set("automationNodeId",o);let d=r.toString();n=await a("GET",`/api/v1/metrics/sequences/${encodeURIComponent(i)}/events${d?`?${d}`:""}`,void 0,s);break}case"list_email_metrics":{let s=e.companyId,i=new URLSearchParams,r=S("list_email_metrics",e,"emailType",["campaign","sequence"]);if(r)i.set("emailType",r);let o=Nt("list_email_metrics",e,"sequenceId"),d=Nt("list_email_metrics",e,"campaignId"),c=P("list_email_metrics",e,"step",1,1000);if(d.length>0&&(o.length>0||c))throw Error("`campaignId` cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(r==="campaign"&&(o.length>0||c!==void 0))throw Error("`emailType` campaign cannot be combined with `sequenceId` or `step` when calling `list_email_metrics`.");if(r==="sequence"&&d.length>0)throw Error("`emailType` sequence cannot be combined with `campaignId` when calling `list_email_metrics`.");if(o.length>0)i.set("sequenceId",o.join(","));if(d.length>0)i.set("campaignId",d.join(","));if(c!==void 0)i.set("step",String(c));let m=S("list_email_metrics",e,"period",["1h","24h","7d","30d","90d"]);if(m)i.set("period",m);for(let E of["start","end"]){let C=l(e,E);if(C)i.set(E,C)}let g=S("list_email_metrics",e,"sort",["sent","delivered","opened","clicked","openRate","clickRate","unsubscribed","conversions","revenue","step","name"]);if(g)i.set("sort",g);let w=S("list_email_metrics",e,"order",["asc","desc"]);if(w)i.set("order",w);let f=P("list_email_metrics",e,"page",1,1e6);if(f!==void 0)i.set("page",String(f));let _=P("list_email_metrics",e,"limit",1,500);if(_!==void 0)i.set("limit",String(_));if(e.includeMachineEngagement===!0)i.set("includeMachineEngagement","true");let T=i.toString();n=await a("GET",`/api/v1/metrics/emails${T?`?${T}`:""}`,void 0,s);break}case"get_subscriber_activity":{let s=e.companyId,i=V("get_subscriber_activity",e),r=await $e(i,s,{includeMachineEngagement:e.includeMachineEngagement===!0});n={success:r.success,email:r.subscriber.email,emailStats:r.subscriber.emailStats??null,activity:r.subscriber.activity??[],sequenceEnrollments:r.subscriber.sequenceEnrollments??[]};break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function br(t,e){let n;switch(t){case"list_tags":{let s=e.companyId;n=await a("GET","/api/v1/tags",void 0,s);break}case"create_tag":{let s=e.companyId,i=u("create_tag",e,"name"),r=S("create_tag",e,"color",ke);n=await a("POST","/api/v1/tags",{name:i,...r!==void 0&&{color:r}},s);break}case"update_tag":{let s=e.companyId,i=u("update_tag",e,"tagId"),r=Fe("update_tag",e,"color",ke);n=await a("PATCH",`/api/v1/tags/${encodeURIComponent(i)}`,{color:r},s);break}case"delete_tag":{let s=e.companyId,i=u("delete_tag",e,"tagId");n=await a("DELETE",`/api/v1/tags/${encodeURIComponent(i)}`,void 0,s);break}case"list_lists":{let s=e.companyId;n=await a("GET","/api/v1/lists",void 0,s);break}case"create_list":{let s=e.companyId;n=await a("POST","/api/v1/lists",e,s);break}case"update_list":{let s=e.companyId,i=u("update_list",e,"listId");if(e.name===void 0&&e.description===void 0&&e.isPrivate===void 0)throw Error("Provide at least one of `name`, `description`, or `isPrivate` when calling `update_list`.");if(e.name!==void 0&&l(e,"name")===void 0)throw Error("`name` cannot be empty when calling `update_list`.");if(e.description!==void 0&&e.description!==null&&typeof e.description!=="string")throw Error("`description` must be a string or null when calling `update_list`.");if(e.isPrivate!==void 0&&typeof e.isPrivate!=="boolean")throw Error("`isPrivate` must be a boolean when calling `update_list`.");n=await a("PATCH",`/api/v1/lists/${encodeURIComponent(i)}`,{...e.name!==void 0&&{name:l(e,"name")},...e.description!==void 0&&{description:e.description},...e.isPrivate!==void 0&&{isPrivate:e.isPrivate}},s);break}case"delete_list":{let s=e.companyId,i=u("delete_list",e,"listId");n=await a("DELETE",`/api/v1/lists/${encodeURIComponent(i)}`,void 0,s);break}case"add_subscribers_to_list":{let s=e.companyId,i=u("add_subscribers_to_list",e,"listId"),r=Pn("add_subscribers_to_list",e),o=S("add_subscribers_to_list",e,"duplicateStrategy",["skip","merge","overwrite"])??"skip",d=S("add_subscribers_to_list",e,"optInMode",["default","confirmed","double_opt_in"])??"default";n=await a("POST",`/api/v1/lists/${encodeURIComponent(i)}/subscribers`,{emails:r,duplicateStrategy:o,enrollInSequences:e.enrollInSequences===!0,optInMode:d},s);break}case"remove_subscribers_from_list":{let s=e.companyId,i=u("remove_subscribers_from_list",e,"listId"),r=Pn("remove_subscribers_from_list",e);n=await a("POST",`/api/v1/lists/${encodeURIComponent(i)}/subscribers/remove`,{emails:r},s);break}case"list_segments":{let s=e.companyId;n=await a("GET","/api/v1/segments",void 0,s);break}case"create_segment":{Ui(e);let s=e.companyId;n=await a("POST","/api/v1/segments",{...e,...e.filters!==void 0?{filters:st(e.filters)}:{},...e.root!==void 0?{root:rt(e.root)}:{}},s);break}case"update_segment":{ji(e);let s=e.companyId,i=u("update_segment",e,"segmentId"),r=l(e,"name"),o=S("update_segment",e,"filterJoinOperator",["and","or"]);n=await a("PATCH",`/api/v1/segments/${encodeURIComponent(i)}`,{...r!==void 0&&{name:r},...o!==void 0&&{filterJoinOperator:o},...e.filters!==void 0?{filters:st(e.filters)}:{},...e.root!==void 0?{root:rt(e.root)}:{}},s);break}case"delete_segment":{let s=e.companyId,i=u("delete_segment",e,"segmentId");n=await a("DELETE",`/api/v1/segments/${encodeURIComponent(i)}`,void 0,s);break}case"get_segment_count":{let s=e.companyId;n=await a("GET",`/api/v1/segments/${e.segmentId}/count`,void 0,s);break}case"list_audience_syncs":{let s=e.companyId;n=await a("GET","/api/v1/audience-syncs",void 0,s);break}case"list_ad_accounts":{let s=e.companyId;n=await a("GET","/api/v1/ad-accounts",void 0,s);break}case"create_audience_sync":{let s=e.companyId,i=l(e,"segmentId"),r=l(e,"predefinedSegmentId");if(i&&r)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`, not both.");if(!i&&!r)throw Error("Provide either `segmentId` or `predefinedSegmentId` when calling `create_audience_sync`.");n=await a("POST","/api/v1/audience-syncs",{segmentId:i,predefinedSegmentId:r,adAccountId:u("create_audience_sync",e,"adAccountId"),audienceName:u("create_audience_sync",e,"audienceName"),...e.frequency!==void 0?{frequency:e.frequency}:{}},s);break}case"update_audience_sync":{let s=e.companyId,i=u("update_audience_sync",e,"syncId");n=await a("PATCH",`/api/v1/audience-syncs/${encodeURIComponent(i)}`,{...e.frequency!==void 0?{frequency:e.frequency}:{},...e.isActive!==void 0?{isActive:e.isActive}:{}},s);break}case"delete_audience_sync":{let s=e.companyId,i=u("delete_audience_sync",e,"syncId");n=await a("DELETE",`/api/v1/audience-syncs/${encodeURIComponent(i)}`,void 0,s);break}case"sync_audience_now":{let s=e.companyId,i=u("sync_audience_now",e,"syncId");n=await a("POST",`/api/v1/audience-syncs/${encodeURIComponent(i)}/sync`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function wr(t,e){let n;switch(t){case"list_templates":{let s=e.companyId,i=new URLSearchParams,r=l(e,"label");if(r)i.set("label",r);if(typeof e.isTemplate==="boolean")i.set("isTemplate",String(e.isTemplate));let o=P("list_templates",e,"limit",1,100);if(o!==void 0)i.set("limit",String(o));let d=P("list_templates",e,"offset",0,1e6);if(d!==void 0)i.set("offset",String(d));n=await a("GET",`/api/v1/templates${i.size>0?`?${i}`:""}`,void 0,s);break}case"get_template":{let s=e.companyId;n=await a("GET",`/api/v1/templates/${e.templateId}`,void 0,s);break}case"create_template":{let s=e.companyId;as(e);let i=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="companyId"));n=await a("POST","/api/v1/templates",i,s);break}case"update_template":{let s=e.companyId,i=new Set(["companyId","templateId","name","subject","previewText","html","blocks","labels","isTemplate"]),r=Object.keys(e).filter((o)=>!i.has(o));if(r.length>0)throw Error(`\`update_template\` accepts only \`name\`, \`subject\`, \`previewText\`, \`html\`, \`blocks\`, \`labels\`, and \`isTemplate\` update fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);if(z("update_template",e),X("update_template",e),e.name===void 0&&e.subject===void 0&&e.previewText===void 0&&e.html===void 0&&e.blocks===void 0&&e.labels===void 0&&e.isTemplate===void 0)throw Error("Provide at least one of `name`, `subject`, `previewText`, `html`, `blocks`, `labels`, or `isTemplate` when calling `update_template`.");n=await a("PUT",`/api/v1/templates/${e.templateId}`,e,s);break}case"set_template_localization":{let s=e.companyId,i=u("set_template_localization",e,"templateId"),r=u("set_template_localization",e,"locale"),o=u("set_template_localization",e,"subject"),d=new Set(["companyId","templateId","locale","subject","previewText","html","blocks"]),c=Object.keys(e).filter((g)=>!d.has(g));if(c.length>0)throw Error(`\`set_template_localization\` received unsupported field${c.length===1?"":"s"}: ${c.map((g)=>`\`${g}\``).join(", ")}.`);z("set_template_localization",e,{requireContent:!0});let m={subject:o};if(e.previewText!==void 0)m.previewText=e.previewText;if(e.html!==void 0)m.html=e.html;if(e.blocks!==void 0)m.blocks=e.blocks;n=await a("PUT",`/api/v1/templates/${encodeURIComponent(i)}/localizations/${encodeURIComponent(r)}`,m,s);break}case"sync_template_localizations":{let s=e.companyId,i=u("sync_template_localizations",e,"templateId"),r=new Set(["companyId","templateId","locales"]),o=Object.keys(e).filter((c)=>!r.has(c));if(o.length>0)throw Error(`\`sync_template_localizations\` received unsupported field${o.length===1?"":"s"}: ${o.map((c)=>`\`${c}\``).join(", ")}.`);let d;if(e.locales!==void 0){if(!Array.isArray(e.locales)||e.locales.length===0||e.locales.some((c)=>typeof c!=="string"||c.trim().length===0))throw Error("`locales` must contain at least one non-empty locale string when calling `sync_template_localizations`.");d=e.locales.map((c)=>c.trim())}n=await a("POST",`/api/v1/templates/${encodeURIComponent(i)}/localizations/sync`,d===void 0?{}:{locales:d},s);break}case"delete_template":{let s=e.companyId;n=await a("DELETE",`/api/v1/templates/${e.templateId}`,void 0,s);break}case"share_template":{let s=e.companyId,i=u("share_template",e,"templateId");n=await a("POST",`/api/v1/templates/${encodeURIComponent(i)}/share-link`,void 0,s);break}case"unshare_template":{let s=e.companyId,i=u("unshare_template",e,"templateId");n=await a("DELETE",`/api/v1/templates/${encodeURIComponent(i)}/share-link`,void 0,s);break}case"list_ab_tests":{let s=e.companyId,i=new URLSearchParams,r=l(e,"sequenceId");if(r)i.set("sequenceId",r);n=await a("GET",`/api/v1/ab-tests${i.size>0?`?${i}`:""}`,void 0,s);break}case"get_ab_test":{let s=e.companyId;n=await a("GET",`/api/v1/ab-tests/${e.abTestId}`,void 0,s);break}case"get_ab_test_stats":{let s=e.companyId,i=new URLSearchParams,r=l(e,"period"),o=l(e,"start"),d=l(e,"end");if(r)i.set("period",r);if(o)i.set("start",o);if(d)i.set("end",d);if(e.includeMachineEngagement===!0)i.set("includeMachineEngagement","true");n=await a("GET",`/api/v1/ab-tests/${e.abTestId}/stats${i.size>0?`?${i}`:""}`,void 0,s);break}case"restart_ab_test":{let s=e.companyId,i=new Set(["companyId","abTestId","sourceVariantId","testType","winnerThreshold","variantCount"]),r=Object.keys(e).filter((m)=>!i.has(m));if(r.length>0)throw Error(`\`restart_ab_test\` accepts only \`sourceVariantId\`, \`testType\`, \`winnerThreshold\`, and \`variantCount\` option fields. Unsupported field${r.length===1?"":"s"}: ${r.map((m)=>`\`${m}\``).join(", ")}.`);let o=l(e,"testType");if(o!==void 0&&o!=="subject"&&o!=="content")throw Error("`restart_ab_test` testType must be `subject` or `content`.");let d=e.winnerThreshold===void 0?void 0:Number(e.winnerThreshold);if(d!==void 0&&(!Number.isInteger(d)||d<10||d>1000))throw Error("`restart_ab_test` winnerThreshold must be an integer from 10 to 1000.");let c=e.variantCount===void 0?void 0:Number(e.variantCount);if(c!==void 0&&(!Number.isInteger(c)||c<2||c>4))throw Error("`restart_ab_test` variantCount must be an integer from 2 to 4.");n=await a("POST",`/api/v1/ab-tests/${e.abTestId}/restart`,{sourceVariantId:l(e,"sourceVariantId"),testType:o,winnerThreshold:d,variantCount:c},s);break}case"select_ab_test_winner":{let s=e.companyId,i=u("select_ab_test_winner",e,"abTestId"),r=u("select_ab_test_winner",e,"variantId");n=await a("POST",`/api/v1/ab-tests/${i}/select-winner`,{variantId:r},s);break}case"update_ab_test_variant":{let s=e.companyId,i=new Set(["companyId","abTestId","variantId","subject","previewText","html","blocks","confirmLiveChange"]),r=Object.keys(e).filter((o)=>!i.has(o));if(r.length>0)throw Error(`\`update_ab_test_variant\` accepts only \`subject\`, \`previewText\`, \`html\`, \`blocks\`, and \`confirmLiveChange\` fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);if(z("update_ab_test_variant",e),e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test_variant`.");if(e.subject===void 0&&e.previewText===void 0&&e.html===void 0&&e.blocks===void 0)throw Error("Provide at least one of `subject`, `previewText`, `html`, or `blocks` when calling `update_ab_test_variant`.");n=await a("PATCH",`/api/v1/ab-tests/${e.abTestId}/variants/${e.variantId}`,e,s);break}case"update_ab_test":{let s=e.companyId,i=u("update_ab_test",e,"abTestId"),r=new Set(["companyId","abTestId","name","testPercentage","testDurationMinutes","winnerCriteria","testType","winnerThreshold","confirmLiveChange"]),o=Object.keys(e).filter((_)=>!r.has(_));if(o.length>0)throw Error(`\`update_ab_test\` received unsupported field${o.length===1?"":"s"}: ${o.map((_)=>`\`${_}\``).join(", ")}.`);if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `update_ab_test`.");let d=l(e,"name"),c=P("update_ab_test",e,"testPercentage",5,50),m=P("update_ab_test",e,"testDurationMinutes",15,1440),g=S("update_ab_test",e,"winnerCriteria",["open_rate","click_rate"]),w=S("update_ab_test",e,"testType",["subject","content"]),f=P("update_ab_test",e,"winnerThreshold",10,1000);if(d===void 0&&c===void 0&&m===void 0&&g===void 0&&w===void 0&&f===void 0)throw Error("Provide at least one of `name`, `testPercentage`, `testDurationMinutes`, `winnerCriteria`, `testType`, or `winnerThreshold` when calling `update_ab_test`.");n=await a("PATCH",`/api/v1/ab-tests/${encodeURIComponent(i)}`,{...d!==void 0&&{name:d},...c!==void 0&&{testPercentage:c},...m!==void 0&&{testDurationMinutes:m},...g!==void 0&&{winnerCriteria:g},...w!==void 0&&{testType:w},...f!==void 0&&{winnerThreshold:f},...e.confirmLiveChange===!0&&{confirmLiveChange:!0}},s);break}case"create_ab_test":{let s=e.companyId,i=l(e,"campaignId"),r=l(e,"automationNodeId");if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `create_ab_test`.");if(Boolean(i)===Boolean(r))throw Error("Provide exactly one of `campaignId` or `automationNodeId` when calling `create_ab_test`.");let o=l(e,"name"),d=P("create_ab_test",e,"testPercentage",5,50),c=P("create_ab_test",e,"testDurationMinutes",15,1440),m=S("create_ab_test",e,"winnerCriteria",["open_rate","click_rate"]),g=S("create_ab_test",e,"testType",["subject","content"]),w=P("create_ab_test",e,"winnerThreshold",10,1000);if(e.variants!==void 0){if(!Array.isArray(e.variants))throw Error("`variants` must be an array when calling `create_ab_test`.");e.variants.forEach((_,T)=>{if(!I(_)||typeof _.subject!=="string"||_.subject.trim()==="")throw Error(`\`variants\` item ${T+1} must include a non-empty \`subject\` when calling \`create_ab_test\`.`);if(_.blocks!==void 0&&!Array.isArray(_.blocks))throw Error(`\`variants\` item ${T+1} \`blocks\` must be an array when calling \`create_ab_test\`.`)})}let f=Array.isArray(e.variants)?e.variants:void 0;if(r!==void 0&&(!f||f.length<1))throw Error("`variants` must include at least one competing variant when calling `create_ab_test` with `automationNodeId`.");if(f&&f.length>4)throw Error("`variants` supports at most four extra variants when calling `create_ab_test`.");n=await a("POST","/api/v1/ab-tests",{...i!==void 0&&{campaignId:i},...r!==void 0&&{automationNodeId:r},...e.confirmLiveChange===!0&&{confirmLiveChange:!0},...o!==void 0&&{name:o},...d!==void 0&&{testPercentage:d},...c!==void 0&&{testDurationMinutes:c},...m!==void 0&&{winnerCriteria:m},...g!==void 0&&{testType:g},...w!==void 0&&{winnerThreshold:w},...e.variants!==void 0&&{variants:e.variants}},s);break}case"add_ab_test_variant":{let s=e.companyId,i=u("add_ab_test_variant",e,"abTestId"),r=u("add_ab_test_variant",e,"subject"),o=l(e,"previewText");if(e.blocks!==void 0&&!Array.isArray(e.blocks))throw Error("`blocks` must be an array when calling `add_ab_test_variant`.");if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `add_ab_test_variant`.");n=await a("POST",`/api/v1/ab-tests/${encodeURIComponent(i)}/variants`,{subject:r,...o!==void 0&&{previewText:o},...e.blocks!==void 0&&{blocks:e.blocks},...e.confirmLiveChange===!0&&{confirmLiveChange:!0}},s);break}case"delete_ab_test_variant":{let s=e.companyId,i=u("delete_ab_test_variant",e,"abTestId"),r=u("delete_ab_test_variant",e,"variantId");if(e.confirmLiveChange!==void 0&&typeof e.confirmLiveChange!=="boolean")throw Error("`confirmLiveChange` must be a boolean when calling `delete_ab_test_variant`.");n=await a("DELETE",`/api/v1/ab-tests/${encodeURIComponent(i)}/variants/${encodeURIComponent(r)}${e.confirmLiveChange===!0?"?confirmLiveChange=true":""}`,void 0,s);break}case"delete_ab_test":{let s=e.companyId,i=u("delete_ab_test",e,"abTestId");n=await a("DELETE",`/api/v1/ab-tests/${encodeURIComponent(i)}`,void 0,s);break}case"list_campaigns":{let s=e.companyId,i=new URLSearchParams;if(e.status)i.set("status",String(e.status));let r=l(e,"label");if(r)i.set("label",r);for(let o of["limit","offset"])if(e[o]!==void 0)i.set(o,String(e[o]));n=await a("GET",`/api/v1/campaigns?${i}`,void 0,s);break}case"get_campaign":{let s=e.companyId;n=await a("GET",`/api/v1/campaigns/${e.campaignId}`,void 0,s);break}case"get_campaign_audience":{let s=e.companyId;n=await a("GET",`/api/v1/campaigns/${encodeURIComponent(String(e.campaignId))}/audience`,void 0,s);break}case"get_email_send":{let s=e.companyId;n=await a("GET",`/api/v1/email-sends/${encodeURIComponent(String(e.emailSendId))}`,void 0,s);break}case"list_email_sends":{let s=e.companyId,i=new URLSearchParams,r=["search","subject","recipient","campaignId","transactionalEmailId","automationId","automationNodeId"];for(let C of r){let D=l(e,C);if(D)i.set(C,D)}let o=S("list_email_sends",e,"status",["pending","sent","delivered","opened","clicked","bounced","complained","failed","suppressed"]),d=S("list_email_sends",e,"emailType",["campaign","transactional","sequence"]),c=S("list_email_sends",e,"bounceType",["Permanent","Transient"]),m=S("list_email_sends",e,"sortField",["recipientEmail","subject","status","eventAt","sentAt","createdAt"]),g=S("list_email_sends",e,"sortOrder",["asc","desc"]),w=P("list_email_sends",e,"days",1,14),f=P("list_email_sends",e,"page",1,Number.MAX_SAFE_INTEGER),_=P("list_email_sends",e,"limit",1,100),T=[["status",o],["emailType",d],["bounceType",c],["sortField",m],["sortOrder",g],["days",w],["page",f],["limit",_]];for(let[C,D]of T)if(D!==void 0)i.set(C,String(D));let E=i.toString();n=await a("GET",`/api/v1/email-sends${E?`?${E}`:""}`,void 0,s);break}case"create_campaign":{let s=e.companyId;os(e),re("create_campaign",e);let i=Object.fromEntries(Object.entries(e).filter(([r])=>r!=="companyId"));n=await a("POST","/api/v1/campaigns",i,s);break}case"update_campaign":{let s=e.companyId,i=new Set(["companyId","campaignId","name","subject","trackingCode","html","blocks","emailPreset","fromEmail","fromName","senderProfileId","replyTo","replyToName","replyProfileId","ccEmails","bccEmails","campaignData","computedLists","targetLists","segmentId","listIds","labels","sendTimeOptimization","sendTimeWindowHours"]),r=Object.keys(e).filter((o)=>!i.has(o));if(r.length>0)throw Error(`\`update_campaign\` accepts only content, sending identity, campaign data, computed list, audience, label, and delivery pacing update fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);if(z("update_campaign",e),X("update_campaign",e),un("update_campaign",e),mn("update_campaign",e),re("update_campaign",e,{replyFirst:!0}),[e.segmentId,e.listIds,e.targetLists].filter((o)=>o!==void 0).length>1)throw Error("Provide at most one of `segmentId`, `listIds`, or `targetLists` when calling `update_campaign`.");if(e.name===void 0&&e.subject===void 0&&e.trackingCode===void 0&&e.html===void 0&&e.blocks===void 0&&e.emailPreset===void 0&&e.fromEmail===void 0&&e.senderProfileId===void 0&&e.replyTo===void 0&&e.replyProfileId===void 0&&e.ccEmails===void 0&&e.bccEmails===void 0&&e.campaignData===void 0&&e.computedLists===void 0&&e.targetLists===void 0&&e.segmentId===void 0&&e.listIds===void 0&&e.labels===void 0&&e.sendTimeOptimization===void 0&&e.sendTimeWindowHours===void 0)throw Error("Provide at least one campaign content, sending identity, campaign data, computed list, audience, label, or delivery pacing field when calling `update_campaign`.");n=await a("PUT",`/api/v1/campaigns/${e.campaignId}`,e,s);break}case"schedule_campaign":{let s=e.companyId,i=new Set(["companyId","campaignId","scheduledAt","targetLists","listIds","sendTimeOptimization","sendTimeWindowHours","spreadOverHours","sendInRecipientTimezone","scheduledTimezone","recurringInterval"]),r=Object.keys(e).filter((o)=>!i.has(o));if(r.length>0)throw Error(`\`schedule_campaign\` accepts only \`campaignId\`, \`scheduledAt\`, \`targetLists\`, \`listIds\`, \`sendTimeOptimization\`, \`sendTimeWindowHours\`, \`spreadOverHours\`, \`sendInRecipientTimezone\`, \`scheduledTimezone\`, and \`recurringInterval\`. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);ds(e),n=await a("POST",`/api/v1/campaigns/${e.campaignId}/schedule`,{scheduledAt:e.scheduledAt,...e.targetLists!==void 0&&{targetLists:e.targetLists},...e.listIds!==void 0&&{listIds:e.listIds},...e.sendTimeOptimization!==void 0&&{sendTimeOptimization:e.sendTimeOptimization},...e.sendTimeWindowHours!==void 0&&{sendTimeWindowHours:e.sendTimeWindowHours},...e.spreadOverHours!==void 0&&{spreadOverHours:e.spreadOverHours},...e.sendInRecipientTimezone!==void 0&&{sendInRecipientTimezone:e.sendInRecipientTimezone},...e.scheduledTimezone!==void 0&&{scheduledTimezone:e.scheduledTimezone},...e.recurringInterval!==void 0&&{recurringInterval:e.recurringInterval}},s);break}case"send_test_email":{let s=e.companyId;n=await a("POST",`/api/v1/campaigns/${e.campaignId}/test`,{to:e.to},s);break}case"cancel_campaign":{let s=e.companyId,i=u("cancel_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/cancel`,void 0,s);break}case"share_campaign":{let s=e.companyId,i=u("share_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/share-link`,void 0,s);break}case"unshare_campaign":{let s=e.companyId,i=u("unshare_campaign",e,"campaignId");n=await a("DELETE",`/api/v1/campaigns/${encodeURIComponent(i)}/share-link`,void 0,s);break}case"unschedule_campaign":{let s=e.companyId,i=u("unschedule_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/unschedule`,void 0,s);break}case"pause_campaign":{let s=e.companyId,i=u("pause_campaign",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/pause`,void 0,s);break}case"resume_campaign":{let s=e.companyId,i=u("resume_campaign",e,"campaignId"),r=P("resume_campaign",e,"spreadOverHours",1,72);n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/resume`,{...r!==void 0&&{spreadOverHours:r}},s);break}case"delete_campaign":{let s=e.companyId,i=u("delete_campaign",e,"campaignId");n=await a("DELETE",`/api/v1/campaigns/${encodeURIComponent(i)}`,void 0,s);break}case"duplicate_campaign":{let s=e.companyId,i=u("duplicate_campaign",e,"campaignId"),r=S("duplicate_campaign",e,"mode",["campaign","ab_test","variant"]),o=l(e,"variantId");if(r==="variant"&&o===void 0)throw Error("`variantId` is required when calling `duplicate_campaign` with mode `variant`.");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/duplicate`,{...r!==void 0&&{mode:r},...o!==void 0&&{variantId:o}},s);break}case"resend_campaign_to_non_openers":{let s=e.companyId,i=u("resend_campaign_to_non_openers",e,"campaignId");n=await a("POST",`/api/v1/campaigns/${encodeURIComponent(i)}/resend-to-non-openers`,void 0,s);break}case"list_campaign_goals":{let s=e.companyId,i=u(t,e,"campaignId");n=await a("GET",`/api/v1/campaigns/${encodeURIComponent(i)}/goals`,void 0,s);break}case"create_campaign_goal":case"update_campaign_goal":{let s=e.companyId,i=u(t,e,"campaignId");if(t==="create_campaign_goal")u(t,e,"name"),Hi(e);else Wi(e);let r=t==="update_campaign_goal"?u(t,e,"goalId"):void 0,o={...e};delete o.companyId,delete o.campaignId,delete o.goalId,n=await a(t==="create_campaign_goal"?"POST":"PATCH",`/api/v1/campaigns/${encodeURIComponent(i)}/goals${r?`/${encodeURIComponent(r)}`:""}`,o,s);break}case"delete_campaign_goal":{let s=e.companyId,i=u(t,e,"campaignId"),r=u(t,e,"goalId");n=await a("DELETE",`/api/v1/campaigns/${encodeURIComponent(i)}/goals/${encodeURIComponent(r)}`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function _r(t,e){if(t!=="get_email_block_schema")return{handled:!1,result:void 0};let n=l(e,"blockType");if(n!==void 0){let r=e.conditionFields===!0?"?conditionFields=true":"";return{handled:!0,result:await a("GET",`/api/v1/email-blocks/${encodeURIComponent(n)}${r}`)}}let s=e.creatableOnly===!0?"/api/v1/email-blocks?creatableOnly=true":"/api/v1/email-blocks";return{handled:!0,result:await a("GET",s)}}function Nn(t,e){let n=e.blocks;if(!Array.isArray(n))throw Error(`\`blocks\` must be an array of block objects when calling \`${t}\`.`);return n}var Ca=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 vr(t,e){if(!Ca.has(t))return{handled:!1,result:void 0};let n=l(e,"companyId");if(t==="list_email_components"){let r=new URLSearchParams,o=l(e,"type");if(o)r.set("type",o);if(e.defaultsOnly===!0)r.set("defaultsOnly","true");return{handled:!0,result:await a("GET",`/api/v1/email-components${r.size>0?`?${r}`:""}`,void 0,n)}}if(t==="get_email_component"){let r=u(t,e,"componentId");return{handled:!0,result:await a("GET",`/api/v1/email-components/${encodeURIComponent(r)}`,void 0,n)}}if(t==="get_default_email_component"){let r=u(t,e,"slot");return{handled:!0,result:await a("GET",`/api/v1/email-components/defaults/${encodeURIComponent(r)}`,void 0,n)}}if(t==="set_default_email_component"){let r=u(t,e,"slot"),d={blocks:Nn(t,e)},c=l(e,"name"),m=l(e,"description");if(c!==void 0)d.name=c;if(m!==void 0)d.description=m;return{handled:!0,result:await a("PUT",`/api/v1/email-components/defaults/${encodeURIComponent(r)}`,d,n)}}if(t==="create_email_component"){let r={name:u(t,e,"name"),blocks:Nn(t,e)},o=l(e,"description"),d=l(e,"componentType");if(o!==void 0)r.description=o;if(d!==void 0)r.componentType=d;return{handled:!0,result:await a("POST","/api/v1/email-components",r,n)}}if(t==="update_email_component"){let r=u(t,e,"componentId"),o={},d=l(e,"name"),c=l(e,"description"),m=l(e,"componentType");if(d!==void 0)o.name=d;if(c!==void 0)o.description=c;if(m!==void 0)o.componentType=m;if(e.blocks!==void 0)o.blocks=Nn(t,e);return{handled:!0,result:await a("PATCH",`/api/v1/email-components/${encodeURIComponent(r)}`,o,n)}}let s=u(t,e,"componentId");return{handled:!0,result:await a("DELETE",`/api/v1/email-components/${encodeURIComponent(s)}`,void 0,n)}}async function Ir(t,e){if(t!=="get_event_schema")return{handled:!1,result:void 0};let n=new URLSearchParams,s=l(e,"eventName");if(s)n.set("eventName",s);let i=l(e,"provider");if(i)n.set("provider",i);let r=n.toString();return{handled:!0,result:await a("GET",`/api/v1/events/schemas${r?`?${r}`:""}`,void 0,l(e,"companyId"))}}async function kr(t,e){let n;switch(t){case"list_forms":{let s=e.companyId;n=await a("GET","/api/v1/forms",void 0,s);break}case"create_form":{let s=e.companyId,i=u("create_form",e,"name"),r=Array.isArray(e.listIds)?e.listIds.filter((c)=>typeof c==="string").map((c)=>c.trim()).filter(Boolean):[];if(r.length===0)throw Error("`listIds` must contain at least one list ID when calling `create_form`.");let o=S("create_form",e,"duplicateStrategy",["skip","merge","overwrite"]),d={name:i,listIds:r};for(let c of["tagIds","buttonText","headline","description","successMessage","redirectUrl","showFirstName","showLastName","theme"])if(e[c]!==void 0)d[c]=e[c];if(o!==void 0)d.duplicateStrategy=o;n=await a("POST","/api/v1/forms",d,s);break}case"update_form":{let s=e.companyId,i=u("update_form",e,"formId"),r=S("update_form",e,"duplicateStrategy",["skip","merge","overwrite"]),o={};for(let d of["name","listIds","tagIds","buttonText","headline","description","successMessage","redirectUrl","theme","blocks"])if(e[d]!==void 0)o[d]=e[d];if(r!==void 0)o.duplicateStrategy=r;if(Object.keys(o).length===0)throw Error("Provide at least one field to change when calling `update_form`.");n=await a("PATCH",`/api/v1/forms/${encodeURIComponent(i)}`,o,s);break}case"get_form_embed":{let s=e.companyId,i=u("get_form_embed",e,"formId");n=await a("GET",`/api/v1/forms/embed/${encodeURIComponent(i)}`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function bt(t,e,n,s,i){let r=t[e];if(r===void 0)return;if(typeof r!=="number"||!Number.isFinite(r)||r<n||r>s||i&&!Number.isInteger(r))throw Error(`\`${e}\` must be a ${i?"integer":"number"} between ${n} and ${s} when calling \`upload_image_asset\`.`);return r}async function Sr(t,e){if(t!=="upload_image_asset")return{handled:!1,result:void 0};let n=l(e,"filePath"),s=l(e,"imageBase64");if(n===void 0===(s===void 0))throw Error("Provide either `filePath` or `imageBase64` (not both) when calling `upload_image_asset`.");let i=l(e,"filename");if(s!==void 0&&i===void 0)throw Error("`filename` is required with `imageBase64` when calling `upload_image_asset`.");let r=bt(e,"sourceWidth",1,20000,!0),o=bt(e,"sourceHeight",1,20000,!0);if(r===void 0!==(o===void 0))throw Error("Provide both `sourceWidth` and `sourceHeight` when calling `upload_image_asset`.");let d=bt(e,"displayWidthPercent",1,100,!1)??100,c=bt(e,"cropHeight",1,2000,!0),m=l(e,"objectFit");if(m!==void 0&&m!=="cover"&&m!=="contain")throw Error("`objectFit` must be 'cover' or 'contain' when calling `upload_image_asset`.");if(m!==void 0&&c===void 0)throw Error("`objectFit` can only be used with `cropHeight` when calling `upload_image_asset`.");let g=l(e,"align");if(g!==void 0&&!["left","center","right"].includes(g))throw Error("`align` must be 'left', 'center', or 'right' when calling `upload_image_asset`.");let w=typeof e.altText==="string"?e.altText.trim():void 0;if(w!==void 0&&w.length>500)throw Error("`altText` must be 500 characters or fewer when calling `upload_image_asset`.");let f=await Ps({companyId:l(e,"companyId"),filePath:n,imageBase64:s,filename:i,contentType:l(e,"contentType"),altText:w,sourceWidth:r,sourceHeight:o}),_={type:"image",src:f.url,alt:f.altText??"",width:d,widthType:"percent",...c!==void 0&&{height:c,objectFit:m??"cover"},...g!==void 0&&{align:g}};return{handled:!0,result:{success:!0,asset:f,imageBlock:_,message:"Insert imageBlock into the target email's blocks array with its create or update tool."}}}function Tr(t,e,n){if(t===void 0)return;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`\`${e}\` must be an object when calling \`${n}\`.`);let s={};for(let[i,r]of Object.entries(t)){if(!i.trim()||typeof r!=="string"||!r.trim())throw Error(`\`${e}\` must map non-empty Sequenzy list IDs to non-empty Attio list IDs or slugs when calling \`${n}\`.`);s[i]=r}return s}async function qr(t,e){let n=e.companyId,s;switch(t){case"connect_integration":{let i=u("connect_integration",e,"provider");if(i!=="attio")u("connect_integration",e,"webhookSecret");if(i==="attio")u("connect_integration",e,"apiKey");let r=typeof e.webhookSecret==="string"?e.webhookSecret:void 0,o=e.settings!==void 0&&typeof e.settings==="object"&&e.settings!==null&&!Array.isArray(e.settings)?e.settings:void 0,d=Tr(o?.listMap,"settings.listMap","connect_integration");s=await a("POST","/api/v1/integrations/connect",{provider:i,...r?{webhookSecret:r}:{},...typeof e.apiKey==="string"&&e.apiKey?{apiKey:e.apiKey}:{},...typeof e.providerAccountId==="string"&&e.providerAccountId?{providerAccountId:e.providerAccountId}:{},...o?{settings:{...typeof o.syncAllEvents==="boolean"?{syncAllEvents:o.syncAllEvents}:{},...Array.isArray(o.eventAllowlist)?{eventAllowlist:o.eventAllowlist.filter((c)=>typeof c==="string")}:{},...d!==void 0?{listMap:d}:{},...typeof o.syncCompanyFromDomain==="boolean"?{syncCompanyFromDomain:o.syncCompanyFromDomain}:{}}}:{},...e.historyImport!==void 0?{historyImport:e.historyImport}:{}},n);break}case"get_integration":{let i=u("get_integration",e,"integrationId");s=await a("GET",`/api/v1/integrations/${encodeURIComponent(i)}`,void 0,n);break}case"list_integration_capabilities":{let i=new URLSearchParams;if(typeof e.provider==="string"&&e.provider)i.set("provider",e.provider);if(typeof e.category==="string"&&e.category)i.set("category",e.category);let r=i.toString();s=await a("GET",`/api/v1/integrations/catalog${r?`?${r}`:""}`,void 0,n);break}case"list_integration_activity":{let i=new URLSearchParams;if(typeof e.integrationId==="string"&&e.integrationId)i.set("integrationId",e.integrationId);if(typeof e.provider==="string"&&e.provider)i.set("provider",e.provider);if(typeof e.status==="string"&&e.status)i.set("status",e.status);if(typeof e.limit==="number")i.set("limit",String(e.limit));let r=i.toString();s=await a("GET",`/api/v1/integrations/activity${r?`?${r}`:""}`,void 0,n);break}case"set_integration_sync_enabled":{let i=u("set_integration_sync_enabled",e,"integrationId");if(typeof e.syncEnabled!=="boolean")throw Error("`syncEnabled` must be a boolean when calling `set_integration_sync_enabled`.");s=await a("PATCH",`/api/v1/integrations/${encodeURIComponent(i)}`,{syncEnabled:e.syncEnabled},n);break}case"set_integration_list_targeting":{let i=u("set_integration_list_targeting",e,"integrationId");if(e.listIds===void 0)throw Error("`listIds` is required when calling `set_integration_list_targeting`. Pass an array of list IDs, `[]` to join no list, or null to fall back to the workspace default lists.");if(e.listIds!==null&&!Array.isArray(e.listIds))throw Error("`listIds` must be an array of list IDs, or null to fall back to the workspace default lists.");s=await a("PATCH",`/api/v1/integrations/${encodeURIComponent(i)}`,{listIds:e.listIds},n);break}case"get_integration_pixel":{let i=u("get_integration_pixel",e,"integrationId");s=await a("GET",`/api/v1/integrations/${encodeURIComponent(i)}/pixel`,void 0,n);break}case"activate_integration_pixel":{let i=u("activate_integration_pixel",e,"integrationId");s=await a("POST",`/api/v1/integrations/${encodeURIComponent(i)}/pixel`,void 0,n);break}case"sync_integration":{let i=u("sync_integration",e,"integrationId");s=await a("POST",`/api/v1/integrations/${encodeURIComponent(i)}/sync`,void 0,n);break}case"get_attio_mapping":{let i=u("get_attio_mapping",e,"integrationId");s=await a("GET",`/api/v1/integrations/${encodeURIComponent(i)}/attio`,void 0,n);break}case"update_attio_settings":{let i=u("update_attio_settings",e,"integrationId"),r=Tr(e.listMap,"listMap","update_attio_settings");if(r===void 0&&typeof e.syncCompanyFromDomain!=="boolean")throw Error("Provide at least one of `listMap` or `syncCompanyFromDomain` when calling `update_attio_settings`.");s=await a("PATCH",`/api/v1/integrations/${encodeURIComponent(i)}/attio`,{...r!==void 0?{listMap:r}:{},...typeof e.syncCompanyFromDomain==="boolean"?{syncCompanyFromDomain:e.syncCompanyFromDomain}:{}},n);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:s}}async function Pr(t,e){let n;switch(t){case"list_landing_pages":{let s=e.companyId;n=await a("GET","/api/v1/landing-pages",void 0,s);break}case"get_landing_page":{let s=e.companyId;n=await a("GET",`/api/v1/landing-pages/${e.landingPageId}`,void 0,s);break}case"get_landing_page_stats":{let s=e.companyId,i=new URLSearchParams;if(typeof e.period==="string")i.set("period",e.period);if(typeof e.start==="string")i.set("start",e.start);if(typeof e.end==="string")i.set("end",e.end);if(e.includeBots===!0)i.set("includeBots","true");let r=i.toString();n=await a("GET",`/api/v1/landing-pages/${e.landingPageId}/stats${r?`?${r}`:""}`,void 0,s);break}case"render_landing_page":{let s=e.companyId;n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/render`,void 0,s);break}case"create_landing_page":{let s=e.companyId,i=new Set(["companyId","name","slug","template","content"]),r=Object.keys(e).filter((o)=>!i.has(o));if(r.length>0)throw Error(`\`create_landing_page\` accepts only \`name\`, \`slug\`, \`template\`, and \`content\` fields. Unsupported field${r.length===1?"":"s"}: ${r.map((o)=>`\`${o}\``).join(", ")}.`);n=await a("POST","/api/v1/landing-pages",{...e.name!==void 0&&{name:e.name},...e.slug!==void 0&&{slug:e.slug},...e.template!==void 0&&{template:e.template},...e.content!==void 0&&{content:e.content}},s);break}case"update_landing_page":{let s=e.companyId,i=lt("update_landing_page",e,{requireUpdate:!0});n=await a("PUT",`/api/v1/landing-pages/${e.landingPageId}`,i,s);break}case"publish_landing_page":{let s=e.companyId,i=lt("publish_landing_page",e,{requireUpdate:!1});n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/publish`,i,s);break}case"unpublish_landing_page":{let s=e.companyId,i=lt("unpublish_landing_page",e,{requireUpdate:!1});n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/unpublish`,i,s);break}case"duplicate_landing_page":{let s=e.companyId;n=await a("POST",`/api/v1/landing-pages/${e.landingPageId}/duplicate`,{...e.name!==void 0&&{name:e.name},...e.slug!==void 0&&{slug:e.slug}},s);break}case"delete_landing_page":{let s=e.companyId;n=await a("DELETE",`/api/v1/landing-pages/${e.landingPageId}`,void 0,s);break}case"connect_landing_page_domain":{let{companyId:s,landingPageId:i}=e;n=await a("POST",i?`/api/v1/landing-pages/${encodeURIComponent(i)}/domain`:"/api/v1/landing-pages/domain",{domain:e.domain},s);break}case"update_landing_page_domain_settings":{let s=e.companyId,i=cs(e),r=e.landingPageId;if(!r){n=await a("PUT","/api/v1/landing-pages/domain",i,s);break}let o=`/api/v1/landing-pages/${encodeURIComponent(r)}/domain`;if(e.domain!==void 0)n=await a("POST",o,{domain:e.domain},s);if(e.verify===!0)n=await a("POST",`${o}/verify`,void 0,s);break}case"remove_landing_page_domain":{let{companyId:s,landingPageId:i}=e;n=await a("DELETE",`/api/v1/landing-pages/${encodeURIComponent(i)}/domain`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}var Er=["listIds","tagIds","headline","description","buttonText","successMessage","redirectUrl","presentation","placement","trigger","targeting","schedule","frequency","visual","theme","blocks"];async function Cr(t,e){let n;switch(t){case"list_popups":{let s=e.companyId,i=e.includeContent===!0;n=await a("GET",i?"/api/v1/popups?includeContent=true":"/api/v1/popups",void 0,s);break}case"get_popup":{let s=e.companyId,i=u("get_popup",e,"popupId");n=await a("GET",`/api/v1/popups/${encodeURIComponent(i)}`,void 0,s);break}case"create_popup":{let s=e.companyId,i=u("create_popup",e,"name"),r=S("create_popup",e,"duplicateStrategy",["skip","merge","overwrite"]),o=S("create_popup",e,"status",["draft","published"]),d=e.template,c={name:i};for(let m of Er)if(e[m]!==void 0)c[m]=e[m];if(r!==void 0)c.duplicateStrategy=r;if(o!==void 0)c.status=o;if(d!==void 0)c.template=d;n=await a("POST","/api/v1/popups",c,s);break}case"update_popup":{let s=e.companyId,i=u("update_popup",e,"popupId"),r=S("update_popup",e,"duplicateStrategy",["skip","merge","overwrite"]),o=S("update_popup",e,"status",["draft","published"]),d={};if(e.name!==void 0)d.name=e.name;for(let c of Er)if(e[c]!==void 0)d[c]=e[c];if(r!==void 0)d.duplicateStrategy=r;if(o!==void 0)d.status=o;if(Object.keys(d).length===0)throw Error("Provide at least one field to change when calling `update_popup`.");n=await a("PATCH",`/api/v1/popups/${encodeURIComponent(i)}`,d,s);break}case"get_popup_embed":{let s=e.companyId,i=u("get_popup_embed",e,"popupId");n=await a("GET",`/api/v1/popups/embed/${encodeURIComponent(i)}`,void 0,s);break}case"duplicate_popup":{let s=e.companyId,i=u("duplicate_popup",e,"popupId"),r={};if(e.name!==void 0)r.name=e.name;n=await a("POST",`/api/v1/popups/${encodeURIComponent(i)}/duplicate`,r,s);break}case"delete_popup":{let s=e.companyId,i=u("delete_popup",e,"popupId");n=await a("DELETE",`/api/v1/popups/${encodeURIComponent(i)}`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function xr(t,e){let n;switch(t){case"list_products":{let s=e.companyId,i=new URLSearchParams;if(typeof e.provider==="string"&&e.provider.trim())i.set("provider",e.provider.trim());if(typeof e.search==="string"&&e.search.trim())i.set("search",e.search.trim());let r=P("list_products",e,"limit",1,100);if(r!==void 0)i.set("limit",String(r));let o=P("list_products",e,"offset",0,Number.MAX_SAFE_INTEGER);if(o!==void 0)i.set("offset",String(o));let d=i.size>0?`?${i.toString()}`:"";n=await a("GET",`/api/v1/products${d}`,void 0,s);break}case"upsert_products":{let s=e.companyId;if(!Array.isArray(e.products)||e.products.length===0)throw Error("`products` must be a non-empty array when calling `upsert_products`.");n=await a("POST","/api/v1/products",{products:e.products},s);break}case"delete_product":{let s=e.companyId,i=u("delete_product",e,"productId");n=await a("DELETE",`/api/v1/products/${encodeURIComponent(i)}`,void 0,s);break}case"attach_product_file":{let s=e.companyId,i=u("attach_product_file",e,"productId"),r=l(e,"url"),o=l(e,"filePath");if(r===void 0===(o===void 0))throw Error("Provide either `url` or `filePath` (not both) when calling `attach_product_file`.");let d;if(o!==void 0){let c=await vs(o,s);d={url:c.url,source:"upload",fileName:l(e,"fileName")??c.fileName,fileSizeBytes:c.fileSizeBytes,mimeType:c.mimeType}}else{d={url:r};let c=l(e,"fileName");if(c)d.fileName=c}n=await a("PUT",`/api/v1/products/${encodeURIComponent(i)}/delivery`,d,s);break}case"remove_product_file":{let s=e.companyId,i=u("remove_product_file",e,"productId");n=await a("DELETE",`/api/v1/products/${encodeURIComponent(i)}/delivery`,void 0,s);break}case"sync_products":{let s=e.companyId,i=new URLSearchParams;if(typeof e.integrationId==="string"&&e.integrationId)i.set("integrationId",e.integrationId);let r=i.toString();n=await a("POST",`/api/v1/products/sync${r?`?${r}`:""}`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function xa(t){let e=l(t,"campaignId"),n=l(t,"sequenceId"),s=l(t,"templateId"),i=[e,n,s].filter((r)=>r!==void 0);if(i.length===0)throw Error("render_email requires one of campaignId, sequenceId plus nodeId, or templateId.");if(i.length>1)throw Error("render_email accepts exactly one of campaignId, sequenceId, or templateId.");if(e!==void 0)return`/api/v1/campaigns/${encodeURIComponent(e)}/render`;if(n!==void 0){let r=u("render_email",t,"nodeId");return`/api/v1/sequences/${encodeURIComponent(n)}/nodes/${encodeURIComponent(r)}/render`}return`/api/v1/templates/${encodeURIComponent(s)}/render`}var Ra=["subscriberId","subscriber","variables","locale","variantId","tracking"];async function Rr(t,e){if(t!=="render_email")return{handled:!1,result:void 0};let n=xa(e),s={};for(let r of Ra)if(e[r]!==void 0)s[r]=e[r];return{handled:!0,result:await a("POST",n,s,l(e,"companyId"))}}var Ar=80,Dr=10;function Aa(t){if(!Array.isArray(t.recipients))throw Error("`recipients` must be an array when calling `send_sequence_test_email`.");if(t.recipients.length>Dr)throw Error(`\`recipients\` must include no more than ${Dr} email addresses when calling \`send_sequence_test_email\`.`);if(t.recipients.find((i)=>typeof i!=="string"||i.trim().length===0)!==void 0)throw Error("Every `recipients` item must be a non-empty email address when calling `send_sequence_test_email`.");let n=Array.from(new Set(t.recipients.map((i)=>typeof i==="string"?i.trim().toLowerCase():""))).filter(Boolean);if(n.length===0)throw Error("`recipients` must include at least one email address when calling `send_sequence_test_email`.");let s=n.find((i)=>!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i));if(s)throw Error(`Invalid test recipient email address: \`${s}\`.`);return n}function Da(t){let e=t.trim().replace(/\s+/g," ");if(e.length<=Ar)return e;return`${e.slice(0,Ar-3).trimEnd()}...`}async function Mn(t,e){let n;switch(t){case"generate_sequence":{let s=u("generate_sequence",e,"goal"),i=typeof e.name==="string"&&e.name.trim().length>0?e.name.trim():void 0,o=(await Mn("create_sequence",{...e,goal:s,name:i??Da(s),trigger:"contact_added",durationDays:e.durationDays??14})).result;return{handled:!0,result:typeof o==="object"&&o!==null?{...o,deprecated:!0,deprecationMessage:"generate_sequence is deprecated. Use create_sequence for new integrations."}:o}}case"list_sequences":{let s=e.companyId,i=new URLSearchParams;for(let o of["status","search","limit","offset"])if(e[o]!==void 0)i.set(o,String(e[o]));if(Array.isArray(e.labels)&&e.labels.length>0)i.set("labels",e.labels.join(","));let r=i.size>0?`?${i.toString()}`:"";n=await a("GET",`/api/v1/sequences${r}`,void 0,s);break}case"get_sequence":{let s=e.companyId;n=await a("GET",`/api/v1/sequences/${e.sequenceId}`,void 0,s);break}case"get_sequence_enrollment":{let s=e.companyId,i=u(t,e,"sequenceId"),r=u(t,e,"enrollmentId");n=await a("GET",`/api/v1/sequences/${encodeURIComponent(i)}/enrollments/${encodeURIComponent(r)}`,void 0,s);break}case"simulate_sequence":{let s=e.companyId,i=u(t,e,"sequenceId"),r=l(e,"subscriberId"),o=l(e,"email"),d=P(t,e,"limit",1,25);if(r&&o)throw Error("Pass `subscriberId` or `email`, not both, when calling `simulate_sequence`.");let c=new URLSearchParams;if(r)c.set("subscriberId",r);if(o)c.set("email",o);if(d!==void 0)c.set("limit",String(d));let m=c.size>0?`?${c.toString()}`:"";n=await a("GET",`/api/v1/sequences/${encodeURIComponent(i)}/simulate${m}`,void 0,s);break}case"list_sequence_enrollments":{let s=e.companyId,i=u(t,e,"sequenceId"),r=new URLSearchParams;for(let d of["currentNodeId","status","subscriberId"]){let c=e[d];if(Array.isArray(c)){if(c.length>0)r.set(d,c.join(","))}else if(c!==void 0)r.set(d,String(c))}for(let d of["email","sort","limit","offset","stopConditionMatch"])if(e[d]!==void 0)r.set(d,String(e[d]));let o=r.size>0?`?${r.toString()}`:"";n=await a("GET",`/api/v1/sequences/${encodeURIComponent(i)}/enrollments${o}`,void 0,s);break}case"send_sequence_test_email":{let s=e.companyId,i=u(t,e,"sequenceId"),r=u(t,e,"nodeId"),o=Aa(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(i)}/nodes/${encodeURIComponent(r)}/test`,{recipients:o},s);break}case"create_sequence":{let s=e.companyId;X("create_sequence",e),ln("create_sequence",e,{defaultTrigger:"contact_added"}),re("create_sequence",e,{hasEmailSteps:!0});let i=Array.isArray(e.steps),r=e.goal===void 0&&e.steps===void 0,o=await a("POST","/api/v1/sequences",e,s);if(!o.success){n=o;break}let d=o.sequence.id;if(i||r){let f=await a("GET",`/api/v1/sequences/${d}`,void 0,s);if(f.success)n={...o,success:!0,sequence:f.sequence,message:`Sequence "${f.sequence.name}" created ${r?"as a blank draft":"with explicit steps"}. Review it before enabling.${o.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else n=f;break}let c=7,m=0,g="pending";while(g!=="complete"&&m<c){let f=await a("GET",`/api/v1/sequences/${d}`,void 0,s);if(f.success)g=f.sequence.enrichmentStatus;if(m++,g!=="complete"&&m<c)await new Promise((_)=>setTimeout(_,20000))}let w=await a("GET",`/api/v1/sequences/${d}`,void 0,s);if(w.success)n={...o,success:!0,sequence:w.sequence,message:w.sequence.enrichmentStatus==="complete"?`Sequence "${w.sequence.name}" created with ${w.sequence.emailCount} AI-generated emails. The sequence is ready to review and enable.${o.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`:`Sequence "${w.sequence.name}" created. Email enrichment is still in progress (${w.sequence.enrichedCount}/${w.sequence.emailCount} emails generated). You can check status with get_sequence.${o.eventTrackingCode?" Add the custom event feed using eventTrackingCode and eventTracking before enabling.":""}`};else n=w;break}case"update_sequence":{let s=e.companyId,i=$i(e);n=await a("PUT",`/api/v1/sequences/${e.sequenceId}`,i,s);break}case"update_sequence_node":{let s=e.companyId,i=u("update_sequence_node",e,"sequenceId"),r=Xi(e);n=await a("PUT",`/api/v1/sequences/${i}`,r,s);break}case"update_sequence_nodes":{let s=e.companyId,i=u("update_sequence_nodes",e,"sequenceId"),r=es(e);n=await a("PUT",`/api/v1/sequences/${i}`,r,s);break}case"edit_sequence_graph":{let s=e.companyId,i=ts(e);n=await a("PUT",`/api/v1/sequences/${e.sequenceId}`,i,s);break}case"insert_sequence_step":{let s=e.companyId,i=ns(e),r=await a("PUT",`/api/v1/sequences/${e.sequenceId}`,i,s);if(typeof r==="object"&&r!==null){let o=r,d=o.sequence;if(typeof d==="object"&&d!==null){let c=d;n={...o,...c.insertedNodeIds!==void 0?{insertedNodeIds:c.insertedNodeIds}:{},...c.insertedEmailIds!==void 0?{insertedEmailIds:c.insertedEmailIds}:{},...c.insertedEmailCount!==void 0?{insertedEmailCount:c.insertedEmailCount}:{},...c.addedBranchNodeId!==void 0?{addedBranchNodeId:c.addedBranchNodeId}:{},...c.addedBranchPathNodeIds!==void 0?{addedBranchPathNodeIds:c.addedBranchPathNodeIds}:{}};break}}n=r;break}case"enable_sequence":{let s=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/enable`,void 0,s);break}case"disable_sequence":{let s=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/disable`,void 0,s);break}case"duplicate_sequence":{let s=e.companyId,i=u("duplicate_sequence",e,"sequenceId"),r=l(e,"name");n=await a("POST",`/api/v1/sequences/${encodeURIComponent(i)}/duplicate`,r===void 0?void 0:{name:r},s);break}case"archive_sequence":case"unarchive_sequence":{let s=e.companyId,i=u(t,e,"sequenceId"),r=t==="archive_sequence"?"archive":"unarchive";n=await a("POST",`/api/v1/sequences/${encodeURIComponent(i)}/${r}`,void 0,s);break}case"list_sequence_goals":{let s=e.companyId,i=u(t,e,"sequenceId");n=await a("GET",`/api/v1/sequences/${encodeURIComponent(i)}/goals`,void 0,s);break}case"create_sequence_goal":case"update_sequence_goal":{let s=e.companyId,i=u(t,e,"sequenceId");if(t==="create_sequence_goal")u(t,e,"name"),zi(e);else Bi(e);let r=t==="update_sequence_goal"?u(t,e,"goalId"):void 0,o={...e};delete o.companyId,delete o.sequenceId,delete o.goalId,n=await a(t==="create_sequence_goal"?"POST":"PATCH",`/api/v1/sequences/${encodeURIComponent(i)}/goals${r?`/${encodeURIComponent(r)}`:""}`,o,s);break}case"delete_sequence_goal":{let s=e.companyId,i=u(t,e,"sequenceId"),r=u(t,e,"goalId");n=await a("DELETE",`/api/v1/sequences/${encodeURIComponent(i)}/goals/${encodeURIComponent(r)}`,void 0,s);break}case"get_sequence_inbound_webhook":case"configure_sequence_inbound_webhook":case"rotate_sequence_inbound_webhook_secret":{let s=e.companyId,i=u(t,e,"sequenceId");if(e.clearFieldMapping===!0&&e.fieldMapping!==void 0)throw Error("Provide either `fieldMapping` or `clearFieldMapping`, not both.");if(e.clearSamplePayload===!0&&e.samplePayload!==void 0)throw Error("Provide either `samplePayload` or `clearSamplePayload`, not both.");let r=t==="configure_sequence_inbound_webhook",o=t==="rotate_sequence_inbound_webhook_secret",d=r?{...e.clearFieldMapping===!0?{fieldMapping:null}:e.fieldMapping!==void 0?{fieldMapping:e.fieldMapping}:{},...e.clearSamplePayload===!0?{samplePayload:null}:e.samplePayload!==void 0?{samplePayload:e.samplePayload}:{}}:void 0;n=await a(o?"POST":r?"PUT":"GET",`/api/v1/sequences/${encodeURIComponent(i)}/inbound-webhook${o?"/rotate-secret":""}`,d,s);break}case"pause_sequence_enrollments":{let s=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/pause-enrollments`,void 0,s);break}case"resume_sequence_enrollments":{let s=e.companyId;n=await a("POST",`/api/v1/sequences/${e.sequenceId}/resume-enrollments`,void 0,s);break}case"enroll_subscribers_in_sequence":{let s=e.companyId,i=u("enroll_subscribers_in_sequence",e,"sequenceId"),r=fs(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(i)}/enroll`,r,s);break}case"cancel_sequence_enrollments":{let s=e.companyId,i=ss(e);n=await a("POST",`/api/v1/sequences/${e.sequenceId}/enrollments/cancel`,i,s);break}case"move_sequence_enrollments":{let s=e.companyId,i=u("move_sequence_enrollments",e,"sequenceId"),r=rs(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(i)}/enrollments/move`,r,s);break}case"realign_sequence_enrollments":{let s=e.companyId,i=u("realign_sequence_enrollments",e,"sequenceId"),r=is(e);n=await a("POST",`/api/v1/sequences/${encodeURIComponent(i)}/enrollments/realign-sending-window`,r,s);break}case"get_sequence_enrollment_realignment":{let s=e.companyId,i=u(t,e,"sequenceId"),r=u(t,e,"jobId");n=await a("GET",`/api/v1/sequences/${encodeURIComponent(i)}/enrollments/realign-sending-window/jobs/${encodeURIComponent(r)}`,void 0,s);break}case"delete_sequence":{let s=e.companyId;n=await a("DELETE",`/api/v1/sequences/${e.sequenceId}`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function wt(t,e,n){let s=e[n];if(s===void 0)return;if(!Array.isArray(s))throw Error(`\`${n}\` must be an array of strings when calling \`${t}\`.`);let i=s.filter((r)=>typeof r==="string").map((r)=>r.trim()).filter((r)=>r.length>0);if(i.length!==s.length)throw Error(`\`${n}\` must contain only non-empty strings when calling \`${t}\`.`);return i}function Oa(t,e){let n=wt(t,e,"tags");if(n===void 0||n.length===0)throw Error(`\`tags\` must contain at least one tag when calling \`${t}\`.`);let s=wt(t,e,"emails"),i=wt(t,e,"externalIds"),r=wt(t,e,"subscriberIds");if((s?.length??0)+(i?.length??0)+(r?.length??0)===0)throw Error(`Provide \`emails\`, \`externalIds\`, or \`subscriberIds\` when calling \`${t}\`.`);return{tags:n,...s?.length?{emails:s}:{},...i?.length?{externalIds:i}:{},...r?.length?{subscriberIds:r}:{},...t==="bulk_add_subscriber_tags"&&typeof e.triggerAutomations==="boolean"?{triggerAutomations:e.triggerAutomations}:{}}}async function Or(t,e){let n;switch(t){case"add_subscriber":{let s=e.companyId,i=typeof e.phone==="string"&&e.phone.trim()!==""?e.phone.trim():void 0,r=i?kn(e):V("add_subscriber",e),o=S("add_subscriber",e,"status",["active","unsubscribed","bounced"]),d=S("add_subscriber",e,"optInMode",["default","confirmed","double_opt_in"]);if(e.enrollInSequences!==void 0&&typeof e.enrollInSequences!=="boolean")throw Error("`enrollInSequences` must be a boolean when calling `add_subscriber`.");let c=In("add_subscriber",e);if(n=await a("POST","/api/v1/subscribers",{...r,...i!==void 0&&{phone:i},...typeof e.phoneCountry==="string"&&e.phoneCountry.trim()!==""&&{phoneCountry:e.phoneCountry.trim()},...typeof e.smsConsent==="boolean"&&{smsConsent:e.smsConsent},...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...typeof e.timezone==="string"&&{timezone:e.timezone.trim()||null},...c!==void 0&&{customAttributes:c.value},tags:e.tags,lists:e.listIds,...o!==void 0&&{status:o},...d!==void 0&&{optInMode:d},...typeof e.enrollInSequences==="boolean"&&{enrollInSequences:e.enrollInSequences},...e.createdAt!==void 0&&{createdAt:e.createdAt}},s),o!==void 0&&I(n)&&I(n.subscriber)&&n.subscriber.skipped===!0&&n.subscriber.status!==o)throw Error(`Existing subscriber was not changed to status '${o}'. Use update_subscriber to change an existing contact's status.`);break}case"create_subscriber_import":{let s=e.companyId;if(!Array.isArray(e.subscribers)||e.subscribers.length===0)throw Error("`subscribers` must be a non-empty array when calling `create_subscriber_import`.");if(e.subscribers.length>5000)throw Error("`create_subscriber_import` accepts at most 5000 subscriber records per call.");for(let o=0;o<e.subscribers.length;o+=1){let d=e.subscribers[o],c=I(d)&&typeof d.email==="string"&&d.email.trim()!=="",m=I(d)&&typeof d.phone==="string"&&d.phone.trim()!=="";if(!c&&!m)throw Error(`Subscriber record ${o} must include an email or a phone number.`)}let i=S("create_subscriber_import",e,"duplicateStrategy",["skip","merge","overwrite"]),r=S("create_subscriber_import",e,"optInMode",["default","confirmed","double_opt_in"]);n=await a("POST","/api/v1/subscribers/imports",{subscribers:e.subscribers,...i!==void 0&&{duplicateStrategy:i},...e.fileName!==void 0&&{fileName:e.fileName},...e.listIds!==void 0&&{listIds:e.listIds},...e.enrollInSequences!==void 0&&{enrollInSequences:e.enrollInSequences},...e.defaultPhoneCountry!==void 0&&{defaultPhoneCountry:e.defaultPhoneCountry},...e.smsConsent!==void 0&&{smsConsent:e.smsConsent},...r!==void 0&&{optInMode:r},...e.idempotencyKey!==void 0&&{idempotencyKey:e.idempotencyKey}},s);break}case"get_subscriber_import":{let s=e.companyId,i=u("get_subscriber_import",e,"importId");n=await a("GET",`/api/v1/subscribers/imports/${encodeURIComponent(i)}`,void 0,s);break}case"update_subscriber":{let s=e.companyId,i=V("update_subscriber",e),r=S("update_subscriber",e,"status",["active","unsubscribed","bounced"]),o=In("update_subscriber",e),c=o?.source==="attributes"||e.addTags!==void 0||e.removeTags!==void 0?await $e(i,s):null,m=Array.isArray(c?.subscriber.tags)?c.subscriber.tags.filter((T)=>typeof T==="string"):[],g=Array.isArray(e.addTags)?e.addTags.filter((T)=>typeof T==="string"&&T.trim()!=="").map(vn):[],w=new Set(Array.isArray(e.removeTags)?e.removeTags.filter((T)=>typeof T==="string"&&T.trim()!=="").map(vn):[]),f=m.filter((T)=>!w.has(T));for(let T of g)if(!f.includes(T))f.push(T);let _={};if(i.email&&i.externalId)_.externalId=i.externalId;if(e.firstName!==void 0)_.firstName=e.firstName;if(e.lastName!==void 0)_.lastName=e.lastName;if(typeof e.timezone==="string")_.timezone=e.timezone.trim()||null;if(typeof e.phone==="string"||e.phone===null)_.phone=e.phone;if(typeof e.phoneCountry==="string")_.phoneCountry=e.phoneCountry;if(typeof e.smsConsent==="boolean")_.smsConsent=e.smsConsent;if(r!==void 0)_.status=r;if(o!==void 0)_.customAttributes=o.source==="attributes"?{...I(c?.subscriber.customAttributes)?c.subscriber.customAttributes:{},...o.value}:o.value;if(e.addTags||e.removeTags)_.tags=f;n=await a("PATCH",pt(i),_,s);break}case"remove_subscriber":{let s=e.companyId,i=V("remove_subscriber",e),r=pt(i);if(e.hardDelete===!0)n=await a("DELETE",r,void 0,s);else n=await a("PATCH",r,{status:"unsubscribed"},s);break}case"get_subscriber":{let s=e.companyId,i=V("get_subscriber",e);n=await $e(i,s,{includeMachineEngagement:e.includeMachineEngagement===!0});break}case"list_subscriber_notes":{let s=e.companyId,i=V("list_subscriber_notes",e);n=await a("GET",Sn(i),void 0,s);break}case"add_subscriber_note":{let s=e.companyId,i=V("add_subscriber_note",e),r=typeof e.body==="string"?e.body.trim():void 0;if(!r)throw Error("`body` is required when calling `add_subscriber_note`.");if(r.length>5000)throw Error("`body` must be 5000 characters or fewer when calling `add_subscriber_note`.");n=await a("POST",Sn(i),{body:r},s);break}case"delete_subscriber_note":{let s=e.companyId,i=typeof e.noteId==="string"?e.noteId.trim():"";if(!i)throw Error("`noteId` is required when calling `delete_subscriber_note`.");n=await a("DELETE",`/api/v1/subscribers/notes/${encodeURIComponent(i)}`,void 0,s);break}case"trigger_subscriber_event":{let s=e.companyId,i=V("trigger_subscriber_event",e),r=u("trigger_subscriber_event",e,"event");if(e.properties!==void 0&&!I(e.properties))throw Error("`properties` must be an object when calling `trigger_subscriber_event`.");n=await a("POST","/api/v1/subscribers/events",{...i,event:r,...e.properties!==void 0&&{properties:e.properties},...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...e.attributes!==void 0&&{customAttributes:e.attributes},...e.occurredAt!==void 0&&{occurredAt:e.occurredAt},...e.eventId!==void 0&&{eventId:e.eventId}},s);break}case"trigger_subscriber_events":{let s=e.companyId,i=V("trigger_subscriber_events",e);if(!Array.isArray(e.events)||e.events.length===0)throw Error("`events` must be a non-empty array when calling `trigger_subscriber_events`.");if(e.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 r=0;r<e.events.length;r+=1){let o=e.events[r];if(!I(o)||typeof o.name!=="string"||o.name.trim()==="")throw Error(`Event ${r} must include a non-empty \`name\` string.`)}n=await a("POST","/api/v1/subscribers/events/bulk",{...i,events:e.events,...e.firstName!==void 0&&{firstName:e.firstName},...e.lastName!==void 0&&{lastName:e.lastName},...e.attributes!==void 0&&{customAttributes:e.attributes}},s);break}case"import_subscriber_events":{let s=e.companyId;if(!Array.isArray(e.events)||e.events.length===0)throw Error("`events` must be a non-empty array when calling `import_subscriber_events`.");if(e.events.length>25)throw Error("`import_subscriber_events` accepts at most 25 events per call. Split a larger import into several calls.");for(let i=0;i<e.events.length;i+=1){let r=e.events[i];if(!I(r)||typeof r.name!=="string"||r.name.trim()==="")throw Error(`Event ${i} must include a non-empty \`name\` string.`);let o=typeof r.email==="string"&&r.email.trim()!=="",d=typeof r.externalId==="string"&&r.externalId.trim()!=="";if(!o&&!d)throw Error(`Event ${i} must include an \`email\` or an \`externalId\`.`);if(typeof r.eventId!=="string"||r.eventId.trim()==="")throw Error(`Event ${i} must include a non-empty \`eventId\` so retries are safe.`)}n=await a("POST","/api/v1/subscribers/events/imports",{events:e.events},s);break}case"bulk_add_subscriber_tags":case"bulk_remove_subscriber_tags":{let s=e.companyId,i=Oa(t,e);n=await a("POST",`/api/v1/subscribers/bulk/tags/${t==="bulk_add_subscriber_tags"?"add":"remove"}`,i,s);break}case"search_subscribers":{let s=e.companyId;n=await hs(e,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}async function Ur(t,e){if(t==="list_recipient_suppressions"){let c=l(e,"companyId"),m=l(e,"search"),g=P(t,e,"page",1,Number.MAX_SAFE_INTEGER),w=P(t,e,"limit",1,100),f=l(e,"sort"),_=l(e,"order"),T=new URLSearchParams;if(m)T.set("search",m);if(g!==void 0)T.set("page",String(g));if(w!==void 0)T.set("limit",String(w));if(f)T.set("sort",f);if(_)T.set("order",_);let E=`/api/v1/suppressions${T.size>0?`?${T}`:""}`;return{handled:!0,result:await a("GET",E,void 0,c)}}if(t!=="get_recipient_suppression"&&t!=="remove_recipient_suppression")return{handled:!1,result:void 0};let n=l(e,"companyId"),s=u(t,e,"email"),i=l(e,"region"),r=new URLSearchParams;if(i)r.set("region",i);let o=`/api/v1/suppressions/${encodeURIComponent(s)}${r.size>0?`?${r}`:""}`;return{handled:!0,result:await a(t==="get_recipient_suppression"?"GET":"DELETE",o,void 0,n)}}async function jr(t,e){let n;switch(t){case"list_team_members":{let s=e.companyId;n=await a("GET","/api/v1/team",void 0,s);break}case"invite_team_member":{let s=e.companyId,i=u("invite_team_member",e,"email"),r=Fe("invite_team_member",e,"role",["admin","marketer","viewer","restricted"]);if(e.canManageBilling!==void 0&&typeof e.canManageBilling!=="boolean")throw Error("`canManageBilling` must be a boolean when calling `invite_team_member`.");n=await a("POST","/api/v1/team/invitations",{email:i,role:r,...e.canManageBilling!==void 0&&{canManageBilling:e.canManageBilling}},s);break}case"cancel_team_invitation":{let s=e.companyId,i=u("cancel_team_invitation",e,"invitationId");n=await a("DELETE",`/api/v1/team/invitations/${encodeURIComponent(i)}`,void 0,s);break}case"list_conversations":{let s=e.companyId,i=new URLSearchParams,r=S("list_conversations",e,"status",["open","closed","all"]);if(r)i.set("status",r);let o=l(e,"search");if(o)i.set("search",o);if(e.unread!==void 0){if(typeof e.unread!=="boolean")throw Error("`unread` must be a boolean when calling `list_conversations`.");if(e.unread)i.set("unread","true")}if(e.page!==void 0){if(typeof e.page!=="number"||!Number.isInteger(e.page)||e.page<1)throw Error("`page` must be a positive integer when calling `list_conversations`.");i.set("page",String(e.page))}let d=P("list_conversations",e,"limit",1,100);if(d!==void 0)i.set("limit",String(d));n=await a("GET",`/api/v1/conversations${i.size>0?`?${i}`:""}`,void 0,s);break}case"get_conversation":{let s=e.companyId,i=u("get_conversation",e,"conversationId");n=await a("GET",`/api/v1/conversations/${encodeURIComponent(i)}`,void 0,s);break}case"reply_to_conversation":{let s=e.companyId,i=u("reply_to_conversation",e,"conversationId"),r=S("reply_to_conversation",e,"type",["outbound","note"])??"outbound",o=l(e,"subject"),d=l(e,"bodyText"),c=l(e,"bodyHtml");if(r==="outbound"&&d===void 0&&c===void 0)throw Error("Provide `bodyText` or `bodyHtml` when calling `reply_to_conversation` with an outbound message.");n=await a("POST",`/api/v1/conversations/${encodeURIComponent(i)}/messages`,{type:r,...o!==void 0&&{subject:o},...d!==void 0&&{bodyText:d},...c!==void 0&&{bodyHtml:c}},s);break}case"update_conversation_status":{let s=e.companyId,i=u("update_conversation_status",e,"conversationId"),r=Fe("update_conversation_status",e,"status",["open","closed"]);n=await a("POST",`/api/v1/conversations/${encodeURIComponent(i)}/status`,{status:r},s);break}case"mark_conversation_read":{let s=e.companyId,i=u("mark_conversation_read",e,"conversationId");n=await a("POST",`/api/v1/conversations/${encodeURIComponent(i)}/read`,void 0,s);break}case"list_webhooks":{let s=e.companyId;n=await a("GET","/api/v1/webhooks",void 0,s);break}case"create_webhook":{let s=e.companyId,i=u("create_webhook",e,"name"),r=u("create_webhook",e,"url"),o=qn("create_webhook",e);n=await a("POST","/api/v1/webhooks",{name:i,url:r,...o!==void 0&&{events:o}},s);break}case"update_webhook":{let s=e.companyId,i=u("update_webhook",e,"webhookId"),r=l(e,"name"),o=l(e,"url"),d=qn("update_webhook",e),c=S("update_webhook",e,"status",["enabled","disabled"]);if(r===void 0&&o===void 0&&d===void 0&&c===void 0)throw Error("Provide at least one of `name`, `url`, `events`, or `status` when calling `update_webhook`.");n=await a("PATCH",`/api/v1/webhooks/${encodeURIComponent(i)}`,{...r!==void 0&&{name:r},...o!==void 0&&{url:o},...d!==void 0&&{events:d},...c!==void 0&&{status:c}},s);break}case"delete_webhook":{let s=e.companyId,i=u("delete_webhook",e,"webhookId");n=await a("DELETE",`/api/v1/webhooks/${encodeURIComponent(i)}`,void 0,s);break}case"test_webhook":{let s=e.companyId,i=u("test_webhook",e,"webhookId");n=await a("POST",`/api/v1/webhooks/${encodeURIComponent(i)}/test`,void 0,s);break}case"list_webhook_deliveries":{let s=e.companyId,i=u("list_webhook_deliveries",e,"webhookId"),r=P("list_webhook_deliveries",e,"limit",1,100),o=new URLSearchParams;if(r!==void 0)o.set("limit",String(r));n=await a("GET",`/api/v1/webhooks/${encodeURIComponent(i)}/deliveries${o.size>0?`?${o}`:""}`,void 0,s);break}case"replay_webhook_delivery":{let s=e.companyId,i=u("replay_webhook_delivery",e,"webhookId"),r=u("replay_webhook_delivery",e,"deliveryId");n=await a("POST",`/api/v1/webhooks/${encodeURIComponent(i)}/deliveries/${encodeURIComponent(r)}/replay`,void 0,s);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:n}}function Nr(t){if(!Array.isArray(t))return;return t.filter((e)=>typeof e==="string")}async function Mr(t,e){let n=e.companyId,s;switch(t){case"list_web_tracking_keys":{s=await a("GET","/api/v1/web-tracking-keys",void 0,n);break}case"get_web_tracking_key":{let i=u("get_web_tracking_key",e,"id");s=await a("GET",`/api/v1/web-tracking-keys/${encodeURIComponent(i)}`,void 0,n);break}case"create_web_tracking_key":{let i=u("create_web_tracking_key",e,"name"),r=Nr(e.allowedOrigins);s=await a("POST","/api/v1/web-tracking-keys",{name:i,...r?{allowedOrigins:r}:{}},n);break}case"update_web_tracking_key":{let i=u("update_web_tracking_key",e,"id"),r=Nr(e.allowedOrigins);if(typeof e.name!=="string"&&r===void 0&&typeof e.isActive!=="boolean")throw Error("Provide at least one of `name`, `allowedOrigins`, or `isActive` when calling `update_web_tracking_key`.");s=await a("PATCH",`/api/v1/web-tracking-keys/${encodeURIComponent(i)}`,{...typeof e.name==="string"?{name:e.name}:{},...r?{allowedOrigins:r}:{},...typeof e.isActive==="boolean"?{isActive:e.isActive}:{}},n);break}case"delete_web_tracking_key":{let i=u("delete_web_tracking_key",e,"id");s=await a("DELETE",`/api/v1/web-tracking-keys/${encodeURIComponent(i)}`,void 0,n);break}default:return{handled:!1,result:void 0}}return{handled:!0,result:s}}var Lr=[yr,qr,Ir,Or,Ur,xr,br,wr,_r,vr,Rr,kr,Cr,Pr,Sr,Mn,fr,jr,Mr,gr];function _t(t,e){if(e==="standard")return[...t];return t.map(Ti).filter((n)=>n!==null)}var Ua=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 $r(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Ln(t){if(Array.isArray(t))return t.some(Ln);if(!$r(t))return!1;for(let[e,n]of Object.entries(t)){if((e==="html"||e==="htmlContent")&&typeof n==="string"&&n.trim().length>0)return!0;if(Ln(n))return!0}return!1}function Fr(t,e,n){if(!Ua.has(t)||!Ln(e)||!$r(n))return n;let s=Array.isArray(n.warnings)?n.warnings.filter((i)=>typeof i==="string"):[];return{...n,warnings:[...new Set([...s,zt])]}}var vt="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.",ja={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:vt,sortOrder:vt,sort:vt,order:vt,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."}},zr=null;function Na(t){return zr??=new Map(ft.map((e)=>{let n=e.inputSchema.properties;return[e.name,new Set(n&&typeof n==="object"?Object.keys(n):[])]})),zr.get(t)??null}function Hr(t,e,n){let s=n?.properties,i=s?new Set(Object.keys(s)):Na(t);if(!i)return;let r=Object.keys(e??{}).filter((m)=>!i.has(m));if(r.length===0)return;let o=ja[t]??{},d=[...new Set(r.flatMap((m)=>o[m]?[o[m]]:[]))],c=i.size>0?`Supported arguments: ${[...i].map((m)=>`\`${m}\``).join(", ")}.`:`\`${t}\` takes no arguments.`;throw Error([`Unsupported field${r.length===1?"":"s"}: ${r.map((m)=>`\`${m}\``).join(", ")}.`,`\`${t}\` rejects arguments it does not support rather than ignoring them, because ignoring them would return a result that silently does not match the request.`,c,...d].join(" "))}var $n=ft.map(Ds).map(Ri);function Ma(t,e){if(t!=="import_subscriber_events"||e===null||typeof e!=="object")return!1;let n=e;return n.success===!1&&typeof n.total==="number"&&typeof n.recorded==="number"&&typeof n.duplicates==="number"&&typeof n.failed==="number"&&typeof n.subscribers==="number"&&(n.failed>0&&Array.isArray(n.failures)||typeof n.sideEffectFailed==="number"&&n.sideEffectFailed>0&&Array.isArray(n.sideEffectFailures))}async function Br(t,e,n={}){let s=n.profile??"standard";try{let i=_t($n,s).find((c)=>c.name===t);if(!i)throw Error(`Tool is not available on this MCP surface: ${t}`);if(Hr(t,e,i.inputSchema),s==="openai")qi(t,e);let r,o=!1;for(let c of Lr){let m=await c(t,e);if(m.handled){r=m.result,o=!0;break}}if(!o)throw Error(`Unknown tool: ${t}`);let d=Ma(t,r)?null:ps(r);if(d)throw d;if(r=Fr(t,e,r),r=await ks(t,e,r),s==="openai")r=Ye(t,r);return{structuredContent:Os(r),content:[{type:"text",text:JSON.stringify(r,null,2)}]}}catch(i){return{isError:!0,content:[{type:"text",text:ne(i,{includeDetails:s!=="openai"})}]}}}var Fn={ttlMs:60000,cacheScope:"public"};async function Wr(t,e){let n=t.getRequestContext?.();if(!n)return e();try{return await kt(n,e)}finally{await t.onRequestContextUpdated?.(n)}}function zn(t={}){let e=t.profile??"standard",n=_t($n,e),s=new La({name:"sequenzy",version:We.version},{capabilities:{tools:{listChanged:!1},resources:{listChanged:!1}},instructions:["Sequenzy email marketing MCP server: manage subscribers, campaigns, sequences, templates, and delivery stats.",...e==="openai"?["This OpenAI-reviewed surface accepts only ordinary business, contact, marketing, and commerce data. Never provide payment-card data, health or medical data, government identifiers, biometric or genetic data, authentication credentials or secrets, sensitive demographic data, or precise geolocation. Credential-producing operations and raw outbound-webhook delivery tools are intentionally unavailable here; use the Sequenzy dashboard or local CLI for those workflows."]:[],"If you have access to multiple companies, call get_account and then select_company (or pass companyId per call) before other tools.","Sequence A/B step variant bodies are on get_sequence.sequence.emails[].abTest.variants[].blocks when the key has ab_tests:read. get_ab_test is optional for that copy audit; it still returns settings, localization, and stats. Write those bodies with update_ab_test_variant (IDs from the same variants list). If that tool is not in the tool list, enable it on the Sequenzy connector - do not write through update_template or update_sequence_node.",...e==="openai"?["Only call submit_feedback when the user explicitly asks you to send feedback to Sequenzy. Before calling it, tell the user that the message goes to the Sequenzy team. Include no subscriber data, message content, identifiers, credentials, raw tool calls, API responses, errors, or debug payloads."]:["Only call submit_feedback when the user explicitly asks you to send feedback to Sequenzy. Before calling it, tell the user that the message goes to the Sequenzy team. Include only reproduction details and resource IDs needed for that report; never include unrelated subscriber data, message content, credentials, raw API payloads, or debug data."]].join(`
32
+ `),cacheHints:{"tools/list":Fn,"resources/list":Fn,"server/discover":Fn}});return s.server.setRequestHandler("tools/list",async()=>({tools:n})),s.server.setRequestHandler("tools/call",async(i)=>{let{name:r,arguments:o}=i.params;return Wr(t,()=>Br(r,o??{},{profile:e}))}),s.server.setRequestHandler("resources/list",async()=>({resources:Pi})),s.server.setRequestHandler("resources/read",async(i)=>{let{uri:r}=i.params;return Wr(t,()=>Ei(r,{profile:e}))}),s}function Fa(){Jn(),Wn(),$a(()=>zn()),console.error("Sequenzy MCP server running on stdio")}try{Fa()}catch(t){console.error(ne(t)),process.exit(1)}export{a as apiRequest,zn as createSequenzyMcpServer,ie as getSelectedCompanyId,Ae as setSelectedCompanyId,kt as withMcpRequestContext};