Skip to content

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

feat(intercom): let AI agents manage contacts, conversations and tickets (#16385)

Odai Ahmadd685618444c9
diff --git a/bun.lock b/bun.lock
index 7eaeab1283e..f034f652b5b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4666,7 +4666,7 @@
},
"packages/pieces/community/intercom": {
"name": "@activepieces/piece-intercom",
- "version": "0.8.3",
+ "version": "0.9.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4675,6 +4675,7 @@
"dayjs": "1.11.9",
"intercom-client": "6.2.0",
"string-strip-html": "8.5.0",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
diff --git a/packages/pieces/community/intercom/package.json b/packages/pieces/community/intercom/package.json
index 6aae6a758f7..a4a78f4fd25 100644
--- a/packages/pieces/community/intercom/package.json
+++ b/packages/pieces/community/intercom/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-intercom",
- "version": "0.8.3",
+ "version": "0.9.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
@@ -10,7 +10,8 @@
"intercom-client": "6.2.0",
"string-strip-html": "8.5.0",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
"tslib": "2.6.2",
diff --git a/packages/pieces/community/intercom/src/i18n/translation.json b/packages/pieces/community/intercom/src/i18n/translation.json
index ae9de5cc18a..b246c7d45db 100644
--- a/packages/pieces/community/intercom/src/i18n/translation.json
+++ b/packages/pieces/community/intercom/src/i18n/translation.json
@@ -25,6 +25,37 @@
"Find User": "Find User",
"List Tags": "List Tags",
"Retrieve a Conversation": "Retrieve a Conversation",
+ "Get Conversation (by ID)": "Get Conversation (by ID)",
+ "Reply to Conversation (by ID)": "Reply to Conversation (by ID)",
+ "Add Note to Conversation (by ID)": "Add Note to Conversation (by ID)",
+ "Assign Conversation (by ID)": "Assign Conversation (by ID)",
+ "Tag or Untag Record": "Tag or Untag Record",
+ "Send Message to Contact": "Send Message to Contact",
+ "Create Ticket (by Type ID)": "Create Ticket (by Type ID)",
+ "Update Ticket (by ID)": "Update Ticket (by ID)",
+ "Get Contact": "Get Contact",
+ "Search Contacts": "Search Contacts",
+ "Update Contact": "Update Contact",
+ "Attach Contact to Company": "Attach Contact to Company",
+ "List Contact Notes": "List Contact Notes",
+ "Search Conversations": "Search Conversations",
+ "Close, Reopen or Snooze Conversation": "Close, Reopen or Snooze Conversation",
+ "Convert Conversation to Ticket": "Convert Conversation to Ticket",
+ "Get Ticket": "Get Ticket",
+ "Search Tickets": "Search Tickets",
+ "Reply to Ticket": "Reply to Ticket",
+ "List Ticket Types": "List Ticket Types",
+ "List Admins": "List Admins",
+ "List Teams": "List Teams",
+ "List Data Attributes": "List Data Attributes",
+ "Create Tag": "Create Tag",
+ "Get Company": "Get Company",
+ "List Companies": "List Companies",
+ "Search Help Center Articles": "Search Help Center Articles",
+ "List Segments": "List Segments",
+ "Add Note to Contact (by ID)": "Add Note to Contact (by ID)",
+ "Create Conversation from Contact": "Create Conversation from Contact",
+ "Create Help Center Article": "Create Help Center Article",
"Custom API Call": "Custom API Call",
"Add a note to a user": "Add a note to a user",
"Add a note (for other admins) to an existing conversation": "Add a note (for other admins) to an existing conversation",
@@ -51,6 +82,37 @@
"Finds an existing user.": "Finds an existing user.",
"List all tags.": "List all tags.",
"Retrieves a specific conversation by ID.": "Retrieves a specific conversation by ID.",
+ "Gets a conversation and its messages by conversation ID.": "Gets a conversation and its messages by conversation ID.",
+ "Posts an admin reply that the customer sees in a conversation.": "Posts an admin reply that the customer sees in a conversation.",
+ "Adds an internal note, visible only to your team, to a conversation.": "Adds an internal note, visible only to your team, to a conversation.",
+ "Assigns a conversation to an admin or a team, or unassigns it.": "Assigns a conversation to an admin or a team, or unassigns it.",
+ "Adds or removes a tag on a contact, conversation, company or ticket.": "Adds or removes a tag on a contact, conversation, company or ticket.",
+ "Sends a new email or in-app message from an admin to one contact.": "Sends a new email or in-app message from an admin to one contact.",
+ "Creates a ticket of a given ticket type for one contact.": "Creates a ticket of a given ticket type for one contact.",
+ "Changes a ticket's state, assignee, snooze time or attributes.": "Changes a ticket's state, assignee, snooze time or attributes.",
+ "Gets one contact (user or lead) by ID, email or external ID.": "Gets one contact (user or lead) by ID, email or external ID.",
+ "Finds contacts (users and leads) by email, name, tag, segment, update time or a custom attribute.": "Finds contacts (users and leads) by email, name, tag, segment, update time or a custom attribute.",
+ "Updates a contact's role, email, name, phone, external ID, owner, subscription or custom attributes.": "Updates a contact's role, email, name, phone, external ID, owner, subscription or custom attributes.",
+ "Links a contact to a company.": "Links a contact to a company.",
+ "Lists the internal notes on a contact.": "Lists the internal notes on a contact.",
+ "Finds conversations by state, assignee, contact, tag, text or date.": "Finds conversations by state, assignee, contact, tag, text or date.",
+ "Closes, reopens or snoozes a conversation.": "Closes, reopens or snoozes a conversation.",
+ "Turns a conversation into a ticket of the chosen ticket type.": "Turns a conversation into a ticket of the chosen ticket type.",
+ "Gets one ticket by its ID.": "Gets one ticket by its ID.",
+ "Finds tickets by type, state, contact, assignee, title or date.": "Finds tickets by type, state, contact, assignee, title or date.",
+ "Adds an admin reply or an internal note to a ticket.": "Adds an admin reply or an internal note to a ticket.",
+ "Lists ticket types with their attributes and list options.": "Lists ticket types with their attributes and list options.",
+ "Lists the admins (teammates) in the workspace.": "Lists the admins (teammates) in the workspace.",
+ "Lists the teams in the workspace.": "Lists the teams in the workspace.",
+ "Lists the standard and custom attributes for contacts, companies or conversations.": "Lists the standard and custom attributes for contacts, companies or conversations.",
+ "Creates a tag, or returns the existing tag with that name.": "Creates a tag, or returns the existing tag with that name.",
+ "Gets one company by its Intercom ID or by your own Company ID.": "Gets one company by its Intercom ID or by your own Company ID.",
+ "Lists companies, optionally only those with a tag or in a segment.": "Lists companies, optionally only those with a tag or in a segment.",
+ "Searches Help Center articles for a phrase.": "Searches Help Center articles for a phrase.",
+ "Lists the contact segments in the workspace.": "Lists the contact segments in the workspace.",
+ "Adds an internal note to a contact by contact ID.": "Adds an internal note to a contact by contact ID.",
+ "Starts a new conversation with a first message written as the contact.": "Starts a new conversation with a first message written as the contact.",
+ "Creates a Help Center article, as a draft unless told to publish.": "Creates a Help Center article, as a draft unless told to publish.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Email": "Email",
"Note Text": "Note Text",
@@ -105,6 +167,71 @@
"Status": "Status",
"Update After": "Update After",
"Update Before": "Update Before",
+ "Plain Text Bodies": "Plain Text Bodies",
+ "Reply": "Reply",
+ "Admin ID": "Admin ID",
+ "Attachment URLs": "Attachment URLs",
+ "Note": "Note",
+ "Assign To": "Assign To",
+ "Acting Admin ID": "Acting Admin ID",
+ "Record Type": "Record Type",
+ "Record ID": "Record ID",
+ "Tag ID": "Tag ID",
+ "Remove Tag": "Remove Tag",
+ "Contact Email": "Contact Email",
+ "Subject": "Subject",
+ "Email Template": "Email Template",
+ "Message": "Message",
+ "From Admin ID": "From Admin ID",
+ "Open Conversation Right Away": "Open Conversation Right Away",
+ "Ticket Type ID": "Ticket Type ID",
+ "Contact": "Contact",
+ "Other Attributes": "Other Attributes",
+ "Ticket ID": "Ticket ID",
+ "Open or Closed": "Open or Closed",
+ "Visible to Customer": "Visible to Customer",
+ "Snooze Until": "Snooze Until",
+ "Assignee Admin ID": "Assignee Admin ID",
+ "Attributes": "Attributes",
+ "Look Up By": "Look Up By",
+ "Value": "Value",
+ "Email Is": "Email Is",
+ "Name Contains": "Name Contains",
+ "Role": "Role",
+ "Segment ID": "Segment ID",
+ "Updated After": "Updated After",
+ "Updated Before": "Updated Before",
+ "Custom Attribute Name": "Custom Attribute Name",
+ "Custom Attribute Value": "Custom Attribute Value",
+ "Advanced Query": "Advanced Query",
+ "Results Per Page": "Results Per Page",
+ "Starting After": "Starting After",
+ "External ID": "External ID",
+ "Owner Admin ID": "Owner Admin ID",
+ "Email Subscription": "Email Subscription",
+ "Clear Fields": "Clear Fields",
+ "Intercom Company ID": "Intercom Company ID",
+ "Page": "Page",
+ "Assigned Admin ID": "Assigned Admin ID",
+ "Assigned Team ID": "Assigned Team ID",
+ "Author Email": "Author Email",
+ "First Message Contains": "First Message Contains",
+ "Subject Contains": "Subject Contains",
+ "Created After": "Created After",
+ "Created Before": "Created Before",
+ "New State": "New State",
+ "Closing Message": "Closing Message",
+ "Ticket Attributes": "Ticket Attributes",
+ "Title Contains": "Title Contains",
+ "Reply Type": "Reply Type",
+ "Text": "Text",
+ "Include Archived": "Include Archived",
+ "Object": "Object",
+ "Phrase": "Phrase",
+ "Help Center ID": "Help Center ID",
+ "Include Counts": "Include Counts",
+ "Author Admin ID": "Author Admin ID",
+ "Parent Collection ID": "Parent Collection ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -122,8 +249,64 @@
"How much revenue the company generates for your business (whole integers only).": "How much revenue the company generates for your business (whole integers only).",
"The time the company was created by you.": "The time the company was created by you.",
"Whether a conversation should be opened in the inbox for the message without the contact replying. Defaults to false if not provided.": "Whether a conversation should be opened in the inbox for the message without the contact replying. Defaults to false if not provided.",
+ "Conversation ID, Assigned Admin, Team and Tag IDs only support Equals.": "Conversation ID, Assigned Admin, Team and Tag IDs only support Equals.",
+ "Intercom compares dates by calendar day in your workspace time zone.": "Intercom compares dates by calendar day in your workspace time zone.",
"The company ID you have defined for the company. Used to look up and create.": "The company ID you have defined for the company. Used to look up and create.",
"Used to look up by name when no Company ID is given, and when creating.": "Used to look up by name when no Company ID is given, and when creating.",
+ "The Intercom conversation ID, for example from Search Conversations.": "The Intercom conversation ID, for example from Search Conversations.",
+ "Return message bodies as plain text instead of HTML.": "Return message bodies as plain text instead of HTML.",
+ "The Intercom conversation ID.": "The Intercom conversation ID.",
+ "The reply text. Simple HTML is allowed.": "The reply text. Simple HTML is allowed.",
+ "The admin who replies. Leave empty to reply as the admin who owns this connection (see List Admins).": "The admin who replies. Leave empty to reply as the admin who owns this connection (see List Admins).",
+ "Up to 10 public image URLs to attach.": "Up to 10 public image URLs to attach.",
+ "The note text. Simple HTML is allowed.": "The note text. Simple HTML is allowed.",
+ "The admin who writes the note. Leave empty to use the admin who owns this connection.": "The admin who writes the note. Leave empty to use the admin who owns this connection.",
+ "The admin or team ID. Use 0 to unassign.": "The admin or team ID. Use 0 to unassign.",
+ "The admin who performs the assignment. Leave empty to use the admin who owns this connection.": "The admin who performs the assignment. Leave empty to use the admin who owns this connection.",
+ "The Intercom ID of the contact, conversation, company (Intercom company ID, not your Company ID) or ticket.": "The Intercom ID of the contact, conversation, company (Intercom company ID, not your Company ID) or ticket.",
+ "The tag ID from List Tags. Give either Tag ID or Tag Name.": "The tag ID from List Tags. Give either Tag ID or Tag Name.",
+ "The tag name (case-insensitive). Give either Tag ID or Tag Name.": "The tag name (case-insensitive). Give either Tag ID or Tag Name.",
+ "Turn on to remove the tag instead of adding it.": "Turn on to remove the tag instead of adding it.",
+ "The Intercom contact ID. Give either Contact ID or Contact Email.": "The Intercom contact ID. Give either Contact ID or Contact Email.",
+ "Used when no Contact ID is given. Fails if several contacts share this email.": "Used when no Contact ID is given. Fails if several contacts share this email.",
+ "Required for email.": "Required for email.",
+ "The message text. Simple HTML is allowed.": "The message text. Simple HTML is allowed.",
+ "The sending admin. Leave empty to send as the admin who owns this connection.": "The sending admin. Leave empty to send as the admin who owns this connection.",
+ "Open a conversation in the inbox without waiting for the contact to reply.": "Open a conversation in the inbox without waiting for the contact to reply.",
+ "From List Ticket Types.": "From List Ticket Types.",
+ "The contact ID, email or external ID, matching Identify Contact By.": "The contact ID, email or external ID, matching Identify Contact By.",
+ "Ticket type attributes by name, for example {\"Priority\": \"<list option ID>\", \"Due\": \"2026-10-20T12:00:00Z\"}.": "Ticket type attributes by name, for example {\"Priority\": \"<list option ID>\", \"Due\": \"2026-10-20T12:00:00Z\"}.",
+ "Optional Intercom company ID to link.": "Optional Intercom company ID to link.",
+ "The ticket \"id\" from Intercom, not the inbox ticket number.": "The ticket \"id\" from Intercom, not the inbox ticket number.",
+ "Assign the ticket to this admin (see List Admins). Use 0 to unassign.": "Assign the ticket to this admin (see List Admins). Use 0 to unassign.",
+ "The admin who makes the assignment. Leave empty to use the admin who owns this connection.": "The admin who makes the assignment. Leave empty to use the admin who owns this connection.",
+ "Ticket attributes by name; null clears one. Dates take ISO 8601; list attributes take the option ID.": "Ticket attributes by name; null clears one. Dates take ISO 8601; list attributes take the option ID.",
+ "The contact ID, email or external ID.": "The contact ID, email or external ID.",
+ "From List Tags.": "From List Tags.",
+ "Match contacts whose custom attribute equals Custom Attribute Value.": "Match contacts whose custom attribute equals Custom Attribute Value.",
+ "Optional Intercom search filter, combined with the fields above using AND.": "Optional Intercom search filter, combined with the fields above using AND.",
+ "1 to 150. Default 50.": "1 to 150. Default 50.",
+ "The next_starting_after value from the previous page.": "The next_starting_after value from the previous page.",
+ "The Intercom contact ID (see Search Contacts or Get Contact).": "The Intercom contact ID (see Search Contacts or Get Contact).",
+ "Custom attributes by name. Only the ones you list change.": "Custom attributes by name. Only the ones you list change.",
+ "Fields to blank on the contact.": "Fields to blank on the contact.",
+ "The Intercom \"id\" of the company, not your own Company ID.": "The Intercom \"id\" of the company, not your own Company ID.",
+ "Starts at 1.": "Starts at 1.",
+ "Intercom matches single words of the first message best.": "Intercom matches single words of the first message best.",
+ "Required for Snooze; must be in the future.": "Required for Snooze; must be in the future.",
+ "Optional, Close only. The customer sees this message.": "Optional, Close only. The customer sees this message.",
+ "Leave empty to act as the admin who owns this connection.": "Leave empty to act as the admin who owns this connection.",
+ "Optional attributes by name. Dates take ISO 8601; list attributes take the option ID.": "Optional attributes by name. Dates take ISO 8601; list attributes take the option ID.",
+ "Leave empty to reply as the admin who owns this connection.": "Leave empty to reply as the admin who owns this connection.",
+ "Only needed when the workspace has several Help Centers.": "Only needed when the workspace has several Help Centers.",
+ "Also return how many contacts are in each segment.": "Also return how many contacts are in each segment.",
+ "The Intercom contact ID.": "The Intercom contact ID.",
+ "The admin shown as the author. Leave empty to use the admin who owns this connection.": "The admin shown as the author. Leave empty to use the admin who owns this connection.",
+ "The Intercom contact ID (user or lead).": "The Intercom contact ID (user or lead).",
+ "Plain text; HTML is not supported here.": "Plain text; HTML is not supported here.",
+ "The article content. HTML is allowed.": "The article content. HTML is allowed.",
+ "Leave empty to use the admin who owns this connection.": "Leave empty to use the admin who owns this connection.",
+ "The Help Center collection to put the article in. Leave empty for none.": "The Help Center collection to put the article in. Leave empty for none.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
@@ -139,8 +322,6 @@
"In Progress": "In Progress",
"Waiting on Customer": "Waiting on Customer",
"Resolved": "Resolved",
- "Subject": "Subject",
- "Author Email": "Author Email",
"Team": "Team",
"Tag IDs": "Tag IDs",
"Contains": "Contains",
@@ -148,7 +329,27 @@
"Starts With": "Starts With",
"Open": "Open",
"Closed": "Closed",
+ "Snoozed": "Snoozed",
"ID": "ID",
+ "Admin": "Admin",
+ "Conversation": "Conversation",
+ "Company": "Company",
+ "In-App": "In-App",
+ "Plain": "Plain",
+ "Personal": "Personal",
+ "Shared": "Shared",
+ "Not Shared": "Not Shared",
+ "Subscribed": "Subscribed",
+ "Unsubscribed": "Unsubscribed",
+ "Owner": "Owner",
+ "Close": "Close",
+ "Reopen": "Reopen",
+ "Snooze": "Snooze",
+ "Submitted": "Submitted",
+ "Internal Note": "Internal Note",
+ "Reply to Customer": "Reply to Customer",
+ "Your Company ID": "Your Company ID",
+ "All": "All",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
@@ -200,5 +401,6 @@
"Triggers when a reply is received from an Intercom admin (not a user or lead)": "Triggers when a reply is received from an Intercom admin (not a user or lead)",
"Triggers when a note is added to a conversation": "Triggers when a note is added to a conversation",
"Type": "Type",
- "Keyword (optional)": "Keyword (optional)"
+ "Keyword (optional)": "Keyword (optional)",
+ "Only notes containing this exact word fire the flow. Matching is whole-word and case-sensitive.": "Only notes containing this exact word fire the flow. Matching is whole-word and case-sensitive."
}
\ No newline at end of file
diff --git a/packages/pieces/community/intercom/src/index.ts b/packages/pieces/community/intercom/src/index.ts
index c52ae1d327f..de61ad999c9 100644
--- a/packages/pieces/community/intercom/src/index.ts
+++ b/packages/pieces/community/intercom/src/index.ts
@@ -1,7 +1,11 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
-import { getIntercomRegion, getIntercomToken, IntercomAuthValue } from './lib/common';
+import {
+ getIntercomBaseUrl,
+ getIntercomRegion,
+ getIntercomToken,
+} from './lib/common';
import { sendMessageAction } from './lib/actions/send-message.action';
import crypto from 'node:crypto';
import { noteAddedToConversation } from './lib/triggers/note-added-to-conversation';
@@ -51,11 +55,42 @@ import { findOrCreateCompanyAction } from './lib/actions/find-or-create-company'
import { findOrCreateLeadAction } from './lib/actions/find-or-create-lead';
import { updatedTicketTrigger } from './lib/triggers/updated-ticket';
import { newUnsubscriptionTrigger } from './lib/triggers/new-unsubscription';
+import { getConversationByIdAction } from './lib/actions/ai/get-conversation-by-id';
+import { replyToConversationByIdAction } from './lib/actions/ai/reply-to-conversation-by-id';
+import { addNoteToConversationByIdAction } from './lib/actions/ai/add-note-to-conversation-by-id';
+import { assignConversationByIdAction } from './lib/actions/ai/assign-conversation-by-id';
+import { tagOrUntagRecordAction } from './lib/actions/ai/tag-or-untag-record';
+import { sendMessageToContactAction } from './lib/actions/ai/send-message-to-contact';
+import { createTicketByTypeIdAction } from './lib/actions/ai/create-ticket-by-type-id';
+import { updateTicketByIdAction } from './lib/actions/ai/update-ticket-by-id';
+import { getContactAction } from './lib/actions/get-contact';
+import { searchContactsAction } from './lib/actions/search-contacts';
+import { updateContactAction } from './lib/actions/update-contact';
+import { attachContactToCompanyAction } from './lib/actions/attach-contact-to-company';
+import { listContactNotesAction } from './lib/actions/list-contact-notes';
+import { searchConversationsAction } from './lib/actions/search-conversations';
+import { setConversationStateAction } from './lib/actions/set-conversation-state';
+import { convertConversationToTicketAction } from './lib/actions/convert-conversation-to-ticket';
+import { getTicketAction } from './lib/actions/get-ticket';
+import { searchTicketsAction } from './lib/actions/search-tickets';
+import { replyToTicketAction } from './lib/actions/reply-to-ticket';
+import { listTicketTypesAction } from './lib/actions/list-ticket-types';
+import { listAdminsAction } from './lib/actions/list-admins';
+import { listTeamsAction } from './lib/actions/list-teams';
+import { listDataAttributesAction } from './lib/actions/list-data-attributes';
+import { createTagAction } from './lib/actions/create-tag';
+import { getCompanyAction } from './lib/actions/get-company';
+import { listCompaniesAction } from './lib/actions/list-companies';
+import { searchArticlesAction } from './lib/actions/search-articles';
+import { listSegmentsAction } from './lib/actions/ai/list-segments';
+import { addNoteToContactAction } from './lib/actions/ai/add-note-to-contact';
+import { createConversationFromContactAction } from './lib/actions/ai/create-conversation-from-contact';
+import { createHelpCenterArticleAction } from './lib/actions/ai/create-help-center-article';
export const intercom = createPiece({
displayName: 'Intercom',
description: 'Customer messaging platform for sales, marketing, and support',
- minimumSupportedRelease: '0.79.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/intercom.png',
categories: [PieceCategory.CUSTOMER_SUPPORT],
auth: intercomAuth,
@@ -94,12 +129,47 @@ export const intercom = createPiece({
findUserAction,
listAllTagsAction,
getConversationAction,
+ getConversationByIdAction,
+ replyToConversationByIdAction,
+ addNoteToConversationByIdAction,
+ assignConversationByIdAction,
+ tagOrUntagRecordAction,
+ sendMessageToContactAction,
+ createTicketByTypeIdAction,
+ updateTicketByIdAction,
+ getContactAction,
+ searchContactsAction,
+ updateContactAction,
+ attachContactToCompanyAction,
+ listContactNotesAction,
+ searchConversationsAction,
+ setConversationStateAction,
+ convertConversationToTicketAction,
+ getTicketAction,
+ searchTicketsAction,
+ replyToTicketAction,
+ listTicketTypesAction,
+ listAdminsAction,
+ listTeamsAction,
+ listDataAttributesAction,
+ createTagAction,
+ getCompanyAction,
+ listCompaniesAction,
+ searchArticlesAction,
+ listSegmentsAction,
+ addNoteToContactAction,
+ createConversationFromContactAction,
+ createHelpCenterArticleAction,
createCustomApiCallAction({
- baseUrl: (auth) =>
- `https://api.${getIntercomRegion(auth as IntercomAuthValue)}.io`,
+ baseUrl: (auth) => {
+ if (!auth) {
+ throw new Error('Connect Intercom first.');
+ }
+ return getIntercomBaseUrl(getIntercomRegion(auth));
+ },
auth: intercomAuth,
authMapping: async (auth) => ({
- Authorization: `Bearer ${getIntercomToken(auth as IntercomAuthValue)}`,
+ Authorization: `Bearer ${getIntercomToken(auth)}`,
}),
}),
],
@@ -128,36 +198,62 @@ export const intercom = createPiece({
noteAddedToConversation,
],
events: {
- parseAndReply: ({ payload }) => {
- const payloadBody = payload.body as PayloadBody;
- return {
- event: payloadBody.topic,
- identifierValue: payloadBody.app_id,
- };
- },
- verify: ({ payload, webhookSecret }) => {
- const signature = payload.headers['x-hub-signature'];
- let hmac: crypto.Hmac;
- if (typeof webhookSecret === 'string') {
- hmac = crypto.createHmac('sha1', webhookSecret);
- } else {
- const app_id = (payload.body as PayloadBody).app_id;
- const webhookSecrets = webhookSecret as Record<string, string>;
- if (!(app_id in webhookSecrets)) {
- return false;
- }
- hmac = crypto.createHmac('sha1', webhookSecrets[app_id]);
- }
- hmac.update(`${payload.rawBody}`);
- const computedSignature = `sha1=${hmac.digest('hex')}`;
- return signature === computedSignature;
- },
+ parseAndReply: ({ payload }) => {
+ const payloadBody = readPayloadBody(payload.body);
+ return {
+ event: payloadBody?.topic,
+ identifierValue: payloadBody?.app_id,
+ };
+ },
+ verify: ({ payload, webhookSecret }) => {
+ const signature = payload.headers['x-hub-signature'];
+ const secret = resolveWebhookSecret({
+ webhookSecret,
+ appId: readPayloadBody(payload.body)?.app_id,
+ });
+ if (typeof signature !== 'string' || secret === undefined) {
+ return false;
+ }
+ const expected = `sha1=${crypto.createHmac('sha1', secret).update(`${payload.rawBody}`).digest('hex')}`;
+ const given = Buffer.from(signature);
+ const wanted = Buffer.from(expected);
+ return given.length === wanted.length && crypto.timingSafeEqual(given, wanted);
+ },
},
});
+function resolveWebhookSecret({
+ webhookSecret,
+ appId,
+}: {
+ webhookSecret: unknown;
+ appId: string | undefined;
+}): string | undefined {
+ if (typeof webhookSecret === 'string') {
+ return webhookSecret;
+ }
+ if (typeof webhookSecret !== 'object' || webhookSecret === null || appId === undefined) {
+ return undefined;
+ }
+ const secret = Object.prototype.hasOwnProperty.call(webhookSecret, appId)
+ ? Reflect.get(webhookSecret, appId)
+ : undefined;
+ return typeof secret === 'string' ? secret : undefined;
+}
+
+function readPayloadBody(body: unknown): PayloadBody | undefined {
+ if (typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const topic = Reflect.get(body, 'topic');
+ const appId = Reflect.get(body, 'app_id');
+ return {
+ topic: typeof topic === 'string' ? topic : undefined,
+ app_id: typeof appId === 'string' ? appId : undefined,
+ };
+}
+
type PayloadBody = {
- type: string;
- topic: string;
- id: string;
- app_id: string;
+ topic: string | undefined;
+ app_id: string | undefined;
};
diff --git a/packages/pieces/community/intercom/src/lib/actions/add-note-to-conversation.ts b/packages/pieces/community/intercom/src/lib/actions/add-note-to-conversation.ts
index 0a3cba7482d..a65018fec16 100644
--- a/packages/pieces/community/intercom/src/lib/actions/add-note-to-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/add-note-to-conversation.ts
@@ -2,6 +2,7 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { commonProps, intercomClient } from '../common';
import { conversationIdProp } from '../common/props';
+import { conversationOutputSchema } from '../output-schemas';
export const addNoteToConversationAction = createAction({
auth: intercomAuth,
@@ -9,18 +10,19 @@ export const addNoteToConversationAction = createAction({
classification: 'WRITE',
displayName: 'Add note to conversation',
description: 'Add a note (for other admins) to an existing conversation',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Append an internal admin-only note to an existing conversation; the note is visible to admins but never sent to the contact. Each call adds a new note, so it is not idempotent. To send a customer-visible reply instead, use Reply to conversation.', idempotent: false },
props: {
from: commonProps.admins({ displayName: 'From (Admin)', required: true }),
conversationId:conversationIdProp('Conversation ID', true),
- body: Property.ShortText({
+ body: Property.LongText({
displayName: 'Message Body',
required: true,
}),
},
+ outputSchema: conversationOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.reply({
conversation_id: context.propsValue.conversationId!,
diff --git a/packages/pieces/community/intercom/src/lib/actions/add-note-to-user.ts b/packages/pieces/community/intercom/src/lib/actions/add-note-to-user.ts
index 52d65c5d7b3..0939ddee58d 100644
--- a/packages/pieces/community/intercom/src/lib/actions/add-note-to-user.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/add-note-to-user.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
+import { noteOutputSchema } from '../output-schemas';
export const addNoteToUserAction = createAction({
auth: intercomAuth,
@@ -8,8 +9,8 @@ export const addNoteToUserAction = createAction({
classification: 'WRITE',
displayName: 'Add Note',
description: 'Add a note to a user',
- audience: 'both',
- aiMetadata: { description: 'Add an internal note to a contact resolved by email address; errors if no contact matches that email. Each call appends a new note, so it is not idempotent. This attaches a note to a contact, distinct from Add note to conversation which annotates a conversation thread.', idempotent: false },
+ audience: 'human',
+ aiMetadata: { description: 'Add an internal note to a contact resolved by email address; errors if no contact matches, and when several contacts (users or leads) share the email it uses the first match, so prefer a unique email. Each call appends a new note, so it is not idempotent. This attaches a note to a contact, distinct from Add note to conversation which annotates a conversation thread.', idempotent: false },
props: {
email: Property.ShortText({
displayName: 'Email',
@@ -20,8 +21,9 @@ export const addNoteToUserAction = createAction({
required: true,
}),
},
+ outputSchema: noteOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const contactResponse = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-company.ts b/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-company.ts
index dd5d9713b75..c98fe561f01 100644
--- a/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-company.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-company.ts
@@ -2,6 +2,8 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { companyIdProp } from '../common/props';
import { intercomClient } from '../common';
+import { findTagByName } from '../common/lookups';
+import { tagOutputSchema } from '../output-schemas';
export const addOrRemoveTagOnCompanyAction = createAction({
auth: intercomAuth,
@@ -9,8 +11,8 @@ export const addOrRemoveTagOnCompanyAction = createAction({
classification: 'WRITE',
displayName: 'Add/Remove Tag on Company',
description: 'Attach or remove a tag from a specific company.',
- audience: 'both',
- aiMetadata: { description: 'Attach or remove a tag (by tag name) on a company identified by its Intercom company ID; set the Untag flag to remove rather than add. Tags are created or reused by name, and the operation mutates the company, so it is not idempotent.', idempotent: false },
+ audience: 'human',
+ aiMetadata: { description: 'Attach or remove a tag (by tag name) on a company identified by its Intercom company ID; set the Untag flag to remove rather than add. Tags are created or reused by name. Adding a tag that is already there changes nothing; removing needs the tag to exist, so a retry after removal can fail and the action is not marked idempotent.', idempotent: false },
props: {
companyId: companyIdProp('Company ID', true),
tagName: Property.ShortText({
@@ -23,15 +25,18 @@ export const addOrRemoveTagOnCompanyAction = createAction({
defaultValue: false,
}),
},
+ outputSchema: tagOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
+ const existingTag = await findTagByName({ auth: context.auth, name: context.propsValue.tagName });
+ const tagName = typeof existingTag?.['name'] === 'string' ? existingTag['name'] : context.propsValue.tagName;
if (context.propsValue.untag) {
const company = await client.companies.find({ company_id: context.propsValue.companyId! });
const userDefinedCompanyId = company.company_id;
const response = await client.tags.create({
- name: context.propsValue.tagName,
+ name: tagName,
companies: [
{ id: context.propsValue.companyId!, untag: true, company_id: userDefinedCompanyId },
],
@@ -41,7 +46,7 @@ export const addOrRemoveTagOnCompanyAction = createAction({
}
const response = await client.tags.create({
- name: context.propsValue.tagName,
+ name: tagName,
companies: [{ id: context.propsValue.companyId }],
});
diff --git a/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-contact.ts b/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-contact.ts
index daa4e0076d8..fdb216c6898 100644
--- a/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-contact.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-contact.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { contactIdProp, tagIdProp } from '../common/props';
import { intercomClient } from '../common';
+import { tagOutputSchema } from '../output-schemas';
export const addOrRemoveTagOnContactAction = createAction({
auth: intercomAuth,
@@ -9,8 +10,8 @@ export const addOrRemoveTagOnContactAction = createAction({
classification: 'WRITE',
displayName: 'Add/Remove Tag on Contact',
description: 'Attach or remove a tag from a specific contact.',
- audience: 'both',
- aiMetadata: { description: 'Tag or untag a contact by contact ID and tag ID; set the Untag flag to remove rather than add. Mutates the contact, so it is not idempotent. Requires an existing tag ID (use List Tags to discover one).', idempotent: false },
+ audience: 'human',
+ aiMetadata: { description: 'Tag or untag a contact by contact ID and tag ID; set the Untag flag to remove rather than add. Adding a tag that is already there changes nothing; removing a tag that is gone can fail, so it is not marked idempotent. Requires an existing tag ID (use List Tags to discover one).', idempotent: false },
props: {
contactId: contactIdProp('Contact ID','user', true),
tagId: tagIdProp('Tag Name', true),
@@ -20,8 +21,9 @@ export const addOrRemoveTagOnContactAction = createAction({
defaultValue: false,
}),
},
+ outputSchema: tagOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
if (context.propsValue.untag) {
const response = await client.tags.untagContact({
diff --git a/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-conversation.ts b/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-conversation.ts
index 7fecb80c879..a6e07517304 100644
--- a/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/add-remove-tag-on-conversation.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { conversationIdProp, tagIdProp } from '../common/props';
import { intercomClient } from '../common';
+import { tagOutputSchema } from '../output-schemas';
export const addOrRemoveTagOnConversationAction = createAction({
auth: intercomAuth,
@@ -9,8 +10,8 @@ export const addOrRemoveTagOnConversationAction = createAction({
classification: 'WRITE',
displayName: 'Add/Remove Tag on Conversation',
description: 'Attach or remove a tag from a specific conversation.',
- audience: 'both',
- aiMetadata: { description: 'Tag or untag a conversation by conversation ID and tag ID; set the Untag flag to remove rather than add. Mutates the conversation, so it is not idempotent. Requires an existing tag ID (use List Tags to discover one).', idempotent: false },
+ audience: 'human',
+ aiMetadata: { description: 'Tag or untag a conversation by conversation ID and tag ID; set the Untag flag to remove rather than add. Adding a tag that is already there changes nothing; removing a tag that is gone can fail, so it is not marked idempotent. Requires an existing tag ID (use List Tags to discover one).', idempotent: false },
props: {
conversationId: conversationIdProp('Conversation ID', true),
tagId: tagIdProp('Tag', true),
@@ -20,8 +21,9 @@ export const addOrRemoveTagOnConversationAction = createAction({
defaultValue: false,
}),
},
+ outputSchema: tagOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const admin = await client.admins.identify();
const adminId = admin.id;
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/add-note-to-contact.ts b/packages/pieces/community/intercom/src/lib/actions/ai/add-note-to-contact.ts
new file mode 100644
index 00000000000..d6f3e3dad7c
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/add-note-to-contact.ts
@@ -0,0 +1,51 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { requireText } from '../../common/lookups';
+import { noteOutputSchema } from '../../output-schemas';
+
+export const addNoteToContactAction = createAction({
+ auth: intercomAuth,
+ name: 'add_note_to_contact',
+ classification: 'WRITE',
+ displayName: 'Add Note to Contact (by ID)',
+ description: 'Adds an internal note to a contact by contact ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds an internal note to one contact (user or lead) by Intercom contact ID; only teammates see it. Get the ID from Get Contact or Search Contacts. Use Add Note to Conversation (by ID) to annotate a conversation instead. Each call adds another note, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ contactId: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Intercom contact ID.',
+ required: true,
+ }),
+ body: Property.LongText({
+ displayName: 'Note Text',
+ description: 'The note text. Simple HTML is allowed.',
+ required: true,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'Author Admin ID',
+ description: 'The admin shown as the author. Leave empty to use the admin who owns this connection.',
+ required: false,
+ }),
+ },
+ outputSchema: noteOutputSchema,
+ async run(context) {
+ const contactId = requireText({ label: 'Contact ID', value: context.propsValue.contactId });
+ const body = requireText({ label: 'Note Text', value: context.propsValue.body });
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['contacts', contactId, 'notes'],
+ body: { body, admin_id: adminId },
+ operation: 'add the note',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/add-note-to-conversation-by-id.ts b/packages/pieces/community/intercom/src/lib/actions/ai/add-note-to-conversation-by-id.ts
new file mode 100644
index 00000000000..150aa2df21a
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/add-note-to-conversation-by-id.ts
@@ -0,0 +1,51 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { requireText } from '../../common/lookups';
+import { conversationOutputSchema } from '../../output-schemas';
+
+export const addNoteToConversationByIdAction = createAction({
+ auth: intercomAuth,
+ name: 'add_note_to_conversation_by_id',
+ classification: 'WRITE',
+ displayName: 'Add Note to Conversation (by ID)',
+ description: 'Adds an internal note, visible only to your team, to a conversation.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds an internal note to an existing conversation; only teammates see it, the customer never does. Use Reply to Conversation (by ID) to answer the customer. Each call adds another note, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ conversationId: Property.ShortText({
+ displayName: 'Conversation ID',
+ description: 'The Intercom conversation ID.',
+ required: true,
+ }),
+ body: Property.LongText({
+ displayName: 'Note',
+ description: 'The note text. Simple HTML is allowed.',
+ required: true,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'Admin ID',
+ description: 'The admin who writes the note. Leave empty to use the admin who owns this connection.',
+ required: false,
+ }),
+ },
+ outputSchema: conversationOutputSchema,
+ async run(context) {
+ const conversationId = requireText({ label: 'Conversation ID', value: context.propsValue.conversationId });
+ const body = requireText({ label: 'Note', value: context.propsValue.body });
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['conversations', conversationId, 'reply'],
+ body: { message_type: 'note', type: 'admin', admin_id: adminId, body },
+ operation: 'add a note to the conversation',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/assign-conversation-by-id.ts b/packages/pieces/community/intercom/src/lib/actions/ai/assign-conversation-by-id.ts
new file mode 100644
index 00000000000..822e833f7e8
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/assign-conversation-by-id.ts
@@ -0,0 +1,64 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { requireText } from '../../common/lookups';
+import { conversationOutputSchema } from '../../output-schemas';
+
+export const assignConversationByIdAction = createAction({
+ auth: intercomAuth,
+ name: 'assign_conversation_by_id',
+ classification: 'WRITE',
+ displayName: 'Assign Conversation (by ID)',
+ description: 'Assigns a conversation to an admin or a team, or unassigns it.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Assigns an existing conversation to an admin or a team by ID; assignee ID 0 unassigns it. Get IDs from List Admins or List Teams. No message is posted, and assigning to the same assignee again leaves the same state, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ conversationId: Property.ShortText({
+ displayName: 'Conversation ID',
+ description: 'The Intercom conversation ID.',
+ required: true,
+ }),
+ assigneeType: Property.StaticDropdown({
+ displayName: 'Assign To',
+ required: true,
+ defaultValue: 'admin',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Admin', value: 'admin' },
+ { label: 'Team', value: 'team' },
+ ],
+ },
+ }),
+ assigneeId: Property.ShortText({
+ displayName: 'Assignee ID',
+ description: 'The admin or team ID. Use 0 to unassign.',
+ required: true,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'Acting Admin ID',
+ description: 'The admin who performs the assignment. Leave empty to use the admin who owns this connection.',
+ required: false,
+ }),
+ },
+ outputSchema: conversationOutputSchema,
+ async run(context) {
+ const conversationId = requireText({ label: 'Conversation ID', value: context.propsValue.conversationId });
+ const assigneeId = requireText({ label: 'Assignee ID', value: context.propsValue.assigneeId });
+ const assigneeType = context.propsValue.assigneeType === 'team' ? 'team' : 'admin';
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['conversations', conversationId, 'parts'],
+ body: { message_type: 'assignment', type: assigneeType, admin_id: adminId, assignee_id: assigneeId },
+ operation: 'assign the conversation',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/create-conversation-from-contact.ts b/packages/pieces/community/intercom/src/lib/actions/ai/create-conversation-from-contact.ts
new file mode 100644
index 00000000000..f1616afae35
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/create-conversation-from-contact.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { requireText, resolveContact } from '../../common/lookups';
+import { messageOutputSchema } from '../../output-schemas';
+
+export const createConversationFromContactAction = createAction({
+ auth: intercomAuth,
+ name: 'create_conversation_from_contact',
+ classification: 'WRITE',
+ displayName: 'Create Conversation from Contact',
+ description: 'Starts a new conversation with a first message written as the contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts a new inbox conversation whose first message is authored by the contact (as if they wrote in), by Intercom contact ID. It does not message the contact; use Send Message to Contact for an outbound admin message and Reply to Conversation (by ID) to answer an existing thread. Returns the message with its conversation_id. Each call opens another conversation, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ contactId: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Intercom contact ID (user or lead).',
+ required: true,
+ }),
+ body: Property.LongText({
+ displayName: 'Message Body',
+ description: 'Plain text; HTML is not supported here.',
+ required: true,
+ }),
+ },
+ outputSchema: messageOutputSchema,
+ async run(context) {
+ const contactId = requireText({ label: 'Contact ID', value: context.propsValue.contactId });
+ const body = requireText({ label: 'Message Body', value: context.propsValue.body });
+ const contact = await resolveContact({ auth: context.auth, lookupBy: 'id', value: contactId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['conversations'],
+ body: { from: { type: contact['role'] === 'lead' ? 'lead' : 'user', id: String(contact['id']) }, body },
+ operation: 'create the conversation',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/create-help-center-article.ts b/packages/pieces/community/intercom/src/lib/actions/ai/create-help-center-article.ts
new file mode 100644
index 00000000000..468314f296d
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/create-help-center-article.ts
@@ -0,0 +1,90 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { requireText } from '../../common/lookups';
+import { articleOutputSchema } from '../../output-schemas';
+
+export const createHelpCenterArticleAction = createAction({
+ auth: intercomAuth,
+ name: 'create_help_center_article',
+ classification: 'WRITE',
+ displayName: 'Create Help Center Article',
+ description: 'Creates a Help Center article, as a draft unless told to publish.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a Help Center article with a title and optional description, HTML body, author admin ID and parent collection ID. It is saved as a draft unless State is published, which makes it public. Use Search Help Center Articles to check for an existing article first. Each call creates another article, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ title: Property.ShortText({
+ displayName: 'Title',
+ required: true,
+ }),
+ description: Property.ShortText({
+ displayName: 'Description',
+ required: false,
+ }),
+ body: Property.LongText({
+ displayName: 'Body',
+ description: 'The article content. HTML is allowed.',
+ required: false,
+ }),
+ authorId: Property.ShortText({
+ displayName: 'Author Admin ID',
+ description: 'Leave empty to use the admin who owns this connection.',
+ required: false,
+ }),
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ defaultValue: 'draft',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Draft', value: 'draft' },
+ { label: 'Published', value: 'published' },
+ ],
+ },
+ }),
+ collectionId: Property.ShortText({
+ displayName: 'Parent Collection ID',
+ description: 'The Help Center collection to put the article in. Leave empty for none.',
+ required: false,
+ }),
+ },
+ outputSchema: articleOutputSchema,
+ async run(context) {
+ const title = requireText({ label: 'Title', value: context.propsValue.title });
+ const authorId = toInteger({
+ label: 'Author Admin ID',
+ value: await resolveAdminId({ auth: context.auth, adminId: context.propsValue.authorId }),
+ });
+ const collectionId = context.propsValue.collectionId?.trim();
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['articles'],
+ body: {
+ title,
+ description: context.propsValue.description || undefined,
+ body: context.propsValue.body || undefined,
+ author_id: authorId,
+ state: context.propsValue.state === 'published' ? 'published' : 'draft',
+ parent_id: collectionId ? toInteger({ label: 'Parent Collection ID', value: collectionId }) : undefined,
+ parent_type: collectionId ? 'collection' : undefined,
+ },
+ operation: 'create the article',
+ });
+ },
+});
+
+function toInteger({ label, value }: { label: string; value: string }): number {
+ const parsed = Number(value.trim());
+ if (!Number.isInteger(parsed)) {
+ throw new Error(`${label} must be a numeric Intercom ID, got "${value}".`);
+ }
+ return parsed;
+}
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/create-ticket-by-type-id.ts b/packages/pieces/community/intercom/src/lib/actions/ai/create-ticket-by-type-id.ts
new file mode 100644
index 00000000000..a98907157dd
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/create-ticket-by-type-id.ts
@@ -0,0 +1,97 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { requireText } from '../../common/lookups';
+import { getTicketTypeAttributes, toTicketAttributes } from '../../common/ticket-attributes';
+import { ticketOutputSchema } from '../../output-schemas';
+
+export const createTicketByTypeIdAction = createAction({
+ auth: intercomAuth,
+ name: 'create_ticket_by_type_id',
+ classification: 'WRITE',
+ displayName: 'Create Ticket (by Type ID)',
+ description: 'Creates a ticket of a given ticket type for one contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a ticket of a given ticket type for one contact (by contact ID, email or external ID). An email that matches no contact makes Intercom create a new contact for it, so look the contact up first if that is not wanted. Call List Ticket Types first to get the type ID and its attribute names; list attributes take the option ID, dates take ISO 8601. Each call creates another ticket, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ ticketTypeId: Property.ShortText({
+ displayName: 'Ticket Type ID',
+ description: 'From List Ticket Types.',
+ required: true,
+ }),
+ contactLookupBy: Property.StaticDropdown({
+ displayName: 'Identify Contact By',
+ required: true,
+ defaultValue: 'id',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Contact ID', value: 'id' },
+ { label: 'Email', value: 'email' },
+ { label: 'External ID', value: 'external_id' },
+ ],
+ },
+ }),
+ contactValue: Property.ShortText({
+ displayName: 'Contact',
+ description: 'The contact ID, email or external ID, matching Identify Contact By. An unknown email creates a new contact.',
+ required: true,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title',
+ required: false,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ attributes: Property.Object({
+ displayName: 'Other Attributes',
+ description: 'Ticket type attributes by name, for example {"Priority": "<list option ID>", "Due": "2026-10-20T12:00:00Z"}.',
+ required: false,
+ }),
+ companyId: Property.ShortText({
+ displayName: 'Company ID',
+ description: 'Optional Intercom company ID to link.',
+ required: false,
+ }),
+ },
+ outputSchema: ticketOutputSchema,
+ async run(context) {
+ const ticketTypeId = requireText({ label: 'Ticket Type ID', value: context.propsValue.ticketTypeId });
+ const contactValue = requireText({ label: 'Contact', value: context.propsValue.contactValue });
+ const lookupBy = context.propsValue.contactLookupBy;
+ const contactKey = lookupBy === 'email' ? 'email' : lookupBy === 'external_id' ? 'external_id' : 'id';
+ const { title, description } = context.propsValue;
+ const values: Record<string, unknown> = {
+ ...(context.propsValue.attributes ?? {}),
+ ...(title?.trim() ? { _default_title_: title.trim() } : {}),
+ ...(description?.trim() ? { _default_description_: description.trim() } : {}),
+ };
+ const definitions = await getTicketTypeAttributes({ auth: context.auth, ticketTypeId });
+ const missing = definitions
+ .filter((definition) => definition.required_to_create === true && definition.archived !== true)
+ .map((definition) => definition.name)
+ .filter((name) => values[name] === undefined || values[name] === '');
+ if (missing.length > 0) {
+ throw new Error(`This ticket type requires: ${missing.join(', ')}.`);
+ }
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['tickets'],
+ body: {
+ ticket_type_id: ticketTypeId,
+ contacts: [{ [contactKey]: contactValue }],
+ company_id: context.propsValue.companyId?.trim() || undefined,
+ ticket_attributes: toTicketAttributes({ attributes: definitions, values }),
+ },
+ operation: 'create the ticket',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/get-conversation-by-id.ts b/packages/pieces/community/intercom/src/lib/actions/ai/get-conversation-by-id.ts
new file mode 100644
index 00000000000..90c24b649de
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/get-conversation-by-id.ts
@@ -0,0 +1,46 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { flattenParts, requireText } from '../../common/lookups';
+import { conversationFlatPartsOutputSchema } from '../../output-schemas';
+
+export const getConversationByIdAction = createAction({
+ auth: intercomAuth,
+ name: 'get_conversation_by_id',
+ classification: 'READ',
+ displayName: 'Get Conversation (by ID)',
+ description: 'Gets a conversation and its messages by conversation ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Fetch one conversation by its ID, with every message flattened into parts (author type, author ID and name, part type, body, time). Use after Search Conversations or a trigger gives you the ID; use Search Conversations when you only know the customer or topic. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ conversationId: Property.ShortText({
+ displayName: 'Conversation ID',
+ description: 'The Intercom conversation ID, for example from Search Conversations.',
+ required: true,
+ }),
+ plainText: Property.Checkbox({
+ displayName: 'Plain Text Bodies',
+ description: 'Return message bodies as plain text instead of HTML.',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ outputSchema: conversationFlatPartsOutputSchema,
+ async run(context) {
+ const conversationId = requireText({ label: 'Conversation ID', value: context.propsValue.conversationId });
+ const conversation = await intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['conversations', conversationId],
+ query: { display_as: context.propsValue.plainText === false ? undefined : 'plaintext' },
+ operation: 'get the conversation',
+ });
+ const { conversation_parts, ...rest } = conversation;
+ return { ...rest, parts: flattenParts(conversation_parts) };
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/list-segments.ts b/packages/pieces/community/intercom/src/lib/actions/ai/list-segments.ts
new file mode 100644
index 00000000000..e9f6241c58c
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/list-segments.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { listSegmentsOutputSchema } from '../../output-schemas';
+
+export const listSegmentsAction = createAction({
+ auth: intercomAuth,
+ name: 'list_segments',
+ classification: 'SEARCH',
+ displayName: 'List Segments',
+ description: 'Lists the contact segments in the workspace.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every contact segment with ID, name and person type, optionally with the number of contacts in each. Use to find a segment ID before Search Contacts or List Companies. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ includeCount: Property.Checkbox({
+ displayName: 'Include Counts',
+ description: 'Also return how many contacts are in each segment.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: listSegmentsOutputSchema,
+ async run(context) {
+ const body = await intercomRequest<{ segments?: Array<Record<string, unknown>> }>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['segments'],
+ query: { include_count: context.propsValue.includeCount === true ? true : undefined },
+ operation: 'list segments',
+ });
+ return {
+ items: (body.segments ?? []).map((segment) => ({
+ id: segment['id'],
+ name: segment['name'] ?? null,
+ person_type: segment['person_type'] ?? null,
+ count: segment['count'] ?? null,
+ created_at: segment['created_at'] ?? null,
+ updated_at: segment['updated_at'] ?? null,
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/reply-to-conversation-by-id.ts b/packages/pieces/community/intercom/src/lib/actions/ai/reply-to-conversation-by-id.ts
new file mode 100644
index 00000000000..6663ca0d59c
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/reply-to-conversation-by-id.ts
@@ -0,0 +1,63 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { attachmentUrlList, requireText } from '../../common/lookups';
+import { conversationOutputSchema } from '../../output-schemas';
+
+export const replyToConversationByIdAction = createAction({
+ auth: intercomAuth,
+ name: 'reply_to_conversation_by_id',
+ classification: 'WRITE',
+ displayName: 'Reply to Conversation (by ID)',
+ description: 'Posts an admin reply that the customer sees in a conversation.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Posts a customer-visible admin reply in an existing conversation; Intercom may also email it to the contact. Use Add Note to Conversation (by ID) for internal remarks and Send Message to Contact to start a new thread. Each call posts a new reply, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ conversationId: Property.ShortText({
+ displayName: 'Conversation ID',
+ description: 'The Intercom conversation ID.',
+ required: true,
+ }),
+ body: Property.LongText({
+ displayName: 'Reply',
+ description: 'The reply text. Simple HTML is allowed.',
+ required: true,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'Admin ID',
+ description: 'The admin who replies. Leave empty to reply as the admin who owns this connection (see List Admins).',
+ required: false,
+ }),
+ attachmentUrls: Property.Array({
+ displayName: 'Attachment URLs',
+ description: 'Up to 10 public image URLs to attach.',
+ required: false,
+ }),
+ },
+ outputSchema: conversationOutputSchema,
+ async run(context) {
+ const conversationId = requireText({ label: 'Conversation ID', value: context.propsValue.conversationId });
+ const body = requireText({ label: 'Reply', value: context.propsValue.body });
+ const attachmentUrls = attachmentUrlList(context.propsValue.attachmentUrls);
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['conversations', conversationId, 'reply'],
+ body: {
+ message_type: 'comment',
+ type: 'admin',
+ admin_id: adminId,
+ body,
+ attachment_urls: attachmentUrls,
+ },
+ operation: 'reply to the conversation',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/send-message-to-contact.ts b/packages/pieces/community/intercom/src/lib/actions/ai/send-message-to-contact.ts
new file mode 100644
index 00000000000..a32140ab87b
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/send-message-to-contact.ts
@@ -0,0 +1,115 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { requireText, resolveContact } from '../../common/lookups';
+import { messageOutputSchema } from '../../output-schemas';
+
+export const sendMessageToContactAction = createAction({
+ auth: intercomAuth,
+ name: 'send_message_to_contact',
+ classification: 'WRITE',
+ displayName: 'Send Message to Contact',
+ description: 'Sends a new email or in-app message from an admin to one contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sends a new outbound email or in-app message from an admin to one contact (by contact ID or a unique email); it reaches a real person. Use Reply to Conversation (by ID) to answer inside an existing conversation. Each call sends again, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ contactId: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Intercom contact ID. Give either Contact ID or Contact Email.',
+ required: false,
+ }),
+ email: Property.ShortText({
+ displayName: 'Contact Email',
+ description: 'Used when no Contact ID is given. Fails if several contacts share this email.',
+ required: false,
+ }),
+ messageType: Property.StaticDropdown({
+ displayName: 'Message Type',
+ required: true,
+ defaultValue: 'email',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Email', value: 'email' },
+ { label: 'In-App', value: 'in_app' },
+ ],
+ },
+ }),
+ subject: Property.ShortText({
+ displayName: 'Subject',
+ description: 'Required for email.',
+ required: false,
+ }),
+ template: Property.StaticDropdown({
+ displayName: 'Email Template',
+ required: false,
+ defaultValue: 'plain',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Plain', value: 'plain' },
+ { label: 'Personal', value: 'personal' },
+ ],
+ },
+ }),
+ body: Property.LongText({
+ displayName: 'Message',
+ description: 'The message text. Simple HTML is allowed.',
+ required: true,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'From Admin ID',
+ description: 'The sending admin. Leave empty to send as the admin who owns this connection.',
+ required: false,
+ }),
+ openConversation: Property.Checkbox({
+ displayName: 'Open Conversation Right Away',
+ description: 'Open a conversation in the inbox without waiting for the contact to reply.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: messageOutputSchema,
+ async run(context) {
+ const { contactId, email, messageType, subject, template, openConversation } = context.propsValue;
+ const body = requireText({ label: 'Message', value: context.propsValue.body });
+ const isEmail = messageType !== 'in_app';
+ if (isEmail && !subject?.trim()) {
+ throw new Error('Subject is required for an email message.');
+ }
+ const hasId = Boolean(contactId?.trim());
+ const hasEmail = Boolean(email?.trim());
+ if (hasId === hasEmail) {
+ throw new Error('Give exactly one of Contact ID or Contact Email.');
+ }
+ const contact = await resolveContact({
+ auth: context.auth,
+ lookupBy: hasId ? 'id' : 'email',
+ value: hasId ? contactId ?? '' : email ?? '',
+ });
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['messages'],
+ body: {
+ message_type: isEmail ? 'email' : IN_APP_WIRE_VALUE,
+ subject: isEmail ? subject?.trim() : undefined,
+ template: isEmail ? template || 'plain' : undefined,
+ body,
+ from: { type: 'admin', id: Number(adminId) },
+ to: { type: contact['role'] === 'user' ? 'user' : 'lead', id: String(contact['id']) },
+ create_conversation_without_contact_reply: openConversation === true,
+ },
+ operation: 'send the message',
+ });
+ },
+});
+
+const IN_APP_WIRE_VALUE = 'inapp';
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/tag-or-untag-record.ts b/packages/pieces/community/intercom/src/lib/actions/ai/tag-or-untag-record.ts
new file mode 100644
index 00000000000..193389a7943
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/tag-or-untag-record.ts
@@ -0,0 +1,73 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { requireText, setRecordTag, TagTarget } from '../../common/lookups';
+import { tagOrUntagOutputSchema } from '../../output-schemas';
+
+export const tagOrUntagRecordAction = createAction({
+ auth: intercomAuth,
+ name: 'tag_or_untag_record',
+ classification: 'WRITE',
+ displayName: 'Tag or Untag Record',
+ description: 'Adds or removes a tag on a contact, conversation, company or ticket.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds or removes a tag on a contact, conversation, company or ticket by record ID. Pass a tag ID or a tag name; when adding, a name that does not exist yet is created. Applying a tag that is already there, or removing one that is not applied, succeeds and leaves the same state (already_in_state is true only when the tag does not exist at all), so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ target: Property.StaticDropdown({
+ displayName: 'Record Type',
+ required: true,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Contact', value: 'contact' },
+ { label: 'Conversation', value: 'conversation' },
+ { label: 'Company', value: 'company' },
+ { label: 'Ticket', value: 'ticket' },
+ ],
+ },
+ }),
+ recordId: Property.ShortText({
+ displayName: 'Record ID',
+ description: 'The Intercom ID of the contact, conversation, company (Intercom company ID, not your Company ID) or ticket.',
+ required: true,
+ }),
+ tagId: Property.ShortText({
+ displayName: 'Tag ID',
+ description: 'The tag ID from List Tags. Give either Tag ID or Tag Name.',
+ required: false,
+ }),
+ tagName: Property.ShortText({
+ displayName: 'Tag Name',
+ description: 'The tag name (case-insensitive). Give either Tag ID or Tag Name.',
+ required: false,
+ }),
+ remove: Property.Checkbox({
+ displayName: 'Remove Tag',
+ description: 'Turn on to remove the tag instead of adding it.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: tagOrUntagOutputSchema,
+ async run(context) {
+ const target = parseTarget(context.propsValue.target);
+ const recordId = requireText({ label: 'Record ID', value: context.propsValue.recordId });
+ const tagId = context.propsValue.tagId?.trim() || undefined;
+ const tagName = context.propsValue.tagName?.trim() || undefined;
+ if ((tagId === undefined) === (tagName === undefined)) {
+ throw new Error('Give exactly one of Tag ID or Tag Name.');
+ }
+ const remove = context.propsValue.remove === true;
+ return setRecordTag({ auth: context.auth, target, recordId, tagId, tagName, remove });
+ },
+});
+
+function parseTarget(value: unknown): TagTarget {
+ if (value === 'contact' || value === 'conversation' || value === 'company' || value === 'ticket') {
+ return value;
+ }
+ throw new Error('Record Type must be contact, conversation, company or ticket.');
+}
diff --git a/packages/pieces/community/intercom/src/lib/actions/ai/update-ticket-by-id.ts b/packages/pieces/community/intercom/src/lib/actions/ai/update-ticket-by-id.ts
new file mode 100644
index 00000000000..1aaf9f61854
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/ai/update-ticket-by-id.ts
@@ -0,0 +1,125 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../../auth';
+import { intercomRequest } from '../../common';
+import { resolveAdminId } from '../../common/client';
+import { requireText, toUnixSeconds } from '../../common/lookups';
+import { getTicketTypeAttributes, toTicketAttributes } from '../../common/ticket-attributes';
+import { ticketOutputSchema } from '../../output-schemas';
+
+export const updateTicketByIdAction = createAction({
+ auth: intercomAuth,
+ name: 'update_ticket_by_id',
+ classification: 'WRITE',
+ displayName: 'Update Ticket (by ID)',
+ description: "Changes a ticket's state, assignee, snooze time or attributes.",
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Changes a ticket's state, open flag, shared flag, assignee, snooze time or attributes by ticket ID (the API id, not the inbox number). Omitted fields stay as they are; an attribute set to null is cleared. Setting the same values again changes nothing, so it is safe to retry.",
+ idempotent: true,
+ },
+ props: {
+ ticketId: Property.ShortText({
+ displayName: 'Ticket ID',
+ description: 'The ticket "id" from Intercom, not the inbox ticket number.',
+ required: true,
+ }),
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'In Progress', value: 'in_progress' },
+ { label: 'Waiting on Customer', value: 'waiting_on_customer' },
+ { label: 'Resolved', value: 'resolved' },
+ ],
+ },
+ }),
+ open: Property.StaticDropdown({
+ displayName: 'Open or Closed',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Open', value: 'open' },
+ { label: 'Closed', value: 'closed' },
+ ],
+ },
+ }),
+ isShared: Property.StaticDropdown({
+ displayName: 'Visible to Customer',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Shared', value: 'shared' },
+ { label: 'Not Shared', value: 'not_shared' },
+ ],
+ },
+ }),
+ snoozedUntil: Property.DateTime({
+ displayName: 'Snooze Until',
+ required: false,
+ }),
+ assigneeId: Property.ShortText({
+ displayName: 'Assignee Admin ID',
+ description: 'Assign the ticket to this admin (see List Admins). Use 0 to unassign.',
+ required: false,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'Acting Admin ID',
+ description: 'The admin who makes the assignment. Leave empty to use the admin who owns this connection.',
+ required: false,
+ }),
+ attributes: Property.Object({
+ displayName: 'Attributes',
+ description: 'Ticket attributes by name; null clears one. Dates take ISO 8601; list attributes take the option ID.',
+ required: false,
+ }),
+ },
+ outputSchema: ticketOutputSchema,
+ async run(context) {
+ const ticketId = requireText({ label: 'Ticket ID', value: context.propsValue.ticketId });
+ const { state, open, isShared, snoozedUntil, attributes } = context.propsValue;
+ const assigneeId = context.propsValue.assigneeId?.trim() || undefined;
+ const hasAttributes = attributes !== undefined && attributes !== null && Object.keys(attributes).length > 0;
+
+ const body: Record<string, unknown> = {
+ ...(state ? { state } : {}),
+ ...(open ? { open: open === 'open' } : {}),
+ ...(isShared ? { is_shared: isShared === 'shared' } : {}),
+ ...(snoozedUntil ? { snoozed_until: toUnixSeconds({ label: 'Snooze Until', value: snoozedUntil }) } : {}),
+ };
+ if (Object.keys(body).length === 0 && assigneeId === undefined && !hasAttributes) {
+ throw new Error('Nothing to update. Set at least one field.');
+ }
+ if (assigneeId !== undefined) {
+ body['assignment'] = {
+ admin_id: await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId }),
+ assignee_id: assigneeId,
+ };
+ }
+ if (hasAttributes) {
+ const ticket = await intercomRequest<{ ticket_type?: { id?: string } }>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['tickets', ticketId],
+ operation: 'get the ticket',
+ });
+ const ticketTypeId = ticket.ticket_type?.id;
+ const definitions = ticketTypeId
+ ? await getTicketTypeAttributes({ auth: context.auth, ticketTypeId: String(ticketTypeId) })
+ : [];
+ body['ticket_attributes'] = toTicketAttributes({ attributes: definitions, values: attributes });
+ }
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.PUT,
+ path: ['tickets', ticketId],
+ body,
+ operation: 'update the ticket',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/assign-conversation-to-admin.ts b/packages/pieces/community/intercom/src/lib/actions/assign-conversation-to-admin.ts
index 1284dac55b1..6b4e6c4e3b0 100644
--- a/packages/pieces/community/intercom/src/lib/actions/assign-conversation-to-admin.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/assign-conversation-to-admin.ts
@@ -2,6 +2,7 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { commonProps, intercomClient } from '../common';
import { conversationIdProp } from '../common/props';
+import { conversationOutputSchema } from '../output-schemas';
export const assignConversationAction = createAction({
auth: intercomAuth,
@@ -9,8 +10,8 @@ export const assignConversationAction = createAction({
classification: 'WRITE',
displayName: 'Assign conversation to an admin or a team',
description: '(Re)assign conversation to a specific admin or team.',
- audience: 'both',
- aiMetadata: { description: 'Reassign an existing conversation to a specific admin or team by assignee ID, optionally with a message body. Reapplying the same assignee converges on the same state so it is effectively idempotent, though each call logs an assignment part. The assignee ID must be a valid admin or team ID.', idempotent: true },
+ audience: 'human',
+ aiMetadata: { description: 'Reassign an existing conversation to a specific admin or team by assignee ID, optionally with a message body. The assignee converges on retry, but each call logs a new assignment part and posts the optional message again, so it is not idempotent. The assignee ID must be a valid admin or team ID.', idempotent: false },
props: {
from: commonProps.admins({ displayName: 'From (Admin)', required: true }),
conversationId:conversationIdProp('Conversation ID', true),
@@ -19,13 +20,14 @@ export const assignConversationAction = createAction({
description: 'The ID of the admin or team to assign this conversation to',
required: true,
}),
- body: Property.ShortText({
+ body: Property.LongText({
displayName: 'Message Body',
required: false,
}),
},
+ outputSchema: conversationOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.manage({
conversation_id: context.propsValue.conversationId!,
diff --git a/packages/pieces/community/intercom/src/lib/actions/attach-contact-to-company.ts b/packages/pieces/community/intercom/src/lib/actions/attach-contact-to-company.ts
new file mode 100644
index 00000000000..9ce40a1bb1c
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/attach-contact-to-company.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { requireText } from '../common/lookups';
+import { companyOutputSchema } from '../output-schemas';
+
+export const attachContactToCompanyAction = createAction({
+ auth: intercomAuth,
+ name: 'attach_contact_to_company',
+ classification: 'WRITE',
+ displayName: 'Attach Contact to Company',
+ description: 'Links a contact to a company.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Links a contact to a company, both by Intercom ID (use Get Company to turn your own Company ID into the Intercom ID). A contact can belong to several companies; attaching an existing link leaves the same state, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: true }),
+ companyId: Property.ShortText({
+ displayName: 'Intercom Company ID',
+ description: 'The Intercom "id" of the company, not your own Company ID.',
+ required: true,
+ }),
+ },
+ outputSchema: companyOutputSchema,
+ async run(context) {
+ const contactId = requireText({ label: 'Contact ID', value: context.propsValue.contactId });
+ const companyId = requireText({ label: 'Intercom Company ID', value: context.propsValue.companyId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['contacts', contactId, 'companies'],
+ body: { id: companyId },
+ operation: 'attach the contact to the company',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/convert-conversation-to-ticket.ts b/packages/pieces/community/intercom/src/lib/actions/convert-conversation-to-ticket.ts
new file mode 100644
index 00000000000..5fceaf8949f
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/convert-conversation-to-ticket.ts
@@ -0,0 +1,54 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { requireText } from '../common/lookups';
+import { getTicketTypeAttributes, toTicketAttributes } from '../common/ticket-attributes';
+import { ticketOutputSchema } from '../output-schemas';
+
+export const convertConversationToTicketAction = createAction({
+ auth: intercomAuth,
+ name: 'convert_conversation_to_ticket',
+ classification: 'WRITE',
+ displayName: 'Convert Conversation to Ticket',
+ description: 'Turns a conversation into a ticket of the chosen ticket type.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Turns an existing conversation into a ticket of the given ticket type (only Customer-category types), optionally setting ticket attributes. The customer may be notified. Converting is a one-off change, so retries fail or duplicate; it is not idempotent.',
+ idempotent: false,
+ },
+ props: {
+ conversationId: Property.ShortText({ displayName: 'Conversation ID', required: true }),
+ ticketTypeId: Property.ShortText({
+ displayName: 'Ticket Type ID',
+ description: 'From List Ticket Types.',
+ required: true,
+ }),
+ attributes: Property.Object({
+ displayName: 'Ticket Attributes',
+ description: 'Optional attributes by name. Dates take ISO 8601; list attributes take the option ID.',
+ required: false,
+ }),
+ },
+ outputSchema: ticketOutputSchema,
+ async run(context) {
+ const conversationId = requireText({ label: 'Conversation ID', value: context.propsValue.conversationId });
+ const ticketTypeId = requireText({ label: 'Ticket Type ID', value: context.propsValue.ticketTypeId });
+ const values = context.propsValue.attributes ?? {};
+ const attributes =
+ Object.keys(values).length > 0
+ ? toTicketAttributes({
+ attributes: await getTicketTypeAttributes({ auth: context.auth, ticketTypeId }),
+ values,
+ })
+ : undefined;
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['conversations', conversationId, 'convert'],
+ body: { ticket_type_id: ticketTypeId, attributes },
+ operation: 'convert the conversation to a ticket',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-article.ts b/packages/pieces/community/intercom/src/lib/actions/create-article.ts
index 3c857da0774..7307b7d2d0f 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-article.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-article.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { commonProps, intercomClient } from '../common';
import { collectionIdProp } from '../common/props';
+import { articleOutputSchema } from '../output-schemas';
export const createArticleAction = createAction({
auth: intercomAuth,
@@ -9,7 +10,7 @@ export const createArticleAction = createAction({
classification: 'WRITE',
displayName: 'Create Article',
description: 'Creates a new article in your Help Center.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Create a new Help Center article with title, optional description and body, an author admin, and a draft or published state, optionally nested under a parent collection. Always creates a new article, so it is not idempotent and repeated calls produce duplicates.', idempotent: false },
props: {
title: Property.LongText({
@@ -39,6 +40,7 @@ export const createArticleAction = createAction({
}),
collectionId: collectionIdProp('Parent Collection', false),
},
+ outputSchema: articleOutputSchema,
async run(context) {
const { authorId, collectionId, title, description, body, state } = context.propsValue;
@@ -46,7 +48,7 @@ export const createArticleAction = createAction({
throw new Error('Author is required');
}
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.articles.create({
title,
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-conversation.ts b/packages/pieces/community/intercom/src/lib/actions/create-conversation.ts
index 0b4f06f17d7..09c99cbb416 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-conversation.ts
@@ -1,10 +1,8 @@
import { intercomAuth } from '../auth';
-import {
- createAction,
- DropdownOption,
- Property,
-} from '@activepieces/pieces-framework';
-import { intercomClient, IntercomAuthValue } from '../common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomClient } from '../common';
+import { contactOptionsForRoles } from '../common/props';
+import { messageOutputSchema } from '../output-schemas';
export const createConversationAction = createAction({
auth: intercomAuth,
@@ -12,7 +10,7 @@ export const createConversationAction = createAction({
classification: 'WRITE',
displayName: 'Create Conversation',
description: 'Creates a new conversation from a contact.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Start a new Intercom conversation on behalf of an existing contact by sending an initial message body from that contact. Pick this to open a fresh thread tied to a known user or lead; it does not reply to or search existing conversations. Requires a valid contact ID and the matching contact type (user or lead). Not idempotent — each call creates a separate conversation.',
@@ -45,25 +43,7 @@ export const createConversationAction = createAction({
};
}
- const type = contactType as 'user' | 'lead';
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const response = await client.contacts.list();
- const options: DropdownOption<string>[] = [];
-
- for await (const contact of response) {
- if (contact.role === type) {
- options.push({
- value: contact.id,
- label: `${contact.name ?? ''}, ${contact.email}, ${contact.external_id ?? ''}`,
- });
- }
- }
- return {
- disabled: false,
- options,
- };
+ return contactOptionsForRoles({ auth: auth, roles: [String(contactType)] });
},
}),
body: Property.LongText({
@@ -71,10 +51,11 @@ export const createConversationAction = createAction({
required: true,
}),
},
+ outputSchema: messageOutputSchema,
async run(context) {
const { contactId, body, contactType } = context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.create({
body,
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-data-event.ts b/packages/pieces/community/intercom/src/lib/actions/create-data-event.ts
index a8f37eb683e..bfa5f6100d2 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-data-event.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-data-event.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
import dayjs from 'dayjs';
+import { dataEventOutputSchema } from '../output-schemas';
export const createDataEventAction = createAction({
auth: intercomAuth,
@@ -49,11 +50,12 @@ export const createDataEventAction = createAction({
required: false,
}),
},
+ outputSchema: dataEventOutputSchema,
async run(context) {
const { identifierType, identifierValue, eventName, createdAt, metadata } =
context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const createdAtUnix = createdAt ? dayjs(createdAt).unix() : dayjs().unix();
const stringMetadata = metadata
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-tag.ts b/packages/pieces/community/intercom/src/lib/actions/create-tag.ts
new file mode 100644
index 00000000000..79d9900bcb1
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/create-tag.ts
@@ -0,0 +1,26 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { findOrCreateTag, requireText } from '../common/lookups';
+import { tagOutputSchema } from '../output-schemas';
+
+export const createTagAction = createAction({
+ auth: intercomAuth,
+ name: 'create_tag',
+ classification: 'WRITE',
+ displayName: 'Create Tag',
+ description: 'Creates a tag, or returns the existing tag with that name.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a tag with the given name, or returns the existing tag when one already has that name in any letter case (the existing name is left as it is). Calling it again returns the same tag, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Tag Name', required: true }),
+ },
+ outputSchema: tagOutputSchema,
+ async run(context) {
+ const name = requireText({ label: 'Tag Name', value: context.propsValue.name });
+ return findOrCreateTag({ auth: context.auth, name });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-ticket.ts b/packages/pieces/community/intercom/src/lib/actions/create-ticket.ts
index 32aa6897ecc..cc6f94794a2 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-ticket.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-ticket.ts
@@ -1,13 +1,15 @@
import { intercomAuth } from '../auth';
import { createAction } from '@activepieces/pieces-framework';
-import { intercomClient } from '../common';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { intercomRequest } from '../common';
import {
companyIdProp,
contactIdProp,
ticketPropertiesProp,
ticketTypeIdProp,
} from '../common/props';
-import dayjs from 'dayjs';
+import { getTicketTypeAttributes, toTicketAttributes } from '../common/ticket-attributes';
+import { ticketOutputSchema } from '../output-schemas';
export const createTicketAction = createAction({
auth: intercomAuth,
@@ -15,14 +17,15 @@ export const createTicketAction = createAction({
classification: 'WRITE',
displayName: 'Create Ticket',
description: 'Creates a new ticket.',
- audience: 'both',
- aiMetadata: { description: 'Create a new ticket of a given ticket type for a contact, optionally tied to a company, with type-specific ticket attributes (date-like strings are converted to timestamps). Always creates a new ticket, so it is not idempotent. To change an existing ticket instead, use Update Ticket.', idempotent: false },
+ audience: 'human',
+ aiMetadata: { description: 'Create a new ticket of a given ticket type for a contact, optionally tied to a company, with type-specific ticket attributes (only attributes the ticket type defines as date-time are converted to timestamps; text and list values are sent as given). Always creates a new ticket, so it is not idempotent. To change an existing ticket instead, use Update Ticket.', idempotent: false },
props: {
ticketTypeId: ticketTypeIdProp('Ticket Type', true),
contactId: contactIdProp('Contact ID', null, true),
companyId: companyIdProp('Company ID', false),
ticketProperties: ticketPropertiesProp('Ticket Properties', true),
},
+ outputSchema: ticketOutputSchema,
async run(context) {
const { ticketTypeId, contactId, companyId } = context.propsValue;
const ticketProperties = context.propsValue.ticketProperties ?? {};
@@ -35,26 +38,20 @@ export const createTicketAction = createAction({
throw new Error('Contact ID is required');
}
- const client = intercomClient(context.auth);
+ const attributes = await getTicketTypeAttributes({ auth: context.auth, ticketTypeId });
+ const formattedProperties = toTicketAttributes({ attributes, values: ticketProperties });
- const formattedProperties: Record<string, any> = {};
- for (const key in ticketProperties) {
- const value = ticketProperties[key];
-
- // Check if value is a valid date string and convert it to a timestamp
- if (typeof value === 'string' && dayjs(value).isValid()) {
- formattedProperties[key] = dayjs(value).unix(); // Convert to timestamp
- } else {
- formattedProperties[key] = value;
- }
- }
- const response = await client.tickets.create({
- ticket_type_id: ticketTypeId,
- contacts: [{ id: contactId }],
- company_id: companyId,
- ticket_attributes: formattedProperties,
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['tickets'],
+ body: {
+ ticket_type_id: ticketTypeId,
+ contacts: [{ id: contactId }],
+ company_id: companyId || undefined,
+ ticket_attributes: formattedProperties,
+ },
+ operation: 'create the ticket',
});
-
- return response;
},
});
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-update-company.ts b/packages/pieces/community/intercom/src/lib/actions/create-update-company.ts
index 0fabb0f1acd..4ef45649f82 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-update-company.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-update-company.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
import dayjs from 'dayjs';
+import { companyOutputSchema } from '../output-schemas';
export const createOrUpdateCompanyAction = createAction({
auth: intercomAuth,
@@ -12,8 +13,8 @@ export const createOrUpdateCompanyAction = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Upsert a company: Intercom matches on the Company ID you provide and updates that company if it exists, otherwise creates a new one. Company ID cannot be changed after creation. Repeating with the same Company ID and fields converges on the same record, so it is effectively idempotent.',
- idempotent: true,
+ 'Create or update a company. With a Company ID, Intercom updates the company that has it or creates one with it, so a retry converges; without a Company ID every call creates a new company. Company ID cannot be changed after creation.',
+ idempotent: false,
},
props: {
companyId: Property.ShortText({
@@ -57,6 +58,7 @@ export const createOrUpdateCompanyAction = createAction({
required: false,
}),
},
+ outputSchema: companyOutputSchema,
async run(context) {
const {
companyId,
@@ -74,7 +76,7 @@ export const createOrUpdateCompanyAction = createAction({
throw new Error('Provide a Company ID or a Name to create or update a company.');
}
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.companies.createOrUpdate({
company_id: companyId,
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-update-lead.ts b/packages/pieces/community/intercom/src/lib/actions/create-update-lead.ts
index e084c57c344..8cb90429a6c 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-update-lead.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-update-lead.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
import dayjs from 'dayjs';
+import { contactOutputSchema } from '../output-schemas';
export const createOrUpdateLeadAction = createAction({
auth: intercomAuth,
@@ -10,7 +11,7 @@ export const createOrUpdateLeadAction = createAction({
displayName: 'Create or Update Lead',
description: 'Create or update an Intercom lead.If an ID is provided, the lead will be updated.',
audience: 'both',
- aiMetadata: { description: 'Upsert a lead (prospect contact): if a Lead ID is supplied the matching lead is updated (erroring if none is found), otherwise a new lead is created. Providing an ID makes it effectively idempotent; without an ID each call creates a new lead. For signed-up users use Create/Update User instead.', idempotent: true },
+ aiMetadata: { description: 'Update a lead (prospect contact) when a Lead ID is given (errors if none is found), otherwise create a new lead. With a Lead ID a retry writes the same values; without one each call creates another lead, so it is not marked idempotent. For signed-up users use Create/Update User instead.', idempotent: false },
props: {
leadId: Property.ShortText({
displayName: 'Lead ID',
@@ -41,10 +42,11 @@ export const createOrUpdateLeadAction = createAction({
required: false,
}),
},
+ outputSchema: contactOutputSchema,
async run(context) {
const { leadId, name, email, phone, unsubscribe, createdAt, customAttributes } =
context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
if (leadId) {
const lead = await client.contacts.search({
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-update-user.ts b/packages/pieces/community/intercom/src/lib/actions/create-update-user.ts
index 25698416aa7..1d915d2128a 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-update-user.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-update-user.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
import dayjs from 'dayjs';
+import { contactOutputSchema } from '../output-schemas';
export const createOrUpdateUserAction = createAction({
auth: intercomAuth,
@@ -37,8 +38,9 @@ export const createOrUpdateUserAction = createAction({
required: false,
}),
},
+ outputSchema: contactOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const contact = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/actions/create-user.ts b/packages/pieces/community/intercom/src/lib/actions/create-user.ts
index 2a9d9e57b9f..1f10a6e04fd 100644
--- a/packages/pieces/community/intercom/src/lib/actions/create-user.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/create-user.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
import dayjs from 'dayjs';
+import { contactOutputSchema } from '../output-schemas';
export const createUserAction = createAction({
auth: intercomAuth,
@@ -33,8 +34,9 @@ export const createUserAction = createAction({
required: false,
}),
},
+ outputSchema: contactOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.create({
role: 'user',
diff --git a/packages/pieces/community/intercom/src/lib/actions/find-company.ts b/packages/pieces/community/intercom/src/lib/actions/find-company.ts
index 5d884076554..7f14cc709a3 100644
--- a/packages/pieces/community/intercom/src/lib/actions/find-company.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/find-company.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { intercomClient } from '../common';
+import { findCompanyBy } from '../common/lookups';
+import { findCompanyOutputSchema } from '../output-schemas';
export const findCompanyAction = createAction({
auth: intercomAuth,
@@ -9,7 +10,7 @@ export const findCompanyAction = createAction({
displayName: 'Find Company',
description: 'Finds an existing company.',
audience: 'both',
- aiMetadata: { description: 'Look up a single existing company by either its name or its company ID (choose the search field). Read-only and repeatable; returns the first match plus a found flag. Use to resolve a company before tagging it or attaching it to a ticket.', idempotent: true },
+ aiMetadata: { description: 'Look up a single existing company by its exact name or your own Company ID (choose the search field). Returns found=false when nothing matches; a name lookup only finds companies that already have a contact attached; the company is under "company" ("user" is a legacy copy). Read-only and safe to retry.', idempotent: true },
props: {
searchField: Property.StaticDropdown({
displayName: 'Search Field',
@@ -27,21 +28,20 @@ export const findCompanyAction = createAction({
required: true,
}),
},
+ outputSchema: findCompanyOutputSchema,
async run(context) {
const { searchField, searchValue } = context.propsValue;
- const client = intercomClient(context.auth);
-
- const companyResponse = await client.companies.retrieve({
- company_id: searchField === 'company_id' ? searchValue : undefined,
- name: searchField === 'name' ? searchValue : undefined,
- per_page:1
-
- })
+ const company = await findCompanyBy({
+ auth: context.auth,
+ field: searchField === 'company_id' ? 'company_id' : 'name',
+ value: searchValue,
+ });
return {
- found: companyResponse.data.length > 0,
- user: companyResponse.data.length > 0 ? companyResponse.data[0] : {},
+ found: company !== undefined,
+ company: company ?? {},
+ user: company ?? {},
};
},
});
diff --git a/packages/pieces/community/intercom/src/lib/actions/find-conversation.ts b/packages/pieces/community/intercom/src/lib/actions/find-conversation.ts
index eba5aacb293..b8dd3ab8b0c 100644
--- a/packages/pieces/community/intercom/src/lib/actions/find-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/find-conversation.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient, Operator } from '../common';
import dayjs from 'dayjs';
+import { findConversationOutputSchema } from '../output-schemas';
export const findConversationAction = createAction({
auth: intercomAuth,
@@ -9,8 +10,8 @@ export const findConversationAction = createAction({
classification: 'SEARCH',
displayName: 'Find Conversation',
description: 'Searches for conversations using various criteria',
- audience: 'both',
- aiMetadata: { description: 'Search conversations by a chosen field (ID, subject, message body, author email, assigned admin, team, or tag IDs) with a contains/equals/starts-with match, optionally filtered by open/closed status and an update-time window. Read-only and repeatable; returns the first match plus a found flag. Use when you do not already have the conversation ID — otherwise use Retrieve a Conversation.', idempotent: true },
+ audience: 'human',
+ aiMetadata: { description: 'Search conversations by a chosen field (ID, subject, message body, author email, assigned admin, team, or tag IDs) with a contains/equals/starts-with match (IDs: equals only), optionally filtered by open/closed/snoozed status and an update-time window. Read-only and repeatable; returns the first match plus a found flag. Use when you do not already have the conversation ID — otherwise use Retrieve a Conversation.', idempotent: true },
props: {
searchField: Property.StaticDropdown({
displayName: 'Search Field',
@@ -42,6 +43,7 @@ export const findConversationAction = createAction({
}),
searchTerm: Property.ShortText({
displayName: 'Search Term',
+ description: 'Conversation ID, Assigned Admin, Team and Tag IDs only support Equals.',
required: true,
}),
status: Property.StaticDropdown({
@@ -52,11 +54,13 @@ export const findConversationAction = createAction({
options: [
{ label: 'Open', value: 'open' },
{ label: 'Closed', value: 'closed' },
+ { label: 'Snoozed', value: 'snoozed' },
],
},
}),
updateAfter: Property.DateTime({
displayName: 'Update After',
+ description: 'Intercom compares dates by calendar day in your workspace time zone.',
required: false,
}),
updateBefore: Property.DateTime({
@@ -64,14 +68,19 @@ export const findConversationAction = createAction({
required: false,
}),
},
+ outputSchema: findConversationOutputSchema,
async run(context) {
const { searchField, matchType, searchTerm, status, updateAfter, updateBefore } =
context.propsValue;
+ if (matchType !== 'equals' && EQUALS_ONLY_FIELDS.includes(searchField)) {
+ throw new Error('Conversation ID, Assigned Admin, Team and Tag IDs can only be matched with Equals.');
+ }
+
const operator = matchType === 'contains' ? '~' : matchType === 'starts_with' ? '^' : '=';
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const filter = [
{
@@ -114,4 +123,6 @@ export const findConversationAction = createAction({
conversation: response.data.length > 0 ? response.data[0] : {},
};
},
-});
\ No newline at end of file
+});
+
+const EQUALS_ONLY_FIELDS = ['id', 'admin_assignee_id', 'team_assignee_id', 'tag_ids'];
diff --git a/packages/pieces/community/intercom/src/lib/actions/find-lead.ts b/packages/pieces/community/intercom/src/lib/actions/find-lead.ts
index bdedb1c36a2..2fe255dc7e7 100644
--- a/packages/pieces/community/intercom/src/lib/actions/find-lead.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/find-lead.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
+import { findLeadOutputSchema } from '../output-schemas';
export const findLeadAction = createAction({
auth: intercomAuth,
@@ -8,7 +9,7 @@ export const findLeadAction = createAction({
classification: 'READ',
displayName: 'Find Lead',
description: 'Finds an existing lead.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Look up a single existing lead (prospect contact) by email, Intercom ID, or external user ID. Read-only and repeatable; returns the first match plus a found flag and only matches role=lead. To find a signed-up user instead, use Find User.', idempotent: true },
props: {
searchField: Property.StaticDropdown({
@@ -28,10 +29,11 @@ export const findLeadAction = createAction({
required: true,
}),
},
+ outputSchema: findLeadOutputSchema,
async run(context) {
const { searchField, searchValue } = context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const contactResponse = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/actions/find-or-create-company.ts b/packages/pieces/community/intercom/src/lib/actions/find-or-create-company.ts
index 0e1aa6f8a40..e05521a87de 100644
--- a/packages/pieces/community/intercom/src/lib/actions/find-or-create-company.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/find-or-create-company.ts
@@ -1,6 +1,9 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { intercomClient } from '../common';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { intercomRequest } from '../common';
+import { findCompanyBy } from '../common/lookups';
+import { findOrCreateCompanyOutputSchema } from '../output-schemas';
export const findOrCreateCompanyAction = createAction({
auth: intercomAuth,
@@ -11,8 +14,8 @@ export const findOrCreateCompanyAction = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Resolve a company to a single record: looks it up by Company ID (preferred) or name and returns the match, or creates a new company when none exists. Returns the company plus a "created" flag. Effectively idempotent when a Company ID is supplied.',
- idempotent: true,
+ 'Resolve a company to a single record: looks it up by your Company ID (preferred) or exact name and returns the match, or creates a new company when none exists. Returns the company plus a "created" flag. With a Company ID a retry finds the same company; with only a name, a company that has no contact yet is not found by name, so a duplicate can be created.',
+ idempotent: false,
},
props: {
companyId: Property.ShortText({
@@ -46,6 +49,7 @@ export const findOrCreateCompanyAction = createAction({
required: false,
}),
},
+ outputSchema: findOrCreateCompanyOutputSchema,
async run(context) {
const { companyId, name, plan, size, website, industry, customAttributes } =
context.propsValue;
@@ -54,26 +58,28 @@ export const findOrCreateCompanyAction = createAction({
throw new Error('Provide a Company ID or a Name to find or create a company.');
}
- const client = intercomClient(context.auth);
+ const existing = companyId
+ ? await findCompanyBy({ auth: context.auth, field: 'company_id', value: companyId })
+ : await findCompanyBy({ auth: context.auth, field: 'name', value: name ?? '' });
- const existing = await client.companies.retrieve({
- company_id: companyId || undefined,
- name: companyId ? undefined : name || undefined,
- per_page: 1,
- });
-
- if (existing.data.length > 0) {
- return { created: false, company: existing.data[0] };
+ if (existing !== undefined) {
+ return { created: false, company: existing };
}
- const company = await client.companies.createOrUpdate({
- company_id: companyId,
- name,
- plan,
- size,
- website,
- industry,
- custom_attributes: customAttributes,
+ const company = await intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['companies'],
+ body: {
+ company_id: companyId || undefined,
+ name: name || undefined,
+ plan,
+ size,
+ website,
+ industry,
+ custom_attributes: customAttributes,
+ },
+ operation: 'create the company',
});
return { created: true, company };
diff --git a/packages/pieces/community/intercom/src/lib/actions/find-or-create-lead.ts b/packages/pieces/community/intercom/src/lib/actions/find-or-create-lead.ts
index 9f982cf5143..b42f156364b 100644
--- a/packages/pieces/community/intercom/src/lib/actions/find-or-create-lead.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/find-or-create-lead.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
+import { findOrCreateLeadOutputSchema } from '../output-schemas';
export const findOrCreateLeadAction = createAction({
auth: intercomAuth,
@@ -11,7 +12,7 @@ export const findOrCreateLeadAction = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Resolve a lead (role=lead prospect) to a single record: searches by email, Intercom ID, or external User ID and returns the match, or creates a new lead when none exists. Returns the lead plus a "created" flag. For signed-up users use Find User / Create User instead.',
+ 'Resolve a lead (role=lead prospect) to a single record: searches by email, Intercom ID, or external User ID and returns the match, or creates a new lead when none exists. Returns the lead plus a "created" flag. For signed-up users use Get Contact or Create User instead.',
idempotent: true,
},
props: {
@@ -45,10 +46,11 @@ export const findOrCreateLeadAction = createAction({
required: false,
}),
},
+ outputSchema: findOrCreateLeadOutputSchema,
async run(context) {
const { searchField, searchValue, name, phone, customAttributes } = context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const existing = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/actions/find-user.ts b/packages/pieces/community/intercom/src/lib/actions/find-user.ts
index 5f2346ecc43..48ba79638d3 100644
--- a/packages/pieces/community/intercom/src/lib/actions/find-user.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/find-user.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomClient } from '../common';
+import { findUserOutputSchema } from '../output-schemas';
export const findUserAction = createAction({
auth: intercomAuth,
@@ -8,7 +9,7 @@ export const findUserAction = createAction({
classification: 'READ',
displayName: 'Find User',
description: 'Finds an existing user.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Look up a single existing user (signed-up contact) by email, Intercom ID, or external user ID. Read-only and repeatable; returns the first match plus a found flag and only matches role=user. To find a prospect instead, use Find Lead.', idempotent: true },
props: {
searchField: Property.StaticDropdown({
@@ -28,10 +29,11 @@ export const findUserAction = createAction({
required: true,
}),
},
+ outputSchema: findUserOutputSchema,
async run(context) {
const { searchField, searchValue } = context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const contactResponse = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/actions/get-company.ts b/packages/pieces/community/intercom/src/lib/actions/get-company.ts
new file mode 100644
index 00000000000..84fe7069fbb
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/get-company.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { findCompanyBy, requireText } from '../common/lookups';
+import { companyOutputSchema } from '../output-schemas';
+
+export const getCompanyAction = createAction({
+ auth: intercomAuth,
+ name: 'get_company',
+ classification: 'READ',
+ displayName: 'Get Company',
+ description: 'Gets one company by its Intercom ID or by your own Company ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets one company by its Intercom ID or by your own Company ID, and fails with a clear error when none matches. Use Find Company to look up by name without failing. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ lookupBy: Property.StaticDropdown({
+ displayName: 'Look Up By',
+ required: true,
+ defaultValue: 'id',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Intercom Company ID', value: 'id' },
+ { label: 'Your Company ID', value: 'company_id' },
+ ],
+ },
+ }),
+ value: Property.ShortText({ displayName: 'Value', required: true }),
+ },
+ outputSchema: companyOutputSchema,
+ async run(context) {
+ const value = requireText({ label: 'Value', value: context.propsValue.value });
+ if (context.propsValue.lookupBy === 'company_id') {
+ const company = await findCompanyBy({ auth: context.auth, field: 'company_id', value });
+ if (company === undefined) {
+ throw new Error(`No Intercom company has the Company ID ${value}.`);
+ }
+ return company;
+ }
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['companies', value],
+ operation: 'get the company',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/get-contact.ts b/packages/pieces/community/intercom/src/lib/actions/get-contact.ts
new file mode 100644
index 00000000000..c18f675bb49
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/get-contact.ts
@@ -0,0 +1,47 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { resolveContact } from '../common/lookups';
+import { contactOutputSchema } from '../output-schemas';
+
+export const getContactAction = createAction({
+ auth: intercomAuth,
+ name: 'get_contact',
+ classification: 'READ',
+ displayName: 'Get Contact',
+ description: 'Gets one contact (user or lead) by ID, email or external ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets one contact (user or lead) by Intercom ID, email or external ID. Fails when no contact matches, or when several contacts share the email (then use Search Contacts). Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ lookupBy: Property.StaticDropdown({
+ displayName: 'Look Up By',
+ required: true,
+ defaultValue: 'id',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Contact ID', value: 'id' },
+ { label: 'Email', value: 'email' },
+ { label: 'External ID', value: 'external_id' },
+ ],
+ },
+ }),
+ value: Property.ShortText({
+ displayName: 'Value',
+ description: 'The contact ID, email or external ID.',
+ required: true,
+ }),
+ },
+ outputSchema: contactOutputSchema,
+ async run(context) {
+ const lookupBy = context.propsValue.lookupBy;
+ return resolveContact({
+ auth: context.auth,
+ lookupBy: lookupBy === 'email' ? 'email' : lookupBy === 'external_id' ? 'external_id' : 'id',
+ value: context.propsValue.value,
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/get-conversation.ts b/packages/pieces/community/intercom/src/lib/actions/get-conversation.ts
index 122f4936078..4401d0e9138 100644
--- a/packages/pieces/community/intercom/src/lib/actions/get-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/get-conversation.ts
@@ -2,6 +2,7 @@ import { intercomAuth } from '../auth';
import { createAction } from '@activepieces/pieces-framework';
import { conversationIdProp } from '../common/props';
import { intercomClient } from '../common';
+import { conversationWithPartsOutputSchema } from '../output-schemas';
export const getConversationAction = createAction({
auth: intercomAuth,
@@ -9,14 +10,15 @@ export const getConversationAction = createAction({
classification: 'READ',
displayName: 'Retrieve a Conversation',
description: 'Retrieves a specific conversation by ID.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Fetch a single Intercom conversation by its conversation ID. Use when you already have the exact ID and need its full details (messages, parts, assignee, state); read-only and repeatable. To locate a conversation by subject, body, author, assignee, or tag instead, use Find Conversation.', idempotent: true },
props: {
conversationId: conversationIdProp('Conversation ID', true),
},
+ outputSchema: conversationWithPartsOutputSchema,
async run(context) {
const { conversationId } = context.propsValue;
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
if (!conversationId) {
throw new Error('Conversation ID is required');
diff --git a/packages/pieces/community/intercom/src/lib/actions/get-ticket.ts b/packages/pieces/community/intercom/src/lib/actions/get-ticket.ts
new file mode 100644
index 00000000000..3b574e0d221
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/get-ticket.ts
@@ -0,0 +1,37 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { requireText } from '../common/lookups';
+import { ticketOutputSchema } from '../output-schemas';
+
+export const getTicketAction = createAction({
+ auth: intercomAuth,
+ name: 'get_ticket',
+ classification: 'READ',
+ displayName: 'Get Ticket',
+ description: 'Gets one ticket by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets one ticket by its API ID (the ticket "id", not the inbox ticket number shown to teammates). Use Search Tickets when you only know the contact, type or title. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ ticketId: Property.ShortText({
+ displayName: 'Ticket ID',
+ description: 'The ticket "id" from Intercom, not the inbox ticket number.',
+ required: true,
+ }),
+ },
+ outputSchema: ticketOutputSchema,
+ async run(context) {
+ const ticketId = requireText({ label: 'Ticket ID', value: context.propsValue.ticketId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['tickets', ticketId],
+ operation: 'get the ticket',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-admins.ts b/packages/pieces/community/intercom/src/lib/actions/list-admins.ts
new file mode 100644
index 00000000000..60268f003c8
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/list-admins.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { getCurrentAdmin } from '../common/client';
+import { listAdminsOutputSchema } from '../output-schemas';
+
+export const listAdminsAction = createAction({
+ auth: intercomAuth,
+ name: 'list_admins',
+ classification: 'SEARCH',
+ displayName: 'List Admins',
+ description: 'Lists the admins (teammates) in the workspace.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the admins (teammates) with ID, name, email, away status and team IDs, plus the ID of the admin who owns this connection. Use to find an admin ID for replies, notes or assignments. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: listAdminsOutputSchema,
+ async run(context) {
+ const [list, me] = await Promise.all([
+ intercomRequest<{ admins?: Array<Record<string, unknown>> }>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['admins'],
+ operation: 'list admins',
+ }),
+ getCurrentAdmin(context.auth),
+ ]);
+ return {
+ items: (list.admins ?? []).map((admin) => ({
+ id: admin['id'],
+ name: admin['name'] ?? null,
+ email: admin['email'] ?? null,
+ job_title: admin['job_title'] ?? null,
+ away_mode_enabled: admin['away_mode_enabled'] === true,
+ has_inbox_seat: admin['has_inbox_seat'] === true,
+ team_ids: Array.isArray(admin['team_ids']) ? admin['team_ids'] : [],
+ })),
+ current_admin_id: String(me.id),
+ };
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-all-tags.ts b/packages/pieces/community/intercom/src/lib/actions/list-all-tags.ts
index 779b2737600..0c9d8a0ede1 100644
--- a/packages/pieces/community/intercom/src/lib/actions/list-all-tags.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/list-all-tags.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createAction } from "@activepieces/pieces-framework";
import { intercomClient } from "../common";
+import { listTagsOutputSchema } from '../output-schemas';
export const listAllTagsAction = createAction({
auth:intercomAuth,
@@ -11,8 +12,9 @@ export const listAllTagsAction = createAction({
audience: 'both',
aiMetadata: { description: 'List all tags defined in the Intercom workspace. Takes no input; read-only and repeatable. Use to discover tag IDs before tagging or untagging a conversation, contact, or company.', idempotent: true },
props:{},
+ outputSchema: listTagsOutputSchema,
async run(context){
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.tags.list();
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-companies.ts b/packages/pieces/community/intercom/src/lib/actions/list-companies.ts
new file mode 100644
index 00000000000..09939420187
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/list-companies.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { listCompanies } from '../common/lookups';
+import { listCompaniesOutputSchema } from '../output-schemas';
+
+export const listCompaniesAction = createAction({
+ auth: intercomAuth,
+ name: 'list_companies',
+ classification: 'SEARCH',
+ displayName: 'List Companies',
+ description: 'Lists companies, optionally only those with a tag or in a segment.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists companies one page at a time, optionally only those with a tag or in a segment; pass next_page to continue. Intercom only lists companies that have at least one contact. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ tagId: Property.ShortText({ displayName: 'Tag ID', required: false }),
+ segmentId: Property.ShortText({ displayName: 'Segment ID', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Starts at 1.', required: false }),
+ perPage: Property.Number({ displayName: 'Results Per Page', description: '1 to 150. Default 50.', required: false }),
+ },
+ outputSchema: listCompaniesOutputSchema,
+ async run(context) {
+ const tagId = context.propsValue.tagId?.trim() || undefined;
+ const segmentId = context.propsValue.segmentId?.trim() || undefined;
+ if (tagId && segmentId) {
+ throw new Error('Filter by Tag ID or Segment ID, not both.');
+ }
+ const page = context.propsValue.page ?? 1;
+ if (!Number.isInteger(page) || page < 1) {
+ throw new Error('Page must be a whole number of 1 or more.');
+ }
+ return listCompanies({ auth: context.auth, tagId, segmentId, page, perPage: context.propsValue.perPage });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-contact-notes.ts b/packages/pieces/community/intercom/src/lib/actions/list-contact-notes.ts
new file mode 100644
index 00000000000..0f9665450ab
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/list-contact-notes.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { clampPerPage, requireText, toPagedList } from '../common/lookups';
+import { listContactNotesOutputSchema } from '../output-schemas';
+
+export const listContactNotesAction = createAction({
+ auth: intercomAuth,
+ name: 'list_contact_notes',
+ classification: 'SEARCH',
+ displayName: 'List Contact Notes',
+ description: 'Lists the internal notes on a contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the internal notes on one contact, newest first, one page at a time; pass next_page to continue. Read-only and safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: true }),
+ page: Property.Number({ displayName: 'Page', description: 'Starts at 1.', required: false }),
+ perPage: Property.Number({ displayName: 'Results Per Page', description: '1 to 150. Default 50.', required: false }),
+ },
+ outputSchema: listContactNotesOutputSchema,
+ async run(context) {
+ const contactId = requireText({ label: 'Contact ID', value: context.propsValue.contactId });
+ const page = context.propsValue.page ?? 1;
+ if (!Number.isInteger(page) || page < 1) {
+ throw new Error('Page must be a whole number of 1 or more.');
+ }
+ const body = await intercomRequest<unknown>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['contacts', contactId, 'notes'],
+ query: { page, per_page: clampPerPage(context.propsValue.perPage) },
+ operation: 'list the contact notes',
+ });
+ return toPagedList({ body, itemsKey: 'data' });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-data-attributes.ts b/packages/pieces/community/intercom/src/lib/actions/list-data-attributes.ts
new file mode 100644
index 00000000000..3b63bbae509
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/list-data-attributes.ts
@@ -0,0 +1,63 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { listDataAttributesOutputSchema } from '../output-schemas';
+
+export const listDataAttributesAction = createAction({
+ auth: intercomAuth,
+ name: 'list_data_attributes',
+ classification: 'SEARCH',
+ displayName: 'List Data Attributes',
+ description: 'Lists the standard and custom attributes for contacts, companies or conversations.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the data attributes (standard and custom) for contacts, companies or conversations, with name, label, data type, options and whether the API can write them. Use to learn custom attribute names before Search Contacts or Update Contact. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ model: Property.StaticDropdown({
+ displayName: 'Object',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Contact', value: 'contact' },
+ { label: 'Company', value: 'company' },
+ { label: 'Conversation', value: 'conversation' },
+ ],
+ },
+ }),
+ includeArchived: Property.Checkbox({
+ displayName: 'Include Archived',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: listDataAttributesOutputSchema,
+ async run(context) {
+ const body = await intercomRequest<{ data?: Array<Record<string, unknown>> }>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['data_attributes'],
+ query: {
+ model: context.propsValue.model || undefined,
+ include_archived: context.propsValue.includeArchived === true ? true : undefined,
+ },
+ operation: 'list data attributes',
+ });
+ return {
+ items: (body.data ?? []).map((attribute) => ({
+ name: attribute['name'],
+ full_name: attribute['full_name'] ?? null,
+ label: attribute['label'] ?? null,
+ data_type: attribute['data_type'] ?? null,
+ model: attribute['model'] ?? null,
+ custom: attribute['custom'] === true,
+ api_writable: attribute['api_writable'] === true,
+ options: Array.isArray(attribute['options']) ? attribute['options'] : [],
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-teams.ts b/packages/pieces/community/intercom/src/lib/actions/list-teams.ts
new file mode 100644
index 00000000000..87dec32d6a8
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/list-teams.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { listTeamsOutputSchema } from '../output-schemas';
+
+export const listTeamsAction = createAction({
+ auth: intercomAuth,
+ name: 'list_teams',
+ classification: 'SEARCH',
+ displayName: 'List Teams',
+ description: 'Lists the teams in the workspace.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the teams with ID, name and member admin IDs. Use to find a team ID before assigning a conversation to a team. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: listTeamsOutputSchema,
+ async run(context) {
+ const body = await intercomRequest<{ teams?: Array<Record<string, unknown>> }>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['teams'],
+ operation: 'list teams',
+ });
+ return {
+ items: (body.teams ?? []).map((team) => ({
+ id: team['id'],
+ name: team['name'] ?? null,
+ admin_ids: Array.isArray(team['admin_ids']) ? team['admin_ids'] : [],
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/list-ticket-types.ts b/packages/pieces/community/intercom/src/lib/actions/list-ticket-types.ts
new file mode 100644
index 00000000000..20c5a8a34a8
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/list-ticket-types.ts
@@ -0,0 +1,62 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { listTicketTypes } from '../common/props';
+import { listTicketTypesOutputSchema } from '../output-schemas';
+
+export const listTicketTypesAction = createAction({
+ auth: intercomAuth,
+ name: 'list_ticket_types',
+ classification: 'SEARCH',
+ displayName: 'List Ticket Types',
+ description: 'Lists ticket types with their attributes and list options.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the ticket types in the workspace with each attribute (name, data type, required to create) and list option IDs. Call before Create Ticket (by Type ID), Update Ticket (by ID) or Convert Conversation to Ticket. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ includeArchived: Property.Checkbox({
+ displayName: 'Include Archived',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: listTicketTypesOutputSchema,
+ async run(context) {
+ const types = await listTicketTypes({ auth: context.auth });
+ const includeArchived = context.propsValue.includeArchived === true;
+ return {
+ items: types
+ .filter((type) => includeArchived || type.archived !== true)
+ .map((type) => ({
+ id: type.id,
+ name: type.name,
+ description: type.description ?? null,
+ category: type.category ?? null,
+ archived: type.archived === true,
+ attributes: (type.ticket_type_attributes?.data ?? [])
+ .filter(isRecord)
+ .filter((attribute) => includeArchived || attribute['archived'] !== true)
+ .map((attribute) => ({
+ name: attribute['name'],
+ data_type: attribute['data_type'],
+ required_to_create: attribute['required_to_create'] === true,
+ visible_to_contacts: attribute['visible_to_contacts'] === true,
+ options: listOptions(attribute['input_options']),
+ })),
+ })),
+ };
+ },
+});
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function listOptions(inputOptions: unknown): Array<{ id: unknown; label: unknown }> {
+ if (!isRecord(inputOptions) || !Array.isArray(inputOptions['list_options'])) {
+ return [];
+ }
+ return inputOptions['list_options'].filter(isRecord).map((option) => ({ id: option['id'], label: option['label'] }));
+}
diff --git a/packages/pieces/community/intercom/src/lib/actions/reply-to-conversation.ts b/packages/pieces/community/intercom/src/lib/actions/reply-to-conversation.ts
index 9819795de96..863495c47ed 100644
--- a/packages/pieces/community/intercom/src/lib/actions/reply-to-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/reply-to-conversation.ts
@@ -2,6 +2,7 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { commonProps, intercomClient } from '../common';
import { conversationIdProp } from '../common/props';
+import { conversationOutputSchema } from '../output-schemas';
export const replyToConversation = createAction({
auth: intercomAuth,
@@ -9,18 +10,19 @@ export const replyToConversation = createAction({
classification: 'WRITE',
displayName: 'Reply to conversation',
description: 'Reply (as an admin) to a conversation with a contact',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Post an admin reply (a customer-visible comment) to an existing conversation. Each call adds a new reply, so it is not idempotent. Use to respond within an ongoing conversation; for an admin-only internal note use Add note to conversation, and to start a brand-new message use Send Message.', idempotent: false },
props: {
from: commonProps.admins({ displayName: 'From (Admin)', required: true }),
conversationId: conversationIdProp('Conversation ID', true),
- body: Property.ShortText({
+ body: Property.LongText({
displayName: 'Message Body',
required: true,
}),
},
+ outputSchema: conversationOutputSchema,
async run(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.reply({
conversation_id: context.propsValue.conversationId!,
diff --git a/packages/pieces/community/intercom/src/lib/actions/reply-to-ticket.ts b/packages/pieces/community/intercom/src/lib/actions/reply-to-ticket.ts
new file mode 100644
index 00000000000..7916792c400
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/reply-to-ticket.ts
@@ -0,0 +1,66 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { resolveAdminId } from '../common/client';
+import { attachmentUrlList, requireText } from '../common/lookups';
+import { ticketReplyOutputSchema } from '../output-schemas';
+
+export const replyToTicketAction = createAction({
+ auth: intercomAuth,
+ name: 'reply_to_ticket',
+ classification: 'WRITE',
+ displayName: 'Reply to Ticket',
+ description: 'Adds an admin reply or an internal note to a ticket.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds an admin reply (customer-visible on shared Customer tickets) or an internal note to a ticket by ticket ID. Tracker and unshared back-office tickets only accept notes. Each call adds another part, so retries duplicate.',
+ idempotent: false,
+ },
+ props: {
+ ticketId: Property.ShortText({
+ displayName: 'Ticket ID',
+ description: 'The ticket "id" from Intercom, not the inbox ticket number.',
+ required: true,
+ }),
+ messageType: Property.StaticDropdown({
+ displayName: 'Reply Type',
+ required: true,
+ defaultValue: 'note',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Internal Note', value: 'note' },
+ { label: 'Reply to Customer', value: 'comment' },
+ ],
+ },
+ }),
+ body: Property.LongText({ displayName: 'Text', required: true }),
+ adminId: Property.ShortText({
+ displayName: 'Admin ID',
+ description: 'Leave empty to reply as the admin who owns this connection.',
+ required: false,
+ }),
+ attachmentUrls: Property.Array({
+ displayName: 'Attachment URLs',
+ description: 'Up to 10 public image URLs to attach.',
+ required: false,
+ }),
+ },
+ outputSchema: ticketReplyOutputSchema,
+ async run(context) {
+ const ticketId = requireText({ label: 'Ticket ID', value: context.propsValue.ticketId });
+ const body = requireText({ label: 'Text', value: context.propsValue.body });
+ const messageType = context.propsValue.messageType === 'comment' ? 'comment' : 'note';
+ const attachmentUrls = attachmentUrlList(context.propsValue.attachmentUrls);
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['tickets', ticketId, 'reply'],
+ body: { message_type: messageType, type: 'admin', admin_id: adminId, body, attachment_urls: attachmentUrls },
+ operation: 'reply to the ticket',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/search-articles.ts b/packages/pieces/community/intercom/src/lib/actions/search-articles.ts
new file mode 100644
index 00000000000..1fe3f3fe13c
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/search-articles.ts
@@ -0,0 +1,69 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { requireText } from '../common/lookups';
+import { searchArticlesOutputSchema } from '../output-schemas';
+
+export const searchArticlesAction = createAction({
+ auth: intercomAuth,
+ name: 'search_articles',
+ classification: 'SEARCH',
+ displayName: 'Search Help Center Articles',
+ description: 'Searches Help Center articles for a phrase.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches Help Center articles for a phrase and returns matching articles with title, description, body, URL and state. Use to find an answer to send a customer. Searches published articles unless another state is chosen. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ phrase: Property.ShortText({ displayName: 'Phrase', required: true }),
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ defaultValue: 'published',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Published', value: 'published' },
+ { label: 'Draft', value: 'draft' },
+ { label: 'All', value: 'all' },
+ ],
+ },
+ }),
+ helpCenterId: Property.ShortText({
+ displayName: 'Help Center ID',
+ description: 'Only needed when the workspace has several Help Centers.',
+ required: false,
+ }),
+ },
+ outputSchema: searchArticlesOutputSchema,
+ async run(context) {
+ const phrase = requireText({ label: 'Phrase', value: context.propsValue.phrase });
+ const body = await intercomRequest<{ total_count?: number; data?: { articles?: Array<Record<string, unknown>> } }>({
+ auth: context.auth,
+ method: HttpMethod.GET,
+ path: ['articles', 'search'],
+ query: {
+ phrase,
+ state: context.propsValue.state || 'published',
+ help_center_id: context.propsValue.helpCenterId?.trim() || undefined,
+ },
+ operation: 'search articles',
+ });
+ const articles = body.data?.articles ?? [];
+ return {
+ items: articles.map((article) => ({
+ id: article['id'],
+ title: article['title'] ?? null,
+ description: article['description'] ?? null,
+ body: article['body'] ?? null,
+ url: article['url'] ?? null,
+ state: article['state'] ?? null,
+ updated_at: article['updated_at'] ?? null,
+ })),
+ total_count: typeof body.total_count === 'number' ? body.total_count : articles.length,
+ };
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/search-contacts.ts b/packages/pieces/community/intercom/src/lib/actions/search-contacts.ts
new file mode 100644
index 00000000000..55bb04fa1fd
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/search-contacts.ts
@@ -0,0 +1,90 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import {
+ buildSearchQuery,
+ dateFilters,
+ SearchQuery,
+ searchRecords,
+} from '../common/lookups';
+import { searchContactsOutputSchema } from '../output-schemas';
+
+export const searchContactsAction = createAction({
+ auth: intercomAuth,
+ name: 'search_contacts',
+ classification: 'SEARCH',
+ displayName: 'Search Contacts',
+ description: 'Finds contacts (users and leads) by email, name, tag, segment, update time or a custom attribute.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Finds contacts (users and leads) by email, name, tag, segment, update time or a custom attribute, one page at a time. Use to get contact IDs before Get Contact, Update Contact or Send Message to Contact; pass next_starting_after to continue. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email Is', required: false }),
+ nameContains: Property.ShortText({ displayName: 'Name Contains', required: false }),
+ role: Property.StaticDropdown({
+ displayName: 'Role',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'User', value: 'user' },
+ { label: 'Lead', value: 'lead' },
+ ],
+ },
+ }),
+ tagId: Property.ShortText({ displayName: 'Tag ID', description: 'From List Tags.', required: false }),
+ segmentId: Property.ShortText({ displayName: 'Segment ID', required: false }),
+ updatedAfter: Property.DateTime({
+ displayName: 'Updated After',
+ description: 'Intercom compares dates by calendar day in your workspace time zone.',
+ required: false,
+ }),
+ updatedBefore: Property.DateTime({ displayName: 'Updated Before', required: false }),
+ customAttribute: Property.ShortText({
+ displayName: 'Custom Attribute Name',
+ description: 'Match contacts whose custom attribute equals Custom Attribute Value.',
+ required: false,
+ }),
+ customValue: Property.ShortText({ displayName: 'Custom Attribute Value', required: false }),
+ advancedQuery: Property.Json({
+ displayName: 'Advanced Query',
+ description: 'Optional Intercom search filter, combined with the fields above using AND.',
+ required: false,
+ }),
+ perPage: Property.Number({
+ displayName: 'Results Per Page',
+ description: '1 to 150. Default 50.',
+ required: false,
+ }),
+ startingAfter: Property.ShortText({
+ displayName: 'Starting After',
+ description: 'The next_starting_after value from the previous page.',
+ required: false,
+ }),
+ },
+ outputSchema: searchContactsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const customAttribute = p.customAttribute?.trim();
+ if (customAttribute && (p.customValue === undefined || p.customValue === '')) {
+ throw new Error('Give a Custom Attribute Value together with the Custom Attribute Name.');
+ }
+ const filters: SearchQuery[] = [
+ ...(p.email?.trim() ? [{ field: 'email', operator: '=', value: p.email.trim() }] : []),
+ ...(p.nameContains?.trim() ? [{ field: 'name', operator: '~', value: p.nameContains.trim() }] : []),
+ ...(p.role ? [{ field: 'role', operator: '=', value: p.role }] : []),
+ ...(p.tagId?.trim() ? [{ field: 'tag_id', operator: '=', value: p.tagId.trim() }] : []),
+ ...(p.segmentId?.trim() ? [{ field: 'segment_id', operator: '=', value: p.segmentId.trim() }] : []),
+ ...dateFilters({ field: 'updated_at', after: p.updatedAfter, before: p.updatedBefore }),
+ ...(customAttribute ? [{ field: `custom_attributes.${customAttribute}`, operator: '=', value: p.customValue }] : []),
+ ];
+ const query = buildSearchQuery({
+ filters,
+ advancedQuery: p.advancedQuery,
+ fallback: { field: 'role', operator: 'IN', value: ['user', 'lead'] },
+ });
+ return searchRecords({ auth: context.auth, resource: 'contacts', query, perPage: p.perPage, startingAfter: p.startingAfter });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/search-conversations.ts b/packages/pieces/community/intercom/src/lib/actions/search-conversations.ts
new file mode 100644
index 00000000000..b73509dee74
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/search-conversations.ts
@@ -0,0 +1,101 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import {
+ buildSearchQuery,
+ dateFilters,
+ SearchQuery,
+ searchRecords,
+} from '../common/lookups';
+import { searchConversationsOutputSchema } from '../output-schemas';
+
+export const searchConversationsAction = createAction({
+ auth: intercomAuth,
+ name: 'search_conversations',
+ classification: 'SEARCH',
+ displayName: 'Search Conversations',
+ description: 'Finds conversations by state, assignee, contact, tag, text or date.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Finds conversations by state, assigned admin or team, contact, tag, author email, words in the first message or subject, and created/updated dates, one page at a time. Returns conversations without their replies; use Get Conversation (by ID) for the messages. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Open', value: 'open' },
+ { label: 'Closed', value: 'closed' },
+ { label: 'Snoozed', value: 'snoozed' },
+ ],
+ },
+ }),
+ adminAssigneeId: Property.ShortText({ displayName: 'Assigned Admin ID', required: false }),
+ teamAssigneeId: Property.ShortText({ displayName: 'Assigned Team ID', required: false }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ tagId: Property.ShortText({ displayName: 'Tag ID', required: false }),
+ authorEmail: Property.ShortText({ displayName: 'Author Email', required: false }),
+ bodyContains: Property.ShortText({
+ displayName: 'First Message Contains',
+ description: 'Intercom matches single words of the first message best.',
+ required: false,
+ }),
+ subjectContains: Property.ShortText({ displayName: 'Subject Contains', required: false }),
+ createdAfter: Property.DateTime({
+ displayName: 'Created After',
+ description: 'Intercom compares dates by calendar day in your workspace time zone.',
+ required: false,
+ }),
+ createdBefore: Property.DateTime({ displayName: 'Created Before', required: false }),
+ updatedAfter: Property.DateTime({ displayName: 'Updated After', required: false }),
+ updatedBefore: Property.DateTime({ displayName: 'Updated Before', required: false }),
+ advancedQuery: Property.Json({
+ displayName: 'Advanced Query',
+ description: 'Optional Intercom search filter, combined with the fields above using AND.',
+ required: false,
+ }),
+ perPage: Property.Number({ displayName: 'Results Per Page', description: '1 to 150. Default 50.', required: false }),
+ startingAfter: Property.ShortText({
+ displayName: 'Starting After',
+ description: 'The next_starting_after value from the previous page.',
+ required: false,
+ }),
+ },
+ outputSchema: searchConversationsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const filters: SearchQuery[] = [
+ ...(p.state ? [{ field: 'state', operator: '=', value: p.state }] : []),
+ ...stringFilter({ field: 'admin_assignee_id', operator: '=', value: p.adminAssigneeId }),
+ ...stringFilter({ field: 'team_assignee_id', operator: '=', value: p.teamAssigneeId }),
+ ...stringFilter({ field: 'contact_ids', operator: '=', value: p.contactId }),
+ ...stringFilter({ field: 'tag_ids', operator: '=', value: p.tagId }),
+ ...stringFilter({ field: 'source.author.email', operator: '=', value: p.authorEmail }),
+ ...stringFilter({ field: 'source.body', operator: '~', value: p.bodyContains }),
+ ...stringFilter({ field: 'source.subject', operator: '~', value: p.subjectContains }),
+ ...dateFilters({ field: 'created_at', after: p.createdAfter, before: p.createdBefore }),
+ ...dateFilters({ field: 'updated_at', after: p.updatedAfter, before: p.updatedBefore }),
+ ];
+ const query = buildSearchQuery({
+ filters,
+ advancedQuery: p.advancedQuery,
+ fallback: { field: 'created_at', operator: '>', value: 0 },
+ });
+ return searchRecords({ auth: context.auth, resource: 'conversations', query, perPage: p.perPage, startingAfter: p.startingAfter });
+ },
+});
+
+function stringFilter({
+ field,
+ operator,
+ value,
+}: {
+ field: string;
+ operator: string;
+ value: string | undefined;
+}): SearchQuery[] {
+ return value?.trim() ? [{ field, operator, value: value.trim() }] : [];
+}
diff --git a/packages/pieces/community/intercom/src/lib/actions/search-tickets.ts b/packages/pieces/community/intercom/src/lib/actions/search-tickets.ts
new file mode 100644
index 00000000000..b5cf95350ae
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/search-tickets.ts
@@ -0,0 +1,96 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import {
+ buildSearchQuery,
+ dateFilters,
+ SearchQuery,
+ searchRecords,
+} from '../common/lookups';
+import { searchTicketsOutputSchema } from '../output-schemas';
+
+export const searchTicketsAction = createAction({
+ auth: intercomAuth,
+ name: 'search_tickets',
+ classification: 'SEARCH',
+ displayName: 'Search Tickets',
+ description: 'Finds tickets by type, state, contact, assignee, title or date.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Finds tickets by ticket type, state, open flag, contact, assigned admin, words in the title and created/updated dates, one page at a time; pass next_starting_after to continue. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ ticketTypeId: Property.ShortText({ displayName: 'Ticket Type ID', required: false }),
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Submitted', value: 'submitted' },
+ { label: 'In Progress', value: 'in_progress' },
+ { label: 'Waiting on Customer', value: 'waiting_on_customer' },
+ { label: 'Resolved', value: 'resolved' },
+ ],
+ },
+ }),
+ open: Property.StaticDropdown({
+ displayName: 'Open or Closed',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Open', value: 'open' },
+ { label: 'Closed', value: 'closed' },
+ ],
+ },
+ }),
+ contactId: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ adminAssigneeId: Property.ShortText({ displayName: 'Assigned Admin ID', required: false }),
+ titleContains: Property.ShortText({ displayName: 'Title Contains', required: false }),
+ createdAfter: Property.DateTime({
+ displayName: 'Created After',
+ description: 'Intercom compares dates by calendar day in your workspace time zone.',
+ required: false,
+ }),
+ createdBefore: Property.DateTime({ displayName: 'Created Before', required: false }),
+ updatedAfter: Property.DateTime({ displayName: 'Updated After', required: false }),
+ updatedBefore: Property.DateTime({ displayName: 'Updated Before', required: false }),
+ advancedQuery: Property.Json({
+ displayName: 'Advanced Query',
+ description: 'Optional Intercom search filter, combined with the fields above using AND.',
+ required: false,
+ }),
+ perPage: Property.Number({ displayName: 'Results Per Page', description: '1 to 150. Default 50.', required: false }),
+ startingAfter: Property.ShortText({
+ displayName: 'Starting After',
+ description: 'The next_starting_after value from the previous page.',
+ required: false,
+ }),
+ },
+ outputSchema: searchTicketsOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const filters: SearchQuery[] = [
+ ...equalsFilter({ field: 'ticket_type_id', value: p.ticketTypeId }),
+ ...(p.state ? [{ field: 'state', operator: '=', value: p.state }] : []),
+ ...(p.open ? [{ field: 'open', operator: '=', value: p.open === 'open' }] : []),
+ ...equalsFilter({ field: 'contact_ids', value: p.contactId }),
+ ...equalsFilter({ field: 'admin_assignee_id', value: p.adminAssigneeId }),
+ ...(p.titleContains?.trim() ? [{ field: 'title', operator: '~', value: p.titleContains.trim() }] : []),
+ ...dateFilters({ field: 'created_at', after: p.createdAfter, before: p.createdBefore }),
+ ...dateFilters({ field: 'updated_at', after: p.updatedAfter, before: p.updatedBefore }),
+ ];
+ const query = buildSearchQuery({
+ filters,
+ advancedQuery: p.advancedQuery,
+ fallback: { field: 'created_at', operator: '>', value: 0 },
+ });
+ return searchRecords({ auth: context.auth, resource: 'tickets', query, perPage: p.perPage, startingAfter: p.startingAfter });
+ },
+});
+
+function equalsFilter({ field, value }: { field: string; value: string | undefined }): SearchQuery[] {
+ return value?.trim() ? [{ field, operator: '=', value: value.trim() }] : [];
+}
diff --git a/packages/pieces/community/intercom/src/lib/actions/send-message.action.ts b/packages/pieces/community/intercom/src/lib/actions/send-message.action.ts
index 8fdd6939a69..fff87a92354 100644
--- a/packages/pieces/community/intercom/src/lib/actions/send-message.action.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/send-message.action.ts
@@ -1,11 +1,12 @@
import { createAction, DynamicPropsValue, Property } from '@activepieces/pieces-framework';
import { commonProps, intercomClient } from '../common';
import { intercomAuth } from '../auth';
+import { messageOutputSchema } from '../output-schemas';
export const sendMessageAction = createAction({
auth: intercomAuth,
description: 'Send a message to a contact (only allowed by admins)',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Send a new outbound message from an admin to a contact, as either an email (with subject and template) or an in-app chat message. Each call sends a new message and may open a conversation, so it is not idempotent. Use to initiate contact; to respond within an existing conversation use Reply to conversation.', idempotent: false },
displayName: 'Send Message',
name: 'send_message',
@@ -67,8 +68,9 @@ export const sendMessageAction = createAction({
defaultValue: false,
}),
},
+ outputSchema: messageOutputSchema,
run: async (context) => {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const user = await client.contacts.find({ contact_id: context.propsValue.to });
const response = await client.messages.create({
diff --git a/packages/pieces/community/intercom/src/lib/actions/set-conversation-state.ts b/packages/pieces/community/intercom/src/lib/actions/set-conversation-state.ts
new file mode 100644
index 00000000000..ad7b2f75dc1
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/set-conversation-state.ts
@@ -0,0 +1,84 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { resolveAdminId } from '../common/client';
+import { requireText, toUnixSeconds } from '../common/lookups';
+import { conversationOutputSchema } from '../output-schemas';
+
+export const setConversationStateAction = createAction({
+ auth: intercomAuth,
+ name: 'set_conversation_state',
+ classification: 'WRITE',
+ displayName: 'Close, Reopen or Snooze Conversation',
+ description: 'Closes, reopens or snoozes a conversation.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Closes, reopens or snoozes a conversation until a future time, by conversation ID. A closing message, if given, is shown to the customer and is posted again on every call, so the action is not marked idempotent; without one, setting the same state again leaves the same state.',
+ idempotent: false,
+ },
+ props: {
+ conversationId: Property.ShortText({ displayName: 'Conversation ID', required: true }),
+ state: Property.StaticDropdown({
+ displayName: 'New State',
+ required: true,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Close', value: 'close' },
+ { label: 'Reopen', value: 'open' },
+ { label: 'Snooze', value: 'snoozed' },
+ ],
+ },
+ }),
+ snoozedUntil: Property.DateTime({
+ displayName: 'Snooze Until',
+ description: 'Required for Snooze; must be in the future.',
+ required: false,
+ }),
+ closingMessage: Property.LongText({
+ displayName: 'Closing Message',
+ description: 'Optional, Close only. The customer sees this message.',
+ required: false,
+ }),
+ adminId: Property.ShortText({
+ displayName: 'Acting Admin ID',
+ description: 'Leave empty to act as the admin who owns this connection.',
+ required: false,
+ }),
+ },
+ outputSchema: conversationOutputSchema,
+ async run(context) {
+ const conversationId = requireText({ label: 'Conversation ID', value: context.propsValue.conversationId });
+ const { state, snoozedUntil } = context.propsValue;
+ const closingMessage = context.propsValue.closingMessage?.trim() || undefined;
+ if (state !== 'close' && state !== 'open' && state !== 'snoozed') {
+ throw new Error('New State must be close, open or snoozed.');
+ }
+ if (closingMessage && state !== 'close') {
+ throw new Error('A closing message can only be sent when closing the conversation.');
+ }
+ const snoozeUntil =
+ state === 'snoozed'
+ ? toUnixSeconds({ label: 'Snooze Until', value: requireText({ label: 'Snooze Until', value: snoozedUntil }) })
+ : undefined;
+ if (snoozeUntil !== undefined && snoozeUntil <= Math.floor(Date.now() / 1000)) {
+ throw new Error('Snooze Until must be in the future.');
+ }
+ const adminId = await resolveAdminId({ auth: context.auth, adminId: context.propsValue.adminId });
+ const body =
+ state === 'close'
+ ? { message_type: 'close', type: 'admin', admin_id: adminId, body: closingMessage }
+ : state === 'open'
+ ? { message_type: 'open', admin_id: adminId }
+ : { message_type: 'snoozed', admin_id: adminId, snoozed_until: snoozeUntil };
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.POST,
+ path: ['conversations', conversationId, 'parts'],
+ body,
+ operation: 'change the conversation state',
+ });
+ },
+});
diff --git a/packages/pieces/community/intercom/src/lib/actions/update-contact.ts b/packages/pieces/community/intercom/src/lib/actions/update-contact.ts
new file mode 100644
index 00000000000..fff3262940d
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/actions/update-contact.ts
@@ -0,0 +1,112 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { intercomAuth } from '../auth';
+import { intercomRequest } from '../common';
+import { requireText } from '../common/lookups';
+import { contactOutputSchema } from '../output-schemas';
+
+export const updateContactAction = createAction({
+ auth: intercomAuth,
+ name: 'update_contact',
+ classification: 'WRITE',
+ displayName: 'Update Contact',
+ description: "Updates a contact's role, email, name, phone, external ID, owner, subscription or custom attributes.",
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates one contact by Intercom ID: role, email, name, phone, external ID, owner, email subscription or custom attributes. Omitted fields stay as they are; list a field under Clear Fields to blank it. Setting the same values again changes nothing, so it is safe to retry.',
+ idempotent: true,
+ },
+ props: {
+ contactId: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Intercom contact ID (see Search Contacts or Get Contact).',
+ required: true,
+ }),
+ role: Property.StaticDropdown({
+ displayName: 'Role',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'User', value: 'user' },
+ { label: 'Lead', value: 'lead' },
+ ],
+ },
+ }),
+ email: Property.ShortText({ displayName: 'Email', required: false }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ phone: Property.ShortText({ displayName: 'Phone', required: false }),
+ externalId: Property.ShortText({ displayName: 'External ID', required: false }),
+ ownerId: Property.ShortText({ displayName: 'Owner Admin ID', required: false }),
+ unsubscribed: Property.StaticDropdown({
+ displayName: 'Email Subscription',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Subscribed', value: 'subscribed' },
+ { label: 'Unsubscribed', value: 'unsubscribed' },
+ ],
+ },
+ }),
+ customAttributes: Property.Object({
+ displayName: 'Custom Attributes',
+ description: 'Custom attributes by name. Only the ones you list change.',
+ required: false,
+ }),
+ clearFields: Property.StaticMultiSelectDropdown({
+ displayName: 'Clear Fields',
+ description: 'Fields to blank on the contact.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Name', value: 'name' },
+ { label: 'Phone', value: 'phone' },
+ { label: 'External ID', value: 'external_id' },
+ { label: 'Owner', value: 'owner_id' },
+ ],
+ },
+ }),
+ },
+ outputSchema: contactOutputSchema,
+ async run(context) {
+ const p = context.propsValue;
+ const contactId = requireText({ label: 'Contact ID', value: p.contactId });
+ const clear = new Set(p.clearFields ?? []);
+ const set: Record<string, unknown> = {
+ ...(p.role ? { role: p.role } : {}),
+ ...(p.email?.trim() ? { email: p.email.trim() } : {}),
+ ...(p.name?.trim() ? { name: p.name.trim() } : {}),
+ ...(p.phone?.trim() ? { phone: p.phone.trim() } : {}),
+ ...(p.externalId?.trim() ? { external_id: p.externalId.trim() } : {}),
+ ...(p.ownerId?.trim() ? { owner_id: toOwnerId(p.ownerId.trim()) } : {}),
+ ...(p.unsubscribed ? { unsubscribed_from_emails: p.unsubscribed === 'unsubscribed' } : {}),
+ ...(p.customAttributes && Object.keys(p.customAttributes).length > 0 ? { custom_attributes: p.customAttributes } : {}),
+ };
+ const conflicts = [...clear].filter((field) => field in set);
+ if (conflicts.length > 0) {
+ throw new Error(`Do not set and clear the same field: ${conflicts.join(', ')}.`);
+ }
+ const body = { ...set, ...Object.fromEntries([...clear].map((field) => [field, null])) };
+ if (Object.keys(body).length === 0) {
+ throw new Error('Nothing to update. Set or clear at least one field.');
+ }
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.PUT,
+ path: ['contacts', contactId],
+ body,
+ operation: 'update the contact',
+ });
+ },
+});
+
+function toOwnerId(value: string): number {
+ const numeric = Number(value);
+ if (!Number.isInteger(numeric) || numeric < 0) {
+ throw new Error('Owner Admin ID must be a numeric admin ID.');
+ }
+ return numeric;
+}
diff --git a/packages/pieces/community/intercom/src/lib/actions/update-ticket.ts b/packages/pieces/community/intercom/src/lib/actions/update-ticket.ts
index afad3a31b5c..5dc9e693741 100644
--- a/packages/pieces/community/intercom/src/lib/actions/update-ticket.ts
+++ b/packages/pieces/community/intercom/src/lib/actions/update-ticket.ts
@@ -1,10 +1,12 @@
import { intercomAuth } from '../auth';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { commonProps, intercomClient } from '../common';
+import { commonProps, intercomRequest } from '../common';
+import { resolveAdminId } from '../common/client';
import { ticketIdProp, ticketPropertiesProp, ticketTypeIdProp } from '../common/props';
-import { UpdateTicketRequest } from 'intercom-client/api';
-
+import { HttpMethod } from '@activepieces/pieces-common';
import dayjs from 'dayjs';
+import { getTicketTypeAttributes, toTicketAttributes } from '../common/ticket-attributes';
+import { ticketOutputSchema } from '../output-schemas';
export const updateTicketAction = createAction({
auth: intercomAuth,
@@ -12,7 +14,7 @@ export const updateTicketAction = createAction({
classification: 'WRITE',
displayName: 'Update Ticket',
description: 'Updates an existing ticket.',
- audience: 'both',
+ audience: 'human',
aiMetadata: { description: 'Modify an existing ticket by ID: change its open flag, state (in progress / waiting on customer / resolved), snooze time, assigned admin, and ticket-type attributes. Updating with the same values converges on the same result, so it is effectively idempotent. To create a new ticket instead, use Create Ticket.', idempotent: true },
props: {
ticketTypeId: ticketTypeIdProp('Ticket Type', true),
@@ -49,6 +51,7 @@ export const updateTicketAction = createAction({
}),
assignedAdminId: commonProps.admins({ displayName: 'Assigned Admin', required: false }),
},
+ outputSchema: ticketOutputSchema,
async run(context) {
const { ticketTypeId, ticketId, isOpen, state, snoozedTill, assignedAdminId } =
context.propsValue;
@@ -62,42 +65,30 @@ export const updateTicketAction = createAction({
throw new Error('Ticket ID is required');
}
- const client = intercomClient(context.auth);
-
- const request: UpdateTicketRequest = {
- ticket_id: ticketId,
- open: isOpen,
- state: state as 'in_progress' | 'waiting_on_customer' | 'resolved' | undefined,
- };
-
- if (snoozedTill) {
- request.snoozed_until = dayjs(snoozedTill).unix();
- }
- if (assignedAdminId) {
- const admin = await client.admins.identify();
- request.assignment = {
- assignee_id: assignedAdminId,
- admin_id: admin.id,
- };
- }
+ const assignment = assignedAdminId
+ ? { assignee_id: assignedAdminId, admin_id: await resolveAdminId({ auth: context.auth, adminId: undefined }) }
+ : undefined;
- if (Object.keys(ticketProperties).length > 0) {
- const formattedProperties: Record<string, any> = {};
- for (const key in ticketProperties) {
- const value = ticketProperties[key];
+ const ticketAttributes =
+ Object.keys(ticketProperties).length > 0
+ ? toTicketAttributes({
+ attributes: await getTicketTypeAttributes({ auth: context.auth, ticketTypeId }),
+ values: ticketProperties,
+ })
+ : undefined;
- // Check if value is a valid date string and convert it to a timestamp
- if (typeof value === 'string' && dayjs(value).isValid()) {
- formattedProperties[key] = dayjs(value).unix(); // Convert to timestamp
- } else {
- formattedProperties[key] = value;
- }
- }
- request.ticket_attributes = formattedProperties;
- }
-
- const response = await client.tickets.update(request);
-
- return response;
+ return intercomRequest<Record<string, unknown>>({
+ auth: context.auth,
+ method: HttpMethod.PUT,
+ path: ['tickets', ticketId],
+ body: {
+ open: isOpen,
+ state: state || undefined,
+ snoozed_until: snoozedTill ? dayjs(snoozedTill).unix() : undefined,
+ assignment,
+ ticket_attributes: ticketAttributes,
+ },
+ operation: 'update the ticket',
+ });
},
});
diff --git a/packages/pieces/community/intercom/src/lib/auth.ts b/packages/pieces/community/intercom/src/lib/auth.ts
index d868b1dd6da..d33eec7c7be 100644
--- a/packages/pieces/community/intercom/src/lib/auth.ts
+++ b/packages/pieces/community/intercom/src/lib/auth.ts
@@ -1,9 +1,6 @@
import { PieceAuth, Property } from '@activepieces/pieces-framework';
-import {
- AuthenticationType,
- httpClient,
- HttpMethod,
-} from '@activepieces/pieces-common';
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { getIntercomBaseUrl, INTERCOM_API_VERSION, isRecord, verifiedTlsDispatcher } from './common/client';
const regionProp = Property.StaticDropdown({
displayName: 'Region',
@@ -53,17 +50,16 @@ const intercomCustomAuth = PieceAuth.CustomAuth({
},
validate: async ({ auth }) => {
try {
- await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `https://api.${auth.region}.io/me`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: auth.accessToken,
- },
- });
+ await sendMeRequest({ token: auth.accessToken, region: auth.region, timeout: 15000 });
return { valid: true };
} catch (e) {
- return { valid: false, error: (e as Error).message };
+ const response = isRecord(e) ? e['response'] : undefined;
+ const status = isRecord(response) ? response['status'] : undefined;
+ if (status === 401 || status === 403) {
+ return { valid: false, error: 'Invalid access token or wrong region. Check both and try again.' };
+ }
+ const detail = typeof status === 'number' ? `Intercom answered with HTTP ${status}.` : e instanceof Error ? e.message : String(e);
+ return { valid: false, error: `Could not validate the connection. ${detail}` };
}
},
getConnectionIdentifier: async ({ auth }) =>
@@ -79,19 +75,39 @@ async function fetchAdminLabel({
token: string;
region: unknown;
}): Promise<string | undefined> {
- const host = typeof region === 'string' && region.length > 0 ? region : 'intercom';
try {
- const response = await httpClient.sendRequest<IntercomAdmin>({
- method: HttpMethod.GET,
- url: `https://api.${host}.io/me`,
- headers: { Authorization: `Bearer ${token}` },
- timeout: 5000,
- });
- const admin = response.body;
+ const admin = await sendMeRequest({ token, region, timeout: 5000 });
return admin.email || admin.name || admin.app?.name || undefined;
} catch {
return undefined;
}
}
+async function sendMeRequest({
+ token,
+ region,
+ timeout,
+}: {
+ token: string;
+ region: unknown;
+ timeout: number;
+}): Promise<IntercomAdmin> {
+ const dispatcher = await verifiedTlsDispatcher();
+ const response = await httpClient.sendRequest<IntercomAdmin>(
+ {
+ method: HttpMethod.GET,
+ url: `${getIntercomBaseUrl(region)}/me`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Intercom-Version': INTERCOM_API_VERSION,
+ Accept: 'application/json',
+ },
+ timeout,
+ followRedirects: false,
+ },
+ { dispatcher },
+ );
+ return response.body;
+}
+
type IntercomAdmin = { email?: string; name?: string; app?: { name?: string } };
diff --git a/packages/pieces/community/intercom/src/lib/common/client.ts b/packages/pieces/community/intercom/src/lib/common/client.ts
new file mode 100644
index 00000000000..e2d3960796c
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/common/client.ts
@@ -0,0 +1,422 @@
+import {
+ getAccessTokenOrThrow,
+ httpClient,
+ HttpMethod,
+ HttpRequest,
+} from '@activepieces/pieces-common';
+import { AppConnectionType, AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
+import type { FetchFunction, Fetcher } from 'intercom-client/core';
+import type { intercomAuth } from '../auth';
+
+const REGION_BASE_URLS: Record<string, string> = {
+ intercom: 'https://api.intercom.io',
+ 'eu.intercom': 'https://api.eu.intercom.io',
+ 'au.intercom': 'https://api.au.intercom.io',
+};
+
+const REQUEST_TIMEOUT_MS = 30_000;
+const MAX_RETRIES = 2;
+const MAX_ERROR_TEXT = 500;
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function getIntercomBaseUrl(region: unknown): string {
+ if (region === undefined || region === null || region === '') {
+ return REGION_BASE_URLS['intercom'];
+ }
+ if (typeof region === 'string' && Object.prototype.hasOwnProperty.call(REGION_BASE_URLS, region)) {
+ return REGION_BASE_URLS[region];
+ }
+ throw new Error('Unsupported Intercom region. Reconnect Intercom and pick US, EU or AU.');
+}
+
+export function getIntercomToken(auth: IntercomAuthValue): string {
+ if (auth.type === AppConnectionType.CUSTOM_AUTH) {
+ return auth.props.accessToken;
+ }
+ return getAccessTokenOrThrow(auth);
+}
+
+export function getIntercomRegion(auth: IntercomAuthValue): string {
+ if (auth.type === AppConnectionType.CUSTOM_AUTH) {
+ return auth.props.region;
+ }
+ const region = auth.props?.['region'];
+ return typeof region === 'string' ? region : 'intercom';
+}
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export function verifiedTlsDispatcher(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(
+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }),
+ );
+ return verifiedTlsAgent;
+}
+
+export class IntercomApiError extends Error {
+ readonly status: number;
+ readonly code: string | undefined;
+ readonly responseBody: unknown;
+
+ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {
+ super(`Intercom ${operation} failed (${status}): ${describeError({ status, responseBody })}`);
+ this.name = 'IntercomApiError';
+ this.status = status;
+ this.code = errorCode(responseBody);
+ this.responseBody = responseBody;
+ }
+}
+
+export function isIntercomNotFound({ error, codes }: { error: unknown; codes: string[] }): boolean {
+ return (
+ error instanceof IntercomApiError &&
+ error.status === 404 &&
+ (error.code === undefined || codes.includes(error.code))
+ );
+}
+
+export async function intercomRequest<T>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+ operation,
+}: {
+ auth: IntercomAuthValue;
+ method: HttpMethod;
+ path: string[];
+ query?: Record<string, string | number | boolean | undefined>;
+ body?: unknown;
+ operation: string;
+}): Promise<T> {
+ const url = `${getIntercomBaseUrl(getIntercomRegion(auth))}/${encodePath(path)}`;
+ const response = await sendIntercomHttp<T>({
+ method,
+ url,
+ headers: {
+ Authorization: `Bearer ${getIntercomToken(auth)}`,
+ 'Intercom-Version': INTERCOM_API_VERSION,
+ Accept: 'application/json',
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
+ },
+ queryParams: toQueryParams(query),
+ body,
+ });
+ if (!response.ok) {
+ throw new IntercomApiError({ operation, status: response.status, responseBody: response.body });
+ }
+ return response.body;
+}
+
+export async function getCurrentAdmin(auth: IntercomAuthValue): Promise<IntercomMe> {
+ return intercomRequest<IntercomMe>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['me'],
+ operation: 'get the current admin',
+ });
+}
+
+export async function resolveAdminId({
+ auth,
+ adminId,
+}: {
+ auth: IntercomAuthValue;
+ adminId: string | undefined;
+}): Promise<string> {
+ const trimmed = adminId?.trim();
+ if (trimmed) {
+ return trimmed;
+ }
+ const me = await getCurrentAdmin(auth);
+ return String(me.id);
+}
+
+export function encodePath(segments: string[]): string {
+ return segments
+ .map((segment) => {
+ const value = typeof segment === 'string' ? segment.trim() : '';
+ if (value === '' || value === '.' || value === '..') {
+ throw new Error('An Intercom ID is empty or invalid. Pass the ID exactly as Intercom returns it.');
+ }
+ return encodeURIComponent(value);
+ })
+ .join('/');
+}
+
+export async function collectCapped<T>({
+ max,
+ fetchPage,
+}: {
+ max: number;
+ fetchPage: (cursor: string | undefined) => Promise<{ items: T[]; next: string | undefined }>;
+}): Promise<{ items: T[]; truncated: boolean }> {
+ let collected: T[] = [];
+ let cursor: string | undefined = undefined;
+ for (;;) {
+ const page = await fetchPage(cursor);
+ collected = collected.concat(page.items);
+ if (collected.length >= max) {
+ return { items: collected.slice(0, max), truncated: collected.length > max || page.next !== undefined };
+ }
+ if (page.next === undefined || page.items.length === 0) {
+ return { items: collected, truncated: false };
+ }
+ cursor = page.next;
+ }
+}
+
+export function nextStartingAfter(body: unknown): string | undefined {
+ if (typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const pages = isRecord(body) ? body['pages'] : undefined;
+ const next = isRecord(pages) ? pages['next'] : undefined;
+ if (isRecord(next)) {
+ const cursor = next['starting_after'];
+ return typeof cursor === 'string' && cursor.length > 0 ? cursor : undefined;
+ }
+ return undefined;
+}
+
+export function nextPageNumber(body: unknown): number | undefined {
+ if (typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const pages = isRecord(body) ? body['pages'] : undefined;
+ const page = Number(isRecord(pages) ? pages['page'] : undefined);
+ const totalPages = Number(isRecord(pages) ? pages['total_pages'] : undefined);
+ if (!Number.isFinite(page) || !Number.isFinite(totalPages)) {
+ return undefined;
+ }
+ return page < totalPages ? page + 1 : undefined;
+}
+
+async function sendIntercomHttp<T = unknown>({
+ method,
+ url,
+ headers,
+ queryParams,
+ body,
+ timeout,
+}: {
+ method: HttpMethod;
+ url: string;
+ headers: Record<string, string>;
+ queryParams?: Record<string, string>;
+ body?: unknown;
+ timeout?: number;
+}): Promise<IntercomHttpResult<T>> {
+ const dispatcher = await verifiedTlsDispatcher();
+ const request: HttpRequest = {
+ method,
+ url,
+ headers,
+ queryParams,
+ body,
+ timeout: timeout ?? REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ };
+ for (let attempt = 0; ; attempt++) {
+ const canRetry = attempt < MAX_RETRIES;
+ let result: IntercomHttpResult<T>;
+ try {
+ result = await sendOnce<T>({ request, dispatcher });
+ } catch (error) {
+ if (method !== HttpMethod.GET || !canRetry || !isNetworkError(error)) {
+ throw error;
+ }
+ await intercomHttpInternals.sleep(1000);
+ continue;
+ }
+ if (!result.ok && canRetry && shouldRetry({ method, status: result.status })) {
+ await intercomHttpInternals.sleep(Math.min(2000 * 2 ** attempt, 10_000));
+ continue;
+ }
+ return result;
+ }
+}
+
+function isNetworkError(error: unknown): boolean {
+ return error instanceof TypeError && error.message === 'fetch failed';
+}
+
+async function sendOnce<T>({
+ request,
+ dispatcher,
+}: {
+ request: HttpRequest;
+ dispatcher: unknown;
+}): Promise<IntercomHttpResult<T>> {
+ try {
+ const response = await httpClient.sendRequest<T>(request, { dispatcher });
+ if (response.status >= 300) {
+ return { ok: false, status: response.status, body: 'Intercom answered with an unexpected redirect.' };
+ }
+ return { ok: true, status: response.status, body: response.body, headers: response.headers ?? {} };
+ } catch (error) {
+ const status = statusOf(error);
+ if (status === undefined) {
+ throw error;
+ }
+ return { ok: false, status, body: responseBodyOf(error) };
+ }
+}
+
+function toHttpMethod(method: string): HttpMethod {
+ const upper = method.toUpperCase();
+ const match = Object.values(HttpMethod).find((value) => value === upper);
+ if (match === undefined) {
+ throw new Error(`Unsupported HTTP method ${method}`);
+ }
+ return match;
+}
+
+function shouldRetry({ method, status }: { method: HttpMethod; status: number }): boolean {
+ if (status === 429) {
+ return true;
+ }
+ return method === HttpMethod.GET && (status === 502 || status === 503 || status === 504);
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (typeof error !== 'object' || error === null) {
+ return undefined;
+ }
+ const response = Reflect.get(error, 'response');
+ const status = isRecord(response) ? response['status'] : undefined;
+ return typeof status === 'number' ? status : undefined;
+}
+
+function responseBodyOf(error: unknown): unknown {
+ const response = isRecord(error) ? error['response'] : undefined;
+ return isRecord(response) ? response['body'] : undefined;
+}
+
+function toQueryParams(
+ query: Record<string, string | number | boolean | undefined> | undefined,
+): Record<string, string> | undefined {
+ if (!query) {
+ return undefined;
+ }
+ const entries = Object.entries(query).filter(
+ (entry): entry is [string, string | number | boolean] => entry[1] !== undefined && entry[1] !== '',
+ );
+ return entries.length === 0 ? undefined : Object.fromEntries(entries.map(([key, value]) => [key, String(value)]));
+}
+
+function sdkQueryParams(query: Fetcher.Args['queryParameters']): Record<string, string> | undefined {
+ if (!query) {
+ return undefined;
+ }
+ const result: Record<string, string> = {};
+ for (const [key, value] of Object.entries(query)) {
+ if (value === null || value === undefined) {
+ continue;
+ }
+ result[key] = Array.isArray(value)
+ ? value.map((item) => (typeof item === 'object' ? JSON.stringify(item) : String(item))).join(',')
+ : typeof value === 'object'
+ ? JSON.stringify(value)
+ : String(value);
+ }
+ return Object.keys(result).length === 0 ? undefined : result;
+}
+
+function errorCode(responseBody: unknown): string | undefined {
+ const first = firstError(responseBody);
+ return typeof first?.['code'] === 'string' ? first['code'] : undefined;
+}
+
+function firstError(responseBody: unknown): Record<string, unknown> | undefined {
+ if (typeof responseBody !== 'object' || responseBody === null) {
+ return undefined;
+ }
+ const errors = isRecord(responseBody) ? responseBody['errors'] : undefined;
+ if (!Array.isArray(errors) || errors.length === 0) {
+ return undefined;
+ }
+ const first: unknown = errors[0];
+ return isRecord(first) ? first : undefined;
+}
+
+function describeError({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const first = firstError(responseBody);
+ const vendorMessage =
+ typeof first?.['message'] === 'string' && first['message'].length > 0
+ ? first['message']
+ : typeof first?.['code'] === 'string'
+ ? first['code']
+ : typeof responseBody === 'string' && responseBody.length > 0
+ ? responseBody
+ : undefined;
+ const hint =
+ status === 401
+ ? ' Check the access token and the region, then reconnect Intercom.'
+ : status === 403 && errorCode(responseBody) !== 'action_forbidden'
+ ? ' The Intercom app behind this connection lacks the permission for this action; add it in the Developer Hub and reconnect.'
+ : '';
+ const text = vendorMessage ?? 'No error details returned.';
+ return `${text.length > MAX_ERROR_TEXT ? `${text.slice(0, MAX_ERROR_TEXT)}...` : text}${hint}`;
+}
+
+type IntercomHttpResult<T = unknown> =
+ | { ok: true; status: number; body: T; headers: Record<string, unknown> }
+ | { ok: false; status: number; body: unknown };
+
+export type IntercomMe = {
+ type?: string;
+ id: string | number;
+ name?: string;
+ email?: string;
+ app?: { id_code?: string; name?: string; region?: string };
+};
+
+export const intercomSdkFetcher: FetchFunction = async <R>(args: Fetcher.Args) => {
+ const baseHeaders: Record<string, string> = {};
+ for (const [key, value] of Object.entries(args.headers ?? {})) {
+ if (value !== undefined && value !== null) {
+ baseHeaders[key] = value;
+ }
+ }
+ if (args.body !== undefined && args.contentType) {
+ baseHeaders['Content-Type'] = args.contentType;
+ }
+ try {
+ const response = await sendIntercomHttp<R>({
+ method: toHttpMethod(args.method),
+ url: args.url,
+ headers: baseHeaders,
+ queryParams: sdkQueryParams(args.queryParameters),
+ body: args.body,
+ timeout: args.timeoutMs,
+ });
+ if (response.ok) {
+ return { ok: true as const, body: response.body, headers: response.headers };
+ }
+ return {
+ ok: false as const,
+ error: { reason: 'status-code' as const, statusCode: response.status, body: response.body },
+ };
+ } catch (error) {
+ if (error instanceof Error && error.name === 'AbortError') {
+ return { ok: false as const, error: { reason: 'timeout' as const } };
+ }
+ return {
+ ok: false as const,
+ error: { reason: 'unknown' as const, errorMessage: error instanceof Error ? error.message : String(error) },
+ };
+ }
+};
+
+export const intercomHttpInternals = {
+ sleep: (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
+};
+
+export const INTERCOM_API_VERSION = '2.11';
+
+export type IntercomAuthValue = AppConnectionValueForAuthProperty<typeof intercomAuth>;
diff --git a/packages/pieces/community/intercom/src/lib/common/index.ts b/packages/pieces/community/intercom/src/lib/common/index.ts
index 7e48f162f4b..0e461c05ad9 100644
--- a/packages/pieces/community/intercom/src/lib/common/index.ts
+++ b/packages/pieces/community/intercom/src/lib/common/index.ts
@@ -1,127 +1,56 @@
-import { getAccessTokenOrThrow } from '@activepieces/pieces-common';
-import { IntercomClient } from 'intercom-client';
+import type { IntercomClient } from 'intercom-client';
import {
- AppConnectionValueForAuthProperty,
- Property,
-} from '@activepieces/pieces-framework';
-import { AppConnectionType } from '@activepieces/pieces-framework';
-import { intercomAuth } from '../auth';
-
-export type IntercomAuthValue = AppConnectionValueForAuthProperty<
- typeof intercomAuth
->;
-
-export function getIntercomToken(auth: IntercomAuthValue): string {
- if (auth.type === AppConnectionType.CUSTOM_AUTH) {
- return auth.props.accessToken;
- }
- return getAccessTokenOrThrow(auth);
-}
-
-export function getIntercomRegion(auth: IntercomAuthValue): string {
- if (auth.type === AppConnectionType.CUSTOM_AUTH) {
- return auth.props.region;
- }
- return (auth.props?.['region'] as string) ?? 'intercom';
-}
-
-export const intercomClient = (auth: IntercomAuthValue) => {
- const client = new IntercomClient({
- token: getIntercomToken(auth),
- environment: `https://api.${getIntercomRegion(auth)}.io`,
- });
- return client;
+ getIntercomBaseUrl,
+ getIntercomRegion,
+ getIntercomToken,
+ IntercomAuthValue,
+ intercomSdkFetcher,
+} from './client';
+import { adminDropdown, contactDropdown } from './props';
+
+export {
+ getIntercomBaseUrl,
+ getIntercomRegion,
+ getIntercomToken,
+ intercomRequest,
+ IntercomApiError,
+ INTERCOM_API_VERSION,
+} from './client';
+export type { IntercomAuthValue } from './client';
+
+export const intercomClient = async (auth: IntercomAuthValue): Promise<IntercomClient> => {
+ const { IntercomClient } = await import('intercom-client');
+ return new IntercomClient({
+ token: getIntercomToken(auth),
+ environment: getIntercomBaseUrl(getIntercomRegion(auth)),
+ fetcher: intercomSdkFetcher,
+ });
};
export const commonProps = {
- admins: <R extends boolean>(options: { displayName: string; required: R }) =>
- Property.Dropdown<string, R, typeof intercomAuth>({
- auth: intercomAuth,
- displayName: options.displayName,
- required: options.required,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first',
- };
- }
- const client = intercomClient(auth as IntercomAuthValue);
- const adminsResponse = await client.admins.list();
-
- return {
- options: adminsResponse.admins.map((c) => {
- const res = { value: c.id, label: '' };
- if (c.name) {
- res.label = c.name;
- } else if (c.email) {
- res.label = c.email;
- } else {
- res.label = c.id;
- }
- return res;
- }),
- };
- },
- refreshers: [],
- }),
- contacts: <R extends boolean>(options: {
- displayName: string;
- required: R;
- }) =>
- Property.Dropdown<string, R, typeof intercomAuth>({
- auth: intercomAuth,
- displayName: options.displayName,
- required: options.required,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first',
- };
- }
- const client = intercomClient(auth);
- const contactsResponse = await client.contacts.list({});
-
- return {
- options: contactsResponse.data.map((c) => {
- const res = { value: c.id, label: '' };
- if (c.name) {
- res.label = c.name;
- } else if (c.email) {
- res.label = c.email;
- } else {
- res.label = c.id;
- }
- return res;
- }),
- };
- },
- refreshers: [],
- }),
+ admins: adminDropdown,
+ contacts: contactDropdown,
};
export type Operator =
- | '='
- | '!='
- | 'IN'
- | 'NIN'
- | '<'
- | '>'
- | '~'
- | '!~'
- | '^'
- | '$';
+ | '='
+ | '!='
+ | 'IN'
+ | 'NIN'
+ | '<'
+ | '>'
+ | '~'
+ | '!~'
+ | '^'
+ | '$';
export type TriggerPayload = {
- type: string;
- app_id: string;
- id: string;
- topic: string;
- data: {
- type: string;
- item: Record<string, any>;
- };
+ type: string;
+ app_id: string;
+ id: string;
+ topic: string;
+ data: {
+ type: string;
+ item: Record<string, unknown>;
+ };
};
diff --git a/packages/pieces/community/intercom/src/lib/common/lookups.ts b/packages/pieces/community/intercom/src/lib/common/lookups.ts
new file mode 100644
index 00000000000..4acb0dd8f9e
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/common/lookups.ts
@@ -0,0 +1,566 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import dayjs from 'dayjs';
+import {
+ IntercomApiError,
+ intercomRequest,
+ IntercomAuthValue,
+ isIntercomNotFound,
+ isRecord,
+ nextPageNumber,
+ nextStartingAfter,
+ resolveAdminId,
+} from './client';
+
+export async function findCompanyBy({
+ auth,
+ field,
+ value,
+}: {
+ auth: IntercomAuthValue;
+ field: 'name' | 'company_id';
+ value: string;
+}): Promise<IntercomRecord | undefined> {
+ try {
+ const body = await intercomRequest<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['companies'],
+ query: { [field]: value, per_page: 1 },
+ operation: 'find the company',
+ });
+ return firstCompany(body);
+ } catch (error) {
+ if (isIntercomNotFound({ error, codes: ['company_not_found', 'not_found'] })) {
+ return undefined;
+ }
+ throw error;
+ }
+}
+
+export async function searchContacts({
+ auth,
+ query,
+ perPage,
+ startingAfter,
+}: {
+ auth: IntercomAuthValue;
+ query: SearchQuery;
+ perPage: number;
+ startingAfter?: string;
+}): Promise<SearchPage> {
+ return intercomRequest<SearchPage>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['contacts', 'search'],
+ body: {
+ query,
+ pagination: { per_page: perPage, ...(startingAfter ? { starting_after: startingAfter } : {}) },
+ },
+ operation: 'search contacts',
+ });
+}
+
+export async function resolveContact({
+ auth,
+ lookupBy,
+ value,
+}: {
+ auth: IntercomAuthValue;
+ lookupBy: 'id' | 'email' | 'external_id';
+ value: string;
+}): Promise<IntercomRecord> {
+ const trimmed = value.trim();
+ if (trimmed === '') {
+ throw new Error('Provide the contact ID, email or external ID to look up.');
+ }
+ if (lookupBy === 'id') {
+ return intercomRequest<IntercomRecord>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['contacts', trimmed],
+ operation: 'get the contact',
+ });
+ }
+ const page = await searchContacts({
+ auth,
+ query: { field: lookupBy, operator: '=', value: trimmed },
+ perPage: 2,
+ });
+ const matches = page.data ?? [];
+ if (matches.length === 0) {
+ throw new Error(`No Intercom contact has ${lookupBy === 'email' ? 'the email' : 'the external ID'} ${trimmed}. Use Search Contacts to look it up by other fields.`);
+ }
+ if (matches.length > 1) {
+ throw new Error(
+ `More than one Intercom contact has ${lookupBy === 'email' ? 'the email' : 'the external ID'} ${trimmed}. Use Search Contacts and pass the contact ID instead.`,
+ );
+ }
+ return matches[0];
+}
+
+export async function findTagByName({
+ auth,
+ name,
+}: {
+ auth: IntercomAuthValue;
+ name: string;
+}): Promise<IntercomRecord | undefined> {
+ const body = await intercomRequest<{ data?: IntercomRecord[] }>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['tags'],
+ operation: 'list tags',
+ });
+ const wanted = name.trim().toLowerCase();
+ return (body.data ?? []).find((tag) => String(tag['name'] ?? '').toLowerCase() === wanted);
+}
+
+export async function findOrCreateTag({ auth, name }: { auth: IntercomAuthValue; name: string }): Promise<IntercomRecord> {
+ const existing = await findTagByName({ auth, name });
+ if (existing !== undefined) {
+ return existing;
+ }
+ return intercomRequest<IntercomRecord>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['tags'],
+ body: { name: name.trim() },
+ operation: 'create the tag',
+ });
+}
+
+export function toCursorList({ body, itemsKey }: { body: unknown; itemsKey: string }): CursorList {
+ const record: IntercomRecord = isRecord(body) ? body : {};
+ const rawItems = record[itemsKey];
+ const items = Array.isArray(rawItems) ? rawItems : [];
+ const next = nextStartingAfter(body);
+ const total = Number(record['total_count']);
+ return {
+ items,
+ total_count: Number.isFinite(total) ? total : items.length,
+ has_more: next !== undefined,
+ next_starting_after: next ?? null,
+ };
+}
+
+export function toPagedList({ body, itemsKey }: { body: unknown; itemsKey: string }): PagedList {
+ const record: IntercomRecord = isRecord(body) ? body : {};
+ const rawItems = record[itemsKey];
+ const items = Array.isArray(rawItems) ? rawItems : [];
+ const next = nextPageNumber(body);
+ const total = Number(record['total_count']);
+ return {
+ items,
+ total_count: Number.isFinite(total) ? total : items.length,
+ has_more: next !== undefined,
+ next_page: next ?? null,
+ };
+}
+
+export function buildSearchQuery({
+ filters,
+ advancedQuery,
+ fallback,
+}: {
+ filters: SearchQuery[];
+ advancedQuery: unknown;
+ fallback: SearchQuery;
+}): SearchQuery {
+ const all = advancedQuery === undefined || advancedQuery === null ? filters : [...filters, toAdvancedQuery(advancedQuery)];
+ if (all.length > MAX_FILTERS) {
+ throw new Error(`Intercom allows at most ${MAX_FILTERS} filters in one search; ${all.length} were given.`);
+ }
+ if (all.length === 0) {
+ return fallback;
+ }
+ return all.length === 1 ? all[0] : { operator: 'AND', value: all };
+}
+
+export function dateFilters({
+ field,
+ after,
+ before,
+}: {
+ field: string;
+ after: string | undefined;
+ before: string | undefined;
+}): SearchQuery[] {
+ return [
+ ...(after ? [{ field, operator: '>', value: toUnixSeconds({ label: `${field} after`, value: after }) }] : []),
+ ...(before ? [{ field, operator: '<', value: toUnixSeconds({ label: `${field} before`, value: before }) }] : []),
+ ];
+}
+
+export function toUnixSeconds({ label, value }: { label: string; value: string }): number {
+ const parsed = dayjs(value);
+ if (!parsed.isValid()) {
+ throw new Error(`${label} is not a valid date: ${value}`);
+ }
+ return parsed.unix();
+}
+
+export function clampPerPage(value: number | undefined): number {
+ if (value === undefined || value === null) {
+ return DEFAULT_PER_PAGE;
+ }
+ if (!Number.isInteger(value) || value < 1 || value > MAX_PER_PAGE) {
+ throw new Error(`Results Per Page must be a whole number from 1 to ${MAX_PER_PAGE}.`);
+ }
+ return value;
+}
+
+export function flattenParts(conversationParts: unknown): FlatPart[] {
+ if (!isRecord(conversationParts)) {
+ return [];
+ }
+ const parts = conversationParts['conversation_parts'];
+ if (!Array.isArray(parts)) {
+ return [];
+ }
+ return parts.map((rawPart: unknown) => {
+ const part: Record<string, unknown> = isRecord(rawPart) ? rawPart : {};
+ const rawAuthor = part['author'];
+ const author: Record<string, unknown> = isRecord(rawAuthor) ? rawAuthor : {};
+ return {
+ id: String(part['id'] ?? ''),
+ part_type: typeof part['part_type'] === 'string' ? part['part_type'] : null,
+ author_type: typeof author['type'] === 'string' ? author['type'] : null,
+ author_id: author['id'] === undefined || author['id'] === null ? null : String(author['id']),
+ author_name: typeof author['name'] === 'string' ? author['name'] : null,
+ body: typeof part['body'] === 'string' ? part['body'] : null,
+ created_at: typeof part['created_at'] === 'number' ? part['created_at'] : null,
+ };
+ });
+}
+
+export function attachmentUrlList(value: unknown): string[] | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const list = Array.isArray(value) ? value : [value];
+ const urls = list
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
+ .filter((item) => item.length > 0);
+ if (urls.length === 0) {
+ return undefined;
+ }
+ if (urls.length > MAX_ATTACHMENTS) {
+ throw new Error(`Intercom accepts at most ${MAX_ATTACHMENTS} attachment URLs; ${urls.length} were given.`);
+ }
+ for (const url of urls) {
+ if (!/^https?:\/\/\S+$/i.test(url)) {
+ throw new Error(`Attachment URL must be a public http(s) link: ${url}`);
+ }
+ }
+ return urls;
+}
+
+export function requireText({ label, value }: { label: string; value: string | undefined }): string {
+ const trimmed = value?.trim() ?? '';
+ if (trimmed === '') {
+ throw new Error(`${label} is required.`);
+ }
+ return trimmed;
+}
+
+function toAdvancedQuery(value: unknown): SearchQuery {
+ if (!isRecord(value)) {
+ throw new Error('Advanced Query must be an Intercom search object such as {"field": "name", "operator": "~", "value": "Ann"}.');
+ }
+ if (!isSearchQuery(value)) {
+ throw new Error('Advanced Query needs either field, operator and value, or operator AND/OR with a value list.');
+ }
+ return value;
+}
+
+function isSearchQuery(record: Record<string, unknown>): record is Record<string, unknown> & SearchQuery {
+ const hasFilter = typeof record['field'] === 'string' && typeof record['operator'] === 'string' && 'value' in record;
+ const hasGroup = (record['operator'] === 'AND' || record['operator'] === 'OR') && Array.isArray(record['value']);
+ return hasFilter || hasGroup;
+}
+
+function firstCompany(body: unknown): IntercomRecord | undefined {
+ if (!isRecord(body)) {
+ return undefined;
+ }
+ const record: IntercomRecord = body;
+ if (record['type'] === 'company') {
+ return record;
+ }
+ const data = record['data'];
+ if (Array.isArray(data) && data.length > 0) {
+ return data[0];
+ }
+ return undefined;
+}
+
+const MAX_FILTERS = 15;
+const MAX_ATTACHMENTS = 10;
+const DEFAULT_PER_PAGE = 50;
+const MAX_PER_PAGE = 150;
+
+export type IntercomRecord = Record<string, unknown>;
+
+export type CursorList = {
+ items: IntercomRecord[];
+ total_count: number;
+ has_more: boolean;
+ next_starting_after: string | null;
+};
+
+export type PagedList = {
+ items: IntercomRecord[];
+ total_count: number;
+ has_more: boolean;
+ next_page: number | null;
+};
+
+export type SearchQuery =
+ | { field: string; operator: string; value: unknown }
+ | { operator: 'AND' | 'OR'; value: SearchQuery[] };
+
+export type SearchPage = {
+ type?: string;
+ data?: IntercomRecord[];
+ total_count?: number;
+ pages?: { next?: { starting_after?: string } | null; page?: number; per_page?: number; total_pages?: number };
+};
+
+export type FlatPart = {
+ id: string;
+ part_type: string | null;
+ author_type: string | null;
+ author_id: string | null;
+ author_name: string | null;
+ body: string | null;
+ created_at: number | null;
+};
+
+export async function setRecordTag({
+ auth,
+ target,
+ recordId,
+ tagId,
+ tagName,
+ remove,
+}: {
+ auth: IntercomAuthValue;
+ target: TagTarget;
+ recordId: string;
+ tagId: string | undefined;
+ tagName: string | undefined;
+ remove: boolean;
+}) {
+ const tag = remove
+ ? await findExistingTag({ auth, tagId, tagName })
+ : await getOrCreateTag({ auth, tagId, tagName });
+ if (tag === undefined) {
+ return {
+ target,
+ record_id: recordId,
+ tag: { id: tagId ?? null, name: tagName ?? null },
+ removed: true,
+ already_in_state: true,
+ };
+ }
+
+ if (target === 'company') {
+ await tagCompany({ auth, recordId, tag, remove });
+ return { target, record_id: recordId, tag, removed: remove, already_in_state: false };
+ }
+
+ const plural = PLURAL[target];
+ const adminId = target === 'contact' ? undefined : await resolveAdminId({ auth, adminId: undefined });
+ if (!remove) {
+ await intercomRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: [plural, recordId, 'tags'],
+ body: { id: tag.id, ...(adminId ? { admin_id: adminId } : {}) },
+ operation: `tag the ${target}`,
+ });
+ return { target, record_id: recordId, tag, removed: false, already_in_state: false };
+ }
+
+ try {
+ await intercomRequest({
+ auth,
+ method: HttpMethod.DELETE,
+ path: [plural, recordId, 'tags', tag.id],
+ body: adminId ? { admin_id: adminId } : undefined,
+ operation: `untag the ${target}`,
+ });
+ return { target, record_id: recordId, tag, removed: true, already_in_state: false };
+ } catch (error) {
+ if (error instanceof IntercomApiError && error.status === 404) {
+ await intercomRequest({
+ auth,
+ method: HttpMethod.GET,
+ path: [plural, recordId],
+ operation: `get the ${target}`,
+ });
+ return { target, record_id: recordId, tag, removed: true, already_in_state: true };
+ }
+ throw error;
+ }
+}
+
+async function getOrCreateTag({
+ auth,
+ tagId,
+ tagName,
+}: {
+ auth: IntercomAuthValue;
+ tagId: string | undefined;
+ tagName: string | undefined;
+}): Promise<TagRef> {
+ if (tagId !== undefined) {
+ return toTagRef(
+ await intercomRequest<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['tags', tagId],
+ operation: 'get the tag',
+ }),
+ );
+ }
+ return toTagRef(await findOrCreateTag({ auth, name: tagName ?? '' }));
+}
+
+async function findExistingTag({
+ auth,
+ tagId,
+ tagName,
+}: {
+ auth: IntercomAuthValue;
+ tagId: string | undefined;
+ tagName: string | undefined;
+}): Promise<TagRef | undefined> {
+ const body = await intercomRequest<{ data?: Array<Record<string, unknown>> }>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['tags'],
+ operation: 'list tags',
+ });
+ const wanted = tagName?.toLowerCase();
+ const match = (body.data ?? []).find((tag) =>
+ tagId !== undefined ? String(tag['id']) === tagId : String(tag['name'] ?? '').toLowerCase() === wanted,
+ );
+ return match === undefined ? undefined : toTagRef(match);
+}
+
+async function tagCompany({
+ auth,
+ recordId,
+ tag,
+ remove,
+}: {
+ auth: IntercomAuthValue;
+ recordId: string;
+ tag: TagRef;
+ remove: boolean;
+}): Promise<void> {
+ if (!remove) {
+ await intercomRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: ['tags'],
+ body: { name: tag.name, companies: [{ id: recordId }] },
+ operation: 'tag the company',
+ });
+ return;
+ }
+ const company = await intercomRequest<{ company_id?: string }>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['companies', recordId],
+ operation: 'get the company',
+ });
+ await intercomRequest({
+ auth,
+ method: HttpMethod.POST,
+ path: ['tags'],
+ body: { name: tag.name, companies: [{ id: recordId, company_id: company.company_id, untag: true }] },
+ operation: 'untag the company',
+ });
+}
+
+function toTagRef(tag: Record<string, unknown>): TagRef {
+ return { id: String(tag['id']), name: String(tag['name'] ?? '') };
+}
+
+const PLURAL: Record<Exclude<TagTarget, 'company'>, string> = {
+ contact: 'contacts',
+ conversation: 'conversations',
+ ticket: 'tickets',
+};
+
+export type TagTarget = 'contact' | 'conversation' | 'company' | 'ticket';
+
+type TagRef = { id: string; name: string };
+
+export async function searchRecords({
+ auth,
+ resource,
+ query,
+ perPage,
+ startingAfter,
+}: {
+ auth: IntercomAuthValue;
+ resource: 'contacts' | 'conversations' | 'tickets';
+ query: SearchQuery;
+ perPage: number | undefined;
+ startingAfter: string | undefined;
+}): Promise<CursorList> {
+ const cursor = startingAfter?.trim();
+ const body = await intercomRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: [resource, 'search'],
+ body: {
+ query,
+ pagination: { per_page: clampPerPage(perPage), ...(cursor ? { starting_after: cursor } : {}) },
+ },
+ operation: `search ${resource}`,
+ });
+ return toCursorList({ body, itemsKey: SEARCH_ITEMS_KEY[resource] });
+}
+
+const SEARCH_ITEMS_KEY: Record<'contacts' | 'conversations' | 'tickets', string> = {
+ contacts: 'data',
+ conversations: 'conversations',
+ tickets: 'tickets',
+};
+
+export async function listCompanies({
+ auth,
+ tagId,
+ segmentId,
+ page,
+ perPage,
+}: {
+ auth: IntercomAuthValue;
+ tagId: string | undefined;
+ segmentId: string | undefined;
+ page: number | undefined;
+ perPage: number | undefined;
+}): Promise<PagedList> {
+ const pageSize = clampPerPage(perPage);
+ const body =
+ tagId || segmentId
+ ? await intercomRequest<unknown>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['companies'],
+ query: { tag_id: tagId, segment_id: segmentId, page, per_page: pageSize },
+ operation: 'list companies',
+ })
+ : await intercomRequest<unknown>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['companies', 'list'],
+ query: { page, per_page: pageSize, order: 'desc' },
+ operation: 'list companies',
+ });
+ return toPagedList({ body, itemsKey: 'data' });
+}
diff --git a/packages/pieces/community/intercom/src/lib/common/props.ts b/packages/pieces/community/intercom/src/lib/common/props.ts
index 62e47f0cc0b..5c12f21b205 100644
--- a/packages/pieces/community/intercom/src/lib/common/props.ts
+++ b/packages/pieces/community/intercom/src/lib/common/props.ts
@@ -1,11 +1,19 @@
-import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';
-import { getIntercomRegion, getIntercomToken, intercomClient, IntercomAuthValue } from '.';
+import { HttpMethod } from '@activepieces/pieces-common';
import {
DropdownOption,
DynamicPropsValue,
Property,
} from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
+import {
+ collectCapped,
+ intercomRequest,
+ IntercomAuthValue,
+ isRecord,
+ nextPageNumber,
+ nextStartingAfter,
+} from './client';
+import { getTicketTypeAttributes } from './ticket-attributes';
export const conversationIdProp = (displayName: string, required = true) =>
Property.Dropdown({
@@ -15,32 +23,30 @@ export const conversationIdProp = (displayName: string, required = true) =>
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const response = await client.conversations.list();
- const options: DropdownOption<string>[] = [];
-
- for await (const conversation of response) {
- options.push({
- value: conversation.id,
- label: `${conversation.source.author.email}${
- conversation.title ? `, ${conversation.title}` : ''
- }, ${conversation.id}`,
+ return safeDropdown(async () => {
+ const result = await collectCapped<IntercomConversationSummary>({
+ max: DROPDOWN_CAP,
+ fetchPage: async (cursor) => {
+ const body = await intercomRequest<{ conversations?: IntercomConversationSummary[] }>({
+ auth: auth,
+ method: HttpMethod.GET,
+ path: ['conversations'],
+ query: { per_page: 150, starting_after: cursor },
+ operation: 'list conversations',
+ });
+ return { items: body.conversations ?? [], next: nextStartingAfter(body) };
+ },
});
- }
-
- return {
- disabled: false,
- options,
- };
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((conversation) => ({
+ value: conversation.id,
+ label: conversationLabel(conversation),
+ })),
+ });
+ });
},
});
@@ -52,30 +58,20 @@ export const tagIdProp = (displayName: string, required = true) =>
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const response = await client.tags.list();
- const options: DropdownOption<string>[] = [];
-
- for (const tag of response.data) {
- options.push({
- value: tag.id,
- label: tag.name,
+ return safeDropdown(async () => {
+ const body = await intercomRequest<{ data?: Array<{ id: string; name: string }> }>({
+ auth: auth,
+ method: HttpMethod.GET,
+ path: ['tags'],
+ operation: 'list tags',
});
- }
-
- return {
- disabled: false,
- options,
- };
+ return toDropdown({
+ truncated: false,
+ options: (body.data ?? []).map((tag) => ({ value: tag.id, label: tag.name })),
+ });
+ });
},
});
@@ -87,30 +83,28 @@ export const companyIdProp = (displayName: string, required = true) =>
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const response = await client.companies.list();
- const options: DropdownOption<string>[] = [];
-
- for await (const company of response) {
- options.push({
- value: company.id,
- label: company.name,
+ return safeDropdown(async () => {
+ const result = await collectPaged<{ id: string; name?: string; company_id?: string }>({
+ loadPage: (page) =>
+ intercomRequest({
+ auth: auth,
+ method: HttpMethod.POST,
+ path: ['companies', 'list'],
+ query: { page, per_page: 60, order: 'desc' },
+ operation: 'list companies',
+ }),
+ itemsKey: 'data',
});
- }
-
- return {
- disabled: false,
- options,
- };
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((company) => ({
+ value: company.id,
+ label: company.name || company.company_id || company.id,
+ })),
+ });
+ });
},
});
@@ -122,35 +116,37 @@ export const contactIdProp = (displayName: string, contactType: string | null, r
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const response = await client.contacts.list();
- const options: DropdownOption<string>[] = [];
-
- for await (const contact of response) {
- if (contactType === null || contact.role === contactType) {
- options.push({
+ return safeDropdown(async () => {
+ const result = await searchContactsForDropdown({
+ auth: auth,
+ roles: contactType === null ? ['user', 'lead'] : [contactType],
+ });
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((contact) => ({
value: contact.id,
- label: `${contact.name ?? ''}, ${contact.email}, ${contact.external_id ?? ''}`,
- });
- }
- }
-
- return {
- disabled: false,
- options,
- };
+ label: `${contact.name ?? ''}, ${contact.email ?? ''}, ${contact.external_id ?? ''}`,
+ })),
+ });
+ });
},
});
+export async function contactOptionsForRoles({ auth, roles }: { auth: IntercomAuthValue; roles: string[] }) {
+ return safeDropdown(async () => {
+ const result = await searchContactsForDropdown({ auth, roles });
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((contact) => ({
+ value: contact.id,
+ label: `${contact.name ?? ''}, ${contact.email ?? ''}, ${contact.external_id ?? ''}`,
+ })),
+ });
+ });
+}
+
export const collectionIdProp = (displayName: string, required = true) =>
Property.Dropdown({
auth: intercomAuth,
@@ -159,30 +155,25 @@ export const collectionIdProp = (displayName: string, required = true) =>
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const response = await client.helpCenters.collections.list();
- const options: DropdownOption<string>[] = [];
-
- for await (const collection of response) {
- options.push({
- value: collection.id,
- label: collection.name,
+ return safeDropdown(async () => {
+ const result = await collectPaged<{ id: string; name: string }>({
+ loadPage: (page) =>
+ intercomRequest({
+ auth: auth,
+ method: HttpMethod.GET,
+ path: ['help_center', 'collections'],
+ query: { page, per_page: 150 },
+ operation: 'list Help Center collections',
+ }),
+ itemsKey: 'data',
});
- }
-
- return {
- disabled: false,
- options,
- };
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((collection) => ({ value: collection.id, label: collection.name })),
+ });
+ });
},
});
@@ -194,81 +185,15 @@ export const ticketTypeIdProp = (displayName: string, required = true) =>
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const response = await httpClient.sendRequest<{ data: Array<{ id: string; name: string }> }>({
- method: HttpMethod.GET,
- url: `https://api.${getIntercomRegion(authValue)}.io/ticket_types`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: getIntercomToken(authValue),
- },
- });
-
- const options: DropdownOption<string>[] = [];
-
- for (const type of response.body.data) {
- options.push({
- value: type.id,
- label: type.name,
+ return safeDropdown(async () => {
+ const types = await listTicketTypes({ auth: auth });
+ return toDropdown({
+ truncated: false,
+ options: types.map((type) => ({ value: type.id, label: type.name })),
});
- }
-
- return {
- disabled: false,
- options,
- };
- },
- });
-
-export const ticketStateIdProp = (displayName: string, required = true) =>
- Property.Dropdown({
- auth: intercomAuth,
- displayName,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- options: [],
- disabled: true,
- };
- }
-
- const authValue = auth as IntercomAuthValue;
-
- const options: DropdownOption<string>[] = [];
-
- const response = await httpClient.sendRequest<{
- data: Array<{ id: string; internal_label: string }>;
- }>({
- method: HttpMethod.GET,
- url: `https://api.${getIntercomRegion(authValue)}.io/ticket_states`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: getIntercomToken(authValue),
- },
});
-
- if (response.body.data) {
- for (const state of response.body.data) {
- options.push({
- label: state.internal_label,
- value: state.id,
- });
- }
- }
-
- return {
- disabled: false,
- options,
- };
},
});
@@ -279,39 +204,37 @@ export const ticketIdProp = (displayName: string, required = true) =>
required,
refreshers: ['ticketTypeId'],
options: async ({ auth, ticketTypeId }) => {
- if (!auth || !ticketTypeId) {
- return {
- options: [],
- disabled: true,
- placeholder: 'Please connect your account first.',
- };
+ if (!auth) {
+ return connectFirst();
}
-
- const authValue = auth as IntercomAuthValue;
- const client = intercomClient(authValue);
-
- const options: DropdownOption<string>[] = [];
-
- const response = await client.tickets.search({
- query: {
- field: 'ticket_type_id',
- operator: '=',
- value: ticketTypeId as unknown as string,
- },
- pagination: { per_page: 100 },
- });
-
- for await (const ticket of response) {
- options.push({
- value: ticket.id,
- label: (ticket.ticket_attributes['_default_title_'] as string) ?? ticket.id,
- });
+ if (!ticketTypeId) {
+ return { options: [], disabled: true, placeholder: 'Select a ticket type first.' };
}
-
- return {
- disabled: false,
- options,
- };
+ return safeDropdown(async () => {
+ const result = await collectCapped<{ id: string; ticket_attributes?: Record<string, unknown> }>({
+ max: DROPDOWN_CAP,
+ fetchPage: async (cursor) => {
+ const body = await intercomRequest<{ tickets?: Array<{ id: string; ticket_attributes?: Record<string, unknown> }> }>({
+ auth: auth,
+ method: HttpMethod.POST,
+ path: ['tickets', 'search'],
+ body: {
+ query: { field: 'ticket_type_id', operator: '=', value: String(ticketTypeId) },
+ pagination: { per_page: 150, ...(cursor ? { starting_after: cursor } : {}) },
+ },
+ operation: 'search tickets',
+ });
+ return { items: body.tickets ?? [], next: nextStartingAfter(body) };
+ },
+ });
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((ticket) => {
+ const title = ticket.ticket_attributes?.['_default_title_'];
+ return { value: ticket.id, label: typeof title === 'string' && title.length > 0 ? title : ticket.id };
+ }),
+ });
+ });
},
});
@@ -325,24 +248,13 @@ export const ticketPropertiesProp = (displayName: string, required = true) =>
if (!auth) return {};
if (!ticketTypeId) return {};
- const props: DynamicPropsValue = {};
-
- const authValue = auth as IntercomAuthValue;
-
- const response = await httpClient.sendRequest<{
- ticket_type_attributes: {
- data: Array<{ data_type: string; name: string; input_options: Record<string, unknown> }>;
- };
- }>({
- method: HttpMethod.GET,
- url: `https://api.${getIntercomRegion(authValue)}.io/ticket_types/${ticketTypeId}`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: getIntercomToken(authValue),
- },
+ const attributes = await getTicketTypeAttributes({
+ auth: auth,
+ ticketTypeId: String(ticketTypeId),
});
- for (const field of response.body.ticket_type_attributes.data) {
+ const props: DynamicPropsValue = {};
+ for (const field of attributes) {
switch (field.data_type) {
case 'string':
props[field.name] = Property.LongText({
@@ -376,18 +288,14 @@ export const ticketPropertiesProp = (displayName: string, required = true) =>
break;
case 'list':
{
- const options = field.input_options?.['list_options'] as Array<{
- label: string;
- id: string;
- }>;
-
+ const options = field.input_options?.['list_options'];
props[field.name] = Property.StaticDropdown({
displayName: field.name,
required: false,
options: {
disabled: false,
- options: options
- ? options.map((option) => ({
+ options: Array.isArray(options)
+ ? options.map((option: { id: string; label: string }) => ({
value: option.id,
label: option.label,
}))
@@ -395,7 +303,6 @@ export const ticketPropertiesProp = (displayName: string, required = true) =>
},
});
}
-
break;
default:
break;
@@ -405,3 +312,195 @@ export const ticketPropertiesProp = (displayName: string, required = true) =>
return props;
},
});
+
+export const adminDropdown = <R extends boolean>(options: { displayName: string; required: R }) =>
+ Property.Dropdown<string, R, typeof intercomAuth>({
+ auth: intercomAuth,
+ displayName: options.displayName,
+ required: options.required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return connectFirst();
+ }
+ return safeDropdown(async () => {
+ const body = await intercomRequest<{ admins?: Array<{ id: string; name?: string; email?: string }> }>({
+ auth: auth,
+ method: HttpMethod.GET,
+ path: ['admins'],
+ operation: 'list admins',
+ });
+ return toDropdown({
+ truncated: false,
+ options: (body.admins ?? []).map((admin) => ({
+ value: admin.id,
+ label: admin.name || admin.email || admin.id,
+ })),
+ });
+ });
+ },
+ });
+
+export const contactDropdown = <R extends boolean>(options: { displayName: string; required: R }) =>
+ Property.Dropdown<string, R, typeof intercomAuth>({
+ auth: intercomAuth,
+ displayName: options.displayName,
+ required: options.required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return connectFirst();
+ }
+ return safeDropdown(async () => {
+ const result = await searchContactsForDropdown({
+ auth: auth,
+ roles: ['user', 'lead'],
+ });
+ return toDropdown({
+ truncated: result.truncated,
+ options: result.items.map((contact) => ({
+ value: contact.id,
+ label: contact.name || contact.email || contact.id,
+ })),
+ });
+ });
+ },
+ });
+
+export async function listTicketTypes({ auth }: { auth: IntercomAuthValue }): Promise<IntercomTicketTypeSummary[]> {
+ const body = await intercomRequest<{
+ data?: IntercomTicketTypeSummary[];
+ ticket_types?: IntercomTicketTypeSummary[];
+ }>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['ticket_types'],
+ operation: 'list ticket types',
+ });
+ return body.data ?? body.ticket_types ?? [];
+}
+
+async function searchContactsForDropdown({
+ auth,
+ roles,
+}: {
+ auth: IntercomAuthValue;
+ roles: string[];
+}): Promise<{ items: IntercomContactSummary[]; truncated: boolean }> {
+ return collectCapped<IntercomContactSummary>({
+ max: DROPDOWN_CAP,
+ fetchPage: async (cursor) => {
+ const body = await intercomRequest<{ data?: IntercomContactSummary[] }>({
+ auth,
+ method: HttpMethod.POST,
+ path: ['contacts', 'search'],
+ body: {
+ query:
+ roles.length === 1
+ ? { field: 'role', operator: '=', value: roles[0] }
+ : { field: 'role', operator: 'IN', value: roles },
+ pagination: { per_page: 150, ...(cursor ? { starting_after: cursor } : {}) },
+ sort: { field: 'updated_at', order: 'descending' },
+ },
+ operation: 'search contacts',
+ });
+ return { items: body.data ?? [], next: nextStartingAfter(body) };
+ },
+ });
+}
+
+async function collectPaged<T>({
+ loadPage,
+ itemsKey,
+}: {
+ loadPage: (page: number) => Promise<unknown>;
+ itemsKey: string;
+}): Promise<{ items: T[]; truncated: boolean }> {
+ let pagesFetched = 0;
+ const result = await collectCapped<T>({
+ max: DROPDOWN_CAP,
+ fetchPage: async (cursor) => {
+ const page = cursor === undefined ? 1 : Number(cursor);
+ const body = await loadPage(page);
+ pagesFetched += 1;
+ const items = readItems<T>({ body, itemsKey });
+ const nextPage = nextPageNumber(body);
+ if (nextPage === undefined || pagesFetched >= MAX_DROPDOWN_PAGES) {
+ return { items, next: undefined };
+ }
+ return { items, next: String(nextPage) };
+ },
+ });
+ return { items: result.items, truncated: result.truncated || pagesFetched >= MAX_DROPDOWN_PAGES };
+}
+
+function readItems<T>({ body, itemsKey }: { body: unknown; itemsKey: string }): T[] {
+ if (!isRecord(body)) {
+ return [];
+ }
+ const items = body[itemsKey];
+ return Array.isArray(items) ? items : [];
+}
+
+function conversationLabel(conversation: IntercomConversationSummary): string {
+ const author = conversation.source?.author;
+ const who = author?.email || author?.name || 'Unknown sender';
+ return `${who}${conversation.title ? `, ${conversation.title}` : ''}, ${conversation.id}`;
+}
+
+function connectFirst() {
+ return {
+ options: [],
+ disabled: true,
+ placeholder: 'Please connect your account first.',
+ };
+}
+
+async function safeDropdown(
+ load: () => Promise<{ options: DropdownOption<string>[]; disabled: boolean; placeholder?: string }>,
+) {
+ try {
+ return await load();
+ } catch (error) {
+ return {
+ options: [],
+ disabled: true,
+ placeholder: `Could not load options: ${error instanceof Error ? error.message : String(error)}`,
+ };
+ }
+}
+
+function toDropdown({ options, truncated }: { options: DropdownOption<string>[]; truncated: boolean }) {
+ return {
+ disabled: false,
+ options,
+ placeholder: truncated
+ ? `Showing the first ${DROPDOWN_CAP.toLocaleString('en-US')} items. To use another one, switch this field to a custom value and paste its ID.`
+ : undefined,
+ };
+}
+
+const DROPDOWN_CAP = 1000;
+const MAX_DROPDOWN_PAGES = 20;
+
+type IntercomConversationSummary = {
+ id: string;
+ title?: string | null;
+ source?: { author?: { email?: string | null; name?: string | null } | null } | null;
+};
+
+type IntercomContactSummary = {
+ id: string;
+ name?: string | null;
+ email?: string | null;
+ external_id?: string | null;
+};
+
+export type IntercomTicketTypeSummary = {
+ id: string;
+ name: string;
+ description?: string;
+ category?: string;
+ archived?: boolean;
+ ticket_type_attributes?: { data?: unknown[] };
+};
diff --git a/packages/pieces/community/intercom/src/lib/common/ticket-attributes.ts b/packages/pieces/community/intercom/src/lib/common/ticket-attributes.ts
new file mode 100644
index 00000000000..a20b7062a3a
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/common/ticket-attributes.ts
@@ -0,0 +1,132 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import dayjs from 'dayjs';
+import { intercomRequest, IntercomAuthValue } from './client';
+
+export async function getTicketTypeAttributes({
+ auth,
+ ticketTypeId,
+}: {
+ auth: IntercomAuthValue;
+ ticketTypeId: string;
+}): Promise<TicketTypeAttribute[]> {
+ const body = await intercomRequest<{ ticket_type_attributes?: { data?: TicketTypeAttribute[] } }>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['ticket_types', ticketTypeId],
+ operation: 'get the ticket type',
+ });
+ return body.ticket_type_attributes?.data ?? [];
+}
+
+export function toTicketAttributes({
+ attributes,
+ values,
+}: {
+ attributes: TicketTypeAttribute[];
+ values: Record<string, unknown>;
+}): Record<string, unknown> {
+ const byName = new Map(attributes.map((attribute) => [attribute.name, attribute]));
+ return Object.fromEntries(
+ Object.entries(values)
+ .filter(([, value]) => value !== undefined)
+ .map(([name, value]) => [
+ name,
+ convertValue({ name, value, dataType: byName.get(name)?.data_type }),
+ ]),
+ );
+}
+
+export function toWebhookTicketShape(ticket: unknown): unknown {
+ if (typeof ticket !== 'object' || ticket === null) {
+ return ticket;
+ }
+ const state: unknown = Reflect.get(ticket, 'ticket_state');
+ if (typeof state !== 'string') {
+ return ticket;
+ }
+ const flatLabelKeys = ['ticket_state_internal_label', 'ticket_state_external_label'];
+ const rest = Object.fromEntries(Object.entries(ticket).filter(([key]) => !flatLabelKeys.includes(key)));
+ return {
+ ...rest,
+ ticket_state: {
+ type: 'ticket_state',
+ category: state,
+ internal_label: Reflect.get(ticket, 'ticket_state_internal_label') ?? null,
+ external_label: Reflect.get(ticket, 'ticket_state_external_label') ?? null,
+ },
+ };
+}
+
+function convertValue({
+ name,
+ value,
+ dataType,
+}: {
+ name: string;
+ value: unknown;
+ dataType: string | undefined;
+}): unknown {
+ if (value === null) {
+ return null;
+ }
+ switch (dataType) {
+ case 'datetime':
+ return toUnixSeconds({ name, value });
+ case 'integer':
+ case 'decimal':
+ return toNumber({ name, value, integer: dataType === 'integer' });
+ case 'boolean':
+ return toBoolean({ name, value });
+ default:
+ return value;
+ }
+}
+
+function toUnixSeconds({ name, value }: { name: string; value: unknown }): number {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value > MILLISECONDS_THRESHOLD ? Math.floor(value / 1000) : Math.floor(value);
+ }
+ if (typeof value === 'string') {
+ const trimmed = value.trim();
+ if (/^\d+$/.test(trimmed)) {
+ const numeric = Number(trimmed);
+ return numeric > MILLISECONDS_THRESHOLD ? Math.floor(numeric / 1000) : numeric;
+ }
+ const parsed = dayjs(trimmed);
+ if (trimmed.length > 0 && parsed.isValid()) {
+ return parsed.unix();
+ }
+ }
+ throw new Error(`Ticket attribute "${name}" expects a date and time (ISO 8601 or Unix seconds); got ${JSON.stringify(value)}.`);
+}
+
+function toNumber({ name, value, integer }: { name: string; value: unknown; integer: boolean }): number {
+ const numeric = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
+ if (!Number.isFinite(numeric) || (integer && !Number.isInteger(numeric))) {
+ throw new Error(`Ticket attribute "${name}" expects ${integer ? 'a whole number' : 'a number'}; got ${JSON.stringify(value)}.`);
+ }
+ return numeric;
+}
+
+function toBoolean({ name, value }: { name: string; value: unknown }): boolean {
+ if (typeof value === 'boolean') {
+ return value;
+ }
+ if (value === 'true' || value === 'false') {
+ return value === 'true';
+ }
+ throw new Error(`Ticket attribute "${name}" expects true or false; got ${JSON.stringify(value)}.`);
+}
+
+const MILLISECONDS_THRESHOLD = 100_000_000_000;
+
+export type TicketTypeAttribute = {
+ id?: string;
+ name: string;
+ description?: string;
+ data_type: string;
+ required_to_create?: boolean;
+ visible_to_contacts?: boolean;
+ archived?: boolean;
+ input_options?: Record<string, unknown> | null;
+};
diff --git a/packages/pieces/community/intercom/src/lib/common/webhook-samples.ts b/packages/pieces/community/intercom/src/lib/common/webhook-samples.ts
new file mode 100644
index 00000000000..21cac603f71
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/common/webhook-samples.ts
@@ -0,0 +1,153 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { intercomRequest, IntercomAuthValue } from './client';
+
+export async function recentConversationEnvelopes({
+ auth,
+ topic,
+}: {
+ auth: IntercomAuthValue;
+ topic: string;
+}): Promise<Record<string, unknown>[]> {
+ const list = await intercomRequest<{ conversations?: Array<{ id: string }> }>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['conversations'],
+ query: { per_page: 3 },
+ operation: 'list recent conversations',
+ });
+ const recent = (list.conversations ?? []).slice(0, 3);
+ const conversations = await Promise.all(
+ recent.map((conversation) =>
+ intercomRequest<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: ['conversations', conversation.id],
+ operation: 'get the conversation',
+ }),
+ ),
+ );
+ return conversations.map((item) => toEnvelope({ topic, item }));
+}
+
+export function conversationEnvelopeSample(topic: string): Record<string, unknown> {
+ return toEnvelope({ topic, item: CONVERSATION_ITEM_SAMPLE });
+}
+
+function toEnvelope({ topic, item }: { topic: string; item: Record<string, unknown> }): Record<string, unknown> {
+ return {
+ type: 'notification_event',
+ app_id: 'abc12345',
+ id: 'notif_0f4c2b9e-1d1b-4a77-9f3e-9b0c1f0e2a11',
+ topic,
+ delivery_status: 'pending',
+ delivery_attempts: 1,
+ delivered_at: 0,
+ first_sent_at: 1739524230,
+ created_at: 1739524230,
+ data: { type: 'notification_event_data', item },
+ };
+}
+
+const CONVERSATION_ITEM_SAMPLE: Record<string, unknown> = {
+ type: 'conversation',
+ id: '2',
+ title: null,
+ created_at: 1739105560,
+ updated_at: 1739524230,
+ waiting_since: null,
+ snoozed_until: null,
+ open: true,
+ state: 'open',
+ read: true,
+ priority: 'not_priority',
+ admin_assignee_id: 8016437,
+ team_assignee_id: null,
+ tags: { type: 'tag.list', tags: [] },
+ conversation_rating: null,
+ source: {
+ type: 'conversation',
+ id: '2',
+ delivered_as: 'customer_initiated',
+ subject: '',
+ body: '<p>Hi, I cannot log in to the dashboard.</p>',
+ author: { type: 'user', id: '67a9b9dfcc14109e073fbe19', name: 'John Doe', email: '[email protected]' },
+ attachments: [],
+ url: null,
+ redacted: false,
+ },
+ contacts: {
+ type: 'contact.list',
+ contacts: [{ type: 'contact', id: '67a9b9dfcc14109e073fbe19', external_id: '5b803f65-bcec-4198-b4f4-a0588454b537' }],
+ },
+ statistics: {
+ type: 'conversation_statistics',
+ first_admin_reply_at: 1739105600,
+ last_close_at: null,
+ count_reopens: 0,
+ count_conversation_parts: 3,
+ },
+ custom_attributes: {},
+ ai_agent_participated: false,
+ conversation_parts: {
+ type: 'conversation_part.list',
+ conversation_parts: [
+ {
+ type: 'conversation_part',
+ id: '101',
+ part_type: 'comment',
+ body: '<p>Thanks, we are looking into it.</p>',
+ created_at: 1739524230,
+ updated_at: 1739524230,
+ notified_at: 1739524230,
+ assigned_to: null,
+ author: { type: 'admin', id: '8016437', name: 'Pat Lee', email: '[email protected]' },
+ attachments: [],
+ external_id: null,
+ redacted: false,
+ },
+ ],
+ total_count: 1,
+ },
+};
+
+export const COMPANY_SAMPLE: Record<string, unknown> = {
+ type: 'company',
+ company_id: 'acme-001',
+ id: '67a9c1b2cc14109e073fbe55',
+ app_id: 'abc12345',
+ name: 'Acme Inc',
+ remote_created_at: null,
+ created_at: '2025-02-09T12:52:40.000+00:00',
+ updated_at: '2025-02-09T12:52:40.000+00:00',
+ last_request_at: null,
+ size: 120,
+ website: 'https://acme.example.com',
+ industry: 'Software',
+ monthly_spend: 500,
+ session_count: 0,
+ user_count: 0,
+ plan: { type: 'plan', id: '1', name: 'Pro' },
+ custom_attributes: {},
+ tag_ids: [],
+};
+
+export const CONVERSATION_PART_TAG_SAMPLE: Record<string, unknown> = {
+ type: 'conversation_part_tag',
+ created_at: 1739524230,
+ tag: { type: 'tag', id: '7522907', name: 'Bug' },
+ conversation: {
+ type: 'conversation',
+ id: '2',
+ title: '',
+ state: 'open',
+ open: true,
+ read: false,
+ priority: 'not_priority',
+ created_at: 1739105560,
+ updated_at: 1739524230,
+ waiting_since: null,
+ snoozed_until: null,
+ admin_assignee_id: 7654321,
+ team_assignee_id: 0,
+ },
+};
diff --git a/packages/pieces/community/intercom/src/lib/output-schemas.ts b/packages/pieces/community/intercom/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..86f598c2e70
--- /dev/null
+++ b/packages/pieces/community/intercom/src/lib/output-schemas.ts
@@ -0,0 +1,646 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const UNIX = 'Unix timestamp in seconds.';
+
+const referenceListFields = (label: string): OutputSchema['fields'] => [
+ { key: 'data', label, listItems: [{ key: 'id', label: 'ID' }] },
+ { key: 'total_count', label: 'Total Count', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+];
+
+const contactFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Contact ID' },
+ { key: 'role', label: 'Role', description: 'user or lead.' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'name', label: 'Name' },
+ { key: 'phone', label: 'Phone' },
+ { key: 'external_id', label: 'External ID' },
+ { key: 'owner_id', label: 'Owner ID' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+ { key: 'signed_up_at', label: 'Signed Up At', description: UNIX },
+ { key: 'last_seen_at', label: 'Last Seen At', description: UNIX },
+ { key: 'last_replied_at', label: 'Last Replied At', description: UNIX },
+ { key: 'last_contacted_at', label: 'Last Contacted At', description: UNIX },
+ { key: 'unsubscribed_from_emails', label: 'Unsubscribed From Emails', format: 'boolean' },
+ { key: 'has_hard_bounced', label: 'Has Hard Bounced', format: 'boolean' },
+ { key: 'marked_email_as_spam', label: 'Marked Email As Spam', format: 'boolean' },
+ {
+ key: 'location',
+ label: 'Location',
+ children: [
+ { key: 'country', label: 'Country' },
+ { key: 'region', label: 'Region' },
+ { key: 'city', label: 'City' },
+ ],
+ },
+ { key: 'custom_attributes', label: 'Custom Attributes', dynamicKey: true },
+ { key: 'tags', label: 'Tags', children: referenceListFields('Tag References') },
+ { key: 'companies', label: 'Companies', children: referenceListFields('Company References') },
+];
+
+const conversationContactFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Contact ID' },
+ { key: 'external_id', label: 'External ID' },
+];
+
+const conversationFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Conversation ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'state', label: 'State', description: 'open, closed or snoozed.' },
+ { key: 'open', label: 'Open', format: 'boolean' },
+ { key: 'read', label: 'Read', format: 'boolean' },
+ { key: 'priority', label: 'Priority' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+ { key: 'waiting_since', label: 'Waiting Since', description: UNIX },
+ { key: 'snoozed_until', label: 'Snoozed Until', description: UNIX },
+ { key: 'admin_assignee_id', label: 'Assigned Admin ID' },
+ { key: 'team_assignee_id', label: 'Assigned Team ID' },
+ {
+ key: 'source',
+ label: 'First Message',
+ children: [
+ { key: 'type', label: 'Type' },
+ { key: 'delivered_as', label: 'Delivered As' },
+ { key: 'subject', label: 'Subject' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'url', label: 'URL', format: 'url' },
+ {
+ key: 'author',
+ label: 'Author',
+ children: [
+ { key: 'type', label: 'Type' },
+ { key: 'id', label: 'ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ ],
+ },
+ ],
+ },
+ {
+ key: 'contacts',
+ label: 'Contacts',
+ children: [{ key: 'contacts', label: 'Contacts', labelKey: 'id', listItems: conversationContactFields }],
+ },
+ {
+ key: 'tags',
+ label: 'Tags',
+ children: [
+ {
+ key: 'tags',
+ label: 'Tags',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Tag ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ ],
+ },
+ {
+ key: 'conversation_rating',
+ label: 'Rating',
+ children: [
+ { key: 'rating', label: 'Rating', format: 'number' },
+ { key: 'remark', label: 'Remark' },
+ { key: 'created_at', label: 'Rated At', description: UNIX },
+ ],
+ },
+ {
+ key: 'statistics',
+ label: 'Statistics',
+ children: [
+ { key: 'first_admin_reply_at', label: 'First Admin Reply At', description: UNIX },
+ { key: 'last_close_at', label: 'Last Closed At', description: UNIX },
+ { key: 'count_reopens', label: 'Reopen Count', format: 'number' },
+ { key: 'count_conversation_parts', label: 'Part Count', format: 'number' },
+ ],
+ },
+ { key: 'custom_attributes', label: 'Custom Attributes', dynamicKey: true },
+ { key: 'ai_agent_participated', label: 'AI Agent Participated', format: 'boolean' },
+];
+
+const conversationPartFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Part ID' },
+ { key: 'part_type', label: 'Part Type' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ {
+ key: 'author',
+ label: 'Author',
+ children: [
+ { key: 'type', label: 'Type' },
+ { key: 'id', label: 'ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ ],
+ },
+];
+
+const flatPartFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Part ID' },
+ { key: 'part_type', label: 'Part Type' },
+ { key: 'author_type', label: 'Author Type' },
+ { key: 'author_id', label: 'Author ID' },
+ { key: 'author_name', label: 'Author Name' },
+ { key: 'body', label: 'Body' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+];
+
+const ticketFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Ticket ID', description: 'Use this ID in API calls.' },
+ { key: 'ticket_id', label: 'Inbox Ticket Number', description: 'Shown in the Intercom inbox; not used in API calls.' },
+ { key: 'category', label: 'Category' },
+ { key: 'ticket_state', label: 'State' },
+ { key: 'ticket_state_internal_label', label: 'State (Internal Label)' },
+ { key: 'ticket_state_external_label', label: 'State (Customer Label)' },
+ { key: 'open', label: 'Open', format: 'boolean' },
+ { key: 'is_shared', label: 'Shared With Customer', format: 'boolean' },
+ {
+ key: 'ticket_type',
+ label: 'Ticket Type',
+ children: [
+ { key: 'id', label: 'Ticket Type ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ { key: 'ticket_attributes', label: 'Ticket Attributes', dynamicKey: true },
+ {
+ key: 'contacts',
+ label: 'Contacts',
+ children: [{ key: 'contacts', label: 'Contacts', labelKey: 'id', listItems: conversationContactFields }],
+ },
+ { key: 'admin_assignee_id', label: 'Assigned Admin ID' },
+ { key: 'team_assignee_id', label: 'Assigned Team ID' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+ { key: 'snoozed_until', label: 'Snoozed Until', description: UNIX },
+];
+
+const companyFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Intercom Company ID' },
+ { key: 'company_id', label: 'Your Company ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'plan', label: 'Plan', children: [{ key: 'name', label: 'Plan Name' }] },
+ { key: 'size', label: 'Size', format: 'number' },
+ { key: 'website', label: 'Website', format: 'url' },
+ { key: 'industry', label: 'Industry' },
+ { key: 'monthly_spend', label: 'Monthly Spend', format: 'number' },
+ { key: 'user_count', label: 'User Count', format: 'number' },
+ { key: 'session_count', label: 'Session Count', format: 'number' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+ { key: 'remote_created_at', label: 'Created At (Your System)', description: UNIX },
+ { key: 'last_request_at', label: 'Last Request At', description: UNIX },
+ { key: 'custom_attributes', label: 'Custom Attributes', dynamicKey: true },
+ {
+ key: 'tags',
+ label: 'Tags',
+ children: [
+ {
+ key: 'tags',
+ label: 'Tags',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Tag ID' },
+ { key: 'name', label: 'Name' },
+ ],
+ },
+ ],
+ },
+];
+
+const tagFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Tag ID' },
+ { key: 'name', label: 'Name' },
+];
+
+const noteFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Note ID' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ {
+ key: 'author',
+ label: 'Author',
+ children: [
+ { key: 'id', label: 'Admin ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ ],
+ },
+ { key: 'contact', label: 'Contact', children: [{ key: 'id', label: 'Contact ID' }] },
+];
+
+const messageFields: OutputSchema['fields'] = [
+ { key: 'type', label: 'Type' },
+ { key: 'id', label: 'Message ID' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'subject', label: 'Subject' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'message_type', label: 'Message Type' },
+ { key: 'template', label: 'Email Template' },
+ { key: 'conversation_id', label: 'Conversation ID', description: 'Only present when a conversation was opened.' },
+ {
+ key: 'owner',
+ label: 'Sent By',
+ children: [
+ { key: 'id', label: 'Admin ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ ],
+ },
+];
+
+const articleFields: OutputSchema['fields'] = [
+ { key: 'id', label: 'Article ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'author_id', label: 'Author ID' },
+ { key: 'state', label: 'State' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'parent_id', label: 'Parent Collection ID' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+];
+
+const contactWebhookFields: OutputSchema['fields'] = contactFields.map((field) =>
+ field.description === UNIX ? { ...field, description: 'Date and time of the event payload.' } : field,
+);
+
+const cursorListFields = ({
+ itemLabel,
+ items,
+ labelKey,
+}: {
+ itemLabel: string;
+ items: OutputSchema['fields'];
+ labelKey: string;
+}): OutputSchema['fields'] => [
+ { key: 'items', label: itemLabel, labelKey, listItems: items },
+ { key: 'total_count', label: 'Total Matches', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'next_starting_after', label: 'Next Page Cursor', description: 'Pass as Starting After to get the next page.' },
+];
+
+const pagedListFields = ({
+ itemLabel,
+ items,
+ labelKey,
+}: {
+ itemLabel: string;
+ items: OutputSchema['fields'];
+ labelKey: string;
+}): OutputSchema['fields'] => [
+ { key: 'items', label: itemLabel, labelKey, listItems: items },
+ { key: 'total_count', label: 'Total Count', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'next_page', label: 'Next Page', format: 'number' },
+];
+
+const envelopeFields = (item: OutputSchema['fields']): OutputSchema['fields'] => [
+ { key: 'id', label: 'Notification ID' },
+ { key: 'topic', label: 'Topic' },
+ { key: 'app_id', label: 'Workspace ID' },
+ { key: 'created_at', label: 'Sent At', description: UNIX },
+ { key: 'data', label: 'Data', children: [{ key: 'item', label: 'Conversation', children: item }] },
+];
+
+export const contactOutputSchema: OutputSchema = { fields: contactFields };
+
+export const conversationOutputSchema: OutputSchema = { fields: conversationFields };
+
+export const conversationWithPartsOutputSchema: OutputSchema = {
+ fields: [
+ ...conversationFields,
+ {
+ key: 'conversation_parts',
+ label: 'Conversation Parts',
+ children: [
+ { key: 'conversation_parts', label: 'Parts', labelKey: 'part_type', listItems: conversationPartFields },
+ { key: 'total_count', label: 'Total Parts', format: 'number' },
+ ],
+ },
+ ],
+};
+
+export const conversationFlatPartsOutputSchema: OutputSchema = {
+ fields: [...conversationFields, { key: 'parts', label: 'Parts', labelKey: 'part_type', listItems: flatPartFields }],
+};
+
+export const ticketOutputSchema: OutputSchema = { fields: ticketFields };
+
+export const companyOutputSchema: OutputSchema = { fields: companyFields };
+
+export const tagOutputSchema: OutputSchema = { fields: tagFields };
+
+export const noteOutputSchema: OutputSchema = { fields: noteFields };
+
+export const messageOutputSchema: OutputSchema = { fields: messageFields };
+
+export const articleOutputSchema: OutputSchema = { fields: articleFields };
+
+export const dataEventOutputSchema: OutputSchema = {
+ fields: [{ key: 'success', label: 'Success', format: 'boolean' }],
+};
+
+export const listTagsOutputSchema: OutputSchema = {
+ fields: [{ key: 'data', label: 'Tags', labelKey: 'name', listItems: tagFields }],
+};
+
+export const findUserOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'user', label: 'User', children: contactFields },
+ ],
+};
+
+export const findLeadOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'lead', label: 'Lead', children: contactFields },
+ ],
+};
+
+export const findOrCreateLeadOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'created', label: 'Created', format: 'boolean' },
+ { key: 'lead', label: 'Lead', children: contactFields },
+ ],
+};
+
+export const findCompanyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'company', label: 'Company', children: companyFields },
+ { key: 'user', label: 'Company (Legacy Key)', description: 'Same company as Company; kept for older flows.', children: companyFields },
+ ],
+};
+
+export const findOrCreateCompanyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'created', label: 'Created', format: 'boolean' },
+ { key: 'company', label: 'Company', children: companyFields },
+ ],
+};
+
+export const findConversationOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'found', label: 'Found', format: 'boolean' },
+ { key: 'conversation', label: 'Conversation', children: conversationFields },
+ ],
+};
+
+export const tagOrUntagOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'target', label: 'Record Type' },
+ { key: 'record_id', label: 'Record ID' },
+ { key: 'tag', label: 'Tag', children: tagFields },
+ { key: 'removed', label: 'Removed', format: 'boolean' },
+ { key: 'already_in_state', label: 'Already In That State', format: 'boolean' },
+ ],
+};
+
+export const searchContactsOutputSchema: OutputSchema = {
+ fields: cursorListFields({ itemLabel: 'Contacts', items: contactFields, labelKey: 'email' }),
+};
+
+export const searchConversationsOutputSchema: OutputSchema = {
+ fields: cursorListFields({ itemLabel: 'Conversations', items: conversationFields, labelKey: 'id' }),
+};
+
+export const searchTicketsOutputSchema: OutputSchema = {
+ fields: cursorListFields({ itemLabel: 'Tickets', items: ticketFields, labelKey: 'id' }),
+};
+
+export const listContactNotesOutputSchema: OutputSchema = {
+ fields: pagedListFields({ itemLabel: 'Notes', items: noteFields, labelKey: 'id' }),
+};
+
+export const listCompaniesOutputSchema: OutputSchema = {
+ fields: pagedListFields({ itemLabel: 'Companies', items: companyFields, labelKey: 'name' }),
+};
+
+export const ticketReplyOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'type', label: 'Type' },
+ { key: 'id', label: 'Part ID' },
+ { key: 'part_type', label: 'Part Type' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ {
+ key: 'author',
+ label: 'Author',
+ children: [
+ { key: 'type', label: 'Type' },
+ { key: 'id', label: 'ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ ],
+ },
+ ],
+};
+
+export const listTicketTypesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Ticket Types',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Ticket Type ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'description', label: 'Description' },
+ { key: 'category', label: 'Category' },
+ { key: 'archived', label: 'Archived', format: 'boolean' },
+ {
+ key: 'attributes',
+ label: 'Attributes',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'required_to_create', label: 'Required To Create', format: 'boolean' },
+ { key: 'visible_to_contacts', label: 'Visible To Contacts', format: 'boolean' },
+ {
+ key: 'options',
+ label: 'List Options',
+ labelKey: 'label',
+ listItems: [
+ { key: 'id', label: 'Option ID' },
+ { key: 'label', label: 'Label' },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+};
+
+export const listAdminsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Admins',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Admin ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'job_title', label: 'Job Title' },
+ { key: 'away_mode_enabled', label: 'Away', format: 'boolean' },
+ { key: 'has_inbox_seat', label: 'Has Inbox Seat', format: 'boolean' },
+ { key: 'team_ids', label: 'Team IDs' },
+ ],
+ },
+ { key: 'current_admin_id', label: 'Connected Admin ID' },
+ ],
+};
+
+export const listTeamsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Teams',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Team ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'admin_ids', label: 'Admin IDs' },
+ ],
+ },
+ ],
+};
+
+export const listSegmentsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Segments',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Segment ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'person_type', label: 'Person Type', description: 'user or lead (contact).' },
+ { key: 'count', label: 'Contact Count', format: 'number', description: 'Only when Include Counts is on.' },
+ { key: 'created_at', label: 'Created At', description: UNIX },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+ ],
+ },
+ ],
+};
+
+export const listDataAttributesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Data Attributes',
+ labelKey: 'label',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'full_name', label: 'Full Name' },
+ { key: 'label', label: 'Label' },
+ { key: 'data_type', label: 'Data Type' },
+ { key: 'model', label: 'Model' },
+ { key: 'custom', label: 'Custom', format: 'boolean' },
+ { key: 'api_writable', label: 'Writable Through API', format: 'boolean' },
+ { key: 'options', label: 'Options' },
+ ],
+ },
+ ],
+};
+
+export const searchArticlesOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'items',
+ label: 'Articles',
+ labelKey: 'title',
+ listItems: [
+ { key: 'id', label: 'Article ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ { key: 'body', label: 'Body', format: 'html' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'state', label: 'State' },
+ { key: 'updated_at', label: 'Updated At', description: UNIX },
+ ],
+ },
+ { key: 'total_count', label: 'Total Matches', format: 'number' },
+ ],
+};
+
+export const contactTriggerOutputSchema: OutputSchema = { fields: contactWebhookFields };
+
+export const leadConvertedTriggerOutputSchema: OutputSchema = {
+ fields: [
+ ...contactWebhookFields,
+ { key: 'merged_from', label: 'Merged From (Lead)', children: [{ key: 'id', label: 'Lead ID' }] },
+ ],
+};
+
+export const contactTagTriggerOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'tag', label: 'Tag', children: tagFields },
+ { key: 'contact', label: 'Contact', children: contactWebhookFields },
+ ],
+};
+
+const ISO = 'ISO 8601 date and time.';
+
+const companyWebhookFields: OutputSchema['fields'] = [
+ ...companyFields
+ .filter((field) => field.key !== 'tags')
+ .map((field) => (field.description === UNIX ? { ...field, description: ISO } : field)),
+ { key: 'tag_ids', label: 'Tag IDs' },
+];
+
+const ticketWebhookFields: OutputSchema['fields'] = [
+ ...ticketFields
+ .filter((field) => !['ticket_state', 'ticket_state_internal_label', 'ticket_state_external_label'].includes(field.key))
+ .flatMap((field) =>
+ field.key === 'category'
+ ? [
+ field,
+ {
+ key: 'ticket_state',
+ label: 'State',
+ children: [
+ { key: 'id', label: 'State ID' },
+ { key: 'category', label: 'State Category', description: 'submitted, in_progress, waiting_on_customer or resolved.' },
+ { key: 'internal_label', label: 'Internal Label' },
+ { key: 'external_label', label: 'Customer Label' },
+ ],
+ },
+ ]
+ : [field],
+ ),
+ { key: 'previous_ticket_state_id', label: 'Previous State ID' },
+];
+
+export const companyTriggerOutputSchema: OutputSchema = { fields: companyWebhookFields };
+
+export const conversationPartTaggedTriggerOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'created_at', label: 'Tagged At', description: UNIX },
+ { key: 'tag', label: 'Tag', children: tagFields },
+ { key: 'conversation', label: 'Conversation', children: conversationFields },
+ ],
+};
+
+export const conversationTriggerOutputSchema: OutputSchema = { fields: conversationFields };
+
+export const conversationEnvelopeTriggerOutputSchema: OutputSchema = {
+ fields: envelopeFields([
+ ...conversationFields,
+ {
+ key: 'conversation_parts',
+ label: 'New Parts',
+ children: [{ key: 'conversation_parts', label: 'Parts', labelKey: 'part_type', listItems: conversationPartFields }],
+ },
+ ]),
+};
+
+export const ticketTriggerOutputSchema: OutputSchema = { fields: ticketWebhookFields };
diff --git a/packages/pieces/community/intercom/src/lib/triggers/contact-replied.ts b/packages/pieces/community/intercom/src/lib/triggers/contact-replied.ts
index 13be985801a..1f8c4f58d91 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/contact-replied.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/contact-replied.ts
@@ -1,6 +1,7 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient, TriggerPayload } from '../common';
+import { conversationTriggerOutputSchema } from '../output-schemas';
export const contactRepliedTrigger = createTrigger({
name: 'contactReplied',
@@ -12,9 +13,10 @@ export const contactRepliedTrigger = createTrigger({
},
props: {},
auth: intercomAuth,
+ outputSchema: conversationTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const contactRepliedTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.list({ per_page: 10 });
diff --git a/packages/pieces/community/intercom/src/lib/triggers/contact-updated.ts b/packages/pieces/community/intercom/src/lib/triggers/contact-updated.ts
index 5e000b1d9f4..2c43265d001 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/contact-updated.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/contact-updated.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { contactTriggerOutputSchema } from '../output-schemas';
export const contactUpdatedTrigger = createTrigger({
auth: intercomAuth,
@@ -26,9 +27,10 @@ export const contactUpdatedTrigger = createTrigger({
},
}),
},
+ outputSchema: contactTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -42,11 +44,11 @@ export const contactUpdatedTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.search({
query:{
diff --git a/packages/pieces/community/intercom/src/lib/triggers/conversation-assigned.ts b/packages/pieces/community/intercom/src/lib/triggers/conversation-assigned.ts
index f36f5ab4f40..9d25c496a83 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/conversation-assigned.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/conversation-assigned.ts
@@ -1,6 +1,8 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
+import { conversationEnvelopeTriggerOutputSchema } from '../output-schemas';
+import { conversationEnvelopeSample, recentConversationEnvelopes } from '../common/webhook-samples';
export const conversationAssigned = createTrigger({
name: 'conversationAssigned',
@@ -8,14 +10,15 @@ export const conversationAssigned = createTrigger({
displayName: 'Conversation assigned to any Intercom admin',
description: 'Triggers when a conversation is assigned to an admin',
aiMetadata: {
- description: 'Fires when a conversation is assigned to an Intercom admin or teammate, whether manually or via routing rules. Outputs the conversation object including its admin_assignee_id and team_assignee_id.',
+ description: 'Fires when a conversation is assigned to an Intercom admin or teammate, whether manually or via routing rules. Outputs the whole webhook notification (id, topic, created_at); the conversation, with the new parts, is under data.item.',
},
props: {},
- sampleData: undefined,
+ sampleData: conversationEnvelopeSample('conversation.admin.assigned'),
auth: intercomAuth,
+ outputSchema: conversationEnvelopeTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -27,8 +30,11 @@ export const conversationAssigned = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ return recentConversationEnvelopes({ auth: context.auth, topic: 'conversation.admin.assigned' });
},
async run(context) {
return [context.payload.body];
diff --git a/packages/pieces/community/intercom/src/lib/triggers/conversation-closed.ts b/packages/pieces/community/intercom/src/lib/triggers/conversation-closed.ts
index 19d377fbc94..7fc47bbc137 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/conversation-closed.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/conversation-closed.ts
@@ -1,6 +1,7 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient, TriggerPayload } from '../common';
+import { conversationTriggerOutputSchema } from '../output-schemas';
export const conversationClosedTrigger = createTrigger({
name: 'conversationClosed',
@@ -12,9 +13,10 @@ export const conversationClosedTrigger = createTrigger({
},
props: {},
auth: intercomAuth,
+ outputSchema: conversationTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const conversationClosedTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/triggers/conversation-part-tagged.ts b/packages/pieces/community/intercom/src/lib/triggers/conversation-part-tagged.ts
index b9c5e82ad17..34cc88cebb9 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/conversation-part-tagged.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/conversation-part-tagged.ts
@@ -5,6 +5,8 @@ import {
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
import { tagIdProp } from '../common/props';
+import { CONVERSATION_PART_TAG_SAMPLE } from '../common/webhook-samples';
+import { conversationPartTaggedTriggerOutputSchema } from '../output-schemas';
export const conversationPartTagged = createTrigger({
name: 'conversationPartTagged',
@@ -17,10 +19,11 @@ export const conversationPartTagged = createTrigger({
props: {
tagId: tagIdProp('Tag', false),
},
+ outputSchema: conversationPartTaggedTriggerOutputSchema,
auth: intercomAuth,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -32,9 +35,9 @@ export const conversationPartTagged = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
- },
+ async onDisable() {
+ return;
+ },
async run(context) {
const tag = context.propsValue.tagId;
@@ -44,7 +47,7 @@ export const conversationPartTagged = createTrigger({
}
return [];
},
- sampleData: undefined
+ sampleData: CONVERSATION_PART_TAG_SAMPLE,
});
type IntercomPayloadBodyType = {
diff --git a/packages/pieces/community/intercom/src/lib/triggers/conversation-rated.ts b/packages/pieces/community/intercom/src/lib/triggers/conversation-rated.ts
index ff9d6726a94..d73e6ac6501 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/conversation-rated.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/conversation-rated.ts
@@ -1,6 +1,7 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient, TriggerPayload } from '../common';
+import { conversationTriggerOutputSchema } from '../output-schemas';
export const conversationRated = createTrigger({
name: 'conversationRated',
@@ -12,9 +13,10 @@ export const conversationRated = createTrigger({
},
props: {},
auth: intercomAuth,
+ outputSchema: conversationTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const conversationRated = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.list({ per_page: 10 });
diff --git a/packages/pieces/community/intercom/src/lib/triggers/conversation-snoozed.ts b/packages/pieces/community/intercom/src/lib/triggers/conversation-snoozed.ts
index 5038f6ccb14..a24261b006b 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/conversation-snoozed.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/conversation-snoozed.ts
@@ -1,22 +1,24 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
+import { conversationEnvelopeTriggerOutputSchema } from '../output-schemas';
+import { conversationEnvelopeSample, recentConversationEnvelopes } from '../common/webhook-samples';
export const conversationSnoozed = createTrigger({
- // auth: check https://www.activepieces.com/docs/developers/piece-reference/authentication,
name: 'conversationSnoozed',
classification: 'READ',
displayName: 'Conversation snoozed',
description: 'Triggers when a conversation is snoozed',
aiMetadata: {
- description: 'Fires when a conversation is snoozed in Intercom, meaning an admin temporarily pauses it until a chosen time. Outputs the snoozed conversation object, including its snoozed_until time.',
+ description: 'Fires when a conversation is snoozed in Intercom, meaning an admin temporarily pauses it until a chosen time. Outputs the whole webhook notification (id, topic, created_at); the conversation, with the new parts, is under data.item.',
},
props: {},
- sampleData: undefined,
+ sampleData: conversationEnvelopeSample('conversation.admin.snoozed'),
auth: intercomAuth,
+ outputSchema: conversationEnvelopeTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -28,8 +30,11 @@ export const conversationSnoozed = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ return recentConversationEnvelopes({ auth: context.auth, topic: 'conversation.admin.snoozed' });
},
async run(context) {
return [context.payload.body];
diff --git a/packages/pieces/community/intercom/src/lib/triggers/conversation-unsnoozed.ts b/packages/pieces/community/intercom/src/lib/triggers/conversation-unsnoozed.ts
index b81e5966e05..0b3a7b16979 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/conversation-unsnoozed.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/conversation-unsnoozed.ts
@@ -1,22 +1,24 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
+import { conversationEnvelopeTriggerOutputSchema } from '../output-schemas';
+import { conversationEnvelopeSample, recentConversationEnvelopes } from '../common/webhook-samples';
export const conversationUnsnoozed = createTrigger({
- // auth: check https://www.activepieces.com/docs/developers/piece-reference/authentication,
name: 'conversationUnsnoozed',
classification: 'READ',
displayName: 'Conversation unsnoozed',
description: 'Triggers when a conversation is unsnoozed',
aiMetadata: {
- description: 'Fires when a previously snoozed conversation is unsnoozed in Intercom, either because its snooze period elapsed or an admin reopened it manually, returning it to an active state. Outputs the conversation object that was unsnoozed.',
+ description: 'Fires when a previously snoozed conversation is unsnoozed in Intercom, either because its snooze period elapsed or an admin reopened it manually, returning it to an active state. Outputs the whole webhook notification (id, topic, created_at); the conversation, with the new parts, is under data.item.',
},
props: {},
- sampleData: undefined,
+ sampleData: conversationEnvelopeSample('conversation.admin.unsnoozed'),
auth: intercomAuth,
+ outputSchema: conversationEnvelopeTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -28,8 +30,11 @@ export const conversationUnsnoozed = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ return recentConversationEnvelopes({ auth: context.auth, topic: 'conversation.admin.unsnoozed' });
},
async run(context) {
return [context.payload.body];
diff --git a/packages/pieces/community/intercom/src/lib/triggers/lead-added-email.ts b/packages/pieces/community/intercom/src/lib/triggers/lead-added-email.ts
index f6bd89b0b13..6c651af4af3 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/lead-added-email.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/lead-added-email.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { contactTriggerOutputSchema } from '../output-schemas';
export const leadAddedEmailTrigger = createTrigger({
auth: intercomAuth,
@@ -12,9 +13,10 @@ export const leadAddedEmailTrigger = createTrigger({
description: 'Fires when a lead provides an email address in Intercom for the first time, capturing the moment an anonymous or partially identified lead becomes contactable by email. Outputs the lead contact object including the newly added email.',
},
props: {},
+ outputSchema: contactTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const leadAddedEmailTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/triggers/lead-converted-to-user.ts b/packages/pieces/community/intercom/src/lib/triggers/lead-converted-to-user.ts
index 88adc5c010e..c1cd584c3f6 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/lead-converted-to-user.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/lead-converted-to-user.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { leadConvertedTriggerOutputSchema } from '../output-schemas';
export const leadConvertedToUserTrigger = createTrigger({
auth: intercomAuth,
@@ -9,12 +10,13 @@ export const leadConvertedToUserTrigger = createTrigger({
displayName: 'Lead Converted To User',
description: 'Triggers when a lead is converted to a user.',
aiMetadata: {
- description: 'Fires when a lead is converted into a user in Intercom, typically when the lead signs up or is otherwise identified and promoted from role "lead" to role "user". Outputs the resulting user contact object.',
+ description: 'Fires when a lead becomes a user in Intercom: when the lead signs up (contact.lead.signed_up) and when a lead is merged into a user (contact.merged). Outputs the resulting user contact; merge events also carry merged_from with the lead ID.',
},
props: {},
+ outputSchema: leadConvertedTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -22,15 +24,15 @@ export const leadConvertedToUserTrigger = createTrigger({
}
context.app.createListeners({
- events: ['contact.merged'],
+ events: ['contact.lead.signed_up', 'contact.merged'],
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
- },
+ async onDisable() {
+ return;
+ },
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.search({
query:{
diff --git a/packages/pieces/community/intercom/src/lib/triggers/new-company.ts b/packages/pieces/community/intercom/src/lib/triggers/new-company.ts
index 7be221a64f0..e6647cd2ab9 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/new-company.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/new-company.ts
@@ -1,6 +1,8 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { companyTriggerOutputSchema } from '../output-schemas';
+import { COMPANY_SAMPLE } from '../common/webhook-samples';
export const newCompanyTrigger = createTrigger({
auth: intercomAuth,
@@ -12,9 +14,10 @@ export const newCompanyTrigger = createTrigger({
description: 'Fires when a new company record is created in Intercom. Companies group related contacts under a single organization. Outputs the newly created company object with its attributes.',
},
props: {},
+ outputSchema: companyTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +29,11 @@ export const newCompanyTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.companies.list({ per_page: 5 });
@@ -40,101 +43,5 @@ export const newCompanyTrigger = createTrigger({
const payload = context.payload.body as TriggerPayload;
return [payload.data.item];
},
- sampleData: {
- type: 'contact',
- id: '67a9b9dfcc14109e073fbe19',
- workspace_id: 'nzekhfwb',
- external_id: '5b803f65-bcec-4198-b4f4-a0588454b537',
- role: 'lead',
- email: '[email protected]',
- phone: null,
- name: 'John Doe',
- avatar: null,
- owner_id: null,
- social_profiles: {
- type: 'list',
- data: [],
- },
- has_hard_bounced: false,
- marked_email_as_spam: false,
- unsubscribed_from_emails: false,
- created_at: '2025-02-10T08:33:35.910+00:00',
- updated_at: '2025-02-10T08:33:35.907+00:00',
- signed_up_at: null,
- last_seen_at: null,
- last_replied_at: null,
- last_contacted_at: null,
- last_email_opened_at: null,
- last_email_clicked_at: null,
- language_override: null,
- browser: null,
- browser_version: null,
- browser_language: null,
- os: null,
- location: {
- type: 'location',
- country: null,
- region: null,
- city: null,
- country_code: null,
- continent_code: null,
- },
- android_app_name: null,
- android_app_version: null,
- android_device: null,
- android_os_version: null,
- android_sdk_version: null,
- android_last_seen_at: null,
- ios_app_name: null,
- ios_app_version: null,
- ios_device: null,
- ios_os_version: null,
- ios_sdk_version: null,
- ios_last_seen_at: null,
- custom_attributes: {},
- tags: {
- type: 'list',
- data: [],
- url: '/contacts/67a9b9dfcc14109e073fbe19/tags',
- total_count: 0,
- has_more: false,
- },
- notes: {
- type: 'list',
- data: [],
- url: '/contacts/67a9b9dfcc14109e073fbe19/notes',
- total_count: 0,
- has_more: false,
- },
- companies: {
- type: 'list',
- data: [],
- url: '/contacts/67a9b9dfcc14109e073fbe19/companies',
- total_count: 0,
- has_more: false,
- },
- opted_out_subscription_types: {
- type: 'list',
- data: [],
- url: '/contacts/67a9b9dfcc14109e073fbe19/subscriptions',
- total_count: 0,
- has_more: false,
- },
- opted_in_subscription_types: {
- type: 'list',
- data: [],
- url: '/contacts/67a9b9dfcc14109e073fbe19/subscriptions',
- total_count: 0,
- has_more: false,
- },
- utm_campaign: null,
- utm_content: null,
- utm_medium: null,
- utm_source: null,
- utm_term: null,
- referrer: null,
- sms_consent: false,
- unsubscribed_from_sms: false,
- enabled_push_messaging: null,
- },
+ sampleData: COMPANY_SAMPLE,
});
diff --git a/packages/pieces/community/intercom/src/lib/triggers/new-conversation-from-user.ts b/packages/pieces/community/intercom/src/lib/triggers/new-conversation-from-user.ts
index 0bfab00064d..437a4a92be0 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/new-conversation-from-user.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/new-conversation-from-user.ts
@@ -1,6 +1,7 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient, TriggerPayload } from '../common';
+import { conversationTriggerOutputSchema } from '../output-schemas';
export const newConversationFromUser = createTrigger({
name: 'newConversationFromUser',
@@ -12,9 +13,10 @@ export const newConversationFromUser = createTrigger({
},
props: {},
auth: intercomAuth,
+ outputSchema: conversationTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const newConversationFromUser = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.conversations.list({ per_page: 10 });
diff --git a/packages/pieces/community/intercom/src/lib/triggers/new-lead.ts b/packages/pieces/community/intercom/src/lib/triggers/new-lead.ts
index 07277073092..ed9d6b1353c 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/new-lead.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/new-lead.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { contactTriggerOutputSchema } from '../output-schemas';
export const newLeadTrigger = createTrigger({
auth: intercomAuth,
@@ -12,9 +13,10 @@ export const newLeadTrigger = createTrigger({
description: 'Fires when a new lead is created in Intercom. A lead is an unidentified or not-yet-signed-up contact (role "lead"), as opposed to a user. Outputs the newly created lead contact object with its attributes.',
},
props: {},
+ outputSchema: contactTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const newLeadTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/triggers/new-ticket.ts b/packages/pieces/community/intercom/src/lib/triggers/new-ticket.ts
index b813ab3e21e..bfc52bd472e 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/new-ticket.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/new-ticket.ts
@@ -1,6 +1,8 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { ticketTriggerOutputSchema } from '../output-schemas';
+import { toWebhookTicketShape } from '../common/ticket-attributes';
export const newTicketTrigger = createTrigger({
auth: intercomAuth,
@@ -12,9 +14,10 @@ export const newTicketTrigger = createTrigger({
description: 'Fires when a new ticket is created in Intercom. Tickets track structured work items such as support requests or tasks. Outputs the newly created ticket object, including its type, state, and custom attributes.',
},
props: {},
+ outputSchema: ticketTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +29,11 @@ export const newTicketTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.tickets.search({
query: {
@@ -41,7 +44,7 @@ export const newTicketTrigger = createTrigger({
pagination: { per_page: 5 },
});
- return response.data;
+ return response.data.map(toWebhookTicketShape);
},
async run(context) {
const payload = context.payload.body as TriggerPayload;
@@ -61,7 +64,13 @@ export const newTicketTrigger = createTrigger({
'date time': null,
files: [],
},
- ticket_state: 'in_progress',
+ ticket_state: {
+ type: 'ticket_state',
+ id: '9744094',
+ category: 'in_progress',
+ internal_label: 'In progress',
+ external_label: 'In progress',
+ },
ticket_type: {
type: 'ticket_type',
id: '1',
diff --git a/packages/pieces/community/intercom/src/lib/triggers/new-unsubscription.ts b/packages/pieces/community/intercom/src/lib/triggers/new-unsubscription.ts
index 92d4396aa12..f7b70c4985c 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/new-unsubscription.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/new-unsubscription.ts
@@ -10,12 +10,12 @@ export const newUnsubscriptionTrigger = createTrigger({
description: 'Triggers when a contact unsubscribes from your emails.',
aiMetadata: {
description:
- 'Fires when a contact unsubscribes from email in Intercom. Outputs the contact that unsubscribed.',
+ 'Fires when a contact unsubscribes from email in Intercom. Outputs the contact that unsubscribed.',
},
props: {},
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -27,11 +27,11 @@ export const newUnsubscriptionTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/triggers/new-user.ts b/packages/pieces/community/intercom/src/lib/triggers/new-user.ts
index 9527032ac0e..a21e78d15fb 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/new-user.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/new-user.ts
@@ -1,6 +1,7 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { contactTriggerOutputSchema } from '../output-schemas';
export const newUserTrigger = createTrigger({
auth: intercomAuth,
@@ -12,9 +13,10 @@ export const newUserTrigger = createTrigger({
description: 'Fires when a new user is created in Intercom. A user is an identified, signed-up contact (role "user"), as opposed to a lead. Outputs the newly created user contact object with its attributes.',
},
props: {},
+ outputSchema: contactTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -26,11 +28,11 @@ export const newUserTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.contacts.search({
query: {
diff --git a/packages/pieces/community/intercom/src/lib/triggers/note-added-to-conversation.ts b/packages/pieces/community/intercom/src/lib/triggers/note-added-to-conversation.ts
index db2f4d06db3..754cdef81d3 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/note-added-to-conversation.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/note-added-to-conversation.ts
@@ -2,27 +2,30 @@ import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-f
import { stripHtml } from 'string-strip-html';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
+import { conversationEnvelopeTriggerOutputSchema } from '../output-schemas';
+import { conversationEnvelopeSample, recentConversationEnvelopes } from '../common/webhook-samples';
export const noteAddedToConversation = createTrigger({
- // auth: check https://www.activepieces.com/docs/developers/piece-reference/authentication,
name: 'noteAddedToConversation',
classification: 'READ',
displayName: 'Note added to conversation',
description: 'Triggers when a note is added to a conversation',
aiMetadata: {
- description: 'Fires when an internal note is added to a conversation in Intercom. Notes are private remarks visible only to admins and teammates, not to the contact. An optional keyword input filters to notes containing that text. Outputs the conversation object reflecting the added note.',
+ description: 'Fires when an internal note is added to a conversation in Intercom. Notes are private remarks visible only to admins and teammates, not to the contact. An optional keyword keeps only notes that contain that exact word (whole word, case-sensitive). Outputs the whole webhook notification (id, topic, created_at); the conversation, with the new parts, is under data.item.',
},
props: {
keyword: Property.ShortText({
displayName: 'Keyword (optional)',
+ description: 'Only notes containing this exact word fire the flow. Matching is whole-word and case-sensitive.',
required: false,
}),
},
- sampleData: undefined,
+ sampleData: conversationEnvelopeSample('conversation.admin.noted'),
auth: intercomAuth,
+ outputSchema: conversationEnvelopeTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
@@ -35,8 +38,11 @@ export const noteAddedToConversation = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ return recentConversationEnvelopes({ auth: context.auth, topic: 'conversation.admin.noted' });
},
async run(context) {
const keyword = context.propsValue.keyword;
diff --git a/packages/pieces/community/intercom/src/lib/triggers/reply-from-admin.ts b/packages/pieces/community/intercom/src/lib/triggers/reply-from-admin.ts
index 5e5c29f5325..b55ffb4ce6b 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/reply-from-admin.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/reply-from-admin.ts
@@ -1,22 +1,24 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
+import { conversationEnvelopeTriggerOutputSchema } from '../output-schemas';
+import { conversationEnvelopeSample, recentConversationEnvelopes } from '../common/webhook-samples';
export const replyFromAdmin = createTrigger({
- // auth: check https://www.activepieces.com/docs/developers/piece-reference/authentication,
name: 'replyFromAdmin',
classification: 'READ',
displayName: 'Reply from an Intercom admin',
description: 'Triggers when a reply is received from an Intercom admin (not a user or lead)',
aiMetadata: {
- description: 'Fires when an Intercom admin or teammate replies to a conversation. Does not fire for replies sent by a user or lead. Outputs the conversation object reflecting the admin reply.',
+ description: 'Fires when an Intercom admin or teammate replies to a conversation. Does not fire for replies sent by a user or lead. Outputs the whole webhook notification (id, topic, created_at); the conversation, with the new parts, is under data.item.',
},
props: {},
- sampleData: undefined,
+ sampleData: conversationEnvelopeSample('conversation.admin.replied'),
auth: intercomAuth,
+ outputSchema: conversationEnvelopeTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -27,8 +29,11 @@ export const replyFromAdmin = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ return recentConversationEnvelopes({ auth: context.auth, topic: 'conversation.admin.replied' });
},
async run(context) {
return [context.payload.body];
diff --git a/packages/pieces/community/intercom/src/lib/triggers/reply-from-user.ts b/packages/pieces/community/intercom/src/lib/triggers/reply-from-user.ts
index a01eddb4f57..c1749cf7ca8 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/reply-from-user.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/reply-from-user.ts
@@ -1,22 +1,24 @@
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
+import { conversationEnvelopeTriggerOutputSchema } from '../output-schemas';
+import { conversationEnvelopeSample, recentConversationEnvelopes } from '../common/webhook-samples';
export const replyFromUser = createTrigger({
- // auth: check https://www.activepieces.com/docs/developers/piece-reference/authentication,
name: 'replyFromUser',
classification: 'READ',
displayName: 'Reply from a user or lead',
description: 'Triggers when a reply is received from a user or lead (not an admin)',
aiMetadata: {
- description: 'Fires when a user or lead replies to a conversation in Intercom. Does not fire for replies sent by an admin or teammate. Outputs the conversation object reflecting the contact reply.',
+ description: 'Fires when a user or lead replies to a conversation in Intercom. Does not fire for replies sent by an admin or teammate. Outputs the whole webhook notification (id, topic, created_at); the conversation, with the new parts, is under data.item.',
},
props: {},
- sampleData: undefined,
+ sampleData: conversationEnvelopeSample('conversation.user.replied'),
auth: intercomAuth,
+ outputSchema: conversationEnvelopeTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -27,8 +29,11 @@ export const replyFromUser = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
+ },
+ async test(context) {
+ return recentConversationEnvelopes({ auth: context.auth, topic: 'conversation.user.replied' });
},
async run(context) {
return [context.payload.body];
diff --git a/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-lead.ts b/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-lead.ts
index 520371e44fe..130e203fa51 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-lead.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-lead.ts
@@ -2,6 +2,7 @@ import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
import { tagIdProp } from '../common/props';
+import { contactTagTriggerOutputSchema } from '../output-schemas';
export const tagAddedToLeadTrigger = createTrigger({
name: 'tag-added-to-lead',
@@ -15,9 +16,10 @@ export const tagAddedToLeadTrigger = createTrigger({
tagId: tagIdProp('Tag', false),
},
auth: intercomAuth,
+ outputSchema: contactTagTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -29,11 +31,11 @@ export const tagAddedToLeadTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
if (context.propsValue.tagId) {
const response = await client.contacts.search({
diff --git a/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-user.ts b/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-user.ts
index 5fd414de558..cec20e8efed 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-user.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/tag-added-to-user.ts
@@ -2,6 +2,7 @@ import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomAuth } from '../auth';
import { intercomClient } from '../common';
import { tagIdProp } from '../common/props';
+import { contactTagTriggerOutputSchema } from '../output-schemas';
export const tagAddedToUserTrigger = createTrigger({
name: 'tag-added-to-user',
@@ -15,9 +16,10 @@ export const tagAddedToUserTrigger = createTrigger({
tagId: tagIdProp('Tag', false),
},
auth: intercomAuth,
+ outputSchema: contactTagTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -29,11 +31,11 @@ export const tagAddedToUserTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
if (context.propsValue.tagId) {
const response = await client.contacts.search({
diff --git a/packages/pieces/community/intercom/src/lib/triggers/updated-ticket.ts b/packages/pieces/community/intercom/src/lib/triggers/updated-ticket.ts
index 83cf850ecb3..f521430106c 100644
--- a/packages/pieces/community/intercom/src/lib/triggers/updated-ticket.ts
+++ b/packages/pieces/community/intercom/src/lib/triggers/updated-ticket.ts
@@ -1,6 +1,8 @@
import { intercomAuth } from '../auth';
import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { intercomClient, TriggerPayload } from '../common';
+import { ticketTriggerOutputSchema } from '../output-schemas';
+import { toWebhookTicketShape } from '../common/ticket-attributes';
export const updatedTicketTrigger = createTrigger({
auth: intercomAuth,
@@ -13,9 +15,10 @@ export const updatedTicketTrigger = createTrigger({
'Fires when an existing Intercom ticket changes, covering both ticket state transitions and ticket attribute updates. Outputs the updated ticket object.',
},
props: {},
+ outputSchema: ticketTriggerOutputSchema,
type: TriggerStrategy.APP_WEBHOOK,
async onEnable(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.admins.identify();
if (!response.app?.id_code) {
@@ -27,11 +30,11 @@ export const updatedTicketTrigger = createTrigger({
identifierValue: response['app']['id_code'],
});
},
- async onDisable(context) {
- // implement webhook deletion logic
+ async onDisable() {
+ return;
},
async test(context) {
- const client = intercomClient(context.auth);
+ const client = await intercomClient(context.auth);
const response = await client.tickets.search({
query: {
@@ -42,7 +45,7 @@ export const updatedTicketTrigger = createTrigger({
pagination: { per_page: 5 },
});
- return response.data;
+ return response.data.map(toWebhookTicketShape);
},
async run(context) {
const payload = context.payload.body as TriggerPayload;
@@ -56,9 +59,14 @@ export const updatedTicketTrigger = createTrigger({
_default_title_: 'Cannot log in',
_default_description_: 'Customer is unable to log in to the dashboard.',
},
- ticket_state: 'in_progress',
- ticket_state_internal_label: 'In progress',
- ticket_state_external_label: 'In progress',
+ ticket_state: {
+ type: 'ticket_state',
+ id: '9744094',
+ category: 'in_progress',
+ internal_label: 'In progress',
+ external_label: 'In progress',
+ },
+ previous_ticket_state_id: '9744093',
open: true,
category: 'Customer',
created_at: 1739105560,
diff --git a/packages/pieces/community/intercom/test/client.test.ts b/packages/pieces/community/intercom/test/client.test.ts
new file mode 100644
index 00000000000..a152e8d7683
--- /dev/null
+++ b/packages/pieces/community/intercom/test/client.test.ts
@@ -0,0 +1,272 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { intercomClient } from '../src/lib/common';
+import {
+ intercomHttpInternals,
+ encodePath,
+ getIntercomBaseUrl,
+ intercomRequest,
+ IntercomApiError,
+} from '../src/lib/common/client';
+import { intercom } from '../src/index';
+import { intercomAuth } from '../src/lib/auth';
+import { callWith, customAuth, oauthAuth, stubIntercom } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('region allowlist', () => {
+ test.each([
+ ['intercom', 'https://api.intercom.io'],
+ ['eu.intercom', 'https://api.eu.intercom.io'],
+ ['au.intercom', 'https://api.au.intercom.io'],
+ [undefined, 'https://api.intercom.io'],
+ ['', 'https://api.intercom.io'],
+ ])('%s maps to %s', (region, url) => {
+ expect(getIntercomBaseUrl(region)).toBe(url);
+ });
+
+ test.each(['evil.com/#', 'intercom.io.evil', 'eu.intercom.evil.io/x', 'EU.intercom', 'constructor', 'toString'])(
+ 'rejects lookalike region %s before any request',
+ async (region) => {
+ const seen = stubIntercom([]);
+ expect(() => getIntercomBaseUrl(region)).toThrow('Unsupported Intercom region');
+ await expect(
+ intercomRequest({ auth: customAuth(region), method: HttpMethod.GET, path: ['me'], operation: 'x' }),
+ ).rejects.toThrow('Unsupported Intercom region');
+ expect(seen).toHaveLength(0);
+ },
+ );
+
+ test('custom API call base URL uses the allowlist', async () => {
+ const action = intercom.actions()['custom_api_call'];
+ const urlProps: (input: { auth: unknown }, ctx: unknown) => Promise<Record<string, { defaultValue?: unknown }>> =
+ Reflect.get(action.props['url'], 'props');
+ const fields = await urlProps({ auth: customAuth('eu.intercom') }, {});
+ expect(fields['url'].defaultValue).toBe('https://api.eu.intercom.io');
+ await expect(Promise.resolve().then(() => urlProps({ auth: customAuth('evil.com/#') }, {}))).rejects.toThrow(
+ 'Unsupported Intercom region',
+ );
+ });
+});
+
+describe('intercomRequest', () => {
+ test('sends bearer token, Intercom-Version 2.11, JSON accept and the TLS dispatcher', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/contacts/abc', reply: { body: { id: 'abc' } } }]);
+ const body = await intercomRequest({
+ auth: customAuth('eu.intercom'),
+ method: HttpMethod.GET,
+ path: ['contacts', 'abc'],
+ operation: 'get the contact',
+ });
+ expect(body).toEqual({ id: 'abc' });
+ expect(seen[0].url).toBe('https://api.eu.intercom.io/contacts/abc');
+ expect(seen[0].headers.get('authorization')).toBe('Bearer TOKEN-123');
+ expect(seen[0].headers.get('intercom-version')).toBe('2.11');
+ expect(seen[0].headers.get('accept')).toBe('application/json');
+ expect(seen[0].dispatcher).toBeDefined();
+ });
+
+ test('oauth connection without region goes to the US host with the oauth token', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/me', reply: { body: { id: '1' } } }]);
+ await intercomRequest({ auth: oauthAuth(), method: HttpMethod.GET, path: ['me'], operation: 'x' });
+ expect(seen[0].url).toBe('https://api.intercom.io/me');
+ expect(seen[0].headers.get('authorization')).toBe('Bearer OAUTH-TOKEN');
+ });
+
+ test('encodes path segments and refuses empty or dot segments', () => {
+ expect(encodePath(['contacts', 'a/b?c#d'])).toBe('contacts/a%2Fb%3Fc%23d');
+ expect(() => encodePath(['contacts', ''])).toThrow('empty or invalid');
+ expect(() => encodePath(['contacts', '..'])).toThrow('empty or invalid');
+ expect(() => encodePath(['contacts', ' . '])).toThrow('empty or invalid');
+ });
+
+ test('error carries status, code and responseBody, never body', async () => {
+ stubIntercom([
+ {
+ method: 'GET',
+ path: '/tickets/9',
+ reply: { status: 404, body: { type: 'error.list', errors: [{ code: 'ticket_not_found', message: 'Ticket not found' }] } },
+ },
+ ]);
+ const error = await intercomRequest({
+ auth: customAuth(),
+ method: HttpMethod.GET,
+ path: ['tickets', '9'],
+ operation: 'get the ticket',
+ }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(IntercomApiError);
+ if (!(error instanceof IntercomApiError)) {
+ throw new Error('expected an IntercomApiError');
+ }
+ const apiError = error;
+ expect(apiError.message).toBe('Intercom get the ticket failed (404): Ticket not found');
+ expect(apiError.status).toBe(404);
+ expect(apiError.code).toBe('ticket_not_found');
+ expect(apiError.responseBody).toEqual({ type: 'error.list', errors: [{ code: 'ticket_not_found', message: 'Ticket not found' }] });
+ expect('body' in apiError).toBe(false);
+ });
+
+ test('long vendor messages are cut to 500 characters and 403 adds a permission hint', async () => {
+ stubIntercom([
+ { method: 'GET', path: '/admins', reply: { status: 403, body: { errors: [{ code: 'forbidden', message: 'x'.repeat(900) }] } } },
+ ]);
+ const error = await intercomRequest({
+ auth: customAuth(),
+ method: HttpMethod.GET,
+ path: ['admins'],
+ operation: 'list admins',
+ }).catch((e: unknown) => e);
+ if (!(error instanceof Error)) {
+ throw new Error('expected an Error');
+ }
+ expect(error.message).toContain(`${'x'.repeat(500)}...`);
+ expect(error.message).not.toContain('x'.repeat(501));
+ expect(error.message).toContain('lacks the permission');
+ });
+
+ test('a 403 action_forbidden business rule gets no permission hint', async () => {
+ stubIntercom([
+ {
+ method: 'POST',
+ path: '/messages',
+ reply: {
+ status: 403,
+ body: { errors: [{ code: 'action_forbidden', message: 'One or more users are unsubscribed from emails' }] },
+ },
+ },
+ ]);
+ const error = await intercomRequest({
+ auth: customAuth(),
+ method: HttpMethod.POST,
+ path: ['messages'],
+ body: {},
+ operation: 'send the message',
+ }).catch((e: unknown) => e);
+ if (!(error instanceof Error)) {
+ throw new Error('expected an Error');
+ }
+ expect(error.message).toBe('Intercom send the message failed (403): One or more users are unsubscribed from emails');
+ });
+
+ test('POST is never retried on 5xx', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/conversations/1/reply', reply: { status: 502, body: { errors: [{ code: 'bad_gateway' }] } } }]);
+ await expect(
+ intercomRequest({
+ auth: customAuth(),
+ method: HttpMethod.POST,
+ path: ['conversations', '1', 'reply'],
+ body: { body: 'hi' },
+ operation: 'reply',
+ }),
+ ).rejects.toThrow('(502)');
+ expect(seen).toHaveLength(1);
+ });
+
+ test('GET is retried on 503 and every method on 429, at most twice', async () => {
+ const getSeen = stubIntercom([
+ { method: 'GET', path: '/tags', reply: (_r, all) => (all.length < 3 ? { status: 503, body: {} } : { body: { data: [] } }) },
+ ]);
+ await intercomRequest({ auth: customAuth(), method: HttpMethod.GET, path: ['tags'], operation: 'list tags' });
+ expect(getSeen).toHaveLength(3);
+ vi.unstubAllGlobals();
+ const postSeen = stubIntercom([{ method: 'POST', path: '/tags', reply: { status: 429, body: {} } }]);
+ await expect(
+ intercomRequest({ auth: customAuth(), method: HttpMethod.POST, path: ['tags'], body: { name: 'a' }, operation: 'create tag' }),
+ ).rejects.toThrow('(429)');
+ expect(postSeen).toHaveLength(3);
+ });
+});
+
+describe('SDK client', () => {
+ test('routes SDK calls through the same HTTP layer, with 2.11 and no POST retry', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/contacts/c1/notes', reply: { status: 500, body: { errors: [{ code: 'server_error' }] } } }]);
+ const client = await intercomClient(customAuth('au.intercom'));
+ await expect(client.notes.create({ contact_id: 'c1', body: 'hello' })).rejects.toThrow('500');
+ expect(seen).toHaveLength(1);
+ expect(seen[0].url).toBe('https://api.au.intercom.io/contacts/c1/notes');
+ expect(seen[0].headers.get('intercom-version')).toBe('2.11');
+ expect(seen[0].dispatcher).toBeDefined();
+ });
+
+ test('SDK returns the raw response body on success', async () => {
+ stubIntercom([{ method: 'GET', path: '/tags', reply: { body: { type: 'list', data: [{ type: 'tag', id: '1', name: 'VIP' }] } } }]);
+ const client = await intercomClient(customAuth());
+ expect(await client.tags.list()).toEqual({ type: 'list', data: [{ type: 'tag', id: '1', name: 'VIP' }] });
+ });
+});
+
+describe('access token validate', () => {
+ const validate = (region: string) => {
+ const validateFn = intercomAuth[1].validate;
+ if (validateFn === undefined) {
+ throw new Error('validate is not defined');
+ }
+ return callWith({ fn: validateFn, ctx: { auth: { accessToken: 'T', region } } });
+ };
+
+ test('401 says invalid token or region; 500 does not blame the credentials', async () => {
+ stubIntercom([{ method: 'GET', path: '/me', reply: { status: 401, body: { errors: [{ code: 'unauthorized' }] } } }]);
+ expect(await validate('intercom')).toEqual({ valid: false, error: 'Invalid access token or wrong region. Check both and try again.' });
+ vi.unstubAllGlobals();
+ stubIntercom([{ method: 'GET', path: '/me', reply: { status: 500, body: {} } }]);
+ expect(await validate('intercom')).toEqual({ valid: false, error: 'Could not validate the connection. Intercom answered with HTTP 500.' });
+ });
+
+ test('valid token passes and sends the version header; lookalike region never sends the token', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/me', reply: { body: { id: '1' } } }]);
+ expect(await validate('au.intercom')).toEqual({ valid: true });
+ expect(seen[0].url).toBe('https://api.au.intercom.io/me');
+ expect(seen[0].headers.get('intercom-version')).toBe('2.11');
+ vi.unstubAllGlobals();
+ const none = stubIntercom([]);
+ expect((await validate('evil.com/#')).valid).toBe(false);
+ expect(none).toHaveLength(0);
+ });
+});
+
+describe('network errors', () => {
+ test('GET retries a dropped connection; POST does not', async () => {
+ let calls = 0;
+ vi.spyOn(intercomHttpInternals, 'sleep').mockResolvedValue(undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ calls += 1;
+ if (calls === 1) {
+ throw new TypeError('fetch failed');
+ }
+ return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } });
+ }),
+ );
+ await intercomRequest({ auth: customAuth(), method: HttpMethod.GET, path: ['tags'], operation: 'list tags' });
+ expect(calls).toBe(2);
+ calls = 0;
+ await expect(
+ intercomRequest({ auth: customAuth(), method: HttpMethod.POST, path: ['tags'], body: { name: 'a' }, operation: 'create tag' }),
+ ).rejects.toThrow('fetch failed');
+ expect(calls).toBe(1);
+ });
+ test('network errors and 503s share one budget of three GET attempts', async () => {
+ let calls = 0;
+ vi.spyOn(intercomHttpInternals, 'sleep').mockResolvedValue(undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ calls += 1;
+ if (calls % 2 === 1) {
+ throw new TypeError('fetch failed');
+ }
+ return new Response(JSON.stringify({}), { status: 503, headers: { 'content-type': 'application/json' } });
+ }),
+ );
+ await expect(
+ intercomRequest({ auth: customAuth(), method: HttpMethod.GET, path: ['tags'], operation: 'list tags' }),
+ ).rejects.toThrow('fetch failed');
+ expect(calls).toBe(3);
+ });
+});
diff --git a/packages/pieces/community/intercom/test/companies.test.ts b/packages/pieces/community/intercom/test/companies.test.ts
new file mode 100644
index 00000000000..25d8e5f1e7c
--- /dev/null
+++ b/packages/pieces/community/intercom/test/companies.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { findCompanyAction } from '../src/lib/actions/find-company';
+import { findOrCreateCompanyAction } from '../src/lib/actions/find-or-create-company';
+import { getCompanyAction } from '../src/lib/actions/get-company';
+import { runAction, stubIntercom } from './helpers';
+
+const COMPANY = { type: 'company', id: '6a1', company_id: 'acme-001', name: 'Acme' };
+const NOT_FOUND = { status: 404, body: { type: 'error.list', errors: [{ code: 'company_not_found', message: 'Company Not Found' }] } };
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('Find Company (P1-2)', () => {
+ test('404 company_not_found returns found=false instead of failing', async () => {
+ stubIntercom([{ method: 'GET', path: '/companies', reply: NOT_FOUND }]);
+ const output = await runAction({ action: findCompanyAction, props: { searchField: 'name', searchValue: 'does-not-exist' } });
+ expect(output).toEqual({ found: false, company: {}, user: {} });
+ });
+
+ test('a match is returned under company and the legacy user key', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/companies', reply: { body: { type: 'list', data: [COMPANY], total_count: 1 } } }]);
+ const output = await runAction({ action: findCompanyAction, props: { searchField: 'company_id', searchValue: 'acme-001' } });
+ expect(output).toEqual({ found: true, company: COMPANY, user: COMPANY });
+ expect(seen[0].query).toEqual({ company_id: 'acme-001', per_page: '1' });
+ });
+
+ test('a single company object response is accepted too', async () => {
+ stubIntercom([{ method: 'GET', path: '/companies', reply: { body: COMPANY } }]);
+ const output = await runAction({ action: findCompanyAction, props: { searchField: 'company_id', searchValue: 'acme-001' } });
+ expect(output).toEqual({ found: true, company: COMPANY, user: COMPANY });
+ });
+
+ test('other errors still fail the step', async () => {
+ stubIntercom([{ method: 'GET', path: '/companies', reply: { status: 401, body: { errors: [{ code: 'unauthorized', message: 'Access Token Invalid' }] } } }]);
+ await expect(runAction({ action: findCompanyAction, props: { searchField: 'name', searchValue: 'x' } })).rejects.toThrow('(401)');
+ });
+});
+
+describe('Find or Create Company (P1-2)', () => {
+ test('creates the company when the lookup 404s', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/companies', reply: NOT_FOUND },
+ { method: 'POST', path: '/companies', reply: { body: COMPANY } },
+ ]);
+ const output = await runAction({
+ action: findOrCreateCompanyAction,
+ props: { companyId: 'acme-001', name: 'Acme', size: 10 },
+ });
+ expect(output).toEqual({ created: true, company: COMPANY });
+ expect(seen.find((r) => r.method === 'POST')?.body).toEqual({ company_id: 'acme-001', name: 'Acme', size: 10 });
+ });
+
+ test('returns the existing company without creating', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/companies', reply: { body: { type: 'list', data: [COMPANY] } } }]);
+ const output = await runAction({ action: findOrCreateCompanyAction, props: { name: 'Acme' } });
+ expect(output).toEqual({ created: false, company: COMPANY });
+ expect(seen.every((r) => r.method === 'GET')).toBe(true);
+ expect(seen[0].query['name']).toBe('Acme');
+ });
+});
+
+describe('Get Company', () => {
+ test('by your Company ID fails clearly when none matches', async () => {
+ stubIntercom([{ method: 'GET', path: '/companies', reply: NOT_FOUND }]);
+ await expect(runAction({ action: getCompanyAction, props: { lookupBy: 'company_id', value: 'nope' } })).rejects.toThrow(
+ 'No Intercom company has the Company ID nope.',
+ );
+ });
+
+ test('by Intercom ID calls GET /companies/{id}', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/companies/6a1', reply: { body: COMPANY } }]);
+ expect(await runAction({ action: getCompanyAction, props: { lookupBy: 'id', value: '6a1' } })).toEqual(COMPANY);
+ expect(seen).toHaveLength(1);
+ });
+});
diff --git a/packages/pieces/community/intercom/test/conversations-and-tags.test.ts b/packages/pieces/community/intercom/test/conversations-and-tags.test.ts
new file mode 100644
index 00000000000..98ed8fb1840
--- /dev/null
+++ b/packages/pieces/community/intercom/test/conversations-and-tags.test.ts
@@ -0,0 +1,303 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { tagOrUntagRecordAction } from '../src/lib/actions/ai/tag-or-untag-record';
+import { getConversationByIdAction } from '../src/lib/actions/ai/get-conversation-by-id';
+import { replyToConversationByIdAction } from '../src/lib/actions/ai/reply-to-conversation-by-id';
+import { assignConversationByIdAction } from '../src/lib/actions/ai/assign-conversation-by-id';
+import { sendMessageToContactAction } from '../src/lib/actions/ai/send-message-to-contact';
+import { setConversationStateAction } from '../src/lib/actions/set-conversation-state';
+import { listAdminsAction } from '../src/lib/actions/list-admins';
+import { createTagAction } from '../src/lib/actions/create-tag';
+import { listSegmentsAction } from '../src/lib/actions/ai/list-segments';
+import { addNoteToContactAction } from '../src/lib/actions/ai/add-note-to-contact';
+import { createConversationFromContactAction } from '../src/lib/actions/ai/create-conversation-from-contact';
+import { createHelpCenterArticleAction } from '../src/lib/actions/ai/create-help-center-article';
+import { ME, runAction, stubIntercom } from './helpers';
+
+const TAG = { type: 'tag', id: '77', name: 'VIP' };
+const TAGS = { type: 'list', data: [TAG] };
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('Tag or Untag Record', () => {
+ test('contact + existing tag name in another case: reuses the tag without renaming it', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/tags', reply: { body: TAGS } },
+ { method: 'POST', path: '/contacts/c1/tags', reply: { body: TAG } },
+ ]);
+ const output = await runAction({ action: tagOrUntagRecordAction, props: { target: 'contact', recordId: 'c1', tagName: 'vip' } });
+ expect(output).toEqual({ target: 'contact', record_id: 'c1', tag: { id: '77', name: 'VIP' }, removed: false, already_in_state: false });
+ expect(seen.map((r) => `${r.method} ${r.path}`)).toEqual(['GET /tags', 'POST /contacts/c1/tags']);
+ expect(seen[1].body).toEqual({ id: '77' });
+ });
+
+ test('a new tag name is created first', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/tags', reply: { body: TAGS } },
+ { method: 'POST', path: '/tags', reply: { body: { type: 'tag', id: '88', name: 'New' } } },
+ { method: 'POST', path: '/contacts/c1/tags', reply: { body: {} } },
+ ]);
+ await runAction({ action: tagOrUntagRecordAction, props: { target: 'contact', recordId: 'c1', tagName: 'New' } });
+ expect(seen.map((r) => `${r.method} ${r.path}`)).toEqual(['GET /tags', 'POST /tags', 'POST /contacts/c1/tags']);
+ expect(seen[1].body).toEqual({ name: 'New' });
+ });
+
+ test('conversation and ticket tagging send the acting admin', async () => {
+ for (const [target, plural] of [
+ ['conversation', 'conversations'],
+ ['ticket', 'tickets'],
+ ]) {
+ vi.unstubAllGlobals();
+ const seen = stubIntercom([
+ { method: 'GET', path: '/tags/77', reply: { body: TAG } },
+ { method: 'GET', path: '/me', reply: { body: ME } },
+ { method: 'POST', path: `/${plural}/r1/tags`, reply: { body: TAG } },
+ ]);
+ await runAction({ action: tagOrUntagRecordAction, props: { target, recordId: 'r1', tagId: '77' } });
+ expect(seen.at(-1)?.body).toEqual({ id: '77', admin_id: '991' });
+ }
+ });
+
+ test('company add uses POST /tags with companies[]; remove looks up company_id and sends untag', async () => {
+ const addSeen = stubIntercom([
+ { method: 'GET', path: '/tags', reply: { body: TAGS } },
+ { method: 'POST', path: '/tags', reply: { body: TAG } },
+ ]);
+ await runAction({ action: tagOrUntagRecordAction, props: { target: 'company', recordId: 'co1', tagName: 'VIP' } });
+ expect(addSeen.at(-1)?.body).toEqual({ name: 'VIP', companies: [{ id: 'co1' }] });
+
+ vi.unstubAllGlobals();
+ const removeSeen = stubIntercom([
+ { method: 'GET', path: '/tags', reply: { body: TAGS } },
+ { method: 'GET', path: '/companies/co1', reply: { body: { id: 'co1', company_id: 'acme-001' } } },
+ { method: 'POST', path: '/tags', reply: { body: TAG } },
+ ]);
+ await runAction({ action: tagOrUntagRecordAction, props: { target: 'company', recordId: 'co1', tagId: '77', remove: true } });
+ expect(removeSeen.at(-1)?.body).toEqual({ name: 'VIP', companies: [{ id: 'co1', company_id: 'acme-001', untag: true }] });
+ });
+
+ test('removing a tag that does not exist reports already_in_state without writing', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/tags', reply: { body: TAGS } }]);
+ const output = await runAction({
+ action: tagOrUntagRecordAction,
+ props: { target: 'contact', recordId: 'c1', tagName: 'Missing', remove: true },
+ });
+ expect(output).toMatchObject({ removed: true, already_in_state: true });
+ expect(seen).toHaveLength(1);
+ });
+
+ test('a 404 on untag counts as already removed only when the record exists', async () => {
+ stubIntercom([
+ { method: 'GET', path: '/tags', reply: { body: TAGS } },
+ { method: 'DELETE', path: '/contacts/c1/tags/77', reply: { status: 404, body: { errors: [{ code: 'not_found' }] } } },
+ { method: 'GET', path: '/contacts/c1', reply: { body: { id: 'c1' } } },
+ ]);
+ expect(
+ await runAction({ action: tagOrUntagRecordAction, props: { target: 'contact', recordId: 'c1', tagId: '77', remove: true } }),
+ ).toMatchObject({ removed: true, already_in_state: true });
+
+ vi.unstubAllGlobals();
+ stubIntercom([
+ { method: 'GET', path: '/tags', reply: { body: TAGS } },
+ { method: 'DELETE', path: '/contacts/gone/tags/77', reply: { status: 404, body: { errors: [{ code: 'not_found' }] } } },
+ ]);
+ await expect(
+ runAction({ action: tagOrUntagRecordAction, props: { target: 'contact', recordId: 'gone', tagId: '77', remove: true } }),
+ ).rejects.toThrow('(404)');
+ });
+
+ test('needs exactly one of tag ID or tag name', async () => {
+ stubIntercom([]);
+ await expect(runAction({ action: tagOrUntagRecordAction, props: { target: 'contact', recordId: 'c1' } })).rejects.toThrow(
+ 'exactly one',
+ );
+ await expect(
+ runAction({ action: tagOrUntagRecordAction, props: { target: 'contact', recordId: 'c1', tagId: '1', tagName: 'x' } }),
+ ).rejects.toThrow('exactly one');
+ });
+});
+
+describe('conversation twins', () => {
+ test('Get Conversation (by ID) asks for plain text and flattens parts', async () => {
+ const seen = stubIntercom([
+ {
+ method: 'GET',
+ path: '/conversations/42',
+ reply: {
+ body: {
+ id: '42',
+ state: 'open',
+ conversation_parts: {
+ conversation_parts: [
+ { id: 'p1', part_type: 'comment', body: 'hi', created_at: 10, author: { type: 'user', id: 'u1', name: 'Ann' } },
+ ],
+ },
+ },
+ },
+ },
+ ]);
+ const output = await runAction({ action: getConversationByIdAction, props: { conversationId: '42' } });
+ expect(seen[0].query).toEqual({ display_as: 'plaintext' });
+ expect(output).toEqual({
+ id: '42',
+ state: 'open',
+ parts: [{ id: 'p1', part_type: 'comment', author_type: 'user', author_id: 'u1', author_name: 'Ann', body: 'hi', created_at: 10 }],
+ });
+ });
+
+ test('Reply (by ID) defaults the admin to the connection owner and posts once even on 5xx', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/me', reply: { body: ME } },
+ { method: 'POST', path: '/conversations/42/reply', reply: { status: 500, body: { errors: [{ code: 'server_error' }] } } },
+ ]);
+ await expect(
+ runAction({ action: replyToConversationByIdAction, props: { conversationId: '42', body: 'Hello', attachmentUrls: ['https://x.io/a.png'] } }),
+ ).rejects.toThrow('(500)');
+ const posts = seen.filter((r) => r.method === 'POST');
+ expect(posts).toHaveLength(1);
+ expect(posts[0].body).toEqual({
+ message_type: 'comment',
+ type: 'admin',
+ admin_id: '991',
+ body: 'Hello',
+ attachment_urls: ['https://x.io/a.png'],
+ });
+ });
+
+ test('Reply (by ID) rejects non-http attachment URLs before sending', async () => {
+ const seen = stubIntercom([]);
+ await expect(
+ runAction({
+ action: replyToConversationByIdAction,
+ props: { conversationId: '42', body: 'Hello', adminId: '5', attachmentUrls: ['javascript:alert(1)'] },
+ }),
+ ).rejects.toThrow('public http(s) link');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('Assign (by ID) posts an assignment part to a team', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/conversations/42/parts', reply: { body: { id: '42' } } }]);
+ await runAction({
+ action: assignConversationByIdAction,
+ props: { conversationId: '42', assigneeType: 'team', assigneeId: '7', adminId: '5' },
+ });
+ expect(seen[0].body).toEqual({ message_type: 'assignment', type: 'team', admin_id: '5', assignee_id: '7' });
+ });
+
+ test('Set Conversation State: snooze needs a future time; closing message only on close', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/conversations/42/parts', reply: { body: { id: '42' } } }]);
+ await expect(
+ runAction({ action: setConversationStateAction, props: { conversationId: '42', state: 'snoozed', adminId: '5' } }),
+ ).rejects.toThrow('Snooze Until is required');
+ await expect(
+ runAction({
+ action: setConversationStateAction,
+ props: { conversationId: '42', state: 'snoozed', snoozedUntil: '2000-01-01T00:00:00Z', adminId: '5' },
+ }),
+ ).rejects.toThrow('must be in the future');
+ await expect(
+ runAction({ action: setConversationStateAction, props: { conversationId: '42', state: 'open', closingMessage: 'bye', adminId: '5' } }),
+ ).rejects.toThrow('only be sent when closing');
+ expect(seen).toHaveLength(0);
+ await runAction({ action: setConversationStateAction, props: { conversationId: '42', state: 'close', closingMessage: 'bye', adminId: '5' } });
+ expect(seen[0].body).toEqual({ message_type: 'close', type: 'admin', admin_id: '5', body: 'bye' });
+ });
+});
+
+describe('Send Message to Contact', () => {
+ test('resolves a unique email, sends an email from the admin to the right contact type', async () => {
+ const seen = stubIntercom([
+ { method: 'POST', path: '/contacts/search', reply: { body: { data: [{ id: 'c1', role: 'lead' }] } } },
+ { method: 'POST', path: '/messages', reply: { body: { type: 'admin_message', id: 'm1' } } },
+ ]);
+ await runAction({
+ action: sendMessageToContactAction,
+ props: { email: '[email protected]', messageType: 'email', subject: 'Hi', body: 'Body', adminId: '5' },
+ });
+ expect(seen.at(-1)?.body).toEqual({
+ message_type: 'email',
+ subject: 'Hi',
+ template: 'plain',
+ body: 'Body',
+ from: { type: 'admin', id: 5 },
+ to: { type: 'lead', id: 'c1' },
+ create_conversation_without_contact_reply: false,
+ });
+ });
+
+ test('email needs a subject and exactly one contact identifier', async () => {
+ const seen = stubIntercom([]);
+ await expect(
+ runAction({ action: sendMessageToContactAction, props: { contactId: 'c1', messageType: 'email', body: 'x' } }),
+ ).rejects.toThrow('Subject is required');
+ await expect(
+ runAction({ action: sendMessageToContactAction, props: { messageType: 'in_app', body: 'x' } }),
+ ).rejects.toThrow('exactly one');
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('List Admins', () => {
+ test('returns admins plus the connected admin ID', async () => {
+ stubIntercom([
+ { method: 'GET', path: '/admins', reply: { body: { admins: [{ id: '991', name: 'Pat', email: '[email protected]', team_ids: [1] }] } } },
+ { method: 'GET', path: '/me', reply: { body: ME } },
+ ]);
+ expect(await runAction({ action: listAdminsAction, props: {} })).toEqual({
+ items: [
+ { id: '991', name: 'Pat', email: '[email protected]', job_title: null, away_mode_enabled: false, has_inbox_seat: false, team_ids: [1] },
+ ],
+ current_admin_id: '991',
+ });
+ });
+});
+
+describe('Create Tag', () => {
+ test('returns an existing tag in another letter case without renaming it', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/tags', reply: { body: TAGS } }]);
+ expect(await runAction({ action: createTagAction, props: { name: 'vip' } })).toEqual(TAG);
+ expect(seen.every((r) => r.method === 'GET')).toBe(true);
+ });
+});
+
+describe('PR1 agent twins', () => {
+ test('List Segments sends include_count only when asked and maps segments', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/segments', reply: { body: { type: 'segment.list', segments: [{ type: 'segment', id: '5f0a', name: 'Active', person_type: 'user', count: 3, created_at: 1, updated_at: 2 }] } } },
+ ]);
+ const output = await runAction({ action: listSegmentsAction, props: { includeCount: true } });
+ expect(seen[0].query).toEqual({ include_count: 'true' });
+ expect(output).toEqual({ items: [{ id: '5f0a', name: 'Active', person_type: 'user', count: 3, created_at: 1, updated_at: 2 }] });
+ vi.unstubAllGlobals();
+ const plain = stubIntercom([{ method: 'GET', path: '/segments', reply: { body: { segments: [] } } }]);
+ await runAction({ action: listSegmentsAction, props: {} });
+ expect(plain[0].query).toEqual({});
+ });
+
+ test('Add Note to Contact posts to the contact with the connection admin by default', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/me', reply: { body: ME } },
+ { method: 'POST', path: '/contacts/c1/notes', reply: { body: { type: 'note', id: 'n1' } } },
+ ]);
+ await runAction({ action: addNoteToContactAction, props: { contactId: ' c1 ', body: 'Hello' } });
+ expect(seen.at(-1)?.body).toEqual({ body: 'Hello', admin_id: '991' });
+ });
+
+ test('Create Conversation from Contact sends the contact role as author type', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/contacts/c1', reply: { body: { id: 'c1', role: 'lead' } } },
+ { method: 'POST', path: '/conversations', reply: { body: { type: 'user_message', id: 'm1', conversation_id: '9' } } },
+ ]);
+ await runAction({ action: createConversationFromContactAction, props: { contactId: 'c1', body: 'Need help' } });
+ expect(seen[1].body).toEqual({ from: { type: 'lead', id: 'c1' }, body: 'Need help' });
+ });
+
+ test('Create Help Center Article defaults to draft with integer IDs and rejects non-numeric IDs', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/articles', reply: { body: { id: '1', state: 'draft' } } }]);
+ await runAction({ action: createHelpCenterArticleAction, props: { title: 'T', authorId: '42', collectionId: '7' } });
+ expect(seen[0].body).toEqual({ title: 'T', author_id: 42, state: 'draft', parent_id: 7, parent_type: 'collection' });
+ await expect(runAction({ action: createHelpCenterArticleAction, props: { title: 'T', authorId: 'abc' } })).rejects.toThrow('Author Admin ID must be a numeric Intercom ID');
+ });
+});
diff --git a/packages/pieces/community/intercom/test/helpers.ts b/packages/pieces/community/intercom/test/helpers.ts
new file mode 100644
index 00000000000..e66d3b707f0
--- /dev/null
+++ b/packages/pieces/community/intercom/test/helpers.ts
@@ -0,0 +1,106 @@
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+import { IntercomAuthValue, intercomHttpInternals } from '../src/lib/common/client';
+
+export function customAuth(region = 'intercom'): IntercomAuthValue {
+ return {
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { accessToken: 'TOKEN-123', region },
+ };
+}
+
+export function oauthAuth(region?: string): IntercomAuthValue {
+ return {
+ type: AppConnectionType.OAUTH2,
+ access_token: 'OAUTH-TOKEN',
+ client_id: 'client',
+ client_secret: 'secret',
+ redirect_url: 'http://localhost/redirect',
+ token_type: 'Bearer',
+ claimed_at: 0,
+ refresh_token: 'refresh',
+ scope: '',
+ token_url: 'https://api.intercom.io/auth/eagle/token',
+ data: {},
+ props: region === undefined ? {} : { region },
+ };
+}
+
+export function stubIntercom(routes: Route[]): Seen[] {
+ const seen: Seen[] = [];
+ vi.spyOn(intercomHttpInternals, 'sleep').mockResolvedValue(undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request, init?: RequestInit & { dispatcher?: unknown }) => {
+ const url = new URL(input instanceof Request ? input.url : String(input));
+ const method = (init?.method ?? 'GET').toUpperCase();
+ const headers = new Headers(init?.headers);
+ const rawBody = typeof init?.body === 'string' ? init.body : undefined;
+ const entry: Seen = {
+ method,
+ url: url.toString(),
+ path: url.pathname,
+ query: Object.fromEntries(url.searchParams.entries()),
+ headers,
+ body: rawBody === undefined ? undefined : JSON.parse(rawBody),
+ dispatcher: init?.dispatcher,
+ };
+ seen.push(entry);
+ const route = routes.find(
+ (candidate) =>
+ candidate.method === method &&
+ (typeof candidate.path === 'string' ? candidate.path === url.pathname : candidate.path.test(url.pathname)),
+ );
+ if (route === undefined) {
+ return new Response(JSON.stringify({ type: 'error.list', errors: [{ code: 'not_found', message: 'no stub' }] }), {
+ status: 404,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ const reply = typeof route.reply === 'function' ? route.reply(entry, seen) : route.reply;
+ return new Response(reply.body === undefined ? '' : JSON.stringify(reply.body), {
+ status: reply.status ?? 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }),
+ );
+ return seen;
+}
+
+export async function runAction<T extends { run: (ctx: never) => Promise<unknown> }>({
+ action,
+ props,
+ auth = customAuth(),
+}: {
+ action: T;
+ props: Record<string, unknown>;
+ auth?: unknown;
+}): Promise<unknown> {
+ const context = { auth, propsValue: props, server: { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 't' } };
+ return callWith({ fn: action.run, ctx: context });
+}
+
+export function callWith<R>({ fn, ctx }: { fn: (ctx: never) => R; ctx: unknown }): R {
+ return Reflect.apply(fn, undefined, [ctx]);
+}
+
+export const ME = { type: 'admin', id: '991', name: 'Pat Lee', email: '[email protected]', app: { id_code: 'app1', name: 'Acme' } };
+
+export type Reply = { status?: number; body?: unknown };
+
+export type Route = {
+ method: string;
+ path: string | RegExp;
+ reply: Reply | ((request: Seen, all: Seen[]) => Reply);
+};
+
+export type Seen = {
+ method: string;
+ url: string;
+ path: string;
+ query: Record<string, string>;
+ headers: Headers;
+ body: unknown;
+ dispatcher: unknown;
+};
diff --git a/packages/pieces/community/intercom/test/search.test.ts b/packages/pieces/community/intercom/test/search.test.ts
new file mode 100644
index 00000000000..953006abeea
--- /dev/null
+++ b/packages/pieces/community/intercom/test/search.test.ts
@@ -0,0 +1,192 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { searchContactsAction } from '../src/lib/actions/search-contacts';
+import { searchConversationsAction } from '../src/lib/actions/search-conversations';
+import { searchTicketsAction } from '../src/lib/actions/search-tickets';
+import { findConversationAction } from '../src/lib/actions/find-conversation';
+import { getContactAction } from '../src/lib/actions/get-contact';
+import { updateContactAction } from '../src/lib/actions/update-contact';
+import { listContactNotesAction } from '../src/lib/actions/list-contact-notes';
+import { buildSearchQuery } from '../src/lib/common/lookups';
+import { runAction, stubIntercom } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('Search Contacts', () => {
+ test('combines filters with AND, uses > and < on dates, and returns a cursor list', async () => {
+ const seen = stubIntercom([
+ {
+ method: 'POST',
+ path: '/contacts/search',
+ reply: {
+ body: { type: 'list', data: [{ id: 'c1' }], total_count: 7, pages: { next: { starting_after: 'CUR2' } } },
+ },
+ },
+ ]);
+ const output = await runAction({
+ action: searchContactsAction,
+ props: {
+ email: ' [email protected] ',
+ role: 'lead',
+ updatedAfter: '2026-10-01T00:00:00Z',
+ customAttribute: 'plan',
+ customValue: 'pro',
+ perPage: 20,
+ startingAfter: 'CUR1',
+ },
+ });
+ expect(seen[0].body).toEqual({
+ query: {
+ operator: 'AND',
+ value: [
+ { field: 'email', operator: '=', value: '[email protected]' },
+ { field: 'role', operator: '=', value: 'lead' },
+ { field: 'updated_at', operator: '>', value: 1790812800 },
+ { field: 'custom_attributes.plan', operator: '=', value: 'pro' },
+ ],
+ },
+ pagination: { per_page: 20, starting_after: 'CUR1' },
+ });
+ expect(output).toEqual({ items: [{ id: 'c1' }], total_count: 7, has_more: true, next_starting_after: 'CUR2' });
+ });
+
+ test('no filters searches all users and leads; last page has has_more=false', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/contacts/search', reply: { body: { data: [], total_count: 0, pages: {} } } }]);
+ const output = await runAction({ action: searchContactsAction, props: {} });
+ expect(seen[0].body).toEqual({
+ query: { field: 'role', operator: 'IN', value: ['user', 'lead'] },
+ pagination: { per_page: 50 },
+ });
+ expect(output).toEqual({ items: [], total_count: 0, has_more: false, next_starting_after: null });
+ });
+
+ test('rejects bad page size and half-given custom attribute before calling Intercom', async () => {
+ const seen = stubIntercom([]);
+ await expect(runAction({ action: searchContactsAction, props: { perPage: 500 } })).rejects.toThrow('1 to 150');
+ await expect(runAction({ action: searchContactsAction, props: { customAttribute: 'plan' } })).rejects.toThrow('Custom Attribute Value');
+ await expect(runAction({ action: searchContactsAction, props: { advancedQuery: ['x'] } })).rejects.toThrow('Advanced Query');
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('Search Conversations / Tickets', () => {
+ test('conversation filters map to Intercom fields and read the conversations key', async () => {
+ const seen = stubIntercom([
+ { method: 'POST', path: '/conversations/search', reply: { body: { conversations: [{ id: '9' }], total_count: 1, pages: {} } } },
+ ]);
+ const output = await runAction({
+ action: searchConversationsAction,
+ props: { state: 'snoozed', contactId: 'c1', bodyContains: 'refund', createdBefore: '2026-10-02T00:00:00Z' },
+ });
+ expect(seen[0].body).toEqual({
+ query: {
+ operator: 'AND',
+ value: [
+ { field: 'state', operator: '=', value: 'snoozed' },
+ { field: 'contact_ids', operator: '=', value: 'c1' },
+ { field: 'source.body', operator: '~', value: 'refund' },
+ { field: 'created_at', operator: '<', value: 1790899200 },
+ ],
+ },
+ pagination: { per_page: 50 },
+ });
+ expect(output).toEqual({ items: [{ id: '9' }], total_count: 1, has_more: false, next_starting_after: null });
+ });
+
+ test('ticket search maps open to a boolean and title to ~', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/tickets/search', reply: { body: { tickets: [], total_count: 0 } } }]);
+ await runAction({ action: searchTicketsAction, props: { open: 'closed', titleContains: 'login', ticketTypeId: '85' } });
+ expect(seen[0].body).toEqual({
+ query: {
+ operator: 'AND',
+ value: [
+ { field: 'ticket_type_id', operator: '=', value: '85' },
+ { field: 'open', operator: '=', value: false },
+ { field: 'title', operator: '~', value: 'login' },
+ ],
+ },
+ pagination: { per_page: 50 },
+ });
+ });
+
+ test('more than 15 filters are refused', () => {
+ const filters = Array.from({ length: 16 }, (_, index) => ({ field: `custom_attributes.a${index}`, operator: '=', value: 'x' }));
+ expect(() => buildSearchQuery({ filters, advancedQuery: undefined, fallback: filters[0] })).toThrow('at most 15 filters');
+ expect(buildSearchQuery({ filters: filters.slice(0, 15), advancedQuery: undefined, fallback: filters[0] })).toMatchObject({
+ operator: 'AND',
+ });
+ });
+});
+
+describe('Find Conversation (existing)', () => {
+ test('ID fields only allow Equals (P2-10) and nothing is sent', async () => {
+ const seen = stubIntercom([]);
+ await expect(
+ runAction({ action: findConversationAction, props: { searchField: 'tag_ids', matchType: 'contains', searchTerm: '12' } }),
+ ).rejects.toThrow('only be matched with Equals');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('snoozed status is accepted', async () => {
+ const seen = stubIntercom([{ method: 'POST', path: '/conversations/search', reply: { body: { conversations: [{ id: '1' }], pages: {} } } }]);
+ const output = await runAction({
+ action: findConversationAction,
+ props: { searchField: 'source.subject', matchType: 'contains', searchTerm: 'refund', status: 'snoozed' },
+ });
+ expect(output).toEqual({ found: true, conversation: { id: '1' } });
+ expect(seen[0].body).toMatchObject({
+ query: {
+ operator: 'AND',
+ value: [
+ { field: 'source.subject', operator: '~', value: 'refund' },
+ { field: 'state', operator: '=', value: 'snoozed' },
+ ],
+ },
+ });
+ });
+});
+
+describe('Contacts', () => {
+ test('Get Contact by email fails when the email is shared', async () => {
+ stubIntercom([{ method: 'POST', path: '/contacts/search', reply: { body: { data: [{ id: 'a' }, { id: 'b' }] } } }]);
+ await expect(runAction({ action: getContactAction, props: { lookupBy: 'email', value: '[email protected]' } })).rejects.toThrow(
+ 'More than one Intercom contact',
+ );
+ });
+
+ test('Update Contact sends only set fields and nulls for Clear Fields', async () => {
+ const seen = stubIntercom([{ method: 'PUT', path: '/contacts/c1', reply: { body: { id: 'c1' } } }]);
+ await runAction({
+ action: updateContactAction,
+ props: { contactId: 'c1', name: 'Ann', unsubscribed: 'unsubscribed', clearFields: ['phone', 'owner_id'] },
+ });
+ expect(seen[0].body).toEqual({ name: 'Ann', unsubscribed_from_emails: true, phone: null, owner_id: null });
+ });
+
+ test('Update Contact refuses an empty update and a set+clear conflict', async () => {
+ const seen = stubIntercom([]);
+ await expect(runAction({ action: updateContactAction, props: { contactId: 'c1' } })).rejects.toThrow('Nothing to update');
+ await expect(
+ runAction({ action: updateContactAction, props: { contactId: 'c1', name: 'A', clearFields: ['name'] } }),
+ ).rejects.toThrow('Do not set and clear');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('List Contact Notes returns page info', async () => {
+ stubIntercom([
+ {
+ method: 'GET',
+ path: '/contacts/c1/notes',
+ reply: { body: { data: [{ id: 'n1' }], total_count: 3, pages: { page: 1, total_pages: 2 } } },
+ },
+ ]);
+ expect(await runAction({ action: listContactNotesAction, props: { contactId: 'c1' } })).toEqual({
+ items: [{ id: 'n1' }],
+ total_count: 3,
+ has_more: true,
+ next_page: 2,
+ });
+ });
+});
diff --git a/packages/pieces/community/intercom/test/tickets.test.ts b/packages/pieces/community/intercom/test/tickets.test.ts
new file mode 100644
index 00000000000..afd9acde3fc
--- /dev/null
+++ b/packages/pieces/community/intercom/test/tickets.test.ts
@@ -0,0 +1,171 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { createTicketAction } from '../src/lib/actions/create-ticket';
+import { updateTicketAction } from '../src/lib/actions/update-ticket';
+import { createTicketByTypeIdAction } from '../src/lib/actions/ai/create-ticket-by-type-id';
+import { updateTicketByIdAction } from '../src/lib/actions/ai/update-ticket-by-id';
+import { toTicketAttributes, TicketTypeAttribute } from '../src/lib/common/ticket-attributes';
+import { ME, runAction, stubIntercom } from './helpers';
+
+const ATTRIBUTES: TicketTypeAttribute[] = [
+ { name: '_default_title_', data_type: 'string', required_to_create: false },
+ { name: '_default_description_', data_type: 'string' },
+ { name: 'Priority', data_type: 'list', input_options: { list_options: [{ id: '2', label: 'High' }] } },
+ { name: 'Due', data_type: 'datetime' },
+ { name: 'Seats', data_type: 'integer' },
+ { name: 'Budget', data_type: 'decimal' },
+ { name: 'Urgent', data_type: 'boolean' },
+ { name: 'Order Ref', data_type: 'string', required_to_create: true },
+];
+
+const TICKET_TYPE = { type: 'ticket_type', id: '85', name: 'AP Test', ticket_type_attributes: { type: 'list', data: ATTRIBUTES } };
+const TICKET = { type: 'ticket', id: '500', ticket_id: '7', ticket_type: { id: '85', name: 'AP Test' }, ticket_attributes: {} };
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('toTicketAttributes', () => {
+ test('keeps text and list values that dayjs could parse as dates', () => {
+ const result = toTicketAttributes({
+ attributes: ATTRIBUTES,
+ values: { _default_title_: 'Order 2024', _default_description_: 'Ticket 5', Priority: '2', 'Order Ref': '123' },
+ });
+ expect(result).toEqual({ _default_title_: 'Order 2024', _default_description_: 'Ticket 5', Priority: '2', 'Order Ref': '123' });
+ });
+
+ test('converts only datetime attributes to unix seconds', () => {
+ const result = toTicketAttributes({
+ attributes: ATTRIBUTES,
+ values: { Due: '2026-10-20T12:00:00.000Z', _default_title_: '2026-10-20' },
+ });
+ expect(result).toEqual({ Due: 1792497600, _default_title_: '2026-10-20' });
+ });
+
+ test('accepts unix seconds and milliseconds for datetime', () => {
+ expect(toTicketAttributes({ attributes: ATTRIBUTES, values: { Due: 1792497600 } })).toEqual({ Due: 1792497600 });
+ expect(toTicketAttributes({ attributes: ATTRIBUTES, values: { Due: 1792497600000 } })).toEqual({ Due: 1792497600 });
+ expect(toTicketAttributes({ attributes: ATTRIBUTES, values: { Due: '1792497600' } })).toEqual({ Due: 1792497600 });
+ });
+
+ test('types numbers and booleans and keeps null to clear', () => {
+ expect(
+ toTicketAttributes({ attributes: ATTRIBUTES, values: { Seats: '12', Budget: '9.5', Urgent: 'true', Priority: null } }),
+ ).toEqual({ Seats: 12, Budget: 9.5, Urgent: true, Priority: null });
+ });
+
+ test('rejects values that do not fit the attribute type', () => {
+ expect(() => toTicketAttributes({ attributes: ATTRIBUTES, values: { Due: 'next week-ish' } })).toThrow('expects a date');
+ expect(() => toTicketAttributes({ attributes: ATTRIBUTES, values: { Seats: '1.5' } })).toThrow('whole number');
+ expect(() => toTicketAttributes({ attributes: ATTRIBUTES, values: { Urgent: 'yes' } })).toThrow('true or false');
+ });
+
+ test('passes unknown attributes through unchanged', () => {
+ expect(toTicketAttributes({ attributes: ATTRIBUTES, values: { Other: '2' } })).toEqual({ Other: '2' });
+ });
+});
+
+describe('Create Ticket (existing, human)', () => {
+ test('sends titles with numbers and list option IDs unchanged (P1-1)', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/ticket_types/85', reply: { body: TICKET_TYPE } },
+ { method: 'POST', path: '/tickets', reply: { body: TICKET } },
+ ]);
+ const output = await runAction({
+ action: createTicketAction,
+ props: {
+ ticketTypeId: '85',
+ contactId: 'c1',
+ ticketProperties: { _default_title_: 'Order 2024', Priority: '2', Due: '2026-10-20T12:00:00.000Z' },
+ },
+ });
+ expect(output).toEqual(TICKET);
+ const post = seen.find((r) => r.method === 'POST');
+ expect(post?.body).toEqual({
+ ticket_type_id: '85',
+ contacts: [{ id: 'c1' }],
+ ticket_attributes: { _default_title_: 'Order 2024', Priority: '2', Due: 1792497600 },
+ });
+ expect(post?.headers.get('intercom-version')).toBe('2.11');
+ });
+});
+
+describe('Update Ticket (existing, human)', () => {
+ test('PUTs only given fields and keeps list values as option IDs', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/ticket_types/85', reply: { body: TICKET_TYPE } },
+ { method: 'GET', path: '/me', reply: { body: ME } },
+ { method: 'PUT', path: '/tickets/500', reply: { body: TICKET } },
+ ]);
+ await runAction({
+ action: updateTicketAction,
+ props: { ticketTypeId: '85', ticketId: '500', ticketProperties: { Priority: '2' }, state: 'resolved', assignedAdminId: '42' },
+ });
+ const put = seen.find((r) => r.method === 'PUT');
+ expect(put?.body).toEqual({
+ state: 'resolved',
+ assignment: { assignee_id: '42', admin_id: '991' },
+ ticket_attributes: { Priority: '2' },
+ });
+ });
+});
+
+describe('Create Ticket (by Type ID)', () => {
+ test('maps title and description, contact by email, and checks required attributes', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/ticket_types/85', reply: { body: TICKET_TYPE } },
+ { method: 'POST', path: '/tickets', reply: { body: TICKET } },
+ ]);
+ await runAction({
+ action: createTicketByTypeIdAction,
+ props: {
+ ticketTypeId: '85',
+ contactLookupBy: 'email',
+ contactValue: '[email protected]',
+ title: 'Ticket 5',
+ attributes: { 'Order Ref': '2024', _default_title_: 'ignored', Seats: '3' },
+ },
+ });
+ expect(seen.find((r) => r.method === 'POST')?.body).toEqual({
+ ticket_type_id: '85',
+ contacts: [{ email: '[email protected]' }],
+ ticket_attributes: { 'Order Ref': '2024', _default_title_: 'Ticket 5', Seats: 3 },
+ });
+ });
+
+ test('refuses before posting when a required attribute is missing', async () => {
+ const seen = stubIntercom([{ method: 'GET', path: '/ticket_types/85', reply: { body: TICKET_TYPE } }]);
+ await expect(
+ runAction({
+ action: createTicketByTypeIdAction,
+ props: { ticketTypeId: '85', contactLookupBy: 'id', contactValue: 'c1', title: 'x' },
+ }),
+ ).rejects.toThrow('requires: Order Ref');
+ expect(seen.some((r) => r.method === 'POST')).toBe(false);
+ });
+});
+
+describe('Update Ticket (by ID)', () => {
+ test('refuses an empty update without calling Intercom', async () => {
+ const seen = stubIntercom([]);
+ await expect(runAction({ action: updateTicketByIdAction, props: { ticketId: '500' } })).rejects.toThrow('Nothing to update');
+ expect(seen).toHaveLength(0);
+ });
+
+ test('reads the ticket type to type attributes and maps open/shared', async () => {
+ const seen = stubIntercom([
+ { method: 'GET', path: '/tickets/500', reply: { body: TICKET } },
+ { method: 'GET', path: '/ticket_types/85', reply: { body: TICKET_TYPE } },
+ { method: 'PUT', path: '/tickets/500', reply: { body: TICKET } },
+ ]);
+ await runAction({
+ action: updateTicketByIdAction,
+ props: { ticketId: '500', open: 'closed', isShared: 'shared', attributes: { Due: '2026-10-20T12:00:00Z', Priority: null } },
+ });
+ expect(seen.find((r) => r.method === 'PUT')?.body).toEqual({
+ open: false,
+ is_shared: true,
+ ticket_attributes: { Due: 1792497600, Priority: null },
+ });
+ });
+});
diff --git a/packages/pieces/community/intercom/test/triggers.test.ts b/packages/pieces/community/intercom/test/triggers.test.ts
new file mode 100644
index 00000000000..a41ad8d49c9
--- /dev/null
+++ b/packages/pieces/community/intercom/test/triggers.test.ts
@@ -0,0 +1,147 @@
+import crypto from 'node:crypto';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { intercom } from '../src/index';
+import { leadConvertedToUserTrigger } from '../src/lib/triggers/lead-converted-to-user';
+import { conversationAssigned } from '../src/lib/triggers/conversation-assigned';
+import { replyFromUser } from '../src/lib/triggers/reply-from-user';
+import { newTicketTrigger } from '../src/lib/triggers/new-ticket';
+import { updatedTicketTrigger } from '../src/lib/triggers/updated-ticket';
+import { callWith, customAuth, ME, stubIntercom } from './helpers';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('Lead Converted To User (P1-3)', () => {
+ test('listens to contact.lead.signed_up and keeps contact.merged', async () => {
+ stubIntercom([{ method: 'GET', path: '/me', reply: { body: ME } }]);
+ const createListeners = vi.fn();
+ await callWith({ fn: leadConvertedToUserTrigger.onEnable, ctx: { auth: customAuth(), app: { createListeners } } });
+ expect(createListeners).toHaveBeenCalledWith({
+ events: ['contact.lead.signed_up', 'contact.merged'],
+ identifierValue: 'app1',
+ });
+ });
+});
+
+describe('envelope triggers', () => {
+ test('test() wraps recent conversations in the webhook envelope shape run() returns', async () => {
+ stubIntercom([
+ { method: 'GET', path: '/conversations', reply: { body: { conversations: [{ id: '1' }, { id: '2' }] } } },
+ { method: 'GET', path: /^\/conversations\/\d+$/, reply: (request) => ({ body: { type: 'conversation', id: request.path.split('/')[2] } }) },
+ ]);
+ const samples: unknown = await callWith({ fn: conversationAssigned.test, ctx: { auth: customAuth() } });
+ if (!Array.isArray(samples)) {
+ throw new Error('expected an array of samples');
+ }
+ expect(samples).toHaveLength(2);
+ expect(samples[0]).toMatchObject({
+ type: 'notification_event',
+ topic: 'conversation.admin.assigned',
+ data: { type: 'notification_event_data', item: { type: 'conversation', id: '1' } },
+ });
+ const live = { topic: 'conversation.user.replied', data: { item: { id: '5' } } };
+ expect(await callWith({ fn: replyFromUser.run, ctx: { payload: { body: live } } })).toEqual([live]);
+ });
+
+ test('every trigger has sampleData and READ classification', () => {
+ for (const trigger of Object.values(intercom.triggers())) {
+ expect(trigger.sampleData, trigger.name).toBeDefined();
+ expect(trigger.classification, trigger.name).toBe('READ');
+ }
+ });
+});
+
+describe('webhook signature verify', () => {
+ const rawBody = JSON.stringify({ topic: 'contact.user.created', app_id: 'app1', id: 'n1' });
+ const sign = (secret: string) => `sha1=${crypto.createHmac('sha1', secret).update(rawBody).digest('hex')}`;
+ const verify = ({ headers, webhookSecret }: { headers: Record<string, unknown>; webhookSecret: unknown }) => {
+ const verifyHook = intercom.events?.verify;
+ if (verifyHook === undefined) {
+ throw new Error('verify is not defined');
+ }
+ return callWith({
+ fn: verifyHook,
+ ctx: {
+ payload: { headers, body: JSON.parse(rawBody), rawBody, method: 'POST', queryParams: {} },
+ webhookSecret,
+ appWebhookUrl: '',
+ },
+ });
+ };
+
+ test('accepts the right signature with a single secret or a per-app map', () => {
+ expect(verify({ headers: { 'x-hub-signature': sign('s3cret') }, webhookSecret: 's3cret' })).toBe(true);
+ expect(verify({ headers: { 'x-hub-signature': sign('per-app') }, webhookSecret: { app1: 'per-app' } })).toBe(true);
+ });
+
+ test('rejects a wrong, missing, array or differently sized signature, and unknown apps', () => {
+ expect(verify({ headers: { 'x-hub-signature': sign('other') }, webhookSecret: 's3cret' })).toBe(false);
+ expect(verify({ headers: {}, webhookSecret: 's3cret' })).toBe(false);
+ expect(verify({ headers: { 'x-hub-signature': [sign('s3cret')] }, webhookSecret: 's3cret' })).toBe(false);
+ expect(verify({ headers: { 'x-hub-signature': 'sha1=abc' }, webhookSecret: 's3cret' })).toBe(false);
+ expect(verify({ headers: { 'x-hub-signature': sign('per-app') }, webhookSecret: { other: 'per-app' } })).toBe(false);
+ expect(verify({ headers: { 'x-hub-signature': sign('per-app') }, webhookSecret: { toString: 'per-app' } })).toBe(false);
+ });
+});
+
+describe('action metadata', () => {
+ test('every action has audience, classification and aiMetadata; counts match the plan', () => {
+ const actions = Object.values(intercom.actions()).filter((action) => action.name !== 'custom_api_call');
+ const counts: Record<string, number> = {};
+ for (const action of actions) {
+ expect(action.audience, action.name).toBeDefined();
+ expect(action.classification, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');
+ expect(action.outputSchema, action.name).toBeDefined();
+ counts[action.audience ?? 'none'] = (counts[action.audience ?? 'none'] ?? 0) + 1;
+ }
+ expect(counts).toEqual({ ai: 31, both: 9, human: 16 });
+ });
+});
+
+describe('ticket triggers', () => {
+ test.each([
+ ['new ticket', newTicketTrigger],
+ ['updated ticket', updatedTicketTrigger],
+ ])('%s test() returns tickets in the webhook ticket_state shape', async (_name, trigger) => {
+ stubIntercom([
+ {
+ method: 'POST',
+ path: '/tickets/search',
+ reply: {
+ body: {
+ type: 'ticket.list',
+ tickets: [
+ {
+ type: 'ticket',
+ id: '7',
+ ticket_state: 'in_progress',
+ ticket_state_internal_label: 'In progress',
+ ticket_state_external_label: 'Being worked on',
+ },
+ ],
+ total_count: 1,
+ pages: { type: 'pages', page: 1, per_page: 5, total_pages: 1 },
+ },
+ },
+ },
+ ]);
+ const samples: unknown = await callWith({ fn: trigger.test, ctx: { auth: customAuth() } });
+ if (!Array.isArray(samples)) {
+ throw new Error('expected an array of samples');
+ }
+ expect(samples[0]).toEqual({
+ type: 'ticket',
+ id: '7',
+ ticket_state: {
+ type: 'ticket_state',
+ category: 'in_progress',
+ internal_label: 'In progress',
+ external_label: 'Being worked on',
+ },
+ });
+ });
+});