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(retell-ai): run voice calls, chats, agents and knowledge bases from flows and AI agents, with signed webhook triggers (#16462)

Odai Ahmad4be2810fa5a0
diff --git a/bun.lock b/bun.lock
index 6162096986a..59328e380d2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -7874,7 +7874,7 @@
},
"packages/pieces/community/retell-ai": {
"name": "@activepieces/piece-retell-ai",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -7882,7 +7882,8 @@
"@activepieces/pieces-framework": "workspace:*",
},
"devDependencies": {
- "tslib": "^2.3.0",
+ "tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/retune": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index faf1bc21169..974275e517e 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,14 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Retell AI 0.3.0: New Call fires only when a call starts, and webhooks must be signed
+
+The **New Call** trigger used to run the flow on every Retell webhook event for a call (started, ended and analyzed), so one call could start the flow three times. From Retell AI 0.3.0 it runs once per call, on the `call_started` event. Deliveries are also checked against Retell's `X-Retell-Signature` header (signed with your API key), and unsigned, forged, stale or repeated deliveries are ignored.
+
+#### What you need to do
+
+To react to a finished call or its analysis, use the new **Call Ended** or **Call Analyzed** trigger. Make sure the API key in your connection is the one with the webhook badge in Retell, or deliveries will not pass the signature check. Steps keep running on the version they were built with until you upgrade them.
+
#### WordPress Update Post keeps a post's categories and tags when those fields are empty
Update Post used to send an empty list when **Categories** or **Tags** was cleared or mapped to an empty list. WordPress then reset the post to the default category and removed all of its tags. From WordPress 0.9.0, an empty Categories or Tags field leaves the post's current categories and tags as they are, like every other empty field on the form. Steps keep running on the version they were built with until you upgrade them.
diff --git a/packages/pieces/community/retell-ai/package.json b/packages/pieces/community/retell-ai/package.json
index 7729aaff425..cc894083a3a 100644
--- a/packages/pieces/community/retell-ai/package.json
+++ b/packages/pieces/community/retell-ai/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-retell-ai",
- "version": "0.2.1",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -11,11 +11,13 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/retell-ai/src/i18n/translation.json b/packages/pieces/community/retell-ai/src/i18n/translation.json
index 1bea09c9b62..fbc3bc7e543 100644
--- a/packages/pieces/community/retell-ai/src/i18n/translation.json
+++ b/packages/pieces/community/retell-ai/src/i18n/translation.json
@@ -1,13 +1,55 @@
{
"API Key": "API Key",
"Your Retell AI API Key.": "Your Retell AI API Key.",
- "\n Please follow these steps to get your Retell AI API key:\n \n 1. Log in to your Retell AI dashboard.\n 2. Navigate to the API section.\n 3. Generate a new API key or copy your existing one.\n 4. Use this API key to authenticate your requests.": "\n Please follow these steps to get your Retell AI API key:\n \n 1. Log in to your Retell AI dashboard.\n 2. Navigate to the API section.\n 3. Generate a new API key or copy your existing one.\n 4. Use this API key to authenticate your requests.",
+ "\n To get your Retell AI API key:\n\n 1. Log in to your Retell AI dashboard.\n 2. Open **Settings > API Keys**.\n 3. Copy an existing key or create a new one.\n 4. To use the webhook triggers, use the key marked with the **webhook** badge: Retell signs webhooks with that key only.": "\n To get your Retell AI API key:\n\n 1. Log in to your Retell AI dashboard.\n 2. Open **Settings > API Keys**.\n 3. Copy an existing key or create a new one.\n 4. To use the webhook triggers, use the key marked with the **webhook** badge: Retell signs webhooks with that key only.",
"Make Phone Call": "Make Phone Call",
"Create Phone Number": "Create Phone Number",
"Get Call": "Get Call",
"Get Phone Number": "Get Phone Number",
"Get Voice": "Get Voice",
"Get Agent": "Get Agent",
+ "Create Batch Call": "Create Batch Call",
+ "Add Knowledge Base Sources": "Add Knowledge Base Sources",
+ "Buy Phone Number": "Buy Phone Number",
+ "Create Chat": "Create Chat",
+ "Create Contact": "Create Contact",
+ "Create Knowledge Base": "Create Knowledge Base",
+ "Create Phone Call": "Create Phone Call",
+ "Create SMS Chat": "Create SMS Chat",
+ "Create Web Call": "Create Web Call",
+ "Delete Agent": "Delete Agent",
+ "Delete Call": "Delete Call",
+ "Delete Knowledge Base Source": "Delete Knowledge Base Source",
+ "Delete Knowledge Base": "Delete Knowledge Base",
+ "Delete Phone Number": "Delete Phone Number",
+ "End Chat": "End Chat",
+ "Get Agent by ID": "Get Agent by ID",
+ "Get Call by ID": "Get Call by ID",
+ "Get Chat Agent": "Get Chat Agent",
+ "Get Chat": "Get Chat",
+ "Get Concurrency": "Get Concurrency",
+ "Get Contact by Phone": "Get Contact by Phone",
+ "Get Knowledge Base": "Get Knowledge Base",
+ "Get Retell LLM": "Get Retell LLM",
+ "Get Voice by ID": "Get Voice by ID",
+ "List Agent Versions": "List Agent Versions",
+ "List Agents": "List Agents",
+ "List Calls": "List Calls",
+ "List Chat Agents": "List Chat Agents",
+ "List Chats": "List Chats",
+ "List Contacts": "List Contacts",
+ "List Knowledge Bases": "List Knowledge Bases",
+ "List Phone Numbers": "List Phone Numbers",
+ "List Retell LLMs": "List Retell LLMs",
+ "List Voices": "List Voices",
+ "Publish Agent": "Publish Agent",
+ "Send Chat Message": "Send Chat Message",
+ "Stop Call": "Stop Call",
+ "Update Agent": "Update Agent",
+ "Update Call Metadata": "Update Call Metadata",
+ "Update Contact": "Update Contact",
+ "Update Phone Number Agents": "Update Phone Number Agents",
+ "Update Retell LLM Prompt": "Update Retell LLM Prompt",
"Custom API Call": "Custom API Call",
"Initiate a new outbound phone call using Retell AI agents.": "Initiate a new outbound phone call using Retell AI agents.",
"Buys a new phone number and binds agents.": "Buys a new phone number and binds agents.",
@@ -15,6 +57,48 @@
"Retrieve full details for an existing phone number in Retell AI.": "Retrieve full details for an existing phone number in Retell AI.",
"Retrieve details for a specific voice model or configuration by ID in Retell AI.": "Retrieve details for a specific voice model or configuration by ID in Retell AI.",
"Fetch details of a Retell AI agent by Agent ID.": "Fetch details of a Retell AI agent by Agent ID.",
+ "Schedules outbound calls to a list of numbers.": "Schedules outbound calls to a list of numbers.",
+ "Adds texts, URLs or a file to a knowledge base.": "Adds texts, URLs or a file to a knowledge base.",
+ "Buys a new US or Canadian phone number.": "Buys a new US or Canadian phone number.",
+ "Starts a text chat session with a chat agent.": "Starts a text chat session with a chat agent.",
+ "Creates a contact for a phone number.": "Creates a contact for a phone number.",
+ "Creates a knowledge base from texts, URLs or a file.": "Creates a knowledge base from texts, URLs or a file.",
+ "Places an outbound phone call handled by a Retell voice agent.": "Places an outbound phone call handled by a Retell voice agent.",
+ "Starts an outbound SMS conversation with a phone number.": "Starts an outbound SMS conversation with a phone number.",
+ "Creates a browser web call and returns its access token.": "Creates a browser web call and returns its access token.",
+ "Deletes a voice agent and all its versions.": "Deletes a voice agent and all its versions.",
+ "Deletes a call and its transcript and recording.": "Deletes a call and its transcript and recording.",
+ "Removes one source from a knowledge base.": "Removes one source from a knowledge base.",
+ "Deletes a knowledge base.": "Deletes a knowledge base.",
+ "Releases a phone number from the workspace.": "Releases a phone number from the workspace.",
+ "Ends an ongoing chat.": "Ends an ongoing chat.",
+ "Returns one voice agent.": "Returns one voice agent.",
+ "Returns one call with transcript, recording and analysis.": "Returns one call with transcript, recording and analysis.",
+ "Returns one chat agent.": "Returns one chat agent.",
+ "Returns one chat with transcript and analysis.": "Returns one chat with transcript and analysis.",
+ "Returns current and maximum concurrent calls.": "Returns current and maximum concurrent calls.",
+ "Finds the contact for a phone number.": "Finds the contact for a phone number.",
+ "Returns one knowledge base with its sources.": "Returns one knowledge base with its sources.",
+ "Returns one Retell LLM response engine.": "Returns one Retell LLM response engine.",
+ "Returns one voice.": "Returns one voice.",
+ "Lists the stored versions of an agent.": "Lists the stored versions of an agent.",
+ "Lists voice and chat agents.": "Lists voice and chat agents.",
+ "Lists calls newest first with optional filters.": "Lists calls newest first with optional filters.",
+ "Lists chat agents.": "Lists chat agents.",
+ "Lists chats newest first with optional filters.": "Lists chats newest first with optional filters.",
+ "Lists or searches contacts, newest first.": "Lists or searches contacts, newest first.",
+ "Lists all knowledge bases.": "Lists all knowledge bases.",
+ "Lists the phone numbers in the workspace.": "Lists the phone numbers in the workspace.",
+ "Lists Retell LLM response engines.": "Lists Retell LLM response engines.",
+ "Lists the voices available to agents.": "Lists the voices available to agents.",
+ "Publishes a draft version of a voice agent.": "Publishes a draft version of a voice agent.",
+ "Sends a user message to a chat and returns the agent reply.": "Sends a user message to a chat and returns the agent reply.",
+ "Hangs up an ongoing call.": "Hangs up an ongoing call.",
+ "Changes the name, voice, language or webhook URL of a voice agent draft.": "Changes the name, voice, language or webhook URL of a voice agent draft.",
+ "Replaces the metadata or data storage setting of a call.": "Replaces the metadata or data storage setting of a call.",
+ "Changes fields of an existing contact.": "Changes fields of an existing contact.",
+ "Changes the agents or nickname of a phone number.": "Changes the agents or nickname of a phone number.",
+ "Changes the prompt, begin message or model of a Retell LLM.": "Changes the prompt, begin message or model of a Retell LLM.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"From Number": "From Number",
"To Number": "To Number",
@@ -38,6 +122,54 @@
"Voice": "Voice",
"Agent ID": "Agent ID",
"Version": "Version",
+ "Calls": "Calls",
+ "Batch Name": "Batch Name",
+ "Scheduled Time": "Scheduled Time",
+ "Knowledge Base ID": "Knowledge Base ID",
+ "Texts": "Texts",
+ "URLs": "URLs",
+ "File": "File",
+ "Country": "Country",
+ "Inbound Agent ID": "Inbound Agent ID",
+ "Outbound Agent ID": "Outbound Agent ID",
+ "Chat Agent ID": "Chat Agent ID",
+ "Agent Version": "Agent Version",
+ "First Name": "First Name",
+ "Last Name": "Last Name",
+ "Do Not Call": "Do Not Call",
+ "Contact Memory": "Contact Memory",
+ "Custom Fields": "Custom Fields",
+ "Name": "Name",
+ "Source ID": "Source ID",
+ "Chat ID": "Chat ID",
+ "Retell LLM ID": "Retell LLM ID",
+ "Voice ID": "Voice ID",
+ "Limit": "Limit",
+ "Pagination Key": "Pagination Key",
+ "Channel": "Channel",
+ "Search": "Search",
+ "Call Statuses": "Call Statuses",
+ "Direction": "Direction",
+ "Call Type": "Call Type",
+ "Started After": "Started After",
+ "Started Before": "Started Before",
+ "Chat Statuses": "Chat Statuses",
+ "Chat Type": "Chat Type",
+ "Provider": "Provider",
+ "Gender": "Gender",
+ "Version Title": "Version Title",
+ "Version Description": "Version Description",
+ "Message": "Message",
+ "Agent Name": "Agent Name",
+ "Language": "Language",
+ "Webhook URL": "Webhook URL",
+ "Clear Webhook URL": "Clear Webhook URL",
+ "Data Storage Setting": "Data Storage Setting",
+ "Contact ID": "Contact ID",
+ "General Prompt": "General Prompt",
+ "Begin Message": "Begin Message",
+ "Clear Begin Message": "Clear Begin Message",
+ "Model": "Model",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -52,19 +184,107 @@
"Select the Retell AI agent.": "Select the Retell AI agent.",
"For this particular call, override the agent version used with this version. This does not bind the agent version to this number, this is for one time override.": "For this particular call, override the agent version used with this version. This does not bind the agent version to this number, this is for one time override.",
"An arbitrary object for storage purpose only. You can put anything here like your internal customer id associated with the call.": "An arbitrary object for storage purpose only. You can put anything here like your internal customer id associated with the call.",
- "Add optional dynamic variables in key value pairs of string that injects into your Response Engine prompt and tool description. Only applicable for Response Engine.": "Add optional dynamic variables in key value pairs of string that injects into your Response Engine prompt and tool description. Only applicable for Response Engine.",
+ "Key-value pairs for the agent prompt. Values are sent as text.": "Key-value pairs for the agent prompt. Values are sent as text.",
"Add optional custom SIP headers to the call.": "Add optional custom SIP headers to the call.",
"Version of the inbound agent to bind to the number. If not provided, will default to latest version.": "Version of the inbound agent to bind to the number. If not provided, will default to latest version.",
"Version of the outbound agent to bind to the number. If not provided, will default to latest version.": "Version of the outbound agent to bind to the number. If not provided, will default to latest version.",
- "Area code of the number to obtain. Format is a 3 digit integer. Currently only supports US area code.": "Area code of the number to obtain. Format is a 3 digit integer. Currently only supports US area code.",
+ "3-digit US area code. Leave empty when Phone Number is set.": "3-digit US area code. Leave empty when Phone Number is set.",
"Nickname of the number. This is for your reference only.": "Nickname of the number. This is for your reference only.",
"If set, will send a webhook for inbound calls, where you can to override agent id, set dynamic variables and other fields specific to that call.": "If set, will send a webhook for inbound calls, where you can to override agent id, set dynamic variables and other fields specific to that call.",
"The provider to purchase the phone number from.": "The provider to purchase the phone number from.",
"The country code for the phone number": "The country code for the phone number",
"Whether to purchase a toll-free number. Toll-free numbers incur higher costs.": "Whether to purchase a toll-free number. Toll-free numbers incur higher costs.",
- "The number you are trying to purchase in E.164 format of the number (+country code then number with no space and no special characters).": "The number you are trying to purchase in E.164 format of the number (+country code then number with no space and no special characters).",
+ "Exact E.164 number to buy. Leave empty when Area Code is set.": "Exact E.164 number to buy. Leave empty when Area Code is set.",
+ "The 100 most recent calls. Map a Call ID from an earlier step for older calls.": "The 100 most recent calls. Map a Call ID from an earlier step for older calls.",
"E.164 format of the number (+country code, then number with no space, no special characters), used as the unique identifier for phone number APIs. Example: \"+14157774444\"": "E.164 format of the number (+country code, then number with no space, no special characters), used as the unique identifier for phone number APIs. Example: \"+14157774444\"",
- "Optional version of the API to use for this request. If not provided, will default to latest version.": "Optional version of the API to use for this request. If not provided, will default to latest version.",
+ "Agent version to return. Leave empty for the latest version.": "Agent version to return. Leave empty for the latest version.",
+ "A number bought from or imported to Retell. E.164 format, for example +14157774444.": "A number bought from or imported to Retell. E.164 format, for example +14157774444.",
+ "One entry per person to call, at most 1000.": "One entry per person to call, at most 1000.",
+ "Optional name for your reference.": "Optional name for your reference.",
+ "Optional voice agent ID for every call. Empty = the outbound agent bound to From Number.": "Optional voice agent ID for every call. Empty = the outbound agent bound to From Number.",
+ "Optional ISO date or Unix time to start. Empty = start now.": "Optional ISO date or Unix time to start. Empty = start now.",
+ "Use List Knowledge Bases to find it.": "Use List Knowledge Bases to find it.",
+ "Optional text snippets to add, each with a title.": "Optional text snippets to add, each with a title.",
+ "Optional web pages Retell scrapes and adds.": "Optional web pages Retell scrapes and adds.",
+ "Optional document to add (PDF, DOCX, TXT, MD, CSV and similar, up to 50 MB).": "Optional document to add (PDF, DOCX, TXT, MD, CSV and similar, up to 50 MB).",
+ "Optional 3-digit US area code. Set this or Phone Number, not both.": "Optional 3-digit US area code. Set this or Phone Number, not both.",
+ "Optional exact number to buy. Set this or Area Code, not both. E.164 format, for example +14157774444.": "Optional exact number to buy. Set this or Area Code, not both. E.164 format, for example +14157774444.",
+ "Buy a toll-free number (higher cost).": "Buy a toll-free number (higher cost).",
+ "Optional voice agent that answers calls.": "Optional voice agent that answers calls.",
+ "Optional voice agent used for calls from this number.": "Optional voice agent used for calls from this number.",
+ "Chat agent ID. Use List Chat Agents to find it.": "Chat agent ID. Use List Chat Agents to find it.",
+ "Optional version number (for example 3) or version tag (for example prod). Empty = the agent default.": "Optional version number (for example 3) or version tag (for example prod). Empty = the agent default.",
+ "Optional JSON object stored with the record for your reference, for example {\"customer_id\": \"123\"}.": "Optional JSON object stored with the record for your reference, for example {\"customer_id\": \"123\"}.",
+ "Optional JSON object of prompt variables, for example {\"customer_name\": \"Ann\"}. Values are sent as text.": "Optional JSON object of prompt variables, for example {\"customer_name\": \"Ann\"}. Values are sent as text.",
+ "The contact phone number. E.164 format, for example +14157774444.": "The contact phone number. E.164 format, for example +14157774444.",
+ "Mark the number as do-not-call.": "Mark the number as do-not-call.",
+ "Optional notes agents can read about this person.": "Optional notes agents can read about this person.",
+ "Optional JSON object of custom field values from Retell CRM settings.": "Optional JSON object of custom field values from Retell CRM settings.",
+ "Knowledge base name, under 40 characters.": "Knowledge base name, under 40 characters.",
+ "The number to call. Retell-bought numbers can only call US numbers. E.164 format, for example +14157774444.": "The number to call. Retell-bought numbers can only call US numbers. E.164 format, for example +14157774444.",
+ "Optional voice agent ID (agent_...) for this call. Empty = the outbound agent bound to From Number.": "Optional voice agent ID (agent_...) for this call. Empty = the outbound agent bound to From Number.",
+ "An SMS-enabled number bought from or imported to Retell. E.164 format, for example +14157774444.": "An SMS-enabled number bought from or imported to Retell. E.164 format, for example +14157774444.",
+ "The number to text. E.164 format, for example +14157774444.": "The number to text. E.164 format, for example +14157774444.",
+ "Optional chat agent ID. Empty = the outbound SMS agent bound to From Number.": "Optional chat agent ID. Empty = the outbound SMS agent bound to From Number.",
+ "Voice agent ID (agent_...). Use List Agents to find it.": "Voice agent ID (agent_...). Use List Agents to find it.",
+ "Voice agent ID to delete.": "Voice agent ID to delete.",
+ "The call to delete.": "The call to delete.",
+ "The knowledge base that holds the source.": "The knowledge base that holds the source.",
+ "The source to remove.": "The source to remove.",
+ "The knowledge base to delete.": "The knowledge base to delete.",
+ "The Retell number to release. E.164 format, for example +14157774444.": "The Retell number to release. E.164 format, for example +14157774444.",
+ "The chat to end.": "The chat to end.",
+ "Voice agent ID. Use List Agents to find it.": "Voice agent ID. Use List Agents to find it.",
+ "Optional version number. Empty = latest.": "Optional version number. Empty = latest.",
+ "The call ID returned when the call was created or listed.": "The call ID returned when the call was created or listed.",
+ "The chat ID.": "The chat ID.",
+ "The phone number to look up. E.164 format, for example +14157774444.": "The phone number to look up. E.164 format, for example +14157774444.",
+ "The llm_id of the response engine.": "The llm_id of the response engine.",
+ "For example 11labs-Adrian. Use List Voices to find it.": "For example 11labs-Adrian. Use List Voices to find it.",
+ "Voice or chat agent ID.": "Voice or chat agent ID.",
+ "Items per page, 1 to 1000. Default 50.": "Items per page, 1 to 1000. Default 50.",
+ "pagination_key from the previous page. Empty for the first page.": "pagination_key from the previous page. Empty for the first page.",
+ "Optional: only voice or only chat agents.": "Optional: only voice or only chat agents.",
+ "Optional text matched against agent name and ID.": "Optional text matched against agent name and ID.",
+ "Optional agent ID to only list its calls.": "Optional agent ID to only list its calls.",
+ "Optional comma-separated statuses: not_connected, ongoing, ended, error.": "Optional comma-separated statuses: not_connected, ongoing, ended, error.",
+ "Optional caller number. E.164 format, for example +14157774444.": "Optional caller number. E.164 format, for example +14157774444.",
+ "Optional called number. E.164 format, for example +14157774444.": "Optional called number. E.164 format, for example +14157774444.",
+ "Optional ISO date or Unix time; calls that started at or after it.": "Optional ISO date or Unix time; calls that started at or after it.",
+ "Optional ISO date or Unix time; calls that started at or before it.": "Optional ISO date or Unix time; calls that started at or before it.",
+ "Optional agent ID to only list its chats.": "Optional agent ID to only list its chats.",
+ "Optional comma-separated statuses: ongoing, ended, error.": "Optional comma-separated statuses: ongoing, ended, error.",
+ "Optional case-insensitive text to match.": "Optional case-insensitive text to match.",
+ "Optional text matched against the name.": "Optional text matched against the name.",
+ "Optional text matched against voice name and ID.": "Optional text matched against voice name and ID.",
+ "Optional provider such as elevenlabs, openai or cartesia.": "Optional provider such as elevenlabs, openai or cartesia.",
+ "Voice agent ID.": "Voice agent ID.",
+ "The draft version number to publish.": "The draft version number to publish.",
+ "Optional title for this version.": "Optional title for this version.",
+ "Optional note about what changed.": "Optional note about what changed.",
+ "chat_id returned by Create Chat.": "chat_id returned by Create Chat.",
+ "The user message text.": "The user message text.",
+ "The ongoing call to stop.": "The ongoing call to stop.",
+ "Optional new name.": "Optional new name.",
+ "Optional voice ID, for example 11labs-Adrian. Use List Voices.": "Optional voice ID, for example 11labs-Adrian. Use List Voices.",
+ "Optional language code such as en-US, es-ES, de-DE or multi.": "Optional language code such as en-US, es-ES, de-DE or multi.",
+ "Optional agent webhook URL; overrides the account webhook.": "Optional agent webhook URL; overrides the account webhook.",
+ "Remove the agent-level webhook so the account webhook is used again.": "Remove the agent-level webhook so the account webhook is used again.",
+ "The call to update.": "The call to update.",
+ "JSON object that replaces the call metadata.": "JSON object that replaces the call metadata.",
+ "Optional. basic_attributes_only drops transcript and recording.": "Optional. basic_attributes_only drops transcript and recording.",
+ "Use Get Contact by Phone or List Contacts to find it.": "Use Get Contact by Phone or List Contacts to find it.",
+ "Optional: set or clear the do-not-call flag.": "Optional: set or clear the do-not-call flag.",
+ "Optional notes; replaces the old notes.": "Optional notes; replaces the old notes.",
+ "Optional JSON object of custom field values; null clears a field.": "Optional JSON object of custom field values; null clears a field.",
+ "The Retell number to change. E.164 format, for example +14157774444.": "The Retell number to change. E.164 format, for example +14157774444.",
+ "Optional voice agent for outbound calls.": "Optional voice agent for outbound calls.",
+ "Optional version number or tag for the outbound agent.": "Optional version number or tag for the outbound agent.",
+ "Optional new nickname.": "Optional new nickname.",
+ "Optional new system prompt (replaces the old one).": "Optional new system prompt (replaces the old one).",
+ "Optional first sentence the agent says.": "Optional first sentence the agent says.",
+ "Remove the begin message so the agent generates its own opener.": "Remove the begin message so the agent generates its own opener.",
+ "Optional model name, for example gpt-4.1 or claude-4.5-sonnet.": "Optional model name, for example gpt-4.1 or claude-4.5-sonnet.",
"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.",
@@ -75,6 +295,20 @@
"Telnyx": "Telnyx",
"United States": "United States",
"Canada": "Canada",
+ "Chat": "Chat",
+ "Inbound": "Inbound",
+ "Outbound": "Outbound",
+ "Phone Call": "Phone Call",
+ "Web Call": "Web Call",
+ "API Chat": "API Chat",
+ "SMS Chat": "SMS Chat",
+ "Male": "Male",
+ "Female": "Female",
+ "Everything": "Everything",
+ "Everything Except PII": "Everything Except PII",
+ "Basic Attributes Only": "Basic Attributes Only",
+ "Yes": "Yes",
+ "No": "No",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
@@ -82,7 +316,13 @@
"DELETE": "DELETE",
"HEAD": "HEAD",
"New Call": "New Call",
- "Triggers when a new outgoing or incoming call is created.": "Triggers when a new outgoing or incoming call is created.",
+ "Call Ended": "Call Ended",
+ "Call Analyzed": "Call Analyzed",
+ "Triggers when an inbound or outbound call starts (call_started event).": "Triggers when an inbound or outbound call starts (call_started event).",
+ "Triggers when a call ends (call_ended event), with transcript and recording.": "Triggers when a call ends (call_ended event), with transcript and recording.",
+ "Triggers when post-call analysis is ready (call_analyzed event).": "Triggers when post-call analysis is ready (call_analyzed event).",
"Markdown": "Markdown",
- "\n To use this trigger, you need to manually set up a webhook in your Retell AI account:\n\n 1. Login to your Retell AI dashboard.\n 2. Navigate to the Webhooks section in your settings.\n 3. Click on \"Add Webhook\" or \"Create New Webhook\".\n 4. Add the following URL in the **Webhook URL** field:\n ```text\n {{webhookUrl}}\n ```\n 5. Select the **call.created** event type.\n 6. Click Save to create the webhook.\n ": "\n To use this trigger, you need to manually set up a webhook in your Retell AI account:\n\n 1. Login to your Retell AI dashboard.\n 2. Navigate to the Webhooks section in your settings.\n 3. Click on \"Add Webhook\" or \"Create New Webhook\".\n 4. Add the following URL in the **Webhook URL** field:\n ```text\n {{webhookUrl}}\n ```\n 5. Select the **call.created** event type.\n 6. Click Save to create the webhook.\n "
+ "Retell sends call events to one account-level webhook URL. To use this trigger:\n\n1. In the Retell AI dashboard, open **Settings > Webhooks**.\n2. Set the account webhook URL to:\n```text\n{{webhookUrl}}\n```\n3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **call_started**.\n4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.\n\nAn agent ": "Retell sends call events to one account-level webhook URL. To use this trigger:\n\n1. In the Retell AI dashboard, open **Settings > Webhooks**.\n2. Set the account webhook URL to:\n```text\n{{webhookUrl}}\n```\n3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **call_started**.\n4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.\n\nAn agent with its own webhook URL sends its events there instead of to the account URL. Nothing is registered or removed automatically when this flow is turned on or off.",
+ "Retell sends call events to one account-level webhook URL. To use this trigger:\n\n1. In the Retell AI dashboard, open **Settings > Webhooks**.\n2. Set the account webhook URL to:\n```text\n{{webhookUrl}}\n```\n3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **call_ended**.\n4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.\n\nAn agent wi": "Retell sends call events to one account-level webhook URL. To use this trigger:\n\n1. In the Retell AI dashboard, open **Settings > Webhooks**.\n2. Set the account webhook URL to:\n```text\n{{webhookUrl}}\n```\n3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **call_ended**.\n4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.\n\nAn agent with its own webhook URL sends its events there instead of to the account URL. Nothing is registered or removed automatically when this flow is turned on or off.",
+ "Retell sends call events to one account-level webhook URL. To use this trigger:\n\n1. In the Retell AI dashboard, open **Settings > Webhooks**.\n2. Set the account webhook URL to:\n```text\n{{webhookUrl}}\n```\n3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **call_analyzed**.\n4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.\n\nAn agent": "Retell sends call events to one account-level webhook URL. To use this trigger:\n\n1. In the Retell AI dashboard, open **Settings > Webhooks**.\n2. Set the account webhook URL to:\n```text\n{{webhookUrl}}\n```\n3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **call_analyzed**.\n4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.\n\nAn agent with its own webhook URL sends its events there instead of to the account URL. Nothing is registered or removed automatically when this flow is turned on or off."
}
\ No newline at end of file
diff --git a/packages/pieces/community/retell-ai/src/index.ts b/packages/pieces/community/retell-ai/src/index.ts
index 4035f0f8bff..5bdd7e97f6b 100644
--- a/packages/pieces/community/retell-ai/src/index.ts
+++ b/packages/pieces/community/retell-ai/src/index.ts
@@ -1,40 +1,122 @@
-
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { createPiece } from "@activepieces/pieces-framework";
-import { retellAiAuth } from './lib/common/auth';
-import { makePhoneCall } from './lib/actions/make-phone-call';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createBatchCallAction } from './lib/actions/create-batch-call';
import { createPhoneNumber } from './lib/actions/create-phone-number';
+import { getAgent } from './lib/actions/get-agent';
import { getCall } from './lib/actions/get-call';
import { getPhoneNumber } from './lib/actions/get-phone-number';
import { getVoice } from './lib/actions/get-voice';
-import { getAgent } from './lib/actions/get-agent';
+import { makePhoneCall } from './lib/actions/make-phone-call';
+import { addKnowledgeBaseSourcesAction } from './lib/actions/ai/add-knowledge-base-sources';
+import { buyPhoneNumberAction } from './lib/actions/ai/buy-phone-number';
+import { createChatAction } from './lib/actions/ai/create-chat';
+import { createContactAction } from './lib/actions/ai/create-contact';
+import { createKnowledgeBaseAction } from './lib/actions/ai/create-knowledge-base';
+import { createPhoneCallAction } from './lib/actions/ai/create-phone-call';
+import { createSmsChatAction } from './lib/actions/ai/create-sms-chat';
+import { createWebCallAction } from './lib/actions/ai/create-web-call';
+import { deleteAgentAction } from './lib/actions/ai/delete-agent';
+import { deleteCallAction } from './lib/actions/ai/delete-call';
+import { deleteKnowledgeBaseSourceAction } from './lib/actions/ai/delete-knowledge-base-source';
+import { deleteKnowledgeBaseAction } from './lib/actions/ai/delete-knowledge-base';
+import { deletePhoneNumberAction } from './lib/actions/ai/delete-phone-number';
+import { endChatAction } from './lib/actions/ai/end-chat';
+import { getAgentByIdAction } from './lib/actions/ai/get-agent-by-id';
+import { getCallByIdAction } from './lib/actions/ai/get-call-by-id';
+import { getChatAgentAction } from './lib/actions/ai/get-chat-agent';
+import { getChatAction } from './lib/actions/ai/get-chat';
+import { getConcurrencyAction } from './lib/actions/ai/get-concurrency';
+import { getContactByPhoneAction } from './lib/actions/ai/get-contact-by-phone';
+import { getKnowledgeBaseAction } from './lib/actions/ai/get-knowledge-base';
+import { getRetellLlmAction } from './lib/actions/ai/get-retell-llm';
+import { getVoiceByIdAction } from './lib/actions/ai/get-voice-by-id';
+import { listAgentVersionsAction } from './lib/actions/ai/list-agent-versions';
+import { listAgentsAction } from './lib/actions/ai/list-agents';
+import { listCallsAction } from './lib/actions/ai/list-calls';
+import { listChatAgentsAction } from './lib/actions/ai/list-chat-agents';
+import { listChatsAction } from './lib/actions/ai/list-chats';
+import { listContactsAction } from './lib/actions/ai/list-contacts';
+import { listKnowledgeBasesAction } from './lib/actions/ai/list-knowledge-bases';
+import { listPhoneNumbersAction } from './lib/actions/ai/list-phone-numbers';
+import { listRetellLlmsAction } from './lib/actions/ai/list-retell-llms';
+import { listVoicesAction } from './lib/actions/ai/list-voices';
+import { publishAgentAction } from './lib/actions/ai/publish-agent';
+import { sendChatMessageAction } from './lib/actions/ai/send-chat-message';
+import { stopCallAction } from './lib/actions/ai/stop-call';
+import { updateAgentAction } from './lib/actions/ai/update-agent';
+import { updateCallMetadataAction } from './lib/actions/ai/update-call-metadata';
+import { updateContactAction } from './lib/actions/ai/update-contact';
+import { updatePhoneNumberAgentsAction } from './lib/actions/ai/update-phone-number-agents';
+import { updateRetellLlmPromptAction } from './lib/actions/ai/update-retell-llm-prompt';
+import { retellAiAuth } from './lib/common/auth';
+import { RETELL_BASE_URL } from './lib/common/client';
+import { callAnalyzedTrigger } from './lib/triggers/call-analyzed';
+import { callEndedTrigger } from './lib/triggers/call-ended';
import { newCallTrigger } from './lib/triggers/new-call';
-import { PieceCategory } from '@activepieces/pieces-framework';
export const retellAi = createPiece({
- displayName: "Retell AI",
+ displayName: 'Retell AI',
auth: retellAiAuth,
- minimumSupportedRelease: '0.36.1',
- logoUrl: "https://cdn.activepieces.com/pieces/retell-ai.png",
+ minimumSupportedRelease: '0.88.2',
+ logoUrl: 'https://cdn.activepieces.com/pieces/retell-ai.png',
authors: ['aryel780'],
- categories:[PieceCategory.BUSINESS_INTELLIGENCE,PieceCategory.PRODUCTIVITY,PieceCategory.COMMUNICATION],
+ categories: [PieceCategory.BUSINESS_INTELLIGENCE, PieceCategory.PRODUCTIVITY, PieceCategory.COMMUNICATION],
actions: [
- makePhoneCall,
- createPhoneNumber,
- getCall,
- getPhoneNumber,
- getVoice,
+ makePhoneCall,
+ createPhoneNumber,
+ getCall,
+ getPhoneNumber,
+ getVoice,
getAgent,
+ createBatchCallAction,
+ addKnowledgeBaseSourcesAction,
+ buyPhoneNumberAction,
+ createChatAction,
+ createContactAction,
+ createKnowledgeBaseAction,
+ createPhoneCallAction,
+ createSmsChatAction,
+ createWebCallAction,
+ deleteAgentAction,
+ deleteCallAction,
+ deleteKnowledgeBaseSourceAction,
+ deleteKnowledgeBaseAction,
+ deletePhoneNumberAction,
+ endChatAction,
+ getAgentByIdAction,
+ getCallByIdAction,
+ getChatAgentAction,
+ getChatAction,
+ getConcurrencyAction,
+ getContactByPhoneAction,
+ getKnowledgeBaseAction,
+ getRetellLlmAction,
+ getVoiceByIdAction,
+ listAgentVersionsAction,
+ listAgentsAction,
+ listCallsAction,
+ listChatAgentsAction,
+ listChatsAction,
+ listContactsAction,
+ listKnowledgeBasesAction,
+ listPhoneNumbersAction,
+ listRetellLlmsAction,
+ listVoicesAction,
+ publishAgentAction,
+ sendChatMessageAction,
+ stopCallAction,
+ updateAgentAction,
+ updateCallMetadataAction,
+ updateContactAction,
+ updatePhoneNumberAgentsAction,
+ updateRetellLlmPromptAction,
createCustomApiCallAction({
auth: retellAiAuth,
- baseUrl: () => 'https://api.retellai.com',
- authMapping: async (auth) => {
- const { apiKey } = auth.props;
- return {
- Authorization: `Bearer ${apiKey}`,
- };
- },
+ baseUrl: () => RETELL_BASE_URL,
+ authMapping: async (auth) => ({
+ Authorization: `Bearer ${auth.props.apiKey.trim()}`,
+ }),
}),
],
- triggers: [newCallTrigger],
+ triggers: [newCallTrigger, callEndedTrigger, callAnalyzedTrigger],
});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/add-knowledge-base-sources.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/add-knowledge-base-sources.ts
new file mode 100644
index 00000000000..0512deb4a1d
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/add-knowledge-base-sources.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+import { buildKnowledgeBaseForm, knowledgeBaseSourceProps } from '../../common/knowledge-base';
+
+export const addKnowledgeBaseSourcesAction = createAction({
+ auth: retellAiAuth,
+ name: 'add_knowledge_base_sources',
+ classification: 'WRITE',
+ displayName: 'Add Knowledge Base Sources',
+ description: 'Adds texts, URLs or a file to a knowledge base.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Adds text snippets, web page URLs and/or one file to an existing Retell knowledge base. Each run adds the sources again as new entries, so do not retry a run that succeeded.',
+ idempotent: false,
+ },
+ props: {
+ knowledge_base_id: retellAiProps.id({ displayName: 'Knowledge Base ID', description: 'Use List Knowledge Bases to find it.' }),
+ texts: knowledgeBaseSourceProps.texts,
+ urls: knowledgeBaseSourceProps.urls,
+ file: knowledgeBaseSourceProps.file,
+ },
+ outputSchema: retellSchemas.knowledgeBase,
+ async run({ auth, propsValue }) {
+ const form = buildKnowledgeBaseForm({
+ texts: propsValue.texts,
+ urls: propsValue.urls,
+ file: propsValue.file,
+ requireSource: true,
+ });
+ const knowledgeBase = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: `/add-knowledge-base-sources/${retellInput.seg({ value: propsValue.knowledge_base_id, label: 'Knowledge Base ID' })}`,
+ body: form.body,
+ contentType: form.contentType,
+ timeoutMs: 120000,
+ });
+ return retellMap.knowledgeBase(knowledgeBase);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/buy-phone-number.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/buy-phone-number.ts
new file mode 100644
index 00000000000..baab45cfac5
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/buy-phone-number.ts
@@ -0,0 +1,65 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+import { buildBuyNumberBody } from '../create-phone-number';
+
+export const buyPhoneNumberAction = createAction({
+ auth: retellAiAuth,
+ name: 'buy_phone_number',
+ classification: 'WRITE',
+ displayName: 'Buy Phone Number',
+ description: 'Buys a new US or Canadian phone number.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Buys a new Retell phone number by area code or exact number (US/CA) and optionally binds inbound/outbound voice agents. Adds a monthly fee per number; each run buys another number, so never retry blindly. Use Update Phone Number Agents to rebind an existing number.',
+ idempotent: false,
+ },
+ props: {
+ area_code: Property.Number({
+ displayName: 'Area Code',
+ description: 'Optional 3-digit US area code. Set this or Phone Number, not both.',
+ required: false,
+ }),
+ phone_number: retellAiProps.e164Number({
+ displayName: 'Phone Number',
+ description: 'Optional exact number to buy. Set this or Area Code, not both.',
+ required: false,
+ }),
+ country_code: Property.StaticDropdown({
+ displayName: 'Country',
+ required: false,
+ options: { options: [{ label: 'United States', value: 'US' }, { label: 'Canada', value: 'CA' }] },
+ }),
+ toll_free: Property.Checkbox({ displayName: 'Toll Free', description: 'Buy a toll-free number (higher cost).', required: false }),
+ inbound_agent_id: retellAiProps.id({ displayName: 'Inbound Agent ID', description: 'Optional voice agent that answers calls.', required: false }),
+ outbound_agent_id: retellAiProps.id({ displayName: 'Outbound Agent ID', description: 'Optional voice agent used for calls from this number.', required: false }),
+ nickname: Property.ShortText({ displayName: 'Nickname', description: 'Optional name for your reference.', required: false }),
+ },
+ outputSchema: retellSchemas.phoneNumber,
+ async run({ auth, propsValue }) {
+ const number = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: '/create-phone-number',
+ body: buildBuyNumberBody({
+ inboundAgentId: propsValue.inbound_agent_id,
+ inboundAgentVersion: undefined,
+ outboundAgentId: propsValue.outbound_agent_id,
+ outboundAgentVersion: undefined,
+ areaCode: propsValue.area_code,
+ phoneNumber: propsValue.phone_number,
+ nickname: propsValue.nickname,
+ inboundWebhookUrl: undefined,
+ numberProvider: undefined,
+ countryCode: propsValue.country_code,
+ tollFree: propsValue.toll_free,
+ }),
+ });
+ return retellMap.phoneNumber(number);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/create-chat.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-chat.ts
new file mode 100644
index 00000000000..c196d30acca
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-chat.ts
@@ -0,0 +1,47 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const createChatAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_chat',
+ classification: 'WRITE',
+ displayName: 'Create Chat',
+ description: 'Starts a text chat session with a chat agent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Starts a new text chat session with a Retell chat agent and returns its chat_id; then use Send Chat Message for each user turn and End Chat when done. Each run opens another session.',
+ idempotent: false,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Chat Agent ID', description: 'Chat agent ID. Use List Chat Agents to find it.' }),
+ agent_version: retellAiProps.agentVersion(),
+ metadata: retellAiProps.metadata(),
+ dynamic_variables: retellAiProps.dynamicVariables(),
+ },
+ outputSchema: retellSchemas.chat,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {
+ agent_id: retellInput.requiredText({ value: propsValue.agent_id, label: 'Chat Agent ID' }),
+ };
+ const version = retellInput.agentVersion({ value: propsValue.agent_version, label: 'Agent Version' });
+ if (version !== undefined) {
+ body['agent_version'] = version;
+ }
+ const metadata = retellInput.objectValue({ value: propsValue.metadata, label: 'Metadata' });
+ if (metadata !== undefined) {
+ body['metadata'] = metadata;
+ }
+ const variables = retellInput.stringMap({ value: propsValue.dynamic_variables, label: 'Dynamic Variables' });
+ if (variables !== undefined) {
+ body['retell_llm_dynamic_variables'] = variables;
+ }
+ const chat = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: '/create-chat', body });
+ return retellMap.chat(chat);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/create-contact.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-contact.ts
new file mode 100644
index 00000000000..41557bcba78
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-contact.ts
@@ -0,0 +1,72 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const createContactAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_contact',
+ classification: 'WRITE',
+ displayName: 'Create Contact',
+ description: 'Creates a contact for a phone number.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a Retell contact (name, do-not-call flag, memory notes, custom fields) for a phone number. Only one contact can exist per number, so look it up with Get Contact by Phone first and use Update Contact if it exists; a second run for the same number fails.',
+ idempotent: false,
+ },
+ props: {
+ phone_number: retellAiProps.e164Number({ displayName: 'Phone Number', description: 'The contact phone number.' }),
+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),
+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),
+ do_not_call: Property.Checkbox({ displayName: 'Do Not Call', description: 'Mark the number as do-not-call.', required: false }),
+ contact_memory: Property.LongText({ displayName: 'Contact Memory', description: 'Optional notes agents can read about this person.', required: false }),
+ custom_fields: Property.Json({
+ displayName: 'Custom Fields',
+ description: 'Optional JSON object of custom field values from Retell CRM settings.',
+ required: false,
+ }),
+ },
+ outputSchema: retellSchemas.contact,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {
+ phone_number: retellInput.e164({ value: propsValue.phone_number, label: 'Phone Number' }),
+ ...contactFields(propsValue),
+ };
+ const contact = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: '/create-contact', body });
+ return retellMap.contact(contact);
+ },
+});
+
+export function contactFields(input: {
+ first_name?: unknown;
+ last_name?: unknown;
+ do_not_call?: unknown;
+ contact_memory?: unknown;
+ custom_fields?: unknown;
+}): Record<string, unknown> {
+ const body: Record<string, unknown> = {};
+ const firstName = retellInput.optionalText(input.first_name);
+ if (firstName !== undefined) {
+ body['first_name'] = firstName;
+ }
+ const lastName = retellInput.optionalText(input.last_name);
+ if (lastName !== undefined) {
+ body['last_name'] = lastName;
+ }
+ if (typeof input.do_not_call === 'boolean') {
+ body['do_not_call'] = input.do_not_call;
+ }
+ const memory = retellInput.optionalText(input.contact_memory);
+ if (memory !== undefined) {
+ body['contact_memory'] = memory;
+ }
+ const customFields = retellInput.objectValue({ value: input.custom_fields, label: 'Custom Fields' });
+ if (customFields !== undefined) {
+ body['custom_fields'] = customFields;
+ }
+ return body;
+}
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/create-knowledge-base.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-knowledge-base.ts
new file mode 100644
index 00000000000..5f058370d18
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-knowledge-base.ts
@@ -0,0 +1,51 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+import { buildKnowledgeBaseForm, knowledgeBaseSourceProps } from '../../common/knowledge-base';
+
+export const createKnowledgeBaseAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_knowledge_base',
+ classification: 'WRITE',
+ displayName: 'Create Knowledge Base',
+ description: 'Creates a knowledge base from texts, URLs or a file.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a new Retell knowledge base from text snippets, web page URLs and/or one file, which agents can then search during calls. Indexing runs in the background (status in_progress). Each run creates another knowledge base.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', description: 'Knowledge base name, under 40 characters.', required: true }),
+ texts: knowledgeBaseSourceProps.texts,
+ urls: knowledgeBaseSourceProps.urls,
+ file: knowledgeBaseSourceProps.file,
+ },
+ outputSchema: retellSchemas.knowledgeBase,
+ async run({ auth, propsValue }) {
+ const name = retellInput.requiredText({ value: propsValue.name, label: 'Name' });
+ if (name.length >= 40) {
+ throw new Error('Name must be shorter than 40 characters.');
+ }
+ const form = buildKnowledgeBaseForm({
+ name,
+ texts: propsValue.texts,
+ urls: propsValue.urls,
+ file: propsValue.file,
+ requireSource: false,
+ });
+ const knowledgeBase = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: '/create-knowledge-base',
+ body: form.body,
+ contentType: form.contentType,
+ timeoutMs: 120000,
+ });
+ return retellMap.knowledgeBase(knowledgeBase);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/create-phone-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-phone-call.ts
new file mode 100644
index 00000000000..b73d2bd288c
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-phone-call.ts
@@ -0,0 +1,59 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+
+export const createPhoneCallAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_phone_call',
+ classification: 'WRITE',
+ displayName: 'Create Phone Call',
+ description: 'Places an outbound phone call handled by a Retell voice agent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Places a real outbound phone call from a Retell number to a person, handled by a Retell voice agent. Billed per minute; each run dials again, so never retry blindly. Returns the call ID; use Get Call by ID after it ends to read the outcome and transcript.',
+ idempotent: false,
+ },
+ props: {
+ from_number: retellAiProps.e164Number({ displayName: 'From Number', description: 'A number bought from or imported to Retell.' }),
+ to_number: retellAiProps.e164Number({ displayName: 'To Number', description: 'The number to call. Retell-bought numbers can only call US numbers.' }),
+ agent_id: retellAiProps.id({
+ displayName: 'Agent ID',
+ description: 'Optional voice agent ID (agent_...) for this call. Empty = the outbound agent bound to From Number.',
+ required: false,
+ }),
+ agent_version: retellAiProps.agentVersion(),
+ metadata: retellAiProps.metadata(),
+ dynamic_variables: retellAiProps.dynamicVariables(),
+ },
+ outputSchema: retellSchemas.call,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {
+ from_number: retellInput.e164({ value: propsValue.from_number, label: 'From Number' }),
+ to_number: retellInput.e164({ value: propsValue.to_number, label: 'To Number' }),
+ };
+ const agentId = retellInput.optionalText(propsValue.agent_id);
+ if (agentId !== undefined) {
+ body['override_agent_id'] = agentId;
+ }
+ const version = retellInput.agentVersion({ value: propsValue.agent_version, label: 'Agent Version' });
+ if (version !== undefined) {
+ body['override_agent_version'] = version;
+ }
+ const metadata = retellInput.objectValue({ value: propsValue.metadata, label: 'Metadata' });
+ if (metadata !== undefined) {
+ body['metadata'] = metadata;
+ }
+ const variables = retellInput.stringMap({ value: propsValue.dynamic_variables, label: 'Dynamic Variables' });
+ if (variables !== undefined) {
+ body['retell_llm_dynamic_variables'] = variables;
+ }
+ const call = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: '/v2/create-phone-call', body });
+ return retellMap.call(call);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/create-sms-chat.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-sms-chat.ts
new file mode 100644
index 00000000000..3cea001f362
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-sms-chat.ts
@@ -0,0 +1,58 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const createSmsChatAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_sms_chat',
+ classification: 'WRITE',
+ displayName: 'Create SMS Chat',
+ description: 'Starts an outbound SMS conversation with a phone number.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Texts a real phone number from a Retell number: the chat agent writes and sends the first SMS, then replies to the person's answers. Billed per message and subject to SMS consent rules; each run sends another first message, so never retry blindly.",
+ idempotent: false,
+ },
+ props: {
+ from_number: retellAiProps.e164Number({ displayName: 'From Number', description: 'An SMS-enabled number bought from or imported to Retell.' }),
+ to_number: retellAiProps.e164Number({ displayName: 'To Number', description: 'The number to text.' }),
+ agent_id: retellAiProps.id({
+ displayName: 'Chat Agent ID',
+ description: 'Optional chat agent ID. Empty = the outbound SMS agent bound to From Number.',
+ required: false,
+ }),
+ agent_version: retellAiProps.agentVersion(),
+ metadata: retellAiProps.metadata(),
+ dynamic_variables: retellAiProps.dynamicVariables(),
+ },
+ outputSchema: retellSchemas.chat,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {
+ from_number: retellInput.e164({ value: propsValue.from_number, label: 'From Number' }),
+ to_number: retellInput.e164({ value: propsValue.to_number, label: 'To Number' }),
+ };
+ const agentId = retellInput.optionalText(propsValue.agent_id);
+ if (agentId !== undefined) {
+ body['override_agent_id'] = agentId;
+ }
+ const version = retellInput.agentVersion({ value: propsValue.agent_version, label: 'Agent Version' });
+ if (version !== undefined) {
+ body['override_agent_version'] = version;
+ }
+ const metadata = retellInput.objectValue({ value: propsValue.metadata, label: 'Metadata' });
+ if (metadata !== undefined) {
+ body['metadata'] = metadata;
+ }
+ const variables = retellInput.stringMap({ value: propsValue.dynamic_variables, label: 'Dynamic Variables' });
+ if (variables !== undefined) {
+ body['retell_llm_dynamic_variables'] = variables;
+ }
+ const chat = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: '/create-sms-chat', body });
+ return retellMap.chat(chat);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/create-web-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-web-call.ts
new file mode 100644
index 00000000000..1f05ba5c025
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/create-web-call.ts
@@ -0,0 +1,48 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+
+export const createWebCallAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_web_call',
+ classification: 'WRITE',
+ displayName: 'Create Web Call',
+ description: 'Creates a browser web call and returns its access token.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Registers a browser (web) call with a Retell voice agent and returns the call ID plus a short-lived access token for the Retell web client SDK. Billed per minute once someone joins. Each run creates a new call.',
+ idempotent: false,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Voice agent ID (agent_...). Use List Agents to find it.' }),
+ agent_version: retellAiProps.agentVersion(),
+ metadata: retellAiProps.metadata(),
+ dynamic_variables: retellAiProps.dynamicVariables(),
+ },
+ outputSchema: retellSchemas.webCall,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {
+ agent_id: retellInput.requiredText({ value: propsValue.agent_id, label: 'Agent ID' }),
+ };
+ const version = retellInput.agentVersion({ value: propsValue.agent_version, label: 'Agent Version' });
+ if (version !== undefined) {
+ body['agent_version'] = version;
+ }
+ const metadata = retellInput.objectValue({ value: propsValue.metadata, label: 'Metadata' });
+ if (metadata !== undefined) {
+ body['metadata'] = metadata;
+ }
+ const variables = retellInput.stringMap({ value: propsValue.dynamic_variables, label: 'Dynamic Variables' });
+ if (variables !== undefined) {
+ body['retell_llm_dynamic_variables'] = variables;
+ }
+ const call = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: '/v3/create-web-call', body });
+ return retellMap.webCall(call);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-agent.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-agent.ts
new file mode 100644
index 00000000000..80ed25c3a47
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-agent.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, isRetellStatus, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+export const deleteAgentAction = createAction({
+ auth: retellAiAuth,
+ name: 'delete_agent',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Agent',
+ description: 'Deletes a voice agent and all its versions.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a voice agent with all its versions; numbers bound to it stop answering with it. Cannot be undone. An agent that is already gone returns already_deleted=true.',
+ idempotent: false,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Voice agent ID to delete.' }),
+ },
+ outputSchema: retellSchemas.deleted({ idKey: 'agent_id', idLabel: 'Agent ID' }),
+ async run({ auth, propsValue }) {
+ const agentId = retellInput.seg({ value: propsValue.agent_id, label: 'Agent ID' });
+ try {
+ await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.DELETE, path: `/delete-agent/${agentId}` });
+ } catch (error) {
+ if (isRetellStatus({ error, statuses: [404] })) {
+ return { agent_id: decodeURIComponent(agentId), deleted: false, already_deleted: true };
+ }
+ throw error;
+ }
+ return { agent_id: decodeURIComponent(agentId), deleted: true, already_deleted: false };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-call.ts
new file mode 100644
index 00000000000..f0e6eede337
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-call.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, isRetellStatus, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+export const deleteCallAction = createAction({
+ auth: retellAiAuth,
+ name: 'delete_call',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Call',
+ description: 'Deletes a call and its transcript and recording.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one call record with its transcript, recording and analysis. Cannot be undone. A call that is already gone returns already_deleted=true.',
+ idempotent: false,
+ },
+ props: {
+ call_id: retellAiProps.id({ displayName: 'Call ID', description: 'The call to delete.' }),
+ },
+ outputSchema: retellSchemas.deleted({ idKey: 'call_id', idLabel: 'Call ID' }),
+ async run({ auth, propsValue }) {
+ const callId = retellInput.seg({ value: propsValue.call_id, label: 'Call ID' });
+ try {
+ await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.DELETE, path: `/v2/delete-call/${callId}` });
+ } catch (error) {
+ if (isRetellStatus({ error, statuses: [404] })) {
+ return { call_id: decodeURIComponent(callId), deleted: false, already_deleted: true };
+ }
+ throw error;
+ }
+ return { call_id: decodeURIComponent(callId), deleted: true, already_deleted: false };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-knowledge-base-source.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-knowledge-base-source.ts
new file mode 100644
index 00000000000..ec81aa18d57
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-knowledge-base-source.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const deleteKnowledgeBaseSourceAction = createAction({
+ auth: retellAiAuth,
+ name: 'delete_knowledge_base_source',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Knowledge Base Source',
+ description: 'Removes one source from a knowledge base.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently removes one source (text, URL or file) from a Retell knowledge base and returns the updated knowledge base. Cannot be undone. Use Get Knowledge Base to find the source_id.',
+ idempotent: false,
+ },
+ props: {
+ knowledge_base_id: retellAiProps.id({ displayName: 'Knowledge Base ID', description: 'The knowledge base that holds the source.' }),
+ source_id: retellAiProps.id({ displayName: 'Source ID', description: 'The source to remove.' }),
+ },
+ outputSchema: retellSchemas.knowledgeBase,
+ async run({ auth, propsValue }) {
+ const knowledgeBaseId = retellInput.seg({ value: propsValue.knowledge_base_id, label: 'Knowledge Base ID' });
+ const sourceId = retellInput.seg({ value: propsValue.source_id, label: 'Source ID' });
+ const knowledgeBase = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.DELETE,
+ path: `/delete-knowledge-base-source/${knowledgeBaseId}/source/${sourceId}`,
+ });
+ return retellMap.knowledgeBase(knowledgeBase);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-knowledge-base.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-knowledge-base.ts
new file mode 100644
index 00000000000..e90a01f44c8
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-knowledge-base.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, isRetellStatus, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+export const deleteKnowledgeBaseAction = createAction({
+ auth: retellAiAuth,
+ name: 'delete_knowledge_base',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Knowledge Base',
+ description: 'Deletes a knowledge base.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one Retell knowledge base with all its sources; agents using it lose that knowledge. Cannot be undone. A knowledge base that is already gone returns already_deleted=true.',
+ idempotent: false,
+ },
+ props: {
+ knowledge_base_id: retellAiProps.id({ displayName: 'Knowledge Base ID', description: 'The knowledge base to delete.' }),
+ },
+ outputSchema: retellSchemas.deleted({ idKey: 'knowledge_base_id', idLabel: 'Knowledge Base ID' }),
+ async run({ auth, propsValue }) {
+ const knowledgeBaseId = retellInput.seg({ value: propsValue.knowledge_base_id, label: 'Knowledge Base ID' });
+ try {
+ await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.DELETE, path: `/delete-knowledge-base/${knowledgeBaseId}` });
+ } catch (error) {
+ if (isRetellStatus({ error, statuses: [404] })) {
+ return { knowledge_base_id: decodeURIComponent(knowledgeBaseId), deleted: false, already_deleted: true };
+ }
+ throw error;
+ }
+ return { knowledge_base_id: decodeURIComponent(knowledgeBaseId), deleted: true, already_deleted: false };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-phone-number.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-phone-number.ts
new file mode 100644
index 00000000000..ce4472e4b8a
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/delete-phone-number.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, isRetellStatus, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+export const deletePhoneNumberAction = createAction({
+ auth: retellAiAuth,
+ name: 'delete_phone_number',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Phone Number',
+ description: 'Releases a phone number from the workspace.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Releases one Retell phone number; calls to it stop working and a bought number usually cannot be bought back. Cannot be undone. A number that is already gone returns already_deleted=true.',
+ idempotent: false,
+ },
+ props: {
+ phone_number: retellAiProps.e164Number({ displayName: 'Phone Number', description: 'The Retell number to release.' }),
+ },
+ outputSchema: retellSchemas.deleted({ idKey: 'phone_number', idLabel: 'Phone Number' }),
+ async run({ auth, propsValue }) {
+ const phoneNumber = retellInput.e164({ value: propsValue.phone_number, label: 'Phone Number' });
+ try {
+ await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.DELETE,
+ path: `/delete-phone-number/${encodeURIComponent(phoneNumber)}`,
+ });
+ } catch (error) {
+ if (isRetellStatus({ error, statuses: [404] })) {
+ return { phone_number: phoneNumber, deleted: false, already_deleted: true };
+ }
+ throw error;
+ }
+ return { phone_number: phoneNumber, deleted: true, already_deleted: false };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/end-chat.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/end-chat.ts
new file mode 100644
index 00000000000..73a354aa5fa
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/end-chat.ts
@@ -0,0 +1,29 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+export const endChatAction = createAction({
+ auth: retellAiAuth,
+ name: 'end_chat',
+ classification: 'DESTRUCTIVE',
+ displayName: 'End Chat',
+ description: 'Ends an ongoing chat.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Ends one ongoing Retell chat so no more messages can be sent and post-chat analysis starts. A chat cannot be reopened.',
+ idempotent: false,
+ },
+ props: {
+ chat_id: retellAiProps.id({ displayName: 'Chat ID', description: 'The chat to end.' }),
+ },
+ outputSchema: retellSchemas.chatEnded,
+ async run({ auth, propsValue }) {
+ const chatId = retellInput.seg({ value: propsValue.chat_id, label: 'Chat ID' });
+ await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.PATCH, path: `/end-chat/${chatId}` });
+ return { chat_id: decodeURIComponent(chatId), ended: true };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-agent-by-id.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-agent-by-id.ts
new file mode 100644
index 00000000000..03c3878c8e8
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-agent-by-id.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getAgentByIdAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_agent_by_id',
+ classification: 'READ',
+ displayName: 'Get Agent by ID',
+ description: 'Returns one voice agent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one Retell voice agent: name, voice, language, webhook URL, response engine (LLM or conversation flow ID) and publish state, for the latest or a given version. Use Get Chat Agent for chat agents. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Voice agent ID. Use List Agents to find it.' }),
+ version: Property.Number({ displayName: 'Version', description: 'Optional version number. Empty = latest.', required: false }),
+ },
+ outputSchema: retellSchemas.agent,
+ async run({ auth, propsValue }) {
+ const agent = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-agent/${retellInput.seg({ value: propsValue.agent_id, label: 'Agent ID' })}`,
+ query: { version: retellInput.optionalInteger({ value: propsValue.version, label: 'Version', min: 0 }) },
+ retryRateLimit: true,
+ });
+ return retellMap.agent(agent);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-call-by-id.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-call-by-id.ts
new file mode 100644
index 00000000000..850a7deaca7
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-call-by-id.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getCallByIdAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_call_by_id',
+ classification: 'READ',
+ displayName: 'Get Call by ID',
+ description: 'Returns one call with transcript, recording and analysis.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns one call's status, transcript, recording link, post-call analysis and cost. Transcript appears after the call ends and analysis after it is analyzed. Use List Calls to find call IDs. Read-only.",
+ idempotent: true,
+ },
+ props: {
+ call_id: retellAiProps.id({ displayName: 'Call ID', description: 'The call ID returned when the call was created or listed.' }),
+ },
+ outputSchema: retellSchemas.call,
+ async run({ auth, propsValue }) {
+ const call = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/v2/get-call/${retellInput.seg({ value: propsValue.call_id, label: 'Call ID' })}`,
+ retryRateLimit: true,
+ });
+ return retellMap.call(call);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-chat-agent.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-chat-agent.ts
new file mode 100644
index 00000000000..6d3c1e72c73
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-chat-agent.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getChatAgentAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_chat_agent',
+ classification: 'READ',
+ displayName: 'Get Chat Agent',
+ description: 'Returns one chat agent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one Retell chat agent: name, language, webhook URL, response engine (LLM or conversation flow ID) and publish state, for the latest or a given version. Use Get Agent by ID for voice agents. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Chat agent ID. Use List Chat Agents to find it.' }),
+ version: Property.Number({ displayName: 'Version', description: 'Optional version number. Empty = latest.', required: false }),
+ },
+ outputSchema: retellSchemas.chatAgent,
+ async run({ auth, propsValue }) {
+ const agent = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-chat-agent/${retellInput.seg({ value: propsValue.agent_id, label: 'Agent ID' })}`,
+ query: { version: retellInput.optionalInteger({ value: propsValue.version, label: 'Version', min: 0 }) },
+ retryRateLimit: true,
+ });
+ return retellMap.chatAgent(agent);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-chat.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-chat.ts
new file mode 100644
index 00000000000..ded4280646b
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-chat.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getChatAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_chat',
+ classification: 'READ',
+ displayName: 'Get Chat',
+ description: 'Returns one chat with transcript and analysis.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one Retell chat (web or SMS) with status, transcript, post-chat analysis and cost. Analysis appears after the chat ends. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ chat_id: retellAiProps.id({ displayName: 'Chat ID', description: 'The chat ID.' }),
+ },
+ outputSchema: retellSchemas.chat,
+ async run({ auth, propsValue }) {
+ const chat = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-chat/${retellInput.seg({ value: propsValue.chat_id, label: 'Chat ID' })}`,
+ retryRateLimit: true,
+ });
+ return retellMap.chat(chat);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-concurrency.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-concurrency.ts
new file mode 100644
index 00000000000..e9470b96bb6
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-concurrency.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+
+export const getConcurrencyAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_concurrency',
+ classification: 'READ',
+ displayName: 'Get Concurrency',
+ description: 'Returns current and maximum concurrent calls.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns how many calls run right now, the concurrency limit and how many slots are free. Check it before placing many calls, since calls over the limit fail. Read-only.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: retellSchemas.concurrency,
+ async run({ auth }) {
+ const response = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.GET, path: '/get-concurrency', retryRateLimit: true });
+ return retellMap.concurrency(response);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-contact-by-phone.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-contact-by-phone.ts
new file mode 100644
index 00000000000..1793ea88ee4
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-contact-by-phone.ts
@@ -0,0 +1,42 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, isRetellStatus, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getContactByPhoneAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_contact_by_phone',
+ classification: 'READ',
+ displayName: 'Get Contact by Phone',
+ description: 'Finds the contact for a phone number.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Looks up the Retell contact for a phone number (at most one exists) with name, do-not-call flag, memory notes, custom fields and conversation count. Returns found=false when there is none. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ phone_number: retellAiProps.e164Number({ displayName: 'Phone Number', description: 'The phone number to look up.' }),
+ },
+ outputSchema: retellSchemas.contactLookup,
+ async run({ auth, propsValue }) {
+ const phoneNumber = retellInput.e164({ value: propsValue.phone_number, label: 'Phone Number' });
+ try {
+ const contact = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-contact-by-phone/${encodeURIComponent(phoneNumber)}`,
+ retryRateLimit: true,
+ });
+ return { found: true, ...retellMap.contact(contact) };
+ } catch (error) {
+ if (isRetellStatus({ error, statuses: [404] })) {
+ return { found: false, ...retellMap.contact({ phone_number: phoneNumber }) };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-knowledge-base.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-knowledge-base.ts
new file mode 100644
index 00000000000..8893dbe83b3
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-knowledge-base.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getKnowledgeBaseAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_knowledge_base',
+ classification: 'READ',
+ displayName: 'Get Knowledge Base',
+ description: 'Returns one knowledge base with its sources.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns one Retell knowledge base with indexing status and its sources (source_id, type, title, URL). Use it to check that indexing is complete or to find a source_id to delete. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ knowledge_base_id: retellAiProps.id({ displayName: 'Knowledge Base ID', description: 'Use List Knowledge Bases to find it.' }),
+ },
+ outputSchema: retellSchemas.knowledgeBase,
+ async run({ auth, propsValue }) {
+ const knowledgeBase = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-knowledge-base/${retellInput.seg({ value: propsValue.knowledge_base_id, label: 'Knowledge Base ID' })}`,
+ retryRateLimit: true,
+ });
+ return retellMap.knowledgeBase(knowledgeBase);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-retell-llm.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-retell-llm.ts
new file mode 100644
index 00000000000..be22d96b6a2
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-retell-llm.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getRetellLlmAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_retell_llm',
+ classification: 'READ',
+ displayName: 'Get Retell LLM',
+ description: 'Returns one Retell LLM response engine.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Returns one Retell LLM response engine with model, general prompt, begin message and knowledge base IDs. Get an agent's llm_id from Get Agent by ID. Read-only.",
+ idempotent: true,
+ },
+ props: {
+ llm_id: retellAiProps.id({ displayName: 'Retell LLM ID', description: 'The llm_id of the response engine.' }),
+ version: Property.Number({ displayName: 'Version', description: 'Optional version number. Empty = latest.', required: false }),
+ },
+ outputSchema: retellSchemas.llm,
+ async run({ auth, propsValue }) {
+ const llm = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-retell-llm/${retellInput.seg({ value: propsValue.llm_id, label: 'Retell LLM ID' })}`,
+ query: { version: retellInput.optionalInteger({ value: propsValue.version, label: 'Version', min: 0 }) },
+ retryRateLimit: true,
+ });
+ return retellMap.retellLlm(llm);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/get-voice-by-id.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-voice-by-id.ts
new file mode 100644
index 00000000000..12da59fd02a
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/get-voice-by-id.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const getVoiceByIdAction = createAction({
+ auth: retellAiAuth,
+ name: 'get_voice_by_id',
+ classification: 'READ',
+ displayName: 'Get Voice by ID',
+ description: 'Returns one voice.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Returns one Retell voice by voice_id with provider, gender, accent, age and preview audio link. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ voice_id: retellAiProps.id({ displayName: 'Voice ID', description: 'For example 11labs-Adrian. Use List Voices to find it.' }),
+ },
+ outputSchema: retellSchemas.voice,
+ async run({ auth, propsValue }) {
+ const voice = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/get-voice/${retellInput.seg({ value: propsValue.voice_id, label: 'Voice ID' })}`,
+ retryRateLimit: true,
+ });
+ return retellMap.voice(voice);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-agent-versions.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-agent-versions.ts
new file mode 100644
index 00000000000..9bbe84793a1
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-agent-versions.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listAgentVersionsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_agent_versions',
+ classification: 'SEARCH',
+ displayName: 'List Agent Versions',
+ description: 'Lists the stored versions of an agent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the versions of one voice or chat agent with publish state, title and description, newest first. Use it to pick a version for Publish Agent or to pin a call to a version. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Voice or chat agent ID.' }),
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.agentVersionPage,
+ async run({ auth, propsValue }) {
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: `/list-agent-versions/${retellInput.seg({ value: propsValue.agent_id, label: 'Agent ID' })}`,
+ query: {
+ limit: retellInput.pageLimit(propsValue.limit),
+ sort_order: 'descending',
+ pagination_key: retellInput.optionalText(propsValue.pagination_key),
+ },
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.agentVersion });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-agents.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-agents.ts
new file mode 100644
index 00000000000..5ea5b393e80
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-agents.ts
@@ -0,0 +1,76 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listAgentsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_agents',
+ classification: 'SEARCH',
+ displayName: 'List Agents',
+ description: 'Lists voice and chat agents.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Retell agents (one row per agent, not per version), optionally only voice or only chat agents, or those whose name or ID contains a search text. Use it to find an agent_id. Pass pagination_key to read the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ channel: Property.StaticDropdown({
+ displayName: 'Channel',
+ description: 'Optional: only voice or only chat agents.',
+ required: false,
+ options: { options: [{ label: 'Voice', value: 'voice' }, { label: 'Chat', value: 'chat' }] },
+ }),
+ search: Property.ShortText({ displayName: 'Search', description: 'Optional text matched against agent name and ID.', required: false }),
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.agentPage,
+ async run({ auth, propsValue }) {
+ return listAgentsPage({
+ apiKey: apiKeyOf(auth),
+ channel: retellInput.optionalText(propsValue.channel),
+ search: retellInput.optionalText(propsValue.search),
+ limit: propsValue.limit,
+ paginationKey: propsValue.pagination_key,
+ });
+ },
+});
+
+export async function listAgentsPage({
+ apiKey,
+ channel,
+ search,
+ limit,
+ paginationKey,
+}: {
+ apiKey: string;
+ channel: string | undefined;
+ search: string | undefined;
+ limit: unknown;
+ paginationKey: unknown;
+}) {
+ const filter: Record<string, unknown> = {};
+ if (channel !== undefined) {
+ filter['channel'] = retellInput.stringFilter(channel);
+ }
+ if (search !== undefined) {
+ filter['query'] = search;
+ }
+ const response = await retellApiCall({
+ apiKey,
+ method: HttpMethod.POST,
+ path: '/v2/list-agents',
+ query: {
+ limit: retellInput.pageLimit(limit),
+ pagination_key: retellInput.optionalText(paginationKey),
+ },
+ body: Object.keys(filter).length > 0 ? { filter_criteria: filter } : {},
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.agentListItem });
+}
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-calls.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-calls.ts
new file mode 100644
index 00000000000..37d94a9f594
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-calls.ts
@@ -0,0 +1,114 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellOptions } from '../../common/options';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listCallsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_calls',
+ classification: 'SEARCH',
+ displayName: 'List Calls',
+ description: 'Lists calls newest first with optional filters.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Retell calls newest first, one page at a time, filtered by agent, status, direction, call type, numbers or start time. Items have no transcript or recording; use Get Call by ID for those. Pass pagination_key to read the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Optional agent ID to only list its calls.', required: false }),
+ call_status: Property.ShortText({
+ displayName: 'Call Statuses',
+ description: `Optional comma-separated statuses: ${retellOptions.CALL_STATUSES.join(', ')}.`,
+ required: false,
+ }),
+ direction: Property.StaticDropdown({
+ displayName: 'Direction',
+ required: false,
+ options: { options: [{ label: 'Inbound', value: 'inbound' }, { label: 'Outbound', value: 'outbound' }] },
+ }),
+ call_type: Property.StaticDropdown({
+ displayName: 'Call Type',
+ required: false,
+ options: { options: [{ label: 'Phone Call', value: 'phone_call' }, { label: 'Web Call', value: 'web_call' }] },
+ }),
+ from_number: retellAiProps.e164Number({ displayName: 'From Number', description: 'Optional caller number.', required: false }),
+ to_number: retellAiProps.e164Number({ displayName: 'To Number', description: 'Optional called number.', required: false }),
+ started_after: Property.ShortText({
+ displayName: 'Started After',
+ description: 'Optional ISO date or Unix time; calls that started at or after it.',
+ required: false,
+ }),
+ started_before: Property.ShortText({
+ displayName: 'Started Before',
+ description: 'Optional ISO date or Unix time; calls that started at or before it.',
+ required: false,
+ }),
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.callPage,
+ async run({ auth, propsValue }) {
+ const filter: Record<string, unknown> = {};
+ const agentId = retellInput.optionalText(propsValue.agent_id);
+ if (agentId !== undefined) {
+ filter['agent'] = [{ agent_id: agentId }];
+ }
+ const status = retellInput.enumFilter({ value: propsValue.call_status, label: 'Call Statuses', allowed: retellOptions.CALL_STATUSES });
+ if (status !== undefined) {
+ filter['call_status'] = status;
+ }
+ const direction = retellInput.optionalText(propsValue.direction);
+ if (direction !== undefined) {
+ filter['direction'] = { type: 'enum', op: 'in', value: [direction] };
+ }
+ const callType = retellInput.optionalText(propsValue.call_type);
+ if (callType !== undefined) {
+ filter['call_type'] = { type: 'enum', op: 'in', value: [callType] };
+ }
+ const fromNumber = retellInput.optionalE164({ value: propsValue.from_number, label: 'From Number' });
+ if (fromNumber !== undefined) {
+ filter['from_number'] = retellInput.stringFilter(fromNumber);
+ }
+ const toNumber = retellInput.optionalE164({ value: propsValue.to_number, label: 'To Number' });
+ if (toNumber !== undefined) {
+ filter['to_number'] = retellInput.stringFilter(toNumber);
+ }
+ const after = retellInput.timestampMs({ value: propsValue.started_after, label: 'Started After' });
+ const before = retellInput.timestampMs({ value: propsValue.started_before, label: 'Started Before' });
+ if (after !== undefined && before !== undefined) {
+ if (after > before) {
+ throw new Error('Started After must be earlier than Started Before.');
+ }
+ filter['start_timestamp'] = { type: 'range', op: 'bt', value: [after, before] };
+ } else if (after !== undefined) {
+ filter['start_timestamp'] = { type: 'number', op: 'ge', value: after };
+ } else if (before !== undefined) {
+ filter['start_timestamp'] = { type: 'number', op: 'le', value: before };
+ }
+ const body: Record<string, unknown> = {
+ sort_order: 'descending',
+ limit: retellInput.pageLimit(propsValue.limit),
+ };
+ if (Object.keys(filter).length > 0) {
+ body['filter_criteria'] = filter;
+ }
+ const paginationKey = retellInput.optionalText(propsValue.pagination_key);
+ if (paginationKey !== undefined) {
+ body['pagination_key'] = paginationKey;
+ }
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: '/v3/list-calls',
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.call });
+ },
+});
+
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-chat-agents.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-chat-agents.ts
new file mode 100644
index 00000000000..da2bbf75c4e
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-chat-agents.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+import { listAgentsPage } from './list-agents';
+
+export const listChatAgentsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_chat_agents',
+ classification: 'SEARCH',
+ displayName: 'List Chat Agents',
+ description: 'Lists chat agents.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Retell chat (text/SMS) agents only, optionally matching a search text. Use it to find the agent_id for Create Chat or Create SMS Chat. Pass pagination_key for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', description: 'Optional text matched against agent name and ID.', required: false }),
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.agentPage,
+ async run({ auth, propsValue }) {
+ return listAgentsPage({
+ apiKey: apiKeyOf(auth),
+ channel: 'chat',
+ search: retellInput.optionalText(propsValue.search),
+ limit: propsValue.limit,
+ paginationKey: propsValue.pagination_key,
+ });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-chats.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-chats.ts
new file mode 100644
index 00000000000..0e2880f4e16
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-chats.ts
@@ -0,0 +1,70 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellOptions } from '../../common/options';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listChatsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_chats',
+ classification: 'SEARCH',
+ displayName: 'List Chats',
+ description: 'Lists chats newest first with optional filters.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Retell chats newest first, one page at a time, filtered by agent, status or chat type. Items have no transcript; use Get Chat for it. Pass pagination_key for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Chat Agent ID', description: 'Optional agent ID to only list its chats.', required: false }),
+ chat_status: Property.ShortText({
+ displayName: 'Chat Statuses',
+ description: `Optional comma-separated statuses: ${retellOptions.CHAT_STATUSES.join(', ')}.`,
+ required: false,
+ }),
+ chat_type: Property.StaticDropdown({
+ displayName: 'Chat Type',
+ required: false,
+ options: { options: [{ label: 'API Chat', value: 'api_chat' }, { label: 'SMS Chat', value: 'sms_chat' }] },
+ }),
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.chatPage,
+ async run({ auth, propsValue }) {
+ const filter: Record<string, unknown> = {};
+ const agentId = retellInput.optionalText(propsValue.agent_id);
+ if (agentId !== undefined) {
+ filter['agent'] = [{ agent_id: agentId }];
+ }
+ const status = retellInput.enumFilter({ value: propsValue.chat_status, label: 'Chat Statuses', allowed: retellOptions.CHAT_STATUSES });
+ if (status !== undefined) {
+ filter['chat_status'] = status;
+ }
+ const chatType = retellInput.optionalText(propsValue.chat_type);
+ if (chatType !== undefined) {
+ filter['chat_type'] = { type: 'enum', op: 'in', value: [chatType] };
+ }
+ const body: Record<string, unknown> = { sort_order: 'descending', limit: retellInput.pageLimit(propsValue.limit) };
+ if (Object.keys(filter).length > 0) {
+ body['filter_criteria'] = filter;
+ }
+ const paginationKey = retellInput.optionalText(propsValue.pagination_key);
+ if (paginationKey !== undefined) {
+ body['pagination_key'] = paginationKey;
+ }
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: '/v3/list-chats',
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.chatListItem });
+ },
+});
+
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-contacts.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-contacts.ts
new file mode 100644
index 00000000000..483771b0ce6
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-contacts.ts
@@ -0,0 +1,46 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listContactsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_contacts',
+ classification: 'SEARCH',
+ displayName: 'List Contacts',
+ description: 'Lists or searches contacts, newest first.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists Retell contacts newest first, optionally matching a search text against phone number, names, external ID and custom fields, with the total number of matches. Pass pagination_key for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', description: 'Optional case-insensitive text to match.', required: false }),
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.contactPage,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = { limit: retellInput.pageLimit(propsValue.limit), sort_order: 'desc' };
+ const search = retellInput.optionalText(propsValue.search);
+ if (search !== undefined) {
+ body['search_query'] = search;
+ }
+ const paginationKey = retellInput.optionalText(propsValue.pagination_key);
+ if (paginationKey !== undefined) {
+ body['pagination_key'] = paginationKey;
+ }
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: '/list-contacts',
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.contact });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-knowledge-bases.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-knowledge-bases.ts
new file mode 100644
index 00000000000..7d938fd5574
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-knowledge-bases.ts
@@ -0,0 +1,38 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listKnowledgeBasesAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_knowledge_bases',
+ classification: 'SEARCH',
+ displayName: 'List Knowledge Bases',
+ description: 'Lists all knowledge bases.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every Retell knowledge base with status and its sources (texts, URLs, files), optionally only those whose name contains a search text. Use it to find a knowledge_base_id or source_id. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', description: 'Optional text matched against the name.', required: false }),
+ },
+ outputSchema: retellSchemas.knowledgeBaseList,
+ async run({ auth, propsValue }) {
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: '/list-knowledge-bases',
+ retryRateLimit: true,
+ });
+ const search = retellInput.optionalText(propsValue.search)?.toLowerCase();
+ const items = retellMap
+ .itemsOf(response)
+ .map(retellMap.knowledgeBase)
+ .filter((kb) => search === undefined || (kb.knowledge_base_name ?? '').toLowerCase().includes(search));
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-phone-numbers.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-phone-numbers.ts
new file mode 100644
index 00000000000..a5481376a86
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-phone-numbers.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listPhoneNumbersAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_phone_numbers',
+ classification: 'SEARCH',
+ displayName: 'List Phone Numbers',
+ description: 'Lists the phone numbers in the workspace.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the Retell phone numbers of the workspace with nickname and bound inbound/outbound agents. Use it to pick a From Number for calls or SMS. Pass pagination_key for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.phoneNumberPage,
+ async run({ auth, propsValue }) {
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: '/v2/list-phone-numbers',
+ query: {
+ limit: retellInput.pageLimit(propsValue.limit),
+ pagination_key: retellInput.optionalText(propsValue.pagination_key),
+ },
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.phoneNumber });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-retell-llms.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-retell-llms.ts
new file mode 100644
index 00000000000..dfd9fa65008
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-retell-llms.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listRetellLlmsAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_retell_llms',
+ classification: 'SEARCH',
+ displayName: 'List Retell LLMs',
+ description: 'Lists Retell LLM response engines.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists the Retell LLM response engines (prompt + model configs that agents use) with model, prompt and begin message. An agent links to one via llm_id. Pass pagination_key for the next page. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ limit: retellAiProps.limit(),
+ pagination_key: retellAiProps.paginationKey(),
+ },
+ outputSchema: retellSchemas.llmPage,
+ async run({ auth, propsValue }) {
+ const response = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.GET,
+ path: '/v2/list-retell-llms',
+ query: {
+ limit: retellInput.pageLimit(propsValue.limit),
+ pagination_key: retellInput.optionalText(propsValue.pagination_key),
+ },
+ retryRateLimit: true,
+ });
+ return retellMap.page({ body: response, mapItem: retellMap.retellLlm });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/list-voices.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-voices.ts
new file mode 100644
index 00000000000..81f192f5864
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/list-voices.ts
@@ -0,0 +1,46 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const listVoicesAction = createAction({
+ auth: retellAiAuth,
+ name: 'list_voices',
+ classification: 'SEARCH',
+ displayName: 'List Voices',
+ description: 'Lists the voices available to agents.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Lists every voice available in the workspace with provider, gender, accent and a preview link, optionally filtered by provider, gender or a name search. Use it to pick a voice_id for Update Agent. Read-only.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', description: 'Optional text matched against voice name and ID.', required: false }),
+ provider: Property.ShortText({ displayName: 'Provider', description: 'Optional provider such as elevenlabs, openai or cartesia.', required: false }),
+ gender: Property.StaticDropdown({
+ displayName: 'Gender',
+ required: false,
+ options: { options: [{ label: 'Male', value: 'male' }, { label: 'Female', value: 'female' }] },
+ }),
+ },
+ outputSchema: retellSchemas.voiceList,
+ async run({ auth, propsValue }) {
+ const response = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.GET, path: '/list-voices', retryRateLimit: true });
+ const search = retellInput.optionalText(propsValue.search)?.toLowerCase();
+ const provider = retellInput.optionalText(propsValue.provider)?.toLowerCase();
+ const gender = retellInput.optionalText(propsValue.gender)?.toLowerCase();
+ const items = retellMap
+ .itemsOf(response)
+ .map(retellMap.voice)
+ .filter(
+ (voice) =>
+ (search === undefined || `${voice.voice_name ?? ''} ${voice.voice_id ?? ''}`.toLowerCase().includes(search)) &&
+ (provider === undefined || (voice.provider ?? '').toLowerCase() === provider) &&
+ (gender === undefined || (voice.gender ?? '').toLowerCase() === gender),
+ );
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/publish-agent.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/publish-agent.ts
new file mode 100644
index 00000000000..01409d70e7d
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/publish-agent.ts
@@ -0,0 +1,55 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const publishAgentAction = createAction({
+ auth: retellAiAuth,
+ name: 'publish_agent',
+ classification: 'WRITE',
+ displayName: 'Publish Agent',
+ description: 'Publishes a draft version of a voice agent.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Publishes one draft version of a voice agent in place, so phone numbers and calls bound to the published agent start using it. Use List Agent Versions to find the draft version number. Publishing the same version again changes nothing.',
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Voice agent ID.' }),
+ version: Property.Number({ displayName: 'Version', description: 'The draft version number to publish.', required: true }),
+ version_title: Property.ShortText({ displayName: 'Version Title', description: 'Optional title for this version.', required: false }),
+ version_description: Property.ShortText({
+ displayName: 'Version Description',
+ description: 'Optional note about what changed.',
+ required: false,
+ }),
+ },
+ outputSchema: retellSchemas.agentPublished,
+ async run({ auth, propsValue }) {
+ const version = retellInput.optionalInteger({ value: propsValue.version, label: 'Version', min: 0 });
+ if (version === undefined) {
+ throw new Error('Version is required.');
+ }
+ const body: Record<string, unknown> = { version };
+ const title = retellInput.optionalText(propsValue.version_title);
+ if (title !== undefined) {
+ body['version_title'] = title;
+ }
+ const description = retellInput.optionalText(propsValue.version_description);
+ if (description !== undefined) {
+ body['version_description'] = description;
+ }
+ const agentId = retellInput.seg({ value: propsValue.agent_id, label: 'Agent ID' });
+ await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: `/publish-agent-version/${agentId}`,
+ body,
+ });
+ return { agent_id: retellMap.str(decodeURIComponent(agentId)), version, published: true };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/send-chat-message.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/send-chat-message.ts
new file mode 100644
index 00000000000..0e7732ae86e
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/send-chat-message.ts
@@ -0,0 +1,39 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const sendChatMessageAction = createAction({
+ auth: retellAiAuth,
+ name: 'send_chat_message',
+ classification: 'WRITE',
+ displayName: 'Send Chat Message',
+ description: 'Sends a user message to a chat and returns the agent reply.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sends one user message to an ongoing Retell chat and returns the agent reply messages generated for it. Billed per message; each run adds another turn to the conversation, so do not retry a turn that succeeded.',
+ idempotent: false,
+ },
+ props: {
+ chat_id: retellAiProps.id({ displayName: 'Chat ID', description: 'chat_id returned by Create Chat.' }),
+ content: Property.LongText({ displayName: 'Message', description: 'The user message text.', required: true }),
+ },
+ outputSchema: retellSchemas.chatCompletion,
+ async run({ auth, propsValue }) {
+ const completion = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.POST,
+ path: '/create-chat-completion',
+ body: {
+ chat_id: retellInput.requiredText({ value: propsValue.chat_id, label: 'Chat ID' }),
+ content: retellInput.requiredText({ value: propsValue.content, label: 'Message' }),
+ },
+ timeoutMs: 120000,
+ });
+ return retellMap.chatCompletion(completion);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/stop-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/stop-call.ts
new file mode 100644
index 00000000000..12d5d4f7aae
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/stop-call.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, isRetellStatus, retellApiCall, toRetellError } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellSchemas } from '../../common/schemas';
+export const stopCallAction = createAction({
+ auth: retellAiAuth,
+ name: 'stop_call',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Stop Call',
+ description: 'Hangs up an ongoing call.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Hangs up one ongoing Retell call immediately; the conversation cannot be resumed. If the call is unknown or already over, returns stopped=false with the reason instead of failing.',
+ idempotent: false,
+ },
+ props: {
+ call_id: retellAiProps.id({ displayName: 'Call ID', description: 'The ongoing call to stop.' }),
+ },
+ outputSchema: retellSchemas.callStopped,
+ async run({ auth, propsValue }) {
+ const callId = retellInput.seg({ value: propsValue.call_id, label: 'Call ID' });
+ try {
+ await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: `/v2/stop-call/${callId}` });
+ } catch (error) {
+ if (isRetellStatus({ error, statuses: [404] })) {
+ return { call_id: decodeURIComponent(callId), stopped: false, reason: 'Call not found or no longer ongoing (HTTP 404).' };
+ }
+ const mapped = toRetellError(error);
+ if (mapped !== undefined && mapped.status === 400 && /only stop an ongoing call/i.test(mapped.message)) {
+ return { call_id: decodeURIComponent(callId), stopped: false, reason: 'Call is not ongoing (not started yet or already over).' };
+ }
+ throw error;
+ }
+ return { call_id: decodeURIComponent(callId), stopped: true, reason: null };
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/update-agent.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-agent.ts
new file mode 100644
index 00000000000..078582fb5e6
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-agent.ts
@@ -0,0 +1,74 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const updateAgentAction = createAction({
+ auth: retellAiAuth,
+ name: 'update_agent',
+ classification: 'WRITE',
+ displayName: 'Update Agent',
+ description: 'Changes the name, voice, language or webhook URL of a voice agent draft.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Changes basic settings (name, voice, language, webhook URL) of a voice agent's latest draft version; only the fields you set are sent. Calls keep using the published version until you run Publish Agent. Safe to retry with the same values.",
+ idempotent: true,
+ },
+ props: {
+ agent_id: retellAiProps.id({ displayName: 'Agent ID', description: 'Voice agent ID.' }),
+ agent_name: Property.ShortText({ displayName: 'Agent Name', description: 'Optional new name.', required: false }),
+ voice_id: Property.ShortText({ displayName: 'Voice ID', description: 'Optional voice ID, for example 11labs-Adrian. Use List Voices.', required: false }),
+ language: Property.ShortText({ displayName: 'Language', description: 'Optional language code such as en-US, es-ES, de-DE or multi.', required: false }),
+ webhook_url: Property.ShortText({
+ displayName: 'Webhook URL',
+ description: 'Optional agent webhook URL; overrides the account webhook.',
+ required: false,
+ }),
+ clear_webhook_url: Property.Checkbox({
+ displayName: 'Clear Webhook URL',
+ description: 'Remove the agent-level webhook so the account webhook is used again.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: retellSchemas.agent,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {};
+ const name = retellInput.optionalText(propsValue.agent_name);
+ if (name !== undefined) {
+ body['agent_name'] = name;
+ }
+ const voiceId = retellInput.optionalText(propsValue.voice_id);
+ if (voiceId !== undefined) {
+ body['voice_id'] = voiceId;
+ }
+ const language = retellInput.optionalText(propsValue.language);
+ if (language !== undefined) {
+ body['language'] = language;
+ }
+ const webhookUrl = retellInput.optionalText(propsValue.webhook_url);
+ if (webhookUrl !== undefined && propsValue.clear_webhook_url === true) {
+ throw new Error('Set Webhook URL or Clear Webhook URL, not both.');
+ }
+ if (webhookUrl !== undefined) {
+ body['webhook_url'] = webhookUrl;
+ } else if (propsValue.clear_webhook_url === true) {
+ body['webhook_url'] = null;
+ }
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set at least one field to update.');
+ }
+ const agent = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.PATCH,
+ path: `/update-agent/${retellInput.seg({ value: propsValue.agent_id, label: 'Agent ID' })}`,
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.agent(agent);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/update-call-metadata.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-call-metadata.ts
new file mode 100644
index 00000000000..4eca2c0d0a2
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-call-metadata.ts
@@ -0,0 +1,64 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const updateCallMetadataAction = createAction({
+ auth: retellAiAuth,
+ name: 'update_call_metadata',
+ classification: 'WRITE',
+ displayName: 'Update Call Metadata',
+ description: 'Replaces the metadata or data storage setting of a call.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Sets the metadata object and/or the data storage setting of one existing call (for example to tag it with a CRM ID). Metadata is replaced as a whole. Safe to retry with the same values.',
+ idempotent: true,
+ },
+ props: {
+ call_id: retellAiProps.id({ displayName: 'Call ID', description: 'The call to update.' }),
+ metadata: Property.Json({
+ displayName: 'Metadata',
+ description: 'JSON object that replaces the call metadata.',
+ required: false,
+ }),
+ data_storage_setting: Property.StaticDropdown({
+ displayName: 'Data Storage Setting',
+ description: 'Optional. basic_attributes_only drops transcript and recording.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Everything', value: 'everything' },
+ { label: 'Everything Except PII', value: 'everything_except_pii' },
+ { label: 'Basic Attributes Only', value: 'basic_attributes_only' },
+ ],
+ },
+ }),
+ },
+ outputSchema: retellSchemas.call,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {};
+ const metadata = retellInput.objectValue({ value: propsValue.metadata, label: 'Metadata' });
+ if (metadata !== undefined) {
+ body['metadata'] = metadata;
+ }
+ const storage = retellInput.optionalText(propsValue.data_storage_setting);
+ if (storage !== undefined) {
+ body['data_storage_setting'] = storage;
+ }
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set Metadata or Data Storage Setting.');
+ }
+ const call = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.PATCH,
+ path: `/v2/update-call/${retellInput.seg({ value: propsValue.call_id, label: 'Call ID' })}`,
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.call(call);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/update-contact.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-contact.ts
new file mode 100644
index 00000000000..772398a4b67
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-contact.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+import { contactFields } from './create-contact';
+
+export const updateContactAction = createAction({
+ auth: retellAiAuth,
+ name: 'update_contact',
+ classification: 'WRITE',
+ displayName: 'Update Contact',
+ description: 'Changes fields of an existing contact.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Changes name, do-not-call flag, memory notes or custom fields of one Retell contact; only fields you set are sent and Contact Memory replaces the old notes. Safe to retry with the same values.',
+ idempotent: true,
+ },
+ props: {
+ contact_id: retellAiProps.id({ displayName: 'Contact ID', description: 'Use Get Contact by Phone or List Contacts to find it.' }),
+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),
+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),
+ do_not_call: Property.StaticDropdown({
+ displayName: 'Do Not Call',
+ description: 'Optional: set or clear the do-not-call flag.',
+ required: false,
+ options: { options: [{ label: 'Yes', value: 'true' }, { label: 'No', value: 'false' }] },
+ }),
+ contact_memory: Property.LongText({ displayName: 'Contact Memory', description: 'Optional notes; replaces the old notes.', required: false }),
+ custom_fields: Property.Json({ displayName: 'Custom Fields', description: 'Optional JSON object of custom field values; null clears a field.', required: false }),
+ },
+ outputSchema: retellSchemas.contact,
+ async run({ auth, propsValue }) {
+ const doNotCall = propsValue.do_not_call === 'true' ? true : propsValue.do_not_call === 'false' ? false : undefined;
+ const body = contactFields({ ...propsValue, do_not_call: doNotCall });
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set at least one field to update.');
+ }
+ const contact = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.PATCH,
+ path: `/update-contact/${retellInput.seg({ value: propsValue.contact_id, label: 'Contact ID' })}`,
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.contact(contact);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/update-phone-number-agents.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-phone-number-agents.ts
new file mode 100644
index 00000000000..a264d7d0dfd
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-phone-number-agents.ts
@@ -0,0 +1,69 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const updatePhoneNumberAgentsAction = createAction({
+ auth: retellAiAuth,
+ name: 'update_phone_number_agents',
+ classification: 'WRITE',
+ displayName: 'Update Phone Number Agents',
+ description: 'Changes the agents or nickname of a phone number.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Binds a voice agent for inbound and/or outbound calls on one existing Retell number, or renames it; only fields you set change, and an agent you set replaces all agents on that side. Safe to retry with the same values.',
+ idempotent: true,
+ },
+ props: {
+ phone_number: retellAiProps.e164Number({ displayName: 'Phone Number', description: 'The Retell number to change.' }),
+ inbound_agent_id: retellAiProps.id({ displayName: 'Inbound Agent ID', description: 'Optional voice agent that answers calls.', required: false }),
+ inbound_agent_version: retellAiProps.agentVersion(),
+ outbound_agent_id: retellAiProps.id({ displayName: 'Outbound Agent ID', description: 'Optional voice agent for outbound calls.', required: false }),
+ outbound_agent_version: Property.ShortText({
+ displayName: 'Outbound Agent Version',
+ description: 'Optional version number or tag for the outbound agent.',
+ required: false,
+ }),
+ nickname: Property.ShortText({ displayName: 'Nickname', description: 'Optional new nickname.', required: false }),
+ },
+ outputSchema: retellSchemas.phoneNumber,
+ async run({ auth, propsValue }) {
+ const phoneNumber = retellInput.e164({ value: propsValue.phone_number, label: 'Phone Number' });
+ const body: Record<string, unknown> = {};
+ const inbound = retellInput.singleAgent({
+ agentId: propsValue.inbound_agent_id,
+ version: propsValue.inbound_agent_version,
+ label: 'Inbound Agent',
+ });
+ if (inbound !== undefined) {
+ body['inbound_agents'] = inbound;
+ }
+ const outbound = retellInput.singleAgent({
+ agentId: propsValue.outbound_agent_id,
+ version: propsValue.outbound_agent_version,
+ label: 'Outbound Agent',
+ });
+ if (outbound !== undefined) {
+ body['outbound_agents'] = outbound;
+ }
+ const nickname = retellInput.optionalText(propsValue.nickname);
+ if (nickname !== undefined) {
+ body['nickname'] = nickname;
+ }
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set an inbound agent, an outbound agent or a nickname.');
+ }
+ const number = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.PATCH,
+ path: `/update-phone-number/${encodeURIComponent(phoneNumber)}`,
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.phoneNumber(number);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/ai/update-retell-llm-prompt.ts b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-retell-llm-prompt.ts
new file mode 100644
index 00000000000..71bcfdfccd8
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/ai/update-retell-llm-prompt.ts
@@ -0,0 +1,65 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../../common/ai-props';
+import { retellAiAuth } from '../../common/auth';
+import { apiKeyOf, retellApiCall } from '../../common/client';
+import { retellInput } from '../../common/input';
+import { retellMap } from '../../common/mappers';
+import { retellSchemas } from '../../common/schemas';
+export const updateRetellLlmPromptAction = createAction({
+ auth: retellAiAuth,
+ name: 'update_retell_llm_prompt',
+ classification: 'WRITE',
+ displayName: 'Update Retell LLM Prompt',
+ description: 'Changes the prompt, begin message or model of a Retell LLM.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ "Replaces the general prompt, begin message and/or model of one Retell LLM response engine's draft; only fields you set are sent. Agents on a published version keep the old prompt until the agent is published again. Safe to retry with the same values.",
+ idempotent: true,
+ },
+ props: {
+ llm_id: retellAiProps.id({ displayName: 'Retell LLM ID', description: 'The llm_id of the response engine.' }),
+ general_prompt: Property.LongText({ displayName: 'General Prompt', description: 'Optional new system prompt (replaces the old one).', required: false }),
+ begin_message: Property.LongText({ displayName: 'Begin Message', description: 'Optional first sentence the agent says.', required: false }),
+ clear_begin_message: Property.Checkbox({
+ displayName: 'Clear Begin Message',
+ description: 'Remove the begin message so the agent generates its own opener.',
+ required: false,
+ defaultValue: false,
+ }),
+ model: Property.ShortText({ displayName: 'Model', description: 'Optional model name, for example gpt-4.1 or claude-4.5-sonnet.', required: false }),
+ },
+ outputSchema: retellSchemas.llm,
+ async run({ auth, propsValue }) {
+ const body: Record<string, unknown> = {};
+ const prompt = retellInput.optionalText(propsValue.general_prompt);
+ if (prompt !== undefined) {
+ body['general_prompt'] = prompt;
+ }
+ const beginMessage = retellInput.optionalText(propsValue.begin_message);
+ if (beginMessage !== undefined && propsValue.clear_begin_message === true) {
+ throw new Error('Set Begin Message or Clear Begin Message, not both.');
+ }
+ if (beginMessage !== undefined) {
+ body['begin_message'] = beginMessage;
+ } else if (propsValue.clear_begin_message === true) {
+ body['begin_message'] = null;
+ }
+ const model = retellInput.optionalText(propsValue.model);
+ if (model !== undefined) {
+ body['model'] = model;
+ }
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set at least one field to update.');
+ }
+ const llm = await retellApiCall({
+ apiKey: apiKeyOf(auth),
+ method: HttpMethod.PATCH,
+ path: `/update-retell-llm/${retellInput.seg({ value: propsValue.llm_id, label: 'Retell LLM ID' })}`,
+ body,
+ retryRateLimit: true,
+ });
+ return retellMap.retellLlm(llm);
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/create-batch-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/create-batch-call.ts
new file mode 100644
index 00000000000..966a998c1d7
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/actions/create-batch-call.ts
@@ -0,0 +1,95 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { retellAiProps } from '../common/ai-props';
+import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
+import { retellOptions } from '../common/options';
+import { retellMap } from '../common/mappers';
+import { retellSchemas } from '../common/schemas';
+export const createBatchCallAction = createAction({
+ auth: retellAiAuth,
+ name: 'create_batch_call',
+ classification: 'WRITE',
+ displayName: 'Create Batch Call',
+ description: 'Schedules outbound calls to a list of numbers.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Schedules one outbound call per listed number from a Retell number, now or at a set time (mass dialing, billed per minute per call). Use Create Phone Call for a single call. Each run creates a new batch and dials everyone again; only use with numbers that agreed to be called.',
+ idempotent: false,
+ },
+ props: {
+ from_number: retellAiProps.e164Number({ displayName: 'From Number', description: 'A number bought from or imported to Retell.' }),
+ tasks: Property.Array({
+ displayName: 'Calls',
+ description: `One entry per person to call, at most ${retellOptions.MAX_BATCH_TASKS}.`,
+ required: true,
+ properties: {
+ to_number: Property.ShortText({ displayName: 'To Number', description: 'E.164 number to call.', required: true }),
+ dynamic_variables: Property.Json({
+ displayName: 'Dynamic Variables',
+ description: 'Optional JSON object of prompt variables for this call.',
+ required: false,
+ }),
+ metadata: Property.Json({ displayName: 'Metadata', description: 'Optional JSON object stored with this call.', required: false }),
+ },
+ }),
+ name: Property.ShortText({ displayName: 'Batch Name', description: 'Optional name for your reference.', required: false }),
+ agent_id: retellAiProps.id({
+ displayName: 'Agent ID',
+ description: 'Optional voice agent ID for every call. Empty = the outbound agent bound to From Number.',
+ required: false,
+ }),
+ scheduled_time: Property.ShortText({
+ displayName: 'Scheduled Time',
+ description: 'Optional ISO date or Unix time to start. Empty = start now.',
+ required: false,
+ }),
+ },
+ outputSchema: retellSchemas.batchCall,
+ async run({ auth, propsValue }) {
+ const entries = Array.isArray(propsValue.tasks) ? propsValue.tasks : [];
+ if (entries.length === 0) {
+ throw new Error('Add at least one call.');
+ }
+ if (entries.length > retellOptions.MAX_BATCH_TASKS) {
+ throw new Error(`A batch can hold at most ${retellOptions.MAX_BATCH_TASKS} calls; split the list.`);
+ }
+ const agentId = retellInput.optionalText(propsValue.agent_id);
+ const tasks = entries.map((entry, index) => {
+ const record = retellMap.rec(entry);
+ const label = `Call ${index + 1}`;
+ const task: Record<string, unknown> = {
+ to_number: retellInput.e164({ value: record['to_number'], label: `${label} To Number` }),
+ };
+ const variables = retellInput.stringMap({ value: record['dynamic_variables'], label: `${label} Dynamic Variables` });
+ if (variables !== undefined) {
+ task['retell_llm_dynamic_variables'] = variables;
+ }
+ const metadata = retellInput.objectValue({ value: record['metadata'], label: `${label} Metadata` });
+ if (metadata !== undefined) {
+ task['metadata'] = metadata;
+ }
+ if (agentId !== undefined) {
+ task['override_agent_id'] = agentId;
+ }
+ return task;
+ });
+ const body: Record<string, unknown> = {
+ from_number: retellInput.e164({ value: propsValue.from_number, label: 'From Number' }),
+ tasks,
+ };
+ const name = retellInput.optionalText(propsValue.name);
+ if (name !== undefined) {
+ body['name'] = name;
+ }
+ const scheduled = retellInput.timestampMs({ value: propsValue.scheduled_time, label: 'Scheduled Time' });
+ if (scheduled !== undefined) {
+ body['trigger_timestamp'] = scheduled;
+ }
+ const batch = await retellApiCall({ apiKey: apiKeyOf(auth), method: HttpMethod.POST, path: '/create-batch-call', body });
+ return retellMap.batchCall(batch);
+ },
+});
+
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/create-phone-number.ts b/packages/pieces/community/retell-ai/src/lib/actions/create-phone-number.ts
index 94a6f19bccc..80115263dd9 100644
--- a/packages/pieces/community/retell-ai/src/lib/actions/create-phone-number.ts
+++ b/packages/pieces/community/retell-ai/src/lib/actions/create-phone-number.ts
@@ -1,8 +1,10 @@
import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from '../common/client';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
import { agentIdDropdown, numberProviderDropdown } from '../common/props';
+import { retellSchemas } from '../common/schemas';
export const createPhoneNumber = createAction({
auth: retellAiAuth,
@@ -10,27 +12,28 @@ export const createPhoneNumber = createAction({
classification: 'WRITE',
displayName: 'Create Phone Number',
description: 'Buys a new phone number and binds agents.',
- audience: 'both',
- aiMetadata: { description: 'Purchase a new US/Canada phone number from Retell and bind inbound and/or outbound AI agents to it. Either request a number by area code or pass a specific number in E.164 format; toll-free can be requested. Use to provision a callable number for an agent. Not idempotent: each call purchases a new number and incurs cost.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Buys a new Retell phone number (monthly fee) and binds inbound/outbound agents. Each run buys another number.',
+ idempotent: false,
+ },
props: {
- inboundAgentId: agentIdDropdown('Inbound Agent'),
- outboundAgentId: agentIdDropdown('Outbound Agent'),
+ inboundAgentId: agentIdDropdown({ displayName: 'Inbound Agent' }),
+ outboundAgentId: agentIdDropdown({ displayName: 'Outbound Agent' }),
inboundAgentVersion: Property.Number({
displayName: 'Inbound Agent Version',
- description:
- 'Version of the inbound agent to bind to the number. If not provided, will default to latest version.',
+ description: 'Version of the inbound agent to bind to the number. If not provided, will default to latest version.',
required: false,
}),
outboundAgentVersion: Property.Number({
displayName: 'Outbound Agent Version',
- description:
- 'Version of the outbound agent to bind to the number. If not provided, will default to latest version.',
+ description: 'Version of the outbound agent to bind to the number. If not provided, will default to latest version.',
required: false,
}),
areaCode: Property.Number({
displayName: 'Area Code',
- description:
- 'Area code of the number to obtain. Format is a 3 digit integer. Currently only supports US area code.',
+ description: '3-digit US area code. Leave empty when Phone Number is set.',
required: false,
}),
nickname: Property.ShortText({
@@ -65,84 +68,84 @@ export const createPhoneNumber = createAction({
}),
phoneNumber: Property.ShortText({
displayName: 'Phone Number',
- description:
- 'The number you are trying to purchase in E.164 format of the number (+country code then number with no space and no special characters).',
+ description: 'Exact E.164 number to buy. Leave empty when Area Code is set.',
required: false,
}),
},
+ outputSchema: retellSchemas.rawPhoneNumber,
async run({ propsValue, auth }) {
- const {
- inboundAgentId,
- outboundAgentId,
- inboundAgentVersion,
- outboundAgentVersion,
- areaCode,
- nickname,
- inboundWebhookUrl,
- numberProvider,
- countryCode,
- tollFree,
- phoneNumber,
- } = propsValue;
-
- // Validate phone number if provided
- if (phoneNumber) {
- const e164Regex = /^\+[1-9]\d{1,14}$/;
- if (!e164Regex.test(phoneNumber)) {
- throw new Error('Phone Number must be in E.164 format (e.g., +14157774444)');
- }
- }
-
- const body: Record<string, unknown> = {
- nickname,
- };
-
- // Add optional fields to the request body
- if (inboundAgentId !== undefined) {
- body['inbound_agent_id'] = inboundAgentId || null;
- }
-
- if (outboundAgentId !== undefined) {
- body['outbound_agent_id'] = outboundAgentId || null;
- }
-
- if (inboundAgentVersion !== undefined) {
- body['inbound_agent_version'] = inboundAgentVersion;
- }
-
- if (outboundAgentVersion !== undefined) {
- body['outbound_agent_version'] = outboundAgentVersion;
- }
-
- if (areaCode !== undefined) {
- body['area_code'] = areaCode;
- }
-
- if (inboundWebhookUrl !== undefined) {
- body['inbound_webhook_url'] = inboundWebhookUrl;
- }
-
- if (numberProvider !== undefined) {
- body['number_provider'] = numberProvider;
- }
-
- if (countryCode !== undefined) {
- body['country_code'] = countryCode;
- }
-
- if (tollFree !== undefined) {
- body['toll_free'] = tollFree;
- }
-
- if (phoneNumber !== undefined) {
- body['phone_number'] = phoneNumber;
- }
-
- return await retellAiApiCall({
+ return retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.POST,
- url: '/create-phone-number',
- auth: auth,
- body,
+ path: '/create-phone-number',
+ body: buildBuyNumberBody({
+ inboundAgentId: propsValue.inboundAgentId,
+ inboundAgentVersion: propsValue.inboundAgentVersion,
+ outboundAgentId: propsValue.outboundAgentId,
+ outboundAgentVersion: propsValue.outboundAgentVersion,
+ areaCode: propsValue.areaCode,
+ phoneNumber: propsValue.phoneNumber,
+ nickname: propsValue.nickname,
+ inboundWebhookUrl: propsValue.inboundWebhookUrl,
+ numberProvider: propsValue.numberProvider,
+ countryCode: propsValue.countryCode,
+ tollFree: propsValue.tollFree,
+ }),
});
},
-});
\ No newline at end of file
+});
+
+export function buildBuyNumberBody(input: {
+ inboundAgentId: unknown;
+ inboundAgentVersion: unknown;
+ outboundAgentId: unknown;
+ outboundAgentVersion: unknown;
+ areaCode: unknown;
+ phoneNumber: unknown;
+ nickname: unknown;
+ inboundWebhookUrl: unknown;
+ numberProvider: unknown;
+ countryCode: unknown;
+ tollFree: unknown;
+}): Record<string, unknown> {
+ const areaCode = retellInput.optionalInteger({ value: input.areaCode, label: 'Area Code', min: 100, max: 999 });
+ const phoneNumber = retellInput.optionalE164({ value: input.phoneNumber, label: 'Phone Number' });
+ if (areaCode !== undefined && phoneNumber !== undefined) {
+ throw new Error('Set either Area Code or Phone Number, not both.');
+ }
+ const body: Record<string, unknown> = {};
+ const inbound = retellInput.singleAgent({ agentId: input.inboundAgentId, version: input.inboundAgentVersion, label: 'Inbound Agent' });
+ if (inbound !== undefined) {
+ body['inbound_agents'] = inbound;
+ }
+ const outbound = retellInput.singleAgent({ agentId: input.outboundAgentId, version: input.outboundAgentVersion, label: 'Outbound Agent' });
+ if (outbound !== undefined) {
+ body['outbound_agents'] = outbound;
+ }
+ if (areaCode !== undefined) {
+ body['area_code'] = areaCode;
+ }
+ if (phoneNumber !== undefined) {
+ body['phone_number'] = phoneNumber;
+ }
+ const nickname = retellInput.optionalText(input.nickname);
+ if (nickname !== undefined) {
+ body['nickname'] = nickname;
+ }
+ const webhookUrl = retellInput.optionalText(input.inboundWebhookUrl);
+ if (webhookUrl !== undefined) {
+ body['inbound_webhook_url'] = webhookUrl;
+ }
+ const provider = retellInput.optionalText(input.numberProvider);
+ if (provider !== undefined) {
+ body['number_provider'] = provider;
+ }
+ const country = retellInput.optionalText(input.countryCode);
+ if (country !== undefined) {
+ body['country_code'] = country;
+ }
+ if (typeof input.tollFree === 'boolean') {
+ body['toll_free'] = input.tollFree;
+ }
+ return body;
+}
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/get-agent.ts b/packages/pieces/community/retell-ai/src/lib/actions/get-agent.ts
index 4d67a20a3b3..9ac9515826b 100644
--- a/packages/pieces/community/retell-ai/src/lib/actions/get-agent.ts
+++ b/packages/pieces/community/retell-ai/src/lib/actions/get-agent.ts
@@ -1,8 +1,10 @@
import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from '../common/client';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
import { agentIdDropdown } from '../common/props';
+import { retellSchemas } from '../common/schemas';
export const getAgent = createAction({
auth: retellAiAuth,
@@ -10,33 +12,27 @@ export const getAgent = createAction({
classification: 'READ',
displayName: 'Get Agent',
description: 'Fetch details of a Retell AI agent by Agent ID.',
- audience: 'both',
- aiMetadata: { description: 'Look up the configuration of a single Retell AI agent by its Agent ID, optionally pinned to a specific version (defaults to the latest). Use to inspect an agent\'s settings before placing a call or binding it to a number. Read-only and idempotent.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description: 'Returns the configuration of one Retell voice agent, optionally a specific version. Read-only.',
+ idempotent: true,
+ },
props: {
- agentId: agentIdDropdown('Agent ID',true),
+ agentId: agentIdDropdown({ displayName: 'Agent ID', required: true }),
version: Property.Number({
displayName: 'Version',
- description: 'Optional version of the API to use for this request. If not provided, will default to latest version.',
+ description: 'Agent version to return. Leave empty for the latest version.',
required: false,
}),
},
+ outputSchema: retellSchemas.rawAgent,
async run({ propsValue, auth }) {
- const { agentId, version } = propsValue;
-
- if (!agentId) {
- throw new Error('Agent ID is required');
- }
-
- let url = `/get-agent/${encodeURIComponent(agentId)}`;
-
- if (version !== undefined) {
- url += `?version=${version}`;
- }
-
- return await retellAiApiCall({
+ return retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.GET,
- url: url,
- auth: auth,
+ path: `/get-agent/${retellInput.seg({ value: propsValue.agentId, label: 'Agent ID' })}`,
+ query: { version: retellInput.optionalInteger({ value: propsValue.version, label: 'Version', min: 0 }) },
+ retryRateLimit: true,
});
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/get-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/get-call.ts
index 714b9f5a0c4..0dd1a287ec3 100644
--- a/packages/pieces/community/retell-ai/src/lib/actions/get-call.ts
+++ b/packages/pieces/community/retell-ai/src/lib/actions/get-call.ts
@@ -1,8 +1,10 @@
import { HttpMethod } from '@activepieces/pieces-common';
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from '../common/client';
+import { createAction } from '@activepieces/pieces-framework';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
import { callIdDropdown } from '../common/props';
+import { retellSchemas } from '../common/schemas';
export const getCall = createAction({
auth: retellAiAuth,
@@ -10,22 +12,21 @@ export const getCall = createAction({
classification: 'READ',
displayName: 'Get Call',
description: 'Retrieve detailed data of a specific call (e.g., transcript), given a Call ID.',
- audience: 'both',
- aiMetadata: { description: 'Look up the full details of a single Retell call by its Call ID, including status, transcript, recording, and metadata. Use to inspect the outcome or content of a known call. Read-only and idempotent.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description: 'Returns one Retell call with status, transcript, recording and analysis. Read-only.',
+ idempotent: true,
+ },
props: {
callId: callIdDropdown,
},
+ outputSchema: retellSchemas.rawCall,
async run({ propsValue, auth }) {
- const { callId } = propsValue;
-
- if (!callId) {
- throw new Error('Call ID is required');
- }
-
- return await retellAiApiCall({
+ return retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.GET,
- url: `/v2/get-call/${callId}`,
- auth: auth,
+ path: `/v2/get-call/${retellInput.seg({ value: propsValue.callId, label: 'Call ID' })}`,
+ retryRateLimit: true,
});
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/get-phone-number.ts b/packages/pieces/community/retell-ai/src/lib/actions/get-phone-number.ts
index 9f31f2a0e9a..344e0ce1a47 100644
--- a/packages/pieces/community/retell-ai/src/lib/actions/get-phone-number.ts
+++ b/packages/pieces/community/retell-ai/src/lib/actions/get-phone-number.ts
@@ -1,7 +1,9 @@
import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from '../common/client';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
+import { retellSchemas } from '../common/schemas';
export const getPhoneNumber = createAction({
auth: retellAiAuth,
@@ -10,27 +12,27 @@ export const getPhoneNumber = createAction({
displayName: 'Get Phone Number',
description: 'Retrieve full details for an existing phone number in Retell AI.',
audience: 'both',
- aiMetadata: { description: 'Look up the configuration of a phone number registered in Retell, including its bound inbound/outbound agents and webhook settings. The number, supplied in E.164 format, is the unique identifier. Use to inspect an existing number before reusing or updating it. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description:
+ 'Returns one Retell phone number (E.164) with its nickname and the inbound/outbound agents bound to it. Use List Phone Numbers to discover numbers. Read-only.',
+ idempotent: true,
+ },
props: {
phoneNumber: Property.ShortText({
displayName: 'Phone Number',
- description: 'E.164 format of the number (+country code, then number with no space, no special characters), used as the unique identifier for phone number APIs. Example: "+14157774444"',
+ description:
+ 'E.164 format of the number (+country code, then number with no space, no special characters), used as the unique identifier for phone number APIs. Example: "+14157774444"',
required: true,
}),
},
+ outputSchema: retellSchemas.rawPhoneNumber,
async run({ propsValue, auth }) {
- const { phoneNumber } = propsValue;
-
- // Validate phone number format
- const e164Regex = /^\+[1-9]\d{1,14}$/;
- if (!e164Regex.test(phoneNumber)) {
- throw new Error('Phone Number must be in E.164 format (e.g., +14157774444)');
- }
-
- return await retellAiApiCall({
+ const phoneNumber = retellInput.e164({ value: propsValue.phoneNumber, label: 'Phone Number' });
+ return retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.GET,
- url: `/get-phone-number/${encodeURIComponent(phoneNumber)}`,
- auth: auth,
+ path: `/get-phone-number/${encodeURIComponent(phoneNumber)}`,
+ retryRateLimit: true,
});
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/get-voice.ts b/packages/pieces/community/retell-ai/src/lib/actions/get-voice.ts
index 426269471b4..c2bb321a896 100644
--- a/packages/pieces/community/retell-ai/src/lib/actions/get-voice.ts
+++ b/packages/pieces/community/retell-ai/src/lib/actions/get-voice.ts
@@ -1,8 +1,10 @@
import { HttpMethod } from '@activepieces/pieces-common';
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from '../common/client';
+import { createAction } from '@activepieces/pieces-framework';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
import { voiceIdDropdown } from '../common/props';
+import { retellSchemas } from '../common/schemas';
export const getVoice = createAction({
auth: retellAiAuth,
@@ -10,22 +12,21 @@ export const getVoice = createAction({
classification: 'READ',
displayName: 'Get Voice',
description: 'Retrieve details for a specific voice model or configuration by ID in Retell AI.',
- audience: 'both',
- aiMetadata: { description: 'Look up the details of a single Retell voice by its Voice ID, such as provider, accent, gender, and preview. Use to inspect a voice before assigning it to an agent. Read-only and idempotent.', idempotent: true },
+ audience: 'human',
+ aiMetadata: {
+ description: 'Returns one Retell voice (provider, accent, gender, preview URL). Read-only.',
+ idempotent: true,
+ },
props: {
voiceId: voiceIdDropdown,
},
+ outputSchema: retellSchemas.rawVoice,
async run({ propsValue, auth }) {
- const { voiceId } = propsValue;
-
- if (!voiceId) {
- throw new Error('Voice ID is required');
- }
-
- return await retellAiApiCall({
+ return retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.GET,
- url: `/get-voice/${encodeURIComponent(voiceId)}`,
- auth: auth,
+ path: `/get-voice/${retellInput.seg({ value: propsValue.voiceId, label: 'Voice ID' })}`,
+ retryRateLimit: true,
});
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/actions/make-phone-call.ts b/packages/pieces/community/retell-ai/src/lib/actions/make-phone-call.ts
index e1b4e67989b..3b9b3610cd7 100644
--- a/packages/pieces/community/retell-ai/src/lib/actions/make-phone-call.ts
+++ b/packages/pieces/community/retell-ai/src/lib/actions/make-phone-call.ts
@@ -1,8 +1,10 @@
import { HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from '../common/client';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf, retellApiCall } from '../common/client';
+import { retellInput } from '../common/input';
import { agentIdDropdown } from '../common/props';
+import { retellSchemas } from '../common/schemas';
export const makePhoneCall = createAction({
auth: retellAiAuth,
@@ -10,13 +12,16 @@ export const makePhoneCall = createAction({
classification: 'WRITE',
displayName: 'Make Phone Call',
description: 'Initiate a new outbound phone call using Retell AI agents.',
- audience: 'both',
- aiMetadata: { description: 'Place an outbound phone call from a Retell-owned/imported number to a destination number, dialed by a Retell AI voice agent. Use to start a live AI-driven call. Both numbers must be in E.164 format; the agent version, metadata, dynamic prompt variables, and custom SIP headers can optionally be overridden per call. Not idempotent: each call places a new outbound call.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Places an outbound phone call from a Retell number, handled by a Retell voice agent. Billed per minute; each run dials again.',
+ idempotent: false,
+ },
props: {
fromNumber: Property.ShortText({
displayName: 'From Number',
- description:
- 'The number you own in E.164 format. Must be a number purchased from Retell or imported to Retell.',
+ description: 'The number you own in E.164 format. Must be a number purchased from Retell or imported to Retell.',
required: true,
}),
toNumber: Property.ShortText({
@@ -25,7 +30,7 @@ export const makePhoneCall = createAction({
'The number you want to call, in E.164 format. If using a number purchased from Retell, only US numbers are supported as destination.',
required: true,
}),
- overrideAgentId: agentIdDropdown('Agent'),
+ overrideAgentId: agentIdDropdown({ displayName: 'Agent' }),
overrideAgentVersion: Property.Number({
displayName: 'Override Agent Version',
description:
@@ -41,7 +46,7 @@ export const makePhoneCall = createAction({
dynamicVariables: Property.Object({
displayName: 'Dynamic Variables',
description:
- 'Add optional dynamic variables in key value pairs of string that injects into your Response Engine prompt and tool description. Only applicable for Response Engine.',
+ 'Key-value pairs for the agent prompt. Values are sent as text.',
required: false,
}),
customSipHeaders: Property.Object({
@@ -50,57 +55,41 @@ export const makePhoneCall = createAction({
required: false,
}),
},
+ outputSchema: retellSchemas.rawCall,
async run({ propsValue, auth }) {
- const {
- fromNumber,
- toNumber,
- overrideAgentId,
- overrideAgentVersion,
- metadata,
- dynamicVariables,
- customSipHeaders,
- } = propsValue;
-
- // Validate phone numbers
- const e164Regex = /^\+[1-9]\d{1,14}$/;
- if (!e164Regex.test(fromNumber)) {
- throw new Error('From Number must be in E.164 format (e.g., +14157774444)');
- }
-
- if (!e164Regex.test(toNumber)) {
- throw new Error('To Number must be in E.164 format (e.g., +12137774445)');
- }
-
const body: Record<string, unknown> = {
- from_number: fromNumber,
- to_number: toNumber,
+ from_number: retellInput.e164({ value: propsValue.fromNumber, label: 'From Number' }),
+ to_number: retellInput.e164({ value: propsValue.toNumber, label: 'To Number' }),
};
-
- if (overrideAgentId) {
- body['override_agent_id'] = overrideAgentId;
+ const agentId = retellInput.optionalText(propsValue.overrideAgentId);
+ if (agentId !== undefined) {
+ body['override_agent_id'] = agentId;
}
-
- if (overrideAgentVersion !== undefined) {
- body['override_agent_version'] = overrideAgentVersion;
+ const version = retellInput.optionalInteger({
+ value: propsValue.overrideAgentVersion,
+ label: 'Override Agent Version',
+ min: 0,
+ });
+ if (version !== undefined) {
+ body['override_agent_version'] = version;
}
-
- if (metadata) {
+ const metadata = retellInput.objectValue({ value: propsValue.metadata, label: 'Metadata' });
+ if (metadata !== undefined) {
body['metadata'] = metadata;
}
-
- if (dynamicVariables) {
- body['retell_llm_dynamic_variables'] = dynamicVariables;
+ const variables = retellInput.stringMap({ value: propsValue.dynamicVariables, label: 'Dynamic Variables' });
+ if (variables !== undefined) {
+ body['retell_llm_dynamic_variables'] = variables;
}
-
- if (customSipHeaders) {
- body['custom_sip_headers'] = customSipHeaders;
+ const sipHeaders = retellInput.stringMap({ value: propsValue.customSipHeaders, label: 'Custom SIP Headers' });
+ if (sipHeaders !== undefined) {
+ body['custom_sip_headers'] = sipHeaders;
}
-
- return await retellAiApiCall({
+ return retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.POST,
- url: '/v2/create-phone-call',
- auth: auth,
+ path: '/v2/create-phone-call',
body,
});
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/common/ai-props.ts b/packages/pieces/community/retell-ai/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..48b3a6f6f09
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/ai-props.ts
@@ -0,0 +1,61 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const retellAiProps = {
+ id,
+ e164Number,
+ agentVersion,
+ metadata,
+ dynamicVariables,
+ limit,
+ paginationKey,
+};
+
+function id({ displayName, description, required = true }: { displayName: string; description: string; required?: boolean }) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function e164Number({ displayName, description, required = true }: { displayName: string; description: string; required?: boolean }) {
+ return Property.ShortText({ displayName, description: `${description} E.164 format, for example +14157774444.`, required });
+}
+
+function agentVersion() {
+ return Property.ShortText({
+ displayName: 'Agent Version',
+ description: 'Optional version number (for example 3) or version tag (for example prod). Empty = the agent default.',
+ required: false,
+ });
+}
+
+function metadata() {
+ return Property.Json({
+ displayName: 'Metadata',
+ description: 'Optional JSON object stored with the record for your reference, for example {"customer_id": "123"}.',
+ required: false,
+ });
+}
+
+function dynamicVariables() {
+ return Property.Json({
+ displayName: 'Dynamic Variables',
+ description:
+ 'Optional JSON object of prompt variables, for example {"customer_name": "Ann"}. Values are sent as text.',
+ required: false,
+ });
+}
+
+function limit() {
+ return Property.Number({
+ displayName: 'Limit',
+ description: 'Items per page, 1 to 1000. Default 50.',
+ required: false,
+ defaultValue: 50,
+ });
+}
+
+function paginationKey() {
+ return Property.ShortText({
+ displayName: 'Pagination Key',
+ description: 'pagination_key from the previous page. Empty for the first page.',
+ required: false,
+ });
+}
diff --git a/packages/pieces/community/retell-ai/src/lib/common/auth.ts b/packages/pieces/community/retell-ai/src/lib/common/auth.ts
index 731a238e24b..a1c8995dbfe 100644
--- a/packages/pieces/community/retell-ai/src/lib/common/auth.ts
+++ b/packages/pieces/community/retell-ai/src/lib/common/auth.ts
@@ -1,43 +1,42 @@
-import { PieceAuth } from '@activepieces/pieces-framework';
-import { retellAiApiCall } from './client';
import { HttpMethod } from '@activepieces/pieces-common';
-import { AppConnectionType } from '@activepieces/pieces-framework';
-
-// For typing purposes in the client
-export const RetellAiAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: 'Your Retell AI API Key.',
- required: true,
-});
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { retellApiCall, toRetellError } from './client';
export const retellAiAuth = PieceAuth.CustomAuth({
description: `
- Please follow these steps to get your Retell AI API key:
-
+ To get your Retell AI API key:
+
1. Log in to your Retell AI dashboard.
- 2. Navigate to the API section.
- 3. Generate a new API key or copy your existing one.
- 4. Use this API key to authenticate your requests.`,
+ 2. Open **Settings > API Keys**.
+ 3. Copy an existing key or create a new one.
+ 4. To use the webhook triggers, use the key marked with the **webhook** badge: Retell signs webhooks with that key only.`,
props: {
- apiKey: RetellAiAuth,
+ apiKey: PieceAuth.SecretText({
+ displayName: 'API Key',
+ description: 'Your Retell AI API Key.',
+ required: true,
+ }),
},
validate: async ({ auth }) => {
try {
- await retellAiApiCall({
- method: HttpMethod.GET,
- url: '/list-chat',
- auth: {
- type: AppConnectionType.CUSTOM_AUTH,
- props: auth,
- },
+ await retellApiCall({
+ apiKey: auth.apiKey.trim(),
+ method: HttpMethod.POST,
+ path: '/v2/list-agents',
+ query: { limit: 1 },
+ body: {},
});
return { valid: true };
- } catch (e) {
+ } catch (error) {
+ const retellError = toRetellError(error);
+ if (retellError !== undefined && (retellError.status === 401 || retellError.status === 403)) {
+ return { valid: false, error: 'Invalid API Key: Retell AI rejected it.' };
+ }
return {
valid: false,
- error: 'Invalid API Key',
+ error: `Could not verify the API key with Retell AI: ${error instanceof Error ? error.message : String(error)}`,
};
}
},
required: true,
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/common/client.ts b/packages/pieces/community/retell-ai/src/lib/common/client.ts
index 64b581931e2..b1d49bf6fa4 100644
--- a/packages/pieces/community/retell-ai/src/lib/common/client.ts
+++ b/packages/pieces/community/retell-ai/src/lib/common/client.ts
@@ -1,93 +1,178 @@
-import {
- httpClient,
- HttpMethod,
- HttpRequest,
- HttpMessageBody,
- AuthenticationType
-} from '@activepieces/pieces-common';
-import { AppConnectionValueForAuthProperty, PiecePropValueSchema } from '@activepieces/pieces-framework';
-import { retellAiAuth } from './auth';
-
-export type RetellAiApiCallParams = {
- method: HttpMethod;
- url: string;
- body?: unknown;
- auth: AppConnectionValueForAuthProperty<typeof retellAiAuth>;
-};
+import { httpClient, HttpMessageBody, HttpMethod, HttpRequest } from '@activepieces/pieces-common';
+
+export const RETELL_BASE_URL = 'https://api.retellai.com';
+
+export class RetellAiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ message, status, responseBody }: { message: string; status: number; responseBody: unknown }) {
+ super(message);
+ this.name = 'RetellAiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export function vendorDetail(responseBody: unknown): string | undefined {
+ let parsed = responseBody;
+ if (typeof parsed === 'string') {
+ const trimmed = parsed.trim();
+ if (trimmed.length === 0) {
+ return undefined;
+ }
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return trimmed.slice(0, 500);
+ }
+ }
+ if (!isRecord(parsed)) {
+ return undefined;
+ }
+ const detail = parsed['error_message'] ?? parsed['message'] ?? parsed['error'] ?? parsed['detail'];
+ if (typeof detail === 'string') {
+ return detail.slice(0, 500);
+ }
+ if (detail === undefined || detail === null) {
+ return undefined;
+ }
+ return JSON.stringify(detail).slice(0, 500);
+}
+
+export function buildRetellError({ status, responseBody }: { status: number; responseBody: unknown }): RetellAiError {
+ const base =
+ STATUS_MESSAGES[status] ??
+ (status >= 500
+ ? 'Retell AI returned a server error. Retry later'
+ : status >= 300 && status < 400
+ ? 'Retell AI answered with an unexpected redirect, which was not followed'
+ : 'Retell AI request failed');
+ const detail = vendorDetail(responseBody);
+ const message = detail === undefined ? `${base} (HTTP ${status}).` : `${base} (HTTP ${status}): ${detail}`;
+ return new RetellAiError({ message, status, responseBody });
+}
+
+export function buildRetellUrl({ path, query }: { path: string; query?: RetellQuery }): string {
+ if (
+ !path.startsWith('/') ||
+ path.startsWith('//') ||
+ path.includes('?') ||
+ path.includes('#') ||
+ path.split('/').some((segment) => segment === '..' || segment === '.')
+ ) {
+ throw new Error(`Refusing to call Retell AI with an unexpected path: ${path}`);
+ }
+ const url = new URL(RETELL_BASE_URL + path);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') {
+ continue;
+ }
+ url.searchParams.set(key, String(value));
+ }
+ }
+ return url.toString();
+}
+
+export function apiKeyOf(auth: { props: { apiKey: string } }): string {
+ return auth.props.apiKey.trim();
+}
-export async function retellAiApiCall<T extends HttpMessageBody>({
+export async function retellApiCall<T extends HttpMessageBody = HttpMessageBody>({
+ apiKey,
method,
- url,
+ path,
+ query,
body,
- auth
-}: RetellAiApiCallParams): Promise<T> {
+ retryRateLimit = false,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ contentType,
+}: RetellApiCallParams): Promise<T> {
const request: HttpRequest = {
method,
- url: `https://api.retellai.com${url}`,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: auth.props.apiKey
- },
+ url: buildRetellUrl({ path, query }),
headers: {
- 'Content-Type': 'application/json',
- accept: 'application/json'
+ Authorization: `Bearer ${apiKey}`,
+ Accept: 'application/json',
+ ...(contentType === undefined ? {} : { 'Content-Type': contentType }),
},
- body
+ body,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ timeout: timeoutMs,
};
-
- try {
- const response = await httpClient.sendRequest<T>(request);
- return response.body;
- } catch (error: unknown) {
- const err = error as {
- response?: {
- status?: number;
- body?: { message?: string };
- };
- message?: string;
- };
-
- const status = err.response?.status;
- const apiMessage = err.response?.body?.message || 'No details provided';
-
- // Provide specific, user-friendly error messages based on status codes
- switch (status) {
- case 400:
- throw new Error(
- `Bad Request: The request format is incorrect or missing required data. Please check your input values. Details: ${apiMessage}`
- );
- case 401:
- throw new Error(
- `Authentication Error: Your API key is invalid or expired. Please check your Retell AI API key in the connection settings. Details: ${apiMessage}`
- );
- case 403:
- throw new Error(
- `Access Forbidden: Your API key doesn't have permission for this operation. Please check your Retell AI account permissions. Details: ${apiMessage}`
- );
- case 404:
- throw new Error(
- `Resource Not Found: The requested resource doesn't exist in your Retell AI account. Details: ${apiMessage}`
- );
- case 409:
- throw new Error(
- `Conflict: The resource already exists or there's a data conflict. Details: ${apiMessage}`
- );
- case 429:
- throw new Error(
- `Rate Limit Exceeded: Too many requests to Retell AI API. Please wait a moment before trying again. Details: ${apiMessage}`
- );
- case 500:
- throw new Error(
- `Server Error: Retell AI is experiencing technical difficulties. Please try again later or contact Retell AI support. Details: ${apiMessage}`
- );
- default: {
- const fallbackMessage = err.message || 'Unknown error occurred';
- throw new Error(
- `Retell AI API Error (Status ${status || 'Unknown'}): ${
- apiMessage || fallbackMessage
- }`
- );
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(request);
+ if (response.status >= 300) {
+ throw buildRetellError({ status: response.status, responseBody: response.body });
+ }
+ return response.body;
+ } catch (error) {
+ const mapped = toRetellError(error);
+ if (mapped === undefined) {
+ throw error;
}
+ if (mapped.status === 429 && retryRateLimit && attempt < RATE_LIMIT_BACKOFF_MS.length) {
+ await sleep(RATE_LIMIT_BACKOFF_MS[attempt]);
+ continue;
+ }
+ throw mapped;
}
}
-}
\ No newline at end of file
+}
+
+export function toRetellError(error: unknown): RetellAiError | undefined {
+ if (error instanceof RetellAiError) {
+ return error;
+ }
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (!isRecord(response) || typeof response['status'] !== 'number') {
+ return undefined;
+ }
+ return buildRetellError({ status: response['status'], responseBody: response['body'] });
+}
+
+export function isRetellStatus({ error, statuses }: { error: unknown; statuses: number[] }): boolean {
+ const mapped = toRetellError(error);
+ return mapped !== undefined && statuses.includes(mapped.status);
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+const STATUS_MESSAGES: Record<number, string> = {
+ 400: 'Retell AI rejected the request as invalid',
+ 401: 'Retell AI rejected the API key. Check the API key in the Retell AI connection',
+ 402: 'Retell AI refused the request because the account has no valid payment method or credit',
+ 403: 'Retell AI denied access. Check the API key permissions',
+ 404: 'Retell AI could not find the resource. Check the ID',
+ 409: 'Retell AI reported a conflict with the current state of the resource',
+ 422: 'Retell AI could not process the request',
+ 429: 'Retell AI rate or concurrency limit reached. Retry later',
+};
+
+const DEFAULT_TIMEOUT_MS = 30000;
+const RATE_LIMIT_BACKOFF_MS = [2000, 5000];
+
+export type RetellQuery = Record<string, string | number | boolean | undefined | null>;
+
+export type RetellApiCallParams = {
+ apiKey: string;
+ method: HttpMethod;
+ path: string;
+ query?: RetellQuery;
+ body?: unknown;
+ retryRateLimit?: boolean;
+ timeoutMs?: number;
+ contentType?: string;
+};
diff --git a/packages/pieces/community/retell-ai/src/lib/common/input.ts b/packages/pieces/community/retell-ai/src/lib/common/input.ts
new file mode 100644
index 00000000000..91202c2a2fd
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/input.ts
@@ -0,0 +1,206 @@
+import { isRecord } from './client';
+
+export const retellInput = {
+ seg,
+ e164,
+ optionalE164,
+ optionalText,
+ requiredText,
+ optionalInteger,
+ agentVersion,
+ stringMap,
+ objectValue,
+ stringList,
+ timestampMs,
+ singleAgent,
+ pageLimit,
+ stringFilter,
+ enumFilter,
+};
+
+function seg({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ if (text === '.' || text === '..' || text.includes('/') || text.includes('\\')) {
+ throw new Error(`${label} "${text}" is not a valid Retell AI ID.`);
+ }
+ return encodeURIComponent(text);
+}
+
+function e164({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (!E164.test(text)) {
+ throw new Error(`${label} must be in E.164 format, for example +14157774444.`);
+ }
+ return text;
+}
+
+function optionalE164({ value, label }: { value: unknown; label: string }): string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ return e164({ value, label });
+}
+
+function requiredText({ value, label }: { value: unknown; label: string }): string {
+ const text = optionalText(value);
+ if (text === undefined) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length === 0 ? undefined : trimmed;
+}
+
+function optionalInteger({
+ value,
+ label,
+ min,
+ max,
+}: {
+ value: unknown;
+ label: string;
+ min?: number;
+ max?: number;
+}): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = typeof value === 'number' ? value : Number(String(value).trim());
+ if (!Number.isInteger(parsed)) {
+ throw new Error(`${label} must be a whole number.`);
+ }
+ if ((min !== undefined && parsed < min) || (max !== undefined && parsed > max)) {
+ throw new Error(`${label} must be between ${min ?? '-∞'} and ${max ?? '∞'}.`);
+ }
+ return parsed;
+}
+
+function agentVersion({ value, label }: { value: unknown; label: string }): number | string | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ if (typeof value === 'number') {
+ return optionalInteger({ value, label, min: 0 });
+ }
+ const text = String(value).trim();
+ if (text.length === 0) {
+ return undefined;
+ }
+ return /^\d+$/.test(text) ? Number(text) : text;
+}
+
+function stringMap({ value, label }: { value: unknown; label: string }): Record<string, string> | undefined {
+ const record = objectValue({ value, label });
+ if (record === undefined) {
+ return undefined;
+ }
+ const result: Record<string, string> = {};
+ for (const [key, item] of Object.entries(record)) {
+ if (item === undefined || item === null) {
+ continue;
+ }
+ result[key] = typeof item === 'string' ? item : typeof item === 'object' ? JSON.stringify(item) : String(item);
+ }
+ return result;
+}
+
+function objectValue({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ if (typeof value === 'string') {
+ const trimmed = value.trim();
+ if (trimmed.length === 0) {
+ return undefined;
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ throw new Error(`${label} must be a JSON object.`);
+ }
+ if (!isRecord(parsed)) {
+ throw new Error(`${label} must be a JSON object.`);
+ }
+ return parsed;
+ }
+ if (!isRecord(value)) {
+ throw new Error(`${label} must be an object.`);
+ }
+ return value;
+}
+
+function stringList({ value, label, max }: { value: unknown; label: string; max?: number }): string[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ const raw = Array.isArray(value) ? value : [value];
+ const items = raw
+ .flatMap((item) => (Array.isArray(item) ? item : [item]))
+ .map((item) => (typeof item === 'string' ? item.trim() : typeof item === 'number' ? String(item) : ''))
+ .filter((item) => item.length > 0);
+ if (max !== undefined && items.length > max) {
+ throw new Error(`${label} accepts at most ${max} entries.`);
+ }
+ return items;
+}
+
+function timestampMs({ value, label }: { value: unknown; label: string }): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ if (typeof value === 'number') {
+ return value < 100000000000 ? value * 1000 : value;
+ }
+ const text = String(value).trim();
+ if (/^\d+$/.test(text)) {
+ const parsed = Number(text);
+ return parsed < 100000000000 ? parsed * 1000 : parsed;
+ }
+ const parsed = Date.parse(text);
+ if (Number.isNaN(parsed)) {
+ throw new Error(`${label} must be an ISO date or a Unix timestamp.`);
+ }
+ return parsed;
+}
+
+function singleAgent({ agentId, version, label }: { agentId: unknown; version: unknown; label: string }) {
+ const id = optionalText(agentId);
+ if (id === undefined) {
+ return undefined;
+ }
+ const parsedVersion = agentVersion({ value: version, label: `${label} Version` });
+ return [{ agent_id: id, ...(parsedVersion === undefined ? {} : { agent_version: parsedVersion }), weight: 1 }];
+}
+
+function pageLimit(value: unknown): number {
+ return optionalInteger({ value, label: 'Limit', min: 1, max: 1000 }) ?? 50;
+}
+
+function stringFilter(value: string) {
+ return { type: 'string', op: 'eq', value };
+}
+
+function enumFilter({ value, label, allowed }: { value: unknown; label: string; allowed: readonly string[] }) {
+ const items = stringList({ value: typeof value === 'string' ? value.split(',') : value, label });
+ if (items.length === 0) {
+ return undefined;
+ }
+ const invalid = items.filter((item) => !allowed.includes(item));
+ if (invalid.length > 0) {
+ throw new Error(`${label} has unknown values: ${invalid.join(', ')}. Allowed: ${allowed.join(', ')}.`);
+ }
+ return { type: 'enum', op: 'in', value: items };
+}
+
+const E164 = /^\+[1-9]\d{1,14}$/;
+
diff --git a/packages/pieces/community/retell-ai/src/lib/common/knowledge-base.ts b/packages/pieces/community/retell-ai/src/lib/common/knowledge-base.ts
new file mode 100644
index 00000000000..6ed6021ccee
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/knowledge-base.ts
@@ -0,0 +1,116 @@
+import { randomBytes } from 'crypto';
+import { Property } from '@activepieces/pieces-framework';
+import { isRecord } from './client';
+import { retellInput } from './input';
+
+export const knowledgeBaseSourceProps = {
+ texts: Property.Array({
+ displayName: 'Texts',
+ description: 'Optional text snippets to add, each with a title.',
+ required: false,
+ properties: {
+ title: Property.ShortText({ displayName: 'Title', required: true }),
+ text: Property.LongText({ displayName: 'Text', required: true }),
+ },
+ }),
+ urls: Property.Array({
+ displayName: 'URLs',
+ description: 'Optional web pages Retell scrapes and adds.',
+ required: false,
+ }),
+ file: Property.File({
+ displayName: 'File',
+ description: 'Optional document to add (PDF, DOCX, TXT, MD, CSV and similar, up to 50 MB).',
+ required: false,
+ }),
+};
+
+export function buildKnowledgeBaseForm({
+ name,
+ texts,
+ urls,
+ file,
+ requireSource,
+}: {
+ name?: string;
+ texts: unknown;
+ urls: unknown;
+ file: unknown;
+ requireSource: boolean;
+}): MultipartBody {
+ const parts: MultipartPart[] = [];
+ if (name !== undefined) {
+ parts.push({ name: 'knowledge_base_name', value: name });
+ }
+ const textEntries = (Array.isArray(texts) ? texts : []).map((entry, index) => {
+ const record = isRecord(entry) ? entry : {};
+ return {
+ title: retellInput.requiredText({ value: record['title'], label: `Text ${index + 1} Title` }),
+ text: retellInput.requiredText({ value: record['text'], label: `Text ${index + 1} Text` }),
+ };
+ });
+ const urlEntries = retellInput.stringList({ value: urls, label: 'URLs', max: MAX_URLS });
+ for (const url of urlEntries) {
+ if (!/^https?:\/\//i.test(url)) {
+ throw new Error(`URL "${url}" must start with http:// or https://.`);
+ }
+ }
+ const upload = readFile(file);
+ if (requireSource && textEntries.length === 0 && urlEntries.length === 0 && upload === undefined) {
+ throw new Error('Add at least one text, URL or file.');
+ }
+ if (textEntries.length > 0) {
+ parts.push({ name: 'knowledge_base_texts', value: JSON.stringify(textEntries) });
+ }
+ if (urlEntries.length > 0) {
+ parts.push({ name: 'knowledge_base_urls', value: JSON.stringify(urlEntries) });
+ }
+ if (upload !== undefined) {
+ parts.push({ name: 'knowledge_base_files', value: upload.data, filename: upload.filename });
+ }
+ return encodeMultipart(parts);
+}
+
+function encodeMultipart(parts: MultipartPart[]): MultipartBody {
+ const boundary = `----RetellAiBoundary${randomBytes(12).toString('hex')}`;
+ const chunks = parts.flatMap((part) => {
+ const disposition =
+ part.filename === undefined
+ ? `form-data; name="${part.name}"`
+ : `form-data; name="${part.name}"; filename="${part.filename.replace(/["\r\n\\]/g, '_')}"`;
+ const headers = [`--${boundary}`, `Content-Disposition: ${disposition}`];
+ if (part.filename !== undefined) {
+ headers.push('Content-Type: application/octet-stream');
+ }
+ return [
+ Buffer.from(`${headers.join('\r\n')}\r\n\r\n`, 'utf8'),
+ typeof part.value === 'string' ? Buffer.from(part.value, 'utf8') : part.value,
+ Buffer.from('\r\n', 'utf8'),
+ ];
+ });
+ return {
+ body: Buffer.concat([...chunks, Buffer.from(`--${boundary}--\r\n`, 'utf8')]),
+ contentType: `multipart/form-data; boundary=${boundary}`,
+ };
+}
+
+function readFile(file: unknown): { data: Buffer; filename: string } | undefined {
+ if (file === undefined || file === null || file === '') {
+ return undefined;
+ }
+ if (!isRecord(file) && typeof file !== 'object') {
+ throw new Error('File must be a file from an earlier step.');
+ }
+ const data: unknown = Reflect.get(file, 'data');
+ const filename: unknown = Reflect.get(file, 'filename');
+ if (!Buffer.isBuffer(data) || typeof filename !== 'string' || filename.length === 0) {
+ throw new Error('File must be a file from an earlier step.');
+ }
+ return { data, filename };
+}
+
+const MAX_URLS = 100;
+
+type MultipartPart = { name: string; value: string | Buffer; filename?: string };
+
+export type MultipartBody = { body: Buffer; contentType: string };
diff --git a/packages/pieces/community/retell-ai/src/lib/common/mappers.ts b/packages/pieces/community/retell-ai/src/lib/common/mappers.ts
new file mode 100644
index 00000000000..e753197d7e6
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/mappers.ts
@@ -0,0 +1,391 @@
+import { isRecord } from './client';
+
+export const retellMap = {
+ str,
+ num,
+ rec,
+ itemsOf,
+ page,
+ call,
+ webCall,
+ chat,
+ chatListItem,
+ chatCompletion,
+ agent,
+ chatAgent,
+ agentListItem,
+ agentVersion,
+ phoneNumber,
+ voice,
+ knowledgeBase,
+ retellLlm,
+ contact,
+ concurrency,
+ batchCall,
+};
+
+function str(value: unknown): string | null {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return String(value);
+ }
+ return null;
+}
+
+function num(value: unknown): number | null {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
+}
+
+function bool(value: unknown): boolean | null {
+ return typeof value === 'boolean' ? value : null;
+}
+
+function rec(value: unknown): Record<string, unknown> {
+ return isRecord(value) ? value : {};
+}
+
+function objOrNull(value: unknown): Record<string, unknown> | null {
+ return isRecord(value) ? value : null;
+}
+
+function iso(value: unknown): string | null {
+ const ms = num(value);
+ if (ms === null) {
+ return null;
+ }
+ const date = new Date(ms);
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
+}
+
+function list(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function itemsOf(body: unknown): unknown[] {
+ if (Array.isArray(body)) {
+ return body;
+ }
+ const record = rec(body);
+ if (Array.isArray(record['items'])) {
+ return record['items'];
+ }
+ if (Array.isArray(record['data'])) {
+ return record['data'];
+ }
+ return [];
+}
+
+function page<T>({ body, mapItem }: { body: unknown; mapItem: (item: unknown) => T }): RetellPage<T> {
+ const record = rec(body);
+ const items = itemsOf(body).map(mapItem);
+ const paginationKey = str(record['pagination_key']);
+ const hasMore = bool(record['has_more']);
+ return {
+ items,
+ count: items.length,
+ pagination_key: paginationKey,
+ has_more: hasMore ?? false,
+ total: num(record['total']),
+ };
+}
+
+function agentWeights(value: unknown): AgentWeight[] {
+ return list(value).map((entry) => {
+ const item = rec(entry);
+ return {
+ agent_id: str(item['agent_id']),
+ agent_version: str(item['agent_version']),
+ weight: num(item['weight']),
+ };
+ });
+}
+
+function call(body: unknown) {
+ const c = rec(body);
+ const analysis = rec(c['call_analysis']);
+ const cost = rec(c['call_cost']);
+ const telephony = rec(c['telephony_identifier']);
+ return {
+ call_id: str(c['call_id']),
+ call_type: str(c['call_type']),
+ call_status: str(c['call_status']),
+ direction: str(c['direction']),
+ from_number: str(c['from_number']),
+ to_number: str(c['to_number']),
+ agent_id: str(c['agent_id']),
+ agent_name: str(c['agent_name']),
+ agent_version: str(c['agent_version']),
+ batch_call_id: str(c['batch_call_id']),
+ start_timestamp: num(c['start_timestamp']),
+ start_time: iso(c['start_timestamp']),
+ end_timestamp: num(c['end_timestamp']),
+ end_time: iso(c['end_timestamp']),
+ duration_ms: num(c['duration_ms']),
+ disconnection_reason: str(c['disconnection_reason']),
+ transcript: str(c['transcript']),
+ recording_url: str(c['recording_url']),
+ public_log_url: str(c['public_log_url']),
+ call_summary: str(analysis['call_summary']),
+ user_sentiment: str(analysis['user_sentiment']),
+ call_successful: bool(analysis['call_successful']),
+ in_voicemail: bool(analysis['in_voicemail']),
+ custom_analysis_data: objOrNull(analysis['custom_analysis_data']),
+ combined_cost_cents: num(cost['combined_cost']),
+ metadata: objOrNull(c['metadata']),
+ dynamic_variables: objOrNull(c['retell_llm_dynamic_variables']),
+ collected_dynamic_variables: objOrNull(c['collected_dynamic_variables']),
+ twilio_call_sid: str(telephony['twilio_call_sid']),
+ };
+}
+
+function webCall(body: unknown) {
+ const c = rec(body);
+ return {
+ call_id: str(c['call_id']),
+ access_token: str(c['access_token']),
+ expires_at: str(c['expires_at']) ?? iso(c['expires_at']),
+ };
+}
+
+function chatMessage(entry: unknown) {
+ const m = rec(entry);
+ return {
+ message_id: str(m['message_id']),
+ role: str(m['role']),
+ content: str(m['content']),
+ created_timestamp: num(m['created_timestamp']),
+ };
+}
+
+function chat(body: unknown) {
+ const c = rec(body);
+ const analysis = rec(c['chat_analysis']);
+ const cost = rec(c['chat_cost']);
+ return {
+ chat_id: str(c['chat_id']),
+ agent_id: str(c['agent_id']),
+ agent_version: str(c['version']),
+ chat_status: str(c['chat_status']),
+ chat_type: str(c['chat_type']),
+ start_timestamp: num(c['start_timestamp']),
+ start_time: iso(c['start_timestamp']),
+ end_timestamp: num(c['end_timestamp']),
+ end_time: iso(c['end_timestamp']),
+ transcript: str(c['transcript']),
+ chat_summary: str(analysis['chat_summary']),
+ user_sentiment: str(analysis['user_sentiment']),
+ chat_successful: bool(analysis['chat_successful']),
+ custom_analysis_data: objOrNull(analysis['custom_analysis_data']),
+ combined_cost_cents: num(cost['combined_cost']),
+ metadata: objOrNull(c['metadata']),
+ };
+}
+
+function chatListItem(body: unknown) {
+ const { transcript: _transcript, ...rest } = chat(body);
+ return rest;
+}
+
+function chatCompletion(body: unknown) {
+ const messages = list(rec(body)['messages']).map(chatMessage);
+ const agentReplies = messages.filter((message) => message.role === 'agent' && message.content !== null);
+ return {
+ messages,
+ reply: agentReplies.map((message) => message.content).join('\n'),
+ message_count: messages.length,
+ };
+}
+
+function responseEngine(value: unknown) {
+ const engine = rec(value);
+ return {
+ response_engine_type: str(engine['type']),
+ llm_id: str(engine['llm_id']),
+ conversation_flow_id: str(engine['conversation_flow_id']),
+ };
+}
+
+function agent(body: unknown) {
+ const a = rec(body);
+ return {
+ agent_id: str(a['agent_id']),
+ agent_name: str(a['agent_name']),
+ version: num(a['version']),
+ is_published: bool(a['is_published']),
+ voice_id: str(a['voice_id']),
+ language: str(a['language']),
+ webhook_url: str(a['webhook_url']),
+ ...responseEngine(a['response_engine']),
+ last_modification_timestamp: num(a['last_modification_timestamp']),
+ last_modified_time: iso(a['last_modification_timestamp']),
+ };
+}
+
+function chatAgent(body: unknown) {
+ const a = rec(body);
+ return {
+ agent_id: str(a['agent_id']),
+ agent_name: str(a['agent_name']),
+ version: num(a['version']),
+ is_published: bool(a['is_published']),
+ language: str(a['language']),
+ webhook_url: str(a['webhook_url']),
+ ...responseEngine(a['response_engine']),
+ last_modification_timestamp: num(a['last_modification_timestamp']),
+ last_modified_time: iso(a['last_modification_timestamp']),
+ };
+}
+
+function agentListItem(body: unknown) {
+ const a = rec(body);
+ return {
+ agent_id: str(a['agent_id']),
+ agent_name: str(a['agent_name']),
+ channel: str(a['channel']),
+ version: num(a['version']),
+ is_published: bool(a['is_published']),
+ last_modified_time: iso(a['user_modified_timestamp'] ?? a['last_modification_timestamp']),
+ };
+}
+
+function agentVersion(body: unknown) {
+ const v = rec(body);
+ return {
+ version: num(v['version']),
+ is_published: bool(v['is_published']),
+ version_title: str(v['version_title']),
+ version_description: str(v['version_description']),
+ base_version: num(v['base_version']),
+ last_modified_time: iso(v['last_modification_timestamp']),
+ };
+}
+
+function phoneNumber(body: unknown) {
+ const p = rec(body);
+ const inbound = agentWeights(p['inbound_agents']);
+ const outbound = agentWeights(p['outbound_agents']);
+ return {
+ phone_number: str(p['phone_number']),
+ phone_number_pretty: str(p['phone_number_pretty']),
+ phone_number_type: str(p['phone_number_type']),
+ nickname: str(p['nickname']),
+ area_code: num(p['area_code']),
+ inbound_agent_id: inbound[0]?.agent_id ?? str(p['inbound_agent_id']),
+ outbound_agent_id: outbound[0]?.agent_id ?? str(p['outbound_agent_id']),
+ inbound_agents: inbound,
+ outbound_agents: outbound,
+ inbound_webhook_url: str(p['inbound_webhook_url']),
+ last_modified_time: iso(p['last_modification_timestamp']),
+ };
+}
+
+function voice(body: unknown) {
+ const v = rec(body);
+ return {
+ voice_id: str(v['voice_id']),
+ voice_name: str(v['voice_name']),
+ provider: str(v['provider']),
+ accent: str(v['accent']),
+ gender: str(v['gender']),
+ age: str(v['age']),
+ preview_audio_url: str(v['preview_audio_url']),
+ };
+}
+
+function knowledgeBase(body: unknown) {
+ const k = rec(body);
+ const sources = list(k['knowledge_base_sources']).map((entry) => {
+ const s = rec(entry);
+ return {
+ source_id: str(s['source_id']),
+ type: str(s['type']),
+ title: str(s['title']) ?? str(s['filename']),
+ url: str(s['url']) ?? str(s['file_url']) ?? str(s['content_url']),
+ };
+ });
+ return {
+ knowledge_base_id: str(k['knowledge_base_id']),
+ knowledge_base_name: str(k['knowledge_base_name']),
+ status: str(k['status']),
+ enable_auto_refresh: bool(k['enable_auto_refresh']),
+ source_count: sources.length,
+ sources,
+ last_refreshed_time: iso(k['last_refreshed_timestamp']),
+ };
+}
+
+function retellLlm(body: unknown) {
+ const l = rec(body);
+ const kbIds = list(l['knowledge_base_ids']).filter((id): id is string => typeof id === 'string');
+ return {
+ llm_id: str(l['llm_id']),
+ version: num(l['version']),
+ is_published: bool(l['is_published']),
+ model: str(l['model']),
+ start_speaker: str(l['start_speaker']),
+ general_prompt: str(l['general_prompt']),
+ begin_message: str(l['begin_message']),
+ knowledge_base_ids: kbIds.join(', '),
+ last_modified_time: iso(l['last_modification_timestamp']),
+ };
+}
+
+function contact(body: unknown) {
+ const c = rec(body);
+ const tags = list(c['contact_tags'])
+ .map((entry) => str(rec(entry)['label']))
+ .filter((label): label is string => label !== null);
+ return {
+ contact_id: str(c['contact_id']),
+ phone_number: str(c['phone_number']),
+ first_name: str(c['first_name']),
+ last_name: str(c['last_name']),
+ do_not_call: bool(c['do_not_call']),
+ contact_memory: str(c['contact_memory']),
+ external_id: str(c['external_id']),
+ tags: tags.join(', '),
+ custom_fields: objOrNull(c['custom_fields']),
+ conversation_count: num(c['conversation_count']),
+ last_conversation_time: iso(c['last_conversation_timestamp']),
+ created_time: iso(c['created_timestamp']),
+ };
+}
+
+function concurrency(body: unknown) {
+ const c = rec(body);
+ const current = num(c['current_concurrency']);
+ const limit = num(c['concurrency_limit']);
+ return {
+ current_concurrency: current,
+ concurrency_limit: limit,
+ available_concurrency: current !== null && limit !== null ? Math.max(limit - current, 0) : null,
+ base_concurrency: num(c['base_concurrency']),
+ purchased_concurrency: num(c['purchased_concurrency']),
+ reserved_inbound_concurrency: num(c['reserved_inbound_concurrency']),
+ concurrency_burst_enabled: bool(c['concurrency_burst_enabled']),
+ };
+}
+
+function batchCall(body: unknown) {
+ const b = rec(body);
+ return {
+ batch_call_id: str(b['batch_call_id']),
+ name: str(b['name']),
+ from_number: str(b['from_number']),
+ scheduled_timestamp: num(b['scheduled_timestamp']),
+ scheduled_time: iso(b['scheduled_timestamp']),
+ total_task_count: num(b['total_task_count']),
+ };
+}
+
+export type RetellPage<T> = {
+ items: T[];
+ count: number;
+ pagination_key: string | null;
+ has_more: boolean;
+ total: number | null;
+};
+
+type AgentWeight = { agent_id: string | null; agent_version: string | null; weight: number | null };
diff --git a/packages/pieces/community/retell-ai/src/lib/common/options.ts b/packages/pieces/community/retell-ai/src/lib/common/options.ts
new file mode 100644
index 00000000000..dd46a6608dd
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/options.ts
@@ -0,0 +1,5 @@
+export const retellOptions = {
+ CALL_STATUSES: ['not_connected', 'ongoing', 'ended', 'error'],
+ CHAT_STATUSES: ['ongoing', 'ended', 'error'],
+ MAX_BATCH_TASKS: 1000,
+};
diff --git a/packages/pieces/community/retell-ai/src/lib/common/props.ts b/packages/pieces/community/retell-ai/src/lib/common/props.ts
index 58fe025941f..4fe32744946 100644
--- a/packages/pieces/community/retell-ai/src/lib/common/props.ts
+++ b/packages/pieces/community/retell-ai/src/lib/common/props.ts
@@ -1,248 +1,150 @@
-import { Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { retellAiApiCall } from './client';
-import { PiecePropValueSchema } from '@activepieces/pieces-framework';
+import { Property } from '@activepieces/pieces-framework';
import { retellAiAuth } from './auth';
+import { apiKeyOf, retellApiCall } from './client';
+import { retellMap } from './mappers';
-interface RetellAiAgent {
- agent_id: string;
- version: number;
- is_published: boolean;
- agent_name: string;
- voice_id: string;
- voice_model?: string;
- fallback_voice_ids?: string[];
- voice_temperature?: number;
- voice_speed?: number;
- volume?: number;
- responsiveness?: number;
- interruption_sensitivity?: number;
- enable_backchannel?: boolean;
- backchannel_frequency?: number;
- backchannel_words?: string[];
- reminder_trigger_ms?: number;
- reminder_max_count?: number;
- ambient_sound?: string;
- ambient_sound_volume?: number;
- language?: string;
- webhook_url?: string;
- boosted_keywords?: string[];
- opt_out_sensitive_data_storage?: boolean;
- opt_in_signed_url?: boolean;
- pronunciation_dictionary?: Array<{
- word: string;
- alphabet: string;
- phoneme: string;
- }>;
- normalize_for_speech?: boolean;
- end_call_after_silence_ms?: number;
- max_call_duration_ms?: number;
- voicemail_option?: {
- action: {
- type: string;
- text: string;
- };
- };
- post_call_analysis_data?: Array<{
- type: string;
- name: string;
- description: string;
- examples: string[];
- }>;
- post_call_analysis_model?: string;
- begin_message_delay_ms?: number;
- ring_duration_ms?: number;
- stt_mode?: string;
- vocab_specialization?: string;
- allow_user_dtmf?: boolean;
- user_dtmf_options?: {
- digit_limit: number;
- termination_key: string;
- timeout_ms: number;
- };
- denoising_mode?: string;
- last_modification_timestamp?: number;
- response_engine?: {
- type: string;
- llm_id: string;
- version: number;
- };
-}
-
-type RetellAiAgentListResponse = RetellAiAgent[];
-
-interface RetellAiCall {
- call_id: string;
- agent_id: string;
- call_status: string;
- call_type: string;
- start_timestamp?: number;
- end_timestamp?: number;
-}
-
-interface RetellAiVoice {
- voice_id: string;
- voice_name: string;
- provider: string;
- gender: string;
- accent?: string;
- age?: string;
+export async function listAllAgents({ apiKey, channel }: { apiKey: string; channel?: 'voice' | 'chat' }) {
+ const agents: { agent_id: string; agent_name: string | null }[] = [];
+ const seen = new Set<string>();
+ let paginationKey: string | null = null;
+ for (let pageIndex = 0; pageIndex < MAX_DROPDOWN_PAGES; pageIndex++) {
+ const body: unknown = await retellApiCall({
+ apiKey,
+ method: HttpMethod.POST,
+ path: '/v2/list-agents',
+ query: { limit: 1000, pagination_key: paginationKey },
+ body: channel === undefined ? {} : { filter_criteria: { channel: { type: 'string', op: 'eq', value: channel } } },
+ retryRateLimit: true,
+ });
+ const page = retellMap.page({ body, mapItem: retellMap.agentListItem });
+ for (const agent of page.items) {
+ if (agent.agent_id !== null && !seen.has(agent.agent_id)) {
+ seen.add(agent.agent_id);
+ agents.push({ agent_id: agent.agent_id, agent_name: agent.agent_name });
+ }
+ }
+ if (!page.has_more || page.pagination_key === null || page.pagination_key === paginationKey) {
+ return { agents, truncated: false };
+ }
+ paginationKey = page.pagination_key;
+ }
+ return { agents, truncated: true };
}
-// --- Agent Dropdown ---
-export const agentIdDropdown = (displayName:string,required=false)=> Property.Dropdown({
- auth: retellAiAuth,
- displayName,
- description: 'Select the Retell AI agent.',
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Connect your Retell AI account first',
- };
- }
- try {
- const agents = await retellAiApiCall<RetellAiAgentListResponse>({
- auth,
- method: HttpMethod.GET,
- url: '/list-agents',
- body: {
- limit: 100,
+export const agentIdDropdown = ({ displayName, required = false }: { displayName: string; required?: boolean }) =>
+ Property.Dropdown({
+ auth: retellAiAuth,
+ displayName,
+ description: 'Select the Retell AI agent.',
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your Retell AI account first' };
+ }
+ try {
+ const { agents } = await listAllAgents({ apiKey: apiKeyOf(auth), channel: 'voice' });
+ if (agents.length === 0) {
+ return { disabled: true, options: [], placeholder: 'No voice agents found in your workspace.' };
}
- });
- const agentList = Array.isArray(agents) ? agents : [];
- if (agentList.length === 0) {
+ return {
+ disabled: false,
+ options: agents.map((agent) => ({
+ label: `${agent.agent_name || 'Unnamed Agent'} (${agent.agent_id})`,
+ value: agent.agent_id,
+ })),
+ };
+ } catch (error) {
return {
disabled: true,
options: [],
- placeholder: 'No agents found in your workspace.',
+ placeholder: `Error loading agents: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
- return {
- disabled: false,
- options: agentList.map((agent) => ({
- label: `${agent.agent_name || 'Unnamed Agent'} (${agent.agent_id})`,
- value: agent.agent_id,
- })),
- };
- } catch (error: unknown) {
- const errorMessage =
- error instanceof Error ? error.message : 'Unknown error occurred';
- return {
- disabled: true,
- options: [],
- placeholder: `Error loading agents: ${errorMessage}`,
- };
- }
- },
-});
+ },
+ });
-// --- Call ID Dropdown ---
-export const callIdDropdown = Property.Dropdown({
+export const callIdDropdown = Property.Dropdown({
auth: retellAiAuth,
displayName: 'Call ID',
+ description: 'The 100 most recent calls. Map a Call ID from an earlier step for older calls.',
required: true,
- refreshers: ['auth'],
+ refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Connect your Retell AI account first',
- };
+ return { disabled: true, options: [], placeholder: 'Connect your Retell AI account first' };
}
try {
- const response = await retellAiApiCall<RetellAiCall[]>({
- auth,
+ const body: unknown = await retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.POST,
- url: '/v2/list-calls',
- body: {
- limit: 50,
- sort_order: 'descending'
- }
+ path: '/v3/list-calls',
+ body: { limit: 100, sort_order: 'descending' },
+ retryRateLimit: true,
});
-
- if (!response || response.length === 0) {
- return {
- disabled: true,
- options: [],
- placeholder: 'No calls found in your workspace.',
- };
+ const calls = retellMap.itemsOf(body).map(retellMap.call);
+ if (calls.length === 0) {
+ return { disabled: true, options: [], placeholder: 'No calls found in your workspace.' };
}
-
return {
disabled: false,
- options: response.map((call) => ({
- label: `${call.call_id} (${call.call_status} - ${call.call_type})`,
- value: call.call_id,
- })),
+ options: calls
+ .filter((call) => call.call_id !== null)
+ .map((call) => ({
+ label: `${call.call_id} (${call.call_status ?? 'unknown'} - ${call.call_type ?? 'call'}${call.start_time ? `, ${call.start_time}` : ''})`,
+ value: call.call_id ?? '',
+ })),
};
- } catch (error: unknown) {
- const errorMessage =
- error instanceof Error ? error.message : 'Unknown error occurred';
+ } catch (error) {
return {
disabled: true,
options: [],
- placeholder: `Error loading calls: ${errorMessage}`,
+ placeholder: `Error loading calls: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
},
});
-// --- Voice Dropdown ---
-export const voiceIdDropdown = Property.Dropdown({
+export const voiceIdDropdown = Property.Dropdown({
auth: retellAiAuth,
displayName: 'Voice',
required: true,
- refreshers: ['auth'],
+ refreshers: [],
options: async ({ auth }) => {
if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Connect your Retell AI account first',
- };
+ return { disabled: true, options: [], placeholder: 'Connect your Retell AI account first' };
}
try {
- const response = await retellAiApiCall<RetellAiVoice[]>({
- auth,
+ const body: unknown = await retellApiCall({
+ apiKey: apiKeyOf(auth),
method: HttpMethod.GET,
- url: '/list-voices',
+ path: '/list-voices',
+ retryRateLimit: true,
});
- const voices = response;
+ const voices = retellMap.itemsOf(body).map(retellMap.voice);
if (voices.length === 0) {
- return {
- disabled: true,
- options: [],
- placeholder: 'No voices found in your workspace.',
- };
+ return { disabled: true, options: [], placeholder: 'No voices found in your workspace.' };
}
return {
disabled: false,
- options: voices.map((voice) => {
- const voiceInfo = voice.accent ? `${voice.gender}, ${voice.accent}` : voice.gender;
- return {
- label: `${voice.voice_name} (${voiceInfo})`,
- value: voice.voice_id,
- };
- }),
+ options: voices
+ .filter((voice) => voice.voice_id !== null)
+ .map((voice) => {
+ const info = [voice.gender, voice.accent].filter((part) => part !== null).join(', ');
+ return { label: `${voice.voice_name ?? voice.voice_id}${info ? ` (${info})` : ''}`, value: voice.voice_id ?? '' };
+ }),
};
- } catch (error: unknown) {
- const errorMessage =
- error instanceof Error ? error.message : 'Unknown error occurred';
+ } catch (error) {
return {
disabled: true,
options: [],
- placeholder: `Error loading voices: ${errorMessage}`,
+ placeholder: `Error loading voices: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
},
});
-// --- Number Provider Dropdown ---
export const numberProviderDropdown = Property.StaticDropdown({
displayName: 'Number Provider',
description: 'The provider to purchase the phone number from.',
@@ -256,52 +158,4 @@ export const numberProviderDropdown = Property.StaticDropdown({
defaultValue: 'twilio',
});
-// --- Language Dropdown ---
-export const languageDropdown = Property.StaticDropdown({
- displayName: 'Language',
- description: 'The language for the agent to use.',
- required: false,
- options: {
- options: [
- { label: 'English (US)', value: 'en-US' },
- { label: 'English (UK)', value: 'en-GB' },
- { label: 'Spanish', value: 'es-ES' },
- { label: 'French', value: 'fr-FR' },
- { label: 'German', value: 'de-DE' },
- { label: 'Italian', value: 'it-IT' },
- { label: 'Portuguese', value: 'pt-PT' },
- { label: 'Dutch', value: 'nl-NL' },
- { label: 'Japanese', value: 'ja-JP' },
- { label: 'Chinese (Mandarin)', value: 'zh-CN' },
- ],
- },
- defaultValue: 'en-US',
-});
-
-// --- STT Mode Dropdown ---
-export const sttModeDropdown = Property.StaticDropdown({
- displayName: 'Speech-to-Text Mode',
- description: 'The speech-to-text mode for the agent.',
- required: false,
- options: {
- options: [
- { label: 'Fast', value: 'fast' },
- { label: 'Standard', value: 'standard' },
- ],
- },
- defaultValue: 'fast',
-});
-
-// --- Denoising Mode Dropdown ---
-export const denoisingModeDropdown = Property.StaticDropdown({
- displayName: 'Denoising Mode',
- description: 'The denoising mode for audio processing.',
- required: false,
- options: {
- options: [
- { label: 'Noise Cancellation', value: 'noise-cancellation' },
- { label: 'None', value: 'none' },
- ],
- },
- defaultValue: 'noise-cancellation',
-});
\ No newline at end of file
+const MAX_DROPDOWN_PAGES = 10;
diff --git a/packages/pieces/community/retell-ai/src/lib/common/sample.ts b/packages/pieces/community/retell-ai/src/lib/common/sample.ts
new file mode 100644
index 00000000000..4741efcc492
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/sample.ts
@@ -0,0 +1,49 @@
+export const SAMPLE_CALL_STARTED = {
+ event: 'call_started',
+ call: { ...baseCall(), call_status: 'ongoing' },
+};
+
+export const SAMPLE_CALL_ENDED = {
+ event: 'call_ended',
+ call: {
+ ...baseCall(),
+ call_status: 'ended',
+ end_timestamp: 1703302428855,
+ duration_ms: 21522,
+ disconnection_reason: 'user_hangup',
+ transcript: 'Agent: hi how are you doing?\nUser: Doing pretty well. How are you?\nAgent: That is great to hear!',
+ recording_url: 'https://retellai.s3.us-west-2.amazonaws.com/Jabr9TXYYJHfvl6Syypi88rdAHYHmcq6/recording.wav',
+ public_log_url: 'https://retellai.s3.us-west-2.amazonaws.com/Jabr9TXYYJHfvl6Syypi88rdAHYHmcq6/public_log.txt',
+ },
+};
+
+export const SAMPLE_CALL_ANALYZED = {
+ event: 'call_analyzed',
+ call: {
+ ...SAMPLE_CALL_ENDED.call,
+ call_analysis: {
+ call_summary: 'The agent called the user to confirm an appointment and the user confirmed.',
+ in_voicemail: false,
+ user_sentiment: 'Positive',
+ call_successful: true,
+ custom_analysis_data: { appointment_confirmed: true },
+ },
+ call_cost: { combined_cost: 7.1, total_duration_seconds: 22 },
+ },
+};
+
+function baseCall() {
+ return {
+ call_type: 'phone_call',
+ call_id: 'Jabr9TXYYJHfvl6Syypi88rdAHYHmcq6',
+ agent_id: 'oBeDLoLOeuAbiuaMFXRtDOLriTJ5tSxD',
+ agent_name: 'Appointment Setter',
+ agent_version: 1,
+ direction: 'outbound',
+ from_number: '+12137771234',
+ to_number: '+12137771235',
+ metadata: { customer_id: 'cus_123' },
+ retell_llm_dynamic_variables: { customer_name: 'John Doe' },
+ start_timestamp: 1703302407333,
+ };
+}
diff --git a/packages/pieces/community/retell-ai/src/lib/common/schemas.ts b/packages/pieces/community/retell-ai/src/lib/common/schemas.ts
new file mode 100644
index 00000000000..af66f3f0db8
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/schemas.ts
@@ -0,0 +1,379 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+function pageSchema({ label, labelKey, itemFields }: { label: string; labelKey: string; itemFields: OutputSchemaField[] }): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label, labelKey, listItems: itemFields },
+ { key: 'count', label: 'Items on This Page', format: 'number' },
+ { key: 'pagination_key', label: 'Pagination Key', description: 'Pass as Pagination Key to fetch the next page.' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'total', label: 'Total Matches', format: 'number', description: 'Only filled when the API reports a total.' },
+ ],
+ };
+}
+
+const callSummaryFields: OutputSchemaField[] = [
+ { key: 'call_id', label: 'Call ID' },
+ { key: 'call_type', label: 'Call Type', description: 'phone_call or web_call.' },
+ { key: 'call_status', label: 'Call Status', description: 'registered, not_connected, ongoing, ended or error.' },
+ { key: 'direction', label: 'Direction' },
+ { key: 'from_number', label: 'From Number' },
+ { key: 'to_number', label: 'To Number' },
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_name', label: 'Agent Name' },
+ { key: 'agent_version', label: 'Agent Version' },
+ { key: 'batch_call_id', label: 'Batch Call ID' },
+ { key: 'start_timestamp', label: 'Start Timestamp (ms)', format: 'number' },
+ { key: 'start_time', label: 'Start Time', format: 'datetime' },
+ { key: 'end_timestamp', label: 'End Timestamp (ms)', format: 'number' },
+ { key: 'end_time', label: 'End Time', format: 'datetime' },
+ { key: 'duration_ms', label: 'Duration (ms)', format: 'number' },
+ { key: 'disconnection_reason', label: 'Disconnection Reason' },
+ { key: 'call_summary', label: 'Call Summary' },
+ { key: 'user_sentiment', label: 'User Sentiment' },
+ { key: 'call_successful', label: 'Call Successful', format: 'boolean' },
+ { key: 'in_voicemail', label: 'In Voicemail', format: 'boolean' },
+ { key: 'custom_analysis_data', label: 'Custom Analysis Data', description: 'Post-call extraction fields defined on the agent.' },
+ { key: 'combined_cost_cents', label: 'Combined Cost (cents)', format: 'number' },
+ { key: 'metadata', label: 'Metadata' },
+ { key: 'dynamic_variables', label: 'Dynamic Variables' },
+ { key: 'collected_dynamic_variables', label: 'Collected Dynamic Variables' },
+ { key: 'twilio_call_sid', label: 'Twilio Call SID' },
+];
+
+const callFields: OutputSchemaField[] = [
+ ...callSummaryFields,
+ { key: 'transcript', label: 'Transcript', description: 'Filled after the call ends.' },
+ {
+ key: 'recording_url',
+ label: 'Recording URL',
+ format: 'url',
+ description: 'Expires if the agent uses signed URLs (opt_in_signed_url).',
+ },
+ { key: 'public_log_url', label: 'Public Log URL', format: 'url' },
+];
+
+const chatFields: OutputSchemaField[] = [
+ { key: 'chat_id', label: 'Chat ID' },
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_version', label: 'Agent Version' },
+ { key: 'chat_status', label: 'Chat Status', description: 'ongoing, ended or error.' },
+ { key: 'chat_type', label: 'Chat Type' },
+ { key: 'start_timestamp', label: 'Start Timestamp (ms)', format: 'number' },
+ { key: 'start_time', label: 'Start Time', format: 'datetime' },
+ { key: 'end_timestamp', label: 'End Timestamp (ms)', format: 'number' },
+ { key: 'end_time', label: 'End Time', format: 'datetime' },
+ { key: 'transcript', label: 'Transcript' },
+ { key: 'chat_summary', label: 'Chat Summary' },
+ { key: 'user_sentiment', label: 'User Sentiment' },
+ { key: 'chat_successful', label: 'Chat Successful', format: 'boolean' },
+ { key: 'custom_analysis_data', label: 'Custom Analysis Data' },
+ { key: 'combined_cost_cents', label: 'Combined Cost (cents)', format: 'number' },
+ { key: 'metadata', label: 'Metadata' },
+];
+
+const engineFields: OutputSchemaField[] = [
+ { key: 'response_engine_type', label: 'Response Engine Type', description: 'retell-llm, conversation-flow or custom-llm.' },
+ { key: 'llm_id', label: 'Retell LLM ID' },
+ { key: 'conversation_flow_id', label: 'Conversation Flow ID' },
+];
+
+const agentFields: OutputSchemaField[] = [
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_name', label: 'Agent Name' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'is_published', label: 'Is Published', format: 'boolean' },
+ { key: 'voice_id', label: 'Voice ID' },
+ { key: 'language', label: 'Language' },
+ { key: 'webhook_url', label: 'Webhook URL', format: 'url' },
+ ...engineFields,
+ { key: 'last_modification_timestamp', label: 'Last Modified Timestamp (ms)', format: 'number' },
+ { key: 'last_modified_time', label: 'Last Modified', format: 'datetime' },
+];
+
+const chatAgentFields: OutputSchemaField[] = agentFields.filter((field) => field.key !== 'voice_id');
+
+const agentListItemFields: OutputSchemaField[] = [
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_name', label: 'Agent Name' },
+ { key: 'channel', label: 'Channel', description: 'voice or chat.' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'is_published', label: 'Is Published', format: 'boolean' },
+ { key: 'last_modified_time', label: 'Last Modified', format: 'datetime' },
+];
+
+const agentVersionFields: OutputSchemaField[] = [
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'is_published', label: 'Is Published', format: 'boolean' },
+ { key: 'version_title', label: 'Version Title' },
+ { key: 'version_description', label: 'Version Description' },
+ { key: 'base_version', label: 'Base Version', format: 'number' },
+ { key: 'last_modified_time', label: 'Last Modified', format: 'datetime' },
+];
+
+const agentWeightFields: OutputSchemaField[] = [
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_version', label: 'Agent Version' },
+ { key: 'weight', label: 'Weight', format: 'number' },
+];
+
+const phoneNumberFields: OutputSchemaField[] = [
+ { key: 'phone_number', label: 'Phone Number' },
+ { key: 'phone_number_pretty', label: 'Phone Number (Formatted)' },
+ { key: 'phone_number_type', label: 'Phone Number Type' },
+ { key: 'nickname', label: 'Nickname' },
+ { key: 'area_code', label: 'Area Code', format: 'number' },
+ { key: 'inbound_agent_id', label: 'Inbound Agent ID', description: 'First inbound agent when several are weighted.' },
+ { key: 'outbound_agent_id', label: 'Outbound Agent ID', description: 'First outbound agent when several are weighted.' },
+ { key: 'inbound_agents', label: 'Inbound Agents', labelKey: 'agent_id', listItems: agentWeightFields },
+ { key: 'outbound_agents', label: 'Outbound Agents', labelKey: 'agent_id', listItems: agentWeightFields },
+ { key: 'inbound_webhook_url', label: 'Inbound Webhook URL', format: 'url' },
+ { key: 'last_modified_time', label: 'Last Modified', format: 'datetime' },
+];
+
+const voiceFields: OutputSchemaField[] = [
+ { key: 'voice_id', label: 'Voice ID' },
+ { key: 'voice_name', label: 'Voice Name' },
+ { key: 'provider', label: 'Provider' },
+ { key: 'accent', label: 'Accent' },
+ { key: 'gender', label: 'Gender' },
+ { key: 'age', label: 'Age' },
+ { key: 'preview_audio_url', label: 'Preview Audio URL', format: 'url' },
+];
+
+const knowledgeBaseFields: OutputSchemaField[] = [
+ { key: 'knowledge_base_id', label: 'Knowledge Base ID' },
+ { key: 'knowledge_base_name', label: 'Name' },
+ { key: 'status', label: 'Status', description: 'in_progress, complete, error or refreshing_in_progress.' },
+ { key: 'enable_auto_refresh', label: 'Auto Refresh', format: 'boolean' },
+ { key: 'source_count', label: 'Source Count', format: 'number' },
+ {
+ key: 'sources',
+ label: 'Sources',
+ labelKey: 'title',
+ listItems: [
+ { key: 'source_id', label: 'Source ID' },
+ { key: 'type', label: 'Type', description: 'document, text or url.' },
+ { key: 'title', label: 'Title or File Name' },
+ { key: 'url', label: 'URL', format: 'url' },
+ ],
+ },
+ { key: 'last_refreshed_time', label: 'Last Refreshed', format: 'datetime' },
+];
+
+const llmFields: OutputSchemaField[] = [
+ { key: 'llm_id', label: 'Retell LLM ID' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'is_published', label: 'Is Published', format: 'boolean' },
+ { key: 'model', label: 'Model' },
+ { key: 'start_speaker', label: 'Start Speaker' },
+ { key: 'general_prompt', label: 'General Prompt' },
+ { key: 'begin_message', label: 'Begin Message' },
+ { key: 'knowledge_base_ids', label: 'Knowledge Base IDs', description: 'Comma-separated.' },
+ { key: 'last_modified_time', label: 'Last Modified', format: 'datetime' },
+];
+
+const contactFields: OutputSchemaField[] = [
+ { key: 'contact_id', label: 'Contact ID' },
+ { key: 'phone_number', label: 'Phone Number' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'do_not_call', label: 'Do Not Call', format: 'boolean' },
+ { key: 'contact_memory', label: 'Contact Memory' },
+ { key: 'external_id', label: 'External ID' },
+ { key: 'tags', label: 'Tags', description: 'Comma-separated tag labels.' },
+ { key: 'custom_fields', label: 'Custom Fields' },
+ { key: 'conversation_count', label: 'Conversation Count', format: 'number' },
+ { key: 'last_conversation_time', label: 'Last Conversation', format: 'datetime' },
+ { key: 'created_time', label: 'Created', format: 'datetime' },
+];
+
+const deletedFields = ({ idKey, idLabel }: { idKey: string; idLabel: string }): OutputSchema => ({
+ fields: [
+ { key: idKey, label: idLabel },
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'already_deleted', label: 'Already Deleted', format: 'boolean', description: 'True when Retell answered 404.' },
+ ],
+});
+
+const rawCallFields: OutputSchemaField[] = [
+ { key: 'call_id', label: 'Call ID' },
+ { key: 'call_type', label: 'Call Type' },
+ { key: 'call_status', label: 'Call Status' },
+ { key: 'direction', label: 'Direction' },
+ { key: 'from_number', label: 'From Number' },
+ { key: 'to_number', label: 'To Number' },
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_version', label: 'Agent Version', format: 'number' },
+ { key: 'start_timestamp', label: 'Start Timestamp (ms)', format: 'number' },
+ { key: 'end_timestamp', label: 'End Timestamp (ms)', format: 'number' },
+ { key: 'duration_ms', label: 'Duration (ms)', format: 'number' },
+ { key: 'disconnection_reason', label: 'Disconnection Reason' },
+ { key: 'transcript', label: 'Transcript' },
+ { key: 'recording_url', label: 'Recording URL', format: 'url' },
+ { key: 'public_log_url', label: 'Public Log URL', format: 'url' },
+ { key: 'metadata', label: 'Metadata' },
+ { key: 'retell_llm_dynamic_variables', label: 'Dynamic Variables' },
+ {
+ key: 'call_analysis',
+ label: 'Call Analysis',
+ children: [
+ { key: 'call_summary', label: 'Call Summary' },
+ { key: 'user_sentiment', label: 'User Sentiment' },
+ { key: 'call_successful', label: 'Call Successful', format: 'boolean' },
+ { key: 'in_voicemail', label: 'In Voicemail', format: 'boolean' },
+ { key: 'custom_analysis_data', label: 'Custom Analysis Data' },
+ ],
+ },
+ {
+ key: 'call_cost',
+ label: 'Call Cost',
+ children: [
+ { key: 'combined_cost', label: 'Combined Cost (cents)', format: 'number' },
+ { key: 'total_duration_seconds', label: 'Billed Duration (s)', format: 'number' },
+ ],
+ },
+];
+
+const rawPhoneNumberFields: OutputSchemaField[] = [
+ { key: 'phone_number', label: 'Phone Number' },
+ { key: 'phone_number_pretty', label: 'Phone Number (Formatted)' },
+ { key: 'phone_number_type', label: 'Phone Number Type' },
+ { key: 'nickname', label: 'Nickname' },
+ { key: 'area_code', label: 'Area Code', format: 'number' },
+ { key: 'inbound_agents', label: 'Inbound Agents', labelKey: 'agent_id', listItems: agentWeightFields },
+ { key: 'outbound_agents', label: 'Outbound Agents', labelKey: 'agent_id', listItems: agentWeightFields },
+ { key: 'inbound_webhook_url', label: 'Inbound Webhook URL', format: 'url' },
+ { key: 'last_modification_timestamp', label: 'Last Modified Timestamp (ms)', format: 'number' },
+];
+
+const rawAgentFields: OutputSchemaField[] = [
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'agent_name', label: 'Agent Name' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'is_published', label: 'Is Published', format: 'boolean' },
+ { key: 'voice_id', label: 'Voice ID' },
+ { key: 'language', label: 'Language' },
+ { key: 'webhook_url', label: 'Webhook URL', format: 'url' },
+ {
+ key: 'response_engine',
+ label: 'Response Engine',
+ children: [
+ { key: 'type', label: 'Type' },
+ { key: 'llm_id', label: 'Retell LLM ID' },
+ { key: 'conversation_flow_id', label: 'Conversation Flow ID' },
+ { key: 'version', label: 'Version', format: 'number' },
+ ],
+ },
+ { key: 'last_modification_timestamp', label: 'Last Modified Timestamp (ms)', format: 'number' },
+];
+
+const webhookCallFields: OutputSchemaField[] = [
+ { key: 'event', label: 'Event', description: 'call_started, call_ended or call_analyzed.' },
+ { key: 'call', label: 'Call', children: rawCallFields },
+];
+
+export const retellSchemas = {
+ call: { fields: callFields } satisfies OutputSchema,
+ callPage: pageSchema({ label: 'Calls', labelKey: 'call_id', itemFields: callSummaryFields }),
+ webCall: {
+ fields: [
+ { key: 'call_id', label: 'Call ID' },
+ { key: 'access_token', label: 'Access Token', description: 'Pass to the Retell web client SDK within 30 seconds.' },
+ { key: 'expires_at', label: 'Token Expires At' },
+ ],
+ } satisfies OutputSchema,
+ chat: { fields: chatFields } satisfies OutputSchema,
+ chatPage: pageSchema({ label: 'Chats', labelKey: 'chat_id', itemFields: chatFields.filter((field) => field.key !== 'transcript') }),
+ chatCompletion: {
+ fields: [
+ { key: 'reply', label: 'Agent Reply', description: 'Agent messages from this turn joined by new lines.' },
+ { key: 'message_count', label: 'Message Count', format: 'number' },
+ {
+ key: 'messages',
+ label: 'Messages',
+ labelKey: 'role',
+ listItems: [
+ { key: 'message_id', label: 'Message ID' },
+ { key: 'role', label: 'Role', description: 'agent, user or a tool-call role.' },
+ { key: 'content', label: 'Content' },
+ { key: 'created_timestamp', label: 'Created Timestamp (ms)', format: 'number' },
+ ],
+ },
+ ],
+ } satisfies OutputSchema,
+ agent: { fields: agentFields } satisfies OutputSchema,
+ chatAgent: { fields: chatAgentFields } satisfies OutputSchema,
+ agentPage: pageSchema({ label: 'Agents', labelKey: 'agent_name', itemFields: agentListItemFields }),
+ agentVersionPage: pageSchema({ label: 'Versions', labelKey: 'version', itemFields: agentVersionFields }),
+ agentPublished: {
+ fields: [
+ { key: 'agent_id', label: 'Agent ID' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'published', label: 'Published', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ phoneNumber: { fields: phoneNumberFields } satisfies OutputSchema,
+ phoneNumberPage: pageSchema({ label: 'Phone Numbers', labelKey: 'phone_number', itemFields: phoneNumberFields }),
+ voice: { fields: voiceFields } satisfies OutputSchema,
+ voiceList: {
+ fields: [
+ { key: 'items', label: 'Voices', labelKey: 'voice_name', listItems: voiceFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ knowledgeBase: { fields: knowledgeBaseFields } satisfies OutputSchema,
+ knowledgeBaseList: {
+ fields: [
+ { key: 'items', label: 'Knowledge Bases', labelKey: 'knowledge_base_name', listItems: knowledgeBaseFields },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ llm: { fields: llmFields } satisfies OutputSchema,
+ llmPage: pageSchema({ label: 'Retell LLMs', labelKey: 'llm_id', itemFields: llmFields }),
+ contact: { fields: contactFields } satisfies OutputSchema,
+ contactLookup: {
+ fields: [{ key: 'found', label: 'Found', format: 'boolean' }, ...contactFields],
+ } satisfies OutputSchema,
+ contactPage: pageSchema({ label: 'Contacts', labelKey: 'phone_number', itemFields: contactFields }),
+ concurrency: {
+ fields: [
+ { key: 'current_concurrency', label: 'Current Concurrency', format: 'number' },
+ { key: 'concurrency_limit', label: 'Concurrency Limit', format: 'number' },
+ { key: 'available_concurrency', label: 'Available Concurrency', format: 'number' },
+ { key: 'base_concurrency', label: 'Base Concurrency', format: 'number' },
+ { key: 'purchased_concurrency', label: 'Purchased Concurrency', format: 'number' },
+ { key: 'reserved_inbound_concurrency', label: 'Reserved Inbound Concurrency', format: 'number' },
+ { key: 'concurrency_burst_enabled', label: 'Burst Enabled', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ batchCall: {
+ fields: [
+ { key: 'batch_call_id', label: 'Batch Call ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'from_number', label: 'From Number' },
+ { key: 'scheduled_timestamp', label: 'Scheduled Timestamp (ms)', format: 'number' },
+ { key: 'scheduled_time', label: 'Scheduled Time', format: 'datetime' },
+ { key: 'total_task_count', label: 'Total Calls', format: 'number' },
+ ],
+ } satisfies OutputSchema,
+ callStopped: {
+ fields: [
+ { key: 'call_id', label: 'Call ID' },
+ { key: 'stopped', label: 'Stopped', format: 'boolean' },
+ { key: 'reason', label: 'Reason', description: 'Why the call was not stopped, if it was not.' },
+ ],
+ } satisfies OutputSchema,
+ chatEnded: {
+ fields: [
+ { key: 'chat_id', label: 'Chat ID' },
+ { key: 'ended', label: 'Ended', format: 'boolean' },
+ ],
+ } satisfies OutputSchema,
+ deleted: deletedFields,
+ rawCall: { fields: rawCallFields } satisfies OutputSchema,
+ rawPhoneNumber: { fields: rawPhoneNumberFields } satisfies OutputSchema,
+ rawAgent: { fields: rawAgentFields } satisfies OutputSchema,
+ rawVoice: { fields: voiceFields } satisfies OutputSchema,
+ webhookCall: { fields: webhookCallFields } satisfies OutputSchema,
+};
diff --git a/packages/pieces/community/retell-ai/src/lib/common/webhook.ts b/packages/pieces/community/retell-ai/src/lib/common/webhook.ts
new file mode 100644
index 00000000000..0179ad6d973
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/common/webhook.ts
@@ -0,0 +1,116 @@
+import { createHmac, timingSafeEqual } from 'crypto';
+import { DEDUPE_KEY_PROPERTY, Property } from '@activepieces/pieces-framework';
+import { isRecord } from './client';
+
+export function verifyRetellSignature({
+ apiKey,
+ rawBody,
+ headers,
+ nowMs,
+}: {
+ apiKey: string;
+ rawBody: unknown;
+ headers: Record<string, string | undefined> | undefined;
+ nowMs: number;
+}): boolean {
+ const raw = typeof rawBody === 'string' ? rawBody : Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : undefined;
+ if (raw === undefined) {
+ return false;
+ }
+ const header = headerValue({ headers, name: 'x-retell-signature' });
+ if (header === undefined) {
+ return false;
+ }
+ const match = /^v=(\d+),d=([0-9a-fA-F]+)$/.exec(header.trim());
+ if (match === null) {
+ return false;
+ }
+ const timestamp = Number(match[1]);
+ if (nowMs - timestamp > REPLAY_WINDOW_MS || timestamp - nowMs > CLOCK_SKEW_MS) {
+ return false;
+ }
+ const expected = createHmac('sha256', apiKey.trim()).update(raw + match[1]).digest('hex');
+ const received = Buffer.from(match[2].toLowerCase(), 'utf8');
+ const digest = Buffer.from(expected, 'utf8');
+ return received.length === digest.length && timingSafeEqual(received, digest);
+}
+
+export async function handleRetellWebhook({
+ apiKey,
+ payload,
+ store,
+ event,
+ nowMs,
+}: {
+ apiKey: string;
+ payload: { body: unknown; rawBody?: unknown; headers: Record<string, string | undefined> };
+ store: { get<T>(key: string): Promise<T | null>; put<T>(key: string, value: T): Promise<T> };
+ event: RetellCallEvent;
+ nowMs: number;
+}): Promise<unknown[]> {
+ if (!verifyRetellSignature({ apiKey, rawBody: payload.rawBody, headers: payload.headers, nowMs })) {
+ return [];
+ }
+ const body = parseBody(payload.body);
+ if (body === undefined || body['event'] !== event || !isRecord(body['call'])) {
+ return [];
+ }
+ const callId = body['call']['call_id'];
+ if (typeof callId !== 'string' || callId.length === 0) {
+ return [];
+ }
+ const deliveryKey = `${event}:${callId}`;
+ const storeKey = `retell_${event}_deliveries`;
+ const seen = (await store.get<string[]>(storeKey)) ?? [];
+ if (seen.includes(deliveryKey)) {
+ return [];
+ }
+ await store.put(storeKey, [...seen, deliveryKey].slice(-MAX_REMEMBERED_DELIVERIES));
+ return [{ event, call: body['call'], [DEDUPE_KEY_PROPERTY]: deliveryKey }];
+}
+
+export function webhookInstructions(eventName: RetellCallEvent) {
+ return Property.MarkDown({
+ value: `Retell sends call events to one account-level webhook URL. To use this trigger:
+
+1. In the Retell AI dashboard, open **Settings > Webhooks**.
+2. Set the account webhook URL to:
+\`\`\`text
+{{webhookUrl}}
+\`\`\`
+3. Save. Retell sends **call_started**, **call_ended** and **call_analyzed** to that URL; this trigger only reacts to **${eventName}**.
+4. The connection must use the API key with the **webhook** badge (Settings > API Keys). Deliveries whose X-Retell-Signature does not match that key are ignored.
+
+An agent with its own webhook URL sends its events there instead of to the account URL. Nothing is registered or removed automatically when this flow is turned on or off.`,
+ });
+}
+
+function headerValue({ headers, name }: { headers: Record<string, string | undefined> | undefined; name: string }): string | undefined {
+ if (headers === undefined) {
+ return undefined;
+ }
+ const match = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
+ const value = match?.[1];
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+function parseBody(body: unknown): Record<string, unknown> | undefined {
+ if (isRecord(body)) {
+ return body;
+ }
+ if (typeof body === 'string' || Buffer.isBuffer(body)) {
+ try {
+ const parsed: unknown = JSON.parse(body.toString());
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ return undefined;
+}
+
+const MAX_REMEMBERED_DELIVERIES = 500;
+const REPLAY_WINDOW_MS = 15 * 60 * 1000;
+const CLOCK_SKEW_MS = 5 * 60 * 1000;
+
+export type RetellCallEvent = 'call_started' | 'call_ended' | 'call_analyzed';
diff --git a/packages/pieces/community/retell-ai/src/lib/triggers/call-analyzed.ts b/packages/pieces/community/retell-ai/src/lib/triggers/call-analyzed.ts
new file mode 100644
index 00000000000..7f98ecae003
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/triggers/call-analyzed.ts
@@ -0,0 +1,39 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { retellAiAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { SAMPLE_CALL_ANALYZED } from '../common/sample';
+import { retellSchemas } from '../common/schemas';
+import { handleRetellWebhook, webhookInstructions } from '../common/webhook';
+
+export const callAnalyzedTrigger = createTrigger({
+ auth: retellAiAuth,
+ name: 'call_analyzed',
+ classification: 'READ',
+ displayName: 'Call Analyzed',
+ description: 'Triggers when post-call analysis is ready (call_analyzed event).',
+ aiMetadata: {
+ description:
+ 'Fires once per Retell call when post-call analysis finishes (call_analyzed webhook event). Payload is {event, call} with the full call, including transcript, call_analysis (summary, sentiment, success, custom extraction fields) and cost; the best trigger for CRM updates. Requires the account webhook URL set manually in Retell and a connection key with the webhook badge.',
+ },
+ props: {
+ webhookInstructions: webhookInstructions('call_analyzed'),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: SAMPLE_CALL_ANALYZED,
+ outputSchema: retellSchemas.webhookCall,
+ async onEnable() {
+ return;
+ },
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ return handleRetellWebhook({
+ apiKey: apiKeyOf(context.auth),
+ payload: context.payload,
+ store: context.store,
+ event: 'call_analyzed',
+ nowMs: Date.now(),
+ });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/triggers/call-ended.ts b/packages/pieces/community/retell-ai/src/lib/triggers/call-ended.ts
new file mode 100644
index 00000000000..bbaab2abe2f
--- /dev/null
+++ b/packages/pieces/community/retell-ai/src/lib/triggers/call-ended.ts
@@ -0,0 +1,39 @@
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
+import { retellAiAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { SAMPLE_CALL_ENDED } from '../common/sample';
+import { retellSchemas } from '../common/schemas';
+import { handleRetellWebhook, webhookInstructions } from '../common/webhook';
+
+export const callEndedTrigger = createTrigger({
+ auth: retellAiAuth,
+ name: 'call_ended',
+ classification: 'READ',
+ displayName: 'Call Ended',
+ description: 'Triggers when a call ends (call_ended event), with transcript and recording.',
+ aiMetadata: {
+ description:
+ 'Fires once per Retell call when it ends, is transferred or fails to connect (call_ended webhook event). Payload is {event, call} with status, timestamps, duration, disconnection reason, transcript and recording URL; post-call analysis is not included yet (use Call Analyzed for it). Requires the account webhook URL set manually in Retell and a connection key with the webhook badge.',
+ },
+ props: {
+ webhookInstructions: webhookInstructions('call_ended'),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: SAMPLE_CALL_ENDED,
+ outputSchema: retellSchemas.webhookCall,
+ async onEnable() {
+ return;
+ },
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ return handleRetellWebhook({
+ apiKey: apiKeyOf(context.auth),
+ payload: context.payload,
+ store: context.store,
+ event: 'call_ended',
+ nowMs: Date.now(),
+ });
+ },
+});
diff --git a/packages/pieces/community/retell-ai/src/lib/triggers/new-call.ts b/packages/pieces/community/retell-ai/src/lib/triggers/new-call.ts
index 9e6ef8863dd..c12985e1755 100644
--- a/packages/pieces/community/retell-ai/src/lib/triggers/new-call.ts
+++ b/packages/pieces/community/retell-ai/src/lib/triggers/new-call.ts
@@ -1,60 +1,39 @@
-import {
- createTrigger,
- Property,
- TriggerStrategy,
-} from '@activepieces/pieces-framework';
-
+import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
import { retellAiAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { SAMPLE_CALL_STARTED } from '../common/sample';
+import { retellSchemas } from '../common/schemas';
+import { handleRetellWebhook, webhookInstructions } from '../common/webhook';
export const newCallTrigger = createTrigger({
+ auth: retellAiAuth,
name: 'new_call',
classification: 'READ',
displayName: 'New Call',
- description: 'Triggers when a new outgoing or incoming call is created.',
+ description: 'Triggers when an inbound or outbound call starts (call_started event).',
aiMetadata: {
- description: 'Fires when a new call is created in Retell, for either inbound or outbound direction, via the call.created webhook event. Each event represents a freshly initiated call with its call ID, numbers, direction, agent, and metadata. Requires a manually configured webhook in the Retell dashboard.',
+ description:
+ 'Fires once per Retell call when it starts (call_started webhook event), inbound or outbound. Payload is {event, call} with the call ID, numbers, direction, agent and metadata; no transcript yet. Requires the account webhook URL set manually in Retell and a connection key with the webhook badge.',
},
- auth: retellAiAuth,
props: {
- webhookInstructions: Property.MarkDown({
- value: `
- To use this trigger, you need to manually set up a webhook in your Retell AI account:
-
- 1. Login to your Retell AI dashboard.
- 2. Navigate to the Webhooks section in your settings.
- 3. Click on "Add Webhook" or "Create New Webhook".
- 4. Add the following URL in the **Webhook URL** field:
- \`\`\`text
- {{webhookUrl}}
- \`\`\`
- 5. Select the **call.created** event type.
- 6. Click Save to create the webhook.
- `,
- }),
+ webhookInstructions: webhookInstructions('call_started'),
},
type: TriggerStrategy.WEBHOOK,
- sampleData: {
- call_id: "119c3f8e47135a29e65947eeb34cf12d",
- status: "initiated",
- from_number: "+15551234567",
- to_number: "+15557654321",
- direction: "outbound",
- agent_id: "ag_01h9pc3e7jnb2rvnj5jkxgf5d4",
- created_at: "2023-09-15T14:30:00.000Z",
- metadata: {
- custom_field: "value"
- }
+ sampleData: SAMPLE_CALL_STARTED,
+ outputSchema: retellSchemas.webhookCall,
+ async onEnable() {
+ return;
},
-
- async onEnable(context) {
- // No need to register webhooks programmatically as user will do it manually
- },
-
- async onDisable(context) {
- // No need to unregister webhooks as user will do it manually
+ async onDisable() {
+ return;
},
-
async run(context) {
- return [context.payload.body];
+ return handleRetellWebhook({
+ apiKey: apiKeyOf(context.auth),
+ payload: context.payload,
+ store: context.store,
+ event: 'call_started',
+ nowMs: Date.now(),
+ });
},
-});
\ No newline at end of file
+});
diff --git a/packages/pieces/community/retell-ai/test/actions.test.ts b/packages/pieces/community/retell-ai/test/actions.test.ts
new file mode 100644
index 00000000000..83b00b90e7d
--- /dev/null
+++ b/packages/pieces/community/retell-ai/test/actions.test.ts
@@ -0,0 +1,614 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { retellAi } from '../src';
+import { createBatchCallAction } from '../src/lib/actions/create-batch-call';
+import { createPhoneNumber } from '../src/lib/actions/create-phone-number';
+import { getAgent } from '../src/lib/actions/get-agent';
+import { getCall } from '../src/lib/actions/get-call';
+import { getPhoneNumber } from '../src/lib/actions/get-phone-number';
+import { getVoice } from '../src/lib/actions/get-voice';
+import { makePhoneCall } from '../src/lib/actions/make-phone-call';
+import { addKnowledgeBaseSourcesAction } from '../src/lib/actions/ai/add-knowledge-base-sources';
+import { buyPhoneNumberAction } from '../src/lib/actions/ai/buy-phone-number';
+import { createChatAction } from '../src/lib/actions/ai/create-chat';
+import { createContactAction } from '../src/lib/actions/ai/create-contact';
+import { createKnowledgeBaseAction } from '../src/lib/actions/ai/create-knowledge-base';
+import { createPhoneCallAction } from '../src/lib/actions/ai/create-phone-call';
+import { createSmsChatAction } from '../src/lib/actions/ai/create-sms-chat';
+import { createWebCallAction } from '../src/lib/actions/ai/create-web-call';
+import { deleteAgentAction } from '../src/lib/actions/ai/delete-agent';
+import { deleteCallAction } from '../src/lib/actions/ai/delete-call';
+import { deleteKnowledgeBaseAction } from '../src/lib/actions/ai/delete-knowledge-base';
+import { deleteKnowledgeBaseSourceAction } from '../src/lib/actions/ai/delete-knowledge-base-source';
+import { deletePhoneNumberAction } from '../src/lib/actions/ai/delete-phone-number';
+import { endChatAction } from '../src/lib/actions/ai/end-chat';
+import { getAgentByIdAction } from '../src/lib/actions/ai/get-agent-by-id';
+import { getCallByIdAction } from '../src/lib/actions/ai/get-call-by-id';
+import { getChatAction } from '../src/lib/actions/ai/get-chat';
+import { getChatAgentAction } from '../src/lib/actions/ai/get-chat-agent';
+import { getConcurrencyAction } from '../src/lib/actions/ai/get-concurrency';
+import { getContactByPhoneAction } from '../src/lib/actions/ai/get-contact-by-phone';
+import { getKnowledgeBaseAction } from '../src/lib/actions/ai/get-knowledge-base';
+import { getRetellLlmAction } from '../src/lib/actions/ai/get-retell-llm';
+import { getVoiceByIdAction } from '../src/lib/actions/ai/get-voice-by-id';
+import { listAgentVersionsAction } from '../src/lib/actions/ai/list-agent-versions';
+import { listAgentsAction } from '../src/lib/actions/ai/list-agents';
+import { listCallsAction } from '../src/lib/actions/ai/list-calls';
+import { listChatAgentsAction } from '../src/lib/actions/ai/list-chat-agents';
+import { listChatsAction } from '../src/lib/actions/ai/list-chats';
+import { listContactsAction } from '../src/lib/actions/ai/list-contacts';
+import { listKnowledgeBasesAction } from '../src/lib/actions/ai/list-knowledge-bases';
+import { listPhoneNumbersAction } from '../src/lib/actions/ai/list-phone-numbers';
+import { listRetellLlmsAction } from '../src/lib/actions/ai/list-retell-llms';
+import { listVoicesAction } from '../src/lib/actions/ai/list-voices';
+import { publishAgentAction } from '../src/lib/actions/ai/publish-agent';
+import { sendChatMessageAction } from '../src/lib/actions/ai/send-chat-message';
+import { stopCallAction } from '../src/lib/actions/ai/stop-call';
+import { updateAgentAction } from '../src/lib/actions/ai/update-agent';
+import { updateCallMetadataAction } from '../src/lib/actions/ai/update-call-metadata';
+import { updateContactAction } from '../src/lib/actions/ai/update-contact';
+import { updatePhoneNumberAgentsAction } from '../src/lib/actions/ai/update-phone-number-agents';
+import { updateRetellLlmPromptAction } from '../src/lib/actions/ai/update-retell-llm-prompt';
+import { AGENT, CALL, CHAT, CONTACT, KB, LLM, PHONE, VOICE } from './fixtures';
+import { API_KEY, BASE, invoke, makeContext, stubFetch, toRecord } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+type RunnableAction = {
+ name: string;
+ outputSchema?: { fields: { key: string }[] };
+ run: (...args: never[]) => Promise<unknown>;
+};
+
+function runAction({ action, props }: { action: RunnableAction; props: Record<string, unknown> }) {
+ return invoke({ fn: action.run, self: action, args: [makeContext({ props })] });
+}
+
+const PAGE = (items: unknown[]) => ({ items, pagination_key: 'next_1', has_more: true });
+
+const cases: {
+ action: RunnableAction;
+ props: Record<string, unknown>;
+ response?: unknown;
+ status?: number;
+ method: string;
+ path: string;
+ query?: Record<string, string>;
+ body?: unknown;
+ check?: (output: Record<string, unknown>) => void;
+ raw?: boolean;
+}[] = [
+ {
+ action: makePhoneCall,
+ props: { fromNumber: '+14155550100', toNumber: '+14155550101', overrideAgentId: 'agent_1', overrideAgentVersion: 2, dynamicVariables: { n: 5, ok: true, name: 'Ann' } },
+ response: CALL,
+ status: 201,
+ method: 'POST',
+ path: '/v2/create-phone-call',
+ body: {
+ from_number: '+14155550100',
+ to_number: '+14155550101',
+ override_agent_id: 'agent_1',
+ override_agent_version: 2,
+ retell_llm_dynamic_variables: { n: '5', ok: 'true', name: 'Ann' },
+ },
+ raw: true,
+ },
+ {
+ action: createPhoneNumber,
+ props: { nickname: 'Main', areaCode: 415, inboundAgentId: 'agent_1', inboundAgentVersion: 2, tollFree: false, countryCode: 'US', numberProvider: 'twilio' },
+ response: PHONE,
+ status: 201,
+ method: 'POST',
+ path: '/create-phone-number',
+ body: {
+ nickname: 'Main',
+ area_code: 415,
+ inbound_agents: [{ agent_id: 'agent_1', agent_version: 2, weight: 1 }],
+ toll_free: false,
+ country_code: 'US',
+ number_provider: 'twilio',
+ },
+ raw: true,
+ },
+ { action: getCall, props: { callId: 'call_1' }, response: CALL, method: 'GET', path: '/v2/get-call/call_1', raw: true },
+ { action: getPhoneNumber, props: { phoneNumber: '+14155550100' }, response: PHONE, method: 'GET', path: '/get-phone-number/%2B14155550100', raw: true },
+ { action: getVoice, props: { voiceId: '11labs-Adrian' }, response: VOICE, method: 'GET', path: '/get-voice/11labs-Adrian', raw: true },
+ { action: getAgent, props: { agentId: 'agent_1', version: 3 }, response: AGENT, method: 'GET', path: '/get-agent/agent_1', query: { version: '3' }, raw: true },
+ {
+ action: createBatchCallAction,
+ props: {
+ from_number: '+14155550100',
+ name: 'Promo',
+ agent_id: 'agent_1',
+ scheduled_time: '2026-10-14T10:00:00Z',
+ tasks: [{ to_number: '+14155550101', dynamic_variables: '{"name":"Ann","age":30}' }, { to_number: '+14155550102' }],
+ },
+ response: { batch_call_id: 'batch_1', name: 'Promo', from_number: '+14155550100', scheduled_timestamp: 1791972000000, total_task_count: 2 },
+ status: 201,
+ method: 'POST',
+ path: '/create-batch-call',
+ body: {
+ from_number: '+14155550100',
+ name: 'Promo',
+ trigger_timestamp: Date.parse('2026-10-14T10:00:00Z'),
+ tasks: [
+ { to_number: '+14155550101', retell_llm_dynamic_variables: { name: 'Ann', age: '30' }, override_agent_id: 'agent_1' },
+ { to_number: '+14155550102', override_agent_id: 'agent_1' },
+ ],
+ },
+ check: (out) => expect(out['total_task_count']).toBe(2),
+ },
+ {
+ action: createPhoneCallAction,
+ props: { from_number: '+14155550100', to_number: '+14155550101', agent_version: 'prod', metadata: { a: 1 } },
+ response: { ...CALL, call_status: 'registered' },
+ status: 201,
+ method: 'POST',
+ path: '/v2/create-phone-call',
+ body: { from_number: '+14155550100', to_number: '+14155550101', override_agent_version: 'prod', metadata: { a: 1 } },
+ check: (out) => {
+ expect(out['call_id']).toBe('call_1');
+ expect(out['call_status']).toBe('registered');
+ },
+ },
+ {
+ action: createWebCallAction,
+ props: { agent_id: 'agent_1', agent_version: '4' },
+ response: { call_id: 'call_w', access_token: 'tok', expires_at: '2026-10-13T10:00:30Z' },
+ status: 201,
+ method: 'POST',
+ path: '/v3/create-web-call',
+ body: { agent_id: 'agent_1', agent_version: 4 },
+ check: (out) => expect(out['access_token']).toBe('tok'),
+ },
+ {
+ action: getCallByIdAction,
+ props: { call_id: 'call_1' },
+ response: CALL,
+ method: 'GET',
+ path: '/v2/get-call/call_1',
+ check: (out) => {
+ expect(out['call_summary']).toBe('Confirmed.');
+ expect(out['combined_cost_cents']).toBe(7.1);
+ expect(out['start_time']).toBe(new Date(1703302407333).toISOString());
+ expect(out['twilio_call_sid']).toBe('CA1');
+ },
+ },
+ {
+ action: listCallsAction,
+ props: { agent_id: 'agent_1', call_status: 'ended,error', direction: 'inbound', from_number: '+14155550100', started_after: '1700000000', started_before: '2026-01-01T00:00:00Z', limit: 10, pagination_key: 'pk' },
+ response: PAGE([CALL]),
+ method: 'POST',
+ path: '/v3/list-calls',
+ body: {
+ sort_order: 'descending',
+ limit: 10,
+ pagination_key: 'pk',
+ filter_criteria: {
+ agent: [{ agent_id: 'agent_1' }],
+ call_status: { type: 'enum', op: 'in', value: ['ended', 'error'] },
+ direction: { type: 'enum', op: 'in', value: ['inbound'] },
+ from_number: { type: 'string', op: 'eq', value: '+14155550100' },
+ start_timestamp: { type: 'range', op: 'bt', value: [1700000000000, Date.parse('2026-01-01T00:00:00Z')] },
+ },
+ },
+ check: (out) => {
+ expect(out['count']).toBe(1);
+ expect(out['pagination_key']).toBe('next_1');
+ expect(out['has_more']).toBe(true);
+ },
+ },
+ {
+ action: updateCallMetadataAction,
+ props: { call_id: 'call_1', metadata: '{"crm":"9"}', data_storage_setting: 'everything' },
+ response: CALL,
+ method: 'PATCH',
+ path: '/v2/update-call/call_1',
+ body: { metadata: { crm: '9' }, data_storage_setting: 'everything' },
+ },
+ {
+ action: stopCallAction,
+ props: { call_id: 'call_1' },
+ status: 204,
+ method: 'POST',
+ path: '/v2/stop-call/call_1',
+ check: (out) => expect(out).toEqual({ call_id: 'call_1', stopped: true, reason: null }),
+ },
+ {
+ action: deleteCallAction,
+ props: { call_id: 'call_1' },
+ status: 204,
+ method: 'DELETE',
+ path: '/v2/delete-call/call_1',
+ check: (out) => expect(out).toEqual({ call_id: 'call_1', deleted: true, already_deleted: false }),
+ },
+ {
+ action: listAgentsAction,
+ props: { channel: 'voice', search: 'Set', limit: 5 },
+ response: PAGE([{ agent_id: 'agent_1', agent_name: 'Setter', channel: 'voice', user_modified_timestamp: 1703413636133, tags: {} }]),
+ method: 'POST',
+ path: '/v2/list-agents',
+ query: { limit: '5' },
+ body: { filter_criteria: { channel: { type: 'string', op: 'eq', value: 'voice' }, query: 'Set' } },
+ check: (out) => expect(out['items']).toEqual([
+ { agent_id: 'agent_1', agent_name: 'Setter', channel: 'voice', version: null, is_published: null, last_modified_time: new Date(1703413636133).toISOString() },
+ ]),
+ },
+ {
+ action: listChatAgentsAction,
+ props: { pagination_key: 'pk' },
+ response: PAGE([]),
+ method: 'POST',
+ path: '/v2/list-agents',
+ query: { limit: '50', pagination_key: 'pk' },
+ body: { filter_criteria: { channel: { type: 'string', op: 'eq', value: 'chat' } } },
+ },
+ {
+ action: getAgentByIdAction,
+ props: { agent_id: 'agent_1' },
+ response: AGENT,
+ method: 'GET',
+ path: '/get-agent/agent_1',
+ check: (out) => {
+ expect(out['llm_id']).toBe('llm_1');
+ expect(out['response_engine_type']).toBe('retell-llm');
+ },
+ },
+ { action: getChatAgentAction, props: { agent_id: 'agent_c', version: 1 }, response: AGENT, method: 'GET', path: '/get-chat-agent/agent_c', query: { version: '1' } },
+ {
+ action: listAgentVersionsAction,
+ props: { agent_id: 'agent_1' },
+ response: PAGE([{ version: 2, is_published: true, version_title: 'v2', base_version: 1, last_modification_timestamp: 1 }]),
+ method: 'GET',
+ path: '/list-agent-versions/agent_1',
+ query: { limit: '50', sort_order: 'descending' },
+ },
+ {
+ action: updateAgentAction,
+ props: { agent_id: 'agent_1', agent_name: 'New', clear_webhook_url: true },
+ response: AGENT,
+ method: 'PATCH',
+ path: '/update-agent/agent_1',
+ body: { agent_name: 'New', webhook_url: null },
+ },
+ {
+ action: publishAgentAction,
+ props: { agent_id: 'agent_1', version: 3, version_title: 'Release' },
+ status: 200,
+ method: 'POST',
+ path: '/publish-agent-version/agent_1',
+ body: { version: 3, version_title: 'Release' },
+ check: (out) => expect(out).toEqual({ agent_id: 'agent_1', version: 3, published: true }),
+ },
+ {
+ action: deleteAgentAction,
+ props: { agent_id: 'agent_1' },
+ status: 204,
+ method: 'DELETE',
+ path: '/delete-agent/agent_1',
+ check: (out) => expect(out['deleted']).toBe(true),
+ },
+ {
+ action: createChatAction,
+ props: { agent_id: 'agent_c', dynamic_variables: { a: 1 } },
+ response: CHAT,
+ status: 201,
+ method: 'POST',
+ path: '/create-chat',
+ body: { agent_id: 'agent_c', retell_llm_dynamic_variables: { a: '1' } },
+ check: (out) => expect(out['chat_id']).toBe('chat_1'),
+ },
+ {
+ action: sendChatMessageAction,
+ props: { chat_id: 'chat_1', content: 'Hello' },
+ response: {
+ messages: [
+ { message_id: 'm1', role: 'agent', content: 'Hi there', created_timestamp: 1 },
+ { message_id: 'm2', role: 'agent', content: 'How can I help?', created_timestamp: 2 },
+ ],
+ },
+ status: 201,
+ method: 'POST',
+ path: '/create-chat-completion',
+ body: { chat_id: 'chat_1', content: 'Hello' },
+ check: (out) => {
+ expect(out['reply']).toBe('Hi there\nHow can I help?');
+ expect(out['message_count']).toBe(2);
+ },
+ },
+ {
+ action: createSmsChatAction,
+ props: { from_number: '+14155550100', to_number: '+14155550101', agent_id: 'agent_c' },
+ response: { ...CHAT, chat_type: 'sms_chat' },
+ method: 'POST',
+ path: '/create-sms-chat',
+ body: { from_number: '+14155550100', to_number: '+14155550101', override_agent_id: 'agent_c' },
+ },
+ {
+ action: getChatAction,
+ props: { chat_id: 'chat_1' },
+ response: CHAT,
+ method: 'GET',
+ path: '/get-chat/chat_1',
+ check: (out) => expect(out['chat_summary']).toBe('s'),
+ },
+ {
+ action: listChatsAction,
+ props: { chat_status: 'ended', chat_type: 'sms_chat' },
+ response: PAGE([CHAT]),
+ method: 'POST',
+ path: '/v3/list-chats',
+ body: {
+ sort_order: 'descending',
+ limit: 50,
+ filter_criteria: { chat_status: { type: 'enum', op: 'in', value: ['ended'] }, chat_type: { type: 'enum', op: 'in', value: ['sms_chat'] } },
+ },
+ check: (out) => expect(JSON.stringify(out['items'])).not.toContain('"transcript"'),
+ },
+ {
+ action: endChatAction,
+ props: { chat_id: 'chat_1' },
+ status: 204,
+ method: 'PATCH',
+ path: '/end-chat/chat_1',
+ check: (out) => expect(out).toEqual({ chat_id: 'chat_1', ended: true }),
+ },
+ {
+ action: listPhoneNumbersAction,
+ props: { limit: 1000 },
+ response: PAGE([PHONE]),
+ method: 'GET',
+ path: '/v2/list-phone-numbers',
+ query: { limit: '1000' },
+ check: (out) => {
+ const items = out['items'];
+ expect(Array.isArray(items) && items[0]).toMatchObject({ inbound_agent_id: 'agent_1', outbound_agent_id: 'agent_2' });
+ },
+ },
+ {
+ action: buyPhoneNumberAction,
+ props: { phone_number: '+14155550199', outbound_agent_id: 'agent_2', toll_free: true },
+ response: PHONE,
+ status: 201,
+ method: 'POST',
+ path: '/create-phone-number',
+ body: { phone_number: '+14155550199', outbound_agents: [{ agent_id: 'agent_2', weight: 1 }], toll_free: true },
+ },
+ {
+ action: updatePhoneNumberAgentsAction,
+ props: { phone_number: '+14155550100', inbound_agent_id: 'agent_1', inbound_agent_version: 'prod', nickname: 'Sales' },
+ response: PHONE,
+ method: 'PATCH',
+ path: '/update-phone-number/%2B14155550100',
+ body: { inbound_agents: [{ agent_id: 'agent_1', agent_version: 'prod', weight: 1 }], nickname: 'Sales' },
+ },
+ {
+ action: deletePhoneNumberAction,
+ props: { phone_number: '+14155550100' },
+ status: 204,
+ method: 'DELETE',
+ path: '/delete-phone-number/%2B14155550100',
+ check: (out) => expect(out['deleted']).toBe(true),
+ },
+ {
+ action: listVoicesAction,
+ props: { provider: 'ElevenLabs', gender: 'male', search: 'adr' },
+ response: [VOICE, { ...VOICE, voice_id: 'openai-Nova', voice_name: 'Nova', provider: 'openai', gender: 'female' }],
+ method: 'GET',
+ path: '/list-voices',
+ check: (out) => expect(out['count']).toBe(1),
+ },
+ { action: getVoiceByIdAction, props: { voice_id: '11labs-Adrian' }, response: VOICE, method: 'GET', path: '/get-voice/11labs-Adrian' },
+ {
+ action: listKnowledgeBasesAction,
+ props: { search: 'doc' },
+ response: [KB, { ...KB, knowledge_base_id: 'kb_2', knowledge_base_name: 'Other' }],
+ method: 'GET',
+ path: '/list-knowledge-bases',
+ check: (out) => expect(out['count']).toBe(1),
+ },
+ {
+ action: getKnowledgeBaseAction,
+ props: { knowledge_base_id: 'knowledge_base_1' },
+ response: KB,
+ method: 'GET',
+ path: '/get-knowledge-base/knowledge_base_1',
+ check: (out) => {
+ expect(out['source_count']).toBe(2);
+ expect(out['sources']).toEqual([
+ { source_id: 'src_1', type: 'url', title: null, url: 'https://example.com' },
+ { source_id: 'src_2', type: 'text', title: 'FAQ', url: 'https://example.com/faq' },
+ ]);
+ },
+ },
+ {
+ action: deleteKnowledgeBaseSourceAction,
+ props: { knowledge_base_id: 'knowledge_base_1', source_id: 'src_1' },
+ response: KB,
+ method: 'DELETE',
+ path: '/delete-knowledge-base-source/knowledge_base_1/source/src_1',
+ },
+ {
+ action: deleteKnowledgeBaseAction,
+ props: { knowledge_base_id: 'knowledge_base_1' },
+ status: 204,
+ method: 'DELETE',
+ path: '/delete-knowledge-base/knowledge_base_1',
+ check: (out) => expect(out['deleted']).toBe(true),
+ },
+ {
+ action: listRetellLlmsAction,
+ props: {},
+ response: PAGE([LLM]),
+ method: 'GET',
+ path: '/v2/list-retell-llms',
+ query: { limit: '50' },
+ check: (out) => {
+ const items = out['items'];
+ expect(Array.isArray(items) && items[0]).toMatchObject({ knowledge_base_ids: 'kb_1, kb_2' });
+ },
+ },
+ { action: getRetellLlmAction, props: { llm_id: 'llm_1' }, response: LLM, method: 'GET', path: '/get-retell-llm/llm_1' },
+ {
+ action: updateRetellLlmPromptAction,
+ props: { llm_id: 'llm_1', general_prompt: 'Be brief.', model: 'gpt-4.1' },
+ response: LLM,
+ method: 'PATCH',
+ path: '/update-retell-llm/llm_1',
+ body: { general_prompt: 'Be brief.', model: 'gpt-4.1' },
+ },
+ {
+ action: createContactAction,
+ props: { phone_number: '+14155550101', first_name: 'Ann', do_not_call: false, custom_fields: { plan: 'pro' } },
+ response: CONTACT,
+ status: 201,
+ method: 'POST',
+ path: '/create-contact',
+ body: { phone_number: '+14155550101', first_name: 'Ann', do_not_call: false, custom_fields: { plan: 'pro' } },
+ check: (out) => expect(out['tags']).toBe('vip'),
+ },
+ {
+ action: getContactByPhoneAction,
+ props: { phone_number: '+14155550101' },
+ response: CONTACT,
+ method: 'GET',
+ path: '/get-contact-by-phone/%2B14155550101',
+ check: (out) => expect(out['found']).toBe(true),
+ },
+ {
+ action: updateContactAction,
+ props: { contact_id: 'contact_1', do_not_call: 'true', contact_memory: 'Prefers mornings' },
+ response: CONTACT,
+ method: 'PATCH',
+ path: '/update-contact/contact_1',
+ body: { do_not_call: true, contact_memory: 'Prefers mornings' },
+ },
+ {
+ action: listContactsAction,
+ props: { search: 'Ann', limit: 20 },
+ response: { ...PAGE([CONTACT]), total: 1 },
+ method: 'POST',
+ path: '/list-contacts',
+ body: { limit: 20, sort_order: 'desc', search_query: 'Ann' },
+ check: (out) => expect(out['total']).toBe(1),
+ },
+ {
+ action: getConcurrencyAction,
+ props: {},
+ response: { current_concurrency: 3, concurrency_limit: 20, base_concurrency: 20 },
+ method: 'GET',
+ path: '/get-concurrency',
+ check: (out) => expect(out['available_concurrency']).toBe(17),
+ },
+];
+
+describe('every action sends the documented request', () => {
+ it.each(cases.map((c) => [c.action.name, c] as const))('%s', async (_name, c) => {
+ const calls = stubFetch([{ status: c.status ?? 200, body: c.response }]);
+ const output = await runAction({ action: c.action, props: c.props });
+ expect(calls).toHaveLength(1);
+ const call = calls[0];
+ expect(call.method).toBe(c.method);
+ expect(`${call.url.origin}${call.url.pathname}`).toBe(`${BASE}${c.path}`);
+ expect(Object.fromEntries(call.url.searchParams.entries())).toEqual(c.query ?? {});
+ expect(call.headers['authorization']).toBe(`Bearer ${API_KEY}`);
+ if (c.body !== undefined) {
+ expect(call.body).toEqual(c.body);
+ }
+ if (c.raw === true) {
+ expect(output).toEqual(c.response);
+ } else if (c.action.outputSchema !== undefined) {
+ const record = toRecord(output);
+ for (const field of c.action.outputSchema.fields) {
+ expect(Object.keys(record)).toContain(field.key);
+ }
+ }
+ if (c.check !== undefined) {
+ c.check(toRecord(output));
+ }
+ });
+
+ it('covers every hand-written action of the piece', () => {
+ const tested = new Set([...cases.map((c) => c.action.name), createKnowledgeBaseAction.name, addKnowledgeBaseSourcesAction.name]);
+ const all = Object.keys(retellAi.actions()).filter((name) => name !== 'custom_api_call');
+ expect(all.filter((name) => !tested.has(name))).toEqual([]);
+ });
+});
+
+describe('knowledge base multipart actions', () => {
+ it('create_knowledge_base sends multipart form with texts, urls and file', async () => {
+ const calls = stubFetch([{ status: 201, body: KB }]);
+ const output = await runAction({
+ action: createKnowledgeBaseAction,
+ props: {
+ name: 'Docs',
+ texts: [{ title: 'FAQ', text: 'Open 9-5' }],
+ urls: ['https://example.com'],
+ file: { filename: 'a"b.txt', extension: 'txt', data: Buffer.from('file body') },
+ },
+ });
+ expect(calls[0].url.pathname).toBe('/create-knowledge-base');
+ expect(calls[0].headers['content-type']).toMatch(/^multipart\/form-data; boundary=----RetellAiBoundary[0-9a-f]+$/);
+ const raw = calls[0].rawBody ?? '';
+ expect(raw).toContain('name="knowledge_base_name"\r\n\r\nDocs\r\n');
+ expect(raw).toContain('name="knowledge_base_texts"\r\n\r\n[{"title":"FAQ","text":"Open 9-5"}]\r\n');
+ expect(raw).toContain('name="knowledge_base_urls"\r\n\r\n["https://example.com"]\r\n');
+ expect(raw).toContain('name="knowledge_base_files"; filename="a_b.txt"');
+ expect(raw).toContain('file body');
+ expect(toRecord(output)['knowledge_base_id']).toBe('knowledge_base_1');
+ });
+
+ it('add_knowledge_base_sources needs at least one source and rejects non-http URLs', async () => {
+ const calls = stubFetch([]);
+ await expect(runAction({ action: addKnowledgeBaseSourcesAction, props: { knowledge_base_id: 'kb' } })).rejects.toThrow(
+ 'Add at least one text, URL or file.',
+ );
+ await expect(
+ runAction({ action: addKnowledgeBaseSourcesAction, props: { knowledge_base_id: 'kb', urls: ['file:///etc/passwd'] } }),
+ ).rejects.toThrow('must start with http');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('add_knowledge_base_sources posts to the encoded knowledge base path', async () => {
+ const calls = stubFetch([{ status: 201, body: KB }]);
+ await runAction({ action: addKnowledgeBaseSourcesAction, props: { knowledge_base_id: 'kb 1', urls: ['https://a.example'] } });
+ expect(calls[0].url.pathname).toBe('/add-knowledge-base-sources/kb%201');
+ });
+
+ it('create_knowledge_base rejects names of 40+ characters', async () => {
+ stubFetch([]);
+ await expect(runAction({ action: createKnowledgeBaseAction, props: { name: 'x'.repeat(40) } })).rejects.toThrow('shorter than 40');
+ });
+});
+
+describe('piece metadata', () => {
+ it('every action declares audience, classification, aiMetadata and outputSchema', () => {
+ const actions = Object.values(retellAi.actions()).filter((action) => action.name !== 'custom_api_call');
+ for (const action of actions) {
+ expect(['human', 'ai', 'both']).toContain(action.audience);
+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);
+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(20);
+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');
+ expect(action.outputSchema?.fields.length ?? 0).toBeGreaterThan(0);
+ }
+ });
+
+ it('counts by audience match the plan', () => {
+ const actions = Object.values(retellAi.actions()).filter((action) => action.name !== 'custom_api_call');
+ const count = (audience: string) => actions.filter((action) => action.audience === audience).length;
+ expect({ human: count('human'), both: count('both'), ai: count('ai') }).toEqual({ human: 5, both: 2, ai: 41 });
+ });
+
+ it('triggers are READ with aiMetadata, sample data and output schema', () => {
+ const triggers = Object.values(retellAi.triggers());
+ expect(triggers.map((trigger) => trigger.name).sort()).toEqual(['call_analyzed', 'call_ended', 'new_call']);
+ for (const trigger of triggers) {
+ expect(trigger.classification).toBe('READ');
+ expect(trigger.aiMetadata?.description?.length ?? 0).toBeGreaterThan(20);
+ expect(trigger.outputSchema?.fields.length ?? 0).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/packages/pieces/community/retell-ai/test/behaviour.test.ts b/packages/pieces/community/retell-ai/test/behaviour.test.ts
new file mode 100644
index 00000000000..caab1cfc5c8
--- /dev/null
+++ b/packages/pieces/community/retell-ai/test/behaviour.test.ts
@@ -0,0 +1,386 @@
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { createHmac } from 'crypto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createBatchCallAction } from '../src/lib/actions/create-batch-call';
+import { createPhoneNumber } from '../src/lib/actions/create-phone-number';
+import { getCall } from '../src/lib/actions/get-call';
+import { makePhoneCall } from '../src/lib/actions/make-phone-call';
+import { createPhoneCallAction } from '../src/lib/actions/ai/create-phone-call';
+import { deleteCallAction } from '../src/lib/actions/ai/delete-call';
+import { getCallByIdAction } from '../src/lib/actions/ai/get-call-by-id';
+import { getContactByPhoneAction } from '../src/lib/actions/ai/get-contact-by-phone';
+import { listCallsAction } from '../src/lib/actions/ai/list-calls';
+import { stopCallAction } from '../src/lib/actions/ai/stop-call';
+import { updateAgentAction } from '../src/lib/actions/ai/update-agent';
+import { updateCallMetadataAction } from '../src/lib/actions/ai/update-call-metadata';
+import { retellAiAuth } from '../src/lib/common/auth';
+import { buildRetellUrl, RetellAiError, retellApiCall } from '../src/lib/common/client';
+import { retellInput } from '../src/lib/common/input';
+import { agentIdDropdown, callIdDropdown } from '../src/lib/common/props';
+import { verifyRetellSignature } from '../src/lib/common/webhook';
+import { callAnalyzedTrigger } from '../src/lib/triggers/call-analyzed';
+import { callEndedTrigger } from '../src/lib/triggers/call-ended';
+import { newCallTrigger } from '../src/lib/triggers/new-call';
+import { CALL } from './fixtures';
+import { API_KEY, invoke, makeContext, makeStore, stubFetch, toDropdown } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+type Runnable = { run: (...args: never[]) => Promise<unknown> };
+
+function runAction({ action, props }: { action: Runnable; props: Record<string, unknown> }) {
+ return invoke({ fn: action.run, self: action, args: [makeContext({ props })] });
+}
+
+describe('path safety', () => {
+ it.each(['..', '.', 'a/b', '../delete-call/x', '', ' '])('seg rejects %j', (value) => {
+ expect(() => retellInput.seg({ value, label: 'Call ID' })).toThrow();
+ });
+
+ it('seg encodes reserved characters', () => {
+ expect(retellInput.seg({ value: 'call?x=1#y', label: 'Call ID' })).toBe('call%3Fx%3D1%23y');
+ });
+
+ it('buildRetellUrl refuses traversal, protocol-relative and query paths', () => {
+ expect(() => buildRetellUrl({ path: '/v2/get-call/../delete-call/x' })).toThrow();
+ expect(() => buildRetellUrl({ path: '//evil.example/x' })).toThrow();
+ expect(() => buildRetellUrl({ path: '/get-call?x=1' })).toThrow();
+ expect(buildRetellUrl({ path: '/get-agent/a', query: { version: 2, empty: '', none: undefined } })).toBe(
+ 'https://api.retellai.com/get-agent/a?version=2',
+ );
+ });
+
+ it('get_call never sends an AI-filled traversal id to another endpoint', async () => {
+ const calls = stubFetch([]);
+ await expect(runAction({ action: getCall, props: { callId: '../delete-call/x' } })).rejects.toThrow('not a valid Retell AI ID');
+ await expect(runAction({ action: getCallByIdAction, props: { call_id: '..' } })).rejects.toThrow();
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('error mapping', () => {
+ it('uses Retell error_message and keeps the body in responseBody, never body', async () => {
+ stubFetch([{ status: 400, body: { error_message: 'from_number is not owned' } }]);
+ const error = await runAction({
+ action: createPhoneCallAction,
+ props: { from_number: '+14155550100', to_number: '+14155550101' },
+ }).catch((e: unknown) => e);
+ if (!(error instanceof RetellAiError)) {
+ throw new Error('expected a RetellAiError');
+ }
+ const retellError = error;
+ expect(retellError.message).toBe('Retell AI rejected the request as invalid (HTTP 400): from_number is not owned');
+ expect(retellError.status).toBe(400);
+ expect(retellError.responseBody).toEqual({ error_message: 'from_number is not owned' });
+ expect(Object.keys(retellError)).not.toContain('body');
+ });
+
+ it('does not log request bodies (redactBodyInErrors)', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ stubFetch([{ status: 500, body: { error_message: 'boom' } }]);
+ await expect(
+ runAction({ action: updateCallMetadataAction, props: { call_id: 'c', metadata: { secret_note: 'do-not-log' } } }),
+ ).rejects.toThrow('server error');
+ for (const args of consoleError.mock.calls) {
+ expect(JSON.stringify(args)).not.toContain('do-not-log');
+ }
+ });
+
+ it('retries 429 on reads with backoff, then succeeds', async () => {
+ vi.useFakeTimers();
+ const calls = stubFetch([{ status: 429, body: {} }, { status: 429, body: {} }, { status: 200, body: CALL }]);
+ const promise = runAction({ action: getCallByIdAction, props: { call_id: 'call_1' } });
+ await vi.runAllTimersAsync();
+ await expect(promise).resolves.toMatchObject({ call_id: 'call_1' });
+ expect(calls).toHaveLength(3);
+ });
+
+ it('gives up after two 429 retries', async () => {
+ vi.useFakeTimers();
+ const calls = stubFetch([{ status: 429 }, { status: 429 }, { status: 429 }]);
+ const promise = runAction({ action: getCallByIdAction, props: { call_id: 'call_1' } }).catch((e: unknown) => e);
+ await vi.runAllTimersAsync();
+ expect(await promise).toBeInstanceOf(RetellAiError);
+ expect(calls).toHaveLength(3);
+ });
+
+ it('never retries a call that dials a phone', async () => {
+ const calls = stubFetch([{ status: 429, body: { error_message: 'concurrency' } }]);
+ await expect(
+ runAction({ action: createPhoneCallAction, props: { from_number: '+14155550100', to_number: '+14155550101' } }),
+ ).rejects.toThrow('rate or concurrency limit');
+ expect(calls).toHaveLength(1);
+ });
+
+ it('does not follow redirects', async () => {
+ stubFetch([{ status: 302 }]);
+ await expect(retellApiCall({ apiKey: API_KEY, method: HttpMethod.GET, path: '/get-concurrency' })).rejects.toThrow(
+ 'unexpected redirect',
+ );
+ });
+});
+
+describe('auth.validate', () => {
+ const validate = (apiKey: string) =>
+ invoke({ fn: retellAiAuth.validate, self: retellAiAuth, args: [{ auth: { apiKey }, server: { apiUrl: '', publicUrl: '' } }] });
+
+ it('probes POST /v2/list-agents?limit=1 with the trimmed key', async () => {
+ const calls = stubFetch([{ status: 200, body: { items: [], has_more: false } }]);
+ await expect(validate(` ${API_KEY} `)).resolves.toEqual({ valid: true });
+ expect(calls[0].method).toBe('POST');
+ expect(calls[0].url.pathname).toBe('/v2/list-agents');
+ expect(calls[0].url.searchParams.get('limit')).toBe('1');
+ expect(calls[0].headers['authorization']).toBe(`Bearer ${API_KEY}`);
+ });
+
+ it('reports invalid key only on 401/403', async () => {
+ stubFetch([{ status: 401, body: { error_message: 'bad key' } }]);
+ await expect(validate('x')).resolves.toEqual({ valid: false, error: 'Invalid API Key: Retell AI rejected it.' });
+ });
+
+ it('reports other failures as a verification problem, not a bad key', async () => {
+ stubFetch([{ status: 503, body: {} }]);
+ const result = await validate('x');
+ expect(result).toMatchObject({ valid: false });
+ expect(JSON.stringify(result)).toContain('Could not verify');
+ });
+});
+
+describe('input validation', () => {
+ it('rejects non-E.164 numbers before any request', async () => {
+ const calls = stubFetch([]);
+ await expect(runAction({ action: makePhoneCall, props: { fromNumber: '4155550100', toNumber: '+14155550101' } })).rejects.toThrow(
+ 'E.164',
+ );
+ expect(calls).toHaveLength(0);
+ });
+
+ it('create_phone_number refuses area code and phone number together', async () => {
+ const calls = stubFetch([]);
+ await expect(
+ runAction({ action: createPhoneNumber, props: { nickname: 'x', areaCode: 415, phoneNumber: '+14155550100' } }),
+ ).rejects.toThrow('either Area Code or Phone Number');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('dynamic variables must be an object and non-string values become text', () => {
+ expect(retellInput.stringMap({ value: { a: 1, b: false, c: { d: 1 }, e: null }, label: 'X' })).toEqual({
+ a: '1',
+ b: 'false',
+ c: '{"d":1}',
+ });
+ expect(() => retellInput.stringMap({ value: '[1]', label: 'Dynamic Variables' })).toThrow('JSON object');
+ });
+
+ it('batch call validates every number and the size cap', async () => {
+ const calls = stubFetch([]);
+ await expect(
+ runAction({ action: createBatchCallAction, props: { from_number: '+14155550100', tasks: [{ to_number: '+1415' }, { to_number: 'abc' }] } }),
+ ).rejects.toThrow('Call 2 To Number must be in E.164');
+ await expect(runAction({ action: createBatchCallAction, props: { from_number: '+14155550100', tasks: [] } })).rejects.toThrow(
+ 'at least one call',
+ );
+ const many = Array.from({ length: 1001 }, () => ({ to_number: '+14155550101' }));
+ await expect(runAction({ action: createBatchCallAction, props: { from_number: '+14155550100', tasks: many } })).rejects.toThrow(
+ 'at most 1000',
+ );
+ expect(calls).toHaveLength(0);
+ });
+
+ it('list_calls validates statuses and time range', async () => {
+ const calls = stubFetch([]);
+ await expect(runAction({ action: listCallsAction, props: { call_status: 'done' } })).rejects.toThrow('unknown values: done');
+ await expect(
+ runAction({ action: listCallsAction, props: { started_after: '2026-02-01T00:00:00Z', started_before: '2026-01-01T00:00:00Z' } }),
+ ).rejects.toThrow('earlier than');
+ await expect(runAction({ action: listCallsAction, props: { limit: 5000 } })).rejects.toThrow('between 1 and 1000');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('update actions refuse an empty update and contradictory clear flags', async () => {
+ const calls = stubFetch([]);
+ await expect(runAction({ action: updateAgentAction, props: { agent_id: 'a' } })).rejects.toThrow('at least one field');
+ await expect(
+ runAction({ action: updateAgentAction, props: { agent_id: 'a', webhook_url: 'https://x.example', clear_webhook_url: true } }),
+ ).rejects.toThrow('not both');
+ await expect(runAction({ action: updateCallMetadataAction, props: { call_id: 'c' } })).rejects.toThrow('Set Metadata');
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('documented empty and not-found results', () => {
+ it('stop_call reports a call that is no longer ongoing', async () => {
+ stubFetch([{ status: 404, body: { error_message: 'not found' } }]);
+ await expect(runAction({ action: stopCallAction, props: { call_id: 'call_1' } })).resolves.toEqual({
+ call_id: 'call_1',
+ stopped: false,
+ reason: 'Call not found or no longer ongoing (HTTP 404).',
+ });
+ });
+
+ it('stop_call reports a call that has not started (HTTP 400) as not stopped, and rethrows other 400s', async () => {
+ stubFetch([{ status: 400, body: { message: 'Can only stop an ongoing call.' } }, { status: 400, body: { message: 'bad' } }]);
+ await expect(runAction({ action: stopCallAction, props: { call_id: 'call_1' } })).resolves.toEqual({
+ call_id: 'call_1',
+ stopped: false,
+ reason: 'Call is not ongoing (not started yet or already over).',
+ });
+ await expect(runAction({ action: stopCallAction, props: { call_id: 'call_1' } })).rejects.toThrow('HTTP 400');
+ });
+
+ it('delete_call treats 404 as already deleted but rethrows other errors', async () => {
+ stubFetch([{ status: 404 }, { status: 500 }]);
+ await expect(runAction({ action: deleteCallAction, props: { call_id: 'call_1' } })).resolves.toEqual({
+ call_id: 'call_1',
+ deleted: false,
+ already_deleted: true,
+ });
+ await expect(runAction({ action: deleteCallAction, props: { call_id: 'call_1' } })).rejects.toThrow('server error');
+ });
+
+ it('get_contact_by_phone returns found=false on 404', async () => {
+ stubFetch([{ status: 404 }]);
+ await expect(runAction({ action: getContactByPhoneAction, props: { phone_number: '+14155550101' } })).resolves.toMatchObject({
+ found: false,
+ contact_id: null,
+ phone_number: '+14155550101',
+ });
+ });
+
+ it('list_calls accepts a bare array response defensively', async () => {
+ stubFetch([{ status: 200, body: [CALL] }]);
+ await expect(runAction({ action: listCallsAction, props: {} })).resolves.toMatchObject({
+ count: 1,
+ has_more: false,
+ pagination_key: null,
+ });
+ });
+});
+
+describe('dropdowns', () => {
+ const auth = { type: 'CUSTOM_AUTH', props: { apiKey: API_KEY } };
+ const loadOptions = (dropdown: { options: unknown }) => invoke({ fn: dropdown.options, self: dropdown, args: [{ auth }, {}] });
+
+ it('call dropdown uses POST /v3/list-calls and reads items', async () => {
+ const calls = stubFetch([{ status: 200, body: { items: [CALL], has_more: false } }]);
+ const result = toDropdown(await loadOptions(callIdDropdown));
+ expect(calls[0].method).toBe('POST');
+ expect(calls[0].url.pathname).toBe('/v3/list-calls');
+ expect(calls[0].body).toEqual({ limit: 100, sort_order: 'descending' });
+ expect(result.options[0].value).toBe('call_1');
+ });
+
+ it('agent dropdown pages through /v2/list-agents and dedupes', async () => {
+ const calls = stubFetch([
+ { status: 200, body: { items: [{ agent_id: 'a1', agent_name: 'One' }], pagination_key: 'p2', has_more: true } },
+ { status: 200, body: { items: [{ agent_id: 'a1', agent_name: 'One' }, { agent_id: 'a2', agent_name: 'Two' }], has_more: false } },
+ ]);
+ const result = toDropdown(await loadOptions(agentIdDropdown({ displayName: 'Agent' })));
+ expect(calls.map((call) => call.url.searchParams.get('pagination_key'))).toEqual([null, 'p2']);
+ expect(result.options.map((option) => option.value)).toEqual(['a1', 'a2']);
+ expect(calls.every((call) => JSON.stringify(call.body ?? '').includes('voice'))).toBe(true);
+ });
+
+ it('agent dropdown stops after 10 pages', async () => {
+ let page = 0;
+ const calls = stubFetch(() => {
+ page += 1;
+ return { status: 200, body: { items: [{ agent_id: `a${page}` }], pagination_key: `p${page}`, has_more: true } };
+ });
+ const result = toDropdown(await loadOptions(agentIdDropdown({ displayName: 'Agent' })));
+ expect(calls).toHaveLength(10);
+ expect(result.options).toHaveLength(10);
+ });
+
+ it('dropdown shows a disabled reason on error', async () => {
+ stubFetch([{ status: 401, body: { error_message: 'bad' } }]);
+ const result = toDropdown(await loadOptions(callIdDropdown));
+ expect(result.disabled).toBe(true);
+ expect(result.placeholder).toContain('Error loading calls');
+ });
+});
+
+describe('webhook triggers', () => {
+ const now = 1760000000000;
+
+ function signedPayload({ event, callId = 'call_1', timestamp = now, key = API_KEY }: { event: string; callId?: string; timestamp?: number; key?: string }) {
+ const rawBody = JSON.stringify({ event, call: { ...CALL, call_id: callId } });
+ const digest = createHmac('sha256', key).update(rawBody + String(timestamp)).digest('hex');
+ return { body: JSON.parse(rawBody), rawBody, headers: { 'X-Retell-Signature': `v=${timestamp},d=${digest}` } };
+ }
+
+ function triggerContext({ payload, store = makeStore() }: { payload: unknown; store?: ReturnType<typeof makeStore> }) {
+ return { auth: { type: 'CUSTOM_AUTH', props: { apiKey: API_KEY } }, propsValue: {}, store, payload };
+ }
+
+ function runTrigger({ trigger, context }: { trigger: { run: unknown }; context: unknown }) {
+ return invoke({ fn: trigger.run, self: trigger, args: [context] });
+ }
+
+ it('verifies v=<ms>,d=<hmac(rawBody+ts)>', () => {
+ const payload = signedPayload({ event: 'call_ended' });
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: payload.rawBody, headers: payload.headers, nowMs: now })).toBe(true);
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: Buffer.from(payload.rawBody), headers: payload.headers, nowMs: now })).toBe(true);
+ expect(verifyRetellSignature({ apiKey: 'other', rawBody: payload.rawBody, headers: payload.headers, nowMs: now })).toBe(false);
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: payload.rawBody + ' ', headers: payload.headers, nowMs: now })).toBe(false);
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: payload.rawBody, headers: {}, nowMs: now })).toBe(false);
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: undefined, headers: payload.headers, nowMs: now })).toBe(false);
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: payload.rawBody, headers: { 'x-retell-signature': 'garbage' }, nowMs: now })).toBe(false);
+ });
+
+ it('accepts deliveries up to 15 minutes old (queue lag) and rejects older or far-future ones', () => {
+ const old = signedPayload({ event: 'call_ended', timestamp: now - 14 * 60 * 1000 });
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: old.rawBody, headers: old.headers, nowMs: now })).toBe(true);
+ const stale = signedPayload({ event: 'call_ended', timestamp: now - 16 * 60 * 1000 });
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: stale.rawBody, headers: stale.headers, nowMs: now })).toBe(false);
+ const future = signedPayload({ event: 'call_ended', timestamp: now + 6 * 60 * 1000 });
+ expect(verifyRetellSignature({ apiKey: API_KEY, rawBody: future.rawBody, headers: future.headers, nowMs: now })).toBe(false);
+ });
+
+ it.each([
+ [newCallTrigger, 'call_started'],
+ [callEndedTrigger, 'call_ended'],
+ [callAnalyzedTrigger, 'call_analyzed'],
+ ] as const)('%s fires only for its event, once per call', async (trigger, event) => {
+ vi.spyOn(Date, 'now').mockReturnValue(now);
+ const store = makeStore();
+ const own = signedPayload({ event });
+ const first = await runTrigger({ trigger, context: triggerContext({ payload: own, store }) });
+ expect(first).toEqual([{ event, call: own.body.call, [DEDUPE_KEY_PROPERTY]: `${event}:call_1` }]);
+ expect(await runTrigger({ trigger, context: triggerContext({ payload: own, store }) })).toEqual([]);
+ const other = signedPayload({ event: event === 'call_started' ? 'call_ended' : 'call_started' });
+ expect(await runTrigger({ trigger, context: triggerContext({ payload: other, store }) })).toEqual([]);
+ const second = signedPayload({ event, callId: 'call_2' });
+ expect(await runTrigger({ trigger, context: triggerContext({ payload: second, store }) })).toHaveLength(1);
+ });
+
+ it('ignores unsigned or forged deliveries', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(now);
+ const forged = signedPayload({ event: 'call_analyzed', key: 'attacker' });
+ expect(await runTrigger({ trigger: callAnalyzedTrigger, context: triggerContext({ payload: forged }) })).toEqual([]);
+ const unsigned = { ...signedPayload({ event: 'call_analyzed' }), headers: {} };
+ expect(await runTrigger({ trigger: callAnalyzedTrigger, context: triggerContext({ payload: unsigned }) })).toEqual([]);
+ });
+
+ it('tags each event with the platform dedupe key and keeps the fallback list bounded', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(now);
+ const store = makeStore();
+ store.data.set('retell_call_ended_deliveries', Array.from({ length: 500 }, (_, i) => `call_ended:old_${i}`));
+ const out = await runTrigger({ trigger: callEndedTrigger, context: triggerContext({ payload: signedPayload({ event: 'call_ended' }), store }) });
+ expect(out[0]).toMatchObject({ event: 'call_ended', [DEDUPE_KEY_PROPERTY]: 'call_ended:call_1' });
+ const kept = store.data.get('retell_call_ended_deliveries');
+ expect(Array.isArray(kept) && kept.length).toBe(500);
+ expect(Array.isArray(kept) && kept[kept.length - 1]).toBe('call_ended:call_1');
+ expect(store.data.has('retell_call_ended_call_1')).toBe(false);
+ });
+
+ it('sample data matches the real {event, call} shape', () => {
+ expect(newCallTrigger.sampleData).toMatchObject({ event: 'call_started', call: { call_id: expect.any(String) } });
+ expect(callAnalyzedTrigger.sampleData).toMatchObject({ event: 'call_analyzed', call: { call_analysis: expect.any(Object) } });
+ });
+});
diff --git a/packages/pieces/community/retell-ai/test/fixtures.ts b/packages/pieces/community/retell-ai/test/fixtures.ts
new file mode 100644
index 00000000000..554b6e9a1be
--- /dev/null
+++ b/packages/pieces/community/retell-ai/test/fixtures.ts
@@ -0,0 +1,109 @@
+export const CALL = {
+ call_type: 'phone_call',
+ call_id: 'call_1',
+ agent_id: 'agent_1',
+ agent_name: 'Setter',
+ agent_version: 2,
+ call_status: 'ended',
+ direction: 'outbound',
+ from_number: '+14155550100',
+ to_number: '+14155550101',
+ start_timestamp: 1703302407333,
+ end_timestamp: 1703302428855,
+ duration_ms: 21522,
+ disconnection_reason: 'user_hangup',
+ transcript: 'Agent: hi',
+ recording_url: 'https://example.com/rec.wav',
+ public_log_url: 'https://example.com/log.txt',
+ metadata: { crm: '1' },
+ retell_llm_dynamic_variables: { name: 'Ann' },
+ call_analysis: {
+ call_summary: 'Confirmed.',
+ user_sentiment: 'Positive',
+ call_successful: true,
+ in_voicemail: false,
+ custom_analysis_data: { ok: true },
+ },
+ call_cost: { combined_cost: 7.1 },
+ telephony_identifier: { twilio_call_sid: 'CA1' },
+};
+
+export const CHAT = {
+ chat_id: 'chat_1',
+ agent_id: 'agent_c',
+ version: 1,
+ chat_status: 'ongoing',
+ chat_type: 'api_chat',
+ start_timestamp: 1703302407333,
+ transcript: 'User: hi',
+ chat_analysis: { chat_summary: 's', user_sentiment: 'Neutral', chat_successful: true },
+ chat_cost: { combined_cost: 1 },
+ metadata: {},
+};
+
+export const AGENT = {
+ agent_id: 'agent_1',
+ agent_name: 'Setter',
+ version: 3,
+ is_published: false,
+ voice_id: '11labs-Adrian',
+ language: 'en-US',
+ webhook_url: null,
+ response_engine: { type: 'retell-llm', llm_id: 'llm_1', version: 3 },
+ last_modification_timestamp: 1703413636133,
+};
+
+export const PHONE = {
+ phone_number: '+14155550100',
+ phone_number_pretty: '(415) 555-0100',
+ phone_number_type: 'retell-twilio',
+ nickname: 'Main',
+ area_code: 415,
+ inbound_agents: [{ agent_id: 'agent_1', weight: 1 }],
+ outbound_agents: [{ agent_id: 'agent_2', agent_version: 2, weight: 1 }],
+ last_modification_timestamp: 1703413636133,
+};
+
+export const VOICE = {
+ voice_id: '11labs-Adrian',
+ voice_name: 'Adrian',
+ provider: 'elevenlabs',
+ accent: 'American',
+ gender: 'male',
+ age: 'Young',
+ preview_audio_url: 'https://example.com/a.mp3',
+};
+
+export const KB = {
+ knowledge_base_id: 'knowledge_base_1',
+ knowledge_base_name: 'Docs',
+ status: 'in_progress',
+ enable_auto_refresh: false,
+ knowledge_base_sources: [
+ { type: 'url', source_id: 'src_1', url: 'https://example.com' },
+ { type: 'text', source_id: 'src_2', title: 'FAQ', content_url: 'https://example.com/faq' },
+ ],
+};
+
+export const LLM = {
+ llm_id: 'llm_1',
+ version: 1,
+ is_published: true,
+ model: 'gpt-4.1',
+ general_prompt: 'You are helpful.',
+ begin_message: 'Hi',
+ knowledge_base_ids: ['kb_1', 'kb_2'],
+ last_modification_timestamp: 1703413636133,
+};
+
+export const CONTACT = {
+ contact_id: 'contact_1',
+ phone_number: '+14155550101',
+ first_name: 'Ann',
+ last_name: 'Lee',
+ do_not_call: false,
+ contact_tags: [{ id: 't1', label: 'vip' }],
+ custom_fields: { plan: 'pro' },
+ conversation_count: 2,
+ created_timestamp: 1703413636133,
+};
diff --git a/packages/pieces/community/retell-ai/test/helpers.ts b/packages/pieces/community/retell-ai/test/helpers.ts
new file mode 100644
index 00000000000..7562fa4bdfc
--- /dev/null
+++ b/packages/pieces/community/retell-ai/test/helpers.ts
@@ -0,0 +1,114 @@
+import { vi } from 'vitest';
+
+export function stubFetch(responses: FakeResponse[] | ((call: RecordedCall) => FakeResponse)) {
+ const calls: RecordedCall[] = [];
+ const queue = Array.isArray(responses) ? [...responses] : undefined;
+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key] = value;
+ });
+ const rawBody =
+ typeof init?.body === 'string'
+ ? init.body
+ : init?.body instanceof Uint8Array
+ ? Buffer.from(init.body).toString('utf8')
+ : undefined;
+ const call: RecordedCall = {
+ method: init?.method ?? 'GET',
+ url: new URL(String(input)),
+ headers,
+ rawBody,
+ body: parseJson(rawBody),
+ };
+ calls.push(call);
+ const next = queue ? queue.shift() : typeof responses === 'function' ? responses(call) : undefined;
+ if (next === undefined) {
+ throw new Error(`Unexpected request ${call.method} ${call.url.toString()}`);
+ }
+ const status = next.status ?? 200;
+ const payload = next.body === undefined ? '' : JSON.stringify(next.body);
+ return new Response(status === 204 || payload === '' ? null : payload, {
+ status,
+ headers: { 'content-type': 'application/json' },
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return calls;
+}
+
+export function makeStore() {
+ const data = new Map<string, unknown>();
+ return {
+ data,
+ get: vi.fn(async (key: string) => (data.has(key) ? data.get(key) : null)),
+ put: vi.fn(async (key: string, value: unknown) => {
+ data.set(key, value);
+ return value;
+ }),
+ delete: vi.fn(async (key: string) => {
+ data.delete(key);
+ }),
+ };
+}
+
+export function makeContext({ props, extra = {} }: { props: Record<string, unknown>; extra?: Record<string, unknown> }) {
+ const auth = { type: 'CUSTOM_AUTH', props: { apiKey: ` ${API_KEY} ` } };
+ return {
+ auth,
+ propsValue: { auth, ...props },
+ store: makeStore(),
+ ...extra,
+ };
+}
+
+export async function invoke({ fn, self, args }: { fn: unknown; self: unknown; args: unknown[] }): Promise<unknown> {
+ if (typeof fn !== 'function') {
+ throw new Error('not a function');
+ }
+ return Reflect.apply(fn, self, args);
+}
+
+export function toRecord(value: unknown): Record<string, unknown> {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error(`expected an object, got ${JSON.stringify(value)}`);
+ }
+ return Object.fromEntries(Object.entries(value));
+}
+
+export function toDropdown(value: unknown): { disabled: boolean; placeholder: string | undefined; options: { label: string; value: string }[] } {
+ const record = toRecord(value);
+ const options = Array.isArray(record['options']) ? record['options'] : [];
+ return {
+ disabled: record['disabled'] === true,
+ placeholder: typeof record['placeholder'] === 'string' ? record['placeholder'] : undefined,
+ options: options.map((option) => {
+ const item = toRecord(option);
+ return { label: String(item['label']), value: String(item['value']) };
+ }),
+ };
+}
+
+function parseJson(raw: string | undefined): unknown {
+ if (raw === undefined || raw.length === 0) {
+ return undefined;
+ }
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+}
+
+export const API_KEY = 'key_test_123';
+export const BASE = 'https://api.retellai.com';
+
+export type RecordedCall = {
+ method: string;
+ url: URL;
+ headers: Record<string, string>;
+ rawBody: string | undefined;
+ body: unknown;
+};
+
+export type FakeResponse = { status?: number; body?: unknown };
diff --git a/packages/pieces/community/retell-ai/vitest.config.ts b/packages/pieces/community/retell-ai/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/retell-ai/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})