Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(lemlist): manage campaigns, leads, contacts, companies and tasks from flows and AI agents (#16459)

Odai Ahmad97a00159b182
diff --git a/bun.lock b/bun.lock
index 50c05910c08..0509c20bdab 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5158,7 +5158,7 @@
},
"packages/pieces/community/lemlist": {
"name": "@activepieces/piece-lemlist",
- "version": "0.1.11",
+ "version": "0.2.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -5167,6 +5167,7 @@
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/lemon-squeezy": {
diff --git a/packages/pieces/community/lemlist/package.json b/packages/pieces/community/lemlist/package.json
index 86e900a49e0..cff56accb58 100644
--- a/packages/pieces/community/lemlist/package.json
+++ b/packages/pieces/community/lemlist/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-lemlist",
- "version": "0.1.11",
+ "version": "0.2.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -11,11 +11,13 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/lemlist/src/i18n/translation.json b/packages/pieces/community/lemlist/src/i18n/translation.json
index 5f9dc29e91e..ffc3fcde7e8 100644
--- a/packages/pieces/community/lemlist/src/i18n/translation.json
+++ b/packages/pieces/community/lemlist/src/i18n/translation.json
@@ -1,5 +1,5 @@
{
- "\n \n 1.Click on your profile picture in the bottom left-hand corner and click on Settings.\n 2.Go to the Integrations tab.\n 3.Click on Generate a new API key.\n 4.Store it securely because you won’t be able to see it again": "\n \n 1.Click on your profile picture in the bottom left-hand corner and click on Settings.\n 2.Go to the Integrations tab.\n 3.Click on Generate a new API key.\n 4.Store it securely because you won’t be able to see it again",
+ "To get your API key:\n\n1. In lemlist, click your profile picture (bottom left) and open **Settings**.\n2. Go to **Integrations**.\n3. Click **Generate** next to API key and copy it. You won't see it again.": "To get your API key:\n\n1. In lemlist, click your profile picture (bottom left) and open **Settings**.\n2. Go to **Integrations**.\n3. Click **Generate** next to API key and copy it. You won't see it again.",
"Mark Lead From One Campaign as Interested": "Mark Lead From One Campaign as Interested",
"Mark Lead From One Campaign as Not Interested": "Mark Lead From One Campaign as Not Interested",
"Mark Lead From All Campaign as Interested": "Mark Lead From All Campaign as Interested",
@@ -13,19 +13,129 @@
"Add Custom Variables on Lead": "Add Custom Variables on Lead",
"Update Lead From Campaign": "Update Lead From Campaign",
"Search Lead": "Search Lead",
+ "Get Team": "Get Team",
+ "List Team Senders": "List Team Senders",
+ "Get Team Credits": "Get Team Credits",
+ "List Campaigns": "List Campaigns",
+ "Get Campaign": "Get Campaign",
+ "Get Campaign Stats": "Get Campaign Stats",
+ "Get Campaign Sequences": "Get Campaign Sequences",
+ "List Campaign Schedules": "List Campaign Schedules",
+ "List Schedules": "List Schedules",
+ "Create Campaign": "Create Campaign",
+ "Update Campaign": "Update Campaign",
+ "Start Campaign": "Start Campaign",
+ "Pause Campaign": "Pause Campaign",
+ "List Campaign Leads": "List Campaign Leads",
+ "Create Lead in Campaign": "Create Lead in Campaign",
+ "Get Lead by Email": "Get Lead by Email",
+ "Update Campaign Lead": "Update Campaign Lead",
+ "Delete Lead from Campaign": "Delete Lead from Campaign",
+ "Unsubscribe Lead from Campaign": "Unsubscribe Lead from Campaign",
+ "Pause Lead in Campaign": "Pause Lead in Campaign",
+ "Pause Lead in All Campaigns": "Pause Lead in All Campaigns",
+ "Resume Lead in Campaign": "Resume Lead in Campaign",
+ "Resume Lead in All Campaigns": "Resume Lead in All Campaigns",
+ "Launch Lead": "Launch Lead",
+ "Mark Lead Interested in Campaign": "Mark Lead Interested in Campaign",
+ "Mark Lead Not Interested in Campaign": "Mark Lead Not Interested in Campaign",
+ "Update Lead Variables": "Update Lead Variables",
+ "Erase Lead Variables": "Erase Lead Variables",
+ "Enrich Lead": "Enrich Lead",
+ "Get Enrichment Result": "Get Enrichment Result",
+ "List Activities": "List Activities",
+ "List Unsubscribes": "List Unsubscribes",
+ "Check Unsubscribe": "Check Unsubscribe",
+ "Add Unsubscribe": "Add Unsubscribe",
+ "Remove from Unsubscribe List": "Remove from Unsubscribe List",
+ "Create or Update Contact": "Create or Update Contact",
+ "Get Contact": "Get Contact",
+ "List Contacts": "List Contacts",
+ "Create Contact Note": "Create Contact Note",
+ "List Contact Notes": "List Contact Notes",
+ "Create or Update Company": "Create or Update Company",
+ "Get Company": "Get Company",
+ "List Companies": "List Companies",
+ "Create Company Note": "Create Company Note",
+ "List Company Notes": "List Company Notes",
+ "Get Contact Messages": "Get Contact Messages",
+ "Send Inbox Email": "Send Inbox Email",
+ "List Inbox Labels": "List Inbox Labels",
+ "Create Inbox Label": "Create Inbox Label",
+ "Create Task": "Create Task",
+ "List Pending Tasks": "List Pending Tasks",
+ "Update Task": "Update Task",
+ "Ignore Tasks": "Ignore Tasks",
+ "List Webhooks": "List Webhooks",
+ "Custom API Call": "Custom API Call",
"Mark a lead in a campaign as interested.": "Mark a lead in a campaign as interested.",
"Mark a lead in a campaign as not interested.": "Mark a lead in a campaign as not interested.",
"Mark a lead as “interested” across all campaigns.": "Mark a lead as “interested” across all campaigns.",
"Mark a lead as “not interested” across all campaigns.": "Mark a lead as “not interested” across all campaigns.",
"Pause a lead’s outreach across all or specific campaigns.": "Pause a lead’s outreach across all or specific campaigns.",
- "Resume a lead’s outreach across all or specific campaigns.": "Resume a lead’s outreach across all or specific campaigns.",
- "Remove a lead from “unsubscribe” list.": "Remove a lead from “unsubscribe” list.",
- "removes a lead from a specific campaign.": "removes a lead from a specific campaign.",
+ "Resume a lead’s outreach across all or specific campaigns. Resumed leads can receive emails right away.": "Resume a lead’s outreach across all or specific campaigns. Resumed leads can receive emails right away.",
+ "Remove a lead from the “unsubscribe” list so lemlist can contact them again. Only do this when the person opted back in.": "Remove a lead from the “unsubscribe” list so lemlist can contact them again. Only do this when the person opted back in.",
+ "Removes a lead from a specific campaign.": "Removes a lead from a specific campaign.",
"Unsubscribe a lead from a campaign.": "Unsubscribe a lead from a campaign.",
- "Adds a lead to a specific campaign with optional enrichment and lead details.": "Adds a lead to a specific campaign with optional enrichment and lead details.",
+ "Adds a lead to a specific campaign with optional enrichment and lead details. Enrichment options use lemlist credits.": "Adds a lead to a specific campaign with optional enrichment and lead details. Enrichment options use lemlist credits.",
"Add new custom variables to a lead.": "Add new custom variables to a lead.",
- "Updates a lead in a specific campaign.": "Updates a lead in a specific campaign.",
+ "Updates a lead in a specific campaign. Empty fields are left unchanged.": "Updates a lead in a specific campaign. Empty fields are left unchanged.",
"Look up a lead by email and campaign.": "Look up a lead by email and campaign.",
+ "Returns the lemlist team of the connected API key, with its users.": "Returns the lemlist team of the connected API key, with its users.",
+ "Lists team members and the campaigns they send from.": "Lists team members and the campaigns they send from.",
+ "Returns the remaining lemlist credits of the team.": "Returns the remaining lemlist credits of the team.",
+ "Lists lemlist campaigns, newest first.": "Lists lemlist campaigns, newest first.",
+ "Returns one lemlist campaign.": "Returns one lemlist campaign.",
+ "Returns performance statistics of a campaign for a date range.": "Returns performance statistics of a campaign for a date range.",
+ "Returns the sequences and steps of a campaign.": "Returns the sequences and steps of a campaign.",
+ "Lists the sending schedules of a campaign.": "Lists the sending schedules of a campaign.",
+ "Lists the sending schedules of the team.": "Lists the sending schedules of the team.",
+ "Creates a draft lemlist campaign. It is not started.": "Creates a draft lemlist campaign. It is not started.",
+ "Updates the name and stop/tracking settings of a campaign.": "Updates the name and stop/tracking settings of a campaign.",
+ "Starts or resumes a campaign. This sends real emails and messages to its leads.": "Starts or resumes a campaign. This sends real emails and messages to its leads.",
+ "Pauses a running campaign.": "Pauses a running campaign.",
+ "Lists the leads of a campaign, optionally by state.": "Lists the leads of a campaign, optionally by state.",
+ "Creates a lead in a campaign. Runs no paid enrichment.": "Creates a lead in a campaign. Runs no paid enrichment.",
+ "Finds the leads of one email across campaigns.": "Finds the leads of one email across campaigns.",
+ "Updates fields of a lead in a campaign.": "Updates fields of a lead in a campaign.",
+ "Deletes a lead from a campaign.": "Deletes a lead from a campaign.",
+ "Unsubscribes a lead from one campaign.": "Unsubscribes a lead from one campaign.",
+ "Pauses a lead in one campaign.": "Pauses a lead in one campaign.",
+ "Pauses a lead in every campaign.": "Pauses a lead in every campaign.",
+ "Resumes a paused lead in one campaign. It can be emailed right away.": "Resumes a paused lead in one campaign. It can be emailed right away.",
+ "Resumes a paused lead in every campaign. It can be emailed right away.": "Resumes a paused lead in every campaign. It can be emailed right away.",
+ "Launches a lead waiting for review. Its campaign can then email it.": "Launches a lead waiting for review. Its campaign can then email it.",
+ "Marks a lead as interested in one campaign.": "Marks a lead as interested in one campaign.",
+ "Marks a lead as not interested in one campaign.": "Marks a lead as not interested in one campaign.",
+ "Updates values of existing custom variables on a lead.": "Updates values of existing custom variables on a lead.",
+ "Erases the values of custom variables on a lead.": "Erases the values of custom variables on a lead.",
+ "Starts a credit-spending enrichment of a lead. Returns an enrichment ID.": "Starts a credit-spending enrichment of a lead. Returns an enrichment ID.",
+ "Returns the result of an enrichment request.": "Returns the result of an enrichment request.",
+ "Lists campaign activities (emails sent, opened, replied, ...).": "Lists campaign activities (emails sent, opened, replied, ...).",
+ "Lists unsubscribed emails and domains.": "Lists unsubscribed emails and domains.",
+ "Checks whether an email or domain is on the unsubscribe list.": "Checks whether an email or domain is on the unsubscribe list.",
+ "Adds an email or domain to the unsubscribe list.": "Adds an email or domain to the unsubscribe list.",
+ "Removes an email or domain from the unsubscribe list. Only when the person opted back in.": "Removes an email or domain from the unsubscribe list. Only when the person opted back in.",
+ "Creates a CRM contact or updates the one with the same email or LinkedIn URL.": "Creates a CRM contact or updates the one with the same email or LinkedIn URL.",
+ "Returns a CRM contact by ID or email.": "Returns a CRM contact by ID or email.",
+ "Lists or searches CRM contacts.": "Lists or searches CRM contacts.",
+ "Adds a note to a CRM contact.": "Adds a note to a CRM contact.",
+ "Lists the notes of a CRM contact.": "Lists the notes of a CRM contact.",
+ "Creates a CRM company or updates the one with the same domain or LinkedIn URL.": "Creates a CRM company or updates the one with the same domain or LinkedIn URL.",
+ "Returns a CRM company by ID.": "Returns a CRM company by ID.",
+ "Lists or searches CRM companies.": "Lists or searches CRM companies.",
+ "Adds a note to a CRM company.": "Adds a note to a CRM company.",
+ "Lists the notes of a CRM company.": "Lists the notes of a CRM company.",
+ "Returns the inbox conversation with a contact.": "Returns the inbox conversation with a contact.",
+ "Sends a real email to a contact from a lemlist mailbox.": "Sends a real email to a contact from a lemlist mailbox.",
+ "Lists the inbox labels of the team.": "Lists the inbox labels of the team.",
+ "Creates an inbox label.": "Creates an inbox label.",
+ "Creates a task for a team member about a contact, company or lead.": "Creates a task for a team member about a contact, company or lead.",
+ "Lists pending tasks of the team.": "Lists pending tasks of the team.",
+ "Updates a task: assignee, due date, title, instructions, priority or done.": "Updates a task: assignee, due date, title, instructions, priority or done.",
+ "Marks tasks as ignored.": "Marks tasks as ignored.",
+ "Lists the webhooks registered on the team.": "Lists the webhooks registered on the team.",
+ "Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Campaign": "Campaign",
"Lead Email": "Lead Email",
"First Name": "First Name",
@@ -44,6 +154,73 @@
"Find Phone": "Find Phone",
"Lead ID": "Lead ID",
"Custom Variables": "Custom Variables",
+ "Campaign State": "Campaign State",
+ "Status": "Status",
+ "Limit": "Limit",
+ "Offset": "Offset",
+ "Campaign ID": "Campaign ID",
+ "Start Date": "Start Date",
+ "End Date": "End Date",
+ "Name": "Name",
+ "Timezone": "Timezone",
+ "Stop on Email Replied": "Stop on Email Replied",
+ "Stop on Meeting Booked": "Stop on Meeting Booked",
+ "Stop on Link Clicked": "Stop on Link Clicked",
+ "Disable Open Tracking": "Disable Open Tracking",
+ "Disable Click Tracking": "Disable Click Tracking",
+ "Disable Reply Tracking": "Disable Reply Tracking",
+ "State": "State",
+ "Lead ID or Email": "Lead ID or Email",
+ "Variables": "Variables",
+ "Variable Names": "Variable Names",
+ "Enrichment ID": "Enrichment ID",
+ "Type": "Type",
+ "Min Date": "Min Date",
+ "Max Date": "Max Date",
+ "Email or Domain": "Email or Domain",
+ "Email": "Email",
+ "Location": "Location",
+ "Update Strategy": "Update Strategy",
+ "Contact ID or Email": "Contact ID or Email",
+ "Search": "Search",
+ "Company ID": "Company ID",
+ "Contact List ID": "Contact List ID",
+ "Note": "Note",
+ "Page": "Page",
+ "Domain": "Domain",
+ "Industry": "Industry",
+ "Size": "Size",
+ "Description": "Description",
+ "Search by Name": "Search by Name",
+ "IDs or Domains": "IDs or Domains",
+ "Contact ID": "Contact ID",
+ "Skip": "Skip",
+ "Sender User ID": "Sender User ID",
+ "Sender Email": "Sender Email",
+ "Sender Mailbox ID": "Sender Mailbox ID",
+ "Subject": "Subject",
+ "Message": "Message",
+ "CC": "CC",
+ "Reply To Activity ID": "Reply To Activity ID",
+ "Label Name": "Label Name",
+ "Record ID": "Record ID",
+ "Assigned To (User ID)": "Assigned To (User ID)",
+ "Due Date": "Due Date",
+ "Title": "Title",
+ "Instructions": "Instructions",
+ "Priority": "Priority",
+ "Task ID": "Task ID",
+ "Done": "Done",
+ "Task IDs": "Task IDs",
+ "Method": "Method",
+ "Headers": "Headers",
+ "Query Parameters": "Query Parameters",
+ "Body Type": "Body Type",
+ "Body": "Body",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
+ "Follow redirects": "Follow redirects",
"Select a campaign": "Select a campaign",
"The email of the lead to mark as interested.": "The email of the lead to mark as interested.",
"The email of the lead to mark as not interested.": "The email of the lead to mark as not interested.",
@@ -54,17 +231,111 @@
"The email of the lead to remove.": "The email of the lead to remove.",
"The email of the lead to unsubscribe.": "The email of the lead to unsubscribe.",
"The email of the lead to add": "The email of the lead to add",
- "Avoid adding the lead if it already exists in any campaign": "Avoid adding the lead if it already exists in any campaign",
- "Run LinkedIn enrichment for this lead": "Run LinkedIn enrichment for this lead",
- "Try to find a verified email for this lead": "Try to find a verified email for this lead",
- "Verify the lead’s email using debounce": "Verify the lead’s email using debounce",
- "Try to find a phone number for this lead": "Try to find a phone number for this lead",
+ "Refuse the lead if the contact is already in another campaign.": "Refuse the lead if the contact is already in another campaign.",
+ "Run LinkedIn enrichment for this lead. Uses lemlist credits.": "Run LinkedIn enrichment for this lead. Uses lemlist credits.",
+ "Try to find a verified email for this lead. Uses lemlist credits.": "Try to find a verified email for this lead. Uses lemlist credits.",
+ "Verify the lead’s email. Uses lemlist credits.": "Verify the lead’s email. Uses lemlist credits.",
+ "Try to find a phone number for this lead. Uses lemlist credits.": "Try to find a phone number for this lead. Uses lemlist credits.",
"The unique identifier of the lead (e.g. lea_8xJSc7sV7ggpiVnXe). Available as the _id field returned by the Add Lead To A Campaign and Search Lead actions.": "The unique identifier of the lead (e.g. lea_8xJSc7sV7ggpiVnXe). Available as the _id field returned by the Add Lead To A Campaign and Search Lead actions.",
"New custom variables to create on the lead. Each key is the variable name and each value is its content. Names must not match an existing default or custom variable.": "New custom variables to create on the lead. Each key is the variable name and each value is its content. Names must not match an existing default or custom variable.",
"The email of the lead to update.": "The email of the lead to update.",
"The email of the lead to look up": "The email of the lead to look up",
+ "Only include campaigns in this state.": "Only include campaigns in this state.",
+ "How many items to return (1-100). Default 100.": "How many items to return (1-100). Default 100.",
+ "How many items to skip, for paging. Default 0.": "How many items to skip, for paging. Default 0.",
+ "lemlist campaign ID (starts with cam_). Use List Campaigns to find it.": "lemlist campaign ID (starts with cam_). Use List Campaigns to find it.",
+ "ISO 8601 date, e.g. 2026-10-01.": "ISO 8601 date, e.g. 2026-10-01.",
+ "ISO 8601 date, e.g. 2026-10-31.": "ISO 8601 date, e.g. 2026-10-31.",
+ "IANA timezone of the schedule, e.g. Europe/Paris.": "IANA timezone of the schedule, e.g. Europe/Paris.",
+ "Lead state filter, e.g. scanned, contacted, interested, notInterested.": "Lead state filter, e.g. scanned, contacted, interested, notInterested.",
+ "How many items to return (1-500). Default 100.": "How many items to return (1-500). Default 100.",
+ "Email address of the lead.": "Email address of the lead.",
+ "Refuse the lead when the contact is already in another campaign.": "Refuse the lead when the contact is already in another campaign.",
+ "The lead ID (lea_...) or the lead email address.": "The lead ID (lea_...) or the lead email address.",
+ "lemlist lead ID (starts with lea_), as returned by Create Lead in Campaign or Get Lead by Email.": "lemlist lead ID (starts with lea_), as returned by Create Lead in Campaign or Get Lead by Email.",
+ "Variable names and their new values.": "Variable names and their new values.",
+ "Names of the variables whose values to erase.": "Names of the variables whose values to erase.",
+ "Exact activity type, e.g. emailsReplied.": "Exact activity type, e.g. emailsReplied.",
+ "ISO 8601 date-time.": "ISO 8601 date-time.",
+ "An email address ([email protected]) or a whole domain (acme.com).": "An email address ([email protected]) or a whole domain (acme.com).",
+ "For an existing record: overwriteIgnoreEmpty (default) replaces stored values with the ones sent, fillEmptyOnly only fills empty fields, overwrite also clears fields sent empty.": "For an existing record: overwriteIgnoreEmpty (default) replaces stored values with the ones sent, fillEmptyOnly only fills empty fields, overwrite also clears fields sent empty.",
+ "Page number, starting at 1.": "Page number, starting at 1.",
+ "Comma-separated company IDs or domains (max 100).": "Comma-separated company IDs or domains (max 100).",
+ "How many items to return (1-100). Default 50.": "How many items to return (1-100). Default 50.",
+ "Messages to skip. Default 0.": "Messages to skip. Default 0.",
+ "usr_... of the sender.": "usr_... of the sender.",
+ "usm_... mailbox ID.": "usm_... mailbox ID.",
+ "Recipient contact (ctc_...). Give this or Lead ID.": "Recipient contact (ctc_...). Give this or Lead ID.",
+ "Recipient lead (lea_...). Give this or Contact ID.": "Recipient lead (lea_...). Give this or Contact ID.",
+ "Required unless replying in a thread.": "Required unless replying in a thread.",
+ "Email body (HTML allowed).": "Email body (HTML allowed).",
+ "Contact (ctc_), company (cpn_) or lead (lea_) ID.": "Contact (ctc_), company (cpn_) or lead (lea_) ID.",
+ "Page number, starting at 0.": "Page number, starting at 0.",
+ "Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
+ "Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "running": "running",
+ "paused": "paused",
+ "draft": "draft",
+ "ended": "ended",
+ "archived": "archived",
+ "errors": "errors",
+ "overwriteIgnoreEmpty": "overwriteIgnoreEmpty",
+ "fillEmptyOnly": "fillEmptyOnly",
+ "overwrite": "overwrite",
+ "manual": "manual",
+ "email": "email",
+ "phone": "phone",
+ "linkedin": "linkedin",
+ "whatsapp": "whatsapp",
+ "None": "None",
+ "Low": "Low",
+ "Medium": "Medium",
+ "High": "High",
+ "GET": "GET",
+ "POST": "POST",
+ "PATCH": "PATCH",
+ "PUT": "PUT",
+ "DELETE": "DELETE",
+ "HEAD": "HEAD",
"New Activity": "New Activity",
"Unsubscribed Recipient": "Unsubscribed Recipient",
- "Triggers for each new activity.": "Triggers for each new activity.",
- "Triggers when a recipient unsubscribes.": "Triggers when a recipient unsubscribes."
+ "Triggers for each new activity, optionally only some event types or one campaign.": "Triggers for each new activity, optionally only some event types or one campaign.",
+ "Triggers when a recipient unsubscribes.": "Triggers when a recipient unsubscribes.",
+ "Event Types": "Event Types",
+ "Only trigger for these events. Leave empty for every event.": "Only trigger for these events. Leave empty for every event.",
+ "contacted": "contacted",
+ "hooked": "hooked",
+ "attracted": "attracted",
+ "warmed": "warmed",
+ "interested": "interested",
+ "notInterested": "notInterested",
+ "emailsSent": "emailsSent",
+ "emailsOpened": "emailsOpened",
+ "emailsClicked": "emailsClicked",
+ "emailsReplied": "emailsReplied",
+ "emailsBounced": "emailsBounced",
+ "emailsFailed": "emailsFailed",
+ "emailsInterested": "emailsInterested",
+ "emailsNotInterested": "emailsNotInterested",
+ "emailsUnsubscribed": "emailsUnsubscribed",
+ "entityUnsubscribed": "entityUnsubscribed",
+ "variableUnsubscribed": "variableUnsubscribed",
+ "linkedinSent": "linkedinSent",
+ "linkedinOpened": "linkedinOpened",
+ "linkedinReplied": "linkedinReplied",
+ "linkedinInterested": "linkedinInterested",
+ "linkedinNotInterested": "linkedinNotInterested",
+ "linkedinInviteDone": "linkedinInviteDone",
+ "linkedinInviteAccepted": "linkedinInviteAccepted",
+ "linkedinVisitDone": "linkedinVisitDone",
+ "whatsappReplied": "whatsappReplied",
+ "smsReplied": "smsReplied",
+ "apiInterested": "apiInterested",
+ "apiNotInterested": "apiNotInterested",
+ "manualInterested": "manualInterested",
+ "manualNotInterested": "manualNotInterested"
}
\ No newline at end of file
diff --git a/packages/pieces/community/lemlist/src/index.ts b/packages/pieces/community/lemlist/src/index.ts
index 8cb23d37322..38dc8fce849 100644
--- a/packages/pieces/community/lemlist/src/index.ts
+++ b/packages/pieces/community/lemlist/src/index.ts
@@ -1,25 +1,85 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
-import { lemlistAuth } from './lib/common/constants';
-import { newActivity } from './lib/triggers/new-activity';
-import { unsubscribedRecipient } from './lib/triggers/unsubscribed-recipient';
-import { markLeadFromOneCampaignAsInterested } from './lib/actions/mark-lead-from-one-campaign-as-interested';
-import { markLeadFromOneCampaignAsNotInterested } from './lib/actions/mark-lead-from-one-campaign-as-not-interested';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { createPiece } from '@activepieces/pieces-framework';
+import { addCustomVariablesOnLead } from './lib/actions/add-custom-variables-on-lead';
+import { addLeadToACampaign } from './lib/actions/add-lead-to-a-campaign';
+import { listActivitiesAction } from './lib/actions/ai/activities';
+import {
+ createCampaignAction,
+ getCampaignAction,
+ getCampaignSequencesAction,
+ getCampaignStatsAction,
+ listCampaignSchedulesAction,
+ listCampaignsAction,
+ listSchedulesAction,
+ pauseCampaignAction,
+ startCampaignAction,
+ updateCampaignAction,
+} from './lib/actions/ai/campaigns';
+import {
+ createCompanyNoteAction,
+ createContactNoteAction,
+ getCompanyAction,
+ getContactAction,
+ listCompaniesAction,
+ listCompanyNotesAction,
+ listContactNotesAction,
+ listContactsAction,
+ upsertCompanyAction,
+ upsertContactAction,
+} from './lib/actions/ai/crm';
+import { enrichLeadAction, getEnrichmentResultAction } from './lib/actions/ai/enrichment';
+import {
+ createLabelAction,
+ getContactMessagesAction,
+ listLabelsAction,
+ sendInboxEmailAction,
+} from './lib/actions/ai/inbox';
+import {
+ createLeadInCampaignAction,
+ deleteLeadFromCampaignAction,
+ eraseLeadVariablesAction,
+ getLeadByEmailAction,
+ launchLeadAction,
+ listCampaignLeadsAction,
+ markLeadInterestedInCampaignAction,
+ markLeadNotInterestedInCampaignAction,
+ pauseLeadEverywhereAction,
+ pauseLeadInCampaignAction,
+ resumeLeadEverywhereAction,
+ resumeLeadInCampaignAction,
+ unsubscribeLeadFromCampaignAction,
+ updateCampaignLeadAction,
+ updateLeadVariablesAction,
+} from './lib/actions/ai/leads';
+import { createTaskAction, ignoreTasksAction, listTasksAction, updateTaskAction } from './lib/actions/ai/tasks';
+import { getTeamAction, getTeamCreditsAction, listTeamSendersAction } from './lib/actions/ai/team';
+import {
+ addUnsubscribeAction,
+ getUnsubscribeAction,
+ listUnsubscribesAction,
+ resubscribeEmailAction,
+} from './lib/actions/ai/unsubscribes';
+import { listWebhooksAction } from './lib/actions/ai/webhooks';
import { markLeadFromAllCampaignAsInterested } from './lib/actions/mark-lead-from-all-campaign-as-interested';
import { markLeadFromAllCampaignsAsNotInterested } from './lib/actions/mark-lead-from-all-campaigns-as-not-interested';
+import { markLeadFromOneCampaignAsInterested } from './lib/actions/mark-lead-from-one-campaign-as-interested';
+import { markLeadFromOneCampaignAsNotInterested } from './lib/actions/mark-lead-from-one-campaign-as-not-interested';
import { pauseLeadFromAllOrSpecificCampaigns } from './lib/actions/pause-lead-from-all-or-specific-campaigns';
-import { resumeLeadFromAllOrSpecificCampaigns } from './lib/actions/resume-lead-from-all-or-specific-campaigns';
-import { removeLeadFromUnsubscribeList } from './lib/actions/remove-lead-from-unsubscribe-list';
import { removeLeadFromACampaign } from './lib/actions/remove-lead-from-a-campaign';
+import { removeLeadFromUnsubscribeList } from './lib/actions/remove-lead-from-unsubscribe-list';
+import { resumeLeadFromAllOrSpecificCampaigns } from './lib/actions/resume-lead-from-all-or-specific-campaigns';
+import { searchLead } from './lib/actions/search-lead';
import { unsubscribeALead } from './lib/actions/unsubscribe-a-lead';
-import { addLeadToACampaign } from './lib/actions/add-lead-to-a-campaign';
-import { addCustomVariablesOnLead } from './lib/actions/add-custom-variables-on-lead';
import { updateLeadFromCampaign } from './lib/actions/update-lead-from-campaign';
-import { searchLead } from './lib/actions/search-lead';
+import { basicAuthHeader, BASE_URL } from './lib/common/client';
+import { lemlistAuth } from './lib/common/constants';
+import { newActivity } from './lib/triggers/new-activity';
+import { unsubscribedRecipient } from './lib/triggers/unsubscribed-recipient';
export const lemlist = createPiece({
displayName: 'Lemlist',
auth: lemlistAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/lemlist.png',
authors: ['gs03-dev'],
actions: [
@@ -36,6 +96,65 @@ export const lemlist = createPiece({
addCustomVariablesOnLead,
updateLeadFromCampaign,
searchLead,
+ getTeamAction,
+ listTeamSendersAction,
+ getTeamCreditsAction,
+ listCampaignsAction,
+ getCampaignAction,
+ getCampaignStatsAction,
+ getCampaignSequencesAction,
+ listCampaignSchedulesAction,
+ listSchedulesAction,
+ createCampaignAction,
+ updateCampaignAction,
+ startCampaignAction,
+ pauseCampaignAction,
+ listCampaignLeadsAction,
+ createLeadInCampaignAction,
+ getLeadByEmailAction,
+ updateCampaignLeadAction,
+ deleteLeadFromCampaignAction,
+ unsubscribeLeadFromCampaignAction,
+ pauseLeadInCampaignAction,
+ pauseLeadEverywhereAction,
+ resumeLeadInCampaignAction,
+ resumeLeadEverywhereAction,
+ launchLeadAction,
+ markLeadInterestedInCampaignAction,
+ markLeadNotInterestedInCampaignAction,
+ updateLeadVariablesAction,
+ eraseLeadVariablesAction,
+ enrichLeadAction,
+ getEnrichmentResultAction,
+ listActivitiesAction,
+ listUnsubscribesAction,
+ getUnsubscribeAction,
+ addUnsubscribeAction,
+ resubscribeEmailAction,
+ upsertContactAction,
+ getContactAction,
+ listContactsAction,
+ createContactNoteAction,
+ listContactNotesAction,
+ upsertCompanyAction,
+ getCompanyAction,
+ listCompaniesAction,
+ createCompanyNoteAction,
+ listCompanyNotesAction,
+ getContactMessagesAction,
+ sendInboxEmailAction,
+ listLabelsAction,
+ createLabelAction,
+ createTaskAction,
+ listTasksAction,
+ updateTaskAction,
+ ignoreTasksAction,
+ listWebhooksAction,
+ createCustomApiCallAction({
+ auth: lemlistAuth,
+ baseUrl: () => BASE_URL,
+ authMapping: async (auth) => ({ Authorization: basicAuthHeader(auth.secret_text) }),
+ }),
],
triggers: [newActivity, unsubscribedRecipient],
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/add-custom-variables-on-lead.ts b/packages/pieces/community/lemlist/src/lib/actions/add-custom-variables-on-lead.ts
index 415e1da12d3..702fc96ca5e 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/add-custom-variables-on-lead.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/add-custom-variables-on-lead.ts
@@ -1,6 +1,8 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const addCustomVariablesOnLead = createAction({
auth: lemlistAuth,
@@ -11,7 +13,7 @@ export const addCustomVariablesOnLead = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Creates new custom variables on a specific lead (identified by its Lemlist lead id) and sets each variable’s value for that lead. Variable names must be new — the call fails if a name matches a default field (email, firstName, lastName, picture, phone, linkedinUrl, companyName, companyDomain, icebreaker) or a previously created custom variable. Use to add extra mail-merge fields beyond the standard ones. Not idempotent: re-running with the same variable names returns an error.',
+ 'Creates new custom variables on one lead (Lemlist lead ID lea_...) and sets their values. Names must be new: the call fails with a conflict if a name matches a default field (email, firstName, lastName, picture, phone, linkedinUrl, companyName, companyDomain, icebreaker) or an existing custom variable; use Update Lead Variables to change existing values. company-prefixed names write to the shared company record. Not idempotent: a second run with the same names fails.',
idempotent: false,
},
props: {
@@ -28,12 +30,13 @@ export const addCustomVariablesOnLead = createAction({
required: true,
}),
},
+ outputSchema: lemlistSchemas.variables,
async run({ auth, propsValue }) {
- const { leadId, customVariables } = propsValue;
-
- return await lemlistApiService.addLeadVariables(auth, {
- leadId,
- variables: customVariables ?? {},
+ return lemlistLeads.writeLeadVariables({
+ apiKey: auth.secret_text,
+ leadId: propsValue.leadId,
+ variables: propsValue.customVariables,
+ method: HttpMethod.POST,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/add-lead-to-a-campaign.ts b/packages/pieces/community/lemlist/src/lib/actions/add-lead-to-a-campaign.ts
index b32e74df849..16184404f65 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/add-lead-to-a-campaign.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/add-lead-to-a-campaign.ts
@@ -1,7 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const addLeadToACampaign = createAction({
auth: lemlistAuth,
@@ -9,9 +10,13 @@ export const addLeadToACampaign = createAction({
classification: 'WRITE',
displayName: 'Add Lead To A Campaign',
description:
- 'Adds a lead to a specific campaign with optional enrichment and lead details.',
- audience: 'both',
- aiMetadata: { description: 'Adds a lead (by email, with optional name, company, phone, LinkedIn and other details) to a specific Lemlist campaign, optionally running enrichment such as email/phone finding, email verification, or LinkedIn lookup. Use to enroll a new contact into outreach. Not idempotent: each call adds the lead and re-runs requested enrichment unless the deduplicate option is enabled to skip leads already present in any campaign.', idempotent: false },
+ 'Adds a lead to a specific campaign with optional enrichment and lead details. Enrichment options use lemlist credits.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Adds a lead (by email, with optional name, company, phone, LinkedIn and other details) to a Lemlist campaign, optionally running credit-spending enrichment. Not idempotent: each call creates a lead unless Deduplicate is on.',
+ idempotent: false,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'] }),
email: Property.ShortText({
@@ -19,85 +24,68 @@ export const addLeadToACampaign = createAction({
description: 'The email of the lead to add',
required: true,
}),
- firstName: Property.ShortText({
- displayName: 'First Name',
- required: false,
- }),
+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),
lastName: Property.ShortText({ displayName: 'Last Name', required: false }),
- picture: Property.ShortText({
- displayName: 'Picture URL',
- required: false,
- }),
+ picture: Property.ShortText({ displayName: 'Picture URL', required: false }),
phone: Property.ShortText({ displayName: 'Phone', required: false }),
- linkedinUrl: Property.ShortText({
- displayName: 'LinkedIn URL',
- required: false,
- }),
- companyName: Property.ShortText({
- displayName: 'Company Name',
- required: false,
- }),
- companyDomain: Property.ShortText({
- displayName: 'Company Domain',
- required: false,
- }),
- icebreaker: Property.LongText({
- displayName: 'Icebreaker',
- required: false,
- }),
+ linkedinUrl: Property.ShortText({ displayName: 'LinkedIn URL', required: false }),
+ companyName: Property.ShortText({ displayName: 'Company Name', required: false }),
+ companyDomain: Property.ShortText({ displayName: 'Company Domain', required: false }),
+ icebreaker: Property.LongText({ displayName: 'Icebreaker', required: false }),
jobTitle: Property.ShortText({ displayName: 'Job Title', required: false }),
deduplicate: Property.Checkbox({
displayName: 'Deduplicate',
- description: 'Avoid adding the lead if it already exists in any campaign',
+ description: 'Refuse the lead if the contact is already in another campaign.',
required: false,
defaultValue: false,
}),
linkedinEnrichment: Property.Checkbox({
displayName: 'LinkedIn Enrichment',
- description: 'Run LinkedIn enrichment for this lead',
+ description: 'Run LinkedIn enrichment for this lead. Uses lemlist credits.',
required: false,
defaultValue: false,
}),
findEmail: Property.Checkbox({
displayName: 'Find Email',
- description: 'Try to find a verified email for this lead',
+ description: 'Try to find a verified email for this lead. Uses lemlist credits.',
required: false,
defaultValue: false,
}),
verifyEmail: Property.Checkbox({
displayName: 'Verify Email',
- description: 'Verify the lead’s email using debounce',
+ description: 'Verify the lead’s email. Uses lemlist credits.',
required: false,
defaultValue: false,
}),
findPhone: Property.Checkbox({
displayName: 'Find Phone',
- description: 'Try to find a phone number for this lead',
+ description: 'Try to find a phone number for this lead. Uses lemlist credits.',
required: false,
defaultValue: false,
}),
},
+ outputSchema: lemlistSchemas.createdLead,
async run({ auth, propsValue }) {
- const {
- campaignId,
- email,
- deduplicate,
- linkedinEnrichment,
- findEmail,
- verifyEmail,
- findPhone,
- ...leadData
- } = propsValue as any;
-
- return await lemlistApiService.addLeadToACampaign(auth, {
- campaignId,
- leadEmail: email,
- leadData,
- deduplicate,
- linkedinEnrichment,
- findEmail,
- verifyEmail,
- findPhone,
+ return lemlistLeads.createLeadInCampaign({
+ apiKey: auth.secret_text,
+ campaignId: propsValue.campaignId,
+ email: propsValue.email,
+ fields: {
+ firstName: propsValue.firstName,
+ lastName: propsValue.lastName,
+ picture: propsValue.picture,
+ phone: propsValue.phone,
+ linkedinUrl: propsValue.linkedinUrl,
+ companyName: propsValue.companyName,
+ companyDomain: propsValue.companyDomain,
+ icebreaker: propsValue.icebreaker,
+ jobTitle: propsValue.jobTitle,
+ },
+ deduplicate: propsValue.deduplicate,
+ linkedinEnrichment: propsValue.linkedinEnrichment,
+ findEmail: propsValue.findEmail,
+ verifyEmail: propsValue.verifyEmail,
+ findPhone: propsValue.findPhone,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/activities.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/activities.ts
new file mode 100644
index 00000000000..0540acd9fb9
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/activities.ts
@@ -0,0 +1,66 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemlistApiCall } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+export const listActivitiesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_activities',
+ classification: 'SEARCH',
+ displayName: 'List Activities',
+ description: 'Lists campaign activities (emails sent, opened, replied, ...).',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists lemlist activities (emails sent/opened/clicked/replied/bounced, LinkedIn steps, interest changes...), newest first. Filters: Type (exact activity type such as emailsReplied), Campaign ID, Lead ID, Min/Max Date (ISO 8601). Limit 1-100 (default 100) and Offset; has_more=true means call again with Offset + Limit. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ type: Property.ShortText({
+ displayName: 'Type',
+ description: 'Exact activity type, e.g. emailsReplied.',
+ required: false,
+ }),
+ campaign_id: aiProps.campaignId(false),
+ lead_id: Property.ShortText({ displayName: 'Lead ID', required: false }),
+ min_date: Property.ShortText({ displayName: 'Min Date', description: 'ISO 8601 date-time.', required: false }),
+ max_date: Property.ShortText({ displayName: 'Max Date', description: 'ISO 8601 date-time.', required: false }),
+ limit: aiProps.limit({ max: 100, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.activityPage,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const campaignId = lemlistInput.optionalText(propsValue.campaign_id);
+ const leadId = lemlistInput.optionalText(propsValue.lead_id);
+ const minDate = lemlistInput.optionalText(propsValue.min_date);
+ const maxDate = lemlistInput.optionalText(propsValue.max_date);
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/activities',
+ query: {
+ version: 'v2',
+ type: lemlistInput.optionalText(propsValue.type),
+ campaignId:
+ campaignId === undefined
+ ? undefined
+ : decodeURIComponent(lemlistInput.idSegment({ value: campaignId, label: 'Campaign ID', prefix: 'cam' })),
+ leadId:
+ leadId === undefined
+ ? undefined
+ : decodeURIComponent(lemlistInput.idSegment({ value: leadId, label: 'Lead ID', prefix: 'lea' })),
+ minDate: minDate === undefined ? undefined : lemlistInput.isoDate({ value: minDate, label: 'Min Date' }),
+ maxDate: maxDate === undefined ? undefined : lemlistInput.isoDate({ value: maxDate, label: 'Max Date' }),
+ limit,
+ offset,
+ },
+ });
+ return lemlistResults.page({ items: lemlistResults.listFrom({ body }), offset, limit });
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/campaigns.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/campaigns.ts
new file mode 100644
index 00000000000..f82f4c26156
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/campaigns.ts
@@ -0,0 +1,326 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isRecord, lemlistApiCall } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { campaignItems } from '../../common/props';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+function campaignPath(value: unknown): string {
+ return `/campaigns/${lemlistInput.idSegment({ value, label: 'Campaign ID', prefix: 'cam' })}`;
+}
+
+export const listCampaignsAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_campaigns',
+ classification: 'SEARCH',
+ displayName: 'List Campaigns',
+ description: 'Lists lemlist campaigns, newest first.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists lemlist campaigns newest first with ID, name, status and errors. Optional status filter (running, draft, paused, ended, archived, errors). Paged: Limit 1-100 (default 100) and Offset; has_more=true means call again with Offset + Limit. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: {
+ disabled: false,
+ options: ['running', 'draft', 'paused', 'ended', 'archived', 'errors'].map((value) => ({
+ label: value,
+ value,
+ })),
+ },
+ }),
+ limit: aiProps.limit({ max: 100, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.campaignPage,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/campaigns',
+ query: {
+ version: 'v2',
+ limit,
+ offset,
+ sortBy: 'createdAt',
+ sortOrder: 'desc',
+ status: propsValue.status ?? undefined,
+ },
+ });
+ return lemlistResults.page({ items: campaignItems(body), offset, limit });
+ },
+});
+
+export const getCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_campaign',
+ classification: 'READ',
+ displayName: 'Get Campaign',
+ description: 'Returns one lemlist campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one lemlist campaign by campaign ID (cam_...): name, status, creator and senders. Read-only.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId() },
+ outputSchema: lemlistSchemas.campaignDetails,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: campaignPath(propsValue.campaign_id),
+ });
+ },
+});
+
+export const getCampaignStatsAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_campaign_stats',
+ classification: 'READ',
+ displayName: 'Get Campaign Stats',
+ description: 'Returns performance statistics of a campaign for a date range.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns counters for one campaign between Start Date and End Date (ISO 8601): leads launched/reached/opened/answered/interested, messages sent/bounced, opens, clicks, replies, meetings and per-step numbers. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ start_date: Property.ShortText({ displayName: 'Start Date', description: 'ISO 8601 date, e.g. 2026-10-01.', required: true }),
+ end_date: Property.ShortText({ displayName: 'End Date', description: 'ISO 8601 date, e.g. 2026-10-31.', required: true }),
+ },
+ outputSchema: lemlistSchemas.campaignStats,
+ async run({ auth, propsValue }) {
+ const startDate = lemlistInput.isoDate({ value: propsValue.start_date, label: 'Start Date' });
+ const endDate = lemlistInput.isoDate({ value: propsValue.end_date, label: 'End Date' });
+ if (Date.parse(startDate) > Date.parse(endDate)) {
+ throw new Error('Start Date must be before End Date.');
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `/v2${campaignPath(propsValue.campaign_id)}/stats`,
+ query: { startDate, endDate },
+ });
+ },
+});
+
+export const getCampaignSequencesAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_campaign_sequences',
+ classification: 'READ',
+ displayName: 'Get Campaign Sequences',
+ description: 'Returns the sequences and steps of a campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns every sequence of one campaign with its steps (step ID, index, type, delay in days, subject, message). Read-only; this piece does not edit sequences.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId() },
+ outputSchema: lemlistSchemas.sequences,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `${campaignPath(propsValue.campaign_id)}/sequences`,
+ });
+ const sequences = Array.isArray(body)
+ ? lemlistResults.records(body)
+ : isRecord(body)
+ ? Object.values(body).filter(isRecord)
+ : [];
+ return { sequences, count: sequences.length };
+ },
+});
+
+export const listCampaignSchedulesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_campaign_schedules',
+ classification: 'SEARCH',
+ displayName: 'List Campaign Schedules',
+ description: 'Lists the sending schedules of a campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the sending schedules attached to one campaign (timezone, start/end time, weekdays, seconds between emails). Read-only.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId() },
+ outputSchema: lemlistSchemas.schedules,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `${campaignPath(propsValue.campaign_id)}/schedules/`,
+ });
+ const items = lemlistResults.listFrom({ body, key: 'schedules' });
+ return { items, count: items.length };
+ },
+});
+
+export const listSchedulesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_schedules',
+ classification: 'SEARCH',
+ displayName: 'List Schedules',
+ description: 'Lists the sending schedules of the team.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the team sending schedules (name, timezone, hours, weekdays), newest first. Limit 1-100 (default 100) and Offset for paging. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ limit: aiProps.limit({ max: 100, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.schedules,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/schedules',
+ query: { limit, offset, sortBy: 'createdAt', sortOrder: 'desc' },
+ });
+ const items = lemlistResults.listFrom({ body, key: 'schedules' });
+ return { items, count: items.length };
+ },
+});
+
+export const createCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'create_campaign',
+ classification: 'WRITE',
+ displayName: 'Create Campaign',
+ description: 'Creates a draft lemlist campaign. It is not started.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new draft lemlist campaign with an empty auto-generated sequence and default schedule. The campaign is never started by this action, so no email is sent. Returns the campaign ID (cam_...). Not idempotent: each run creates another campaign with the same name.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ timezone: Property.ShortText({
+ displayName: 'Timezone',
+ description: 'IANA timezone of the schedule, e.g. Europe/Paris.',
+ required: false,
+ }),
+ },
+ outputSchema: lemlistSchemas.createdCampaign,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/campaigns',
+ body: lemlistInput.compact({
+ name: lemlistInput.requireText({ value: propsValue.name, label: 'Name' }),
+ timezone: propsValue.timezone,
+ }),
+ });
+ },
+});
+
+export const updateCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'update_campaign',
+ classification: 'WRITE',
+ displayName: 'Update Campaign',
+ description: 'Updates the name and stop/tracking settings of a campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates one campaign: name, stop-on-reply / meeting-booked / link-clicked rules and open/click/reply tracking switches. Each switch takes yes, no or unchanged; only the name and switches set to yes/no are sent, everything else keeps its current value. Idempotent.',
+ idempotent: true,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ stopOnEmailReplied: aiProps.triState({ displayName: 'Stop on Email Replied', description: 'Stop the sequence for a lead who replies.' }),
+ stopOnMeetingBooked: aiProps.triState({ displayName: 'Stop on Meeting Booked', description: 'Stop the sequence for a lead who books a meeting.' }),
+ stopOnLinkClicked: aiProps.triState({ displayName: 'Stop on Link Clicked', description: 'Stop the sequence for a lead who clicks a link.' }),
+ disableTrackOpen: aiProps.triState({ displayName: 'Disable Open Tracking', description: 'Turn off email open tracking.' }),
+ disableTrackClick: aiProps.triState({ displayName: 'Disable Click Tracking', description: 'Turn off link click tracking.' }),
+ disableTrackReply: aiProps.triState({ displayName: 'Disable Reply Tracking', description: 'Turn off reply tracking.' }),
+ },
+ outputSchema: lemlistSchemas.updatedCampaign,
+ async run({ auth, propsValue }) {
+ const body = lemlistInput.compact({
+ name: propsValue.name,
+ stopOnEmailReplied: lemlistInput.triState(propsValue.stopOnEmailReplied),
+ stopOnMeetingBooked: lemlistInput.triState(propsValue.stopOnMeetingBooked),
+ stopOnLinkClicked: lemlistInput.triState(propsValue.stopOnLinkClicked),
+ disableTrackOpen: lemlistInput.triState(propsValue.disableTrackOpen),
+ disableTrackClick: lemlistInput.triState(propsValue.disableTrackClick),
+ disableTrackReply: lemlistInput.triState(propsValue.disableTrackReply),
+ });
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one setting to update.');
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.PATCH,
+ resourceUri: campaignPath(propsValue.campaign_id),
+ body,
+ });
+ },
+});
+
+export const startCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'start_campaign',
+ classification: 'WRITE',
+ displayName: 'Start Campaign',
+ description: 'Starts or resumes a campaign. This sends real emails and messages to its leads.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts or resumes one campaign. Running campaigns send real emails, LinkedIn and other messages to their leads on schedule, which cannot be recalled. Only call when the user explicitly asked to launch or resume this campaign. Idempotent: starting a running campaign leaves it running.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId() },
+ outputSchema: lemlistSchemas.campaignState,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `${campaignPath(propsValue.campaign_id)}/start`,
+ });
+ },
+});
+
+export const pauseCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'pause_campaign',
+ classification: 'WRITE',
+ displayName: 'Pause Campaign',
+ description: 'Pauses a running campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Pauses one running campaign so no more messages are sent; leads keep their place and Start Campaign resumes it. Idempotent.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId() },
+ outputSchema: lemlistSchemas.campaignState,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `${campaignPath(propsValue.campaign_id)}/pause`,
+ });
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/crm.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/crm.ts
new file mode 100644
index 00000000000..d996ca073ed
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/crm.ts
@@ -0,0 +1,436 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isLemlistStatus, lemlistApiCall } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+function updateStrategyProp() {
+ return Property.StaticDropdown({
+ displayName: 'Update Strategy',
+ description:
+ 'For an existing record: overwriteIgnoreEmpty (default) replaces stored values with the ones sent, fillEmptyOnly only fills empty fields, overwrite also clears fields sent empty.',
+ required: false,
+ options: {
+ disabled: false,
+ options: ['overwriteIgnoreEmpty', 'fillEmptyOnly', 'overwrite'].map((value) => ({ label: value, value })),
+ },
+ });
+}
+
+function upsertBody({
+ record,
+ keys,
+ identityKeys,
+ updateStrategy,
+}: {
+ record: Record<string, unknown>;
+ keys: readonly string[];
+ identityKeys: readonly string[];
+ updateStrategy: unknown;
+}): Record<string, unknown> {
+ const picked = lemlistInput.pick({ record, keys });
+ const body = lemlistInput.compact(picked);
+ if (updateStrategy === 'overwrite') {
+ for (const [key, value] of Object.entries(picked)) {
+ if (!identityKeys.includes(key) && typeof value === 'string' && value.trim().length === 0) {
+ body[key] = '';
+ }
+ }
+ }
+ return body;
+}
+
+function contactPath(value: unknown): string {
+ return `/contacts/${lemlistInput.contactIdOrEmailSegment({ value, label: 'Contact ID or Email' })}`;
+}
+
+function companyPath(value: unknown): string {
+ return `/companies/${lemlistInput.idSegment({ value, label: 'Company ID', prefix: 'cpn' })}`;
+}
+
+function notesPage({
+ body,
+ page,
+ limit,
+}: {
+ body: unknown;
+ page: number;
+ limit: number;
+}) {
+ const items = lemlistResults.listFrom({ body });
+ const total = lemlistResults.numberField({ body, key: 'total' }) ?? items.length;
+ return { items, total, page, has_more: page * limit < total };
+}
+
+export const upsertContactAction = createAction({
+ auth: lemlistAuth,
+ name: 'upsert_contact',
+ classification: 'WRITE',
+ displayName: 'Create or Update Contact',
+ description: 'Creates a CRM contact or updates the one with the same email or LinkedIn URL.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a lemlist CRM contact, or updates the existing one matched by email or LinkedIn URL (one of them is required). Does not add the contact to any campaign. Returns the contact ID and whether it was created or updated. Idempotent: the same input updates the same contact.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ linkedinUrl: Property.ShortText({ displayName: 'LinkedIn URL', required: false }),
+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last Name', required: false }),
+ jobTitle: Property.ShortText({ displayName: 'Job Title', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ companyDomain: Property.ShortText({ displayName: 'Company Domain', required: false }),
+ location: Property.ShortText({ displayName: 'Location', required: false }),
+ update_strategy: updateStrategyProp(),
+ },
+ outputSchema: lemlistSchemas.upsertResult,
+ async run({ auth, propsValue }) {
+ const { update_strategy } = propsValue;
+ const body = upsertBody({
+ record: propsValue,
+ keys: ['email', 'linkedinUrl', 'firstName', 'lastName', 'jobTitle', 'phone', 'companyDomain', 'location'],
+ identityKeys: ['email', 'linkedinUrl'],
+ updateStrategy: update_strategy,
+ });
+ if (body['email'] === undefined && body['linkedinUrl'] === undefined) {
+ throw new Error('Provide an Email or a LinkedIn URL to identify the contact.');
+ }
+ if (body['email'] !== undefined) {
+ body['email'] = lemlistInput.email({ value: body['email'], label: 'Email' });
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/contacts',
+ query: { updateStrategy: update_strategy ?? undefined },
+ body,
+ });
+ },
+});
+
+export const getContactAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_contact',
+ classification: 'READ',
+ displayName: 'Get Contact',
+ description: 'Returns a CRM contact by ID or email.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one lemlist CRM contact by contact ID or email: fields, campaigns it is in (with lead IDs and states), owner and unsubscribed flag. found=false when no contact matches. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ contact: Property.ShortText({ displayName: 'Contact ID or Email', required: true }),
+ },
+ outputSchema: lemlistSchemas.contactLookup,
+ async run({ auth, propsValue }) {
+ const value = lemlistInput.requireText({ value: propsValue.contact, label: 'Contact ID or Email' });
+ try {
+ if (value.includes('@')) {
+ const matches = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/contacts',
+ query: { idsOrEmails: lemlistInput.email({ value, label: 'Contact ID or Email' }) },
+ });
+ const contact = Array.isArray(matches) && matches.length > 0 ? matches[0] : null;
+ return { found: contact !== null, contact };
+ }
+ const contact = await lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: contactPath(value),
+ });
+ return { found: true, contact };
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 404 })) {
+ return { found: false, contact: null };
+ }
+ throw error;
+ }
+ },
+});
+
+export const listContactsAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_contacts',
+ classification: 'SEARCH',
+ displayName: 'List Contacts',
+ description: 'Lists or searches CRM contacts.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists lemlist CRM contacts, optionally searched by name text (2+ characters) or filtered by company ID (cpn_...) or contact list ID (clt_...). Limit 1-500 (default 100) and Offset; has_more=true means call again with Offset + Limit. Use Get Contact to look up one email. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', required: false }),
+ company_id: Property.ShortText({ displayName: 'Company ID', required: false }),
+ list_id: Property.ShortText({ displayName: 'Contact List ID', required: false }),
+ limit: aiProps.limit({ max: 500, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.contactPage,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 500 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const search = lemlistInput.optionalText(propsValue.search);
+ if (search !== undefined && search.length < 2) {
+ throw new Error('Search must be at least 2 characters.');
+ }
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/contacts',
+ query: {
+ search,
+ companyId: lemlistInput.optionalText(propsValue.company_id),
+ listId: lemlistInput.optionalText(propsValue.list_id),
+ limit,
+ offset,
+ },
+ });
+ return lemlistResults.page({ items: lemlistResults.listFrom({ body }), offset, limit });
+ },
+});
+
+export const createContactNoteAction = createAction({
+ auth: lemlistAuth,
+ name: 'create_contact_note',
+ classification: 'WRITE',
+ displayName: 'Create Contact Note',
+ description: 'Adds a note to a CRM contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Writes a note on one lemlist contact (contact ID or email); it is also pushed to the connected CRM. Not idempotent: each run adds another note.',
+ idempotent: false,
+ },
+ props: {
+ contact: Property.ShortText({ displayName: 'Contact ID or Email', required: true }),
+ note: Property.LongText({ displayName: 'Note', required: true }),
+ },
+ outputSchema: lemlistSchemas.note,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `${contactPath(propsValue.contact)}/notes`,
+ body: { note: lemlistInput.requireText({ value: propsValue.note, label: 'Note' }) },
+ });
+ },
+});
+
+export const listContactNotesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_contact_notes',
+ classification: 'SEARCH',
+ displayName: 'List Contact Notes',
+ description: 'Lists the notes of a CRM contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists notes on one lemlist contact (contact ID or email), newest first. Page starts at 1, Limit 1-100 (default 100); has_more=true means ask for the next Page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ contact: Property.ShortText({ displayName: 'Contact ID or Email', required: true }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false }),
+ limit: aiProps.limit({ max: 100, fallback: 100 }),
+ },
+ outputSchema: lemlistSchemas.notePage,
+ async run({ auth, propsValue }) {
+ const page = lemlistInput.boundedInt({ value: propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `${contactPath(propsValue.contact)}/notes`,
+ query: { page, limit, sortBy: 'createdAt', sortOrder: 'desc' },
+ });
+ return notesPage({ body, page, limit });
+ },
+});
+
+export const upsertCompanyAction = createAction({
+ auth: lemlistAuth,
+ name: 'upsert_company',
+ classification: 'WRITE',
+ displayName: 'Create or Update Company',
+ description: 'Creates a CRM company or updates the one with the same domain or LinkedIn URL.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a lemlist CRM company, or updates the existing one matched by domain or LinkedIn URL (one of them is required). Returns the company ID and whether it was created or updated. Idempotent: the same input updates the same company.',
+ idempotent: true,
+ },
+ props: {
+ domain: Property.ShortText({ displayName: 'Domain', required: false }),
+ linkedinUrl: Property.ShortText({ displayName: 'LinkedIn URL', required: false }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ industry: Property.ShortText({ displayName: 'Industry', required: false }),
+ location: Property.ShortText({ displayName: 'Location', required: false }),
+ size: Property.ShortText({ displayName: 'Size', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ update_strategy: updateStrategyProp(),
+ },
+ outputSchema: lemlistSchemas.upsertResult,
+ async run({ auth, propsValue }) {
+ const { update_strategy } = propsValue;
+ const body = upsertBody({
+ record: propsValue,
+ keys: ['domain', 'linkedinUrl', 'name', 'industry', 'location', 'size', 'description'],
+ identityKeys: ['domain', 'linkedinUrl'],
+ updateStrategy: update_strategy,
+ });
+ if (body['domain'] === undefined && body['linkedinUrl'] === undefined) {
+ throw new Error('Provide a Domain or a LinkedIn URL to identify the company.');
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/companies',
+ query: { updateStrategy: update_strategy ?? undefined },
+ body,
+ });
+ },
+});
+
+export const getCompanyAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_company',
+ classification: 'READ',
+ displayName: 'Get Company',
+ description: 'Returns a CRM company by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one lemlist CRM company by company ID (cpn_...): domain, LinkedIn URL, fields and owner. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ company_id: Property.ShortText({ displayName: 'Company ID', required: true }),
+ },
+ outputSchema: lemlistSchemas.company,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: companyPath(propsValue.company_id),
+ });
+ },
+});
+
+export const listCompaniesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_companies',
+ classification: 'SEARCH',
+ displayName: 'List Companies',
+ description: 'Lists or searches CRM companies.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists lemlist CRM companies, optionally searched by name or fetched by comma-separated IDs/domains. Limit 1-500 (default 100) and Offset; has_more=true means call again with Offset + Limit. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search by Name', required: false }),
+ ids_or_domains: Property.ShortText({
+ displayName: 'IDs or Domains',
+ description: 'Comma-separated company IDs or domains (max 100).',
+ required: false,
+ }),
+ limit: aiProps.limit({ max: 500, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.companyPage,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 500 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const idsOrDomains = lemlistInput.optionalText(propsValue.ids_or_domains);
+ const ids =
+ idsOrDomains === undefined
+ ? undefined
+ : lemlistInput.stringList({ value: idsOrDomains, label: 'IDs or Domains' });
+ if (ids !== undefined && ids.length > 100) {
+ throw new Error('IDs or Domains accepts at most 100 values.');
+ }
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/companies',
+ query: {
+ search: lemlistInput.optionalText(propsValue.search),
+ idsOrDomains: ids?.join(','),
+ limit,
+ offset,
+ },
+ });
+ const items = lemlistResults.listFrom({ body });
+ return ids === undefined
+ ? lemlistResults.page({ items, offset, limit })
+ : { items, count: items.length, offset: 0, has_more: false };
+ },
+});
+
+export const createCompanyNoteAction = createAction({
+ auth: lemlistAuth,
+ name: 'create_company_note',
+ classification: 'WRITE',
+ displayName: 'Create Company Note',
+ description: 'Adds a note to a CRM company.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Writes a note on one lemlist company (cpn_...). Not idempotent: each run adds another note.',
+ idempotent: false,
+ },
+ props: {
+ company_id: Property.ShortText({ displayName: 'Company ID', required: true }),
+ note: Property.LongText({ displayName: 'Note', required: true }),
+ },
+ outputSchema: lemlistSchemas.note,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `${companyPath(propsValue.company_id)}/notes`,
+ body: { note: lemlistInput.requireText({ value: propsValue.note, label: 'Note' }) },
+ });
+ },
+});
+
+export const listCompanyNotesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_company_notes',
+ classification: 'SEARCH',
+ displayName: 'List Company Notes',
+ description: 'Lists the notes of a CRM company.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists notes on one lemlist company (cpn_...), newest first. Page starts at 1, Limit 1-100 (default 100); has_more=true means ask for the next Page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ company_id: Property.ShortText({ displayName: 'Company ID', required: true }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false }),
+ limit: aiProps.limit({ max: 100, fallback: 100 }),
+ },
+ outputSchema: lemlistSchemas.notePage,
+ async run({ auth, propsValue }) {
+ const page = lemlistInput.boundedInt({ value: propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `${companyPath(propsValue.company_id)}/notes`,
+ query: { page, limit, sortBy: 'createdAt', sortOrder: 'desc' },
+ });
+ return notesPage({ body, page, limit });
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/enrichment.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/enrichment.ts
new file mode 100644
index 00000000000..86840fe2cd9
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/enrichment.ts
@@ -0,0 +1,76 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isRecord, lemlistApiCall, lemlistApiRequest } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { lemlistSchemas } from '../../common/schemas';
+
+export const enrichLeadAction = createAction({
+ auth: lemlistAuth,
+ name: 'enrich_lead',
+ classification: 'WRITE',
+ displayName: 'Enrich Lead',
+ description: 'Starts a credit-spending enrichment of a lead. Returns an enrichment ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts an enrichment of one existing lead (lea_...): find email, verify email, LinkedIn enrichment and/or find phone. Spends lemlist credits for each option chosen (check Get Team Credits first) and only runs when the user asked for it. At least one option is required. Returns an enrichment ID; poll Get Enrichment Result for the data. Not idempotent: each run can spend credits again.',
+ idempotent: false,
+ },
+ props: {
+ lead_id: aiProps.leadId(),
+ find_email: Property.Checkbox({ displayName: 'Find Email', required: false }),
+ verify_email: Property.Checkbox({ displayName: 'Verify Email', required: false }),
+ linkedin_enrichment: Property.Checkbox({ displayName: 'LinkedIn Enrichment', required: false }),
+ find_phone: Property.Checkbox({ displayName: 'Find Phone', required: false }),
+ },
+ outputSchema: lemlistSchemas.enrichment,
+ async run({ auth, propsValue }) {
+ const query = {
+ findEmail: propsValue.find_email === true ? true : undefined,
+ verifyEmail: propsValue.verify_email === true ? true : undefined,
+ linkedinEnrichment: propsValue.linkedin_enrichment === true ? true : undefined,
+ findPhone: propsValue.find_phone === true ? true : undefined,
+ };
+ if (Object.values(query).every((value) => value === undefined)) {
+ throw new Error('Choose at least one enrichment option.');
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/${lemlistInput.idSegment({ value: propsValue.lead_id, label: 'Lead ID', prefix: 'lea' })}/enrich`,
+ query,
+ });
+ },
+});
+
+export const getEnrichmentResultAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_enrichment_result',
+ classification: 'READ',
+ displayName: 'Get Enrichment Result',
+ description: 'Returns the result of an enrichment request.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the result of an enrichment started by Enrich Lead. done=false while lemlist is still working; try again later. When done, data holds the found email, phone or LinkedIn details. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ enrichment_id: Property.ShortText({ displayName: 'Enrichment ID', required: true }),
+ },
+ outputSchema: lemlistSchemas.enrichmentResult,
+ async run({ auth, propsValue }) {
+ const enrichmentId = lemlistInput.requireText({ value: propsValue.enrichment_id, label: 'Enrichment ID' });
+ const response = await lemlistApiRequest<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `/enrich/${lemlistInput.idSegment({ value: enrichmentId, label: 'Enrichment ID' })}`,
+ });
+ if (response.status === 202 || !isRecord(response.body)) {
+ return { enrichmentId, done: false, enrichmentStatus: 'in_progress', input: null, data: null };
+ }
+ return { ...response.body, enrichmentId: response.body['enrichmentId'] ?? enrichmentId, done: true };
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/inbox.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/inbox.ts
new file mode 100644
index 00000000000..7a222b71913
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/inbox.ts
@@ -0,0 +1,157 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isRecord, lemlistApiCall } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+export const getContactMessagesAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_contact_messages',
+ classification: 'READ',
+ displayName: 'Get Contact Messages',
+ description: 'Returns the inbox conversation with a contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the messages exchanged with one contact (contact ID ctc_...) in the lemlist inbox: emails, LinkedIn and other messages with type, date, subject and body. Limit 1-100 (default 50) and Skip for paging; has_more=true means call again with Skip + Limit. Does not mark the conversation as read. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: true }),
+ limit: aiProps.limit({ max: 100, fallback: 50 }),
+ skip: Property.Number({ displayName: 'Skip', description: 'Messages to skip. Default 0.', required: false }),
+ },
+ outputSchema: lemlistSchemas.messages,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 50;
+ const skip = lemlistInput.boundedInt({ value: propsValue.skip, label: 'Skip', min: 0, max: 1_000_000 }) ?? 0;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `/inbox/${lemlistInput.segment({ value: propsValue.contact_id, label: 'Contact ID' })}`,
+ query: { limit, skip },
+ });
+ const items = lemlistResults.listFrom({ body });
+ const pagination = isRecord(body) ? body['pagination'] : undefined;
+ const total = lemlistResults.numberField({ body: pagination, key: 'totalItems' });
+ return {
+ items,
+ count: items.length,
+ total: total ?? null,
+ has_more: total === undefined ? items.length >= limit : skip + items.length < total,
+ };
+ },
+});
+
+export const sendInboxEmailAction = createAction({
+ auth: lemlistAuth,
+ name: 'send_inbox_email',
+ classification: 'WRITE',
+ displayName: 'Send Inbox Email',
+ description: 'Sends a real email to a contact from a lemlist mailbox.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sends a real email right away from a connected lemlist mailbox to a contact or lead, or replies in an existing thread with Reply To Activity ID (reuses its subject and CC). The email cannot be recalled. Only send when the user approved the recipient and the text. Sender user ID, sender email and mailbox ID come from Get Campaign (senders) or Get Team. Not idempotent: each run sends another email.',
+ idempotent: false,
+ },
+ props: {
+ send_user_id: Property.ShortText({ displayName: 'Sender User ID', description: 'usr_... of the sender.', required: true }),
+ send_user_email: Property.ShortText({ displayName: 'Sender Email', required: true }),
+ send_user_mailbox_id: Property.ShortText({ displayName: 'Sender Mailbox ID', description: 'usm_... mailbox ID.', required: true }),
+ contact_id: Property.ShortText({ displayName: 'Contact ID', description: 'Recipient contact (ctc_...). Give this or Lead ID.', required: false }),
+ lead_id: Property.ShortText({ displayName: 'Lead ID', description: 'Recipient lead (lea_...). Give this or Contact ID.', required: false }),
+ subject: Property.ShortText({ displayName: 'Subject', description: 'Required unless replying in a thread.', required: false }),
+ message: Property.LongText({ displayName: 'Message', description: 'Email body (HTML allowed).', required: true }),
+ cc: Property.Array({ displayName: 'CC', required: false }),
+ reply_to_activity_id: Property.ShortText({ displayName: 'Reply To Activity ID', required: false }),
+ },
+ outputSchema: lemlistSchemas.sentEmail,
+ async run({ auth, propsValue }) {
+ const contactId = lemlistInput.optionalText(propsValue.contact_id);
+ const leadId = lemlistInput.optionalText(propsValue.lead_id);
+ if (contactId === undefined && leadId === undefined) {
+ throw new Error('Provide the recipient Contact ID or Lead ID.');
+ }
+ const replyTo = lemlistInput.optionalText(propsValue.reply_to_activity_id);
+ const subject = lemlistInput.optionalText(propsValue.subject);
+ if (replyTo === undefined && subject === undefined) {
+ throw new Error('Subject is required for a new email.');
+ }
+ const cc =
+ propsValue.cc === undefined || propsValue.cc.length === 0
+ ? undefined
+ : lemlistInput
+ .stringList({ value: propsValue.cc, label: 'CC' })
+ .map((address) => lemlistInput.email({ value: address, label: 'CC' }));
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/inbox/email',
+ body: lemlistInput.compact({
+ sendUserId: lemlistInput.requireText({ value: propsValue.send_user_id, label: 'Sender User ID' }),
+ sendUserEmail: lemlistInput.email({ value: propsValue.send_user_email, label: 'Sender Email' }),
+ sendUserMailboxId: lemlistInput.requireText({ value: propsValue.send_user_mailbox_id, label: 'Sender Mailbox ID' }),
+ contactId,
+ leadId,
+ subject,
+ message: lemlistInput.requireText({ value: propsValue.message, label: 'Message' }),
+ cc,
+ replyToActivityId: replyTo,
+ }),
+ });
+ },
+});
+
+export const listLabelsAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_labels',
+ classification: 'SEARCH',
+ displayName: 'List Inbox Labels',
+ description: 'Lists the inbox labels of the team.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists every lemlist inbox label of the team (ID, name, color). Returns all labels in one call. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: lemlistSchemas.labels,
+ async run({ auth }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/inbox/labels',
+ });
+ const items = lemlistResults.listFrom({ body });
+ return { items, count: items.length };
+ },
+});
+
+export const createLabelAction = createAction({
+ auth: lemlistAuth,
+ name: 'create_label',
+ classification: 'WRITE',
+ displayName: 'Create Inbox Label',
+ description: 'Creates an inbox label.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new inbox label for the team. Fails with a conflict when a label with this name exists (check List Inbox Labels first). Not idempotent.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Label Name', required: true }),
+ },
+ outputSchema: lemlistSchemas.label,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/inbox/labels',
+ body: { labelName: lemlistInput.requireText({ value: propsValue.name, label: 'Label Name' }) },
+ });
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/leads.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/leads.ts
new file mode 100644
index 00000000000..5ed16f5fa64
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/leads.ts
@@ -0,0 +1,456 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isLemlistStatus, lemlistApiCall } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { lemlistLeads } from '../../common/requests';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+const LEAD_FIELD_KEYS = Object.keys(leadFieldProps());
+
+function leadFieldProps() {
+ return {
+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),
+ lastName: Property.ShortText({ displayName: 'Last Name', required: false }),
+ companyName: Property.ShortText({ displayName: 'Company Name', required: false }),
+ companyDomain: Property.ShortText({ displayName: 'Company Domain', required: false }),
+ jobTitle: Property.ShortText({ displayName: 'Job Title', required: false }),
+ linkedinUrl: Property.ShortText({ displayName: 'LinkedIn URL', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ icebreaker: Property.LongText({ displayName: 'Icebreaker', required: false }),
+ };
+}
+
+export const listCampaignLeadsAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_campaign_leads',
+ classification: 'SEARCH',
+ displayName: 'List Campaign Leads',
+ description: 'Lists the leads of a campaign, optionally by state.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists leads of one campaign (lead ID, contact ID, state), optionally only those in a state such as scanned, contacted, interested or notInterested. Returns at most Limit leads (1-500, default 100); Page with Offset (default 0); has_more=true means another page may exist, so call again with offset + limit. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ state: Property.ShortText({
+ displayName: 'State',
+ description: 'Lead state filter, e.g. scanned, contacted, interested, notInterested.',
+ required: false,
+ }),
+ limit: aiProps.limit({ max: 500, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.campaignLeads,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 500 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(propsValue.campaign_id)}/leads/`,
+ query: { state: lemlistInput.optionalText(propsValue.state), limit, offset },
+ });
+ return lemlistResults.page({ items: lemlistResults.listFrom({ body }), offset, limit });
+ },
+});
+
+export const createLeadInCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'create_lead_in_campaign',
+ classification: 'WRITE',
+ displayName: 'Create Lead in Campaign',
+ description: 'Creates a lead in a campaign. Runs no paid enrichment.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new lead (email plus optional name, company, job title, LinkedIn, phone, icebreaker) in one campaign and returns its lead ID (lea_...). If the campaign is running, the lead enters the sequence and may be emailed. Uses no enrichment credits (see Enrich Lead). With Deduplicate on, it is refused when the contact is already in another campaign. Not idempotent: a second run fails or creates a duplicate.',
+ idempotent: false,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ email: aiProps.leadEmail(),
+ ...leadFieldProps(),
+ deduplicate: Property.Checkbox({
+ displayName: 'Deduplicate',
+ description: 'Refuse the lead when the contact is already in another campaign.',
+ required: false,
+ }),
+ },
+ outputSchema: lemlistSchemas.createdLead,
+ async run({ auth, propsValue }) {
+ const { campaign_id, email, deduplicate } = propsValue;
+ const fields = lemlistInput.pick({ record: propsValue, keys: LEAD_FIELD_KEYS });
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(campaign_id)}/leads/`,
+ query: { deduplicate: deduplicate === true ? true : undefined },
+ body: {
+ ...lemlistInput.compact(fields),
+ email: lemlistInput.email({ value: email, label: 'Lead Email' }),
+ },
+ });
+ },
+});
+
+export const getLeadByEmailAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_lead_by_email',
+ classification: 'READ',
+ displayName: 'Get Lead by Email',
+ description: 'Finds the leads of one email across campaigns.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns every lead with this email (one per campaign) with lead ID, state, variables and campaign; optional Campaign ID keeps only that campaign. found=false when there is none. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ email: aiProps.leadEmail(),
+ campaign_id: aiProps.campaignId(false),
+ },
+ outputSchema: lemlistSchemas.leadsByEmail,
+ async run({ auth, propsValue }) {
+ const email = lemlistInput.email({ value: propsValue.email, label: 'Lead Email' });
+ const campaignId = lemlistInput.optionalText(propsValue.campaign_id);
+ const leads = await lemlistLeads.getLeadsByEmail({ apiKey: auth.secret_text, email });
+ const matching =
+ campaignId === undefined ? leads : leads.filter((lead) => lemlistLeads.leadCampaignId(lead) === campaignId);
+ return {
+ found: matching.length > 0,
+ message: matching.length > 0 ? `Found ${matching.length} lead(s).` : `No lead found for ${email}.`,
+ leads: matching,
+ };
+ },
+});
+
+export const updateCampaignLeadAction = createAction({
+ auth: lemlistAuth,
+ name: 'update_campaign_lead',
+ classification: 'WRITE',
+ displayName: 'Update Campaign Lead',
+ description: 'Updates fields of a lead in a campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates a lead in one campaign, found by lead ID (lea_...) or email. Only the fields you pass are changed; at least one is required. Changing company fields also changes the shared company record. Idempotent.',
+ idempotent: true,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ lead: aiProps.leadIdOrEmail(),
+ ...leadFieldProps(),
+ },
+ outputSchema: lemlistSchemas.leadWithWarnings,
+ async run({ auth, propsValue }) {
+ const { campaign_id, lead } = propsValue;
+ const fields = lemlistInput.pick({ record: propsValue, keys: LEAD_FIELD_KEYS });
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.PATCH,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(campaign_id)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: lead, label: 'Lead' })}`,
+ body: requireSomeFields(fields),
+ });
+ },
+});
+
+function requireSomeFields(fields: Record<string, unknown>): Record<string, unknown> {
+ const body = lemlistInput.compact(fields);
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ return body;
+}
+
+export const deleteLeadFromCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'delete_lead_from_campaign',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Lead from Campaign',
+ description: 'Deletes a lead from a campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes a lead (lead ID or email) from one campaign; its progress in that campaign is lost and cannot be restored. The contact itself is kept. Returns alreadyRemoved=true when the lead was not in the campaign, so a retry is safe.',
+ idempotent: true,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ lead: aiProps.leadIdOrEmail(),
+ },
+ outputSchema: lemlistSchemas.deletedLead,
+ async run({ auth, propsValue }) {
+ try {
+ const lead = await lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(propsValue.campaign_id)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}`,
+ query: { action: 'remove' },
+ });
+ return { deleted: true, alreadyRemoved: false, lead };
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 404 })) {
+ return { deleted: false, alreadyRemoved: true, lead: null };
+ }
+ throw error;
+ }
+ },
+});
+
+export const unsubscribeLeadFromCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'unsubscribe_lead_from_campaign',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Unsubscribe Lead from Campaign',
+ description: 'Unsubscribes a lead from one campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Unsubscribes a lead (lead ID or email) from one campaign: it gets no more messages from that campaign and this cannot be undone here. Other campaigns are not affected; use Add Unsubscribe to block an email everywhere.',
+ idempotent: true,
+ },
+ props: {
+ campaign_id: aiProps.campaignId(),
+ lead: aiProps.leadIdOrEmail(),
+ },
+ outputSchema: lemlistSchemas.unsubscribedLead,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(propsValue.campaign_id)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}`,
+ });
+ },
+});
+
+export const pauseLeadInCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'pause_lead_in_campaign',
+ classification: 'WRITE',
+ displayName: 'Pause Lead in Campaign',
+ description: 'Pauses a lead in one campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Pauses a lead (lead ID or email) in one campaign so it gets no more messages there until resumed. Returns the paused leads. Idempotent.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId(), lead: aiProps.leadIdOrEmail() },
+ outputSchema: lemlistSchemas.leadState,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/pause/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}`,
+ query: { campaignId: decodeURIComponent(lemlistLeads.campaignSegment(propsValue.campaign_id)) },
+ });
+ return lemlistLeads.asLeadList(body);
+ },
+});
+
+export const pauseLeadEverywhereAction = createAction({
+ auth: lemlistAuth,
+ name: 'pause_lead_everywhere',
+ classification: 'WRITE',
+ displayName: 'Pause Lead in All Campaigns',
+ description: 'Pauses a lead in every campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Pauses a lead (lead ID or email) in every campaign it belongs to. Returns the paused leads. Idempotent.',
+ idempotent: true,
+ },
+ props: { lead: aiProps.leadIdOrEmail() },
+ outputSchema: lemlistSchemas.leadState,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/pause/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}`,
+ });
+ return lemlistLeads.asLeadList(body);
+ },
+});
+
+export const resumeLeadInCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'resume_lead_in_campaign',
+ classification: 'WRITE',
+ displayName: 'Resume Lead in Campaign',
+ description: 'Resumes a paused lead in one campaign. It can be emailed right away.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Resumes a paused lead (lead ID or email) in one campaign. If the campaign is running the lead can receive real messages right away. Idempotent.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId(), lead: aiProps.leadIdOrEmail() },
+ outputSchema: lemlistSchemas.leadState,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/start/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}`,
+ query: { campaignId: decodeURIComponent(lemlistLeads.campaignSegment(propsValue.campaign_id)) },
+ });
+ return lemlistLeads.asLeadList(body);
+ },
+});
+
+export const resumeLeadEverywhereAction = createAction({
+ auth: lemlistAuth,
+ name: 'resume_lead_everywhere',
+ classification: 'WRITE',
+ displayName: 'Resume Lead in All Campaigns',
+ description: 'Resumes a paused lead in every campaign. It can be emailed right away.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Resumes a paused lead (lead ID or email) in every campaign it belongs to; running campaigns can message it right away. Idempotent.',
+ idempotent: true,
+ },
+ props: { lead: aiProps.leadIdOrEmail() },
+ outputSchema: lemlistSchemas.leadState,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/start/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}`,
+ });
+ return lemlistLeads.asLeadList(body);
+ },
+});
+
+export const launchLeadAction = createAction({
+ auth: lemlistAuth,
+ name: 'launch_lead',
+ classification: 'WRITE',
+ displayName: 'Launch Lead',
+ description: 'Launches a lead waiting for review. Its campaign can then email it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Launches one lead (lea_...) that is waiting for review, so its campaign starts sending it real messages. Fails if the campaign has step errors or no sender. Needs an emailPro plan or higher. Only call when the user asked to launch this lead. Idempotent: an already launched lead stays launched.',
+ idempotent: true,
+ },
+ props: { lead_id: aiProps.leadId() },
+ outputSchema: lemlistSchemas.ok,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/review/${lemlistInput.idSegment({ value: propsValue.lead_id, label: 'Lead ID', prefix: 'lea' })}`,
+ });
+ },
+});
+
+export const markLeadInterestedInCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'mark_lead_interested_in_campaign',
+ classification: 'WRITE',
+ displayName: 'Mark Lead Interested in Campaign',
+ description: 'Marks a lead as interested in one campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Marks a lead (lead ID or email) as interested in one campaign. Returns the updated lead. Idempotent.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId(), lead: aiProps.leadIdOrEmail() },
+ outputSchema: lemlistSchemas.lead,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(propsValue.campaign_id)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}/interested`,
+ });
+ },
+});
+
+export const markLeadNotInterestedInCampaignAction = createAction({
+ auth: lemlistAuth,
+ name: 'mark_lead_not_interested_in_campaign',
+ classification: 'WRITE',
+ displayName: 'Mark Lead Not Interested in Campaign',
+ description: 'Marks a lead as not interested in one campaign.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Marks a lead (lead ID or email) as not interested in one campaign. Returns the updated lead. Idempotent.',
+ idempotent: true,
+ },
+ props: { campaign_id: aiProps.campaignId(), lead: aiProps.leadIdOrEmail() },
+ outputSchema: lemlistSchemas.lead,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/campaigns/${lemlistLeads.campaignSegment(propsValue.campaign_id)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: propsValue.lead, label: 'Lead' })}/notinterested`,
+ });
+ },
+});
+
+export const updateLeadVariablesAction = createAction({
+ auth: lemlistAuth,
+ name: 'update_lead_variables',
+ classification: 'WRITE',
+ displayName: 'Update Lead Variables',
+ description: 'Updates values of existing custom variables on a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets new values for custom variables that already exist on a lead (lea_...). Pass name/value pairs; values are sent in the request body. Use Add Custom Variables on Lead to create new names. company-prefixed names change the shared company record. Idempotent.',
+ idempotent: true,
+ },
+ props: {
+ lead_id: aiProps.leadId(),
+ variables: Property.Object({
+ displayName: 'Variables',
+ description: 'Variable names and their new values.',
+ required: true,
+ }),
+ },
+ outputSchema: lemlistSchemas.variables,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.PATCH,
+ resourceUri: `/leads/${lemlistInput.idSegment({ value: propsValue.lead_id, label: 'Lead ID', prefix: 'lea' })}/variables`,
+ body: lemlistInput.stringRecord({ value: propsValue.variables, label: 'Variables' }),
+ });
+ },
+});
+
+export const eraseLeadVariablesAction = createAction({
+ auth: lemlistAuth,
+ name: 'erase_lead_variables',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Erase Lead Variables',
+ description: 'Erases the values of custom variables on a lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Erases the values of the named custom variables on a lead (lea_...); the variable names stay. Erased values cannot be recovered. companyDomain cannot be erased. Idempotent.',
+ idempotent: true,
+ },
+ props: {
+ lead_id: aiProps.leadId(),
+ variable_names: Property.Array({
+ displayName: 'Variable Names',
+ description: 'Names of the variables whose values to erase.',
+ required: true,
+ }),
+ },
+ outputSchema: lemlistSchemas.variables,
+ async run({ auth, propsValue }) {
+ const names = lemlistInput.stringList({ value: propsValue.variable_names, label: 'Variable Names' });
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ resourceUri: `/leads/${lemlistInput.idSegment({ value: propsValue.lead_id, label: 'Lead ID', prefix: 'lea' })}/variables`,
+ query: Object.fromEntries(names.map((name) => [name, ''])),
+ });
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/tasks.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/tasks.ts
new file mode 100644
index 00000000000..1a3fe0402f0
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/tasks.ts
@@ -0,0 +1,178 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isRecord, lemlistApiCall } from '../../common/client';
+import { lemlistAuth } from '../../common/constants';
+import { aiProps } from '../../common/ai-props';
+import { lemlistInput } from '../../common/input';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+const TASK_TYPES = ['manual', 'email', 'phone', 'linkedin', 'whatsapp'];
+const PRIORITIES = [
+ { label: 'None', value: '' },
+ { label: 'Low', value: '0' },
+ { label: 'Medium', value: '1' },
+ { label: 'High', value: '2' },
+];
+
+export const createTaskAction = createAction({
+ auth: lemlistAuth,
+ name: 'create_task',
+ classification: 'WRITE',
+ displayName: 'Create Task',
+ description: 'Creates a task for a team member about a contact, company or lead.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a lemlist task (manual, email, phone, linkedin or whatsapp) assigned to a team member (usr_...) about a contact (ctc_), company (cpn_, manual only) or lead (lea_), with a due date. Nothing is sent: the task waits for a person. Not idempotent: each run creates another task.',
+ idempotent: false,
+ },
+ props: {
+ record_id: Property.ShortText({
+ displayName: 'Record ID',
+ description: 'Contact (ctc_), company (cpn_) or lead (lea_) ID.',
+ required: true,
+ }),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: true,
+ options: { disabled: false, options: TASK_TYPES.map((value) => ({ label: value, value })) },
+ }),
+ assigned_to: Property.ShortText({ displayName: 'Assigned To (User ID)', required: true }),
+ due_date: Property.ShortText({ displayName: 'Due Date', description: 'ISO 8601 date-time.', required: true }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ message: Property.LongText({ displayName: 'Instructions', required: false }),
+ priority: Property.StaticDropdown({
+ displayName: 'Priority',
+ required: false,
+ options: { disabled: false, options: PRIORITIES },
+ }),
+ },
+ outputSchema: lemlistSchemas.task,
+ async run({ auth, propsValue }) {
+ const type = lemlistInput.requireText({ value: propsValue.type, label: 'Type' });
+ if (!TASK_TYPES.includes(type)) {
+ throw new Error(`Type must be one of ${TASK_TYPES.join(', ')}.`);
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/tasks',
+ body: lemlistInput.compact({
+ recordId: lemlistInput.requireText({ value: propsValue.record_id, label: 'Record ID' }),
+ type,
+ assignedTo: lemlistInput.requireText({ value: propsValue.assigned_to, label: 'Assigned To' }),
+ dueDate: lemlistInput.isoDate({ value: propsValue.due_date, label: 'Due Date' }),
+ title: propsValue.title,
+ message: propsValue.message,
+ priority: propsValue.priority,
+ }),
+ });
+ },
+});
+
+export const listTasksAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_tasks',
+ classification: 'SEARCH',
+ displayName: 'List Pending Tasks',
+ description: 'Lists pending tasks of the team.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists pending (not done) lemlist tasks of the team with type, title, due date, assignee and linked lead/contact/campaign. Paged by Page (starts at 0); an empty page means there are no more. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 0.', required: false }),
+ },
+ outputSchema: lemlistSchemas.taskPage,
+ async run({ auth, propsValue }) {
+ const page = lemlistInput.boundedInt({ value: propsValue.page, label: 'Page', min: 0, max: 100_000 }) ?? 0;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/tasks',
+ query: { filters: '[]', page },
+ });
+ const items = lemlistResults.listFrom({ body, key: 'results' });
+ return { items, count: items.length, page };
+ },
+});
+
+export const updateTaskAction = createAction({
+ auth: lemlistAuth,
+ name: 'update_task',
+ classification: 'WRITE',
+ displayName: 'Update Task',
+ description: 'Updates a task: assignee, due date, title, instructions, priority or done.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates one lemlist task (opp_...): assignee, due date, title, instructions, priority or done status (yes/no; unchanged or empty keeps it). Only fields you pass change; at least one is required. Idempotent.',
+ idempotent: true,
+ },
+ props: {
+ task_id: Property.ShortText({ displayName: 'Task ID', required: true }),
+ assigned_to: Property.ShortText({ displayName: 'Assigned To (User ID)', required: false }),
+ due_date: Property.ShortText({ displayName: 'Due Date', description: 'ISO 8601 date-time.', required: false }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ message: Property.LongText({ displayName: 'Instructions', required: false }),
+ priority: Property.StaticDropdown({
+ displayName: 'Priority',
+ description: 'Leave empty to keep the current priority.',
+ required: false,
+ options: { disabled: false, options: PRIORITIES.filter((option) => option.value !== '') },
+ }),
+ done: aiProps.triState({ displayName: 'Done', description: 'Mark the task done (yes) or not done (no).' }),
+ },
+ outputSchema: lemlistSchemas.task,
+ async run({ auth, propsValue }) {
+ const dueDate = lemlistInput.optionalText(propsValue.due_date);
+ const changes = lemlistInput.compact({
+ assignedTo: propsValue.assigned_to,
+ dueDate: dueDate === undefined ? undefined : lemlistInput.isoDate({ value: dueDate, label: 'Due Date' }),
+ title: propsValue.title,
+ message: propsValue.message,
+ priority: propsValue.priority,
+ done: lemlistInput.triState(propsValue.done),
+ });
+ if (Object.keys(changes).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.PATCH,
+ resourceUri: '/tasks',
+ body: { ...changes, id: lemlistInput.requireText({ value: propsValue.task_id, label: 'Task ID' }) },
+ });
+ },
+});
+
+export const ignoreTasksAction = createAction({
+ auth: lemlistAuth,
+ name: 'ignore_tasks',
+ classification: 'WRITE',
+ displayName: 'Ignore Tasks',
+ description: 'Marks tasks as ignored.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Marks one or more lemlist tasks (opp_...) as ignored so they leave the pending list without being done. Idempotent: ignoring an ignored task changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ task_ids: Property.Array({ displayName: 'Task IDs', required: true }),
+ },
+ outputSchema: lemlistSchemas.ignoredTasks,
+ async run({ auth, propsValue }) {
+ const ids = lemlistInput.stringList({ value: propsValue.task_ids, label: 'Task IDs' });
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: '/tasks/ignore',
+ body: { ids },
+ });
+ return { ignored: ids, count: ids.length, response: isRecord(body) ? body : null };
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/team.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/team.ts
new file mode 100644
index 00000000000..e8ce0b55df4
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/team.ts
@@ -0,0 +1,92 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { lemlistApiCall } from '../../common/client';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+export const getTeamAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_team',
+ classification: 'READ',
+ displayName: 'Get Team',
+ description: 'Returns the lemlist team of the connected API key, with its users.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the lemlist team linked to this connection: team ID, name and its users (userId, name, email, role). Use to find user IDs for tasks, sender filters or Send Inbox Email. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: lemlistSchemas.team,
+ async run({ auth }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/team',
+ query: { version: 'v2' },
+ });
+ },
+});
+
+export const listTeamSendersAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_team_senders',
+ classification: 'SEARCH',
+ displayName: 'List Team Senders',
+ description: 'Lists team members and the campaigns they send from.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every lemlist team member (userId) with the campaigns they send from (campaign ID, name, status). Optional campaign state filter. Returns all senders in one call. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ state: Property.StaticDropdown({
+ displayName: 'Campaign State',
+ description: 'Only include campaigns in this state.',
+ required: false,
+ options: {
+ disabled: false,
+ options: ['running', 'paused', 'draft', 'ended', 'archived', 'errors'].map((value) => ({
+ label: value,
+ value,
+ })),
+ },
+ }),
+ },
+ outputSchema: lemlistSchemas.senders,
+ async run({ auth, propsValue }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/team/senders',
+ query: { state: propsValue.state ?? undefined },
+ });
+ const items = lemlistResults.listFrom({ body });
+ return { items, count: items.length, offset: 0, has_more: false };
+ },
+});
+
+export const getTeamCreditsAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_team_credits',
+ classification: 'READ',
+ displayName: 'Get Team Credits',
+ description: 'Returns the remaining lemlist credits of the team.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns how many lemlist credits the team has left (total plus subscription, paid, gifted and freemium breakdown). Check before credit-spending actions such as Enrich Lead. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: lemlistSchemas.credits,
+ async run({ auth }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/team/credits',
+ });
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/unsubscribes.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/unsubscribes.ts
new file mode 100644
index 00000000000..f1496fff992
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/unsubscribes.ts
@@ -0,0 +1,136 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { isLemlistStatus, lemlistApiCall } from '../../common/client';
+import { aiProps } from '../../common/ai-props';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistInput } from '../../common/input';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+function emailOrDomainProp() {
+ return Property.ShortText({
+ displayName: 'Email or Domain',
+ description: 'An email address ([email protected]) or a whole domain (acme.com).',
+ required: true,
+ });
+}
+
+export const listUnsubscribesAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_unsubscribes',
+ classification: 'SEARCH',
+ displayName: 'List Unsubscribes',
+ description: 'Lists unsubscribed emails and domains.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the team-wide unsubscribe (do-not-contact) list: emails and domains with source and date. Limit 1-100 (default 100) and Offset; has_more=true means call again with Offset + Limit. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ limit: aiProps.limit({ max: 100, fallback: 100 }),
+ offset: aiProps.offset(),
+ },
+ outputSchema: lemlistSchemas.unsubscribePage,
+ async run({ auth, propsValue }) {
+ const limit = lemlistInput.boundedInt({ value: propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;
+ const offset = lemlistInput.boundedInt({ value: propsValue.offset, label: 'Offset', min: 0, max: 1_000_000 }) ?? 0;
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/unsubscribes',
+ query: { limit, offset },
+ });
+ return lemlistResults.page({ items: lemlistResults.listFrom({ body }), offset, limit });
+ },
+});
+
+export const getUnsubscribeAction = createAction({
+ auth: lemlistAuth,
+ name: 'get_unsubscribe',
+ classification: 'READ',
+ displayName: 'Check Unsubscribe',
+ description: 'Checks whether an email or domain is on the unsubscribe list.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Checks whether one email or domain is on the team unsubscribe (do-not-contact) list. Returns unsubscribed=true with the record, or unsubscribed=false. Read-only.',
+ idempotent: true,
+ },
+ props: { value: emailOrDomainProp() },
+ outputSchema: lemlistSchemas.unsubscribeStatus,
+ async run({ auth, propsValue }) {
+ try {
+ const record = await lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: `/unsubscribes/${lemlistInput.emailOrDomainSegment({ value: propsValue.value, label: 'Email or Domain' })}`,
+ });
+ return { unsubscribed: true, record };
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 404 })) {
+ return { unsubscribed: false, record: null };
+ }
+ throw error;
+ }
+ },
+});
+
+export const addUnsubscribeAction = createAction({
+ auth: lemlistAuth,
+ name: 'add_unsubscribe',
+ classification: 'WRITE',
+ displayName: 'Add Unsubscribe',
+ description: 'Adds an email or domain to the unsubscribe list.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds an email or a whole domain to the team unsubscribe (do-not-contact) list, so no campaign contacts it any more. Use to honour an opt-out. Idempotent: adding an existing entry keeps it.',
+ idempotent: true,
+ },
+ props: { value: emailOrDomainProp() },
+ outputSchema: lemlistSchemas.unsubscribe,
+ async run({ auth, propsValue }) {
+ return lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.POST,
+ resourceUri: `/unsubscribes/${lemlistInput.emailOrDomainSegment({ value: propsValue.value, label: 'Email or Domain' })}`,
+ });
+ },
+});
+
+export const resubscribeEmailAction = createAction({
+ auth: lemlistAuth,
+ name: 'resubscribe_email',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove from Unsubscribe List',
+ description: 'Removes an email or domain from the unsubscribe list. Only when the person opted back in.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Deletes an email or domain from the unsubscribe (do-not-contact) list so campaigns can contact it again. Only call when the person explicitly opted back in: emailing someone who unsubscribed can break anti-spam and privacy law. Returns removed=false when the entry was not on the list, so a retry is safe.',
+ idempotent: true,
+ },
+ props: { value: emailOrDomainProp() },
+ outputSchema: {
+ fields: [
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ { key: 'record', label: 'Record', children: lemlistSchemas.unsubscribe.fields },
+ ],
+ },
+ async run({ auth, propsValue }) {
+ try {
+ const record = await lemlistApiCall({
+ apiKey: auth.secret_text,
+ method: HttpMethod.DELETE,
+ resourceUri: `/unsubscribes/${lemlistInput.emailOrDomainSegment({ value: propsValue.value, label: 'Email or Domain' })}`,
+ });
+ return { removed: true, record };
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 404 })) {
+ return { removed: false, record: null };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/ai/webhooks.ts b/packages/pieces/community/lemlist/src/lib/actions/ai/webhooks.ts
new file mode 100644
index 00000000000..3236782863e
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/actions/ai/webhooks.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { lemlistApiCall } from '../../common/client';
+import { lemlistAuth } from '../../common/constants';
+import { lemlistResults } from '../../common/results';
+import { lemlistSchemas } from '../../common/schemas';
+
+export const listWebhooksAction = createAction({
+ auth: lemlistAuth,
+ name: 'list_webhooks',
+ classification: 'SEARCH',
+ displayName: 'List Webhooks',
+ description: 'Lists the webhooks registered on the team.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every webhook registered on the lemlist team (target URL, event type, campaign, disabled flag). A team can hold 200 webhooks, disabled ones included; use this to diagnose a full quota. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: lemlistSchemas.webhooks,
+ async run({ auth }) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ resourceUri: '/hooks',
+ });
+ const items = lemlistResults.listFrom({ body });
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaign-as-interested.ts b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaign-as-interested.ts
index 93e96a565c1..5313dd7dfa1 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaign-as-interested.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaign-as-interested.ts
@@ -1,7 +1,7 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
-import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const markLeadFromAllCampaignAsInterested = createAction({
auth: lemlistAuth,
@@ -10,7 +10,11 @@ export const markLeadFromAllCampaignAsInterested = createAction({
displayName: 'Mark Lead From All Campaign as Interested',
description: 'Mark a lead as “interested” across all campaigns.',
audience: 'both',
- aiMetadata: { description: 'Sets the "interested" status on a lead, identified by email, across every Lemlist campaign the lead belongs to. Use when interest is not campaign-specific; for a single campaign use the per-campaign variant instead. Idempotent: re-running leaves the lead in the same interested state.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets the "interested" status on a lead, identified by email, in every Lemlist campaign the lead belongs to. Returns the updated lead records (one per campaign). For a single campaign use the per-campaign variant. Idempotent: re-running leaves the lead interested.',
+ idempotent: true,
+ },
props: {
email: Property.ShortText({
displayName: 'Lead Email',
@@ -18,9 +22,8 @@ export const markLeadFromAllCampaignAsInterested = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { email } }) {
- return await lemlistApiService.markLeadAsInterestedInAllCampaigns(auth, {
- leadEmail: email as string,
- });
+ outputSchema: lemlistSchemas.leadList,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.setInterestEverywhere({ apiKey: auth.secret_text, lead: propsValue.email, interested: true });
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaigns-as-not-interested.ts b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaigns-as-not-interested.ts
index 3ba30edbd18..28629b57cca 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaigns-as-not-interested.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-all-campaigns-as-not-interested.ts
@@ -1,7 +1,7 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
-import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const markLeadFromAllCampaignsAsNotInterested = createAction({
auth: lemlistAuth,
@@ -10,7 +10,11 @@ export const markLeadFromAllCampaignsAsNotInterested = createAction({
displayName: 'Mark Lead From All Campaigns as Not Interested',
description: 'Mark a lead as “not interested” across all campaigns.',
audience: 'both',
- aiMetadata: { description: 'Sets the "not interested" status on a lead, identified by email, across every Lemlist campaign the lead belongs to. Use when disqualifying interest globally; for a single campaign use the per-campaign variant instead. Idempotent: re-running leaves the lead in the same not-interested state.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Sets the "not interested" status on a lead, identified by email, in every Lemlist campaign the lead belongs to. Returns the updated lead records. For a single campaign use the per-campaign variant. Idempotent: re-running leaves the lead not interested.',
+ idempotent: true,
+ },
props: {
email: Property.ShortText({
displayName: 'Lead Email',
@@ -18,9 +22,8 @@ export const markLeadFromAllCampaignsAsNotInterested = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { email } }) {
- return await lemlistApiService.markLeadAsNotInterestedInAllCampaigns(auth, {
- leadEmail: email as string,
- });
+ outputSchema: lemlistSchemas.leadList,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.setInterestEverywhere({ apiKey: auth.secret_text, lead: propsValue.email, interested: false });
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-interested.ts b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-interested.ts
index e861f070de6..5030cb108a5 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-interested.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-interested.ts
@@ -1,7 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const markLeadFromOneCampaignAsInterested = createAction({
auth: lemlistAuth,
@@ -9,23 +10,27 @@ export const markLeadFromOneCampaignAsInterested = createAction({
classification: 'WRITE',
displayName: 'Mark Lead From One Campaign as Interested',
description: 'Mark a lead in a campaign as interested.',
- audience: 'both',
- aiMetadata: { description: 'Sets the "interested" status on a lead within one specific Lemlist campaign, identified by the campaign and the lead\'s email. Use when you want to flag interest scoped to a single campaign rather than across all of them. Idempotent: re-running leaves the lead in the same interested state.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sets the "interested" status on a lead in one Lemlist campaign, identified by campaign and lead email. Idempotent.',
+ idempotent: true,
+ },
props: {
- campaignId: campaignsDropdown({refreshers: ['auth']}),
+ campaignId: campaignsDropdown({ refreshers: ['auth'] }),
email: Property.ShortText({
displayName: 'Lead Email',
description: 'The email of the lead to mark as interested.',
required: true,
}),
},
- async run({ auth, propsValue: { campaignId, email } }) {
- return await lemlistApiService.markLeadAsInterestedInCampaign(
- auth,
- {
- campaignId: campaignId as string,
- leadEmail: email as string,
- }
- );
+ outputSchema: lemlistSchemas.lead,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.setInterestInCampaign({
+ apiKey: auth.secret_text,
+ campaignId: propsValue.campaignId,
+ lead: propsValue.email,
+ interested: true,
+ });
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-not-interested.ts b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-not-interested.ts
index f25410028ab..f2ab2aee930 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-not-interested.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/mark-lead-from-one-campaign-as-not-interested.ts
@@ -1,7 +1,8 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const markLeadFromOneCampaignAsNotInterested = createAction({
auth: lemlistAuth,
@@ -9,8 +10,12 @@ export const markLeadFromOneCampaignAsNotInterested = createAction({
classification: 'WRITE',
displayName: 'Mark Lead From One Campaign as Not Interested',
description: 'Mark a lead in a campaign as not interested.',
- audience: 'both',
- aiMetadata: { description: 'Sets the "not interested" status on a lead within one specific Lemlist campaign, identified by the campaign and the lead\'s email. Use when disqualifying interest scoped to a single campaign rather than across all of them. Idempotent: re-running leaves the lead in the same not-interested state.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sets the "not interested" status on a lead in one Lemlist campaign, identified by campaign and lead email. Idempotent.',
+ idempotent: true,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'] }),
email: Property.ShortText({
@@ -19,10 +24,13 @@ export const markLeadFromOneCampaignAsNotInterested = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { campaignId, email } }) {
- return await lemlistApiService.markLeadAsNotInterestedInCampaign(auth, {
- campaignId: campaignId as string,
- leadEmail: email as string,
+ outputSchema: lemlistSchemas.lead,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.setInterestInCampaign({
+ apiKey: auth.secret_text,
+ campaignId: propsValue.campaignId,
+ lead: propsValue.email,
+ interested: false,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/pause-lead-from-all-or-specific-campaigns.ts b/packages/pieces/community/lemlist/src/lib/actions/pause-lead-from-all-or-specific-campaigns.ts
index 7007fc744ef..f45c4c075e2 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/pause-lead-from-all-or-specific-campaigns.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/pause-lead-from-all-or-specific-campaigns.ts
@@ -1,16 +1,21 @@
import { createAction, Property } from '@activepieces/pieces-framework';
-import { campaignsDropdown } from '../common/props';
import { lemlistAuth } from '../common/constants';
-import { lemlistApiService } from '../common/requests';
+import { campaignsDropdown } from '../common/props';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const pauseLeadFromAllOrSpecificCampaigns = createAction({
auth: lemlistAuth,
name: 'pauseLeadFromAllOrSpecificCampaigns',
- classification: 'DESTRUCTIVE',
+ classification: 'WRITE',
displayName: 'Pause Lead From All or Specific Campaigns',
description: 'Pause a lead’s outreach across all or specific campaigns.',
- audience: 'both',
- aiMetadata: { description: 'Pauses outreach sequencing for a lead, identified by email. Operates in two modes: supply a campaign to pause the lead only in that campaign, or leave the campaign empty to pause the lead across all campaigns. Idempotent: re-running leaves the lead paused.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Pauses outreach for a lead, identified by email, in one campaign or, with no campaign, in all campaigns. Reversible with Resume. Idempotent.',
+ idempotent: true,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'], required: false }),
email: Property.ShortText({
@@ -19,10 +24,13 @@ export const pauseLeadFromAllOrSpecificCampaigns = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { campaignId, email } }) {
- return await lemlistApiService.pauseLeadInSpecificOrAllCampaigns(auth, {
- campaignId: campaignId as string,
- leadEmail: email as string,
+ outputSchema: lemlistSchemas.leadList,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.setLeadPaused({
+ apiKey: auth.secret_text,
+ lead: propsValue.email,
+ campaignId: propsValue.campaignId,
+ paused: true,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-a-campaign.ts b/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-a-campaign.ts
index d0733e90db1..4f38350ae13 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-a-campaign.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-a-campaign.ts
@@ -1,16 +1,21 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const removeLeadFromACampaign = createAction({
auth: lemlistAuth,
name: 'removeLeadFromACampaign',
- classification: 'WRITE',
+ classification: 'DESTRUCTIVE',
displayName: 'Remove Lead from A Campaign',
- description: 'removes a lead from a specific campaign.',
- audience: 'both',
- aiMetadata: { description: 'Removes a lead, identified by email, from one specific Lemlist campaign, stopping their sequence in it. Requires both the campaign and the lead email. Idempotent: re-running on an already-removed lead leaves them absent from the campaign.', idempotent: true },
+ description: 'Removes a lead from a specific campaign.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Deletes a lead, identified by email, from one Lemlist campaign (its sequence progress is lost). A second run fails with not found.',
+ idempotent: false,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'] }),
email: Property.ShortText({
@@ -19,10 +24,13 @@ export const removeLeadFromACampaign = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { campaignId, email } }) {
- return await lemlistApiService.removeLeadFromACampaign(auth, {
- campaignId: campaignId as string,
- leadEmail: email as string,
+ outputSchema: lemlistSchemas.lead,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.deleteLeadFromCampaign({
+ apiKey: auth.secret_text,
+ campaignId: propsValue.campaignId,
+ lead: propsValue.email,
+ remove: true,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-unsubscribe-list.ts b/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-unsubscribe-list.ts
index 3f5d4fdd70b..404f3c3f4f0 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-unsubscribe-list.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/remove-lead-from-unsubscribe-list.ts
@@ -1,15 +1,20 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const removeLeadFromUnsubscribeList = createAction({
auth: lemlistAuth,
name: 'removeLeadFromUnsubscribeList',
classification: 'WRITE',
displayName: 'Remove Lead From Unsubscribe List',
- description: 'Remove a lead from “unsubscribe” list.',
+ description: 'Remove a lead from the “unsubscribe” list so lemlist can contact them again. Only do this when the person opted back in.',
audience: 'both',
- aiMetadata: { description: 'Removes a lead, identified by email, from the team-wide unsubscribe (do-not-contact) list so they become eligible for outreach again. Use to re-enable contacting a previously unsubscribed lead. Idempotent: re-running leaves the lead off the unsubscribe list.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Removes an email from the team-wide unsubscribe (do-not-contact) list so lemlist campaigns can email that person again. Only use when the person explicitly opted back in: contacting someone who unsubscribed can break anti-spam and privacy law. Fails with not found when the email is not on the list. Idempotent in effect: the email stays off the list.',
+ idempotent: true,
+ },
props: {
email: Property.ShortText({
displayName: 'Lead Email',
@@ -17,9 +22,8 @@ export const removeLeadFromUnsubscribeList = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { email } }) {
- return await lemlistApiService.removeLeadFromUnsubscribeList(auth, {
- leadEmail: email as string,
- });
+ outputSchema: lemlistSchemas.unsubscribe,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.removeFromUnsubscribes({ apiKey: auth.secret_text, email: propsValue.email });
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/resume-lead-from-all-or-specific-campaigns.ts b/packages/pieces/community/lemlist/src/lib/actions/resume-lead-from-all-or-specific-campaigns.ts
index d53c20cd5e8..90e3fb916fa 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/resume-lead-from-all-or-specific-campaigns.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/resume-lead-from-all-or-specific-campaigns.ts
@@ -1,16 +1,21 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const resumeLeadFromAllOrSpecificCampaigns = createAction({
auth: lemlistAuth,
name: 'resumeLeadFromAllOrSpecificCampaigns',
classification: 'WRITE',
displayName: 'Resume Lead From All or Specific Campaigns',
- description: 'Resume a lead’s outreach across all or specific campaigns.',
- audience: 'both',
- aiMetadata: { description: 'Resumes (restarts) outreach sequencing for a previously paused lead, identified by email. Operates in two modes: supply a campaign to resume the lead only in that campaign, or leave the campaign empty to resume across all campaigns. Idempotent: re-running leaves the lead active.', idempotent: true },
+ description: 'Resume a lead’s outreach across all or specific campaigns. Resumed leads can receive emails right away.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Resumes outreach for a paused lead, identified by email, in one campaign or, with no campaign, in all campaigns. Resumed leads can receive real emails from running campaigns. Idempotent.',
+ idempotent: true,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'], required: false }),
email: Property.ShortText({
@@ -19,10 +24,13 @@ export const resumeLeadFromAllOrSpecificCampaigns = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { campaignId, email } }) {
- return await lemlistApiService.resumeLeadInSpecificOrAllCampaigns(auth, {
- campaignId: campaignId as string,
- leadEmail: email as string,
+ outputSchema: lemlistSchemas.leadList,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.setLeadPaused({
+ apiKey: auth.secret_text,
+ lead: propsValue.email,
+ campaignId: propsValue.campaignId,
+ paused: false,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/search-lead.ts b/packages/pieces/community/lemlist/src/lib/actions/search-lead.ts
index 8fba2df1241..a3759bf03cd 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/search-lead.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/search-lead.ts
@@ -1,7 +1,9 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
+import { lemlistInput } from '../common/input';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const searchLead = createAction({
auth: lemlistAuth,
@@ -9,8 +11,12 @@ export const searchLead = createAction({
classification: 'READ',
displayName: 'Search Lead',
description: 'Look up a lead by email and campaign.',
- audience: 'both',
- aiMetadata: { description: 'Looks up a lead by email across the account and returns matching lead records. Operates in two modes: supply a campaign to filter results to that campaign, or leave it empty to return all campaigns the lead belongs to; returns a not-found result when no match exists. Idempotent read-only lookup.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Looks up the leads for one email across Lemlist campaigns, optionally filtered to one campaign. Returns found=false when nothing matches. Read-only.',
+ idempotent: true,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'], required: false }),
email: Property.ShortText({
@@ -19,29 +25,25 @@ export const searchLead = createAction({
required: true,
}),
},
+ outputSchema: lemlistSchemas.leadsByEmail,
async run({ auth, propsValue }) {
- const { email, campaignId } = propsValue as {
- email: string;
- campaignId: string;
- };
-
- const leads = await lemlistApiService.getLeadByEmail(auth, email);
-
- if (!Array.isArray(leads) || leads.length === 0) {
- return { found: false, message: `No leads found for ${email}` };
+ const email = lemlistInput.email({ value: propsValue.email, label: 'Lead Email' });
+ const campaignId = lemlistInput.optionalText(propsValue.campaignId);
+ const leads = await lemlistLeads.getLeadsByEmail({ apiKey: auth.secret_text, email });
+ if (leads.length === 0) {
+ return { found: false, message: `No leads found for ${email}`, leads: [] };
}
-
- const matching = campaignId
- ? leads.filter((lead) => lead.campaign.id === campaignId)
- : leads;
-
+ const matching =
+ campaignId === undefined
+ ? leads
+ : leads.filter((lead) => lemlistLeads.leadCampaignId(lead) === campaignId);
if (matching.length === 0) {
return {
found: false,
message: `Lead with email ${email} not found in campaign ${campaignId}`,
+ leads: [],
};
}
-
return { found: true, leads: matching };
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/unsubscribe-a-lead.ts b/packages/pieces/community/lemlist/src/lib/actions/unsubscribe-a-lead.ts
index c378d1874ca..4fc5c0917f1 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/unsubscribe-a-lead.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/unsubscribe-a-lead.ts
@@ -1,16 +1,21 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
-export const unsubscribeALead = createAction({
+export const unsubscribeALead = createAction({
auth: lemlistAuth,
name: 'unsubscribeALead',
classification: 'DESTRUCTIVE',
displayName: 'Unsubscribe a Lead',
description: 'Unsubscribe a lead from a campaign.',
- audience: 'both',
- aiMetadata: { description: 'Unsubscribes a lead, identified by email, from a specific Lemlist campaign, stopping further emails to them in it. Use to honor an opt-out or stop contacting a lead in one campaign; requires both the campaign and the lead email. Idempotent: re-running leaves the lead unsubscribed.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Unsubscribes a lead, identified by email, from one Lemlist campaign so it gets no more messages from it. Cannot be undone from this piece.',
+ idempotent: true,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'] }),
email: Property.ShortText({
@@ -19,10 +24,13 @@ export const unsubscribeALead = createAction({
required: true,
}),
},
- async run({ auth, propsValue: { campaignId, email } }) {
- return await lemlistApiService.unsubscribeLeadFromACampaign(auth, {
- campaignId: campaignId as string,
- leadEmail: email as string,
+ outputSchema: lemlistSchemas.unsubscribedLead,
+ async run({ auth, propsValue }) {
+ return lemlistLeads.deleteLeadFromCampaign({
+ apiKey: auth.secret_text,
+ campaignId: propsValue.campaignId,
+ lead: propsValue.email,
+ remove: false,
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/actions/update-lead-from-campaign.ts b/packages/pieces/community/lemlist/src/lib/actions/update-lead-from-campaign.ts
index 88ebf7972cd..93fe2b07557 100644
--- a/packages/pieces/community/lemlist/src/lib/actions/update-lead-from-campaign.ts
+++ b/packages/pieces/community/lemlist/src/lib/actions/update-lead-from-campaign.ts
@@ -1,17 +1,21 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
import { campaignsDropdown } from '../common/props';
-import { lemlistApiService } from '../common/requests';
+import { lemlistLeads } from '../common/requests';
+import { lemlistSchemas } from '../common/schemas';
export const updateLeadFromCampaign = createAction({
auth: lemlistAuth,
name: 'updateLeadFromCampaign',
classification: 'WRITE',
displayName: 'Update Lead From Campaign',
- description:
- 'Updates a lead in a specific campaign.',
- audience: 'both',
- aiMetadata: { description: 'Updates an existing lead\'s details (name, company, phone, LinkedIn, icebreaker, job title, etc.) within a specific Lemlist campaign, identified by the campaign and the lead\'s email. Use to edit profile fields on a lead already enrolled in a campaign. Idempotent: re-applying the same field values yields the same result.', idempotent: true },
+ description: 'Updates a lead in a specific campaign. Empty fields are left unchanged.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Updates the details of a lead already in a Lemlist campaign, identified by campaign and lead email. Only filled fields are sent. Idempotent.',
+ idempotent: true,
+ },
props: {
campaignId: campaignsDropdown({ refreshers: ['auth'] }),
email: Property.ShortText({
@@ -19,45 +23,33 @@ export const updateLeadFromCampaign = createAction({
description: 'The email of the lead to update.',
required: true,
}),
- firstName: Property.ShortText({
- displayName: 'First Name',
- required: false,
- }),
+ firstName: Property.ShortText({ displayName: 'First Name', required: false }),
lastName: Property.ShortText({ displayName: 'Last Name', required: false }),
- picture: Property.ShortText({
- displayName: 'Picture URL',
- required: false,
- }),
+ picture: Property.ShortText({ displayName: 'Picture URL', required: false }),
phone: Property.ShortText({ displayName: 'Phone', required: false }),
- linkedinUrl: Property.ShortText({
- displayName: 'LinkedIn URL',
- required: false,
- }),
- companyName: Property.ShortText({
- displayName: 'Company Name',
- required: false,
- }),
- companyDomain: Property.ShortText({
- displayName: 'Company Domain',
- required: false,
- }),
- icebreaker: Property.LongText({
- displayName: 'Icebreaker',
- required: false,
- }),
- jobTitle: Property.ShortText({ displayName: 'Job Title', required: false })
+ linkedinUrl: Property.ShortText({ displayName: 'LinkedIn URL', required: false }),
+ companyName: Property.ShortText({ displayName: 'Company Name', required: false }),
+ companyDomain: Property.ShortText({ displayName: 'Company Domain', required: false }),
+ icebreaker: Property.LongText({ displayName: 'Icebreaker', required: false }),
+ jobTitle: Property.ShortText({ displayName: 'Job Title', required: false }),
},
+ outputSchema: lemlistSchemas.leadWithWarnings,
async run({ auth, propsValue }) {
- const {
- campaignId,
- email,
- ...leadData
- } = propsValue as any;
-
- return await lemlistApiService.updateLeadFromCampaign(auth, {
- campaignId,
- leadEmail: email,
- leadData,
+ return lemlistLeads.updateLeadInCampaign({
+ apiKey: auth.secret_text,
+ campaignId: propsValue.campaignId,
+ lead: propsValue.email,
+ fields: {
+ firstName: propsValue.firstName,
+ lastName: propsValue.lastName,
+ picture: propsValue.picture,
+ phone: propsValue.phone,
+ linkedinUrl: propsValue.linkedinUrl,
+ companyName: propsValue.companyName,
+ companyDomain: propsValue.companyDomain,
+ icebreaker: propsValue.icebreaker,
+ jobTitle: propsValue.jobTitle,
+ },
});
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/common/ai-props.ts b/packages/pieces/community/lemlist/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..25b8ac69bff
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/ai-props.ts
@@ -0,0 +1,54 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const aiProps = {
+ campaignId: (required = true) =>
+ Property.ShortText({
+ displayName: 'Campaign ID',
+ description: 'lemlist campaign ID (starts with cam_). Use List Campaigns to find it.',
+ required,
+ }),
+ leadId: () =>
+ Property.ShortText({
+ displayName: 'Lead ID',
+ description: 'lemlist lead ID (starts with lea_), as returned by Create Lead in Campaign or Get Lead by Email.',
+ required: true,
+ }),
+ leadIdOrEmail: () =>
+ Property.ShortText({
+ displayName: 'Lead ID or Email',
+ description: 'The lead ID (lea_...) or the lead email address.',
+ required: true,
+ }),
+ leadEmail: () =>
+ Property.ShortText({
+ displayName: 'Lead Email',
+ description: 'Email address of the lead.',
+ required: true,
+ }),
+ limit: ({ max, fallback }: { max: number; fallback: number }) =>
+ Property.Number({
+ displayName: 'Limit',
+ description: `How many items to return (1-${max}). Default ${fallback}.`,
+ required: false,
+ }),
+ offset: () =>
+ Property.Number({
+ displayName: 'Offset',
+ description: 'How many items to skip, for paging. Default 0.',
+ required: false,
+ }),
+ triState: ({ displayName, description }: { displayName: string; description: string }) =>
+ Property.StaticDropdown<string, false>({
+ displayName,
+ description: `${description} Leave empty to keep the current setting.`,
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Yes', value: 'yes' },
+ { label: 'No', value: 'no' },
+ { label: 'Leave unchanged', value: 'unchanged' },
+ ],
+ },
+ }),
+};
diff --git a/packages/pieces/community/lemlist/src/lib/common/client.ts b/packages/pieces/community/lemlist/src/lib/common/client.ts
new file mode 100644
index 00000000000..6d8164b0817
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/client.ts
@@ -0,0 +1,225 @@
+import {
+ httpClient,
+ HttpMessageBody,
+ HttpMethod,
+ HttpRequest,
+} from '@activepieces/pieces-common';
+
+export const BASE_URL = 'https://api.lemlist.com/api';
+
+export class LemlistApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({
+ message,
+ status,
+ responseBody,
+ }: {
+ message: string;
+ status: number;
+ responseBody: unknown;
+ }) {
+ super(message);
+ this.name = 'LemlistApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export function isLemlistStatus({
+ error,
+ status,
+}: {
+ error: unknown;
+ status: number;
+}): boolean {
+ return error instanceof LemlistApiError && error.status === status;
+}
+
+function readHttpErrorResponse(
+ error: unknown
+): { status: number; body: unknown } | undefined {
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (!isRecord(response)) {
+ return undefined;
+ }
+ const status = response['status'];
+ if (typeof status !== 'number') {
+ return undefined;
+ }
+ return { status, body: response['body'] };
+}
+
+export function vendorDetail(responseBody: unknown): string | undefined {
+ let parsed = responseBody;
+ if (typeof parsed === 'string') {
+ const trimmed = parsed.trim();
+ if (trimmed.length === 0) {
+ return undefined;
+ }
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return trimmed.slice(0, 300);
+ }
+ }
+ if (!isRecord(parsed)) {
+ return undefined;
+ }
+ const nested = isRecord(parsed['error']) ? parsed['error']['message'] : undefined;
+ const detail = nested ?? parsed['message'] ?? parsed['error'];
+ return typeof detail === 'string' ? detail.slice(0, 300) : undefined;
+}
+
+const STATUS_MESSAGES: Record<number, string> = {
+ 400: 'lemlist rejected the request as invalid',
+ 401: 'lemlist rejected the API key. Check the API key in the lemlist connection',
+ 402: 'lemlist refused the request because the plan or credits do not allow it',
+ 403: 'lemlist refused the request: the plan or API key has no access to this resource',
+ 404: 'lemlist could not find the resource. Check the ID or email',
+ 405: 'lemlist does not allow this operation on the resource',
+ 409: 'lemlist reported a conflict with the current state of the resource',
+ 429: 'lemlist rate limit reached (20 requests per 2 seconds). Retry later',
+};
+
+export function buildLemlistError({
+ status,
+ responseBody,
+}: {
+ status: number;
+ responseBody: unknown;
+}): LemlistApiError {
+ const base =
+ STATUS_MESSAGES[status] ??
+ (status >= 500
+ ? 'lemlist returned a server error. Retry later'
+ : status >= 300 && status < 400
+ ? 'lemlist answered with an unexpected redirect, which was not followed'
+ : 'lemlist request failed');
+ const detail = vendorDetail(responseBody);
+ const message =
+ detail === undefined
+ ? `${base} (HTTP ${status}).`
+ : status === 403
+ ? `lemlist refused the request (HTTP 403): ${detail}`
+ : `${base} (HTTP ${status}): ${detail}`;
+ return new LemlistApiError({ message, status, responseBody });
+}
+
+export function buildLemlistUrl({
+ resourceUri,
+ query,
+}: {
+ resourceUri: string;
+ query?: LemlistQuery;
+}): string {
+ if (
+ !resourceUri.startsWith('/') ||
+ resourceUri.startsWith('//') ||
+ resourceUri.includes('?') ||
+ resourceUri.includes('#') ||
+ resourceUri.split('/').some((segment) => segment === '..' || segment === '.')
+ ) {
+ throw new Error(`Refusing to call lemlist with an unexpected path: ${resourceUri}`);
+ }
+ const url = new URL(BASE_URL + resourceUri);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null) {
+ continue;
+ }
+ url.searchParams.set(key, String(value));
+ }
+ }
+ return url.toString();
+}
+
+export function basicAuthHeader(apiKey: string): string {
+ return `Basic ${Buffer.from(`:${apiKey.trim()}`).toString('base64')}`;
+}
+
+async function sleep(ms: number): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function sendOnce<T extends HttpMessageBody>({
+ apiKey,
+ method,
+ resourceUri,
+ query,
+ body,
+}: LemlistApiCallParams): Promise<{ status: number; body: T }> {
+ const request: HttpRequest = {
+ method,
+ url: buildLemlistUrl({ resourceUri, query }),
+ headers: {
+ Authorization: basicAuthHeader(apiKey),
+ Accept: 'application/json',
+ },
+ body,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ timeout: TIMEOUT_MS,
+ };
+ try {
+ const response = await httpClient.sendRequest<T>(request);
+ if (response.status >= 300) {
+ throw buildLemlistError({ status: response.status, responseBody: response.body });
+ }
+ return { status: response.status, body: response.body };
+ } catch (error) {
+ if (error instanceof LemlistApiError) {
+ throw error;
+ }
+ const httpError = readHttpErrorResponse(error);
+ if (httpError === undefined) {
+ throw error;
+ }
+ throw buildLemlistError({ status: httpError.status, responseBody: httpError.body });
+ }
+}
+
+export async function lemlistApiRequest<T extends HttpMessageBody>(
+ params: LemlistApiCallParams
+): Promise<{ status: number; body: T }> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await sendOnce<T>(params);
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 429 }) && attempt < MAX_RATE_LIMIT_RETRIES) {
+ await sleep(RATE_LIMIT_WAIT_MS * (attempt + 1));
+ continue;
+ }
+ throw error;
+ }
+ }
+}
+
+export async function lemlistApiCall<T extends HttpMessageBody>(
+ params: LemlistApiCallParams
+): Promise<T> {
+ const response = await lemlistApiRequest<T>(params);
+ return response.body;
+}
+
+const TIMEOUT_MS = 30_000;
+const MAX_RATE_LIMIT_RETRIES = 2;
+const RATE_LIMIT_WAIT_MS = 2_000;
+
+export type LemlistQuery = Record<string, string | number | boolean | undefined | null>;
+
+export type LemlistApiCallParams = {
+ apiKey: string;
+ method: HttpMethod;
+ resourceUri: string;
+ query?: LemlistQuery;
+ body?: unknown;
+};
diff --git a/packages/pieces/community/lemlist/src/lib/common/constants.ts b/packages/pieces/community/lemlist/src/lib/common/constants.ts
index 6e32e36fcb9..4c68c56e3ab 100644
--- a/packages/pieces/community/lemlist/src/lib/common/constants.ts
+++ b/packages/pieces/community/lemlist/src/lib/common/constants.ts
@@ -1,43 +1,27 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { PieceAuth } from '@activepieces/pieces-framework';
-import { lemlistApiService } from './requests';
-import { AppConnectionType } from '@activepieces/pieces-framework';
-
-export const BASE_URL = 'https://api.lemlist.com/api';
+import { isLemlistStatus, lemlistApiCall } from './client';
export const lemlistAuth = PieceAuth.SecretText({
displayName: 'Lemlist API Key',
- description: `
-
- 1.Click on your profile picture in the bottom left-hand corner and click on Settings.
- 2.Go to the Integrations tab.
- 3.Click on Generate a new API key.
- 4.Store it securely because you won’t be able to see it again`,
+ description: `To get your API key:
+
+1. In lemlist, click your profile picture (bottom left) and open **Settings**.
+2. Go to **Integrations**.
+3. Click **Generate** next to API key and copy it. You won't see it again.`,
required: true,
validate: async ({ auth }) => {
try {
- await lemlistApiService.fetchTeams({
- secret_text: auth,
- type: AppConnectionType.SECRET_TEXT
- }).catch((err) => {
- throw err;
- });
-
- return {
- valid: true,
- };
- } catch (e: any) {
+ await lemlistApiCall({ apiKey: auth, method: HttpMethod.GET, resourceUri: '/team' });
+ return { valid: true };
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 401 }) || isLemlistStatus({ error, status: 403 })) {
+ return { valid: false, error: 'Invalid API key.' };
+ }
return {
valid: false,
- error: `Auth validation error: ${e.message}`,
+ error: 'Could not reach lemlist to check the API key. Try again in a moment.',
};
}
},
});
-
-export const API_ENDPOINTS = {
- TEAM: '/team',
- HOOKS: '/hooks',
- CAMPAIGNS: '/campaigns',
- LEADS: '/leads',
- UNSUBSCRIBES: '/unsubscribes',
-};
diff --git a/packages/pieces/community/lemlist/src/lib/common/events.ts b/packages/pieces/community/lemlist/src/lib/common/events.ts
new file mode 100644
index 00000000000..695d012882c
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/events.ts
@@ -0,0 +1,41 @@
+export const LEMLIST_EVENT_TYPES = [
+ 'contacted',
+ 'hooked',
+ 'attracted',
+ 'warmed',
+ 'interested',
+ 'notInterested',
+ 'emailsSent',
+ 'emailsOpened',
+ 'emailsClicked',
+ 'emailsReplied',
+ 'emailsBounced',
+ 'emailsFailed',
+ 'emailsInterested',
+ 'emailsNotInterested',
+ 'emailsUnsubscribed',
+ 'entityUnsubscribed',
+ 'variableUnsubscribed',
+ 'linkedinSent',
+ 'linkedinOpened',
+ 'linkedinReplied',
+ 'linkedinInterested',
+ 'linkedinNotInterested',
+ 'linkedinInviteDone',
+ 'linkedinInviteAccepted',
+ 'linkedinVisitDone',
+ 'whatsappReplied',
+ 'smsReplied',
+ 'apiInterested',
+ 'apiNotInterested',
+ 'manualInterested',
+ 'manualNotInterested',
+];
+
+export const LEMLIST_UNSUBSCRIBE_TYPES = [
+ 'emailsUnsubscribed',
+ 'entityUnsubscribed',
+ 'variableUnsubscribed',
+ 'apiUnsubscribed',
+ 'manualUnsubscribed',
+];
diff --git a/packages/pieces/community/lemlist/src/lib/common/input.ts b/packages/pieces/community/lemlist/src/lib/common/input.ts
new file mode 100644
index 00000000000..bdcf6aa5297
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/input.ts
@@ -0,0 +1,204 @@
+function requireText({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value === 'number') {
+ return String(value);
+ }
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const text = value.trim();
+ return text.length === 0 ? undefined : text;
+}
+
+function segment({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ if (text === '.' || text === '..' || /[\s/\\?#%]/.test(text)) {
+ throw new Error(`${label} "${text}" contains characters that are not allowed.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function email({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ if (!EMAIL_PATTERN.test(text)) {
+ throw new Error(`${label} "${text}" is not a valid email address.`);
+ }
+ return text;
+}
+
+function emailSegment({ value, label }: { value: unknown; label: string }): string {
+ return encodeURIComponent(email({ value, label }));
+}
+
+function idSegment({
+ value,
+ label,
+ prefix,
+}: {
+ value: unknown;
+ label: string;
+ prefix?: string;
+}): string {
+ const text = requireText({ value, label });
+ if (!ID_PATTERN.test(text) || (prefix !== undefined && !text.startsWith(`${prefix}_`))) {
+ const expected = prefix === undefined ? 'a lemlist ID' : `a lemlist ID starting with ${prefix}_`;
+ throw new Error(`${label} "${text}" is not ${expected}.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function leadIdOrEmailSegment({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ return text.includes('@')
+ ? emailSegment({ value: text, label })
+ : idSegment({ value: text, label, prefix: 'lea' });
+}
+
+function contactIdOrEmailSegment({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ return text.includes('@') ? emailSegment({ value: text, label }) : segment({ value: text, label });
+}
+
+function emailOrDomainSegment({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ if (text.includes('@')) {
+ return emailSegment({ value: text, label });
+ }
+ if (!DOMAIN_PATTERN.test(text)) {
+ throw new Error(`${label} "${text}" is not a valid email address or domain.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function boundedInt({
+ value,
+ label,
+ min,
+ max,
+}: {
+ value: unknown;
+ label: string;
+ min: number;
+ max: number;
+}): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = typeof value === 'number' ? value : Number(value);
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number between ${min} and ${max}.`);
+ }
+ return parsed;
+}
+
+function isoDate({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ const time = Date.parse(text);
+ if (Number.isNaN(time)) {
+ throw new Error(`${label} "${text}" is not a valid ISO 8601 date.`);
+ }
+ return new Date(time).toISOString();
+}
+
+function stringRecord({ value, label }: { value: unknown; label: string }): Record<string, string> {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`${label} must be an object of name/value pairs.`);
+ }
+ const out: Record<string, string> = {};
+ for (const [key, raw] of Object.entries(value)) {
+ const name = key.trim();
+ if (name.length === 0 || raw === undefined || raw === null) {
+ continue;
+ }
+ out[name] = typeof raw === 'string' ? raw : typeof raw === 'object' ? JSON.stringify(raw) : String(raw);
+ }
+ if (Object.keys(out).length === 0) {
+ throw new Error(`${label} needs at least one name/value pair.`);
+ }
+ return out;
+}
+
+function stringList({ value, label }: { value: unknown; label: string }): string[] {
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];
+ const items = raw
+ .map((item) => (typeof item === 'string' ? item.trim() : typeof item === 'number' ? String(item) : ''))
+ .filter((item) => item.length > 0);
+ if (items.length === 0) {
+ throw new Error(`${label} needs at least one value.`);
+ }
+ return [...new Set(items)];
+}
+
+function pick({ record, keys }: { record: Record<string, unknown>; keys: readonly string[] }): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const key of keys) {
+ out[key] = record[key];
+ }
+ return out;
+}
+
+function compact(record: Record<string, unknown>): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(record)) {
+ if (value === undefined || value === null) {
+ continue;
+ }
+ if (typeof value === 'string') {
+ const text = value.trim();
+ if (text.length === 0) {
+ continue;
+ }
+ out[key] = text;
+ continue;
+ }
+ out[key] = value;
+ }
+ return out;
+}
+
+const EMAIL_PATTERN = /^[^\s@/\\?#]{1,200}@[^\s@/\\?#]{1,200}\.[^\s@/\\?#]{1,60}$/;
+const DOMAIN_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}\.){1,10}[A-Za-z]{2,63}$/;
+const ID_PATTERN = /^[A-Za-z0-9_-]{1,100}$/;
+
+function triState(value: unknown): boolean | undefined {
+ if (typeof value === 'boolean') {
+ return value;
+ }
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const text = value.trim().toLowerCase();
+ if (text === 'yes' || text === 'true') {
+ return true;
+ }
+ if (text === 'no' || text === 'false') {
+ return false;
+ }
+ return undefined;
+}
+
+export const lemlistInput = {
+ triState,
+ requireText,
+ optionalText,
+ segment,
+ email,
+ emailSegment,
+ idSegment,
+ leadIdOrEmailSegment,
+ contactIdOrEmailSegment,
+ emailOrDomainSegment,
+ boundedInt,
+ isoDate,
+ stringRecord,
+ stringList,
+ compact,
+ pick,
+};
diff --git a/packages/pieces/community/lemlist/src/lib/common/props.ts b/packages/pieces/community/lemlist/src/lib/common/props.ts
index 9738305cd58..276a3198bd6 100644
--- a/packages/pieces/community/lemlist/src/lib/common/props.ts
+++ b/packages/pieces/community/lemlist/src/lib/common/props.ts
@@ -1,7 +1,51 @@
+import { HttpMethod } from '@activepieces/pieces-common';
import { Property } from '@activepieces/pieces-framework';
-import { lemlistApiService } from './requests';
+import { isRecord, lemlistApiCall } from './client';
import { lemlistAuth } from './constants';
+export async function fetchAllCampaigns({ apiKey }: { apiKey: string }): Promise<CampaignSummary[]> {
+ const campaigns: CampaignSummary[] = [];
+ const seen = new Set<string>();
+ for (let page = 0; page < MAX_CAMPAIGN_PAGES; page++) {
+ const body = await lemlistApiCall<unknown>({
+ apiKey,
+ method: HttpMethod.GET,
+ resourceUri: '/campaigns',
+ query: {
+ version: 'v2',
+ limit: CAMPAIGN_PAGE_SIZE,
+ offset: page * CAMPAIGN_PAGE_SIZE,
+ sortBy: 'createdAt',
+ sortOrder: 'desc',
+ },
+ });
+ const items = campaignItems(body);
+ let added = 0;
+ for (const item of items) {
+ const id = typeof item['_id'] === 'string' ? item['_id'] : undefined;
+ if (id === undefined || seen.has(id)) {
+ continue;
+ }
+ seen.add(id);
+ added++;
+ campaigns.push({
+ id,
+ name: typeof item['name'] === 'string' ? item['name'] : id,
+ status: typeof item['status'] === 'string' ? item['status'] : undefined,
+ });
+ }
+ if (items.length < CAMPAIGN_PAGE_SIZE || added === 0) {
+ break;
+ }
+ }
+ return campaigns;
+}
+
+export function campaignItems(body: unknown): Record<string, unknown>[] {
+ const list = Array.isArray(body) ? body : isRecord(body) && Array.isArray(body['campaigns']) ? body['campaigns'] : [];
+ return list.filter(isRecord);
+}
+
export const campaignsDropdown = ({
refreshers,
required = true,
@@ -12,9 +56,7 @@ export const campaignsDropdown = ({
Property.Dropdown({
auth: lemlistAuth,
displayName: 'Campaign',
- description: required
- ? 'Select a campaign'
- : 'Select a campaign (optional)',
+ description: required ? 'Select a campaign' : 'Select a campaign (optional)',
required,
refreshers,
async options({ auth }) {
@@ -25,22 +67,26 @@ export const campaignsDropdown = ({
options: [],
};
}
-
try {
- const campaigns = await lemlistApiService.fetchCampaigns(auth.secret_text);
-
+ const campaigns = await fetchAllCampaigns({ apiKey: auth.secret_text });
return {
- options: campaigns.map((c: any) => ({
- label: c.name,
- value: c._id,
+ disabled: false,
+ options: campaigns.map((campaign) => ({
+ label: campaign.status === undefined ? campaign.name : `${campaign.name} (${campaign.status})`,
+ value: campaign.id,
})),
};
- } catch (e) {
- console.error('Failed to fetch campaigns', e);
+ } catch (error) {
return {
+ disabled: true,
options: [],
- placeholder: 'Unable to load campaigns',
+ placeholder: `Unable to load campaigns: ${error instanceof Error ? error.message : 'unknown error'}`,
};
}
},
});
+
+const CAMPAIGN_PAGE_SIZE = 100;
+const MAX_CAMPAIGN_PAGES = 20;
+
+type CampaignSummary = { id: string; name: string; status: string | undefined };
diff --git a/packages/pieces/community/lemlist/src/lib/common/requests.ts b/packages/pieces/community/lemlist/src/lib/common/requests.ts
index 0c4371da6c9..011f7b99e24 100644
--- a/packages/pieces/community/lemlist/src/lib/common/requests.ts
+++ b/packages/pieces/community/lemlist/src/lib/common/requests.ts
@@ -1,265 +1,233 @@
-import {
- AuthenticationType,
- HttpMethod,
- httpClient,
-} from '@activepieces/pieces-common';
-import { API_ENDPOINTS, BASE_URL } from './constants';
-import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { lemlistAuth } from './constants';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { isLemlistStatus, isRecord, lemlistApiCall } from './client';
+import { lemlistInput } from './input';
-async function fireHttpRequest({
- method,
- path,
- auth,
- body,
+async function getLeadsByEmail({
+ apiKey,
+ email,
}: {
- method: HttpMethod;
- path: string;
- auth: string;
- body?: unknown;
-}) {
- return await httpClient
- .sendRequest({
- method,
- url: `${BASE_URL}${path}`,
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- },
- body,
- authentication: {
- type: AuthenticationType.BASIC,
- username: '',
- password: auth,
- },
- })
- .then((res) => res.body);
-}
-
-export const lemlistApiService = {
- async fetchTeams(auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>) {
- return await fireHttpRequest({
- path: `${API_ENDPOINTS.TEAM}`,
- method: HttpMethod.GET,
- auth: auth.secret_text,
- });
- },
- async getLeadByEmail(auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>, email: string) {
- return await fireHttpRequest({
- path: `${API_ENDPOINTS.LEADS}/${email}?version=v2`,
- method: HttpMethod.GET,
- auth: auth.secret_text,
- });
- },
- async fetchCampaigns(auth: string) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}?version=v2&sortBy=createdAt&sortOrder=desc`,
+ apiKey: string;
+ email: string;
+}): Promise<Record<string, unknown>[]> {
+ try {
+ const body = await lemlistApiCall<unknown>({
+ apiKey,
method: HttpMethod.GET,
- auth,
- });
- return response.campaigns;
- },
- async removeLeadFromACampaign(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { campaignId, leadEmail }: { campaignId: string; leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}/${campaignId}${API_ENDPOINTS.LEADS}/${leadEmail}?action=remove`,
- method: HttpMethod.DELETE,
- auth: auth.secret_text,
+ resourceUri: `/leads/${lemlistInput.emailSegment({ value: email, label: 'Lead Email' })}`,
+ query: { version: 'v2' },
});
- return response;
- },
- async addLeadToACampaign(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- {
- campaignId,
- leadEmail,
- leadData,
- deduplicate,
- linkedinEnrichment,
- findEmail,
- verifyEmail,
- findPhone,
- }: {
- campaignId: string;
- leadEmail: string;
- leadData?: Record<string, unknown>;
- deduplicate?: boolean;
- linkedinEnrichment?: boolean;
- findEmail?: boolean;
- verifyEmail?: boolean;
- findPhone?: boolean;
+ if (Array.isArray(body)) {
+ return body.filter(isRecord);
+ }
+ return isRecord(body) ? [body] : [];
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 404 })) {
+ return [];
}
- ) {
- const queryParams = new URLSearchParams();
- if (deduplicate) queryParams.append('deduplicate', 'true');
- if (linkedinEnrichment) queryParams.append('linkedinEnrichment', 'true');
- if (findEmail) queryParams.append('findEmail', 'true');
- if (verifyEmail) queryParams.append('verifyEmail', 'true');
- if (findPhone) queryParams.append('findPhone', 'true');
+ throw error;
+ }
+}
- const query = queryParams.toString() ? `?${queryParams.toString()}` : '';
+function leadCampaignId(lead: Record<string, unknown>): string | undefined {
+ const campaign = lead['campaign'];
+ if (isRecord(campaign)) {
+ const id = campaign['id'] ?? campaign['_id'];
+ if (typeof id === 'string') {
+ return id;
+ }
+ }
+ const direct = lead['campaignId'];
+ return typeof direct === 'string' ? direct : undefined;
+}
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}/${campaignId}${API_ENDPOINTS.LEADS}/${leadEmail}${query}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- body: leadData,
- });
+async function createLeadInCampaign({
+ apiKey,
+ campaignId,
+ email,
+ fields,
+ deduplicate,
+ linkedinEnrichment,
+ findEmail,
+ verifyEmail,
+ findPhone,
+}: {
+ apiKey: string;
+ campaignId: unknown;
+ email: unknown;
+ fields: Record<string, unknown>;
+ deduplicate?: boolean;
+ linkedinEnrichment?: boolean;
+ findEmail?: boolean;
+ verifyEmail?: boolean;
+ findPhone?: boolean;
+}): Promise<unknown> {
+ const leadEmail = lemlistInput.email({ value: email, label: 'Lead Email' });
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.POST,
+ resourceUri: `/campaigns/${lemlistInput.idSegment({ value: campaignId, label: 'Campaign ID', prefix: 'cam' })}/leads/`,
+ query: {
+ deduplicate: deduplicate === true ? true : undefined,
+ linkedinEnrichment: linkedinEnrichment === true ? true : undefined,
+ findEmail: findEmail === true ? true : undefined,
+ verifyEmail: verifyEmail === true ? true : undefined,
+ findPhone: findPhone === true ? true : undefined,
+ },
+ body: { ...lemlistInput.compact(fields), email: leadEmail },
+ });
+}
- return response;
- },
- async addLeadVariables(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { leadId, variables }: { leadId: string; variables: Record<string, unknown> }
- ) {
- const queryParams = new URLSearchParams();
- for (const [key, value] of Object.entries(variables)) {
- if (value !== undefined && value !== null) {
- queryParams.append(key, String(value));
- }
- }
+async function updateLeadInCampaign({
+ apiKey,
+ campaignId,
+ lead,
+ fields,
+}: {
+ apiKey: string;
+ campaignId: unknown;
+ lead: unknown;
+ fields: Record<string, unknown>;
+}): Promise<unknown> {
+ const body = lemlistInput.compact(fields);
+ if (Object.keys(body).length === 0) {
+ throw new Error('Provide at least one field to update.');
+ }
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.PATCH,
+ resourceUri: `/campaigns/${campaignSegment(campaignId)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: lead, label: 'Lead' })}`,
+ body,
+ });
+}
- const query = queryParams.toString() ? `?${queryParams.toString()}` : '';
+async function deleteLeadFromCampaign({
+ apiKey,
+ campaignId,
+ lead,
+ remove,
+}: {
+ apiKey: string;
+ campaignId: unknown;
+ lead: unknown;
+ remove: boolean;
+}): Promise<unknown> {
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.DELETE,
+ resourceUri: `/campaigns/${campaignSegment(campaignId)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: lead, label: 'Lead' })}`,
+ query: { action: remove ? 'remove' : undefined },
+ });
+}
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.LEADS}/${leadId}/variables${query}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
+async function setInterestInCampaign({
+ apiKey,
+ campaignId,
+ lead,
+ interested,
+}: {
+ apiKey: string;
+ campaignId: unknown;
+ lead: unknown;
+ interested: boolean;
+}): Promise<unknown> {
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.POST,
+ resourceUri: `/campaigns/${campaignSegment(campaignId)}/leads/${lemlistInput.leadIdOrEmailSegment({ value: lead, label: 'Lead' })}/${interested ? 'interested' : 'notinterested'}`,
+ });
+}
- return response;
- },
- async updateLeadFromCampaign(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- {
- campaignId,
- leadEmail,
- leadData,
- }: {
- campaignId: string;
- leadEmail: string;
- leadData?: Record<string, unknown>;
- }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}/${campaignId}${API_ENDPOINTS.LEADS}/${leadEmail}`,
- method: HttpMethod.PATCH,
- auth: auth.secret_text,
- body: leadData,
- });
+async function setInterestEverywhere({
+ apiKey,
+ lead,
+ interested,
+}: {
+ apiKey: string;
+ lead: unknown;
+ interested: boolean;
+}): Promise<unknown> {
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/${interested ? 'interested' : 'notinterested'}/${lemlistInput.leadIdOrEmailSegment({ value: lead, label: 'Lead' })}`,
+ });
+}
- return response;
- },
- async unsubscribeLeadFromACampaign(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { campaignId, leadEmail }: { campaignId: string; leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}/${campaignId}${API_ENDPOINTS.LEADS}/${leadEmail}`,
- method: HttpMethod.DELETE,
- auth: auth.secret_text,
- });
- return response;
- },
- async markLeadAsInterestedInCampaign(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { campaignId, leadEmail }: { campaignId: string; leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}/${campaignId}${API_ENDPOINTS.LEADS}/${leadEmail}/interested`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
- return response;
- },
- async markLeadAsInterestedInAllCampaigns(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { leadEmail }: { leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.LEADS}/interested/${leadEmail}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
- return response;
- },
- async markLeadAsNotInterestedInAllCampaigns(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { leadEmail }: { leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.LEADS}/notinterested/${leadEmail}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
- return response;
- },
- async markLeadAsNotInterestedInCampaign(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { campaignId, leadEmail }: { campaignId: string; leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.CAMPAIGNS}/${campaignId}${API_ENDPOINTS.LEADS}/${leadEmail}/notinterested`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
- return response;
- },
- async pauseLeadInSpecificOrAllCampaigns(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { campaignId, leadEmail }: { campaignId?: string; leadEmail: string }
- ) {
- const query = campaignId ? `?campaignId=${campaignId}` : '';
+async function setLeadPaused({
+ apiKey,
+ lead,
+ campaignId,
+ paused,
+}: {
+ apiKey: string;
+ lead: unknown;
+ campaignId?: unknown;
+ paused: boolean;
+}): Promise<unknown> {
+ const campaign = lemlistInput.optionalText(campaignId);
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.POST,
+ resourceUri: `/leads/${paused ? 'pause' : 'start'}/${lemlistInput.leadIdOrEmailSegment({ value: lead, label: 'Lead' })}`,
+ query: {
+ campaignId: campaign === undefined ? undefined : decodeURIComponent(campaignSegment(campaign)),
+ },
+ });
+}
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.LEADS}/pause/${leadEmail}${query}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
+async function writeLeadVariables({
+ apiKey,
+ leadId,
+ variables,
+ method,
+}: {
+ apiKey: string;
+ leadId: unknown;
+ variables: unknown;
+ method: HttpMethod.POST | HttpMethod.PATCH;
+}): Promise<unknown> {
+ return lemlistApiCall({
+ apiKey,
+ method,
+ resourceUri: `/leads/${lemlistInput.idSegment({ value: leadId, label: 'Lead ID', prefix: 'lea' })}/variables`,
+ body: lemlistInput.stringRecord({ value: variables, label: 'Custom Variables' }),
+ });
+}
- return response;
- },
- async resumeLeadInSpecificOrAllCampaigns(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { campaignId, leadEmail }: { campaignId?: string; leadEmail: string }
- ) {
- const query = campaignId ? `?campaignId=${campaignId}` : '';
+async function removeFromUnsubscribes({
+ apiKey,
+ email,
+}: {
+ apiKey: string;
+ email: unknown;
+}): Promise<unknown> {
+ return lemlistApiCall({
+ apiKey,
+ method: HttpMethod.DELETE,
+ resourceUri: `/unsubscribes/${lemlistInput.emailOrDomainSegment({ value: email, label: 'Email' })}`,
+ });
+}
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.LEADS}/start/${leadEmail}${query}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- });
+function campaignSegment(value: unknown): string {
+ return lemlistInput.idSegment({ value, label: 'Campaign ID', prefix: 'cam' });
+}
- return response;
- },
- async removeLeadFromUnsubscribeList(
- auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>,
- { leadEmail }: { leadEmail: string }
- ) {
- const response = await fireHttpRequest({
- path: `${API_ENDPOINTS.UNSUBSCRIBES}/${leadEmail}`,
- method: HttpMethod.DELETE,
- auth: auth.secret_text,
- });
+function asLeadList(body: unknown): { leads: unknown[]; count: number } {
+ const leads = Array.isArray(body) ? body : body === undefined || body === null || body === '' ? [] : [body];
+ return { leads, count: leads.length };
+}
- return response;
- },
- async createWebhook(auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>, payload: any) {
- return await fireHttpRequest({
- path: `${API_ENDPOINTS.HOOKS}`,
- method: HttpMethod.POST,
- auth: auth.secret_text,
- body: payload,
- });
- },
- async deleteWebhook(auth: AppConnectionValueForAuthProperty<typeof lemlistAuth>, webhookId: string) {
- return await fireHttpRequest({
- path: `${API_ENDPOINTS.HOOKS}/${webhookId}`,
- method: HttpMethod.DELETE,
- auth: auth.secret_text,
- });
- },
+export const lemlistLeads = {
+ getLeadsByEmail,
+ leadCampaignId,
+ createLeadInCampaign,
+ updateLeadInCampaign,
+ deleteLeadFromCampaign,
+ setInterestInCampaign,
+ setInterestEverywhere,
+ setLeadPaused,
+ writeLeadVariables,
+ removeFromUnsubscribes,
+ campaignSegment,
+ asLeadList,
};
diff --git a/packages/pieces/community/lemlist/src/lib/common/results.ts b/packages/pieces/community/lemlist/src/lib/common/results.ts
new file mode 100644
index 00000000000..0693f1e9665
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/results.ts
@@ -0,0 +1,42 @@
+import { isRecord } from './client';
+
+function records(value: unknown): Record<string, unknown>[] {
+ return Array.isArray(value) ? value.filter(isRecord) : [];
+}
+
+function listFrom({ body, key }: { body: unknown; key?: string }): Record<string, unknown>[] {
+ if (Array.isArray(body)) {
+ return records(body);
+ }
+ if (isRecord(body)) {
+ if (key !== undefined && Array.isArray(body[key])) {
+ return records(body[key]);
+ }
+ if (Array.isArray(body['data'])) {
+ return records(body['data']);
+ }
+ }
+ return [];
+}
+
+function page({
+ items,
+ offset,
+ limit,
+}: {
+ items: Record<string, unknown>[];
+ offset: number;
+ limit: number;
+}): { items: Record<string, unknown>[]; count: number; offset: number; has_more: boolean } {
+ return { items, count: items.length, offset, has_more: items.length >= limit };
+}
+
+function numberField({ body, key }: { body: unknown; key: string }): number | undefined {
+ if (!isRecord(body)) {
+ return undefined;
+ }
+ const value = body[key];
+ return typeof value === 'number' ? value : undefined;
+}
+
+export const lemlistResults = { records, listFrom, page, numberField };
diff --git a/packages/pieces/community/lemlist/src/lib/common/sample.ts b/packages/pieces/community/lemlist/src/lib/common/sample.ts
new file mode 100644
index 00000000000..db2015816df
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/sample.ts
@@ -0,0 +1,31 @@
+export const SAMPLE_ACTIVITY = {
+ _id: 'act_PbKqTGpQqSlPcoOZ5',
+ type: 'emailsReplied',
+ teamId: 'tea_8QvkOiBfPdb2ZRhHi',
+ createdAt: '2026-10-13T08:07:38.375Z',
+ campaignId: 'cam_bSn8EORHQxbWPjHvu',
+ campaignName: 'Product Launch Campaign',
+ sequenceId: 'seq_9brn1aEKdYbDerkqq',
+ sequenceStep: 1,
+ stepId: 'stp_qsTl0LO6zkQQJQqsP',
+ leadId: 'lea_fiDpiGV585wy3Oii2',
+ contactId: 'ctc_xW8Ou6C03Csv8vatp',
+ leadEmail: '[email protected]',
+ leadFirstName: 'Jane',
+ leadLastName: 'Doe',
+ leadCompanyName: 'Acme Inc',
+ email: '[email protected]',
+ firstName: 'Jane',
+ lastName: 'Doe',
+ sendUserId: 'usr_ahfFktBBHUIxbVG5P',
+ sendUserEmail: '[email protected]',
+ sendUserName: 'Sam Seller',
+ subject: 'Quick question',
+};
+
+export const SAMPLE_UNSUBSCRIBE = {
+ ...SAMPLE_ACTIVITY,
+ _id: 'act_Uns1bscr1b3dXyz12',
+ type: 'entityUnsubscribed',
+ subject: undefined,
+};
diff --git a/packages/pieces/community/lemlist/src/lib/common/schemas.ts b/packages/pieces/community/lemlist/src/lib/common/schemas.ts
new file mode 100644
index 00000000000..92c5cf3a6e3
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/schemas.ts
@@ -0,0 +1,553 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+function pageSchema({
+ label,
+ labelKey,
+ itemFields,
+}: {
+ label: string;
+ labelKey: string;
+ itemFields: OutputSchemaField[];
+}): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label, labelKey, listItems: itemFields },
+ { key: 'count', label: 'Items Returned', format: 'number' },
+ { key: 'offset', label: 'Offset', format: 'number' },
+ {
+ key: 'has_more',
+ label: 'Has More',
+ format: 'boolean',
+ description: 'True when the page was full; call again with Offset + Limit to get more.',
+ },
+ ],
+ };
+}
+
+const leadFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Lead ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'firstName', label: 'First Name' },
+ { key: 'lastName', label: 'Last Name' },
+ { key: 'companyName', label: 'Company Name' },
+ { key: 'companyDomain', label: 'Company Domain' },
+ { key: 'jobTitle', label: 'Job Title' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'isPaused', label: 'Is Paused', format: 'boolean' },
+ { key: 'emailStatus', label: 'Email Status' },
+];
+
+const createdLeadFields: OutputSchemaField[] = [
+ ...leadFields,
+ { key: 'campaignName', label: 'Campaign Name' },
+ { key: 'icebreaker', label: 'Icebreaker' },
+ { key: 'phone', label: 'Phone' },
+ { key: 'linkedinUrl', label: 'LinkedIn URL', format: 'url' },
+];
+
+const leadByEmailFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Lead ID' },
+ { key: 'state', label: 'State' },
+ { key: 'status', label: 'Status' },
+ { key: 'isPaused', label: 'Is Paused', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'updatedAt', label: 'Updated At', format: 'datetime' },
+ { key: 'source', label: 'Source' },
+ { key: 'variables', label: 'Variables', description: 'Lead variables (firstName, companyName, custom variables...).' },
+ {
+ key: 'campaign',
+ label: 'Campaign',
+ children: [
+ { key: 'id', label: 'Campaign ID' },
+ { key: 'name', label: 'Campaign Name' },
+ { key: 'status', label: 'Campaign Status' },
+ ],
+ },
+ { key: 'sendingUser', label: 'Sending User', children: [{ key: 'email', label: 'Sender Email' }] },
+];
+
+const campaignFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Campaign ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'status', label: 'Status' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'createdBy', label: 'Created By (User ID)' },
+ { key: 'timezone', label: 'Timezone' },
+ { key: 'labels', label: 'Labels' },
+ { key: 'hasError', label: 'Has Error', format: 'boolean' },
+ { key: 'errors', label: 'Errors' },
+ { key: 'sequenceId', label: 'Sequence ID' },
+];
+
+const activityFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Activity ID' },
+ { key: 'type', label: 'Event Type' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'campaignName', label: 'Campaign Name' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'leadEmail', label: 'Lead Email', format: 'email' },
+ { key: 'leadFirstName', label: 'Lead First Name' },
+ { key: 'leadLastName', label: 'Lead Last Name' },
+ { key: 'leadCompanyName', label: 'Lead Company Name' },
+ { key: 'email', label: 'Contact Email', format: 'email' },
+ { key: 'firstName', label: 'Contact First Name' },
+ { key: 'lastName', label: 'Contact Last Name' },
+ { key: 'sequenceId', label: 'Sequence ID' },
+ { key: 'sequenceStep', label: 'Sequence Step', format: 'number' },
+ { key: 'stepId', label: 'Step ID' },
+ { key: 'sendUserId', label: 'Sender User ID' },
+ { key: 'sendUserEmail', label: 'Sender Email', format: 'email' },
+ { key: 'sendUserName', label: 'Sender Name' },
+ { key: 'subject', label: 'Email Subject' },
+ { key: 'teamId', label: 'Team ID' },
+];
+
+const contactFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Contact ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'fullName', label: 'Full Name' },
+ { key: 'fields', label: 'Fields', description: 'Contact fields such as firstName, lastName, jobTitle, custom fields.' },
+ {
+ key: 'campaigns',
+ label: 'Campaigns',
+ labelKey: 'campaignId',
+ listItems: [
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'campaignState', label: 'Campaign State' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'leadState', label: 'Lead State' },
+ ],
+ },
+ { key: 'ownerId', label: 'Owner User ID' },
+ { key: 'unsubscribed', label: 'Unsubscribed', format: 'boolean' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'firstName', label: 'First Name', description: 'Returned by List Contacts (Get Contact puts it under Fields).' },
+ { key: 'lastName', label: 'Last Name', description: 'Returned by List Contacts (Get Contact puts it under Fields).' },
+ { key: 'campaignCount', label: 'Campaign Count', format: 'number' },
+];
+
+const companyFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Company ID' },
+ { key: 'domain', label: 'Domain' },
+ { key: 'linkedinUrl', label: 'LinkedIn URL', format: 'url' },
+ { key: 'fields', label: 'Fields', description: 'Company fields such as name, industry, location.' },
+ { key: 'ownerId', label: 'Owner User ID' },
+ { key: 'source', label: 'Source' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+];
+
+const noteFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Note ID' },
+ { key: 'note', label: 'Note' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'companyId', label: 'Company ID' },
+ { key: 'userId', label: 'Author User ID' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+];
+
+const taskFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Task ID' },
+ { key: 'type', label: 'Type' },
+ { key: 'title', label: 'Title' },
+ { key: 'content', label: 'Message' },
+ { key: 'priority', label: 'Priority', format: 'number' },
+ { key: 'dueDate', label: 'Due Date', format: 'datetime' },
+ { key: 'userId', label: 'Assigned User ID' },
+ { key: 'leadId', label: 'Lead ID' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'leadFirstName', label: 'Lead First Name' },
+ { key: 'leadLastName', label: 'Lead Last Name' },
+ { key: 'ownerName', label: 'Assignee Name' },
+ { key: 'manual', label: 'Manual Task', format: 'boolean' },
+];
+
+const unsubscribeFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Unsubscribe ID' },
+ { key: 'value', label: 'Email or Domain' },
+ { key: 'source', label: 'Source' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+];
+
+const labelFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Label ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'color', label: 'Color' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+];
+
+const webhookFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Webhook ID' },
+ { key: 'targetUrl', label: 'Target URL', format: 'url' },
+ { key: 'type', label: 'Event Type' },
+ { key: 'campaignId', label: 'Campaign ID' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'disabled', label: 'Disabled', format: 'boolean' },
+ { key: 'disabledReason', label: 'Disabled Reason' },
+];
+
+const scheduleFields: OutputSchemaField[] = [
+ { key: '_id', label: 'Schedule ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'timezone', label: 'Timezone' },
+ { key: 'start', label: 'Start Time' },
+ { key: 'end', label: 'End Time' },
+ { key: 'weekdays', label: 'Weekdays' },
+ { key: 'secondsToWait', label: 'Seconds Between Emails', format: 'number' },
+];
+
+const warningsField: OutputSchemaField = {
+ key: 'warnings',
+ label: 'Warnings',
+ labelKey: 'code',
+ listItems: [
+ { key: 'code', label: 'Code' },
+ { key: 'message', label: 'Message' },
+ ],
+};
+
+export const lemlistSchemas = {
+ lead: { fields: leadFields },
+ leadWithWarnings: {
+ fields: [
+ ...leadFields,
+ { key: 'campaignName', label: 'Campaign Name' },
+ { key: 'leadUrl', label: 'Lead API URL', format: 'url' },
+ warningsField,
+ ],
+ },
+ createdLead: { fields: [...createdLeadFields, warningsField] },
+ leadList: { fields: leadFields, itemLabel: '{email}' },
+ leadsByEmail: {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'message', label: 'Message' },
+ { key: 'leads', label: 'Leads', labelKey: 'campaign.name', listItems: leadByEmailFields },
+ ],
+ },
+ unsubscribedLead: { fields: leadFields },
+ deletedLead: {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'alreadyRemoved', label: 'Was Already Removed', format: 'boolean' },
+ { key: 'lead', label: 'Lead', children: leadFields },
+ ],
+ },
+ leadState: {
+ fields: [
+ { key: 'leads', label: 'Leads Updated', labelKey: 'campaignId', listItems: leadFields },
+ { key: 'count', label: 'Leads Updated', format: 'number' },
+ ],
+ },
+ variables: {
+ fields: [{ key: 'ok', label: 'OK', format: 'boolean' }, warningsField],
+ },
+ ok: { fields: [{ key: 'ok', label: 'OK', format: 'boolean' }] },
+ team: {
+ fields: [
+ { key: '_id', label: 'Team ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'userIds', label: 'User IDs' },
+ {
+ key: 'users',
+ label: 'Users',
+ labelKey: 'email',
+ listItems: [
+ { key: 'userId', label: 'User ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'role', label: 'Role' },
+ ],
+ },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ ],
+ },
+ senders: pageSchema({
+ label: 'Senders',
+ labelKey: 'userId',
+ itemFields: [
+ { key: 'userId', label: 'User ID' },
+ {
+ key: 'campaigns',
+ label: 'Campaigns',
+ labelKey: 'name',
+ listItems: [
+ { key: '_id', label: 'Campaign ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'status', label: 'Status' },
+ ],
+ },
+ ],
+ }),
+ credits: {
+ fields: [
+ { key: 'credits', label: 'Credits Left', format: 'number' },
+ {
+ key: 'details',
+ label: 'Details',
+ children: [
+ {
+ key: 'remaining',
+ label: 'Remaining',
+ children: [
+ { key: 'total', label: 'Total', format: 'number' },
+ { key: 'subscription', label: 'Subscription', format: 'number' },
+ { key: 'paid', label: 'Paid', format: 'number' },
+ { key: 'gifted', label: 'Gifted', format: 'number' },
+ { key: 'freemium', label: 'Freemium', format: 'number' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ campaign: { fields: campaignFields },
+ campaignDetails: {
+ fields: [
+ ...campaignFields,
+ {
+ key: 'senders',
+ label: 'Senders',
+ labelKey: 'email',
+ listItems: [
+ { key: 'id', label: 'User ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'sendUserMailboxId', label: 'Mailbox ID' },
+ ],
+ },
+ {
+ key: 'creator',
+ label: 'Creator',
+ children: [
+ { key: 'userId', label: 'Creator User ID' },
+ { key: 'userEmail', label: 'Creator Email', format: 'email' },
+ ],
+ },
+ ],
+ },
+ campaignPage: pageSchema({ label: 'Campaigns', labelKey: 'name', itemFields: campaignFields }),
+ createdCampaign: {
+ fields: [
+ { key: '_id', label: 'Campaign ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'state', label: 'State' },
+ { key: 'sequenceId', label: 'Sequence ID' },
+ { key: 'scheduleIds', label: 'Schedule IDs' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ ],
+ },
+ updatedCampaign: {
+ fields: [
+ { key: 'name', label: 'Name' },
+ { key: 'stopOnEmailReplied', label: 'Stop on Email Replied', format: 'boolean' },
+ { key: 'stopOnMeetingBooked', label: 'Stop on Meeting Booked', format: 'boolean' },
+ { key: 'stopOnLinkClicked', label: 'Stop on Link Clicked', format: 'boolean' },
+ { key: 'disableTrackOpen', label: 'Open Tracking Disabled', format: 'boolean' },
+ { key: 'disableTrackClick', label: 'Click Tracking Disabled', format: 'boolean' },
+ ],
+ },
+ campaignState: {
+ fields: [
+ { key: '_id', label: 'Campaign ID' },
+ { key: 'state', label: 'State' },
+ ],
+ },
+ campaignStats: {
+ fields: [
+ { key: 'nbLeads', label: 'Leads', format: 'number' },
+ { key: 'nbLeadsLaunched', label: 'Leads Launched', format: 'number' },
+ { key: 'nbLeadsReached', label: 'Leads Reached', format: 'number' },
+ { key: 'nbLeadsOpened', label: 'Leads Opened', format: 'number' },
+ { key: 'nbLeadsInteracted', label: 'Leads Interacted', format: 'number' },
+ { key: 'nbLeadsAnswered', label: 'Leads Answered', format: 'number' },
+ { key: 'nbLeadsInterested', label: 'Leads Interested', format: 'number' },
+ { key: 'nbLeadsNotInterested', label: 'Leads Not Interested', format: 'number' },
+ { key: 'nbLeadsUnsubscribed', label: 'Leads Unsubscribed', format: 'number' },
+ { key: 'messagesSent', label: 'Messages Sent', format: 'number' },
+ { key: 'messagesBounced', label: 'Messages Bounced', format: 'number' },
+ { key: 'delivered', label: 'Delivered', format: 'number' },
+ { key: 'opened', label: 'Opened', format: 'number' },
+ { key: 'clicked', label: 'Clicked', format: 'number' },
+ { key: 'replied', label: 'Replied', format: 'number' },
+ { key: 'meetingBooked', label: 'Meetings Booked', format: 'number' },
+ { key: 'nbLeadsInterrupted', label: 'Leads Interrupted', format: 'number' },
+ { key: 'messagesNotSent', label: 'Messages Not Sent', format: 'number' },
+ { key: 'invitationAccepted', label: 'LinkedIn Invitations Accepted', format: 'number' },
+ { key: 'perChannel', label: 'Per Channel', description: 'Counts per channel (email, linkedin, ...): sent, delivered, opened, clicked, replied, bounced.' },
+ {
+ key: 'steps',
+ label: 'Steps',
+ labelKey: 'index',
+ listItems: [
+ { key: 'index', label: 'Index', format: 'number' },
+ { key: 'taskType', label: 'Step Type' },
+ { key: 'sent', label: 'Sent', format: 'number' },
+ { key: 'opened', label: 'Opened', format: 'number' },
+ { key: 'clicked', label: 'Clicked', format: 'number' },
+ { key: 'replied', label: 'Replied', format: 'number' },
+ { key: 'bounced', label: 'Bounced', format: 'number' },
+ ],
+ },
+ ],
+ },
+ sequences: {
+ fields: [
+ {
+ key: 'sequences',
+ label: 'Sequences',
+ labelKey: '_id',
+ listItems: [
+ { key: '_id', label: 'Sequence ID' },
+ {
+ key: 'steps',
+ label: 'Steps',
+ labelKey: 'index',
+ listItems: [
+ { key: '_id', label: 'Step ID' },
+ { key: 'index', label: 'Index', format: 'number' },
+ { key: 'type', label: 'Type' },
+ { key: 'delay', label: 'Delay (days)', format: 'number' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'message', label: 'Message', format: 'html' },
+ ],
+ },
+ ],
+ },
+ { key: 'count', label: 'Sequences', format: 'number' },
+ ],
+ },
+ schedules: {
+ fields: [
+ { key: 'items', label: 'Schedules', labelKey: 'name', listItems: scheduleFields },
+ { key: 'count', label: 'Schedules Returned', format: 'number' },
+ ],
+ },
+ campaignLeads: pageSchema({
+ label: 'Leads',
+ labelKey: '_id',
+ itemFields: [
+ { key: '_id', label: 'Lead ID' },
+ { key: 'contactId', label: 'Contact ID' },
+ { key: 'state', label: 'State' },
+ ],
+ }),
+ enrichment: {
+ fields: [{ key: 'id', label: 'Enrichment ID', description: 'Pass to Get Enrichment Result.' }],
+ },
+ enrichmentResult: {
+ fields: [
+ { key: 'enrichmentId', label: 'Enrichment ID' },
+ { key: 'done', label: 'Done', format: 'boolean' },
+ { key: 'enrichmentStatus', label: 'Status' },
+ { key: 'input', label: 'Input' },
+ { key: 'data', label: 'Data', description: 'Found email, phone or LinkedIn data.' },
+ ],
+ },
+ activity: { fields: activityFields },
+ activityPage: pageSchema({ label: 'Activities', labelKey: 'type', itemFields: activityFields }),
+ unsubscribePage: pageSchema({ label: 'Unsubscribes', labelKey: 'value', itemFields: unsubscribeFields }),
+ unsubscribeStatus: {
+ fields: [
+ { key: 'unsubscribed', label: 'Unsubscribed', format: 'boolean' },
+ { key: 'record', label: 'Record', children: unsubscribeFields },
+ ],
+ },
+ unsubscribe: {
+ fields: [
+ { key: '_id', label: 'Unsubscribe ID' },
+ { key: 'value', label: 'Email or Domain' },
+ { key: 'email', label: 'Email', format: 'email' },
+ ],
+ },
+ contact: { fields: contactFields },
+ contactLookup: {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'contact', label: 'Contact', children: contactFields },
+ ],
+ },
+ upsertResult: {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ {
+ key: 'data',
+ label: 'Record',
+ children: [
+ { key: '_id', label: 'ID' },
+ { key: 'created', label: 'Created', format: 'boolean' },
+ { key: 'updated', label: 'Updated', format: 'boolean' },
+ { key: 'fields', label: 'Fields' },
+ ],
+ },
+ warningsField,
+ ],
+ },
+ contactPage: pageSchema({ label: 'Contacts', labelKey: 'email', itemFields: contactFields }),
+ company: { fields: companyFields },
+ companyPage: pageSchema({ label: 'Companies', labelKey: 'domain', itemFields: companyFields }),
+ note: { fields: noteFields },
+ notePage: {
+ fields: [
+ { key: 'items', label: 'Notes', labelKey: 'note', listItems: noteFields },
+ { key: 'total', label: 'Total Notes', format: 'number' },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ ],
+ },
+ messages: {
+ fields: [
+ {
+ key: 'items',
+ label: 'Messages',
+ labelKey: 'type',
+ listItems: [
+ { key: '_id', label: 'Activity ID' },
+ { key: 'type', label: 'Type' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'message', label: 'Message', format: 'html' },
+ ],
+ },
+ { key: 'count', label: 'Items Returned', format: 'number' },
+ { key: 'total', label: 'Total Messages', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ ],
+ },
+ sentEmail: {
+ fields: [
+ { key: 'ok', label: 'Sent', format: 'boolean' },
+ { key: 'contactId', label: 'Contact ID' },
+ ],
+ },
+ labels: {
+ fields: [
+ { key: 'items', label: 'Labels', labelKey: 'name', listItems: labelFields },
+ { key: 'count', label: 'Labels Returned', format: 'number' },
+ ],
+ },
+ label: { fields: labelFields },
+ task: { fields: taskFields },
+ taskPage: {
+ fields: [
+ { key: 'items', label: 'Tasks', labelKey: 'title', listItems: taskFields },
+ { key: 'count', label: 'Items Returned', format: 'number' },
+ { key: 'page', label: 'Page', format: 'number' },
+ ],
+ },
+ ignoredTasks: {
+ fields: [
+ { key: 'ignored', label: 'Ignored Task IDs' },
+ { key: 'count', label: 'Tasks Ignored', format: 'number' },
+ { key: 'response', label: 'lemlist Response', description: 'Raw lemlist reply (an empty object on success).' },
+ ],
+ },
+ webhooks: {
+ fields: [
+ { key: 'items', label: 'Webhooks', labelKey: 'targetUrl', listItems: webhookFields },
+ { key: 'count', label: 'Webhooks (max 200 per team)', format: 'number' },
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
diff --git a/packages/pieces/community/lemlist/src/lib/common/webhook.ts b/packages/pieces/community/lemlist/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..e259b647aab
--- /dev/null
+++ b/packages/pieces/community/lemlist/src/lib/common/webhook.ts
@@ -0,0 +1,187 @@
+import { randomBytes, timingSafeEqual } from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { isLemlistStatus, isRecord, lemlistApiCall } from './client';
+import { lemlistInput } from './input';
+import { lemlistResults } from './results';
+
+async function createHook({
+ apiKey,
+ targetUrl,
+ secret,
+}: {
+ apiKey: string;
+ targetUrl: string;
+ secret: string;
+}): Promise<string> {
+ const body = await lemlistApiCall<unknown>({
+ apiKey,
+ method: HttpMethod.POST,
+ resourceUri: '/hooks',
+ body: { targetUrl, secret },
+ });
+ const id = isRecord(body) ? body['_id'] : undefined;
+ if (typeof id !== 'string' || id.length === 0) {
+ throw new Error('lemlist did not return a webhook ID.');
+ }
+ return id;
+}
+
+async function deleteHook({ apiKey, webhookId }: { apiKey: string; webhookId: string }): Promise<void> {
+ try {
+ await lemlistApiCall({
+ apiKey,
+ method: HttpMethod.DELETE,
+ resourceUri: `/hooks/${lemlistInput.idSegment({ value: webhookId, label: 'Webhook ID' })}`,
+ });
+ } catch (error) {
+ if (isLemlistStatus({ error, status: 404 })) {
+ return;
+ }
+ throw error;
+ }
+}
+
+async function findHookIdByUrl({ apiKey, targetUrl }: { apiKey: string; targetUrl: string }): Promise<string | undefined> {
+ const body = await lemlistApiCall<unknown>({ apiKey, method: HttpMethod.GET, resourceUri: '/hooks' });
+ const match = lemlistResults.listFrom({ body }).find((hook) => hook['targetUrl'] === targetUrl);
+ const id = match?.['_id'];
+ return typeof id === 'string' ? id : undefined;
+}
+
+async function enable({
+ apiKey,
+ targetUrl,
+ store,
+ storeKey,
+}: {
+ apiKey: string;
+ targetUrl: string;
+ store: WebhookStore;
+ storeKey: string;
+}): Promise<void> {
+ const secret = randomBytes(32).toString('hex');
+ let webhookId: string;
+ try {
+ webhookId = await createHook({ apiKey, targetUrl, secret });
+ } catch (error) {
+ if (!isLemlistStatus({ error, status: 409 })) {
+ throw error;
+ }
+ const leftover = await findHookIdByUrl({ apiKey, targetUrl });
+ if (leftover === undefined) {
+ throw new Error(
+ 'lemlist refused the webhook: the team already has 200 webhooks (disabled ones count too). Delete unused webhooks in lemlist and try again.'
+ );
+ }
+ await deleteHook({ apiKey, webhookId: leftover });
+ webhookId = await createHook({ apiKey, targetUrl, secret });
+ }
+ try {
+ await store.put<StoredWebhook>(storeKey, { webhookId, secret });
+ } catch (error) {
+ await deleteHook({ apiKey, webhookId });
+ throw error;
+ }
+}
+
+async function disable({
+ apiKey,
+ store,
+ storeKey,
+}: {
+ apiKey: string;
+ store: WebhookStore;
+ storeKey: string;
+}): Promise<void> {
+ const stored = await store.get<StoredWebhook>(storeKey);
+ const webhookId = isRecord(stored) && typeof stored['webhookId'] === 'string' ? stored['webhookId'] : undefined;
+ if (webhookId !== undefined) {
+ await deleteHook({ apiKey, webhookId });
+ }
+ await store.delete(storeKey);
+ await store.delete(dedupeKey(storeKey));
+}
+
+function secretsMatch({ expected, received }: { expected: string; received: unknown }): boolean {
+ if (typeof received !== 'string') {
+ return false;
+ }
+ const a = Buffer.from(expected, 'utf8');
+ const b = Buffer.from(received, 'utf8');
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+function parseBody(body: unknown): Record<string, unknown> | undefined {
+ if (isRecord(body)) {
+ return body;
+ }
+ if (typeof body === 'string') {
+ try {
+ const parsed: unknown = JSON.parse(body);
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ return undefined;
+}
+
+async function receive({
+ body,
+ store,
+ storeKey,
+ nowMs,
+ accept,
+}: {
+ body: unknown;
+ store: WebhookStore;
+ storeKey: string;
+ nowMs: number;
+ accept: (activity: Record<string, unknown>) => boolean;
+}): Promise<Record<string, unknown> | undefined> {
+ const event = parseBody(body);
+ if (event === undefined) {
+ return undefined;
+ }
+ const stored = await store.get<StoredWebhook>(storeKey);
+ const expected = isRecord(stored) && typeof stored['secret'] === 'string' ? stored['secret'] : undefined;
+ if (expected !== undefined && !secretsMatch({ expected, received: event['secret'] })) {
+ return undefined;
+ }
+ const activity = Object.fromEntries(Object.entries(event).filter(([key]) => key !== 'secret'));
+ const createdAt = typeof activity['createdAt'] === 'string' ? Date.parse(activity['createdAt']) : Number.NaN;
+ if (!Number.isNaN(createdAt) && nowMs - createdAt > MAX_EVENT_AGE_MS) {
+ return undefined;
+ }
+ if (!accept(activity)) {
+ return undefined;
+ }
+ const activityId = typeof activity['_id'] === 'string' ? activity['_id'] : undefined;
+ if (activityId !== undefined) {
+ const seen = (await store.get<string[]>(dedupeKey(storeKey))) ?? [];
+ if (seen.includes(activityId)) {
+ return undefined;
+ }
+ await store.put(dedupeKey(storeKey), [...seen, activityId].slice(-MAX_REMEMBERED_ACTIVITIES));
+ return { ...activity, [DEDUPE_KEY_PROPERTY]: activityId };
+ }
+ return activity;
+}
+
+function dedupeKey(storeKey: string): string {
+ return `${storeKey}_seen_activity_ids`;
+}
+
+const MAX_REMEMBERED_ACTIVITIES = 1000;
+const MAX_EVENT_AGE_MS = 24 * 60 * 60 * 1000;
+
+export const lemlistWebhook = { enable, disable, receive, secretsMatch };
+
+export type StoredWebhook = { webhookId: string; secret?: string };
+
+export type WebhookStore = {
+ get: <T>(key: string) => Promise<T | null>;
+ put: <T>(key: string, value: T) => Promise<T>;
+ delete: (key: string) => Promise<void>;
+};
diff --git a/packages/pieces/community/lemlist/src/lib/triggers/new-activity.ts b/packages/pieces/community/lemlist/src/lib/triggers/new-activity.ts
index e367a429627..2507750c39f 100644
--- a/packages/pieces/community/lemlist/src/lib/triggers/new-activity.ts
+++ b/packages/pieces/community/lemlist/src/lib/triggers/new-activity.ts
@@ -1,6 +1,10 @@
-import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
-import { lemlistApiService } from '../common/requests';
+import { campaignsDropdown } from '../common/props';
+import { LEMLIST_EVENT_TYPES } from '../common/events';
+import { SAMPLE_ACTIVITY } from '../common/sample';
+import { lemlistSchemas } from '../common/schemas';
+import { lemlistWebhook } from '../common/webhook';
const CACHE_KEY = 'lemlist_new_activity_trigger_key';
@@ -9,34 +13,56 @@ export const newActivity = createTrigger({
name: 'newActivity',
classification: 'READ',
displayName: 'New Activity',
- description: 'Triggers for each new activity.',
+ description: 'Triggers for each new activity, optionally only some event types or one campaign.',
aiMetadata: {
- description: 'Fires on each new Lemlist activity event received via webhook, covering campaign engagement signals such as emails sent, opened, clicked, replied, bounced, or unsubscribed. Represents a single activity record as it occurs.',
+ description:
+ 'Fires once per lemlist activity delivered by webhook (emails sent, opened, clicked, replied, bounced, interest changes, LinkedIn steps, unsubscribes...), optionally only for chosen event types or one campaign. Deliveries are checked against a secret created with the webhook and duplicates are dropped by activity ID. Payload is the activity record.',
},
- props: {},
- sampleData: {},
+ props: {
+ eventTypes: Property.StaticMultiSelectDropdown({
+ displayName: 'Event Types',
+ description: 'Only trigger for these events. Leave empty for every event.',
+ required: false,
+ options: {
+ disabled: false,
+ options: LEMLIST_EVENT_TYPES.map((value) => ({ label: value, value })),
+ },
+ }),
+ campaignId: campaignsDropdown({ refreshers: ['auth'], required: false }),
+ },
+ sampleData: SAMPLE_ACTIVITY,
+ outputSchema: lemlistSchemas.activity,
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- const response = await lemlistApiService.createWebhook(context.auth, {
+ await lemlistWebhook.enable({
+ apiKey: context.auth.secret_text,
targetUrl: context.webhookUrl,
- });
-
- await context.store.put(CACHE_KEY, {
- webhookId: response._id,
+ store: context.store,
+ storeKey: CACHE_KEY,
});
},
async onDisable(context) {
- const cachedWebhookData: any = await context.store.get(CACHE_KEY);
-
- if (cachedWebhookData) {
- await lemlistApiService
- .deleteWebhook(context.auth, cachedWebhookData.webhookId)
- .then(async () => {
- await context.store.delete(CACHE_KEY);
- });
- }
+ await lemlistWebhook.disable({
+ apiKey: context.auth.secret_text,
+ store: context.store,
+ storeKey: CACHE_KEY,
+ });
},
async run(context) {
- return [context.payload.body];
+ const activity = await lemlistWebhook.receive({
+ body: context.payload.body,
+ store: context.store,
+ storeKey: CACHE_KEY,
+ nowMs: Date.now(),
+ accept: (event) => {
+ const wanted = context.propsValue.eventTypes ?? [];
+ const campaignId = context.propsValue.campaignId;
+ const typeOk = wanted.length === 0 || wanted.includes(String(event['type']));
+ const campaignOk =
+ typeof campaignId !== 'string' || campaignId.length === 0 || event['campaignId'] === campaignId;
+ return typeOk && campaignOk;
+ },
+ });
+ return activity === undefined ? [] : [activity];
},
});
diff --git a/packages/pieces/community/lemlist/src/lib/triggers/unsubscribed-recipient.ts b/packages/pieces/community/lemlist/src/lib/triggers/unsubscribed-recipient.ts
index c9b902f77a2..4e34c416b0a 100644
--- a/packages/pieces/community/lemlist/src/lib/triggers/unsubscribed-recipient.ts
+++ b/packages/pieces/community/lemlist/src/lib/triggers/unsubscribed-recipient.ts
@@ -1,6 +1,9 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { lemlistAuth } from '../common/constants';
-import { lemlistApiService } from '../common/requests';
+import { LEMLIST_UNSUBSCRIBE_TYPES } from '../common/events';
+import { SAMPLE_UNSUBSCRIBE } from '../common/sample';
+import { lemlistSchemas } from '../common/schemas';
+import { lemlistWebhook } from '../common/webhook';
const CACHE_KEY = 'lemlist_unsubscribed_recipient_trigger_key';
@@ -11,33 +14,36 @@ export const unsubscribedRecipient = createTrigger({
displayName: 'Unsubscribed Recipient',
description: 'Triggers when a recipient unsubscribes.',
aiMetadata: {
- description: 'Fires via webhook when a recipient unsubscribes from outreach (Lemlist emailsUnsubscribed event). Represents an opt-out signal for a single lead.',
+ description:
+ 'Fires once per lemlist unsubscribe event delivered by webhook: a contact unsubscribed (entityUnsubscribed), one of its emails/phones/LinkedIn was unsubscribed (variableUnsubscribed), or a lead stopped because it is on the unsubscribe list (emailsUnsubscribed, apiUnsubscribed, manualUnsubscribed). Deliveries are checked against a webhook secret and duplicates dropped by activity ID. Payload is the activity record.',
},
props: {},
- sampleData: {},
+ sampleData: SAMPLE_UNSUBSCRIBE,
+ outputSchema: lemlistSchemas.activity,
type: TriggerStrategy.WEBHOOK,
async onEnable(context) {
- const response = await lemlistApiService.createWebhook(context.auth, {
+ await lemlistWebhook.enable({
+ apiKey: context.auth.secret_text,
targetUrl: context.webhookUrl,
- type: 'emailsUnsubscribed',
- });
-
- await context.store.put(CACHE_KEY, {
- webhookId: response._id,
+ store: context.store,
+ storeKey: CACHE_KEY,
});
},
async onDisable(context) {
- const cachedWebhookData: any = await context.store.get(CACHE_KEY);
-
- if (cachedWebhookData) {
- await lemlistApiService
- .deleteWebhook(context.auth, cachedWebhookData.webhookId)
- .then(async () => {
- await context.store.delete(CACHE_KEY);
- });
- }
+ await lemlistWebhook.disable({
+ apiKey: context.auth.secret_text,
+ store: context.store,
+ storeKey: CACHE_KEY,
+ });
},
async run(context) {
- return [context.payload.body];
+ const activity = await lemlistWebhook.receive({
+ body: context.payload.body,
+ store: context.store,
+ storeKey: CACHE_KEY,
+ nowMs: Date.now(),
+ accept: (event) => LEMLIST_UNSUBSCRIBE_TYPES.includes(String(event['type'])),
+ });
+ return activity === undefined ? [] : [activity];
},
});
diff --git a/packages/pieces/community/lemlist/test/actions.test.ts b/packages/pieces/community/lemlist/test/actions.test.ts
new file mode 100644
index 00000000000..ac5a00f5c1b
--- /dev/null
+++ b/packages/pieces/community/lemlist/test/actions.test.ts
@@ -0,0 +1,317 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { lemlist } from '../src';
+import { addCustomVariablesOnLead } from '../src/lib/actions/add-custom-variables-on-lead';
+import { addLeadToACampaign } from '../src/lib/actions/add-lead-to-a-campaign';
+import { listActivitiesAction } from '../src/lib/actions/ai/activities';
+import {
+ createCampaignAction,
+ getCampaignAction,
+ getCampaignSequencesAction,
+ getCampaignStatsAction,
+ listCampaignSchedulesAction,
+ listCampaignsAction,
+ listSchedulesAction,
+ pauseCampaignAction,
+ startCampaignAction,
+ updateCampaignAction,
+} from '../src/lib/actions/ai/campaigns';
+import {
+ createCompanyNoteAction,
+ createContactNoteAction,
+ getCompanyAction,
+ getContactAction,
+ listCompaniesAction,
+ listCompanyNotesAction,
+ listContactNotesAction,
+ listContactsAction,
+ upsertCompanyAction,
+ upsertContactAction,
+} from '../src/lib/actions/ai/crm';
+import { enrichLeadAction, getEnrichmentResultAction } from '../src/lib/actions/ai/enrichment';
+import { createLabelAction, getContactMessagesAction, listLabelsAction, sendInboxEmailAction } from '../src/lib/actions/ai/inbox';
+import {
+ createLeadInCampaignAction,
+ deleteLeadFromCampaignAction,
+ eraseLeadVariablesAction,
+ getLeadByEmailAction,
+ launchLeadAction,
+ listCampaignLeadsAction,
+ markLeadInterestedInCampaignAction,
+ markLeadNotInterestedInCampaignAction,
+ pauseLeadEverywhereAction,
+ pauseLeadInCampaignAction,
+ resumeLeadEverywhereAction,
+ resumeLeadInCampaignAction,
+ unsubscribeLeadFromCampaignAction,
+ updateCampaignLeadAction,
+ updateLeadVariablesAction,
+} from '../src/lib/actions/ai/leads';
+import { createTaskAction, ignoreTasksAction, listTasksAction, updateTaskAction } from '../src/lib/actions/ai/tasks';
+import { getTeamAction, getTeamCreditsAction, listTeamSendersAction } from '../src/lib/actions/ai/team';
+import { addUnsubscribeAction, getUnsubscribeAction, listUnsubscribesAction, resubscribeEmailAction } from '../src/lib/actions/ai/unsubscribes';
+import { listWebhooksAction } from '../src/lib/actions/ai/webhooks';
+import { markLeadFromAllCampaignAsInterested } from '../src/lib/actions/mark-lead-from-all-campaign-as-interested';
+import { markLeadFromAllCampaignsAsNotInterested } from '../src/lib/actions/mark-lead-from-all-campaigns-as-not-interested';
+import { markLeadFromOneCampaignAsInterested } from '../src/lib/actions/mark-lead-from-one-campaign-as-interested';
+import { markLeadFromOneCampaignAsNotInterested } from '../src/lib/actions/mark-lead-from-one-campaign-as-not-interested';
+import { pauseLeadFromAllOrSpecificCampaigns } from '../src/lib/actions/pause-lead-from-all-or-specific-campaigns';
+import { removeLeadFromACampaign } from '../src/lib/actions/remove-lead-from-a-campaign';
+import { removeLeadFromUnsubscribeList } from '../src/lib/actions/remove-lead-from-unsubscribe-list';
+import { resumeLeadFromAllOrSpecificCampaigns } from '../src/lib/actions/resume-lead-from-all-or-specific-campaigns';
+import { searchLead } from '../src/lib/actions/search-lead';
+import { unsubscribeALead } from '../src/lib/actions/unsubscribe-a-lead';
+import { updateLeadFromCampaign } from '../src/lib/actions/update-lead-from-campaign';
+import { API_KEY, makeContext, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+const CAM = 'cam_A1';
+const LEA = 'lea_B2';
+const EMAIL = '[email protected]';
+const ENC = encodeURIComponent(EMAIL);
+
+type Case = {
+ action: { name: string; run: unknown };
+ props: Record<string, unknown>;
+ response?: unknown;
+ status?: number;
+ method: string;
+ path: string;
+ query?: Record<string, string>;
+ body?: unknown;
+ output?: unknown;
+};
+
+function call({ fn, ctx }: { fn: unknown; ctx: unknown }): Promise<unknown> {
+ if (typeof fn !== 'function') {
+ throw new Error('not callable');
+ }
+ return fn(ctx);
+}
+
+const CASES: Case[] = [
+ { action: markLeadFromAllCampaignAsInterested, props: { email: EMAIL }, response: [{ _id: LEA }], method: 'POST', path: `/leads/interested/${ENC}`, output: [{ _id: LEA }] },
+ { action: markLeadFromAllCampaignsAsNotInterested, props: { email: EMAIL }, response: [], method: 'POST', path: `/leads/notinterested/${ENC}` },
+ { action: markLeadFromOneCampaignAsInterested, props: { campaignId: CAM, email: EMAIL }, response: { _id: LEA }, method: 'POST', path: `/campaigns/${CAM}/leads/${ENC}/interested` },
+ { action: markLeadFromOneCampaignAsNotInterested, props: { campaignId: CAM, email: EMAIL }, response: { _id: LEA }, method: 'POST', path: `/campaigns/${CAM}/leads/${ENC}/notinterested` },
+ { action: pauseLeadFromAllOrSpecificCampaigns, props: { campaignId: CAM, email: EMAIL }, response: [], method: 'POST', path: `/leads/pause/${ENC}`, query: { campaignId: CAM } },
+ { action: pauseLeadFromAllOrSpecificCampaigns, props: { email: EMAIL }, response: [], method: 'POST', path: `/leads/pause/${ENC}`, query: {} },
+ { action: resumeLeadFromAllOrSpecificCampaigns, props: { campaignId: CAM, email: EMAIL }, response: [], method: 'POST', path: `/leads/start/${ENC}`, query: { campaignId: CAM } },
+ { action: removeLeadFromUnsubscribeList, props: { email: EMAIL }, response: { _id: 'uns_1', value: EMAIL }, method: 'DELETE', path: `/unsubscribes/${ENC}` },
+ { action: removeLeadFromACampaign, props: { campaignId: CAM, email: EMAIL }, response: { _id: LEA }, method: 'DELETE', path: `/campaigns/${CAM}/leads/${ENC}`, query: { action: 'remove' } },
+ { action: unsubscribeALead, props: { campaignId: CAM, email: EMAIL }, response: { _id: LEA }, method: 'DELETE', path: `/campaigns/${CAM}/leads/${ENC}`, query: {} },
+ {
+ action: addLeadToACampaign,
+ props: { campaignId: CAM, email: EMAIL, firstName: 'Jane', lastName: '', deduplicate: true, findEmail: true, verifyEmail: false },
+ response: { _id: LEA },
+ method: 'POST',
+ path: `/campaigns/${CAM}/leads/`,
+ query: { deduplicate: 'true', findEmail: 'true' },
+ body: { firstName: 'Jane', email: EMAIL },
+ },
+ { action: addCustomVariablesOnLead, props: { leadId: LEA, customVariables: { icebreaker: 'Hi there', score: 7 } }, response: { ok: true }, method: 'POST', path: `/leads/${LEA}/variables`, query: {}, body: { icebreaker: 'Hi there', score: '7' } },
+ { action: updateLeadFromCampaign, props: { campaignId: CAM, email: EMAIL, jobTitle: 'CTO', phone: '' }, response: { _id: LEA }, method: 'PATCH', path: `/campaigns/${CAM}/leads/${ENC}`, body: { jobTitle: 'CTO' } },
+ {
+ action: searchLead,
+ props: { email: EMAIL, campaignId: CAM },
+ response: [{ _id: 'lea_1', campaign: { id: 'cam_other' } }, { _id: 'lea_2', campaign: { id: CAM } }],
+ method: 'GET',
+ path: `/leads/${ENC}`,
+ query: { version: 'v2' },
+ output: { found: true, leads: [{ _id: 'lea_2', campaign: { id: CAM } }] },
+ },
+ { action: getTeamAction, props: {}, response: { _id: 'tea_1' }, method: 'GET', path: '/team', query: { version: 'v2' } },
+ { action: listTeamSendersAction, props: { state: 'running' }, response: [{ userId: 'usr_1', campaigns: [] }], method: 'GET', path: '/team/senders', query: { state: 'running' }, output: { items: [{ userId: 'usr_1', campaigns: [] }], count: 1, offset: 0, has_more: false } },
+ { action: getTeamCreditsAction, props: {}, response: { credits: 5 }, method: 'GET', path: '/team/credits' },
+ {
+ action: listCampaignsAction,
+ props: { status: 'running', limit: 2, offset: 4 },
+ response: { campaigns: [{ _id: 'cam_1' }, { _id: 'cam_2' }] },
+ method: 'GET',
+ path: '/campaigns',
+ query: { version: 'v2', limit: '2', offset: '4', sortBy: 'createdAt', sortOrder: 'desc', status: 'running' },
+ output: { items: [{ _id: 'cam_1' }, { _id: 'cam_2' }], count: 2, offset: 4, has_more: true },
+ },
+ { action: getCampaignAction, props: { campaign_id: CAM }, response: { _id: CAM }, method: 'GET', path: `/campaigns/${CAM}` },
+ {
+ action: getCampaignStatsAction,
+ props: { campaign_id: CAM, start_date: '2026-10-01', end_date: '2026-10-31' },
+ response: { nbLeads: 3 },
+ method: 'GET',
+ path: `/v2/campaigns/${CAM}/stats`,
+ query: { startDate: '2026-10-01T00:00:00.000Z', endDate: '2026-10-31T00:00:00.000Z' },
+ },
+ { action: getCampaignSequencesAction, props: { campaign_id: CAM }, response: { seq_1: { _id: 'seq_1', steps: [] } }, method: 'GET', path: `/campaigns/${CAM}/sequences`, output: { sequences: [{ _id: 'seq_1', steps: [] }], count: 1 } },
+ { action: listCampaignSchedulesAction, props: { campaign_id: CAM }, response: [{ _id: 'skd_1' }], method: 'GET', path: `/campaigns/${CAM}/schedules/`, output: { items: [{ _id: 'skd_1' }], count: 1 } },
+ { action: listSchedulesAction, props: {}, response: { schedules: [{ _id: 'skd_1' }] }, method: 'GET', path: '/schedules', query: { limit: '100', offset: '0', sortBy: 'createdAt', sortOrder: 'desc' }, output: { items: [{ _id: 'skd_1' }], count: 1 } },
+ { action: createCampaignAction, props: { name: ' Test ', timezone: '' }, response: { _id: CAM }, method: 'POST', path: '/campaigns', body: { name: 'Test' } },
+ { action: updateCampaignAction, props: { campaign_id: CAM, stopOnEmailReplied: false, name: 'N' }, response: { name: 'N' }, method: 'PATCH', path: `/campaigns/${CAM}`, body: { name: 'N', stopOnEmailReplied: false } },
+ { action: updateCampaignAction, props: { campaign_id: CAM, name: 'N', stopOnEmailReplied: 'no', stopOnMeetingBooked: 'yes', stopOnLinkClicked: 'unchanged', disableTrackOpen: undefined, disableTrackClick: '', disableTrackReply: true }, response: { name: 'N' }, method: 'PATCH', path: `/campaigns/${CAM}`, body: { name: 'N', stopOnEmailReplied: false, stopOnMeetingBooked: true, disableTrackReply: true } },
+ { action: updateCampaignAction, props: { campaign_id: CAM, name: 'Renamed', stopOnEmailReplied: 'unchanged', stopOnMeetingBooked: 'unchanged', stopOnLinkClicked: 'unchanged', disableTrackOpen: 'unchanged', disableTrackClick: 'unchanged', disableTrackReply: 'unchanged' }, response: { name: 'Renamed' }, method: 'PATCH', path: `/campaigns/${CAM}`, body: { name: 'Renamed' } },
+ { action: startCampaignAction, props: { campaign_id: CAM }, response: { _id: CAM, state: 'running' }, method: 'POST', path: `/campaigns/${CAM}/start` },
+ { action: pauseCampaignAction, props: { campaign_id: CAM }, response: { _id: CAM, state: 'paused' }, method: 'POST', path: `/campaigns/${CAM}/pause` },
+ { action: listCampaignLeadsAction, props: { campaign_id: CAM, state: 'interested', limit: 1 }, response: [{ _id: LEA }], method: 'GET', path: `/campaigns/${CAM}/leads/`, query: { state: 'interested', limit: '1', offset: '0' }, output: { items: [{ _id: LEA }], count: 1, offset: 0, has_more: true } },
+ { action: listCampaignLeadsAction, props: { campaign_id: CAM, limit: 2, offset: 4 }, response: [{ _id: LEA }], method: 'GET', path: `/campaigns/${CAM}/leads/`, query: { limit: '2', offset: '4' }, output: { items: [{ _id: LEA }], count: 1, offset: 4, has_more: false } },
+ { action: createLeadInCampaignAction, props: { campaign_id: CAM, email: EMAIL, companyName: 'Acme', deduplicate: false }, response: { _id: LEA }, method: 'POST', path: `/campaigns/${CAM}/leads/`, query: {}, body: { companyName: 'Acme', email: EMAIL } },
+ { action: getLeadByEmailAction, props: { email: EMAIL }, status: 404, response: { message: 'Lead not found' }, method: 'GET', path: `/leads/${ENC}`, output: { found: false, message: `No lead found for ${EMAIL}.`, leads: [] } },
+ { action: updateCampaignLeadAction, props: { campaign_id: CAM, lead: LEA, lastName: 'Doe' }, response: { _id: LEA }, method: 'PATCH', path: `/campaigns/${CAM}/leads/${LEA}`, body: { lastName: 'Doe' } },
+ { action: deleteLeadFromCampaignAction, props: { campaign_id: CAM, lead: LEA }, response: { _id: LEA }, method: 'DELETE', path: `/campaigns/${CAM}/leads/${LEA}`, query: { action: 'remove' }, output: { deleted: true, alreadyRemoved: false, lead: { _id: LEA } } },
+ { action: deleteLeadFromCampaignAction, props: { campaign_id: CAM, lead: LEA }, status: 404, response: {}, method: 'DELETE', path: `/campaigns/${CAM}/leads/${LEA}`, output: { deleted: false, alreadyRemoved: true, lead: null } },
+ { action: unsubscribeLeadFromCampaignAction, props: { campaign_id: CAM, lead: EMAIL }, response: { _id: LEA }, method: 'DELETE', path: `/campaigns/${CAM}/leads/${ENC}`, query: {} },
+ { action: pauseLeadInCampaignAction, props: { campaign_id: CAM, lead: LEA }, response: [{ _id: LEA }], method: 'POST', path: `/leads/pause/${LEA}`, query: { campaignId: CAM }, output: { leads: [{ _id: LEA }], count: 1 } },
+ { action: pauseLeadEverywhereAction, props: { lead: EMAIL }, response: [], method: 'POST', path: `/leads/pause/${ENC}`, query: {}, output: { leads: [], count: 0 } },
+ { action: resumeLeadInCampaignAction, props: { campaign_id: CAM, lead: LEA }, response: [], method: 'POST', path: `/leads/start/${LEA}`, query: { campaignId: CAM } },
+ { action: resumeLeadEverywhereAction, props: { lead: LEA }, response: { _id: LEA }, method: 'POST', path: `/leads/start/${LEA}`, output: { leads: [{ _id: LEA }], count: 1 } },
+ { action: launchLeadAction, props: { lead_id: LEA }, response: { ok: true }, method: 'POST', path: `/leads/review/${LEA}` },
+ { action: markLeadInterestedInCampaignAction, props: { campaign_id: CAM, lead: LEA }, response: { _id: LEA }, method: 'POST', path: `/campaigns/${CAM}/leads/${LEA}/interested` },
+ { action: markLeadNotInterestedInCampaignAction, props: { campaign_id: CAM, lead: LEA }, response: { _id: LEA }, method: 'POST', path: `/campaigns/${CAM}/leads/${LEA}/notinterested` },
+ { action: updateLeadVariablesAction, props: { lead_id: LEA, variables: { icebreaker: 'Yo' } }, response: { ok: true }, method: 'PATCH', path: `/leads/${LEA}/variables`, query: {}, body: { icebreaker: 'Yo' } },
+ { action: eraseLeadVariablesAction, props: { lead_id: LEA, variable_names: ['icebreaker', 'score'] }, response: { ok: true }, method: 'DELETE', path: `/leads/${LEA}/variables`, query: { icebreaker: '', score: '' } },
+ { action: enrichLeadAction, props: { lead_id: LEA, find_phone: true }, response: { id: 'enr_1' }, method: 'POST', path: `/leads/${LEA}/enrich`, query: { findPhone: 'true' } },
+ { action: getEnrichmentResultAction, props: { enrichment_id: 'enr_1' }, response: { enrichmentId: 'enr_1', enrichmentStatus: 'done', data: {} }, method: 'GET', path: '/enrich/enr_1', output: { enrichmentId: 'enr_1', enrichmentStatus: 'done', data: {}, done: true } },
+ { action: getEnrichmentResultAction, props: { enrichment_id: 'enr_1' }, status: 202, response: undefined, method: 'GET', path: '/enrich/enr_1', output: { enrichmentId: 'enr_1', done: false, enrichmentStatus: 'in_progress', input: null, data: null } },
+ {
+ action: listActivitiesAction,
+ props: { type: 'emailsReplied', campaign_id: CAM, lead_id: LEA, min_date: '2026-10-01T00:00:00Z', limit: 10 },
+ response: [{ _id: 'act_1' }],
+ method: 'GET',
+ path: '/activities',
+ query: { version: 'v2', type: 'emailsReplied', campaignId: CAM, leadId: LEA, minDate: '2026-10-01T00:00:00.000Z', limit: '10', offset: '0' },
+ output: { items: [{ _id: 'act_1' }], count: 1, offset: 0, has_more: false },
+ },
+ { action: listUnsubscribesAction, props: { offset: 100 }, response: [{ _id: 'uns_1' }], method: 'GET', path: '/unsubscribes', query: { limit: '100', offset: '100' } },
+ { action: getUnsubscribeAction, props: { value: 'acme.com' }, response: { _id: 'uns_1', value: 'acme.com' }, method: 'GET', path: '/unsubscribes/acme.com', output: { unsubscribed: true, record: { _id: 'uns_1', value: 'acme.com' } } },
+ { action: getUnsubscribeAction, props: { value: EMAIL }, status: 404, response: {}, method: 'GET', path: `/unsubscribes/${ENC}`, output: { unsubscribed: false, record: null } },
+ { action: addUnsubscribeAction, props: { value: EMAIL }, response: { _id: 'uns_1' }, method: 'POST', path: `/unsubscribes/${ENC}` },
+ { action: resubscribeEmailAction, props: { value: EMAIL }, status: 404, response: {}, method: 'DELETE', path: `/unsubscribes/${ENC}`, output: { removed: false, record: null } },
+ { action: upsertContactAction, props: { email: EMAIL, firstName: 'Jane', update_strategy: 'fillEmptyOnly' }, response: { success: true }, method: 'POST', path: '/contacts', query: { updateStrategy: 'fillEmptyOnly' }, body: { email: EMAIL, firstName: 'Jane' } },
+ { action: getContactAction, props: { contact: EMAIL }, response: [{ _id: 'ctc_1' }], method: 'GET', path: '/contacts', query: { idsOrEmails: EMAIL }, output: { found: true, contact: { _id: 'ctc_1' } } },
+ { action: getContactAction, props: { contact: 'ctc_1' }, response: { _id: 'ctc_1' }, method: 'GET', path: '/contacts/ctc_1', output: { found: true, contact: { _id: 'ctc_1' } } },
+ { action: listContactsAction, props: { search: 'Jan', limit: 5 }, response: { data: [{ _id: 'ctc_1' }], total: 1 }, method: 'GET', path: '/contacts', query: { search: 'Jan', limit: '5', offset: '0' }, output: { items: [{ _id: 'ctc_1' }], count: 1, offset: 0, has_more: false } },
+ { action: createContactNoteAction, props: { contact: 'ctc_1', note: 'Met' }, response: { _id: 'act_n' }, method: 'POST', path: '/contacts/ctc_1/notes', body: { note: 'Met' } },
+ { action: listContactNotesAction, props: { contact: 'ctc_1', limit: 1 }, response: { data: [{ _id: 'act_n' }], total: 2 }, method: 'GET', path: '/contacts/ctc_1/notes', query: { page: '1', limit: '1', sortBy: 'createdAt', sortOrder: 'desc' }, output: { items: [{ _id: 'act_n' }], total: 2, page: 1, has_more: true } },
+ { action: upsertCompanyAction, props: { domain: 'acme.com', name: 'Acme' }, response: { success: true }, method: 'POST', path: '/companies', query: {}, body: { domain: 'acme.com', name: 'Acme' } },
+ { action: getCompanyAction, props: { company_id: 'cpn_1' }, response: { _id: 'cpn_1' }, method: 'GET', path: '/companies/cpn_1' },
+ { action: listCompaniesAction, props: { ids_or_domains: 'acme.com, cpn_2' }, response: [{ _id: 'cpn_2' }], method: 'GET', path: '/companies', query: { idsOrDomains: 'acme.com,cpn_2', limit: '100', offset: '0' }, output: { items: [{ _id: 'cpn_2' }], count: 1, offset: 0, has_more: false } },
+ { action: createCompanyNoteAction, props: { company_id: 'cpn_1', note: 'Hot' }, response: { _id: 'act_c' }, method: 'POST', path: '/companies/cpn_1/notes', body: { note: 'Hot' } },
+ { action: listCompanyNotesAction, props: { company_id: 'cpn_1' }, response: { data: [], total: 0 }, method: 'GET', path: '/companies/cpn_1/notes', output: { items: [], total: 0, page: 1, has_more: false } },
+ {
+ action: getContactMessagesAction,
+ props: { contact_id: 'ctc_1', limit: 1 },
+ response: { data: [{ _id: 'act_m' }], pagination: { totalItems: 3 } },
+ method: 'GET',
+ path: '/inbox/ctc_1',
+ query: { limit: '1', skip: '0' },
+ output: { items: [{ _id: 'act_m' }], count: 1, total: 3, has_more: true },
+ },
+ {
+ action: sendInboxEmailAction,
+ props: { send_user_id: 'usr_1', send_user_email: '[email protected]', send_user_mailbox_id: 'usm_1', lead_id: LEA, subject: 'Hi', message: '<p>Hello</p>', cc: ['[email protected]'] },
+ response: { ok: true, contactId: 'ctc_1' },
+ method: 'POST',
+ path: '/inbox/email',
+ body: { sendUserId: 'usr_1', sendUserEmail: '[email protected]', sendUserMailboxId: 'usm_1', leadId: LEA, subject: 'Hi', message: '<p>Hello</p>', cc: ['[email protected]'] },
+ },
+ { action: listLabelsAction, props: {}, response: [{ _id: 'lbl_1' }], method: 'GET', path: '/inbox/labels', output: { items: [{ _id: 'lbl_1' }], count: 1 } },
+ { action: createLabelAction, props: { name: 'Hot' }, response: { _id: 'lbl_1' }, method: 'POST', path: '/inbox/labels', body: { labelName: 'Hot' } },
+ {
+ action: createTaskAction,
+ props: { record_id: 'ctc_1', type: 'manual', assigned_to: 'usr_1', due_date: '2026-10-20', title: 'Call', priority: '' },
+ response: { _id: 'opp_1' },
+ method: 'POST',
+ path: '/tasks',
+ body: { recordId: 'ctc_1', type: 'manual', assignedTo: 'usr_1', dueDate: '2026-10-20T00:00:00.000Z', title: 'Call' },
+ },
+ { action: listTasksAction, props: { page: 2 }, response: { results: [{ _id: 'opp_1' }], page: '2' }, method: 'GET', path: '/tasks', query: { filters: '[]', page: '2' }, output: { items: [{ _id: 'opp_1' }], count: 1, page: 2 } },
+ { action: updateTaskAction, props: { task_id: 'opp_1', done: true }, response: { _id: 'opp_1' }, method: 'PATCH', path: '/tasks', body: { done: true, id: 'opp_1' } },
+ { action: updateTaskAction, props: { task_id: 'opp_1', done: 'no' }, response: { _id: 'opp_1' }, method: 'PATCH', path: '/tasks', body: { done: false, id: 'opp_1' } },
+ { action: updateTaskAction, props: { task_id: 'opp_1', title: 'T', done: 'unchanged' }, response: { _id: 'opp_1' }, method: 'PATCH', path: '/tasks', body: { title: 'T', id: 'opp_1' } },
+ { action: ignoreTasksAction, props: { task_ids: ['opp_1', 'opp_1', 'opp_2'] }, response: {}, method: 'POST', path: '/tasks/ignore', body: { ids: ['opp_1', 'opp_2'] }, output: { ignored: ['opp_1', 'opp_2'], count: 2, response: {} } },
+ { action: listWebhooksAction, props: {}, response: [{ _id: 'hoo_1' }], method: 'GET', path: '/hooks', output: { items: [{ _id: 'hoo_1' }], count: 1 } },
+];
+
+describe('every action sends the documented request', () => {
+ it.each(CASES.map((c, i) => [`${i} ${c.action.name}`, c] as const))('%s', async (_label, c) => {
+ const calls = stubFetch([{ status: c.status ?? 200, body: c.response }]);
+ const result = await call({ fn: c.action.run, ctx: makeContext({ props: c.props }) });
+ expect(calls).toHaveLength(1);
+ const req = calls[0];
+ expect(req.method).toBe(c.method);
+ expect(req.url.origin).toBe('https://api.lemlist.com');
+ expect(req.url.pathname).toBe(`/api${c.path}`);
+ expect(req.headers['authorization']).toBe(`Basic ${Buffer.from(`:${API_KEY}`).toString('base64')}`);
+ if (c.query !== undefined) {
+ expect(Object.fromEntries(req.url.searchParams.entries())).toEqual(c.query);
+ }
+ if (c.body !== undefined) {
+ expect(req.body).toEqual(c.body);
+ }
+ if (c.output !== undefined) {
+ expect(result).toEqual(c.output);
+ }
+ });
+
+ it('covers every registered action except Custom API Call', () => {
+ const tested = new Set(CASES.map((c) => c.action.name));
+ const registered = Object.keys(lemlist.actions()).filter((name) => name !== 'custom_api_call');
+ expect(registered.filter((name) => !tested.has(name))).toEqual([]);
+ });
+});
+
+describe('metadata', () => {
+ const actions = Object.values(lemlist.actions());
+ it('every action has classification, aiMetadata and an outputSchema', () => {
+ for (const action of actions) {
+ expect(action.classification, action.name).toBeDefined();
+ if (action.name !== 'custom_api_call') {
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(action.outputSchema, action.name).toBeDefined();
+ }
+ }
+ });
+
+ it('counts audiences', () => {
+ const counts: Record<string, number> = {};
+ for (const action of actions) {
+ const audience = action.audience ?? 'both';
+ counts[audience] = (counts[audience] ?? 0) + 1;
+ }
+ expect(counts).toEqual({ both: 4, human: 10, ai: 54 });
+ });
+
+ it('ai actions take IDs as text, never dropdowns', () => {
+ for (const action of actions.filter((a) => a.audience === 'ai')) {
+ for (const prop of Object.values(action.props)) {
+ expect(prop.type, action.name).not.toBe('DROPDOWN');
+ }
+ }
+ });
+});
+
+describe('review fixes', () => {
+ it('upsert contact with overwrite sends supplied empty fields so they are cleared', async () => {
+ const calls = stubFetch([{ body: { _id: 'ctc_1' } }]);
+ await call({ fn: upsertContactAction.run, ctx: makeContext({ props: { email: '[email protected]', phone: '', jobTitle: undefined, update_strategy: 'overwrite' } }) });
+ expect(calls[0].body).toEqual({ email: '[email protected]', phone: '' });
+ });
+
+ it('upsert contact without overwrite still drops empty fields', async () => {
+ const calls = stubFetch([{ body: { _id: 'ctc_1' } }]);
+ await call({ fn: upsertContactAction.run, ctx: makeContext({ props: { email: '[email protected]', phone: '', update_strategy: 'overwriteIgnoreEmpty' } }) });
+ expect(calls[0].body).toEqual({ email: '[email protected]' });
+ });
+
+ it('upsert company with overwrite sends supplied empty fields but never an empty identifier', async () => {
+ const calls = stubFetch([{ body: { _id: 'cpn_1' } }]);
+ await call({ fn: upsertCompanyAction.run, ctx: makeContext({ props: { domain: 'acme.com', linkedinUrl: '', industry: '', update_strategy: 'overwrite' } }) });
+ expect(calls[0].body).toEqual({ domain: 'acme.com', industry: '' });
+ });
+
+ it('update task offers no empty priority option, so an omitted priority means unchanged', () => {
+ const options = (updateTaskAction.props.priority as unknown as { options: { options: { value: string }[] } }).options.options;
+ expect(options.map((o) => o.value)).toEqual(['0', '1', '2']);
+ });
+});
diff --git a/packages/pieces/community/lemlist/test/behaviour.test.ts b/packages/pieces/community/lemlist/test/behaviour.test.ts
new file mode 100644
index 00000000000..9291bfeb738
--- /dev/null
+++ b/packages/pieces/community/lemlist/test/behaviour.test.ts
@@ -0,0 +1,325 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { addCustomVariablesOnLead } from '../src/lib/actions/add-custom-variables-on-lead';
+import { listCampaignsAction, getCampaignStatsAction } from '../src/lib/actions/ai/campaigns';
+import { upsertContactAction } from '../src/lib/actions/ai/crm';
+import { enrichLeadAction } from '../src/lib/actions/ai/enrichment';
+import { sendInboxEmailAction } from '../src/lib/actions/ai/inbox';
+import { getLeadByEmailAction, updateCampaignLeadAction } from '../src/lib/actions/ai/leads';
+import { searchLead } from '../src/lib/actions/search-lead';
+import { LemlistApiError } from '../src/lib/common/client';
+import { lemlistAuth } from '../src/lib/common/constants';
+import { campaignsDropdown, fetchAllCampaigns } from '../src/lib/common/props';
+import { newActivity } from '../src/lib/triggers/new-activity';
+import { unsubscribedRecipient } from '../src/lib/triggers/unsubscribed-recipient';
+import { API_KEY, makeContext, makeStore, stubFetch } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+function call({ fn, ctx }: { fn: unknown; ctx: unknown }): Promise<unknown> {
+ if (typeof fn !== 'function') {
+ throw new Error('not callable');
+ }
+ return fn(ctx);
+}
+
+describe('errors', () => {
+ it('maps status + vendor message and keeps the body under responseBody, never body', async () => {
+ stubFetch([{ status: 404, body: { message: 'Campaign not found' } }]);
+ const error = await call({ fn: listCampaignsAction.run, ctx: makeContext({ props: {} }) }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(LemlistApiError);
+ expect(error).toHaveProperty('message', 'lemlist could not find the resource. Check the ID or email (HTTP 404): Campaign not found');
+ expect(error).toHaveProperty('status', 404);
+ expect(error).toHaveProperty('responseBody', { message: 'Campaign not found' });
+ expect(error).not.toHaveProperty('body');
+ });
+
+ it('retries a 429 twice, then succeeds', async () => {
+ vi.useFakeTimers();
+ const calls = stubFetch([{ status: 429, body: {} }, { status: 429, body: {} }, { status: 200, body: [] }]);
+ const pending = call({ fn: listCampaignsAction.run, ctx: makeContext({ props: {} }) });
+ await vi.advanceTimersByTimeAsync(10_000);
+ await expect(pending).resolves.toEqual({ items: [], count: 0, offset: 0, has_more: false });
+ expect(calls).toHaveLength(3);
+ });
+
+ it('gives up after two 429 retries', async () => {
+ vi.useFakeTimers();
+ stubFetch([{ status: 429, body: {} }, { status: 429, body: {} }, { status: 429, body: { message: 'slow down' } }]);
+ const pending = call({ fn: listCampaignsAction.run, ctx: makeContext({ props: {} }) }).catch((e: unknown) => e);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(await pending).toHaveProperty('status', 429);
+ });
+
+ it('does not log request bodies on failure (redacted)', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ stubFetch([{ status: 400, body: { message: 'bad' } }]);
+ await call({
+ fn: addCustomVariablesOnLead.run,
+ ctx: makeContext({ props: { leadId: 'lea_1', customVariables: { secretNote: 'private-pii' } } }),
+ }).catch(() => undefined);
+ expect(JSON.stringify(spy.mock.calls)).not.toContain('private-pii');
+ });
+});
+
+describe('input validation (path safety)', () => {
+ const bad = ['x/../../hooks', '[email protected]', '../team', '[email protected]#frag', ''];
+ it.each(bad)('rejects lead email %s before any request', async (email) => {
+ const calls = stubFetch([]);
+ await expect(call({ fn: getLeadByEmailAction.run, ctx: makeContext({ props: { email } }) })).rejects.toThrow();
+ expect(calls).toHaveLength(0);
+ });
+
+ it('rejects campaign IDs without the cam_ prefix or with slashes', async () => {
+ const calls = stubFetch([]);
+ await expect(
+ call({ fn: updateCampaignLeadAction.run, ctx: makeContext({ props: { campaign_id: 'cam_1/../x', lead: 'lea_1', lastName: 'a' } }) })
+ ).rejects.toThrow('not a lemlist ID');
+ await expect(
+ call({ fn: updateCampaignLeadAction.run, ctx: makeContext({ props: { campaign_id: 'hoo_1', lead: 'lea_1', lastName: 'a' } }) })
+ ).rejects.toThrow('cam_');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('update refuses an empty change set', async () => {
+ const calls = stubFetch([]);
+ await expect(
+ call({ fn: updateCampaignLeadAction.run, ctx: makeContext({ props: { campaign_id: 'cam_1', lead: 'lea_1', lastName: '' } }) })
+ ).rejects.toThrow('at least one field');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('variables go in the JSON body, never the URL', async () => {
+ const calls = stubFetch([{ body: { ok: true } }]);
+ await call({ fn: addCustomVariablesOnLead.run, ctx: makeContext({ props: { leadId: 'lea_1', customVariables: { icebreaker: 'Loved your talk' } } }) });
+ expect(calls[0].url.search).toBe('');
+ expect(calls[0].body).toEqual({ icebreaker: 'Loved your talk' });
+ });
+
+ it('enrich requires at least one option (credits)', async () => {
+ const calls = stubFetch([]);
+ await expect(call({ fn: enrichLeadAction.run, ctx: makeContext({ props: { lead_id: 'lea_1' } }) })).rejects.toThrow('at least one');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('send email needs a recipient and a subject for a new thread', async () => {
+ const calls = stubFetch([]);
+ const base = { send_user_id: 'usr_1', send_user_email: '[email protected]', send_user_mailbox_id: 'usm_1', message: 'x' };
+ await expect(call({ fn: sendInboxEmailAction.run, ctx: makeContext({ props: { ...base, subject: 's' } }) })).rejects.toThrow('recipient');
+ await expect(call({ fn: sendInboxEmailAction.run, ctx: makeContext({ props: { ...base, lead_id: 'lea_1' } }) })).rejects.toThrow('Subject');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('stats reject reversed dates', async () => {
+ stubFetch([]);
+ await expect(
+ call({ fn: getCampaignStatsAction.run, ctx: makeContext({ props: { campaign_id: 'cam_1', start_date: '2026-10-31', end_date: '2026-10-01' } }) })
+ ).rejects.toThrow('before');
+ });
+
+ it('upsert contact needs email or LinkedIn', async () => {
+ stubFetch([]);
+ await expect(call({ fn: upsertContactAction.run, ctx: makeContext({ props: { firstName: 'A' } }) })).rejects.toThrow('Email or a LinkedIn');
+ });
+});
+
+describe('search lead', () => {
+ it('returns found=false on 404 instead of failing', async () => {
+ stubFetch([{ status: 404, body: { message: 'Lead not found' } }]);
+ await expect(call({ fn: searchLead.run, ctx: makeContext({ props: { email: '[email protected]' } }) })).resolves.toEqual({
+ found: false,
+ message: 'No leads found for [email protected]',
+ leads: [],
+ });
+ });
+});
+
+describe('auth validate', () => {
+ it('valid on 200', async () => {
+ stubFetch([{ body: { _id: 'tea_1' } }]);
+ await expect(call({ fn: lemlistAuth.validate, ctx: { auth: API_KEY } })).resolves.toEqual({ valid: true });
+ });
+ it('invalid key only on 401/403', async () => {
+ stubFetch([{ status: 401, body: {} }]);
+ await expect(call({ fn: lemlistAuth.validate, ctx: { auth: API_KEY } })).resolves.toEqual({ valid: false, error: 'Invalid API key.' });
+ });
+ it('network/5xx is not reported as an invalid key', async () => {
+ stubFetch([{ status: 503, body: 'down' }]);
+ const result = await call({ fn: lemlistAuth.validate, ctx: { auth: API_KEY } });
+ expect(result).toHaveProperty('valid', false);
+ expect(JSON.stringify(result)).not.toContain('Invalid API key');
+ });
+});
+
+describe('campaign dropdown', () => {
+ it('pages until a short page and labels with status', async () => {
+ const page1 = Array.from({ length: 100 }, (_, i) => ({ _id: `cam_${i}`, name: `C${i}`, status: 'running' }));
+ const calls = stubFetch([{ body: { campaigns: page1 } }, { body: { campaigns: [{ _id: 'cam_x', name: 'X', status: 'draft' }] } }]);
+ const options = await call({ fn: campaignsDropdown({ refreshers: ['auth'] }).options, ctx: { auth: { secret_text: API_KEY } } });
+ expect(calls.map((c) => c.url.searchParams.get('offset'))).toEqual(['0', '100']);
+ expect(options).toHaveProperty('options.100', { label: 'X (draft)', value: 'cam_x' });
+ });
+ it('stops after 20 pages', async () => {
+ let n = 0;
+ stubFetch(() => ({ body: Array.from({ length: 100 }, () => ({ _id: `cam_${n++}`, name: 'c' })) }));
+ const all = await fetchAllCampaigns({ apiKey: API_KEY });
+ expect(all).toHaveLength(2000);
+ });
+ it('shows a disabled state on error', async () => {
+ stubFetch([{ status: 401, body: {} }]);
+ const result = await call({ fn: campaignsDropdown({ refreshers: ['auth'] }).options, ctx: { auth: { secret_text: API_KEY } } });
+ expect(result).toHaveProperty('disabled', true);
+ });
+});
+
+function triggerContext({ store, props = {}, body }: { store: ReturnType<typeof makeStore>; props?: Record<string, unknown>; body?: unknown }) {
+ return {
+ auth: { type: 'SECRET_TEXT', secret_text: API_KEY },
+ propsValue: props,
+ store,
+ webhookUrl: 'https://cloud.activepieces.com/api/v1/webhooks/flow1',
+ payload: { body, headers: {} },
+ };
+}
+
+describe('webhook triggers', () => {
+ it('onEnable registers the hook with a random secret and stores it', async () => {
+ const calls = stubFetch([{ body: { _id: 'hoo_1' } }]);
+ const store = makeStore();
+ await call({ fn: newActivity.onEnable, ctx: triggerContext({ store }) });
+ expect(calls[0].method).toBe('POST');
+ expect(calls[0].url.pathname).toBe('/api/hooks');
+ const sent = calls[0].body;
+ expect(sent).toHaveProperty('targetUrl', 'https://cloud.activepieces.com/api/v1/webhooks/flow1');
+ expect(sent).not.toHaveProperty('type');
+ const stored = store.data.get('lemlist_new_activity_trigger_key');
+ expect(stored).toHaveProperty('webhookId', 'hoo_1');
+ expect(stored).toHaveProperty('secret', Reflect.get(Object(sent), 'secret'));
+ expect(String(Reflect.get(Object(sent), 'secret'))).toHaveLength(64);
+ });
+
+ it('onEnable on 409 deletes the leftover hook with the same URL and recreates it', async () => {
+ const url = 'https://cloud.activepieces.com/api/v1/webhooks/flow1';
+ const calls = stubFetch([
+ { status: 409, body: { error: 'A webhook with this targetUrl already exists' } },
+ { body: [{ _id: 'hoo_other', targetUrl: 'https://x' }, { _id: 'hoo_old', targetUrl: url }] },
+ { body: { _id: 'hoo_old' } },
+ { body: { _id: 'hoo_new' } },
+ ]);
+ const store = makeStore();
+ await call({ fn: unsubscribedRecipient.onEnable, ctx: triggerContext({ store }) });
+ expect(calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(['POST /api/hooks', 'GET /api/hooks', 'DELETE /api/hooks/hoo_old', 'POST /api/hooks']);
+ expect(store.data.get('lemlist_unsubscribed_recipient_trigger_key')).toHaveProperty('webhookId', 'hoo_new');
+ });
+
+ it('onEnable on 409 with no matching URL explains the 200-webhook cap', async () => {
+ stubFetch([{ status: 409, body: { error: 'Too many webhooks' } }, { body: [] }]);
+ await expect(call({ fn: newActivity.onEnable, ctx: triggerContext({ store: makeStore() }) })).rejects.toThrow('200 webhooks');
+ });
+
+ it('onEnable deletes the new hook when the store write fails', async () => {
+ const calls = stubFetch([{ body: { _id: 'hoo_1' } }, { body: {} }]);
+ const store = makeStore();
+ store.put.mockRejectedValueOnce(new Error('store down'));
+ await expect(call({ fn: newActivity.onEnable, ctx: triggerContext({ store }) })).rejects.toThrow('store down');
+ expect(calls[1].method).toBe('DELETE');
+ expect(calls[1].url.pathname).toBe('/api/hooks/hoo_1');
+ });
+
+ it('onDisable treats 404 as already deleted and clears the store', async () => {
+ stubFetch([{ status: 404, body: {} }]);
+ const store = makeStore();
+ store.data.set('lemlist_new_activity_trigger_key', { webhookId: 'hoo_1', secret: 's' });
+ await call({ fn: newActivity.onDisable, ctx: triggerContext({ store }) });
+ expect(store.data.has('lemlist_new_activity_trigger_key')).toBe(false);
+ });
+
+ it('onDisable keeps the stored ID when the delete fails for another reason', async () => {
+ stubFetch([{ status: 500, body: {} }]);
+ const store = makeStore();
+ store.data.set('lemlist_new_activity_trigger_key', { webhookId: 'hoo_1', secret: 's' });
+ await expect(call({ fn: newActivity.onDisable, ctx: triggerContext({ store }) })).rejects.toThrow();
+ expect(store.data.has('lemlist_new_activity_trigger_key')).toBe(true);
+ });
+
+ const now = new Date().toISOString();
+ function storeWithSecret(key: string) {
+ const store = makeStore();
+ store.data.set(key, { webhookId: 'hoo_1', secret: 'expected-secret' });
+ return store;
+ }
+
+ it('run accepts a delivery with the right secret and strips it', async () => {
+ const store = storeWithSecret('lemlist_new_activity_trigger_key');
+ const out = await call({
+ fn: newActivity.run,
+ ctx: triggerContext({ store, body: { _id: 'act_1', type: 'emailsReplied', createdAt: now, secret: 'expected-secret' } }),
+ });
+ expect(out).toEqual([{ _id: 'act_1', type: 'emailsReplied', createdAt: now, _dedupe_key: 'act_1' }]);
+ });
+
+ it('run drops forged deliveries (missing or wrong secret)', async () => {
+ const store = storeWithSecret('lemlist_new_activity_trigger_key');
+ for (const secret of [undefined, 'nope', 'expected-secreT']) {
+ const out = await call({ fn: newActivity.run, ctx: triggerContext({ store, body: { _id: 'act_1', type: 'x', createdAt: now, secret } }) });
+ expect(out).toEqual([]);
+ }
+ });
+
+ it('run accepts legacy hooks registered before secrets (no stored secret)', async () => {
+ const store = makeStore();
+ store.data.set('lemlist_new_activity_trigger_key', { webhookId: 'hoo_legacy' });
+ const out = await call({ fn: newActivity.run, ctx: triggerContext({ store, body: { _id: 'act_9', type: 'x', createdAt: now } }) });
+ expect(out).toEqual([{ _id: 'act_9', type: 'x', createdAt: now, _dedupe_key: 'act_9' }]);
+ });
+
+ it('run dedupes by activity _id', async () => {
+ const store = storeWithSecret('lemlist_new_activity_trigger_key');
+ const body = { _id: 'act_1', type: 'emailsOpened', createdAt: now, secret: 'expected-secret' };
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, body }) })).toHaveLength(1);
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, body }) })).toEqual([]);
+ });
+
+ it('run drops activities older than 24 h (stale replays)', async () => {
+ const store = storeWithSecret('lemlist_new_activity_trigger_key');
+ const old = new Date(Date.now() - 25 * 3600 * 1000).toISOString();
+ const out = await call({ fn: newActivity.run, ctx: triggerContext({ store, body: { _id: 'act_2', type: 'x', createdAt: old, secret: 'expected-secret' } }) });
+ expect(out).toEqual([]);
+ });
+
+ it('run applies event type and campaign filters', async () => {
+ const store = storeWithSecret('lemlist_new_activity_trigger_key');
+ const props = { eventTypes: ['emailsReplied'], campaignId: 'cam_1' };
+ const base = { createdAt: now, secret: 'expected-secret' };
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, props, body: { ...base, _id: 'a1', type: 'emailsOpened', campaignId: 'cam_1' } }) })).toEqual([]);
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, props, body: { ...base, _id: 'a2', type: 'emailsReplied', campaignId: 'cam_2' } }) })).toEqual([]);
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, props, body: { ...base, _id: 'a3', type: 'emailsReplied', campaignId: 'cam_1' } }) })).toHaveLength(1);
+ });
+
+ it('unsubscribed recipient fires on all unsubscribe types only', async () => {
+ const store = storeWithSecret('lemlist_unsubscribed_recipient_trigger_key');
+ const base = { createdAt: now, secret: 'expected-secret' };
+ expect(await call({ fn: unsubscribedRecipient.run, ctx: triggerContext({ store, body: { ...base, _id: 'u1', type: 'entityUnsubscribed' } }) })).toHaveLength(1);
+ expect(await call({ fn: unsubscribedRecipient.run, ctx: triggerContext({ store, body: { ...base, _id: 'u2', type: 'emailsUnsubscribed' } }) })).toHaveLength(1);
+ expect(await call({ fn: unsubscribedRecipient.run, ctx: triggerContext({ store, body: { ...base, _id: 'u3', type: 'emailsOpened' } }) })).toEqual([]);
+ });
+
+ it('run parses string bodies and ignores non-JSON', async () => {
+ const store = makeStore();
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, body: 'not json' }) })).toEqual([]);
+ expect(await call({ fn: newActivity.run, ctx: triggerContext({ store, body: JSON.stringify({ _id: 'a', type: 't', createdAt: now }) }) })).toHaveLength(1);
+ });
+});
+
+describe('buildLemlistError 403', () => {
+ it('leads with lemlist reason when present', async () => {
+ const { buildLemlistError } = await import('../src/lib/common/client');
+ const withReason = buildLemlistError({ status: 403, responseBody: { message: 'LinkedIn account not linked' } });
+ expect(withReason.message).toBe('lemlist refused the request (HTTP 403): LinkedIn account not linked');
+ const generic = buildLemlistError({ status: 403, responseBody: '' });
+ expect(generic.message).toContain('the plan or API key has no access to this resource (HTTP 403).');
+ });
+});
diff --git a/packages/pieces/community/lemlist/test/helpers.ts b/packages/pieces/community/lemlist/test/helpers.ts
new file mode 100644
index 00000000000..78ed4890f4e
--- /dev/null
+++ b/packages/pieces/community/lemlist/test/helpers.ts
@@ -0,0 +1,89 @@
+import { vi } from 'vitest';
+
+export type RecordedCall = {
+ method: string;
+ url: URL;
+ headers: Record<string, string>;
+ body: unknown;
+};
+
+export type FakeResponse = {
+ status?: number;
+ body?: unknown;
+ contentType?: string;
+ raw?: Buffer | string;
+};
+
+export function stubFetch(responses: FakeResponse[] | ((call: RecordedCall) => FakeResponse)) {
+ const calls: RecordedCall[] = [];
+ const queue = Array.isArray(responses) ? [...responses] : undefined;
+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key] = value;
+ });
+ const rawBody = typeof init?.body === 'string' ? init.body : undefined;
+ const call: RecordedCall = {
+ method: init?.method ?? 'GET',
+ url: new URL(String(input)),
+ headers,
+ body: rawBody === undefined ? undefined : JSON.parse(rawBody),
+ };
+ calls.push(call);
+ const next = queue ? queue.shift() : typeof responses === 'function' ? responses(call) : undefined;
+ if (next === undefined) {
+ throw new Error(`Unexpected request ${call.method} ${call.url.toString()}`);
+ }
+ const status = next.status ?? 200;
+ if (next.raw !== undefined) {
+ return new Response(next.raw, {
+ status,
+ headers: { 'content-type': next.contentType ?? 'application/octet-stream' },
+ });
+ }
+ const payload = next.body === undefined ? '' : JSON.stringify(next.body);
+ return new Response(status === 204 ? null : payload, {
+ status,
+ headers: { 'content-type': next.contentType ?? 'application/json' },
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return calls;
+}
+
+export function makeStore() {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ get: vi.fn(async (key: string) => (data.has(key) ? data.get(key) : null)),
+ put: vi.fn(async (key: string, value: unknown) => {
+ data.set(key, value);
+ return value;
+ }),
+ delete: vi.fn(async (key: string) => {
+ data.delete(key);
+ }),
+ };
+}
+
+export function makeContext({
+ props,
+ extra = {},
+}: {
+ props: Record<string, unknown>;
+ extra?: Record<string, unknown>;
+}) {
+ const auth = { type: 'SECRET_TEXT', secret_text: API_KEY };
+ return {
+ auth,
+ propsValue: { auth, ...props },
+ store: makeStore(),
+ files: {
+ write: vi.fn(async ({ fileName }: { fileName: string }) => `https://files.example/${fileName}`),
+ },
+ ...extra,
+ };
+}
+
+export const API_KEY = 'lm-test-key';
+export const BASE = 'https://api.lemlist.com/api';
diff --git a/packages/pieces/community/lemlist/vitest.config.ts b/packages/pieces/community/lemlist/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/lemlist/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})