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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(smartlead): manage campaigns and leads from flows and AI agents, and trigger flows on campaign events (#16928)
Odai Ahmad38684347db21
diff --git a/bun.lock b/bun.lockindex 604e242e87b..597e49bc5d0 100644--- a/bun.lock+++ b/bun.lock@@ -8688,7 +8688,7 @@},"packages/pieces/community/smartlead": {"name": "@activepieces/piece-smartlead",- "version": "0.1.1",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8697,6 +8697,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/smartsheet": {diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdxindex c2db1e14675..f990e751f11 100644--- a/docs/install/reference/breaking-changes-unreleased.mdx+++ b/docs/install/reference/breaking-changes-unreleased.mdx@@ -8,6 +8,16 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut## What has changed?+#### SmartLead 0.2.0: four actions are builder-only, and Update Campaign Settings skips empty settings++**Create Campaign**, **Add Leads to Campaign**, **Get Campaign Statistics** and **Update Campaign Settings** are no longer offered to AI agents. They keep working in flows with the same names and inputs, but an agent or MCP server that used them as tools loses them after the upgrade.++From SmartLead 0.2.0 the builder's **Update Campaign Settings** skips empty settings. Track Opens, Track Clicks, Enable AI ESP Matching and Send as Plain Text are now an **On** / **Off** dropdown; left empty, the setting keeps its current value. Before, an untouched checkbox was sent as off and overwrote the campaign. The legacy Stop Lead Condition values are no longer listed, but a step that already uses one keeps working.++#### What you need to do++Agents that used these actions as tools switch to their agent versions, which have the same names: Create Campaign, Add Leads to Campaign, Get Campaign Statistics and Update Campaign Settings. Add them to the Run Agent step or MCP server again after the upgrade. If a flow step had a Yes/No setting ticked on, open it after upgrading and set that setting to On. Flow steps keep running on the version they were built with until you upgrade them.+#### Canva 0.3.0: nine actions are builder-only, and Export, Upload and Import wait for the jobCreate Design, Export Design, Find Design, Get Asset, Get Design, Get Folder, Import Design, Move Folder Item and Upload Asset are no longer offered to AI agents. They keep working in flows, but an agent or MCP client that used them as tools loses them after the upgrade.diff --git a/packages/pieces/community/smartlead/package.json b/packages/pieces/community/smartlead/package.jsonindex d61e9fa885f..6ef1ff938c6 100644--- a/packages/pieces/community/smartlead/package.json+++ b/packages/pieces/community/smartlead/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-smartlead",- "version": "0.1.1",+ "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.6.2"+ "tslib": "2.6.2",+ "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/smartlead/src/index.ts b/packages/pieces/community/smartlead/src/index.tsindex 124ff8bc1bd..f33abf68398 100644--- a/packages/pieces/community/smartlead/src/index.ts+++ b/packages/pieces/community/smartlead/src/index.ts@@ -1,5 +1,4 @@-import { createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { createCustomApiCallAction } from '@activepieces/pieces-common';import { smartleadAuth } from './lib/auth';@@ -8,21 +7,54 @@ import { createCampaignAction } from './lib/actions/create-campaign';import { addLeadsToCampaignAction } from './lib/actions/add-leads-to-campaign';import { getCampaignStatisticsAction } from './lib/actions/get-campaign-statistics';import { updateCampaignSettingsAction } from './lib/actions/update-campaign-settings';+import { updateCampaignStatusAction } from './lib/actions/update-campaign-status';+import { updateLeadStatusInCampaignAction } from './lib/actions/update-lead-status-in-campaign';+import { aiCreateCampaignAction } from './lib/actions/ai/ai-create-campaign';+import { aiAddLeadsToCampaignAction } from './lib/actions/ai/ai-add-leads-to-campaign';+import { aiGetCampaignStatisticsAction } from './lib/actions/ai/ai-get-campaign-statistics';+import { aiUpdateCampaignSettingsAction } from './lib/actions/ai/ai-update-campaign-settings';+import { aiListCampaignsAction } from './lib/actions/ai/ai-list-campaigns';+import { aiGetCampaignAction } from './lib/actions/ai/ai-get-campaign';+import { aiUpdateCampaignStatusAction } from './lib/actions/ai/ai-update-campaign-status';+import { aiDeleteCampaignAction } from './lib/actions/ai/ai-delete-campaign';+import { aiListCampaignLeadsAction } from './lib/actions/ai/ai-list-campaign-leads';+import { aiFindLeadByEmailAction } from './lib/actions/ai/ai-find-lead-by-email';+import { aiUpdateLeadStatusInCampaignAction } from './lib/actions/ai/ai-update-lead-status-in-campaign';+import { aiDeleteLeadFromCampaignAction } from './lib/actions/ai/ai-delete-lead-from-campaign';+import { aiListEmailAccountsAction } from './lib/actions/ai/ai-list-email-accounts';+import { aiGetLeadMessageHistoryAction } from './lib/actions/ai/ai-get-lead-message-history';+import { newCampaignEventTrigger } from './lib/triggers/new-campaign-event';export const smartlead = createPiece({displayName: 'SmartLead',description:'Powerful cold email outreach platform with multi-account rotation, email warmup, unified inbox, and advanced analytics.',auth: smartleadAuth,- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/smartlead.png',categories: [PieceCategory.MARKETING, PieceCategory.SALES_AND_CRM],- authors: ['Harmatta'],+ authors: ['Harmatta', 'OdaiAhmed99'],actions: [createCampaignAction,addLeadsToCampaignAction,getCampaignStatisticsAction,updateCampaignSettingsAction,+ updateCampaignStatusAction,+ updateLeadStatusInCampaignAction,+ aiCreateCampaignAction,+ aiAddLeadsToCampaignAction,+ aiGetCampaignStatisticsAction,+ aiUpdateCampaignSettingsAction,+ aiListCampaignsAction,+ aiGetCampaignAction,+ aiUpdateCampaignStatusAction,+ aiDeleteCampaignAction,+ aiListCampaignLeadsAction,+ aiFindLeadByEmailAction,+ aiUpdateLeadStatusInCampaignAction,+ aiDeleteLeadFromCampaignAction,+ aiListEmailAccountsAction,+ aiGetLeadMessageHistoryAction,createCustomApiCallAction({auth: smartleadAuth,baseUrl: () => BASE_URL,@@ -32,5 +64,5 @@ export const smartlead = createPiece({}),}),],- triggers: [],+ triggers: [newCampaignEventTrigger],});diff --git a/packages/pieces/community/smartlead/src/lib/actions/add-leads-to-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/add-leads-to-campaign.tsindex b2d2bbe3b1a..4d2a3a0b5a8 100644--- a/packages/pieces/community/smartlead/src/lib/actions/add-leads-to-campaign.ts+++ b/packages/pieces/community/smartlead/src/lib/actions/add-leads-to-campaign.ts@@ -1,7 +1,7 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { smartleadRequest } from '../common/client';import { smartleadAuth } from '../auth';+import { smartleadOperations } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';export const addLeadsToCampaignAction = createAction({auth: smartleadAuth,@@ -10,12 +10,8 @@ export const addLeadsToCampaignAction = createAction({displayName: 'Add Leads to Campaign',description:'Add one or more leads to a campaign with validation and deduplication. Maximum 400 leads per request.',- audience: 'both',- aiMetadata: {- description:- 'Adds leads to an existing SmartLead campaign by campaign ID, passing a JSON array where each lead requires an email field. Optional flags let you bypass the global block list, unsubscribe list, cross-campaign duplicate check, and community bounce list. Use to populate or grow a campaign recipient list; capped at 400 leads per call. Not idempotent: it appends leads on each call (though SmartLead deduplicates by email within the campaign).',- idempotent: false,- },+ audience: 'human',+ outputSchema: smartleadOutputSchemas.addLeads,props: {campaign_id: Property.Number({displayName: 'Campaign ID',@@ -66,67 +62,17 @@ Example:}),},async run(context) {- const {- campaign_id,- lead_list,- ignore_global_block_list,- ignore_unsubscribe_list,- ignore_duplicate_leads_in_other_campaign,- ignore_community_bounce_list,- } = context.propsValue;- const apiKey = context.auth.secret_text;-- const leads = typeof lead_list === 'string'- ? JSON.parse(lead_list)- : lead_list;-- if (!Array.isArray(leads)) {- throw new Error(- 'lead_list must be a JSON array of lead objects with at least an "email" field'- );- }-- if (leads.length === 0) {- throw new Error(- 'lead_list must contain at least one lead.'- );- }-- if (leads.length > 400) {- throw new Error(- `Maximum 400 leads per request. Got ${leads.length}. Split into multiple requests.`- );- }-- for (let i = 0; i < leads.length; i++) {- if (!leads[i].email || typeof leads[i].email !== 'string') {- throw new Error(- `Lead at index ${i} is missing a required "email" field.`- );- }- }-- const body: Record<string, unknown> = {- lead_list: leads,- };-- const settings: Record<string, boolean> = {};- if (ignore_global_block_list) settings['ignore_global_block_list'] = true;- if (ignore_unsubscribe_list) settings['ignore_unsubscribe_list'] = true;- if (ignore_duplicate_leads_in_other_campaign)- settings['ignore_duplicate_leads_in_other_campaign'] = true;- if (ignore_community_bounce_list)- settings['ignore_community_bounce_list'] = true;-- if (Object.keys(settings).length > 0) {- body['settings'] = settings;- }-- return await smartleadRequest({- endpoint: `campaigns/${campaign_id}/leads`,- method: HttpMethod.POST,- apiKey,- body,+ const p = context.propsValue;+ return smartleadOperations.addLeadsToCampaign({+ apiKey: context.auth.secret_text,+ campaignId: p.campaign_id,+ leadList: p.lead_list,+ flags: {+ ignore_global_block_list: p.ignore_global_block_list,+ ignore_unsubscribe_list: p.ignore_unsubscribe_list,+ ignore_duplicate_leads_in_other_campaign: p.ignore_duplicate_leads_in_other_campaign,+ ignore_community_bounce_list: p.ignore_community_bounce_list,+ },});},});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-add-leads-to-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-add-leads-to-campaign.tsnew file mode 100644index 00000000000..4d60851486e--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-add-leads-to-campaign.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiAddLeadsToCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'ai_add_leads_to_campaign',+ classification: 'WRITE',+ displayName: 'Add Leads to Campaign',+ description: 'Add up to 400 leads to a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Adds 1-400 leads to a SmartLead campaign by numeric campaign_id. Each lead is an object with a required email and optional first_name, last_name, company_name, phone_number, website, location, linkedin_profile, company_url and custom_fields (object of string values). SmartLead skips leads already in the campaign and reports counts (upload_count, duplicate_count, invalid_email_count, block_count). The ignore_* flags bypass block, unsubscribe, cross-campaign duplicate and community bounce checks; leave them off unless asked. Not idempotent.',+ idempotent: false,+ },+ outputSchema: smartleadOutputSchemas.addLeads,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ leads: Property.Array({+ displayName: 'Leads',+ required: true,+ properties: {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),+ company_name: Property.ShortText({ displayName: 'Company Name', required: false }),+ phone_number: Property.ShortText({ displayName: 'Phone Number', required: false }),+ website: Property.ShortText({ displayName: 'Website', required: false }),+ location: Property.ShortText({ displayName: 'Location', required: false }),+ linkedin_profile: Property.ShortText({ displayName: 'LinkedIn Profile', required: false }),+ company_url: Property.ShortText({ displayName: 'Company URL', required: false }),+ custom_fields: Property.Json({ displayName: 'Custom Fields', description: 'Object of custom field name to value.', required: false }),+ },+ }),+ ignore_global_block_list: Property.Checkbox({ displayName: 'Ignore Global Block List', required: false }),+ ignore_unsubscribe_list: Property.Checkbox({ displayName: 'Ignore Unsubscribe List', required: false }),+ ignore_duplicate_leads_in_other_campaign: Property.Checkbox({ displayName: 'Ignore Duplicates in Other Campaigns', required: false }),+ ignore_community_bounce_list: Property.Checkbox({ displayName: 'Ignore Community Bounce List', required: false }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.addLeadsToCampaign({+ apiKey: auth.secret_text,+ campaignId: propsValue.campaign_id,+ leadList: propsValue.leads,+ flags: {+ ignore_global_block_list: propsValue.ignore_global_block_list,+ ignore_unsubscribe_list: propsValue.ignore_unsubscribe_list,+ ignore_duplicate_leads_in_other_campaign: propsValue.ignore_duplicate_leads_in_other_campaign,+ ignore_community_bounce_list: propsValue.ignore_community_bounce_list,+ },+ });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-create-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-create-campaign.tsnew file mode 100644index 00000000000..b6154e81b1c--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-create-campaign.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiCreateCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'ai_create_campaign',+ classification: 'WRITE',+ displayName: 'Create Campaign',+ description: 'Create a new, empty SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a new, empty (drafted) SmartLead cold email campaign with the given name and returns its numeric id. On agency accounts pass client_id to assign it to a client. Not idempotent: each call creates another campaign even with the same name, so check List Campaigns first. Next steps: Add Leads to Campaign, Update Campaign Settings, Update Campaign Status.',+ idempotent: false,+ },+ outputSchema: smartleadOutputSchemas.createCampaign,+ props: {+ name: Property.ShortText({ displayName: 'Campaign Name', required: true }),+ client_id: Property.Number({ displayName: 'Client ID', description: 'Agency client id. Omit for your own account.', required: false }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.createCampaign({ apiKey: auth.secret_text, name: propsValue.name, clientId: propsValue.client_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-delete-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-delete-campaign.tsnew file mode 100644index 00000000000..da6fb2715ba--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-delete-campaign.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiDeleteCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'ai_delete_campaign',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Campaign',+ description: 'Permanently delete a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a SmartLead campaign by numeric campaign_id, including its sequences and lead associations. Cannot be undone; confirm with the user first. To only stop sending, use Update Campaign Status with PAUSED or STOPPED instead. Not idempotent: a second call fails because the campaign no longer exists.',+ idempotent: false,+ },+ outputSchema: smartleadOutputSchemas.deleteCampaign,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.deleteCampaign({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-delete-lead-from-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-delete-lead-from-campaign.tsnew file mode 100644index 00000000000..955d134e265--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-delete-lead-from-campaign.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiDeleteLeadFromCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'ai_delete_lead_from_campaign',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Lead from Campaign',+ description: 'Remove a lead from a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes one lead from a SmartLead campaign by numeric campaign_id and lead_id, dropping its progress in that campaign. Cannot be undone; to only stop emails use Update Lead Status in Campaign with pause or unsubscribe. Not idempotent: a second call fails because the lead is no longer in the campaign.',+ idempotent: false,+ },+ outputSchema: smartleadOutputSchemas.deleteLead,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ lead_id: Property.Number({ displayName: 'Lead ID', description: 'Numeric SmartLead lead ID (from List Campaign Leads or Find Lead by Email).', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.deleteLeadFromCampaign({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id, leadId: propsValue.lead_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-find-lead-by-email.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-find-lead-by-email.tsnew file mode 100644index 00000000000..515f4842708--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-find-lead-by-email.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiFindLeadByEmailAction = createAction({+ auth: smartleadAuth,+ name: 'ai_find_lead_by_email',+ classification: 'SEARCH',+ displayName: 'Find Lead by Email',+ description: 'Look up a SmartLead lead by email address.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Looks up a SmartLead lead by exact email address across the account. Returns found=true with the lead (id, name, company, custom_fields) or found=false with lead=null when no lead has that email. Use the lead id with the campaign lead tools. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.findLeadByEmail,+ props: {+ email: Property.ShortText({ displayName: 'Email', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.findLeadByEmail({ apiKey: auth.secret_text, email: propsValue.email });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-campaign-statistics.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-campaign-statistics.tsnew file mode 100644index 00000000000..3958259198d--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-campaign-statistics.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiGetCampaignStatisticsAction = createAction({+ auth: smartleadAuth,+ name: 'ai_get_campaign_statistics',+ classification: 'READ',+ displayName: 'Get Campaign Statistics',+ description: 'Get analytics for a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns aggregate analytics for one SmartLead campaign by numeric campaign_id: sent, open, click, reply, bounce and unsubscribe counts plus lead status counts. Use List Campaigns to find the id. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.campaignStatistics,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.getCampaignStatistics({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-campaign.tsnew file mode 100644index 00000000000..5979c38de29--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-campaign.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiGetCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'ai_get_campaign',+ classification: 'READ',+ displayName: 'Get Campaign',+ description: 'Get one SmartLead campaign with its settings.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one SmartLead campaign by numeric campaign_id: name, status, schedule, tracking (track_settings lists what is NOT tracked), stop condition, follow-up percentage and sending options. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.campaign,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.getCampaign({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-lead-message-history.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-lead-message-history.tsnew file mode 100644index 00000000000..cbf441322b3--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-get-lead-message-history.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiGetLeadMessageHistoryAction = createAction({+ auth: smartleadAuth,+ name: 'ai_get_lead_message_history',+ classification: 'READ',+ displayName: 'Get Lead Message History',+ description: 'Get the emails sent to and received from a lead in a campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the email thread between a SmartLead campaign and one lead, by numeric campaign_id and lead_id: each message has type (SENT or REPLY), time, from, to, subject and HTML body. Use it to read a lead reply. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.messageHistory,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ lead_id: Property.Number({ displayName: 'Lead ID', description: 'Numeric SmartLead lead ID (from List Campaign Leads or Find Lead by Email).', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.getLeadMessageHistory({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id, leadId: propsValue.lead_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-campaign-leads.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-campaign-leads.tsnew file mode 100644index 00000000000..7b670fe2d34--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-campaign-leads.ts@@ -0,0 +1,27 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiListCampaignLeadsAction = createAction({+ auth: smartleadAuth,+ name: 'ai_list_campaign_leads',+ classification: 'SEARCH',+ displayName: 'List Campaign Leads',+ description: 'List leads in a SmartLead campaign, one page at a time.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists leads in a SmartLead campaign by numeric campaign_id, with each lead id, email, name, company and its status in the campaign. Paginated: limit 1-100 (default 100), offset starts at 0; increase offset by limit while offset + limit < total_leads. Use the lead id with Get Lead Message History, Update Lead Status in Campaign or Delete Lead from Campaign. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.listCampaignLeads,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ offset: Property.Number({ displayName: 'Offset', description: 'Leads to skip. Default 0.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100. Default 100.', required: false }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.listCampaignLeads({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id, offset: propsValue.offset, limit: propsValue.limit });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-campaigns.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-campaigns.tsnew file mode 100644index 00000000000..4645a67af67--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-campaigns.ts@@ -0,0 +1,25 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiListCampaignsAction = createAction({+ auth: smartleadAuth,+ name: 'ai_list_campaigns',+ classification: 'SEARCH',+ displayName: 'List Campaigns',+ description: 'List all SmartLead campaigns.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists every SmartLead campaign in the account with id, name, status (DRAFTED, ACTIVE, PAUSED, STOPPED, COMPLETED), created_at, updated_at and client_id. Use it to find the numeric campaign_id other tools need. Optional client_id filters to one agency client. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.listCampaigns,+ props: {+ client_id: Property.Number({ displayName: 'Client ID', description: 'Only campaigns of this agency client.', required: false }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.listCampaigns({ apiKey: auth.secret_text, clientId: propsValue.client_id });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-email-accounts.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-email-accounts.tsnew file mode 100644index 00000000000..802b8328ac1--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-list-email-accounts.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiListEmailAccountsAction = createAction({+ auth: smartleadAuth,+ name: 'ai_list_email_accounts',+ classification: 'SEARCH',+ displayName: 'List Email Accounts',+ description: 'List the sending email accounts connected to SmartLead.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists sending mailboxes connected to SmartLead with id, from_name, from_email, type, daily limit, sent today and SMTP/IMAP health. Paginated: limit 1-100 (default 100), offset starts at 0; fewer than limit results means the last page. Read-only.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.listEmailAccounts,+ props: {+ offset: Property.Number({ displayName: 'Offset', description: 'Accounts to skip. Default 0.', required: false }),+ limit: Property.Number({ displayName: 'Limit', description: '1-100. Default 100.', required: false }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.listEmailAccounts({ apiKey: auth.secret_text, offset: propsValue.offset, limit: propsValue.limit });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-campaign-settings.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-campaign-settings.tsnew file mode 100644index 00000000000..d0bc3a43852--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-campaign-settings.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiUpdateCampaignSettingsAction = createAction({+ auth: smartleadAuth,+ name: 'ai_update_campaign_settings',+ classification: 'WRITE',+ displayName: 'Update Campaign Settings',+ description: 'Change tracking, stop condition and sending settings of a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates settings of a SmartLead campaign by numeric campaign_id. Only the fields you pass change; omitted fields stay as they are. track_opens, track_clicks, enable_ai_esp_matching and send_as_plain_text take "on" or "off"; omit them to leave them unchanged. stop_lead_settings is one of REPLY_TO_AN_EMAIL, OPEN_AN_EMAIL, CLICK_ON_A_LINK. follow_up_percentage is 0-100. At least one setting is required. Idempotent.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.updateCampaignSettings,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ track_opens: Property.ShortText({ displayName: 'Track Opens', description: '"on" or "off". Omit to keep the current value.', required: false }),+ track_clicks: Property.ShortText({ displayName: 'Track Clicks', description: '"on" or "off". Omit to keep the current value.', required: false }),+ stop_lead_settings: Property.ShortText({ displayName: 'Stop Lead Condition', description: 'REPLY_TO_AN_EMAIL, OPEN_AN_EMAIL or CLICK_ON_A_LINK.', required: false }),+ unsubscribe_text: Property.LongText({ displayName: 'Unsubscribe Text', required: false }),+ enable_ai_esp_matching: Property.ShortText({ displayName: 'Enable AI ESP Matching', description: '"on" or "off". Omit to keep the current value.', required: false }),+ send_as_plain_text: Property.ShortText({ displayName: 'Send as Plain Text', description: '"on" or "off". Omit to keep the current value.', required: false }),+ follow_up_percentage: Property.Number({ displayName: 'Follow Up Percentage', description: '0-100.', required: false }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.updateCampaignSettings({+ apiKey: auth.secret_text,+ campaignId: propsValue.campaign_id,+ settings: {+ trackOpens: smartleadOperations.parseOnOff({ value: propsValue.track_opens, label: 'track_opens' }),+ trackClicks: smartleadOperations.parseOnOff({ value: propsValue.track_clicks, label: 'track_clicks' }),+ stopLeadSettings: propsValue.stop_lead_settings,+ unsubscribeText: propsValue.unsubscribe_text,+ enableAiEspMatching: smartleadOperations.parseOnOff({ value: propsValue.enable_ai_esp_matching, label: 'enable_ai_esp_matching' }),+ sendAsPlainText: smartleadOperations.parseOnOff({ value: propsValue.send_as_plain_text, label: 'send_as_plain_text' }),+ followUpPercentage: propsValue.follow_up_percentage,+ },+ });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-campaign-status.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-campaign-status.tsnew file mode 100644index 00000000000..77872c334f5--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-campaign-status.ts@@ -0,0 +1,26 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiUpdateCampaignStatusAction = createAction({+ auth: smartleadAuth,+ name: 'ai_update_campaign_status',+ classification: 'DESTRUCTIVE',+ displayName: 'Update Campaign Status',+ description: 'Start, pause or stop a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Sets the status of a SmartLead campaign by numeric campaign_id. status is START (begins sending real emails to its leads), PAUSED (can be started again) or STOPPED (ends the campaign; cannot be restarted). Confirm with the user before START or STOPPED. Idempotent: repeating the same status leaves the campaign unchanged.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.updateCampaignStatus,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ status: Property.ShortText({ displayName: 'Status', description: 'START, PAUSED or STOPPED.', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.updateCampaignStatus({ apiKey: auth.secret_text, campaignId: propsValue.campaign_id, status: propsValue.status.trim().toUpperCase() });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-lead-status-in-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-lead-status-in-campaign.tsnew file mode 100644index 00000000000..6a175cab09e--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/ai/ai-update-lead-status-in-campaign.ts@@ -0,0 +1,32 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../../auth';+import { smartleadOperations } from '../../common/operations';+import { smartleadOutputSchemas } from '../../common/output-schemas';++export const aiUpdateLeadStatusInCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'ai_update_lead_status_in_campaign',+ classification: 'DESTRUCTIVE',+ displayName: 'Update Lead Status in Campaign',+ description: 'Pause, resume or unsubscribe a lead in a SmartLead campaign.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes how a SmartLead campaign treats one lead, by numeric campaign_id and lead_id. action is pause (stop sending to this lead for now), resume (continue the sequence) or unsubscribe (permanently stop emailing this lead in this campaign). Idempotent: repeating the same action leaves the lead in the same state.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.updateLeadStatus,+ props: {+ campaign_id: Property.Number({ displayName: 'Campaign ID', description: 'Numeric SmartLead campaign ID (from List Campaigns).', required: true }),+ lead_id: Property.Number({ displayName: 'Lead ID', description: 'Numeric SmartLead lead ID (from List Campaign Leads or Find Lead by Email).', required: true }),+ action: Property.ShortText({ displayName: 'Action', description: 'pause, resume or unsubscribe.', required: true }),+ },+ async run({ auth, propsValue }) {+ return smartleadOperations.updateLeadStatusInCampaign({+ apiKey: auth.secret_text,+ campaignId: propsValue.campaign_id,+ leadId: propsValue.lead_id,+ action: propsValue.action.trim().toLowerCase(),+ });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/create-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/create-campaign.tsindex cd4a28314d2..55ab05fd8af 100644--- a/packages/pieces/community/smartlead/src/lib/actions/create-campaign.ts+++ b/packages/pieces/community/smartlead/src/lib/actions/create-campaign.ts@@ -1,7 +1,7 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { smartleadRequest } from '../common/client';import { smartleadAuth } from '../auth';+import { smartleadOperations } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';export const createCampaignAction = createAction({auth: smartleadAuth,@@ -9,17 +9,12 @@ export const createCampaignAction = createAction({classification: 'WRITE',displayName: 'Create Campaign',description: 'Create a new cold email campaign in SmartLead',- audience: 'both',- aiMetadata: {- description:- 'Creates a new, empty cold email campaign in SmartLead, identified by name; on agency/white-label accounts an optional client ID associates it with a specific client. Use this as the first step before adding leads or configuring sequences. Not idempotent: each call creates a separate campaign even with the same name.',- idempotent: false,- },+ audience: 'human',+ outputSchema: smartleadOutputSchemas.createCampaign,props: {name: Property.ShortText({displayName: 'Campaign Name',- description:- 'Name of the campaign. Defaults to "Untitled Campaign" if not provided.',+ description: 'Name of the new campaign.',required: true,}),client_id: Property.Number({@@ -30,19 +25,10 @@ export const createCampaignAction = createAction({}),},async run(context) {- const { name, client_id } = context.propsValue;- const apiKey = context.auth.secret_text;-- const body: Record<string, unknown> = { name };- if (client_id !== undefined && client_id !== null) {- body['client_id'] = client_id;- }-- return await smartleadRequest({- endpoint: 'campaigns/create',- method: HttpMethod.POST,- apiKey,- body,+ return smartleadOperations.createCampaign({+ apiKey: context.auth.secret_text,+ name: context.propsValue.name,+ clientId: context.propsValue.client_id,});},});diff --git a/packages/pieces/community/smartlead/src/lib/actions/get-campaign-statistics.ts b/packages/pieces/community/smartlead/src/lib/actions/get-campaign-statistics.tsindex 5f96b74ef8d..cb617b4e131 100644--- a/packages/pieces/community/smartlead/src/lib/actions/get-campaign-statistics.ts+++ b/packages/pieces/community/smartlead/src/lib/actions/get-campaign-statistics.ts@@ -1,7 +1,8 @@-import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { smartleadRequest } from '../common/client';+import { createAction } from '@activepieces/pieces-framework';import { smartleadAuth } from '../auth';+import { smartleadOperations } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';+import { smartleadProps } from '../common/props';export const getCampaignStatisticsAction = createAction({auth: smartleadAuth,@@ -10,27 +11,17 @@ export const getCampaignStatisticsAction = createAction({displayName: 'Get Campaign Statistics',description:'Retrieve comprehensive analytics for a campaign including open rates, click rates, reply rates, and engagement statistics.',- audience: 'both',- aiMetadata: {- description:- 'Fetches aggregate performance analytics for a single SmartLead campaign by campaign ID, covering open, click, and reply rates and related engagement metrics. Use to report on or evaluate how a campaign is performing. Read-only and idempotent.',- idempotent: true,- },+ audience: 'human',+ outputSchema: smartleadOutputSchemas.campaignStatistics,props: {- campaign_id: Property.Number({- displayName: 'Campaign ID',- description: 'The ID of the campaign to get statistics for',- required: true,+ campaign_id: smartleadProps.campaignDropdown({+ description: 'The campaign to get statistics for',}),},async run(context) {- const { campaign_id } = context.propsValue;- const apiKey = context.auth.secret_text;-- return await smartleadRequest({- endpoint: `campaigns/${campaign_id}/analytics`,- method: HttpMethod.GET,- apiKey,+ return smartleadOperations.getCampaignStatistics({+ apiKey: context.auth.secret_text,+ campaignId: context.propsValue.campaign_id,});},});diff --git a/packages/pieces/community/smartlead/src/lib/actions/update-campaign-settings.ts b/packages/pieces/community/smartlead/src/lib/actions/update-campaign-settings.tsindex 5995f5b86e4..01f1fbf36a7 100644--- a/packages/pieces/community/smartlead/src/lib/actions/update-campaign-settings.ts+++ b/packages/pieces/community/smartlead/src/lib/actions/update-campaign-settings.ts@@ -1,7 +1,8 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { HttpMethod } from '@activepieces/pieces-common';-import { smartleadRequest } from '../common/client';import { smartleadAuth } from '../auth';+import { smartleadOperations, STOP_LEAD_OPTIONS } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';+import { smartleadProps } from '../common/props';export const updateCampaignSettingsAction = createAction({auth: smartleadAuth,@@ -9,115 +10,62 @@ export const updateCampaignSettingsAction = createAction({classification: 'WRITE',displayName: 'Update Campaign Settings',description:- 'Update campaign settings including tracking, stop conditions, and deliverability options.',- audience: 'both',- aiMetadata: {- description:- 'Updates configuration on an existing SmartLead campaign by campaign ID, such as open/click tracking, the stop-lead condition, unsubscribe text, AI ESP matching, plain-text sending, and follow-up percentage. Use to adjust how a campaign sends and tracks; at least one setting must be supplied and follow-up percentage must be 0-100. Idempotent: it overwrites the targeted settings, so repeating the same input leaves the campaign in the same state.',- idempotent: true,- },+ 'Update campaign settings including tracking, stop conditions, and deliverability options. Settings left empty are not changed.',+ audience: 'human',+ outputSchema: smartleadOutputSchemas.updateCampaignSettings,props: {campaign_id: Property.Number({displayName: 'Campaign ID',description: 'The ID of the campaign to update',required: true,}),- track_open: Property.Checkbox({+ track_open: smartleadProps.triStateDropdown({displayName: 'Track Opens',- description: 'Enable email open tracking',- required: false,+ description: 'Email open tracking.',}),- track_click: Property.Checkbox({+ track_click: smartleadProps.triStateDropdown({displayName: 'Track Clicks',- description: 'Enable link click tracking',- required: false,+ description: 'Link click tracking.',}),stop_lead_settings: Property.StaticDropdown({displayName: 'Stop Lead Condition',description: 'When to stop emailing a lead',required: false,- options: {- options: [- { label: 'Reply to an email', value: 'REPLY_TO_AN_EMAIL' },- { label: 'Opened email', value: 'OPENED_EMAIL' },- { label: 'Clicked link', value: 'CLICKED_LINK' },- ],- },+ options: { options: STOP_LEAD_OPTIONS },}),unsubscribe_text: Property.LongText({displayName: 'Unsubscribe Text',description: 'Custom unsubscribe text added to campaign emails',required: false,}),- enable_ai_esp_matching: Property.Checkbox({+ enable_ai_esp_matching: smartleadProps.triStateDropdown({displayName: 'Enable AI ESP Matching',- description:- 'Use AI to intelligently pair leads with optimal email accounts',- required: false,+ description: 'Use AI to pair leads with the best-matching email accounts.',}),- send_as_plain_text: Property.Checkbox({+ send_as_plain_text: smartleadProps.triStateDropdown({displayName: 'Send as Plain Text',- description:- 'Send emails as plain text for better deliverability with technical audiences',- required: false,+ description: 'Send emails as plain text.',}),follow_up_percentage: Property.Number({displayName: 'Follow Up Percentage',- description:- 'Percentage of leads to follow up with (0-100)',+ description: 'Percentage of leads to follow up with (0-100)',required: false,}),},async run(context) {- const {- campaign_id,- track_open,- track_click,- stop_lead_settings,- unsubscribe_text,- enable_ai_esp_matching,- send_as_plain_text,- follow_up_percentage,- } = context.propsValue;- const apiKey = context.auth.secret_text;-- const body: Record<string, unknown> = {};-- if (track_open !== undefined || track_click !== undefined) {- body['track_settings'] = {- ...(track_open !== undefined && { track_open }),- ...(track_click !== undefined && { track_click }),- };- }-- if (stop_lead_settings !== undefined)- body['stop_lead_settings'] = stop_lead_settings;- if (unsubscribe_text !== undefined && unsubscribe_text !== '')- body['unsubscribe_text'] = unsubscribe_text;- if (enable_ai_esp_matching !== undefined)- body['enable_ai_esp_matching'] = enable_ai_esp_matching;- if (send_as_plain_text !== undefined)- body['send_as_plain_text'] = send_as_plain_text;- if (follow_up_percentage !== undefined) {- if (follow_up_percentage < 0 || follow_up_percentage > 100) {- throw new Error(- `follow_up_percentage must be between 0 and 100. Got ${follow_up_percentage}.`- );- }- body['follow_up_percentage'] = follow_up_percentage;- }-- if (Object.keys(body).length === 0) {- throw new Error(- 'At least one setting must be provided to update.'- );- }-- return await smartleadRequest({- endpoint: `campaigns/${campaign_id}/settings`,- method: HttpMethod.POST,- apiKey,- body,+ const p = context.propsValue;+ return smartleadOperations.updateCampaignSettings({+ apiKey: context.auth.secret_text,+ campaignId: p.campaign_id,+ settings: {+ trackOpens: smartleadOperations.parseTriStateBoolean({ value: p.track_open, label: 'Track Opens' }),+ trackClicks: smartleadOperations.parseTriStateBoolean({ value: p.track_click, label: 'Track Clicks' }),+ stopLeadSettings: p.stop_lead_settings,+ unsubscribeText: p.unsubscribe_text,+ enableAiEspMatching: smartleadOperations.parseTriStateBoolean({ value: p.enable_ai_esp_matching, label: 'Enable AI ESP Matching' }),+ sendAsPlainText: smartleadOperations.parseTriStateBoolean({ value: p.send_as_plain_text, label: 'Send as Plain Text' }),+ followUpPercentage: p.follow_up_percentage,+ },});},});diff --git a/packages/pieces/community/smartlead/src/lib/actions/update-campaign-status.ts b/packages/pieces/community/smartlead/src/lib/actions/update-campaign-status.tsnew file mode 100644index 00000000000..0ae3ed8752a--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/update-campaign-status.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../auth';+import { smartleadOperations } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';+import { smartleadProps } from '../common/props';++export const updateCampaignStatusAction = createAction({+ auth: smartleadAuth,+ name: 'update_campaign_status',+ classification: 'DESTRUCTIVE',+ displayName: 'Update Campaign Status',+ description: 'Start, pause or stop a campaign. Starting sends real emails to its leads; a stopped campaign cannot be restarted.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Sets the status of a SmartLead campaign by numeric campaign_id: START begins sending real emails to its leads, PAUSED halts sending and can be started again, STOPPED ends the campaign permanently. Confirm with the user before START or STOPPED. Idempotent: repeating the same status leaves the campaign unchanged.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.updateCampaignStatus,+ props: {+ campaign_id: smartleadProps.campaignDropdown({+ description: 'The campaign to update.',+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ required: true,+ options: {+ options: [+ { label: 'Start', value: 'START' },+ { label: 'Pause', value: 'PAUSED' },+ { label: 'Stop', value: 'STOPPED' },+ ],+ },+ }),+ },+ async run(context) {+ return smartleadOperations.updateCampaignStatus({+ apiKey: context.auth.secret_text,+ campaignId: context.propsValue.campaign_id,+ status: context.propsValue.status,+ });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/actions/update-lead-status-in-campaign.ts b/packages/pieces/community/smartlead/src/lib/actions/update-lead-status-in-campaign.tsnew file mode 100644index 00000000000..7245f29c80a--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/actions/update-lead-status-in-campaign.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../auth';+import { smartleadOperations } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';+import { smartleadProps } from '../common/props';++export const updateLeadStatusInCampaignAction = createAction({+ auth: smartleadAuth,+ name: 'update_lead_status_in_campaign',+ classification: 'DESTRUCTIVE',+ displayName: 'Update Lead Status in Campaign',+ description: 'Pause, resume or unsubscribe a lead in a campaign.',+ audience: 'human',+ aiMetadata: {+ description:+ 'Changes how a SmartLead campaign treats one lead, by numeric campaign_id and lead_id: pause stops sending to the lead for now, resume continues its sequence, unsubscribe permanently stops emailing it in this campaign. Find the lead id with Find Lead by Email or List Campaign Leads. Idempotent: repeating the same action leaves the lead in the same state.',+ idempotent: true,+ },+ outputSchema: smartleadOutputSchemas.updateLeadStatus,+ props: {+ campaign_id: smartleadProps.campaignDropdown({+ description: 'The campaign the lead belongs to.',+ }),+ lead_id: Property.Number({+ displayName: 'Lead ID',+ description: 'Numeric SmartLead lead ID, e.g. from a previous step that found the lead by email.',+ required: true,+ }),+ action: Property.StaticDropdown({+ displayName: 'Action',+ required: true,+ options: {+ options: [+ { label: 'Pause', value: 'pause' },+ { label: 'Resume', value: 'resume' },+ { label: 'Unsubscribe', value: 'unsubscribe' },+ ],+ },+ }),+ },+ async run(context) {+ return smartleadOperations.updateLeadStatusInCampaign({+ apiKey: context.auth.secret_text,+ campaignId: context.propsValue.campaign_id,+ leadId: context.propsValue.lead_id,+ action: context.propsValue.action,+ });+ },+});diff --git a/packages/pieces/community/smartlead/src/lib/auth.ts b/packages/pieces/community/smartlead/src/lib/auth.tsindex 4ffe8d15f41..3997ec74a8f 100644--- a/packages/pieces/community/smartlead/src/lib/auth.ts+++ b/packages/pieces/community/smartlead/src/lib/auth.ts@@ -1,11 +1,11 @@import { PieceAuth } from '@activepieces/pieces-framework';-import { httpClient, HttpMethod } from '@activepieces/pieces-common';-import { BASE_URL } from './common/client';+import { HttpMethod } from '@activepieces/pieces-common';+import { smartleadRequest, SmartleadApiError } from './common/client';const markdownDescription = `To obtain your API key:1. Log in to your SmartLead account-2. Go to **Profile -> Settings → API Key **+2. Go to **Settings → API Key**3. Copy your API keyThe API key is passed as a query parameter to all API requests.@@ -17,23 +17,26 @@ export const smartleadAuth = PieceAuth.SecretText({required: true,validate: async ({ auth }) => {try {- await httpClient.sendRequest({+ await smartleadRequest({+ endpoint: 'campaigns',method: HttpMethod.GET,- url: `${BASE_URL}/campaigns`,- queryParams: {- api_key: auth,- },+ apiKey: auth,});return { valid: true };} catch (error: unknown) {- const status = (error as { response?: { status?: number } })?.response?.status;- if (status === 401 || status === 403) {+ if (+ error instanceof SmartleadApiError &&+ (error.statusCode === 401 || error.statusCode === 403)+ ) {return {valid: false,- error: 'Invalid API key. Please check your Smartlead API credentials.',+ error: 'Invalid API key. Please check your SmartLead API credentials.',};}- throw error;+ return {+ valid: false,+ error: 'Could not reach SmartLead to validate the API key. Please try again.',+ };}},});diff --git a/packages/pieces/community/smartlead/src/lib/common/client.ts b/packages/pieces/community/smartlead/src/lib/common/client.tsindex 9819ef98fd2..bbfe2e94b72 100644--- a/packages/pieces/community/smartlead/src/lib/common/client.ts+++ b/packages/pieces/community/smartlead/src/lib/common/client.ts@@ -1,8 +1,6 @@import { HttpMethod, httpClient } from '@activepieces/pieces-common';-export const BASE_URL = 'https://server.smartlead.ai/api/v1';--export async function smartleadRequest<T = Record<string, unknown>>({+async function smartleadRequest<T>({endpoint,method,apiKey,@@ -12,28 +10,112 @@ export async function smartleadRequest<T = Record<string, unknown>>({endpoint: string;method: HttpMethod;apiKey: string;- body?: Record<string, unknown>;- queryParams?: Record<string, string | number | boolean>;+ body?: unknown;+ queryParams?: Record<string, string | number | boolean | undefined | null>;}): Promise<T> {- const allParams: Record<string, string> = {- api_key: apiKey,- };-+ const allParams: Record<string, string> = { api_key: apiKey };for (const [k, value] of Object.entries(queryParams)) {if (value !== undefined && value !== null) {allParams[k] = String(value);}}+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${BASE_URL}/${endpoint}`,+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ queryParams: allParams,+ body,+ });+ return response.body;+ } catch (error: unknown) {+ throw toSmartleadError({ error, endpoint, method });+ }+}- const response = await httpClient.sendRequest({- method,- url: `${BASE_URL}/${endpoint}`,- headers: {- 'Content-Type': 'application/json',- },- queryParams: allParams,- body,+function readFailure(error: unknown): { status: number | undefined; body: unknown } {+ if (typeof error !== 'object' || error === null) {+ return { status: undefined, body: undefined };+ }+ const response: unknown = Reflect.get(error, 'response');+ if (typeof response !== 'object' || response === null) {+ return { status: undefined, body: undefined };+ }+ const status: unknown = Reflect.get(response, 'status');+ return {+ status: typeof status === 'number' ? status : undefined,+ body: Reflect.get(response, 'body'),+ };+}++function vendorMessage(body: unknown): string | undefined {+ if (typeof body === 'string' && body.trim() !== '') {+ return body.slice(0, 300);+ }+ if (typeof body === 'object' && body !== null) {+ for (const key of ['message', 'error', 'detail']) {+ const value: unknown = Reflect.get(body, key);+ if (typeof value === 'string' && value.trim() !== '') {+ return value.slice(0, 300);+ }+ }+ }+ return undefined;+}++function toSmartleadError({+ error,+ endpoint,+ method,+}: {+ error: unknown;+ endpoint: string;+ method: HttpMethod;+}): SmartleadApiError {+ const { status, body } = readFailure(error);+ const detail = vendorMessage(body);+ const path = endpoint.split('?')[0];+ let message: string;+ if (status === 401 || status === 403) {+ message = 'SmartLead rejected the API key. Check the connection.';+ } else if (status === 404) {+ message = `SmartLead could not find the requested resource (${method} /${path}).`;+ } else if (status === 429) {+ message = 'SmartLead rate limit reached (about 10 requests per 2 seconds). Try again shortly.';+ } else if (status === undefined) {+ message = `SmartLead request failed (${method} /${path}): network error.`;+ } else {+ message = `SmartLead request failed with status ${status} (${method} /${path}).`;+ }+ return new SmartleadApiError({+ message: detail ? `${message} ${detail}` : message,+ statusCode: status,+ responseBody: body,});+}- return response.body as T;+class SmartleadApiError extends Error {+ readonly statusCode: number | undefined;+ readonly responseBody: unknown;+ constructor({+ message,+ statusCode,+ responseBody,+ }: {+ message: string;+ statusCode: number | undefined;+ responseBody: unknown;+ }) {+ super(message);+ this.name = 'SmartleadApiError';+ this.statusCode = statusCode;+ this.responseBody = responseBody;+ }}++const BASE_URL = 'https://server.smartlead.ai/api/v1';++export { BASE_URL, smartleadRequest, SmartleadApiError };diff --git a/packages/pieces/community/smartlead/src/lib/common/operations.ts b/packages/pieces/community/smartlead/src/lib/common/operations.tsnew file mode 100644index 00000000000..53666a1e865--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/common/operations.ts@@ -0,0 +1,599 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { isNil } from '@activepieces/pieces-framework';+import { smartleadRequest, SmartleadApiError } from './client';++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function pick({ source, key }: { source: unknown; key: string }): unknown {+ return isRecord(source) ? source[key] ?? null : null;+}++function requireId({ value, label }: { value: unknown; label: string }): number {+ const parsed = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed <= 0) {+ throw new Error(`${label} must be a positive whole number.`);+ }+ return parsed;+}++function pageParams({ offset, limit }: { offset: unknown; limit: unknown }): { offset: number; limit: number } {+ const safeOffset = typeof offset === 'number' && Number.isInteger(offset) && offset >= 0 ? offset : 0;+ if (!isNil(limit) && (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE_SIZE)) {+ throw new Error(`Limit must be a whole number between 1 and ${MAX_PAGE_SIZE}.`);+ }+ return { offset: safeOffset, limit: typeof limit === 'number' ? limit : MAX_PAGE_SIZE };+}++function requireCampaignBody({ response, id }: { response: unknown; id: number }): Record<string, unknown> {+ if (!isRecord(response) || Object.keys(response).length === 0) {+ throw new Error(`Campaign ${id} not found.`);+ }+ return response;+}++async function createCampaign({+ apiKey,+ name,+ clientId,+}: {+ apiKey: string;+ name: string;+ clientId?: number | null;+}) {+ const trimmed = typeof name === 'string' ? name.trim() : '';+ if (trimmed === '') {+ throw new Error('Campaign name is required.');+ }+ const body: Record<string, unknown> = { name: trimmed };+ if (!isNil(clientId)) {+ body['client_id'] = requireId({ value: clientId, label: 'Client ID' });+ }+ const response = await smartleadRequest<unknown>({+ endpoint: 'campaigns/create',+ method: HttpMethod.POST,+ apiKey,+ body,+ });+ return {+ ok: pick({ source: response, key: 'ok' }) ?? true,+ id: pick({ source: response, key: 'id' }),+ name: pick({ source: response, key: 'name' }),+ created_at: pick({ source: response, key: 'created_at' }),+ };+}++function parseLeadList(leadList: unknown): Record<string, unknown>[] {+ let leads: unknown = leadList;+ if (typeof leadList === 'string') {+ try {+ leads = JSON.parse(leadList);+ } catch {+ throw new Error('Lead list is not valid JSON. Provide a JSON array of lead objects.');+ }+ }+ if (!Array.isArray(leads)) {+ throw new Error('Lead list must be a JSON array of lead objects with at least an "email" field.');+ }+ if (leads.length === 0) {+ throw new Error('Lead list must contain at least one lead.');+ }+ if (leads.length > MAX_LEADS_PER_REQUEST) {+ throw new Error(+ `Maximum ${MAX_LEADS_PER_REQUEST} leads per request. Got ${leads.length}. Split into multiple requests.`+ );+ }+ const result: Record<string, unknown>[] = [];+ leads.forEach((lead: unknown, index: number) => {+ if (!isRecord(lead)) {+ throw new Error(`Lead at index ${index} must be an object.`);+ }+ const email = lead['email'];+ if (typeof email !== 'string' || email.trim() === '') {+ throw new Error(`Lead at index ${index} is missing a required "email" field.`);+ }+ const compact = Object.fromEntries(+ Object.entries(lead).filter(([, value]) => value !== undefined && value !== null && value !== '')+ );+ result.push({ ...compact, email: email.trim() });+ });+ return result;+}++async function addLeadsToCampaign({+ apiKey,+ campaignId,+ leadList,+ flags,+}: {+ apiKey: string;+ campaignId: unknown;+ leadList: unknown;+ flags: LeadUploadFlags;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const leads = parseLeadList(leadList);+ const body: Record<string, unknown> = { lead_list: leads };+ const settings: Record<string, boolean> = {};+ for (const [key, value] of Object.entries(flags)) {+ if (value === true) {+ settings[key] = true;+ }+ }+ if (Object.keys(settings).length > 0) {+ body['settings'] = settings;+ }+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/leads`,+ method: HttpMethod.POST,+ apiKey,+ body,+ });+ return {+ ok: pick({ source: response, key: 'ok' }) ?? true,+ upload_count: pick({ source: response, key: 'upload_count' }),+ total_leads: pick({ source: response, key: 'total_leads' }),+ already_added_to_campaign: pick({ source: response, key: 'already_added_to_campaign' }),+ duplicate_count: pick({ source: response, key: 'duplicate_count' }),+ invalid_email_count: pick({ source: response, key: 'invalid_email_count' }),+ unsubscribed_leads: pick({ source: response, key: 'unsubscribed_leads' }),+ block_count: pick({ source: response, key: 'block_count' }),+ };+}++async function getCampaignStatistics({ apiKey, campaignId }: { apiKey: string; campaignId: unknown }) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/analytics`,+ method: HttpMethod.GET,+ apiKey,+ });+ return requireCampaignBody({ response, id });+}++function mergeTrackSettings({+ current,+ trackOpens,+ trackClicks,+}: {+ current: unknown;+ trackOpens: boolean | null | undefined;+ trackClicks: boolean | null | undefined;+}): string[] {+ if (!Array.isArray(current)) {+ throw new Error(+ 'SmartLead did not return the current tracking settings for this campaign, so tracking was not changed to avoid clearing other tracking options. Update the other settings without tracking, or change tracking in SmartLead.'+ );+ }+ const existing = current+ .filter((v: unknown): v is string => typeof v === 'string')+ .map((v) => READ_TRACK_ALIASES[v] ?? v);+ const next = new Set(existing);+ const apply = ({ flag, track }: { flag: string; track: boolean | null | undefined }) => {+ if (track === true) next.delete(flag);+ if (track === false) next.add(flag);+ };+ apply({ flag: DONT_TRACK_OPEN, track: trackOpens });+ apply({ flag: DONT_TRACK_CLICK, track: trackClicks });+ return [...next];+}++async function updateCampaignSettings({+ apiKey,+ campaignId,+ settings,+}: {+ apiKey: string;+ campaignId: unknown;+ settings: CampaignSettingsInput;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const body: Record<string, unknown> = {};++ if (!isNil(settings.trackOpens) || !isNil(settings.trackClicks)) {+ const campaign = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}`,+ method: HttpMethod.GET,+ apiKey,+ });+ body['track_settings'] = mergeTrackSettings({+ current: pick({ source: campaign, key: 'track_settings' }),+ trackOpens: settings.trackOpens,+ trackClicks: settings.trackClicks,+ });+ }+ if (!isNil(settings.stopLeadSettings) && settings.stopLeadSettings !== '') {+ const raw = settings.stopLeadSettings;+ const value = LEGACY_STOP_LEAD_VALUES[raw] ?? raw;+ if (!STOP_LEAD_OPTIONS.some((o) => o.value === value)) {+ throw new Error(`Stop lead condition must be one of ${STOP_LEAD_OPTIONS.map((o) => o.value).join(', ')}.`);+ }+ body['stop_lead_settings'] = value;+ }+ if (!isNil(settings.unsubscribeText) && settings.unsubscribeText !== '') {+ body['unsubscribe_text'] = settings.unsubscribeText;+ }+ if (!isNil(settings.enableAiEspMatching)) {+ body['enable_ai_esp_matching'] = settings.enableAiEspMatching;+ }+ if (!isNil(settings.sendAsPlainText)) {+ body['send_as_plain_text'] = settings.sendAsPlainText;+ }+ if (!isNil(settings.followUpPercentage)) {+ const pct = settings.followUpPercentage;+ if (!Number.isFinite(pct) || pct < 0 || pct > 100) {+ throw new Error(`Follow up percentage must be between 0 and 100. Got ${pct}.`);+ }+ body['follow_up_percentage'] = pct;+ }+ if (Object.keys(body).length === 0) {+ throw new Error('At least one setting must be provided to update.');+ }+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/settings`,+ method: HttpMethod.POST,+ apiKey,+ body,+ });+ return { ok: pick({ source: response, key: 'ok' }) ?? true, campaign_id: id, updated: body };+}++function mapCampaignSummary(campaign: unknown) {+ return {+ id: pick({ source: campaign, key: 'id' }),+ name: pick({ source: campaign, key: 'name' }),+ status: pick({ source: campaign, key: 'status' }),+ created_at: pick({ source: campaign, key: 'created_at' }),+ updated_at: pick({ source: campaign, key: 'updated_at' }),+ client_id: pick({ source: campaign, key: 'client_id' }),+ };+}++async function listCampaigns({ apiKey, clientId }: { apiKey: string; clientId?: number | null }) {+ const response = await smartleadRequest<unknown>({+ endpoint: 'campaigns',+ method: HttpMethod.GET,+ apiKey,+ queryParams: isNil(clientId) ? {} : { client_id: requireId({ value: clientId, label: 'Client ID' }) },+ });+ const campaigns = Array.isArray(response) ? response.map(mapCampaignSummary) : [];+ return { campaigns };+}++async function getCampaign({ apiKey, campaignId }: { apiKey: string; campaignId: unknown }) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}`,+ method: HttpMethod.GET,+ apiKey,+ });+ return requireCampaignBody({ response, id });+}++async function updateCampaignStatus({+ apiKey,+ campaignId,+ status,+}: {+ apiKey: string;+ campaignId: unknown;+ status: unknown;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const match = CAMPAIGN_STATUSES.find((s) => s === status);+ if (isNil(match)) {+ throw new Error(`Status must be one of ${CAMPAIGN_STATUSES.join(', ')}.`);+ }+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/status`,+ method: HttpMethod.POST,+ apiKey,+ body: { status: match },+ });+ return { ok: pick({ source: response, key: 'ok' }) ?? true, campaign_id: id, status: match };+}++async function deleteCampaign({ apiKey, campaignId }: { apiKey: string; campaignId: unknown }) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}`,+ method: HttpMethod.DELETE,+ apiKey,+ });+ return { ok: pick({ source: response, key: 'ok' }) ?? true, campaign_id: id };+}++async function listCampaignLeads({+ apiKey,+ campaignId,+ offset,+ limit,+}: {+ apiKey: string;+ campaignId: unknown;+ offset: unknown;+ limit: unknown;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const page = pageParams({ offset, limit });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/leads`,+ method: HttpMethod.GET,+ apiKey,+ queryParams: page,+ });+ const data = pick({ source: response, key: 'data' });+ return {+ total_leads: pick({ source: response, key: 'total_leads' }),+ offset: page.offset,+ limit: page.limit,+ leads: Array.isArray(data) ? data : [],+ };+}++async function findLeadByEmail({ apiKey, email }: { apiKey: string; email: unknown }) {+ const trimmed = typeof email === 'string' ? email.trim() : '';+ if (trimmed === '') {+ throw new Error('Email is required.');+ }+ const response = await smartleadRequest<unknown>({+ endpoint: 'leads/',+ method: HttpMethod.GET,+ apiKey,+ queryParams: { email: trimmed },+ });+ if (!isRecord(response) || isNil(response['id'])) {+ return { found: false, lead: null };+ }+ return { found: true, lead: response };+}++async function updateLeadStatusInCampaign({+ apiKey,+ campaignId,+ leadId,+ action,+}: {+ apiKey: string;+ campaignId: unknown;+ leadId: unknown;+ action: unknown;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const lead = requireId({ value: leadId, label: 'Lead ID' });+ const match = LEAD_STATUS_ACTIONS.find((a) => a === action);+ if (isNil(match)) {+ throw new Error(`Action must be one of ${LEAD_STATUS_ACTIONS.join(', ')}.`);+ }+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/leads/${lead}/${match}`,+ method: HttpMethod.POST,+ apiKey,+ body: {},+ });+ return { ok: pick({ source: response, key: 'ok' }) ?? true, campaign_id: id, lead_id: lead, action: match };+}++async function deleteLeadFromCampaign({+ apiKey,+ campaignId,+ leadId,+}: {+ apiKey: string;+ campaignId: unknown;+ leadId: unknown;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const lead = requireId({ value: leadId, label: 'Lead ID' });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/leads/${lead}`,+ method: HttpMethod.DELETE,+ apiKey,+ });+ return { ok: pick({ source: response, key: 'ok' }) ?? true, campaign_id: id, lead_id: lead };+}++async function listEmailAccounts({ apiKey, offset, limit }: { apiKey: string; offset: unknown; limit: unknown }) {+ const page = pageParams({ offset, limit });+ const response = await smartleadRequest<unknown>({+ endpoint: 'email-accounts',+ method: HttpMethod.GET,+ apiKey,+ queryParams: page,+ });+ const accounts = Array.isArray(response) ? response : [];+ return {+ offset: page.offset,+ limit: page.limit,+ email_accounts: accounts.map((account: unknown) => ({+ id: pick({ source: account, key: 'id' }),+ from_name: pick({ source: account, key: 'from_name' }),+ from_email: pick({ source: account, key: 'from_email' }),+ type: pick({ source: account, key: 'type' }),+ message_per_day: pick({ source: account, key: 'message_per_day' }),+ daily_sent_count: pick({ source: account, key: 'daily_sent_count' }),+ is_smtp_success: pick({ source: account, key: 'is_smtp_success' }),+ is_imap_success: pick({ source: account, key: 'is_imap_success' }),+ client_id: pick({ source: account, key: 'client_id' }),+ created_at: pick({ source: account, key: 'created_at' }),+ })),+ };+}++async function getLeadMessageHistory({+ apiKey,+ campaignId,+ leadId,+}: {+ apiKey: string;+ campaignId: unknown;+ leadId: unknown;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const lead = requireId({ value: leadId, label: 'Lead ID' });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/leads/${lead}/message-history`,+ method: HttpMethod.GET,+ apiKey,+ });+ const history = pick({ source: response, key: 'history' });+ return { campaign_id: id, lead_id: lead, history: Array.isArray(history) ? history : [] };+}++async function createCampaignWebhook({+ apiKey,+ campaignId,+ webhookUrl,+ eventTypes,+}: {+ apiKey: string;+ campaignId: unknown;+ webhookUrl: string;+ eventTypes: string[];+}): Promise<number | string | null> {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ const response = await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/webhooks`,+ method: HttpMethod.POST,+ apiKey,+ body: {+ id: null,+ name: `Activepieces ${Date.now()}`,+ webhook_url: webhookUrl,+ event_types: eventTypes,+ },+ });+ const created = pick({ source: response, key: 'id' }) ?? pick({ source: pick({ source: response, key: 'data' }), key: 'id' });+ return typeof created === 'number' || typeof created === 'string' ? created : null;+}++function parseOnOff({ value, label }: { value: unknown; label: string }): boolean | undefined {+ if (isNil(value) || value === '') return undefined;+ const normalized = typeof value === 'string' ? value.trim().toLowerCase() : value;+ if (normalized === 'on' || normalized === true) return true;+ if (normalized === 'off' || normalized === false) return false;+ throw new Error(`${label} must be "on", "off" or omitted.`);+}++function parseTriStateBoolean({ value, label }: { value: unknown; label: string }): boolean | undefined {+ if (isNil(value)) return undefined;+ if (typeof value === 'boolean') return value;+ if (typeof value === 'string') {+ const normalized = value.trim().toLowerCase();+ if (normalized === '') return undefined;+ if (normalized === 'true') return true;+ if (normalized === 'false') return false;+ }+ throw new Error(`${label} must be true, false or left empty.`);+}++async function deleteCampaignWebhook({+ apiKey,+ campaignId,+ webhookId,+}: {+ apiKey: string;+ campaignId: unknown;+ webhookId: number | string;+}) {+ const id = requireId({ value: campaignId, label: 'Campaign ID' });+ try {+ await smartleadRequest<unknown>({+ endpoint: `campaigns/${id}/webhooks`,+ method: HttpMethod.DELETE,+ apiKey,+ body: { id: webhookId },+ });+ } catch (error: unknown) {+ if (error instanceof SmartleadApiError && error.statusCode === 404) {+ return;+ }+ throw error;+ }+}++async function listCampaignOptions({ apiKey }: { apiKey: string }) {+ const { campaigns } = await listCampaigns({ apiKey });+ return campaigns+ .filter((c): c is typeof c & { id: number } => typeof c.id === 'number')+ .map((c) => ({ label: `${typeof c.name === 'string' ? c.name : 'Untitled'} (${c.id})`, value: c.id }));+}++type LeadUploadFlags = {+ ignore_global_block_list?: boolean | null;+ ignore_unsubscribe_list?: boolean | null;+ ignore_duplicate_leads_in_other_campaign?: boolean | null;+ ignore_community_bounce_list?: boolean | null;+};++type CampaignSettingsInput = {+ trackOpens?: boolean | null;+ trackClicks?: boolean | null;+ stopLeadSettings?: string | null;+ unsubscribeText?: string | null;+ enableAiEspMatching?: boolean | null;+ sendAsPlainText?: boolean | null;+ followUpPercentage?: number | null;+};++const MAX_LEADS_PER_REQUEST = 400;+const MAX_PAGE_SIZE = 100;+const DONT_TRACK_OPEN = 'DONT_TRACK_EMAIL_OPEN';+const DONT_TRACK_CLICK = 'DONT_TRACK_LINK_CLICK';+const READ_TRACK_ALIASES: Record<string, string> = {+ DONT_EMAIL_OPEN: DONT_TRACK_OPEN,+ DONT_LINK_CLICK: DONT_TRACK_CLICK,+ DONT_REPLY_TO_AN_EMAIL: 'DONT_TRACK_REPLY_TO_AN_EMAIL',+};+const CAMPAIGN_STATUSES: readonly string[] = ['START', 'PAUSED', 'STOPPED'];+const LEAD_STATUS_ACTIONS: readonly string[] = ['pause', 'resume', 'unsubscribe'];+const SMARTLEAD_WEBHOOK_EVENTS = [+ { label: 'Email Sent', value: 'EMAIL_SENT' },+ { label: 'Email Opened', value: 'EMAIL_OPEN' },+ { label: 'Link Clicked', value: 'EMAIL_LINK_CLICK' },+ { label: 'Email Replied', value: 'EMAIL_REPLY' },+ { label: 'Lead Unsubscribed', value: 'LEAD_UNSUBSCRIBED' },+ { label: 'Lead Category Updated', value: 'LEAD_CATEGORY_UPDATED' },+];+const STOP_LEAD_OPTIONS = [+ { label: 'Reply to an email', value: 'REPLY_TO_AN_EMAIL' },+ { label: 'Opened an email', value: 'OPEN_AN_EMAIL' },+ { label: 'Clicked a link', value: 'CLICK_ON_A_LINK' },+];+const LEGACY_STOP_LEAD_VALUES: Record<string, string> = {+ OPENED_EMAIL: 'OPEN_AN_EMAIL',+ CLICKED_LINK: 'CLICK_ON_A_LINK',+};++export const smartleadOperations = {+ createCampaign,+ addLeadsToCampaign,+ getCampaignStatistics,+ updateCampaignSettings,+ parseTriStateBoolean,+ listCampaigns,+ getCampaign,+ updateCampaignStatus,+ deleteCampaign,+ listCampaignLeads,+ findLeadByEmail,+ updateLeadStatusInCampaign,+ deleteLeadFromCampaign,+ listEmailAccounts,+ getLeadMessageHistory,+ createCampaignWebhook,+ deleteCampaignWebhook,+ listCampaignOptions,+ parseOnOff,+};++export type { LeadUploadFlags, CampaignSettingsInput };+export {+ MAX_LEADS_PER_REQUEST,+ MAX_PAGE_SIZE,+ CAMPAIGN_STATUSES,+ LEAD_STATUS_ACTIONS,+ STOP_LEAD_OPTIONS,+ SMARTLEAD_WEBHOOK_EVENTS,+};diff --git a/packages/pieces/community/smartlead/src/lib/common/output-schemas.ts b/packages/pieces/community/smartlead/src/lib/common/output-schemas.tsnew file mode 100644index 00000000000..39999622a55--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/common/output-schemas.ts@@ -0,0 +1,231 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const campaignSummaryFields: OutputSchemaField[] = [+ { key: 'id', label: 'Campaign ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'created_at', label: 'Created', format: 'datetime' },+ { key: 'updated_at', label: 'Updated', format: 'datetime' },+ { key: 'client_id', label: 'Client ID', format: 'number' },+];++const leadFields: OutputSchemaField[] = [+ { key: 'id', label: 'Lead ID' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'company_name', label: 'Company' },+ { key: 'phone_number', label: 'Phone' },+ { key: 'website', label: 'Website', format: 'url' },+ { key: 'location', label: 'Location' },+ { key: 'linkedin_profile', label: 'LinkedIn', format: 'url' },+ { key: 'custom_fields', label: 'Custom Fields', dynamicKey: true },+];++const createCampaign: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'id', label: 'Campaign ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'created_at', label: 'Created', format: 'datetime' },+ ],+};++const addLeads: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'upload_count', label: 'Uploaded', format: 'number' },+ { key: 'total_leads', label: 'Total Leads Sent', format: 'number' },+ { key: 'already_added_to_campaign', label: 'Already in Campaign', format: 'number' },+ { key: 'duplicate_count', label: 'Duplicates', format: 'number' },+ { key: 'invalid_email_count', label: 'Invalid Emails', format: 'number' },+ { key: 'unsubscribed_leads', label: 'Unsubscribed Leads' },+ { key: 'block_count', label: 'Blocked', format: 'number' },+ ],+};++const campaignStatistics: OutputSchema = {+ fields: [+ { key: 'id', label: 'Campaign ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'created_at', label: 'Created', format: 'datetime' },+ { key: 'sent_count', label: 'Sent' },+ { key: 'unique_sent_count', label: 'Unique Sent' },+ { key: 'open_count', label: 'Opens' },+ { key: 'unique_open_count', label: 'Unique Opens' },+ { key: 'click_count', label: 'Clicks' },+ { key: 'unique_click_count', label: 'Unique Clicks' },+ { key: 'reply_count', label: 'Replies' },+ { key: 'bounce_count', label: 'Bounces' },+ { key: 'unsubscribed_count', label: 'Unsubscribed' },+ { key: 'total_count', label: 'Total Leads' },+ { key: 'campaign_lead_stats', label: 'Lead Stats', dynamicKey: true },+ ],+};++const updateCampaignSettings: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ { key: 'updated', label: 'Settings Sent', dynamicKey: true },+ ],+};++const listCampaigns: OutputSchema = {+ fields: [+ { key: 'campaigns', label: 'Campaigns', labelKey: 'name', listItems: campaignSummaryFields },+ ],+};++const campaign: OutputSchema = {+ fields: [+ ...campaignSummaryFields,+ { key: 'track_settings', label: 'Tracking Disabled For' },+ { key: 'stop_lead_settings', label: 'Stop Lead Condition' },+ { key: 'scheduler_cron_value', label: 'Schedule' },+ { key: 'min_time_btwn_emails', label: 'Minutes Between Emails', format: 'number' },+ { key: 'max_leads_per_day', label: 'Max Leads Per Day', format: 'number' },+ { key: 'follow_up_percentage', label: 'Follow Up Percentage', format: 'number' },+ { key: 'unsubscribe_text', label: 'Unsubscribe Text' },+ { key: 'send_as_plain_text', label: 'Plain Text', format: 'boolean' },+ { key: 'enable_ai_esp_matching', label: 'AI ESP Matching', format: 'boolean' },+ ],+};++const updateCampaignStatus: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ { key: 'status', label: 'Status' },+ ],+};++const deleteCampaign: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ ],+};++const listCampaignLeads: OutputSchema = {+ fields: [+ { key: 'total_leads', label: 'Total Leads' },+ { key: 'offset', label: 'Offset', format: 'number' },+ { key: 'limit', label: 'Limit', format: 'number' },+ {+ key: 'leads',+ label: 'Leads',+ labelKey: 'lead.email',+ listItems: [+ { key: 'campaign_lead_map_id', label: 'Campaign Lead Map ID', format: 'number' },+ { key: 'status', label: 'Status' },+ { key: 'created_at', label: 'Added', format: 'datetime' },+ { key: 'lead', label: 'Lead', children: leadFields },+ ],+ },+ ],+};++const findLeadByEmail: OutputSchema = {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'lead', label: 'Lead', children: leadFields },+ ],+};++const updateLeadStatus: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ { key: 'lead_id', label: 'Lead ID', format: 'number' },+ { key: 'action', label: 'Action' },+ ],+};++const deleteLead: OutputSchema = {+ fields: [+ { key: 'ok', label: 'Success', format: 'boolean' },+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ { key: 'lead_id', label: 'Lead ID', format: 'number' },+ ],+};++const listEmailAccounts: OutputSchema = {+ fields: [+ { key: 'offset', label: 'Offset', format: 'number' },+ { key: 'limit', label: 'Limit', format: 'number' },+ {+ key: 'email_accounts',+ label: 'Email Accounts',+ labelKey: 'from_email',+ listItems: [+ { key: 'id', label: 'Email Account ID', format: 'number' },+ { key: 'from_name', label: 'From Name' },+ { key: 'from_email', label: 'From Email', format: 'email' },+ { key: 'type', label: 'Type' },+ { key: 'message_per_day', label: 'Messages Per Day', format: 'number' },+ { key: 'daily_sent_count', label: 'Sent Today', format: 'number' },+ { key: 'is_smtp_success', label: 'SMTP OK', format: 'boolean' },+ { key: 'is_imap_success', label: 'IMAP OK', format: 'boolean' },+ { key: 'client_id', label: 'Client ID', format: 'number' },+ { key: 'created_at', label: 'Created', format: 'datetime' },+ ],+ },+ ],+};++const messageHistory: OutputSchema = {+ fields: [+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ { key: 'lead_id', label: 'Lead ID', format: 'number' },+ {+ key: 'history',+ label: 'Messages',+ labelKey: 'subject',+ listItems: [+ { key: 'type', label: 'Type' },+ { key: 'message_id', label: 'Message ID' },+ { key: 'time', label: 'Time', format: 'datetime' },+ { key: 'from', label: 'From', format: 'email' },+ { key: 'to', label: 'To', format: 'email' },+ { key: 'subject', label: 'Subject' },+ { key: 'email_body', label: 'Body', format: 'html' },+ { key: 'open_count', label: 'Opens', format: 'number' },+ { key: 'click_count', label: 'Clicks', format: 'number' },+ ],+ },+ ],+};++const campaignEvent: OutputSchema = {+ fields: [+ { key: 'event_type', label: 'Event Type' },+ { key: 'campaign_id', label: 'Campaign ID', format: 'number' },+ { key: 'campaign_name', label: 'Campaign Name' },+ { key: 'sl_email_lead_id', label: 'Lead ID', format: 'number' },+ { key: 'to_email', label: 'Lead Email', format: 'email' },+ { key: 'to_name', label: 'Lead Name' },+ { key: 'from_email', label: 'From Email', format: 'email' },+ { key: 'subject', label: 'Subject' },+ { key: 'event_timestamp', label: 'Time', format: 'datetime' },+ ],+};++export const smartleadOutputSchemas = {+ createCampaign,+ addLeads,+ campaignStatistics,+ updateCampaignSettings,+ listCampaigns,+ campaign,+ updateCampaignStatus,+ deleteCampaign,+ listCampaignLeads,+ findLeadByEmail,+ updateLeadStatus,+ deleteLead,+ listEmailAccounts,+ messageHistory,+ campaignEvent,+};diff --git a/packages/pieces/community/smartlead/src/lib/common/props.ts b/packages/pieces/community/smartlead/src/lib/common/props.tsnew file mode 100644index 00000000000..85e47b0e722--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/common/props.ts@@ -0,0 +1,44 @@+import { Property } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../auth';+import { smartleadOperations } from './operations';++function campaignDropdown({ description }: { description: string }) {+ return Property.Dropdown<number, true, typeof smartleadAuth>({+ auth: smartleadAuth,+ displayName: 'Campaign',+ description,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your SmartLead account first.' };+ }+ try {+ const options = await smartleadOperations.listCampaignOptions({ apiKey: auth.secret_text });+ return {+ disabled: false,+ options,+ placeholder: options.length === 0 ? 'No campaigns found.' : undefined,+ };+ } catch {+ return { disabled: true, options: [], placeholder: 'Could not load campaigns. Check the connection.' };+ }+ },+ });+}++function triStateDropdown({ displayName, description }: { displayName: string; description: string }) {+ return Property.StaticDropdown<boolean, false>({+ displayName,+ description: `${description} Leave empty to keep the current value.`,+ required: false,+ options: {+ options: [+ { label: 'On', value: true },+ { label: 'Off', value: false },+ ],+ },+ });+}++export const smartleadProps = { campaignDropdown, triStateDropdown };diff --git a/packages/pieces/community/smartlead/src/lib/triggers/new-campaign-event.ts b/packages/pieces/community/smartlead/src/lib/triggers/new-campaign-event.tsnew file mode 100644index 00000000000..9e03c8dff36--- /dev/null+++ b/packages/pieces/community/smartlead/src/lib/triggers/new-campaign-event.ts@@ -0,0 +1,86 @@+import { createTrigger, isNil, Property, TriggerStrategy } from '@activepieces/pieces-framework';+import { smartleadAuth } from '../auth';+import { smartleadOperations, SMARTLEAD_WEBHOOK_EVENTS } from '../common/operations';+import { smartleadOutputSchemas } from '../common/output-schemas';+import { smartleadProps } from '../common/props';++export const newCampaignEventTrigger = createTrigger({+ auth: smartleadAuth,+ name: 'new_campaign_event',+ classification: 'READ',+ displayName: 'New Campaign Event',+ aiMetadata: {+ description:+ 'Fires when a selected event happens in one SmartLead campaign: email sent, opened, link clicked, replied, lead unsubscribed or lead category updated. Registers a webhook on the campaign when enabled and removes it when disabled. The payload carries event_type, campaign id and name, lead id and email, and the email subject.',+ },+ description: 'Triggers when a selected event (email sent, opened, clicked, replied, unsubscribed, category changed) happens in a campaign.',+ props: {+ campaign_id: smartleadProps.campaignDropdown({+ description: 'The campaign to watch.',+ }),+ event_types: Property.StaticMultiSelectDropdown({+ displayName: 'Events',+ description: 'Which campaign events start the flow.',+ required: true,+ options: { options: SMARTLEAD_WEBHOOK_EVENTS },+ }),+ },+ type: TriggerStrategy.WEBHOOK,+ outputSchema: smartleadOutputSchemas.campaignEvent,+ sampleData: {+ event_type: 'EMAIL_REPLY',+ campaign_id: 123456,+ campaign_name: 'AP Test',+ sl_email_lead_id: 987654,+ to_email: '[email protected]',+ to_name: 'Jane Doe',+ from_email: '[email protected]',+ subject: 'Quick question',+ event_timestamp: '2026-10-27T10:00:00.000Z',+ },+ async onEnable(context) {+ const eventTypes = (context.propsValue.event_types ?? []).filter((e) =>+ SMARTLEAD_WEBHOOK_EVENTS.some((o) => o.value === e)+ );+ if (eventTypes.length === 0) {+ throw new Error('Select at least one event.');+ }+ const webhookId = await smartleadOperations.createCampaignWebhook({+ apiKey: context.auth.secret_text,+ campaignId: context.propsValue.campaign_id,+ webhookUrl: context.webhookUrl,+ eventTypes,+ });+ if (isNil(webhookId)) {+ throw new Error('SmartLead did not return a webhook id, so the webhook could not be tracked.');+ }+ await context.store.put<WebhookInfo>(STORE_KEY, {+ webhookId,+ campaignId: context.propsValue.campaign_id,+ });+ },+ async onDisable(context) {+ const info = await context.store.get<WebhookInfo>(STORE_KEY);+ if (isNil(info)) {+ return;+ }+ await smartleadOperations.deleteCampaignWebhook({+ apiKey: context.auth.secret_text,+ campaignId: info.campaignId,+ webhookId: info.webhookId,+ });+ await context.store.delete(STORE_KEY);+ },+ async run(context) {+ const body = context.payload.body;+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {+ return [];+ }+ return [body];+ },+});++type WebhookInfo = { webhookId: number | string; campaignId: number };++const STORE_KEY = 'smartlead_campaign_webhook';+diff --git a/packages/pieces/community/smartlead/test/smartlead.test.ts b/packages/pieces/community/smartlead/test/smartlead.test.tsnew file mode 100644index 00000000000..00dfa7f8ff8--- /dev/null+++ b/packages/pieces/community/smartlead/test/smartlead.test.ts@@ -0,0 +1,321 @@+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { smartlead } from '../src';+import { smartleadAuth } from '../src/lib/auth';+import { SMARTLEAD_WEBHOOK_EVENTS } from '../src/lib/common/operations';++const auth = { secret_text: 'key_123' };++function ok(body: unknown) {+ return { status: 200, headers: {}, body };+}++function failure({ status, body }: { status: number; body: unknown }) {+ return Object.assign(new Error('http'), { response: { status, body, headers: {} } });+}++function mockSeq(...bodies: unknown[]) {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ for (const b of bodies) {+ if (b instanceof Error) spy.mockRejectedValueOnce(b);+ else spy.mockResolvedValueOnce(ok(b));+ }+ return spy;+}++function run({ name, propsValue = {} }: { name: string; propsValue?: Record<string, unknown> }) {+ const found = smartlead.actions()[name];+ if (!found) throw new Error(`missing ${name}`);+ return Reflect.apply(found.run, undefined, [{ auth, propsValue }]);+}++function call({ spy, index = 0 }: { spy: ReturnType<typeof mockSeq>; index?: number }) {+ return spy.mock.calls[index][0];+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('metadata', () => {+ it('has 6 human + custom api call, 14 ai, nothing both', () => {+ const actions = Object.values(smartlead.actions());+ expect(actions.length).toBe(21);+ expect(actions.filter((a) => a.audience === 'human').length).toBe(7);+ expect(actions.filter((a) => a.audience === 'ai').length).toBe(14);+ expect(actions.filter((a) => a.audience === 'both').length).toBe(0);+ expect(Object.keys(smartlead.triggers())).toEqual(['new_campaign_event']);+ });+ it('ai actions have aiMetadata, classification, outputSchema and no dropdowns', () => {+ for (const a of Object.values(smartlead.actions())) {+ if (a.name !== 'custom_api_call') expect(a.outputSchema, a.name).toBeDefined();+ if (a.audience !== 'ai') continue;+ expect(a.aiMetadata?.description, a.name).toBeTruthy();+ expect(typeof a.aiMetadata?.idempotent, a.name).toBe('boolean');+ expect(a.classification, a.name).toBeTruthy();+ for (const p of Object.values(a.props)) {+ expect(['DROPDOWN', 'STATIC_DROPDOWN', 'MULTI_SELECT_DROPDOWN', 'DYNAMIC']).not.toContain(Reflect.get(p, 'type'));+ }+ }+ });+});++describe('auth', () => {+ it('returns invalid on 401 and on other failures without throwing', async () => {+ mockSeq(failure({ status: 401, body: {} }), failure({ status: 500, body: {} }));+ const validate = smartleadAuth.validate;+ if (!validate) throw new Error('no validate');+ const a = await Reflect.apply(validate, undefined, [{ auth: 'bad' }]);+ const b = await Reflect.apply(validate, undefined, [{ auth: 'bad' }]);+ expect(a.valid).toBe(false);+ expect(b.valid).toBe(false);+ });+});++describe('client errors', () => {+ it('maps 404 to a clean message without the api key and keeps responseBody', async () => {+ mockSeq(failure({ status: 404, body: { message: 'Campaign not found' } }));+ const err = await run({ name: 'ai_get_campaign', propsValue: { campaign_id: 5 } }).catch((e: unknown) => e);+ expect(String(Reflect.get(err, 'message'))).toContain('could not find');+ expect(String(Reflect.get(err, 'message'))).not.toContain('key_123');+ expect(Reflect.get(err, 'responseBody')).toEqual({ message: 'Campaign not found' });+ expect(Reflect.get(err, 'body')).toBeUndefined();+ });+});++describe('campaigns', () => {+ it('create campaign: human and ai share the same request', async () => {+ const spy = mockSeq({ ok: true, id: 1, name: 'X', created_at: '2026-01-01' }, { ok: true, id: 2, name: 'Y', created_at: null });+ const human = await run({ name: 'create_campaign', propsValue: { name: ' X ' } });+ await run({ name: 'ai_create_campaign', propsValue: { name: 'Y', client_id: 7 } });+ expect(human).toEqual({ ok: true, id: 1, name: 'X', created_at: '2026-01-01' });+ expect(call({ spy }).url).toContain('/campaigns/create');+ expect(call({ spy }).method).toBe(HttpMethod.POST);+ expect(call({ spy }).body).toEqual({ name: 'X' });+ expect(call({ spy }).queryParams).toEqual({ api_key: 'key_123' });+ expect(call({ spy, index: 1 }).body).toEqual({ name: 'Y', client_id: 7 });+ });++ it('list campaigns maps summary fields', async () => {+ mockSeq([{ id: 1, name: 'A', status: 'ACTIVE', created_at: 'c', updated_at: 'u', client_id: null, extra: 1 }]);+ const out = await run({ name: 'ai_list_campaigns' });+ expect(out).toEqual({ campaigns: [{ id: 1, name: 'A', status: 'ACTIVE', created_at: 'c', updated_at: 'u', client_id: null }] });+ });++ it('update status validates and posts', async () => {+ const spy = mockSeq({ ok: true });+ const out = await run({ name: 'ai_update_campaign_status', propsValue: { campaign_id: 3, status: 'paused' } });+ expect(out).toEqual({ ok: true, campaign_id: 3, status: 'PAUSED' });+ expect(call({ spy }).url).toContain('/campaigns/3/status');+ expect(call({ spy }).body).toEqual({ status: 'PAUSED' });+ await expect(run({ name: 'ai_update_campaign_status', propsValue: { campaign_id: 3, status: 'go' } })).rejects.toThrow('Status must be one of');+ });++ it('empty 200 body for a missing campaign throws not found', async () => {+ mockSeq(null, '', {});+ await expect(run({ name: 'ai_get_campaign', propsValue: { campaign_id: 4247768 } })).rejects.toThrow('Campaign 4247768 not found.');+ await expect(run({ name: 'ai_get_campaign_statistics', propsValue: { campaign_id: 4247768 } })).rejects.toThrow('Campaign 4247768 not found.');+ await expect(run({ name: 'get_campaign_statistics', propsValue: { campaign_id: 4247768 } })).rejects.toThrow('Campaign 4247768 not found.');+ });++ it('human status actions share the ai request path', async () => {+ const spy = mockSeq({ ok: true }, { ok: true });+ expect(await run({ name: 'update_campaign_status', propsValue: { campaign_id: 3, status: 'START' } })).toEqual({ ok: true, campaign_id: 3, status: 'START' });+ expect(call({ spy }).url).toContain('/campaigns/3/status');+ expect(call({ spy }).body).toEqual({ status: 'START' });+ expect(await run({ name: 'update_lead_status_in_campaign', propsValue: { campaign_id: 3, lead_id: 8, action: 'resume' } })).toEqual({ ok: true, campaign_id: 3, lead_id: 8, action: 'resume' });+ expect(call({ spy, index: 1 }).url).toContain('/campaigns/3/leads/8/resume');+ expect(smartlead.actions()['update_campaign_status'].aiMetadata?.idempotent).toBe(true);+ });++ it('delete campaign sends DELETE', async () => {+ const spy = mockSeq({ ok: true });+ expect(await run({ name: 'ai_delete_campaign', propsValue: { campaign_id: 9 } })).toEqual({ ok: true, campaign_id: 9 });+ expect(call({ spy }).method).toBe(HttpMethod.DELETE);+ expect(call({ spy }).url).toContain('/campaigns/9');+ });++ it('rejects a non-positive campaign id before any request', async () => {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ await expect(run({ name: 'ai_get_campaign_statistics', propsValue: { campaign_id: 0 } })).rejects.toThrow('positive whole number');+ expect(spy).not.toHaveBeenCalled();+ });+});++describe('update campaign settings', () => {+ it('untouched tri-state values are not sent; at least one setting required', async () => {+ const spy = vi.spyOn(httpClient, 'sendRequest');+ await expect(+ run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, track_open: null, stop_lead_settings: null, unsubscribe_text: '' } })+ ).rejects.toThrow('At least one setting');+ expect(spy).not.toHaveBeenCalled();+ });++ it('merges tracking into the existing track_settings array', async () => {+ const spy = mockSeq({ id: 1, track_settings: ['DONT_TRACK_LINK_CLICK', 'DONT_TRACK_REPLY_TO_AN_EMAIL'] }, { ok: true });+ await run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, track_open: false, track_click: true } });+ expect(call({ spy }).method).toBe(HttpMethod.GET);+ expect(call({ spy, index: 1 }).url).toContain('/campaigns/1/settings');+ const body = call({ spy, index: 1 }).body;+ expect(Reflect.get(body, 'track_settings')).toEqual(['DONT_TRACK_REPLY_TO_AN_EMAIL', 'DONT_TRACK_EMAIL_OPEN']);+ });++ it('sends only the provided fields, maps legacy stop values, validates percentage', async () => {+ const spy = mockSeq({ ok: true });+ await run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, stop_lead_settings: 'OPENED_EMAIL', send_as_plain_text: false } });+ expect(call({ spy }).body).toEqual({ stop_lead_settings: 'OPEN_AN_EMAIL', send_as_plain_text: false });+ await expect(run({ name: 'ai_update_campaign_settings', propsValue: { campaign_id: 1, follow_up_percentage: 150 } })).rejects.toThrow('between 0 and 100');+ });+});++describe('mapped tri-state settings', () => {+ it('mapped "false" disables tracking', async () => {+ const spy = mockSeq({ id: 1, track_settings: [] }, { ok: true });+ await run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, track_open: 'false', track_click: ' FALSE ' } });+ expect(Reflect.get(call({ spy, index: 1 }).body, 'track_settings')).toEqual(['DONT_TRACK_EMAIL_OPEN', 'DONT_TRACK_LINK_CLICK']);+ });+ it('mapped "true" strings become booleans in the request', async () => {+ const spy = mockSeq({ ok: true });+ await run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, enable_ai_esp_matching: 'true', send_as_plain_text: 'True' } });+ expect(call({ spy }).body).toEqual({ enable_ai_esp_matching: true, send_as_plain_text: true });+ });+ it('empty mapped values leave the field out; invalid values throw', async () => {+ const spy = mockSeq({ ok: true });+ await run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, track_open: '', enable_ai_esp_matching: ' ', send_as_plain_text: 'false' } });+ expect(spy).toHaveBeenCalledTimes(1);+ expect(call({ spy }).body).toEqual({ send_as_plain_text: false });+ await expect(run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, track_click: 'yes' } })).rejects.toThrow('Track Clicks must be true, false');+ });+});++describe('settings fixes', () => {+ it('throws instead of clearing tracking when GET has no track_settings', async () => {+ const spy = mockSeq({ id: 1 });+ await expect(run({ name: 'update_campaign_settings', propsValue: { campaign_id: 1, track_open: true } })).rejects.toThrow('tracking was not changed');+ expect(spy).toHaveBeenCalledTimes(1);+ });+ it('normalises the live GET track_settings names before applying on/off', async () => {+ const spy = mockSeq({ id: 1, track_settings: ['DONT_EMAIL_OPEN', 'DONT_LINK_CLICK', 'DONT_TRACK_EMAIL_OPEN', 'DONT_REPLY_TO_AN_EMAIL', 'DONT_TRACK_REPLY_TO_AN_EMAIL'] }, { ok: true });+ await run({ name: 'ai_update_campaign_settings', propsValue: { campaign_id: 1, track_opens: 'on' } });+ expect(Reflect.get(call({ spy, index: 1 }).body, 'track_settings')).toEqual(['DONT_TRACK_LINK_CLICK', 'DONT_TRACK_REPLY_TO_AN_EMAIL']);+ });+ it('stop options list only the current values; legacy ones are only mapped in run()', () => {+ const prop = Reflect.get(smartlead.actions()['update_campaign_settings'].props, 'stop_lead_settings');+ const values = prop.options.options.map((o: { value: string }) => o.value);+ expect(values).toEqual(['REPLY_TO_AN_EMAIL', 'OPEN_AN_EMAIL', 'CLICK_ON_A_LINK']);+ });+ it('classifies by worst reachable path', () => {+ const actions = smartlead.actions();+ for (const name of ['update_campaign_status', 'ai_update_campaign_status', 'update_lead_status_in_campaign', 'ai_update_lead_status_in_campaign']) {+ expect(Reflect.get(actions[name], 'classification')).toBe('DESTRUCTIVE');+ }+ for (const name of ['ai_list_campaigns', 'ai_list_campaign_leads', 'ai_list_email_accounts']) {+ expect(Reflect.get(actions[name], 'classification')).toBe('SEARCH');+ }+ });+ it('ai settings booleans are tri-state', async () => {+ const spy = mockSeq({ ok: true });+ await run({ name: 'ai_update_campaign_settings', propsValue: { campaign_id: 1, send_as_plain_text: 'off', follow_up_percentage: 10 } });+ expect(call({ spy }).body).toEqual({ send_as_plain_text: false, follow_up_percentage: 10 });+ await expect(run({ name: 'ai_update_campaign_settings', propsValue: { campaign_id: 1, track_opens: 'maybe' } })).rejects.toThrow('"on", "off"');+ });+});++describe('leads', () => {+ it('add leads: invalid JSON and null entries give clean errors', async () => {+ await expect(run({ name: 'add_leads_to_campaign', propsValue: { campaign_id: 1, lead_list: '[{' } })).rejects.toThrow('not valid JSON');+ await expect(run({ name: 'add_leads_to_campaign', propsValue: { campaign_id: 1, lead_list: [null] } })).rejects.toThrow('index 0 must be an object');+ await expect(run({ name: 'add_leads_to_campaign', propsValue: { campaign_id: 1, lead_list: [{ first_name: 'a' }] } })).rejects.toThrow('missing a required "email"');+ });++ it('ai add leads strips empty fields and sends only true flags', async () => {+ const spy = mockSeq({ ok: true, upload_count: 1, total_leads: 1 });+ const out = await run({+ name: 'ai_add_leads_to_campaign',+ propsValue: { campaign_id: 4, leads: [{ email: ' [email protected] ', first_name: '', last_name: 'L' }], ignore_global_block_list: true, ignore_unsubscribe_list: false },+ });+ expect(call({ spy }).url).toContain('/campaigns/4/leads');+ expect(call({ spy }).body).toEqual({ lead_list: [{ email: '[email protected]', last_name: 'L' }], settings: { ignore_global_block_list: true } });+ expect(Reflect.get(out, 'upload_count')).toBe(1);+ });++ it('list campaign leads passes pagination and rejects limit > 100', async () => {+ const spy = mockSeq({ total_leads: '2', data: [{ lead: { id: 1 } }] });+ const out = await run({ name: 'ai_list_campaign_leads', propsValue: { campaign_id: 2, offset: 10, limit: 5 } });+ expect(call({ spy }).queryParams).toEqual({ api_key: 'key_123', offset: '10', limit: '5' });+ expect(out).toEqual({ total_leads: '2', offset: 10, limit: 5, leads: [{ lead: { id: 1 } }] });+ await expect(run({ name: 'ai_list_campaign_leads', propsValue: { campaign_id: 2, limit: 500 } })).rejects.toThrow('between 1 and 100');+ });++ it('find lead by email: found and not found', async () => {+ mockSeq({ id: 77, email: '[email protected]' }, {});+ expect(await run({ name: 'ai_find_lead_by_email', propsValue: { email: '[email protected]' } })).toEqual({ found: true, lead: { id: 77, email: '[email protected]' } });+ expect(await run({ name: 'ai_find_lead_by_email', propsValue: { email: '[email protected]' } })).toEqual({ found: false, lead: null });+ });++ it('update lead status uses the action path', async () => {+ const spy = mockSeq({ ok: true });+ await run({ name: 'ai_update_lead_status_in_campaign', propsValue: { campaign_id: 1, lead_id: 2, action: 'Unsubscribe' } });+ expect(call({ spy }).url).toContain('/campaigns/1/leads/2/unsubscribe');+ await expect(run({ name: 'ai_update_lead_status_in_campaign', propsValue: { campaign_id: 1, lead_id: 2, action: 'archive' } })).rejects.toThrow('Action must be one of');+ });++ it('delete lead and message history', async () => {+ const spy = mockSeq({ ok: true }, { history: [{ type: 'SENT' }] });+ await run({ name: 'ai_delete_lead_from_campaign', propsValue: { campaign_id: 1, lead_id: 2 } });+ expect(call({ spy }).method).toBe(HttpMethod.DELETE);+ const out = await run({ name: 'ai_get_lead_message_history', propsValue: { campaign_id: 1, lead_id: 2 } });+ expect(call({ spy, index: 1 }).url).toContain('/campaigns/1/leads/2/message-history');+ expect(Reflect.get(out, 'history')).toEqual([{ type: 'SENT' }]);+ });++ it('list email accounts maps fields', async () => {+ mockSeq([{ id: 1, from_email: '[email protected]', smtp_password: 'secret' }]);+ const out = await run({ name: 'ai_list_email_accounts' });+ const accounts = Reflect.get(out, 'email_accounts');+ expect(accounts[0].from_email).toBe('[email protected]');+ expect(accounts[0].smtp_password).toBeUndefined();+ });+});++describe('trigger', () => {+ it('registers and deletes the campaign webhook', async () => {+ const trigger = smartlead.triggers()['new_campaign_event'];+ const store = new Map<string, unknown>();+ const ctx = {+ auth,+ webhookUrl: 'https://hook.example/x',+ propsValue: { campaign_id: 5, event_types: [SMARTLEAD_WEBHOOK_EVENTS[3].value] },+ store: {+ put: async (k: string, v: unknown) => { store.set(k, v); return v; },+ get: async (k: string) => store.get(k) ?? null,+ delete: async (k: string) => { store.delete(k); },+ },+ };+ const spy = mockSeq({ id: 42 }, { ok: true });+ await Reflect.apply(trigger.onEnable, undefined, [ctx]);+ expect(call({ spy }).url).toContain('/campaigns/5/webhooks');+ expect(Reflect.get(call({ spy }).body, 'event_types')).toEqual(['EMAIL_REPLY']);+ await Reflect.apply(trigger.onDisable, undefined, [ctx]);+ expect(call({ spy, index: 1 }).method).toBe(HttpMethod.DELETE);+ expect(call({ spy, index: 1 }).body).toEqual({ id: 42 });+ expect(store.size).toBe(0);+ });+ it('onDisable ignores a 404 but rethrows other errors', async () => {+ const trigger = smartlead.triggers()['new_campaign_event'];+ const store = new Map<string, unknown>([['smartlead_campaign_webhook', { webhookId: 1, campaignId: 5 }]]);+ const ctx = {+ auth,+ store: {+ get: async (k: string) => store.get(k) ?? null,+ delete: async (k: string) => { store.delete(k); },+ },+ };+ mockSeq(failure({ status: 404, body: {} }));+ await Reflect.apply(trigger.onDisable, undefined, [ctx]);+ expect(store.size).toBe(0);+ store.set('smartlead_campaign_webhook', { webhookId: 1, campaignId: 5 });+ mockSeq(failure({ status: 500, body: {} }));+ await expect(Reflect.apply(trigger.onDisable, undefined, [ctx])).rejects.toThrow('status 500');+ });+});diff --git a/packages/pieces/community/smartlead/vitest.config.ts b/packages/pieces/community/smartlead/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/smartlead/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ 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'),+ },+ },+})