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(exa): run Exa agents, watch searches with a monitor trigger, and give AI agents search, contents and answer actions (#15983)

Odai Ahmad68e8189e69d0
diff --git a/bun.lock b/bun.lock
index 44135415ffd..75f893bb814 100644
--- a/bun.lock
+++ b/bun.lock
@@ -3019,7 +3019,7 @@
},
"packages/pieces/community/exa": {
"name": "@activepieces/piece-exa",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -3028,6 +3028,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/extracta-ai": {
diff --git a/packages/pieces/community/exa/package.json b/packages/pieces/community/exa/package.json
index a00b16e4386..d53faa66058 100644
--- a/packages/pieces/community/exa/package.json
+++ b/packages/pieces/community/exa/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-exa",
- "version": "0.2.1",
+ "version": "0.3.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"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"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
@@ -15,6 +16,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/exa/src/i18n/translation.json b/packages/pieces/community/exa/src/i18n/translation.json
index 9685065d7e8..3456d67a639 100644
--- a/packages/pieces/community/exa/src/i18n/translation.json
+++ b/packages/pieces/community/exa/src/i18n/translation.json
@@ -5,11 +5,25 @@
"Ask AI": "Ask AI",
"Perform Search": "Perform Search",
"Find Similar Links": "Find Similar Links",
+ "Start Agent Run": "Start Agent Run",
+ "Get Agent Run": "Get Agent Run",
+ "List Agent Runs": "List Agent Runs",
+ "Cancel Agent Run": "Cancel Agent Run",
+ "Search the Web": "Search the Web",
+ "Get Page Contents": "Get Page Contents",
+ "Answer a Question": "Answer a Question",
"Custom API Call": "Custom API Call",
"Retrieve clean HTML content from specified URLs.": "Retrieve clean HTML content from specified URLs.",
"Provides direct answers to queries by summarizing results.": "Provides direct answers to queries by summarizing results.",
"Search the web using semantic or keyword-based search.": "Search the web using semantic or keyword-based search.",
"Find pages similar to a given URL.": "Find pages similar to a given URL.",
+ "Starts an Exa Agent run for deep research, list building or structured extraction. The run works in the background; use Get Agent Run to read the result.": "Starts an Exa Agent run for deep research, list building or structured extraction. The run works in the background; use Get Agent Run to read the result.",
+ "Gets the status and result of an Exa Agent run. Use it after Start Agent Run, for example behind a Delay step.": "Gets the status and result of an Exa Agent run. Use it after Start Agent Run, for example behind a Delay step.",
+ "Lists your team's Exa Agent runs, newest first, one page at a time.": "Lists your team's Exa Agent runs, newest first, one page at a time.",
+ "Cancels a queued or running Exa Agent run right away. The run returns no results, and usage so far is still billed.": "Cancels a queued or running Exa Agent run right away. The run returns no results, and usage so far is still billed.",
+ "Searches the web with Exa and returns flat result rows.": "Searches the web with Exa and returns flat result rows.",
+ "Fetches clean content for known URLs and reports which URLs failed.": "Fetches clean content for known URLs and reports which URLs failed.",
+ "Answers a question from live web results and returns the sources it used.": "Answers a question from live web results and returns the sources it used.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"URLs": "URLs",
"Return Full Text": "Return Full Text",
@@ -17,9 +31,15 @@
"Livecrawl Timeout (ms)": "Livecrawl Timeout (ms)",
"Number of Subpages": "Number of Subpages",
"Subpage Target": "Subpage Target",
+ "Include Highlights": "Include Highlights",
+ "Summary Question": "Summary Question",
+ "Max Content Age (hours)": "Max Content Age (hours)",
+ "Links per Page": "Links per Page",
"Query": "Query",
"Include Text Content": "Include Text Content",
"Model": "Model",
+ "Instructions": "Instructions",
+ "User Country": "User Country",
"Search Type": "Search Type",
"Category": "Category",
"Number of Results": "Number of Results",
@@ -31,41 +51,70 @@
"End Published Date": "End Published Date",
"Include Text": "Include Text",
"Exclude Text": "Exclude Text",
+ "Max Text Characters": "Max Text Characters",
+ "Filter Unsafe Content": "Filter Unsafe Content",
"URL": "URL",
"Start Crawl Date (ISO)": "Start Crawl Date (ISO)",
"End Crawl Date (ISO)": "End Crawl Date (ISO)",
"Start Published Date (ISO)": "Start Published Date (ISO)",
"End Published Date (ISO)": "End Published Date (ISO)",
+ "Task": "Task",
+ "Effort": "Effort",
+ "Output Schema": "Output Schema",
+ "Max Cost (USD)": "Max Cost (USD)",
+ "Previous Run ID": "Previous Run ID",
+ "Metadata": "Metadata",
+ "Run ID": "Run ID",
+ "Limit": "Limit",
+ "Cursor": "Cursor",
+ "Published After": "Published After",
+ "Published Before": "Published Before",
+ "Include Page Text": "Include Page Text",
+ "Highlights Focus": "Highlights Focus",
+ "Subpages": "Subpages",
+ "Subpage Keyword": "Subpage Keyword",
+ "Question": "Question",
+ "Include Source Text": "Include Source Text",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"Array of URLs to crawl": "Array of URLs to crawl",
"If true, returns full page text. If false, disables text return.": "If true, returns full page text. If false, disables text return.",
- "Options for livecrawling pages.": "Options for livecrawling pages.",
+ "Deprecated by Exa: prefer Max Content Age. Ignored when Max Content Age is set.": "Deprecated by Exa: prefer Max Content Age. Ignored when Max Content Age is set.",
"Timeout for livecrawling in milliseconds.": "Timeout for livecrawling in milliseconds.",
"Number of subpages to crawl.": "Number of subpages to crawl.",
"Keyword(s) to find specific subpages.": "Keyword(s) to find specific subpages.",
+ "Also return the most relevant snippets from each page (billed as an extra content type).": "Also return the most relevant snippets from each page (billed as an extra content type).",
+ "Ask for an AI summary of each page focused on this question, e.g. \"What does this company sell?\" (billed per page).": "Ask for an AI summary of each page focused on this question, e.g. \"What does this company sell?\" (billed per page).",
+ "Use cached content only if it is newer than this many hours (0 always fetches fresh, -1 always uses cache, up to 720). Replaces Livecrawl Option.": "Use cached content only if it is newer than this many hours (0 always fetches fresh, -1 always uses cache, up to 720). Replaces Livecrawl Option.",
+ "Also return up to this many links found on each page, e.g. 10.": "Also return up to this many links found on each page, e.g. 10.",
"Ask a question to get summarized answers from the web.": "Ask a question to get summarized answers from the web.",
"If true, includes full text content from the search results": "If true, includes full text content from the search results",
"Choose the Exa model to use for the answer.": "Choose the Exa model to use for the answer.",
+ "Extra guidance for the answer, such as tone, length or preferred sources, e.g. \"Answer in two sentences and prefer official sources.\"": "Extra guidance for the answer, such as tone, length or preferred sources, e.g. \"Answer in two sentences and prefer official sources.\"",
+ "Two-letter country code to localize the search behind the answer, e.g. \"US\".": "Two-letter country code to localize the search behind the answer, e.g. \"US\".",
"Search query to find related articles and data.": "Search query to find related articles and data.",
- "Type of search to perform.": "Type of search to perform.",
- "Category of data to focus the search on.": "Category of data to focus the search on.",
+ "Type of search to perform. Auto suits most searches; Instant and Fast trade depth for speed; Deep Lite, Deep and Deep Reasoning research more and cost more ($0.012 to $0.015 per search). Keyword and Neural are legacy options that Exa no longer documents.": "Type of search to perform. Auto suits most searches; Instant and Fast trade depth for speed; Deep Lite, Deep and Deep Reasoning research more and cost more ($0.012 to $0.015 per search). Keyword and Neural are legacy options that Exa no longer documents.",
+ "Category of data to focus the search on. Company and People do not support published-date filters or Exclude Domains.": "Category of data to focus the search on. Company and People do not support published-date filters or Exclude Domains.",
"Number of results to return (max 100).": "Number of results to return (max 100).",
"Limit results to only these domains.": "Limit results to only these domains.",
"Exclude results from these domains.": "Exclude results from these domains.",
- "Only include results crawled after this ISO date.": "Only include results crawled after this ISO date.",
- "Only include results crawled before this ISO date.": "Only include results crawled before this ISO date.",
+ "Deprecated: Exa now ignores this filter. Use the published date filters instead.": "Deprecated: Exa now ignores this filter. Use the published date filters instead.",
"Only include results published after this ISO date.": "Only include results published after this ISO date.",
"Only include results published before this ISO date.": "Only include results published before this ISO date.",
- "Strings that must be present in the text of results.": "Strings that must be present in the text of results.",
- "Strings that must not be present in the text of results.": "Strings that must not be present in the text of results.",
+ "Deprecated by Exa. Strings that must be present in the text of results.": "Deprecated by Exa. Strings that must be present in the text of results.",
+ "Deprecated by Exa. Strings that must not be present in the text of results.": "Deprecated by Exa. Strings that must not be present in the text of results.",
+ "Limit the page text returned per result to this many characters, e.g. 2000. Leave empty for full text.": "Limit the page text returned per result to this many characters, e.g. 2000. Leave empty for full text.",
+ "Also return the most relevant snippets from each page.": "Also return the most relevant snippets from each page.",
+ "Use cached page content only if it is newer than this many hours (0 always fetches fresh, -1 always uses cache, up to 720). Leave empty for Exa's default.": "Use cached page content only if it is newer than this many hours (0 always fetches fresh, -1 always uses cache, up to 720). Leave empty for Exa's default.",
+ "Two-letter country code to localize results, e.g. \"US\" or \"DE\".": "Two-letter country code to localize results, e.g. \"US\" or \"DE\".",
+ "Remove unsafe content from the results.": "Remove unsafe content from the results.",
"Reference URL to find semantically similar links.": "Reference URL to find semantically similar links.",
"List of domains to include in results.": "List of domains to include in results.",
"List of domains to exclude from results.": "List of domains to exclude from results.",
@@ -75,16 +124,63 @@
"Only include links published before this date (ISO format).": "Only include links published before this date (ISO format).",
"Strings that must be present in the webpage text (max 1 string of up to 5 words).": "Strings that must be present in the webpage text (max 1 string of up to 5 words).",
"Strings that must not be present in the webpage text (max 1 string of up to 5 words).": "Strings that must not be present in the webpage text (max 1 string of up to 5 words).",
+ "What the agent should research or build, in plain language. Example: \"List 10 Series A climate-tech startups in Europe founded after 2022, with their website and lead investor.\"": "What the agent should research or build, in plain language. Example: \"List 10 Series A climate-tech startups in Europe founded after 2022, with their website and lead investor.\"",
+ "How hard the agent works, which sets the price per run. Minimal to Extra High are fixed prices. Auto and Ultra are metered by usage and can cost up to $5 and $20 per run unless you set Max Cost. Defaults to Low.": "How hard the agent works, which sets the price per run. Minimal to Extra High are fixed prices. Auto and Ultra are metered by usage and can cost up to $5 and $20 per run unless you set Max Cost. Defaults to Low.",
+ "Extra guidance for the agent, such as preferred sources or rules like \"only use official company websites\".": "Extra guidance for the agent, such as preferred sources or rules like \"only use official company websites\".",
+ "Optional JSON Schema for a structured result, returned in Structured Output. Example: {\"type\":\"object\",\"properties\":{\"companies\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"website\":{\"type\":\"string\"}}}}}}": "Optional JSON Schema for a structured result, returned in Structured Output. Example: {\"type\":\"object\",\"properties\":{\"companies\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"website\":{\"type\":\"string\"}}}}}}",
+ "Spending cap for one run, between 1 and 100. Only applies when Effort is Auto or Ultra; fixed efforts already have a fixed price.": "Spending cap for one run, between 1 and 100. Only applies when Effort is Auto or Ultra; fixed efforts already have a fixed price.",
+ "Continue from an earlier run so the agent builds on its findings. Use the ID returned by Start Agent Run, e.g. \"agent_run_01k4d9w6y3h7p2m8\".": "Continue from an earlier run so the agent builds on its findings. Use the ID returned by Start Agent Run, e.g. \"agent_run_01k4d9w6y3h7p2m8\".",
+ "Optional key-value labels stored with the run, e.g. {\"flow\": \"lead-research\"}.": "Optional key-value labels stored with the run, e.g. {\"flow\": \"lead-research\"}.",
+ "The ID returned by Start Agent Run (or List Agent Runs), e.g. \"agent_run_01k4d9w6y3h7p2m8\".": "The ID returned by Start Agent Run (or List Agent Runs), e.g. \"agent_run_01k4d9w6y3h7p2m8\".",
+ "How many runs to return in this page, 1 to 100. Defaults to 20.": "How many runs to return in this page, 1 to 100. Defaults to 20.",
+ "Leave empty for the first page. To get the next page, paste the Next Cursor value from the previous result.": "Leave empty for the first page. To get the next page, paste the Next Cursor value from the previous result.",
+ "What to search for, in natural language, e.g. \"latest research on solid-state batteries\".": "What to search for, in natural language, e.g. \"latest research on solid-state batteries\".",
+ "One of 'auto' (default), 'fast', 'instant', 'deep-lite', 'deep', 'deep-reasoning'. Deep modes are slower and cost more.": "One of 'auto' (default), 'fast', 'instant', 'deep-lite', 'deep', 'deep-reasoning'. Deep modes are slower and cost more.",
+ "Optional focus: 'company', 'people', 'news', 'publication', 'personal site' or 'financial report'.": "Optional focus: 'company', 'people', 'news', 'publication', 'personal site' or 'financial report'.",
+ "How many results to return, 1 to 100. Defaults to 10; each result above 10 costs $0.001.": "How many results to return, 1 to 100. Defaults to 10; each result above 10 costs $0.001.",
+ "Only return results from these domains or paths, e.g. \"arxiv.org\" or \"example.com/blog\".": "Only return results from these domains or paths, e.g. \"arxiv.org\" or \"example.com/blog\".",
+ "Never return results from these domains. Not allowed with the company or people category.": "Never return results from these domains. Not allowed with the company or people category.",
+ "Only results published after this ISO 8601 date, e.g. \"2026-01-01T00:00:00Z\". Not allowed with the company or people category.": "Only results published after this ISO 8601 date, e.g. \"2026-01-01T00:00:00Z\". Not allowed with the company or people category.",
+ "Only results published before this ISO 8601 date. Not allowed with the company or people category.": "Only results published before this ISO 8601 date. Not allowed with the company or people category.",
+ "Return the page text for each result.": "Return the page text for each result.",
+ "Cap the page text per result, e.g. 2000. Only used when page text is included.": "Cap the page text per result, e.g. 2000. Only used when page text is included.",
+ "Return the most relevant snippets from each page.": "Return the most relevant snippets from each page.",
+ "Optional question that steers which snippets are picked. Turns highlights on.": "Optional question that steers which snippets are picked. Turns highlights on.",
+ "Return a per-page AI summary focused on this question, e.g. \"What does this company sell?\" ($0.001 per page).": "Return a per-page AI summary focused on this question, e.g. \"What does this company sell?\" ($0.001 per page).",
+ "Use cached content only if newer than this many hours; 0 always fetches fresh, -1 always uses cache, max 720.": "Use cached content only if newer than this many hours; 0 always fetches fresh, -1 always uses cache, max 720.",
+ "Two-letter ISO country code to localize results, e.g. \"US\".": "Two-letter ISO country code to localize results, e.g. \"US\".",
+ "Full URLs to fetch, including https://, e.g. \"https://exa.ai/docs\". Up to 100.": "Full URLs to fetch, including https://, e.g. \"https://exa.ai/docs\". Up to 100.",
+ "Return the page text.": "Return the page text.",
+ "Cap the text per page, e.g. 5000. Only used when page text is included.": "Cap the text per page, e.g. 5000. Only used when page text is included.",
+ "Return a per-page AI summary focused on this question, e.g. \"Who are the founders?\".": "Return a per-page AI summary focused on this question, e.g. \"Who are the founders?\".",
+ "Also fetch up to this many linked subpages per URL, e.g. 3.": "Also fetch up to this many linked subpages per URL, e.g. 3.",
+ "Prefer subpages matching this keyword, e.g. \"pricing\" or \"about\".": "Prefer subpages matching this keyword, e.g. \"pricing\" or \"about\".",
+ "Also return up to this many links found on each page.": "Also return up to this many links found on each page.",
+ "The question to answer, e.g. \"What is the latest stable version of Node.js?\".": "The question to answer, e.g. \"What is the latest stable version of Node.js?\".",
+ "'exa' (default), 'exa-pro' for harder questions, or 'exa-fast' for lower latency.": "'exa' (default), 'exa-pro' for harder questions, or 'exa-fast' for lower latency.",
+ "Optional guidance for the answer, e.g. \"Answer in two sentences and cite official sources only.\"": "Optional guidance for the answer, e.g. \"Answer in two sentences and cite official sources only.\"",
+ "Two-letter ISO country code to localize the search, e.g. \"US\".": "Two-letter ISO country code to localize the search, e.g. \"US\".",
+ "Also return the full text of each cited page.": "Also return the full text of each cited page.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
"Never": "Never",
"Fallback": "Fallback",
"Always": "Always",
"Auto": "Auto",
"Exa": "Exa",
"Exa Pro": "Exa Pro",
- "Keyword": "Keyword",
- "Neural": "Neural",
+ "Exa Fast": "Exa Fast",
+ "Keyword (legacy)": "Keyword (legacy)",
+ "Neural (legacy)": "Neural (legacy)",
+ "Instant": "Instant",
+ "Fast": "Fast",
+ "Deep Lite": "Deep Lite",
+ "Deep": "Deep",
+ "Deep Reasoning": "Deep Reasoning",
"Company": "Company",
"Research Paper": "Research Paper",
"News": "News",
@@ -94,14 +190,39 @@
"Personal Site": "Personal Site",
"LinkedIn Profile": "LinkedIn Profile",
"Financial Report": "Financial Report",
+ "Publication": "Publication",
+ "People": "People",
+ "Minimal ($0.012 per run)": "Minimal ($0.012 per run)",
+ "Low ($0.025 per run)": "Low ($0.025 per run)",
+ "Medium ($0.10 per run)": "Medium ($0.10 per run)",
+ "High ($0.50 per run)": "High ($0.50 per run)",
+ "Extra High ($1.00 per run)": "Extra High ($1.00 per run)",
+ "Auto (metered, up to $5 by default)": "Auto (metered, up to $5 by default)",
+ "Ultra (metered, up to $20 by default)": "Ultra (metered, up to $20 by default)",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw"
+ "New Search Monitor Results": "New Search Monitor Results",
+ "Runs a search on a schedule and triggers with the new results Exa found since the last run.": "Runs a search on a schedule and triggers with the new results Exa found since the last run.",
+ "Markdown": "Markdown",
+ "Search Query": "Search Query",
+ "Check Every": "Check Every",
+ "Max Results per Run": "Max Results per Run",
+ "Monitor Name": "Monitor Name",
+ "Exa creates a **Monitor** that repeats this search on a schedule and sends only new results.\n\n- Each run costs about **$0.015** on your Exa account (plus $0.001 per result above 10). An hourly monitor is about 720 runs a month (≈ $11); daily is about 30 (≈ $0.45).\n- Exa only delivers to a public **HTTPS** address. On a self-hosted instance, the Activepieces webhook URL must be reachable from the internet.\n- Testing the trigger in the builder runs one search (about $0.007, plus content charges when page text": "Exa creates a **Monitor** that repeats this search on a schedule and sends only new results.\n\n- Each run costs about **$0.015** on your Exa account (plus $0.001 per result above 10). An hourly monitor is about 720 runs a month (≈ $11); daily is about 30 (≈ $0.45).\n- Exa only delivers to a public **HTTPS** address. On a self-hosted instance, the Activepieces webhook URL must be reachable from the internet.\n- Testing the trigger in the builder runs one search (about $0.007, plus content charges when page text or highlights are on) and shows its results; it does not create a monitor.\n- Results that were already delivered are not sent again, also after the flow is republished. A run whose results were all delivered before is skipped. When a run mixes old and new results, only the new ones are sent, with their citations; Summary is then empty, and Run Summary and Run Citations cover the whole run. Numbered markers such as [1] in Exa's summaries are Exa's own; Exa does not document what they point to, so use the citation lists for sources.\n- Turning the flow off deletes the monitor, retrying if Exa is briefly unavailable. If it still can't be deleted, remove it in the Exa dashboard: it is named after this flow unless you set Monitor Name.",
+ "What to watch for, written as the ongoing signal rather than a date range. Example: \"new battery recycling facilities announced in North America\".": "What to watch for, written as the ongoing signal rather than a date range. Example: \"new battery recycling facilities announced in North America\".",
+ "How often Exa runs the search. Each run may start up to 30 minutes late.": "How often Exa runs the search. Each run may start up to 30 minutes late.",
+ "Up to how many new results each run returns, 1 to 100. Defaults to 10; results above 10 cost extra.": "Up to how many new results each run returns, 1 to 100. Defaults to 10; results above 10 cost extra.",
+ "Only return results from these domains, e.g. \"techcrunch.com\". Leave empty for the whole web.": "Only return results from these domains, e.g. \"techcrunch.com\". Leave empty for the whole web.",
+ "Never return results from these domains.": "Never return results from these domains.",
+ "Add the full page text to each result.": "Add the full page text to each result.",
+ "Add the most relevant snippets from each page to each result.": "Add the most relevant snippets from each page to each result.",
+ "Optional name shown for this monitor in the Exa dashboard.": "Optional name shown for this monitor in the Exa dashboard.",
+ "Hour": "Hour",
+ "6 hours": "6 hours",
+ "Day": "Day",
+ "Week": "Week"
}
\ No newline at end of file
diff --git a/packages/pieces/community/exa/src/index.ts b/packages/pieces/community/exa/src/index.ts
index 0c24a73c726..3d21b1fa991 100644
--- a/packages/pieces/community/exa/src/index.ts
+++ b/packages/pieces/community/exa/src/index.ts
@@ -1,20 +1,25 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
import { getContentsAction } from './lib/actions/get-contents';
import { generateAnswerAction } from './lib/actions/generate-answer';
import { performSearchAction } from './lib/actions/perform-search';
import { findSimilarLinksAction } from './lib/actions/find-similar-links';
-import { createCustomApiCallAction, HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from './lib/common';
+import { createAgentRunAction } from './lib/actions/agent/create-agent-run';
+import { getAgentRunAction } from './lib/actions/agent/get-agent-run';
+import { listAgentRunsAction } from './lib/actions/agent/list-agent-runs';
+import { cancelAgentRunAction } from './lib/actions/agent/cancel-agent-run';
+import { exaSearchAction } from './lib/actions/ai/exa-search';
+import { exaGetContentsAction } from './lib/actions/ai/exa-get-contents';
+import { exaAnswerAction } from './lib/actions/ai/exa-answer';
+import { newSearchMonitorResultsTrigger } from './lib/triggers/new-search-monitor-results';
+import { exaCustomApiCallAction } from './lib/actions/custom-api-call';
import { exaAuth } from './lib/auth';
-const markdownDescription = `Obtain your API key from [Dashboard Setting](https://dashboard.exa.ai/api-keys).`;
-
export const exa = createPiece({
displayName: 'Exa',
description: 'AI-powered search and content extraction from the web.',
auth: exaAuth,
- minimumSupportedRelease: '0.36.1',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/exa.png',
categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE,PieceCategory.PRODUCTIVITY],
authors: ['krushnarout','kishanprmr'],
@@ -23,13 +28,14 @@ export const exa = createPiece({
generateAnswerAction,
performSearchAction,
findSimilarLinksAction,
- createCustomApiCallAction({
- auth:exaAuth,
- baseUrl: () => 'https://api.exa.ai',
- authMapping: async (auth) => ({
- 'x-api-key': `${auth}`,
- }),
- })
+ createAgentRunAction,
+ getAgentRunAction,
+ listAgentRunsAction,
+ cancelAgentRunAction,
+ exaSearchAction,
+ exaGetContentsAction,
+ exaAnswerAction,
+ exaCustomApiCallAction,
],
- triggers: [],
+ triggers: [newSearchMonitorResultsTrigger],
});
diff --git a/packages/pieces/community/exa/src/lib/actions/agent/cancel-agent-run.ts b/packages/pieces/community/exa/src/lib/actions/agent/cancel-agent-run.ts
new file mode 100644
index 00000000000..cf0dd169c55
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/agent/cancel-agent-run.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { AgentRun, agentRuns } from '../../common/agent';
+import { agentRunOutputSchema } from '../../output-schemas';
+
+export const cancelAgentRunAction = createAction({
+ name: 'exa_cancel_agent_run',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Cancel Agent Run',
+ description:
+ 'Cancels a queued or running Exa Agent run right away. The run returns no results, and usage so far is still billed.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Cancels a queued or running Exa Agent run immediately, discarding its results; usage accrued before the cancel is still billed. Use to stop spend on a run that is no longer needed; to read a finished run use exa_get_agent_run instead. Safe to retry: a run that already finished is returned unchanged.',
+ idempotent: true,
+ },
+ auth: exaAuth,
+ outputSchema: agentRunOutputSchema,
+ props: {
+ runId: Property.ShortText({
+ displayName: 'Run ID',
+ description:
+ 'The ID returned by Start Agent Run (or List Agent Runs), e.g. "agent_run_01k4d9w6y3h7p2m8".',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const runId = exaInput.requiredId({ value: context.propsValue.runId, name: 'Run ID' });
+ const run = await exaApi.call<AgentRun>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `/agent/runs/${encodeURIComponent(runId)}/cancel`,
+ });
+ return agentRuns.flattenRun(run);
+ },
+});
diff --git a/packages/pieces/community/exa/src/lib/actions/agent/create-agent-run.ts b/packages/pieces/community/exa/src/lib/actions/agent/create-agent-run.ts
new file mode 100644
index 00000000000..f0004cdc339
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/agent/create-agent-run.ts
@@ -0,0 +1,139 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { AgentRun, agentEfforts, agentRuns } from '../../common/agent';
+import { agentRunOutputSchema } from '../../output-schemas';
+
+export const createAgentRunAction = createAction({
+ name: 'exa_create_agent_run',
+ classification: 'WRITE',
+ displayName: 'Start Agent Run',
+ description:
+ 'Starts an Exa Agent run for deep research, list building or structured extraction. The run works in the background; use Get Agent Run to read the result.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Starts an asynchronous Exa Agent run that researches a natural-language task on the web and can return JSON shaped by an optional output schema. Use for multi-step research or list building that a single search cannot answer; it returns right away with the run id and a queued or running status, so poll exa_get_agent_run until status is completed, failed or cancelled. Effort sets the price (minimal $0.012 to xhigh $1.00; auto and ultra are metered up to $5/$20), defaulting to low. Not idempotent: each call starts and bills a new run.',
+ idempotent: false,
+ },
+ auth: exaAuth,
+ outputSchema: agentRunOutputSchema,
+ props: {
+ query: Property.LongText({
+ displayName: 'Task',
+ description:
+ 'What the agent should research or build, in plain language. Example: "List 10 Series A climate-tech startups in Europe founded after 2022, with their website and lead investor."',
+ required: true,
+ }),
+ effort: Property.StaticDropdown({
+ displayName: 'Effort',
+ description:
+ 'How hard the agent works, which sets the price per run. Minimal to Extra High are fixed prices. Auto and Ultra are metered by usage and can cost up to $5 and $20 per run unless you set Max Cost. Defaults to Low.',
+ required: false,
+ defaultValue: agentEfforts.DEFAULT,
+ options: { options: agentEfforts.OPTIONS },
+ }),
+ systemPrompt: Property.LongText({
+ displayName: 'Instructions',
+ description:
+ 'Extra guidance for the agent, such as preferred sources or rules like "only use official company websites".',
+ required: false,
+ }),
+ outputSchema: Property.Json({
+ displayName: 'Output Schema',
+ description:
+ 'Optional JSON Schema for a structured result, returned in Structured Output. Example: {"type":"object","properties":{"companies":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"website":{"type":"string"}}}}}}',
+ required: false,
+ }),
+ maxCostDollars: Property.Number({
+ displayName: 'Max Cost (USD)',
+ description:
+ 'Spending cap for one run, between 1 and 100. Only applies when Effort is Auto or Ultra; fixed efforts already have a fixed price.',
+ required: false,
+ }),
+ previousRunId: Property.ShortText({
+ displayName: 'Previous Run ID',
+ description:
+ 'Continue from an earlier run so the agent builds on its findings. Use the ID returned by Start Agent Run, e.g. "agent_run_01k4d9w6y3h7p2m8".',
+ required: false,
+ }),
+ metadata: Property.Object({
+ displayName: 'Metadata',
+ description: 'Optional key-value labels stored with the run, e.g. {"flow": "lead-research"}.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { query, systemPrompt, previousRunId, metadata } = context.propsValue;
+ const effort = effortOf(context.propsValue.effort);
+ const maxCostDollars = exaInput.optionalNumber({
+ value: context.propsValue.maxCostDollars,
+ name: 'Max Cost (USD)',
+ min: 1,
+ max: 100,
+ });
+ if (maxCostDollars !== undefined && !agentEfforts.METERED.includes(effort)) {
+ throw new Error('Max Cost only applies when Effort is Auto or Ultra. Clear it or change the effort.');
+ }
+ const outputSchema = schemaOf(context.propsValue.outputSchema);
+ const metadataValues = metadataOf(metadata);
+ const instructions = exaInput.optionalText(systemPrompt);
+ const previous = exaInput.optionalText(previousRunId);
+
+ const body = {
+ query,
+ effort,
+ ...(instructions ? { systemPrompt: instructions } : {}),
+ ...(outputSchema ? { outputSchema } : {}),
+ ...(maxCostDollars !== undefined ? { budget: { maxCostDollars } } : {}),
+ ...(previous ? { previousRunId: previous } : {}),
+ ...(metadataValues ? { metadata: metadataValues } : {}),
+ };
+
+ const run = await exaApi.call<AgentRun>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/agent/runs',
+ body,
+ });
+ return agentRuns.flattenRun(run);
+ },
+});
+
+function effortOf(value: unknown): string {
+ const effort = exaInput.optionalText(value) ?? agentEfforts.DEFAULT;
+ if (!agentEfforts.ALL.includes(effort)) {
+ throw new Error(`Effort must be one of: ${agentEfforts.ALL.join(', ')}.`);
+ }
+ return effort;
+}
+
+function schemaOf(value: unknown): Record<string, unknown> | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed: unknown = typeof value === 'string' ? parseJson(value) : value;
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ throw new Error('Output Schema must be a JSON Schema object, e.g. {"type":"object","properties":{...}}.');
+ }
+ return Object.fromEntries(Object.entries(parsed));
+}
+
+function parseJson(text: string): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error('Output Schema is not valid JSON.');
+ }
+}
+
+function metadataOf(value: unknown): Record<string, string> | undefined {
+ if (typeof value !== 'object' || value === null) {
+ return undefined;
+ }
+ const entries = Object.entries(value)
+ .filter(([, v]) => v !== undefined && v !== null && v !== '')
+ .map(([k, v]) => [k, typeof v === 'string' ? v : JSON.stringify(v)]);
+ return entries.length === 0 ? undefined : Object.fromEntries(entries);
+}
diff --git a/packages/pieces/community/exa/src/lib/actions/agent/get-agent-run.ts b/packages/pieces/community/exa/src/lib/actions/agent/get-agent-run.ts
new file mode 100644
index 00000000000..d0e83c9e5cb
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/agent/get-agent-run.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { AgentRun, agentRuns } from '../../common/agent';
+import { agentRunOutputSchema } from '../../output-schemas';
+
+export const getAgentRunAction = createAction({
+ name: 'exa_get_agent_run',
+ classification: 'READ',
+ displayName: 'Get Agent Run',
+ description:
+ 'Gets the status and result of an Exa Agent run. Use it after Start Agent Run, for example behind a Delay step.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads one Exa Agent run by id and returns its status (queued, running, completed, failed, cancelled), the text answer, the structured output when a schema was given, flattened citations and the cost. Use to poll a run started with exa_create_agent_run; it is a single read, so call it again while status is queued or running. Read-only and idempotent.',
+ idempotent: true,
+ },
+ auth: exaAuth,
+ outputSchema: agentRunOutputSchema,
+ props: {
+ runId: Property.ShortText({
+ displayName: 'Run ID',
+ description:
+ 'The ID returned by Start Agent Run (or List Agent Runs), e.g. "agent_run_01k4d9w6y3h7p2m8".',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const runId = exaInput.requiredId({ value: context.propsValue.runId, name: 'Run ID' });
+ const run = await exaApi.call<AgentRun>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/agent/runs/${encodeURIComponent(runId)}`,
+ });
+ return agentRuns.flattenRun(run);
+ },
+});
diff --git a/packages/pieces/community/exa/src/lib/actions/agent/list-agent-runs.ts b/packages/pieces/community/exa/src/lib/actions/agent/list-agent-runs.ts
new file mode 100644
index 00000000000..83fa785a005
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/agent/list-agent-runs.ts
@@ -0,0 +1,59 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { AgentRunList, agentRuns } from '../../common/agent';
+import { agentRunListOutputSchema } from '../../output-schemas';
+
+export const listAgentRunsAction = createAction({
+ name: 'exa_list_agent_runs',
+ classification: 'SEARCH',
+ displayName: 'List Agent Runs',
+ description: 'Lists your team\'s Exa Agent runs, newest first, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the team\'s Exa Agent runs newest first, returning id, status, query, effort and cost per run plus has_more and next_cursor for paging. Use to find an earlier run id when it was not kept; to read one run\'s full result use exa_get_agent_run. Returns one page only, so pass next_cursor as Cursor to continue. Read-only and idempotent.',
+ idempotent: true,
+ },
+ auth: exaAuth,
+ outputSchema: agentRunListOutputSchema,
+ props: {
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'How many runs to return in this page, 1 to 100. Defaults to 20.',
+ required: false,
+ defaultValue: 20,
+ }),
+ cursor: Property.ShortText({
+ displayName: 'Cursor',
+ description: 'Leave empty for the first page. To get the next page, paste the Next Cursor value from the previous result.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const limit = exaInput.optionalInteger({
+ value: context.propsValue.limit,
+ name: 'Limit',
+ min: 1,
+ max: 100,
+ });
+ const cursor = exaInput.optionalText(context.propsValue.cursor);
+ const page = await exaApi.call<AgentRunList>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/agent/runs',
+ query: {
+ ...(limit !== undefined ? { limit: String(limit) } : {}),
+ ...(cursor ? { cursor } : {}),
+ },
+ });
+ const runs = (page.data ?? []).map((run) => agentRuns.summarizeRun(run));
+ return {
+ runs,
+ count: runs.length,
+ has_more: page.hasMore ?? false,
+ next_cursor: page.nextCursor ?? null,
+ };
+ },
+});
diff --git a/packages/pieces/community/exa/src/lib/actions/ai/exa-answer.ts b/packages/pieces/community/exa/src/lib/actions/ai/exa-answer.ts
new file mode 100644
index 00000000000..dad4dc199e3
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/ai/exa-answer.ts
@@ -0,0 +1,99 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { ExaCost, ExaResult } from '../../common/results';
+import { exaAnswerOutputSchema } from '../../output-schemas-ai';
+
+export const exaAnswerAction = createAction({
+ name: 'exa_answer',
+ classification: 'READ',
+ displayName: 'Answer a Question',
+ description: 'Answers a question from live web results and returns the sources it used.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Answers a natural-language question from a live Exa web search and returns the answer text with the cited source pages. Use for a quick factual answer with sources in one call ($0.005); use exa_search to get the pages themselves or exa_create_agent_run for multi-step research. Read-only and idempotent, though wording can vary between calls as web data changes.',
+ idempotent: true,
+ },
+ auth: exaAuth,
+ outputSchema: exaAnswerOutputSchema,
+ props: {
+ query: Property.LongText({
+ displayName: 'Question',
+ description: 'The question to answer, e.g. "What is the latest stable version of Node.js?".',
+ required: true,
+ }),
+ model: Property.StaticDropdown({
+ displayName: 'Model',
+ description: "'exa' (default), 'exa-pro' for harder questions, or 'exa-fast' for lower latency.",
+ required: false,
+ defaultValue: 'exa',
+ options: {
+ options: [
+ { label: 'Exa', value: 'exa' },
+ { label: 'Exa Pro', value: 'exa-pro' },
+ { label: 'Exa Fast', value: 'exa-fast' },
+ ],
+ },
+ }),
+ systemPrompt: Property.LongText({
+ displayName: 'Instructions',
+ description: 'Optional guidance for the answer, e.g. "Answer in two sentences and cite official sources only."',
+ required: false,
+ }),
+ userLocation: Property.ShortText({
+ displayName: 'User Country',
+ description: 'Two-letter ISO country code to localize the search, e.g. "US".',
+ required: false,
+ }),
+ includeSourceText: Property.Checkbox({
+ displayName: 'Include Source Text',
+ description: 'Also return the full text of each cited page.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const props = context.propsValue;
+ const systemPrompt = exaInput.optionalText(props.systemPrompt);
+ const userLocation = exaInput.optionalCountry({ value: props.userLocation, name: 'User Country' });
+ const model = exaInput.optionalText(props.model) ?? 'exa';
+ if (!ANSWER_MODELS.includes(model)) {
+ throw new Error(`Model must be one of: ${ANSWER_MODELS.join(', ')}.`);
+ }
+ const response = await exaApi.call<{ answer?: unknown; citations?: ExaResult[]; costDollars?: ExaCost }>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/answer',
+ body: {
+ query: props.query,
+ model,
+ text: props.includeSourceText === true,
+ ...(systemPrompt ? { systemPrompt } : {}),
+ ...(userLocation ? { userLocation } : {}),
+ },
+ });
+ return {
+ answer: answerTextOf(response.answer),
+ citations: (response.citations ?? []).map((citation) => ({
+ id: citation.id ?? null,
+ title: citation.title ?? null,
+ url: citation.url ?? null,
+ published_date: citation.publishedDate ?? null,
+ author: citation.author ?? null,
+ text: citation.text ?? null,
+ })),
+ cost_total: response.costDollars?.total ?? null,
+ };
+ },
+});
+
+function answerTextOf(answer: unknown): string | null {
+ if (typeof answer === 'string') {
+ return answer;
+ }
+ return answer === undefined || answer === null ? null : JSON.stringify(answer);
+}
+
+const ANSWER_MODELS: readonly string[] = ['exa', 'exa-pro', 'exa-fast'];
diff --git a/packages/pieces/community/exa/src/lib/actions/ai/exa-get-contents.ts b/packages/pieces/community/exa/src/lib/actions/ai/exa-get-contents.ts
new file mode 100644
index 00000000000..330c42afa23
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/ai/exa-get-contents.ts
@@ -0,0 +1,136 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { ExaCost, ExaResult, ExaStatus, exaResults } from '../../common/results';
+import { exaGetContentsOutputSchema } from '../../output-schemas-ai';
+
+export const exaGetContentsAction = createAction({
+ name: 'exa_get_contents',
+ classification: 'READ',
+ displayName: 'Get Page Contents',
+ description: 'Fetches clean content for known URLs and reports which URLs failed.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Fetches clean page text, and optionally highlights, a question-guided summary, outgoing links and matching subpages, for URLs you already have, and reports a per-URL status so failed fetches are visible (the call still succeeds when some URLs fail). Use after exa_search or when given URLs; use exa_search to discover pages. Billed $0.001 per page per content type. Read-only and idempotent.',
+ idempotent: true,
+ },
+ auth: exaAuth,
+ outputSchema: exaGetContentsOutputSchema,
+ props: {
+ urls: Property.Array({
+ displayName: 'URLs',
+ description: 'Full URLs to fetch, including https://, e.g. "https://exa.ai/docs". Up to 100.',
+ required: true,
+ }),
+ includeText: Property.Checkbox({
+ displayName: 'Include Page Text',
+ description: 'Return the page text.',
+ required: false,
+ defaultValue: true,
+ }),
+ textMaxCharacters: Property.Number({
+ displayName: 'Max Text Characters',
+ description: 'Cap the text per page, e.g. 5000. Only used when page text is included.',
+ required: false,
+ }),
+ includeHighlights: Property.Checkbox({
+ displayName: 'Include Highlights',
+ description: 'Return the most relevant snippets from each page.',
+ required: false,
+ defaultValue: false,
+ }),
+ highlightsQuery: Property.ShortText({
+ displayName: 'Highlights Focus',
+ description: 'Optional question that steers which snippets are picked. Turns highlights on.',
+ required: false,
+ }),
+ summaryQuery: Property.ShortText({
+ displayName: 'Summary Question',
+ description: 'Return a per-page AI summary focused on this question, e.g. "Who are the founders?".',
+ required: false,
+ }),
+ maxAgeHours: Property.Number({
+ displayName: 'Max Content Age (hours)',
+ description: 'Use cached content only if newer than this many hours; 0 always fetches fresh, -1 always uses cache, max 720.',
+ required: false,
+ }),
+ subpages: Property.Number({
+ displayName: 'Subpages',
+ description: 'Also fetch up to this many linked subpages per URL, e.g. 3.',
+ required: false,
+ }),
+ subpageTarget: Property.ShortText({
+ displayName: 'Subpage Keyword',
+ description: 'Prefer subpages matching this keyword, e.g. "pricing" or "about".',
+ required: false,
+ }),
+ linksPerPage: Property.Number({
+ displayName: 'Links per Page',
+ description: 'Also return up to this many links found on each page.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const props = context.propsValue;
+ const listed = exaInput.stringList(props.urls);
+ const urls = listed ? [...new Set(listed)] : undefined;
+ if (!urls) {
+ throw new Error('Provide at least one URL.');
+ }
+ if (urls.length > MAX_URLS) {
+ throw new Error(`Provide at most ${MAX_URLS} URLs per call; ${urls.length} were given.`);
+ }
+ const textMaxCharacters = exaInput.optionalInteger({ value: props.textMaxCharacters, name: 'Max Text Characters', min: 1, max: 1000000 });
+ const maxAgeHours = exaInput.optionalInteger({ value: props.maxAgeHours, name: 'Max Content Age (hours)', min: -1, max: 720 });
+ const subpages = exaInput.optionalInteger({ value: props.subpages, name: 'Subpages', min: 1, max: 100 });
+ const linksPerPage = exaInput.optionalInteger({ value: props.linksPerPage, name: 'Links per Page', min: 1, max: 1000 });
+ const highlightsQuery = exaInput.optionalText(props.highlightsQuery);
+ const summaryQuery = exaInput.optionalText(props.summaryQuery);
+ const subpageTarget = exaInput.optionalText(props.subpageTarget);
+ const includeText = props.includeText !== false;
+ if (!includeText && !highlightsQuery && !props.includeHighlights && !summaryQuery && linksPerPage === undefined) {
+ throw new Error('Choose at least one thing to return: page text, highlights, a summary question or links per page.');
+ }
+
+ const response = await exaApi.call<{ results?: ExaResult[]; statuses?: ExaStatus[]; costDollars?: ExaCost }>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/contents',
+ body: {
+ urls,
+ text: includeText
+ ? textMaxCharacters !== undefined
+ ? { maxCharacters: textMaxCharacters }
+ : true
+ : false,
+ ...(highlightsQuery
+ ? { highlights: { query: highlightsQuery } }
+ : props.includeHighlights
+ ? { highlights: true }
+ : {}),
+ ...(summaryQuery ? { summary: { query: summaryQuery } } : {}),
+ ...(maxAgeHours !== undefined ? { maxAgeHours } : {}),
+ ...(subpages !== undefined ? { subpages } : {}),
+ ...(subpageTarget ? { subpageTarget } : {}),
+ ...(linksPerPage !== undefined ? { extras: { links: linksPerPage } } : {}),
+ },
+ });
+ const statuses = (response.statuses ?? []).map(exaResults.flattenStatus);
+ const results = (response.results ?? []).map(exaResults.flattenPage);
+ const fetched = new Set(
+ statuses.length > 0
+ ? statuses.filter((status) => status.status === 'success').map((status) => status.url)
+ : results.flatMap((result) => [result.id, result.url].filter((value): value is string => value !== null)),
+ );
+ return {
+ results,
+ statuses,
+ failed_count: urls.filter((url) => !fetched.has(url)).length,
+ cost_total: response.costDollars?.total ?? null,
+ };
+ },
+});
+
+const MAX_URLS = 100;
diff --git a/packages/pieces/community/exa/src/lib/actions/ai/exa-search.ts b/packages/pieces/community/exa/src/lib/actions/ai/exa-search.ts
new file mode 100644
index 00000000000..42e46dc8f51
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/ai/exa-search.ts
@@ -0,0 +1,186 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../../auth';
+import { exaApi, exaInput } from '../../common/client';
+import { ExaCost, ExaResult, exaResults } from '../../common/results';
+import { exaSearchOutputSchema } from '../../output-schemas-ai';
+
+export const exaSearchAction = createAction({
+ name: 'exa_search',
+ classification: 'SEARCH',
+ displayName: 'Search the Web',
+ description: 'Searches the web with Exa and returns flat result rows.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Searches the live web with Exa and returns ranked pages with title, URL, date and optionally page text, highlights or a query-guided summary. Use to discover pages for a topic; use exa_get_contents when the URLs are already known and exa_answer for a direct cited answer. Type sets depth and price (instant $0.004, auto/fast $0.007, deep modes $0.012 to $0.015); the company and people categories reject published-date filters and excludeDomains. Read-only and idempotent.',
+ idempotent: true,
+ },
+ auth: exaAuth,
+ outputSchema: exaSearchOutputSchema,
+ props: {
+ query: Property.LongText({
+ displayName: 'Query',
+ description: 'What to search for, in natural language, e.g. "latest research on solid-state batteries".',
+ required: true,
+ }),
+ type: Property.StaticDropdown({
+ displayName: 'Search Type',
+ description: "One of 'auto' (default), 'fast', 'instant', 'deep-lite', 'deep', 'deep-reasoning'. Deep modes are slower and cost more.",
+ required: false,
+ defaultValue: 'auto',
+ options: {
+ options: [
+ { label: 'Auto', value: 'auto' },
+ { label: 'Fast', value: 'fast' },
+ { label: 'Instant', value: 'instant' },
+ { label: 'Deep Lite', value: 'deep-lite' },
+ { label: 'Deep', value: 'deep' },
+ { label: 'Deep Reasoning', value: 'deep-reasoning' },
+ ],
+ },
+ }),
+ category: Property.StaticDropdown({
+ displayName: 'Category',
+ description: "Optional focus: 'company', 'people', 'news', 'publication', 'personal site' or 'financial report'.",
+ required: false,
+ options: {
+ options: [
+ { label: 'Company', value: 'company' },
+ { label: 'People', value: 'people' },
+ { label: 'News', value: 'news' },
+ { label: 'Publication', value: 'publication' },
+ { label: 'Personal Site', value: 'personal site' },
+ { label: 'Financial Report', value: 'financial report' },
+ ],
+ },
+ }),
+ numResults: Property.Number({
+ displayName: 'Number of Results',
+ description: 'How many results to return, 1 to 100. Defaults to 10; each result above 10 costs $0.001.',
+ required: false,
+ defaultValue: 10,
+ }),
+ includeDomains: Property.Array({
+ displayName: 'Include Domains',
+ description: 'Only return results from these domains or paths, e.g. "arxiv.org" or "example.com/blog".',
+ required: false,
+ }),
+ excludeDomains: Property.Array({
+ displayName: 'Exclude Domains',
+ description: 'Never return results from these domains. Not allowed with the company or people category.',
+ required: false,
+ }),
+ startPublishedDate: Property.DateTime({
+ displayName: 'Published After',
+ description: 'Only results published after this ISO 8601 date, e.g. "2026-01-01T00:00:00Z". Not allowed with the company or people category.',
+ required: false,
+ }),
+ endPublishedDate: Property.DateTime({
+ displayName: 'Published Before',
+ description: 'Only results published before this ISO 8601 date. Not allowed with the company or people category.',
+ required: false,
+ }),
+ includeText: Property.Checkbox({
+ displayName: 'Include Page Text',
+ description: 'Return the page text for each result.',
+ required: false,
+ defaultValue: true,
+ }),
+ textMaxCharacters: Property.Number({
+ displayName: 'Max Text Characters',
+ description: 'Cap the page text per result, e.g. 2000. Only used when page text is included.',
+ required: false,
+ }),
+ includeHighlights: Property.Checkbox({
+ displayName: 'Include Highlights',
+ description: 'Return the most relevant snippets from each page.',
+ required: false,
+ defaultValue: false,
+ }),
+ highlightsQuery: Property.ShortText({
+ displayName: 'Highlights Focus',
+ description: 'Optional question that steers which snippets are picked. Turns highlights on.',
+ required: false,
+ }),
+ summaryQuery: Property.ShortText({
+ displayName: 'Summary Question',
+ description: 'Return a per-page AI summary focused on this question, e.g. "What does this company sell?" ($0.001 per page).',
+ required: false,
+ }),
+ maxAgeHours: Property.Number({
+ displayName: 'Max Content Age (hours)',
+ description: 'Use cached content only if newer than this many hours; 0 always fetches fresh, -1 always uses cache, max 720.',
+ required: false,
+ }),
+ userLocation: Property.ShortText({
+ displayName: 'User Country',
+ description: 'Two-letter ISO country code to localize results, e.g. "US".',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const props = context.propsValue;
+ const numResults = exaInput.optionalInteger({ value: props.numResults, name: 'Number of Results', min: 1, max: 100 });
+ const textMaxCharacters = exaInput.optionalInteger({ value: props.textMaxCharacters, name: 'Max Text Characters', min: 1, max: 1000000 });
+ const maxAgeHours = exaInput.optionalInteger({ value: props.maxAgeHours, name: 'Max Content Age (hours)', min: -1, max: 720 });
+ const includeDomains = exaInput.stringList(props.includeDomains);
+ const excludeDomains = exaInput.stringList(props.excludeDomains);
+ const type = exaInput.optionalText(props.type) ?? 'auto';
+ if (!SEARCH_TYPES.includes(type)) {
+ throw new Error(`Search Type must be one of: ${SEARCH_TYPES.join(', ')}.`);
+ }
+ const category = exaInput.optionalText(props.category);
+ const highlightsQuery = exaInput.optionalText(props.highlightsQuery);
+ const summaryQuery = exaInput.optionalText(props.summaryQuery);
+ const userLocation = exaInput.optionalCountry({ value: props.userLocation, name: 'User Country' });
+ const startPublishedDate = exaInput.optionalText(props.startPublishedDate);
+ const endPublishedDate = exaInput.optionalText(props.endPublishedDate);
+
+ if (category === 'company' || category === 'people') {
+ if (startPublishedDate || endPublishedDate || excludeDomains) {
+ throw new Error(`The ${category} category does not support published-date filters or Exclude Domains.`);
+ }
+ }
+
+ const includeText = props.includeText !== false;
+ const contents = {
+ ...(includeText
+ ? { text: textMaxCharacters !== undefined ? { maxCharacters: textMaxCharacters } : true }
+ : {}),
+ ...(highlightsQuery
+ ? { highlights: { query: highlightsQuery } }
+ : props.includeHighlights
+ ? { highlights: true }
+ : {}),
+ ...(summaryQuery ? { summary: { query: summaryQuery } } : {}),
+ ...(maxAgeHours !== undefined ? { maxAgeHours } : {}),
+ };
+
+ const response = await exaApi.call<{ results?: ExaResult[]; costDollars?: ExaCost }>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/search',
+ body: {
+ query: props.query,
+ type,
+ ...(category ? { category } : {}),
+ ...(numResults !== undefined ? { numResults } : {}),
+ ...(includeDomains ? { includeDomains } : {}),
+ ...(excludeDomains ? { excludeDomains } : {}),
+ ...(startPublishedDate ? { startPublishedDate } : {}),
+ ...(endPublishedDate ? { endPublishedDate } : {}),
+ ...(userLocation ? { userLocation } : {}),
+ ...(Object.keys(contents).length > 0 ? { contents } : {}),
+ },
+ });
+ const results = (response.results ?? []).map(exaResults.flattenResult);
+ return {
+ results,
+ count: results.length,
+ cost_total: response.costDollars?.total ?? null,
+ };
+ },
+});
+
+const SEARCH_TYPES: readonly string[] = ['auto', 'fast', 'instant', 'deep-lite', 'deep', 'deep-reasoning'];
diff --git a/packages/pieces/community/exa/src/lib/actions/custom-api-call.ts b/packages/pieces/community/exa/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..4740139be60
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
+import { exaAuth } from '../auth';
+import { BASE_URL, exaApi } from '../common/client';
+
+const baseAction = createCustomApiCallAction({
+ auth: exaAuth,
+ baseUrl: () => BASE_URL,
+ authMapping: async (auth, propsValue) => {
+ exaApi.assertExaUrl(propsValue['url']?.['url']);
+ if (propsValue['followRedirects'] === true) {
+ throw new Error('Follow redirects is not supported for Exa: a redirect could carry your API key to another host.');
+ }
+ return { 'x-api-key': auth.secret_text };
+ },
+});
+
+export const exaCustomApiCallAction = createAction({
+ auth: exaAuth,
+ name: 'custom_api_call',
+ displayName: 'Custom API Call',
+ description: 'Make a custom API call to a specific endpoint',
+ props: baseAction.props,
+ requireAuth: baseAction.requireAuth,
+ errorHandlingOptions: baseAction.errorHandlingOptions,
+ audience: 'human',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Sends an authenticated request to any Exa API path on https://api.exa.ai, for endpoints the other Exa actions do not cover. Takes a relative path or a full api.exa.ai URL, a method, headers, query parameters and an optional body, and returns the HTTP status, headers and body. Not idempotent in general: POST and DELETE change Exa state.',
+ idempotent: false,
+ },
+ run: async (context) =>
+ baseAction.run({
+ ...context,
+ propsValue: { ...context.propsValue, followRedirects: context.propsValue.followRedirects ?? false },
+ }),
+});
diff --git a/packages/pieces/community/exa/src/lib/actions/find-similar-links.ts b/packages/pieces/community/exa/src/lib/actions/find-similar-links.ts
index a380d9adb1c..778d4215fc2 100644
--- a/packages/pieces/community/exa/src/lib/actions/find-similar-links.ts
+++ b/packages/pieces/community/exa/src/lib/actions/find-similar-links.ts
@@ -2,18 +2,20 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { makeRequest } from '../common';
import { exaAuth } from '../auth';
+import { similarLinksOutputSchema } from '../output-schemas';
export const findSimilarLinksAction = createAction({
name: 'find_similar_links',
classification: 'SEARCH',
displayName: 'Find Similar Links',
description: 'Find pages similar to a given URL.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description: 'Finds web pages semantically similar to a single reference URL via Exa. Use when an agent has one example page and wants more of the same kind rather than searching by a text query; results can be narrowed by domain include/exclude lists, crawl/publish date ranges, and required/forbidden text. Requires a reference URL. Read-only and idempotent.',
idempotent: true,
},
auth: exaAuth,
+ outputSchema: similarLinksOutputSchema,
props: {
url: Property.ShortText({
displayName: 'URL',
diff --git a/packages/pieces/community/exa/src/lib/actions/generate-answer.ts b/packages/pieces/community/exa/src/lib/actions/generate-answer.ts
index 936368edcb9..3afb961fd50 100644
--- a/packages/pieces/community/exa/src/lib/actions/generate-answer.ts
+++ b/packages/pieces/community/exa/src/lib/actions/generate-answer.ts
@@ -2,15 +2,16 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { makeRequest } from '../common';
import { exaAuth } from '../auth';
+import { exaInput } from '../common/client';
export const generateAnswerAction = createAction({
name: 'generate_answer',
classification: 'READ',
displayName: 'Ask AI',
description: 'Provides direct answers to queries by summarizing results.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
- description: 'Asks Exa a natural-language question and returns a synthesized answer grounded in live web search results. Use when an agent wants a direct factual answer rather than a list of links to triage itself; choose the exa or exa-pro model. Requires a query string. Read-only lookup; repeating the same query is safe though phrasing and live web data may vary the wording.',
+ description: 'Asks Exa a natural-language question and returns a synthesized answer grounded in live web search results. Use when an agent wants a direct factual answer rather than a list of links to triage itself; choose the exa, exa-pro or exa-fast model and optionally add instructions or a country. Requires a query string. Read-only lookup; repeating the same query is safe though phrasing and live web data may vary the wording.',
idempotent: true,
},
auth: exaAuth,
@@ -34,10 +35,21 @@ export const generateAnswerAction = createAction({
options: [
{ label: 'Exa', value: 'exa' },
{ label: 'Exa Pro', value: 'exa-pro' },
+ { label: 'Exa Fast', value: 'exa-fast' },
],
},
defaultValue: 'exa',
}),
+ systemPrompt: Property.LongText({
+ displayName: 'Instructions',
+ description: 'Extra guidance for the answer, such as tone, length or preferred sources, e.g. "Answer in two sentences and prefer official sources."',
+ required: false,
+ }),
+ userLocation: Property.ShortText({
+ displayName: 'User Country',
+ description: 'Two-letter country code to localize the search behind the answer, e.g. "US".',
+ required: false,
+ }),
},
async run(context) {
const apiKey = context.auth.secret_text;
@@ -48,10 +60,15 @@ export const generateAnswerAction = createAction({
model,
} = context.propsValue;
+ const systemPrompt = exaInput.optionalText(context.propsValue.systemPrompt);
+ const userLocation = exaInput.optionalCountry({ value: context.propsValue.userLocation, name: 'User Country' });
+
const body: Record<string, unknown> = {
query,
text,
- model
+ model,
+ ...(systemPrompt ? { systemPrompt } : {}),
+ ...(userLocation ? { userLocation } : {}),
};
diff --git a/packages/pieces/community/exa/src/lib/actions/get-contents.ts b/packages/pieces/community/exa/src/lib/actions/get-contents.ts
index cc2c429a234..65884d70aa3 100644
--- a/packages/pieces/community/exa/src/lib/actions/get-contents.ts
+++ b/packages/pieces/community/exa/src/lib/actions/get-contents.ts
@@ -2,18 +2,21 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { makeRequest } from '../common';
import { exaAuth } from '../auth';
+import { exaInput } from '../common/client';
+import { contentsResultsOutputSchema } from '../output-schemas';
export const getContentsAction = createAction({
name: 'get_contents',
classification: 'READ',
displayName: 'Get Contents',
description: 'Retrieve clean HTML content from specified URLs.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
- description: 'Crawls and extracts clean page content (and optionally full text) from a given list of URLs via Exa. Use when an agent already has specific URLs and needs their on-page content rather than running a web search; optionally fetch matching subpages by keyword. Requires an array of URLs as input. Read-only and idempotent.',
+ description: 'Crawls and extracts clean page content (and optionally full text, highlights, a guided summary and outgoing links) from a given list of URLs via Exa. Use when an agent already has specific URLs and needs their on-page content rather than running a web search; optionally fetch matching subpages by keyword and control cache freshness. Requires an array of URLs as input. Read-only and idempotent.',
idempotent: true,
},
auth: exaAuth,
+ outputSchema: contentsResultsOutputSchema,
props: {
urls: Property.Array({
displayName: 'URLs',
@@ -28,7 +31,7 @@ export const getContentsAction = createAction({
}),
livecrawl: Property.StaticDropdown({
displayName: 'Livecrawl Option',
- description: 'Options for livecrawling pages.',
+ description: 'Deprecated by Exa: prefer Max Content Age. Ignored when Max Content Age is set.',
required: false,
options: {
options: [
@@ -54,6 +57,27 @@ export const getContentsAction = createAction({
description: 'Keyword(s) to find specific subpages.',
required: false,
}),
+ highlights: Property.Checkbox({
+ displayName: 'Include Highlights',
+ description: 'Also return the most relevant snippets from each page (billed as an extra content type).',
+ required: false,
+ defaultValue: false,
+ }),
+ summaryQuery: Property.ShortText({
+ displayName: 'Summary Question',
+ description: 'Ask for an AI summary of each page focused on this question, e.g. "What does this company sell?" (billed per page).',
+ required: false,
+ }),
+ maxAgeHours: Property.Number({
+ displayName: 'Max Content Age (hours)',
+ description: 'Use cached content only if it is newer than this many hours (0 always fetches fresh, -1 always uses cache, up to 720). Replaces Livecrawl Option.',
+ required: false,
+ }),
+ extrasLinks: Property.Number({
+ displayName: 'Links per Page',
+ description: 'Also return up to this many links found on each page, e.g. 10.',
+ required: false,
+ }),
},
async run(context) {
const apiKey = context.auth.secret_text;
@@ -62,8 +86,26 @@ export const getContentsAction = createAction({
urls: context.propsValue.urls,
};
+ const maxAgeHours = exaInput.optionalInteger({
+ value: context.propsValue.maxAgeHours,
+ name: 'Max Content Age (hours)',
+ min: -1,
+ max: 720,
+ });
+ const extrasLinks = exaInput.optionalInteger({
+ value: context.propsValue.extrasLinks,
+ name: 'Links per Page',
+ min: 1,
+ max: 1000,
+ });
+ const summaryQuery = exaInput.optionalText(context.propsValue.summaryQuery);
+
if (context.propsValue.text !== undefined) body['text'] = context.propsValue.text;
- if (context.propsValue.livecrawl) body['livecrawl'] = context.propsValue.livecrawl;
+ if (maxAgeHours !== undefined) body['maxAgeHours'] = maxAgeHours;
+ else if (context.propsValue.livecrawl) body['livecrawl'] = context.propsValue.livecrawl;
+ if (context.propsValue.highlights) body['highlights'] = true;
+ if (summaryQuery) body['summary'] = { query: summaryQuery };
+ if (extrasLinks !== undefined) body['extras'] = { links: extrasLinks };
if (context.propsValue.livecrawlTimeout !== undefined) body['livecrawlTimeout'] = context.propsValue.livecrawlTimeout;
if (context.propsValue.subpages !== undefined) body['subpages'] = context.propsValue.subpages;
if (context.propsValue.subpageTarget) body['subpageTarget'] = context.propsValue.subpageTarget;
diff --git a/packages/pieces/community/exa/src/lib/actions/perform-search.ts b/packages/pieces/community/exa/src/lib/actions/perform-search.ts
index a8384478f50..5e8698e57a5 100644
--- a/packages/pieces/community/exa/src/lib/actions/perform-search.ts
+++ b/packages/pieces/community/exa/src/lib/actions/perform-search.ts
@@ -2,18 +2,21 @@ import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { makeRequest } from '../common';
import { exaAuth } from '../auth';
+import { exaInput } from '../common/client';
+import { searchResultsOutputSchema } from '../output-schemas';
export const performSearchAction = createAction({
name: 'perform_search',
classification: 'SEARCH',
displayName: 'Perform Search',
description: "Search the web using semantic or keyword-based search.",
- audience: 'both',
+ audience: 'human',
aiMetadata: {
- description: 'Runs a web search through Exa and returns matching results with page text. Use when an agent needs to discover relevant URLs/content for a query; the search type can be auto, neural (semantic), or keyword, and results can be narrowed by category, domain include/exclude lists, crawl/publish date ranges, and required/forbidden text. Requires a query string. Read-only and idempotent.',
+ description: 'Runs a web search through Exa and returns matching results with page text. Use when an agent needs to discover relevant URLs/content for a query; the search type ranges from instant and fast to auto and the deep research modes, and results can be narrowed by category, domain include/exclude lists, publish date range, and country, optionally adding highlights. Requires a query string. Read-only and idempotent.',
idempotent: true,
},
auth: exaAuth,
+ outputSchema: searchResultsOutputSchema,
props: {
query: Property.ShortText({
displayName: 'Query',
@@ -22,20 +25,25 @@ export const performSearchAction = createAction({
}),
type: Property.StaticDropdown({
displayName: 'Search Type',
- description: 'Type of search to perform.',
+ description: 'Type of search to perform. Auto suits most searches; Instant and Fast trade depth for speed; Deep Lite, Deep and Deep Reasoning research more and cost more ($0.012 to $0.015 per search). Keyword and Neural are legacy options that Exa no longer documents.',
required: false,
defaultValue: 'auto',
options: {
options: [
{ label: 'Auto', value: 'auto' },
- { label: 'Keyword', value: 'keyword' },
- { label: 'Neural', value: 'neural' },
+ { label: 'Keyword (legacy)', value: 'keyword' },
+ { label: 'Neural (legacy)', value: 'neural' },
+ { label: 'Instant', value: 'instant' },
+ { label: 'Fast', value: 'fast' },
+ { label: 'Deep Lite', value: 'deep-lite' },
+ { label: 'Deep', value: 'deep' },
+ { label: 'Deep Reasoning', value: 'deep-reasoning' },
],
},
}),
category: Property.StaticDropdown({
displayName: 'Category',
- description: 'Category of data to focus the search on.',
+ description: 'Category of data to focus the search on. Company and People do not support published-date filters or Exclude Domains.',
required: false,
options: {
options: [
@@ -48,6 +56,8 @@ export const performSearchAction = createAction({
{ label: 'Personal Site', value: 'personal site' },
{ label: 'LinkedIn Profile', value: 'linkedin profile' },
{ label: 'Financial Report', value: 'financial report' },
+ { label: 'Publication', value: 'publication' },
+ { label: 'People', value: 'people' },
],
},
}),
@@ -69,12 +79,12 @@ export const performSearchAction = createAction({
}),
startCrawlDate: Property.DateTime({
displayName: 'Start Crawl Date',
- description: 'Only include results crawled after this ISO date.',
+ description: 'Deprecated: Exa now ignores this filter. Use the published date filters instead.',
required: false,
}),
endCrawlDate: Property.DateTime({
displayName: 'End Crawl Date',
- description: 'Only include results crawled before this ISO date.',
+ description: 'Deprecated: Exa now ignores this filter. Use the published date filters instead.',
required: false,
}),
startPublishedDate: Property.DateTime({
@@ -89,23 +99,68 @@ export const performSearchAction = createAction({
}),
includeText: Property.Array({
displayName: 'Include Text',
- description: 'Strings that must be present in the text of results.',
+ description: 'Deprecated by Exa. Strings that must be present in the text of results.',
required: false,
}),
excludeText: Property.Array({
displayName: 'Exclude Text',
- description: 'Strings that must not be present in the text of results.',
+ description: 'Deprecated by Exa. Strings that must not be present in the text of results.',
required: false,
}),
+ textMaxCharacters: Property.Number({
+ displayName: 'Max Text Characters',
+ description: 'Limit the page text returned per result to this many characters, e.g. 2000. Leave empty for full text.',
+ required: false,
+ }),
+ highlights: Property.Checkbox({
+ displayName: 'Include Highlights',
+ description: 'Also return the most relevant snippets from each page.',
+ required: false,
+ defaultValue: false,
+ }),
+ maxAgeHours: Property.Number({
+ displayName: 'Max Content Age (hours)',
+ description: 'Use cached page content only if it is newer than this many hours (0 always fetches fresh, -1 always uses cache, up to 720). Leave empty for Exa\'s default.',
+ required: false,
+ }),
+ userLocation: Property.ShortText({
+ displayName: 'User Country',
+ description: 'Two-letter country code to localize results, e.g. "US" or "DE".',
+ required: false,
+ }),
+ moderation: Property.Checkbox({
+ displayName: 'Filter Unsafe Content',
+ description: 'Remove unsafe content from the results.',
+ required: false,
+ defaultValue: false,
+ }),
},
async run(context) {
const apiKey = context.auth.secret_text;
+ const textMaxCharacters = exaInput.optionalInteger({
+ value: context.propsValue.textMaxCharacters,
+ name: 'Max Text Characters',
+ min: 1,
+ max: 1000000,
+ });
+ const maxAgeHours = exaInput.optionalInteger({
+ value: context.propsValue.maxAgeHours,
+ name: 'Max Content Age (hours)',
+ min: -1,
+ max: 720,
+ });
+ const userLocation = exaInput.optionalCountry({ value: context.propsValue.userLocation, name: 'User Country' });
+
const body: Record<string, unknown> = {
query: context.propsValue.query,
- contents:{
- text:true
- }
+ contents: {
+ text: textMaxCharacters !== undefined ? { maxCharacters: textMaxCharacters } : true,
+ ...(context.propsValue.highlights ? { highlights: true } : {}),
+ ...(maxAgeHours !== undefined ? { maxAgeHours } : {}),
+ },
+ ...(userLocation ? { userLocation } : {}),
+ ...(context.propsValue.moderation ? { moderation: true } : {}),
};
const optionalProps = [
diff --git a/packages/pieces/community/exa/src/lib/auth.ts b/packages/pieces/community/exa/src/lib/auth.ts
index c1296713086..93516ad5152 100644
--- a/packages/pieces/community/exa/src/lib/auth.ts
+++ b/packages/pieces/community/exa/src/lib/auth.ts
@@ -1,6 +1,6 @@
import { PieceAuth } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from './common';
+import { exaApi } from './common/client';
const markdownDescription = `
Obtain your API key from [Dashboard Setting](https://dashboard.exa.ai/api-keys).
@@ -10,23 +10,24 @@ export const exaAuth = PieceAuth.SecretText({
displayName: 'API Key',
description: markdownDescription,
required: true,
- validate:async ({auth})=>{
- try
- {
- await makeRequest(auth,HttpMethod.POST,
- '/search',{query:'Activepieces'}
- )
-
- return{
- valid:true
- }
-
- }catch(e)
- {
- return{
- valid:false,
- error:'Invalid API Key.'
+ validate: async ({ auth }) => {
+ try {
+ await exaApi.call<unknown>({
+ apiKey: auth,
+ method: HttpMethod.GET,
+ path: '/agent/runs',
+ query: { limit: '1' },
+ });
+ return { valid: true };
+ } catch (e) {
+ const status = exaApi.statusOf(e);
+ if (status === 401 || status === 403) {
+ return { valid: false, error: 'Invalid API Key.' };
}
+ return {
+ valid: false,
+ error: `Could not verify the API key with Exa${status ? ` (HTTP ${status})` : ''}. Try again in a moment.`,
+ };
}
- }
+ },
});
diff --git a/packages/pieces/community/exa/src/lib/common/agent.ts b/packages/pieces/community/exa/src/lib/common/agent.ts
new file mode 100644
index 00000000000..4b76aaabfee
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/common/agent.ts
@@ -0,0 +1,117 @@
+export const agentEfforts = {
+ ALL: ['minimal', 'low', 'medium', 'high', 'xhigh', 'auto', 'ultra'],
+ METERED: ['auto', 'ultra'],
+ DEFAULT: 'low',
+ OPTIONS: [
+ { label: 'Minimal ($0.012 per run)', value: 'minimal' },
+ { label: 'Low ($0.025 per run)', value: 'low' },
+ { label: 'Medium ($0.10 per run)', value: 'medium' },
+ { label: 'High ($0.50 per run)', value: 'high' },
+ { label: 'Extra High ($1.00 per run)', value: 'xhigh' },
+ { label: 'Auto (metered, up to $5 by default)', value: 'auto' },
+ { label: 'Ultra (metered, up to $20 by default)', value: 'ultra' },
+ ],
+};
+
+export const agentRuns = { flattenRun, summarizeRun };
+
+function flattenRun(run: AgentRun): FlatAgentRun {
+ return {
+ id: run.id,
+ status: run.status,
+ stop_reason: run.stopReason ?? null,
+ created_at: run.createdAt ?? null,
+ completed_at: run.completedAt ?? null,
+ query: run.request?.query ?? null,
+ effort: run.request?.effort ?? null,
+ output_text: run.output?.text ?? null,
+ output_structured: run.output?.structured ?? null,
+ citations: citationsOf(run.output?.grounding),
+ search_count: run.usage?.searches ?? null,
+ agent_compute_units: run.usage?.agentComputeUnits ?? null,
+ cost_total: run.costDollars?.total ?? null,
+ };
+}
+
+function summarizeRun(run: AgentRun): AgentRunSummary {
+ return {
+ id: run.id,
+ status: run.status,
+ stop_reason: run.stopReason ?? null,
+ created_at: run.createdAt ?? null,
+ completed_at: run.completedAt ?? null,
+ query: run.request?.query ?? null,
+ effort: run.request?.effort ?? null,
+ cost_total: run.costDollars?.total ?? null,
+ };
+}
+
+function citationsOf(grounding: AgentGrounding[] | undefined): FlatCitation[] {
+ if (!Array.isArray(grounding)) {
+ return [];
+ }
+ return grounding.flatMap((entry) =>
+ (entry.citations ?? []).map((citation) => ({
+ field: entry.field ?? null,
+ url: citation.url,
+ title: citation.title ?? null,
+ confidence: entry.confidence ?? null,
+ })),
+ );
+}
+
+export type AgentGrounding = {
+ field?: string;
+ citations?: { url: string; title?: string }[];
+ confidence?: string | null;
+};
+
+export type AgentRun = {
+ id: string;
+ object?: string;
+ status: string;
+ stopReason?: string | null;
+ createdAt?: string;
+ completedAt?: string | null;
+ request?: { query?: string; effort?: string } | null;
+ output?: {
+ text?: string;
+ structured?: unknown;
+ grounding?: AgentGrounding[];
+ };
+ usage?: { agentComputeUnits?: number; searches?: number };
+ costDollars?: { total?: number };
+};
+
+export type AgentRunList = {
+ object?: string;
+ data: AgentRun[];
+ hasMore?: boolean;
+ nextCursor?: string | null;
+};
+
+export type FlatCitation = {
+ field: string | null;
+ url: string;
+ title: string | null;
+ confidence: string | null;
+};
+
+export type AgentRunSummary = {
+ id: string;
+ status: string;
+ stop_reason: string | null;
+ created_at: string | null;
+ completed_at: string | null;
+ query: string | null;
+ effort: string | null;
+ cost_total: number | null;
+};
+
+export type FlatAgentRun = AgentRunSummary & {
+ output_text: string | null;
+ output_structured: unknown;
+ citations: FlatCitation[];
+ search_count: number | null;
+ agent_compute_units: number | null;
+};
diff --git a/packages/pieces/community/exa/src/lib/common/client.ts b/packages/pieces/community/exa/src/lib/common/client.ts
new file mode 100644
index 00000000000..a6e33e6dde2
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/common/client.ts
@@ -0,0 +1,254 @@
+import {
+ HttpMethod,
+ QueryParams,
+ httpClient,
+} from '@activepieces/pieces-common';
+
+export const BASE_URL = 'https://api.exa.ai';
+
+export const exaApi = { call, statusOf, assertExaUrl, toError, bodyOf };
+
+export const exaInput = {
+ optionalInteger,
+ optionalNumber,
+ optionalText,
+ optionalCountry,
+ requiredId,
+ stringList,
+};
+
+async function call<T>({
+ apiKey,
+ method,
+ path,
+ body,
+ query,
+}: {
+ apiKey: string;
+ method: HttpMethod;
+ path: string;
+ body?: unknown;
+ query?: QueryParams;
+}): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${BASE_URL}${path}`,
+ headers: {
+ 'x-api-key': apiKey,
+ 'Content-Type': 'application/json',
+ },
+ queryParams: query,
+ body,
+ followRedirects: false,
+ });
+ return bodyOf(response);
+ } catch (error) {
+ throw toError(error);
+ }
+}
+
+function bodyOf<T>(response: { status: number; body: T }): T {
+ if (response.status >= 300) {
+ throw new ExaApiError({
+ message: `Exa answered with a redirect (${response.status}), which is not followed so the API key stays on ${BASE_URL}.`,
+ status: response.status,
+ });
+ }
+ return response.body;
+}
+
+function toError(error: unknown): ExaApiError {
+ if (error instanceof ExaApiError) {
+ return error;
+ }
+ return new ExaApiError({
+ message: errorMessageOf(error),
+ status: responseOf(error)?.status,
+ });
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (typeof error === 'object' && error !== null) {
+ const status: unknown = Reflect.get(error, 'status');
+ if (typeof status === 'number') {
+ return status;
+ }
+ }
+ return responseOf(error)?.status;
+}
+
+function assertExaUrl(url: unknown): void {
+ if (typeof url !== 'string' || !/^https?:\/\//i.test(url.trim())) {
+ return;
+ }
+ const parsed = parseUrl(url.trim());
+ const allowed = new URL(BASE_URL);
+ if (
+ parsed === undefined ||
+ parsed.protocol !== allowed.protocol ||
+ parsed.hostname !== allowed.hostname ||
+ parsed.port !== '' ||
+ parsed.username !== '' ||
+ parsed.password !== ''
+ ) {
+ throw new Error(
+ `Custom API Call only sends your Exa API key to ${BASE_URL}. Use a path such as /search, or the HTTP piece for other hosts.`,
+ );
+ }
+}
+
+function optionalInteger({
+ value,
+ name,
+ min,
+ max,
+}: {
+ value: unknown;
+ name: string;
+ min: number;
+ max: number;
+}): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = typeof value === 'number' ? value : Number(value);
+ if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${name} must be a whole number between ${min} and ${max}.`);
+ }
+ return parsed;
+}
+
+function optionalNumber({
+ value,
+ name,
+ min,
+ max,
+}: {
+ value: unknown;
+ name: string;
+ min: number;
+ max: number;
+}): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = typeof value === 'number' ? value : Number(value);
+ if (!Number.isFinite(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${name} must be a number between ${min} and ${max}.`);
+ }
+ return parsed;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length === 0 ? undefined : trimmed;
+}
+
+function optionalCountry({ value, name }: { value: unknown; name: string }): string | undefined {
+ const text = optionalText(value);
+ if (text === undefined) {
+ return undefined;
+ }
+ if (!/^[A-Za-z]{2}$/.test(text)) {
+ throw new Error(`${name} must be a two-letter country code, e.g. "US".`);
+ }
+ return text.toUpperCase();
+}
+
+function requiredId({ value, name }: { value: unknown; name: string }): string {
+ const id = optionalText(value);
+ if (id === undefined) {
+ throw new Error(`${name} is required.`);
+ }
+ return id;
+}
+
+function stringList(value: unknown): string[] | undefined {
+ if (!Array.isArray(value)) {
+ return undefined;
+ }
+ const items = value
+ .map((item) => (typeof item === 'string' ? item : String(item ?? '')).trim())
+ .filter((item) => item.length > 0);
+ return items.length === 0 ? undefined : items;
+}
+
+function parseUrl(url: string): URL | undefined {
+ try {
+ return new URL(url);
+ } catch {
+ return undefined;
+ }
+}
+
+function responseOf(error: unknown): { status: number; body: unknown } | undefined {
+ if (typeof error !== 'object' || error === null) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (typeof response !== 'object' || response === null) {
+ return undefined;
+ }
+ const status: unknown = Reflect.get(response, 'status');
+ if (typeof status !== 'number') {
+ return undefined;
+ }
+ return { status, body: Reflect.get(response, 'body') };
+}
+
+function errorMessageOf(error: unknown): string {
+ const response = responseOf(error);
+ if (response === undefined) {
+ return error instanceof Error ? error.message : String(error);
+ }
+ const detail = detailOf(response.body);
+ const suffix = detail ? `: ${detail}` : '';
+ switch (response.status) {
+ case 401:
+ return `Exa rejected the API key (401)${suffix}. Check the key in your Exa connection.`;
+ case 402:
+ return `Exa reports insufficient credits (402)${suffix}. Add credits in the Exa dashboard.`;
+ case 403:
+ return `Exa refused the request (403)${suffix}.`;
+ case 404:
+ return `Exa could not find that resource (404)${suffix}. Check the ID.`;
+ case 429:
+ return `Exa rate limit or concurrency limit reached (429)${suffix}. Wait and try again.`;
+ default:
+ return `Exa request failed (${response.status})${suffix}`;
+ }
+}
+
+function detailOf(body: unknown): string | undefined {
+ if (typeof body === 'string') {
+ return body.slice(0, 500);
+ }
+ if (typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const err: unknown = Reflect.get(body, 'error');
+ if (typeof err === 'string') {
+ return err;
+ }
+ if (typeof err === 'object' && err !== null) {
+ const message: unknown = Reflect.get(err, 'message');
+ const code: unknown = Reflect.get(err, 'code');
+ if (typeof message === 'string') {
+ return typeof code === 'string' ? `${code} ${message}` : message;
+ }
+ }
+ return undefined;
+}
+
+class ExaApiError extends Error {
+ readonly status: number | undefined;
+ constructor({ message, status }: { message: string; status: number | undefined }) {
+ super(message);
+ this.name = 'ExaApiError';
+ this.status = status;
+ }
+}
diff --git a/packages/pieces/community/exa/src/lib/common/index.ts b/packages/pieces/community/exa/src/lib/common/index.ts
index 7e2d2d4f24d..eb1e8751675 100644
--- a/packages/pieces/community/exa/src/lib/common/index.ts
+++ b/packages/pieces/community/exa/src/lib/common/index.ts
@@ -1,17 +1,21 @@
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-
-export const BASE_URL = 'https://api.exa.ai';
+import { BASE_URL, exaApi } from './client';
export async function makeRequest(auth: string, method: HttpMethod, path: string, body?: unknown) {
- const response = await httpClient.sendRequest({
- method,
- url: `${BASE_URL}${path}`,
- headers: {
- 'x-api-key': `${auth}`,
- 'Content-Type': 'application/json',
- },
- body,
- });
+ try {
+ const response = await httpClient.sendRequest({
+ method,
+ url: `${BASE_URL}${path}`,
+ headers: {
+ 'x-api-key': `${auth}`,
+ 'Content-Type': 'application/json',
+ },
+ body,
+ followRedirects: false,
+ });
- return response.body;
+ return exaApi.bodyOf(response);
+ } catch (error) {
+ throw exaApi.toError(error);
+ }
}
diff --git a/packages/pieces/community/exa/src/lib/common/results.ts b/packages/pieces/community/exa/src/lib/common/results.ts
new file mode 100644
index 00000000000..a2e0813afdc
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/common/results.ts
@@ -0,0 +1,81 @@
+export const exaResults = { flattenResult, flattenPage, flattenStatus };
+
+function flattenResult(result: ExaResult): FlatResult {
+ return {
+ id: result.id ?? null,
+ title: result.title ?? null,
+ url: result.url ?? null,
+ published_date: result.publishedDate ?? null,
+ author: result.author ?? null,
+ text: result.text ?? null,
+ highlights: Array.isArray(result.highlights) ? result.highlights.join('\n') : null,
+ summary: result.summary ?? null,
+ image: result.image ?? null,
+ };
+}
+
+function flattenPage(result: ExaResult): FlatPage {
+ return {
+ ...flattenResult(result),
+ links: Array.isArray(result.extras?.links) ? result.extras.links : null,
+ subpages: Array.isArray(result.subpages) ? result.subpages.map(flattenResult) : [],
+ };
+}
+
+function flattenStatus(status: ExaStatus): FlatStatus {
+ return {
+ url: status.id,
+ status: status.status,
+ source: status.source ?? null,
+ error_tag: status.error?.tag ?? null,
+ error_http_status: status.error?.httpStatusCode ?? null,
+ };
+}
+
+export type ExaResult = {
+ id?: string;
+ title?: string | null;
+ url?: string;
+ publishedDate?: string | null;
+ author?: string | null;
+ text?: string;
+ highlights?: string[];
+ summary?: string;
+ image?: string;
+ extras?: { links?: string[] };
+ subpages?: ExaResult[];
+};
+
+export type ExaStatus = {
+ id: string;
+ status: string;
+ source?: string;
+ error?: { tag?: string; httpStatusCode?: number | null } | null;
+};
+
+export type ExaCost = { total?: number };
+
+export type FlatResult = {
+ id: string | null;
+ title: string | null;
+ url: string | null;
+ published_date: string | null;
+ author: string | null;
+ text: string | null;
+ highlights: string | null;
+ summary: string | null;
+ image: string | null;
+};
+
+export type FlatPage = FlatResult & {
+ links: string[] | null;
+ subpages: FlatResult[];
+};
+
+export type FlatStatus = {
+ url: string;
+ status: string;
+ source: string | null;
+ error_tag: string | null;
+ error_http_status: number | null;
+};
diff --git a/packages/pieces/community/exa/src/lib/common/webhook-signature.ts b/packages/pieces/community/exa/src/lib/common/webhook-signature.ts
new file mode 100644
index 00000000000..5ad020cf4a0
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/common/webhook-signature.ts
@@ -0,0 +1,103 @@
+import crypto from 'crypto';
+
+export const exaWebhookSignature = { HEADER: 'exa-signature', verify, problemOf, headerOf };
+
+function verify(params: SignatureCheck): boolean {
+ return problemOf(params) === undefined;
+}
+
+function problemOf({ secret, signatureHeader, rawBody, nowMs = Date.now() }: SignatureCheck): string | undefined {
+ if (!secret) {
+ return 'no webhook secret is stored for this flow';
+ }
+ if (!signatureHeader) {
+ return 'the Exa-Signature header is missing';
+ }
+ const payload = bytesOf(rawBody);
+ if (payload === undefined) {
+ return 'the raw request body is not available';
+ }
+ const parts = partsOf(signatureHeader);
+ const timestamp = parts.get('t');
+ const signatures = parts.getAll('v1');
+ if (!timestamp || signatures.length === 0) {
+ return 'the Exa-Signature header is malformed';
+ }
+ const expected = crypto
+ .createHmac('sha256', secret)
+ .update(`${timestamp}.`)
+ .update(payload)
+ .digest();
+ if (!signatures.some((signature) => matches({ expected, signature }))) {
+ return 'the signature does not match';
+ }
+ if (!isRecent({ timestamp, nowMs })) {
+ return `it was signed more than 15 minutes ago (t=${timestamp})`;
+ }
+ return undefined;
+}
+
+function isRecent({ timestamp, nowMs }: { timestamp: string; nowMs: number }): boolean {
+ if (!/^\d+$/.test(timestamp)) {
+ return false;
+ }
+ const value = Number(timestamp);
+ const sentSeconds = value > MILLISECOND_TIMESTAMP_FLOOR ? value / 1000 : value;
+ return Math.abs(nowMs / 1000 - sentSeconds) <= TIMESTAMP_TOLERANCE_SECONDS;
+}
+
+function headerOf({
+ headers,
+ name,
+}: {
+ headers: Record<string, string> | undefined;
+ name: string;
+}): string | undefined {
+ if (!headers) {
+ return undefined;
+ }
+ const key = Object.keys(headers).find((header) => header.toLowerCase() === name);
+ return key === undefined ? undefined : headers[key];
+}
+
+function bytesOf(rawBody: unknown): Buffer | undefined {
+ if (Buffer.isBuffer(rawBody)) {
+ return rawBody;
+ }
+ if (typeof rawBody === 'string') {
+ return Buffer.from(rawBody, 'utf8');
+ }
+ return undefined;
+}
+
+function partsOf(header: string): { get: (key: string) => string | undefined; getAll: (key: string) => string[] } {
+ const pairs = header
+ .split(',')
+ .map((part) => part.trim())
+ .map((part) => {
+ const index = part.indexOf('=');
+ return index === -1 ? ['', ''] : [part.slice(0, index), part.slice(index + 1)];
+ });
+ return {
+ get: (key) => pairs.find(([k]) => k === key)?.[1],
+ getAll: (key) => pairs.filter(([k]) => k === key).map(([, v]) => v),
+ };
+}
+
+function matches({ expected, signature }: { expected: Buffer; signature: string }): boolean {
+ if (!/^[0-9a-fA-F]+$/.test(signature)) {
+ return false;
+ }
+ const provided = Buffer.from(signature, 'hex');
+ return provided.length === expected.length && crypto.timingSafeEqual(provided, expected);
+}
+
+const TIMESTAMP_TOLERANCE_SECONDS = 900;
+const MILLISECOND_TIMESTAMP_FLOOR = 1e12;
+
+type SignatureCheck = {
+ secret: string | undefined;
+ signatureHeader: string | undefined;
+ rawBody: unknown;
+ nowMs?: number;
+};
diff --git a/packages/pieces/community/exa/src/lib/output-schemas-ai.ts b/packages/pieces/community/exa/src/lib/output-schemas-ai.ts
new file mode 100644
index 00000000000..c786e79762b
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/output-schemas-ai.ts
@@ -0,0 +1,78 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+import { exaSharedFields } from './output-schemas';
+
+const twinPageFields: OutputSchemaField[] = [
+ ...exaSharedFields.flatResultFields,
+ { key: 'links', label: 'Links on Page' },
+ {
+ key: 'subpages',
+ label: 'Subpages',
+ labelKey: 'url',
+ listItems: exaSharedFields.flatResultFields,
+ },
+];
+
+const costField: OutputSchemaField = {
+ key: 'cost_total',
+ label: 'Cost (USD)',
+ format: 'currency',
+ currency: 'USD',
+};
+
+export const exaSearchOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'results',
+ label: 'Results',
+ labelKey: 'title',
+ listItems: exaSharedFields.flatResultFields,
+ },
+ { key: 'count', label: 'Result Count', format: 'number' },
+ costField,
+ ],
+};
+
+export const exaGetContentsOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'results',
+ label: 'Pages',
+ labelKey: 'url',
+ listItems: twinPageFields,
+ },
+ {
+ key: 'statuses',
+ label: 'Per-URL Status',
+ labelKey: 'url',
+ listItems: [
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'status', label: 'Status' },
+ { key: 'source', label: 'Source' },
+ { key: 'error_tag', label: 'Error' },
+ { key: 'error_http_status', label: 'HTTP Status', format: 'number' },
+ ],
+ },
+ { key: 'failed_count', label: 'Failed URLs', format: 'number' },
+ costField,
+ ],
+};
+
+export const exaAnswerOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'answer', label: 'Answer' },
+ {
+ key: 'citations',
+ label: 'Citations',
+ labelKey: 'title',
+ listItems: [
+ { key: 'title', label: 'Title' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'published_date', label: 'Published Date', format: 'date' },
+ { key: 'author', label: 'Author' },
+ { key: 'text', label: 'Page Text' },
+ { key: 'id', label: 'Document ID' },
+ ],
+ },
+ costField,
+ ],
+};
diff --git a/packages/pieces/community/exa/src/lib/output-schemas.ts b/packages/pieces/community/exa/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..10149c45321
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/output-schemas.ts
@@ -0,0 +1,188 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+const rawLinkFields: OutputSchemaField[] = [
+ { key: 'title', label: 'Title' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'publishedDate', label: 'Published Date', format: 'date' },
+ { key: 'author', label: 'Author' },
+ { key: 'image', label: 'Image', format: 'image' },
+ { key: 'id', label: 'Document ID' },
+];
+
+const rawSearchFields: OutputSchemaField[] = [
+ ...rawLinkFields,
+ { key: 'text', label: 'Page Text' },
+ { key: 'highlights', label: 'Highlights' },
+ { key: 'score', label: 'Relevance Score', format: 'number' },
+];
+
+const rawSimilarFields: OutputSchemaField[] = [
+ ...rawLinkFields,
+ { key: 'score', label: 'Relevance Score', format: 'number' },
+];
+
+const rawSubpageFields: OutputSchemaField[] = [
+ ...rawLinkFields,
+ { key: 'text', label: 'Page Text' },
+];
+
+const rawContentsFields: OutputSchemaField[] = [
+ ...rawLinkFields,
+ { key: 'text', label: 'Page Text' },
+ { key: 'highlights', label: 'Highlights' },
+ { key: 'summary', label: 'Summary' },
+ {
+ key: 'extras',
+ label: 'Extras',
+ children: [{ key: 'links', label: 'Links on Page' }],
+ },
+ {
+ key: 'subpages',
+ label: 'Subpages',
+ labelKey: 'title',
+ listItems: rawSubpageFields,
+ },
+];
+
+const citationFields: OutputSchemaField[] = [
+ { key: 'title', label: 'Title' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'field', label: 'Supports Field' },
+ { key: 'confidence', label: 'Confidence' },
+];
+
+const agentRunSummaryFields: OutputSchemaField[] = [
+ { key: 'id', label: 'Run ID' },
+ { key: 'status', label: 'Status' },
+ { key: 'stop_reason', label: 'Stop Reason' },
+ { key: 'query', label: 'Task' },
+ { key: 'effort', label: 'Effort' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'completed_at', label: 'Completed At', format: 'datetime' },
+ { key: 'cost_total', label: 'Cost (USD)', format: 'currency', currency: 'USD' },
+];
+
+const flatResultFields: OutputSchemaField[] = [
+ { key: 'title', label: 'Title' },
+ { key: 'url', label: 'URL', format: 'url' },
+ { key: 'published_date', label: 'Published Date', format: 'date' },
+ { key: 'author', label: 'Author' },
+ { key: 'text', label: 'Page Text' },
+ { key: 'highlights', label: 'Highlights' },
+ { key: 'summary', label: 'Summary' },
+ { key: 'image', label: 'Image', format: 'image' },
+ { key: 'id', label: 'Document ID' },
+];
+
+export const searchResultsOutputSchema: OutputSchema = {
+ itemLabel: '{title}',
+ fields: [
+ {
+ key: 'results',
+ label: 'Results',
+ value: '',
+ labelKey: 'title',
+ listItems: rawSearchFields,
+ },
+ ],
+};
+
+export const similarLinksOutputSchema: OutputSchema = {
+ itemLabel: '{title}',
+ fields: [
+ {
+ key: 'results',
+ label: 'Similar Pages',
+ value: '',
+ labelKey: 'title',
+ listItems: rawSimilarFields,
+ },
+ ],
+};
+
+export const contentsResultsOutputSchema: OutputSchema = {
+ itemLabel: '{title}',
+ fields: [
+ {
+ key: 'results',
+ label: 'Pages',
+ value: '',
+ labelKey: 'title',
+ listItems: rawContentsFields,
+ },
+ ],
+};
+
+export const agentRunOutputSchema: OutputSchema = {
+ fields: [
+ ...agentRunSummaryFields,
+ { key: 'output_text', label: 'Answer' },
+ { key: 'output_structured', label: 'Structured Output' },
+ {
+ key: 'citations',
+ label: 'Citations',
+ labelKey: 'title',
+ listItems: citationFields,
+ },
+ { key: 'search_count', label: 'Searches Used', format: 'number' },
+ { key: 'agent_compute_units', label: 'Agent Compute Units', format: 'number' },
+ ],
+};
+
+export const agentRunListOutputSchema: OutputSchema = {
+ fields: [
+ {
+ key: 'runs',
+ label: 'Runs',
+ labelKey: 'id',
+ listItems: agentRunSummaryFields,
+ },
+ { key: 'count', label: 'Runs in This Page', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ { key: 'next_cursor', label: 'Next Cursor' },
+ ],
+};
+
+export const searchMonitorRunOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'status', label: 'Run Status' },
+ { key: 'fail_reason', label: 'Fail Reason' },
+ {
+ key: 'summary',
+ label: 'Summary',
+ description: "Exa's summary of the results in this payload. Empty when the run also held results that were delivered before; see Run Summary.",
+ },
+ { key: 'result_count', label: 'New Results', format: 'number' },
+ {
+ key: 'run_summary',
+ label: 'Run Summary',
+ description: "Exa's summary of the whole monitor run, which can mention results delivered before. Numbered markers such as [1] are Exa's own and do not reliably index Run Citations.",
+ },
+ { key: 'run_result_count', label: 'Results in Run', format: 'number' },
+ {
+ key: 'results',
+ label: 'Results',
+ labelKey: 'title',
+ listItems: flatResultFields,
+ },
+ {
+ key: 'citations',
+ label: 'Citations',
+ labelKey: 'title',
+ description: 'Sources for the results in this payload.',
+ listItems: citationFields,
+ },
+ {
+ key: 'run_citations',
+ label: 'Run Citations',
+ labelKey: 'title',
+ description: 'Every source Exa cited for the whole run, in Exa\'s order.',
+ listItems: citationFields,
+ },
+ { key: 'run_id', label: 'Run ID' },
+ { key: 'monitor_id', label: 'Monitor ID' },
+ { key: 'event_id', label: 'Event ID' },
+ { key: 'event_created_at', label: 'Delivered At', format: 'datetime' },
+ ],
+};
+export const exaSharedFields = { flatResultFields };
diff --git a/packages/pieces/community/exa/src/lib/triggers/new-search-monitor-results.ts b/packages/pieces/community/exa/src/lib/triggers/new-search-monitor-results.ts
new file mode 100644
index 00000000000..4242c42f311
--- /dev/null
+++ b/packages/pieces/community/exa/src/lib/triggers/new-search-monitor-results.ts
@@ -0,0 +1,558 @@
+import {
+ createTrigger,
+ Property,
+ Store,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { exaAuth } from '../auth';
+import { exaApi, exaInput } from '../common/client';
+import { exaWebhookSignature } from '../common/webhook-signature';
+import { searchMonitorRunOutputSchema } from '../output-schemas';
+
+export const newSearchMonitorResultsTrigger = createTrigger({
+ auth: exaAuth,
+ name: 'new_search_monitor_results',
+ classification: 'READ',
+ displayName: 'New Search Monitor Results',
+ description:
+ 'Runs a search on a schedule and triggers with the new results Exa found since the last run.',
+ aiMetadata: {
+ description:
+ 'Fires once per completed Exa search-monitor run: Exa repeats the configured query on the chosen interval, removes results it already returned, and delivers the new results with their citations; summary describes exactly those results and is null when the run also held results delivered before (run_summary, run_result_count and run_citations then describe the whole run). Numbered markers such as [1] in the summaries come from Exa and do not reliably index the citation lists. Check status and fail_reason before using the results. Each run is billed by Exa (about $0.015 per run).',
+ },
+ props: {
+ info: Property.MarkDown({
+ value: `Exa creates a **Monitor** that repeats this search on a schedule and sends only new results.
+
+- Each run costs about **$0.015** on your Exa account (plus $0.001 per result above 10). An hourly monitor is about 720 runs a month (≈ $11); daily is about 30 (≈ $0.45).
+- Exa only delivers to a public **HTTPS** address. On a self-hosted instance, the Activepieces webhook URL must be reachable from the internet.
+- Testing the trigger in the builder runs one search (about $0.007, plus content charges when page text or highlights are on) and shows its results; it does not create a monitor.
+- Results that were already delivered are not sent again, also after the flow is republished. A run whose results were all delivered before is skipped. When a run mixes old and new results, only the new ones are sent, with their citations; Summary is then empty, and Run Summary and Run Citations cover the whole run. Numbered markers such as [1] in Exa's summaries are Exa's own; Exa does not document what they point to, so use the citation lists for sources.
+- Turning the flow off deletes the monitor, retrying if Exa is briefly unavailable. If it still can't be deleted, remove it in the Exa dashboard: it is named after this flow unless you set Monitor Name.`,
+ }),
+ query: Property.LongText({
+ displayName: 'Search Query',
+ description:
+ 'What to watch for, written as the ongoing signal rather than a date range. Example: "new battery recycling facilities announced in North America".',
+ required: true,
+ }),
+ period: Property.StaticDropdown({
+ displayName: 'Check Every',
+ description: 'How often Exa runs the search. Each run may start up to 30 minutes late.',
+ required: true,
+ defaultValue: '1d',
+ options: {
+ options: [
+ { label: 'Hour', value: '1h' },
+ { label: '6 hours', value: '6h' },
+ { label: 'Day', value: '1d' },
+ { label: 'Week', value: '7d' },
+ ],
+ },
+ }),
+ numResults: Property.Number({
+ displayName: 'Max Results per Run',
+ description: 'Up to how many new results each run returns, 1 to 100. Defaults to 10; results above 10 cost extra.',
+ required: false,
+ defaultValue: 10,
+ }),
+ includeDomains: Property.Array({
+ displayName: 'Include Domains',
+ description: 'Only return results from these domains, e.g. "techcrunch.com". Leave empty for the whole web.',
+ required: false,
+ }),
+ excludeDomains: Property.Array({
+ displayName: 'Exclude Domains',
+ description: 'Never return results from these domains.',
+ required: false,
+ }),
+ includeText: Property.Checkbox({
+ displayName: 'Include Page Text',
+ description: 'Add the full page text to each result.',
+ required: false,
+ defaultValue: false,
+ }),
+ includeHighlights: Property.Checkbox({
+ displayName: 'Include Highlights',
+ description: 'Add the most relevant snippets from each page to each result.',
+ required: false,
+ defaultValue: false,
+ }),
+ monitorName: Property.ShortText({
+ displayName: 'Monitor Name',
+ description: 'Optional name shown for this monitor in the Exa dashboard.',
+ required: false,
+ }),
+ },
+ sampleData: sampleRun(),
+ outputSchema: searchMonitorRunOutputSchema,
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context) {
+ if (!context.webhookUrl.startsWith('https://')) {
+ throw new Error(
+ `Exa only delivers to a public HTTPS address, and this flow's webhook URL is ${context.webhookUrl}. Make the Activepieces webhook URL reachable over HTTPS from the internet.`,
+ );
+ }
+ const apiKey = context.auth.secret_text;
+ const search = monitorSearchOf(context.propsValue);
+ const name = exaInput.optionalText(context.propsValue.monitorName) ?? `Activepieces flow ${context.flows.current.id}`;
+
+ const previous = await context.store.get<MonitorState>(STORE_KEY);
+
+ const monitor = await exaApi.call<{ id: string; webhookSecret?: string }>({
+ apiKey,
+ method: HttpMethod.POST,
+ path: '/monitors',
+ body: {
+ name,
+ search,
+ trigger: { type: 'interval', period: context.propsValue.period },
+ webhook: {
+ url: context.webhookUrl,
+ events: ['monitor.run.completed'],
+ },
+ },
+ });
+
+ const staleBefore = staleIdsOf(previous);
+ const webhookSecret = monitor.webhookSecret;
+ if (!webhookSecret) {
+ const cleanup = await rollBackMonitor({ apiKey, monitorId: monitor.id });
+ if (!cleanup.deleted) {
+ try {
+ await context.store.put<MonitorState>(STORE_KEY, {
+ monitorId: previous?.monitorId ?? null,
+ webhookSecret: previous?.webhookSecret ?? null,
+ stale: uniqueIds([...staleBefore, monitor.id]),
+ });
+ } catch (error) {
+ throw new Error(
+ `Exa created the monitor without a webhook secret, and it could not be saved for cleanup: ${messageOf(error)}. ${cleanup.message}`,
+ );
+ }
+ }
+ throw new Error(`Exa created the monitor without a webhook secret, so deliveries could not be verified. ${cleanup.message} Turn the flow on again.`);
+ }
+ const stale = uniqueIds([...staleBefore, ...(previous?.monitorId ? [previous.monitorId] : [])]).filter((id) => id !== monitor.id);
+ try {
+ await context.store.put<MonitorState>(STORE_KEY, { monitorId: monitor.id, webhookSecret, stale });
+ } catch (error) {
+ const cleanup = await rollBackMonitor({ apiKey, monitorId: monitor.id });
+ throw new Error(`Could not save the Exa monitor ID: ${messageOf(error)}. ${cleanup.message}`);
+ }
+ await drainStaleMonitors({ store: context.store, apiKey, state: { monitorId: monitor.id, webhookSecret, stale } });
+ },
+ async onDisable(context) {
+ const apiKey = context.auth.secret_text;
+ const state = await context.store.get<MonitorState>(STORE_KEY);
+ if (!state) {
+ return;
+ }
+ if (state.monitorId) {
+ try {
+ await deleteMonitor({ apiKey, monitorId: state.monitorId });
+ } catch (error) {
+ throw new Error(
+ `Could not delete the Exa monitor ${state.monitorId}: ${messageOf(error)}. It stays recorded and is retried the next time the flow is turned on or off; you can also delete it in the Exa dashboard.`,
+ );
+ }
+ }
+ await drainStaleMonitors({ store: context.store, apiKey, state: { monitorId: null, webhookSecret: null, stale: staleIdsOf(state) } });
+ },
+ async test(context) {
+ const search = monitorSearchOf(context.propsValue);
+ const response = await exaApi.call<{ results?: unknown[] }>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/search',
+ body: search,
+ });
+ const results = (response.results ?? []).map(resultOf);
+ return [
+ {
+ event_id: null,
+ event_created_at: null,
+ run_id: null,
+ monitor_id: null,
+ status: 'completed',
+ fail_reason: null,
+ summary: null,
+ run_summary: null,
+ result_count: results.length,
+ run_result_count: results.length,
+ results,
+ citations: [],
+ run_citations: [],
+ },
+ ];
+ },
+ async run(context) {
+ const state = await context.store.get<MonitorState>(STORE_KEY);
+ const signatureHeader = exaWebhookSignature.headerOf({
+ headers: context.payload.headers,
+ name: exaWebhookSignature.HEADER,
+ });
+ const problem = exaWebhookSignature.problemOf({
+ secret: state?.webhookSecret ?? undefined,
+ signatureHeader,
+ rawBody: context.payload.rawBody,
+ });
+ if (problem !== undefined || !state?.monitorId) {
+ console.warn(`[exa] Dropped a search-monitor delivery because ${problem ?? 'the flow has no monitor'}.`);
+ return [];
+ }
+ const event = eventOf(context.payload.body);
+ if (!event || event.type !== 'monitor.run.completed' || event.data?.monitorId !== state.monitorId) {
+ return [];
+ }
+ const seen = (await context.store.get<SeenState>(SEEN_KEY)) ?? { eventIds: [], urls: [] };
+ const dedupeId = event.id ?? event.data?.id;
+ if (dedupeId && seen.eventIds.includes(dedupeId)) {
+ return [];
+ }
+ const run = flattenEvent(event);
+ const fresh = run.results.filter((result) => result.url === null || !seen.urls.includes(result.url));
+ const freshUrls = fresh.flatMap((result) => (result.url === null ? [] : [result.url]));
+ const freshUrlSet = new Set(freshUrls);
+ const complete = fresh.length === run.results.length;
+ await context.store.put<SeenState>(SEEN_KEY, {
+ eventIds: (dedupeId ? [dedupeId, ...seen.eventIds] : seen.eventIds).slice(0, SEEN_EVENT_LIMIT),
+ urls: [...freshUrls, ...seen.urls].slice(0, SEEN_URL_LIMIT),
+ });
+ if (run.results.length > 0 && fresh.length === 0) {
+ return [];
+ }
+ return [
+ {
+ ...run,
+ results: fresh,
+ result_count: fresh.length,
+ summary: complete ? run.run_summary : null,
+ citations: complete
+ ? run.citations
+ : run.citations.filter((citation) => citation.url !== null && freshUrlSet.has(citation.url)),
+ },
+ ];
+ },
+});
+
+function monitorSearchOf(propsValue: {
+ query: string;
+ numResults?: number;
+ includeDomains?: unknown[];
+ excludeDomains?: unknown[];
+ includeText?: boolean;
+ includeHighlights?: boolean;
+}): Record<string, unknown> {
+ const numResults = exaInput.optionalInteger({
+ value: propsValue.numResults,
+ name: 'Max Results per Run',
+ min: 1,
+ max: 100,
+ });
+ const includeDomains = exaInput.stringList(propsValue.includeDomains);
+ const excludeDomains = exaInput.stringList(propsValue.excludeDomains);
+ const contents = {
+ ...(propsValue.includeText ? { text: true } : {}),
+ ...(propsValue.includeHighlights ? { highlights: true } : {}),
+ };
+ return {
+ query: propsValue.query,
+ ...(numResults !== undefined ? { numResults } : {}),
+ ...(includeDomains ? { includeDomains } : {}),
+ ...(excludeDomains ? { excludeDomains } : {}),
+ ...(Object.keys(contents).length > 0 ? { contents } : {}),
+ };
+}
+
+async function deleteMonitor({ apiKey, monitorId }: { apiKey: string; monitorId: string }): Promise<void> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await exaApi.call<unknown>({
+ apiKey,
+ method: HttpMethod.DELETE,
+ path: `/monitors/${encodeURIComponent(monitorId)}`,
+ });
+ return;
+ } catch (error) {
+ const status = exaApi.statusOf(error);
+ if (status === 404) {
+ return;
+ }
+ const retryable = status === undefined || status === 429 || status >= 500;
+ if (!retryable || attempt >= DELETE_RETRY_DELAYS_MS.length) {
+ throw error;
+ }
+ await new Promise((resolve) => setTimeout(resolve, DELETE_RETRY_DELAYS_MS[attempt]));
+ }
+ }
+}
+
+async function drainStaleMonitors({ store, apiKey, state }: { store: Store; apiKey: string; state: MonitorState }): Promise<void> {
+ const remaining: string[] = [];
+ for (const monitorId of state.stale) {
+ try {
+ await deleteMonitor({ apiKey, monitorId });
+ } catch {
+ remaining.push(monitorId);
+ }
+ }
+ try {
+ if (state.monitorId === null && remaining.length === 0) {
+ await store.delete(STORE_KEY);
+ } else {
+ await store.put<MonitorState>(STORE_KEY, { ...state, stale: remaining });
+ }
+ } catch (error) {
+ console.warn(
+ `[exa] Could not update the monitor cleanup list (${messageOf(error)}). Monitors still to delete: ${remaining.length > 0 ? remaining.join(', ') : 'none'}; the stored list is unchanged and is retried on the next enable or disable.`,
+ );
+ }
+}
+
+function staleIdsOf(state: MonitorState | null): string[] {
+ return Array.isArray(state?.stale) ? state.stale.filter((id) => typeof id === 'string') : [];
+}
+
+function uniqueIds(ids: string[]): string[] {
+ return [...new Set(ids)];
+}
+
+async function rollBackMonitor({ apiKey, monitorId }: { apiKey: string; monitorId: string }): Promise<{ deleted: boolean; message: string }> {
+ try {
+ await deleteMonitor({ apiKey, monitorId });
+ return { deleted: true, message: 'The new monitor was deleted again.' };
+ } catch (error) {
+ return {
+ deleted: false,
+ message: `The new monitor ${monitorId} could not be deleted (${messageOf(error)}); delete it in the Exa dashboard.`,
+ };
+ }
+}
+
+function messageOf(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+function eventOf(body: unknown): MonitorEvent | undefined {
+ if (typeof body !== 'object' || body === null) {
+ return undefined;
+ }
+ const type: unknown = Reflect.get(body, 'type');
+ if (typeof type !== 'string') {
+ return undefined;
+ }
+ const id: unknown = Reflect.get(body, 'id');
+ const createdAt: unknown = Reflect.get(body, 'createdAt');
+ const data: unknown = Reflect.get(body, 'data');
+ return {
+ id: typeof id === 'string' ? id : undefined,
+ type,
+ createdAt: typeof createdAt === 'string' ? createdAt : undefined,
+ data: typeof data === 'object' && data !== null ? runOf(data) : undefined,
+ };
+}
+
+function runOf(data: object): MonitorRun {
+ const output: unknown = Reflect.get(data, 'output');
+ const outputObject = typeof output === 'object' && output !== null ? output : undefined;
+ const results: unknown = outputObject ? Reflect.get(outputObject, 'results') : undefined;
+ const grounding: unknown = outputObject ? Reflect.get(outputObject, 'grounding') : undefined;
+ return {
+ id: stringOf(Reflect.get(data, 'id')),
+ monitorId: stringOf(Reflect.get(data, 'monitorId')),
+ status: stringOf(Reflect.get(data, 'status')),
+ failReason: stringOf(Reflect.get(data, 'failReason')),
+ content: outputObject ? Reflect.get(outputObject, 'content') ?? null : null,
+ results: Array.isArray(results) ? results : [],
+ grounding: Array.isArray(grounding) ? grounding : [],
+ };
+}
+
+function flattenEvent(event: MonitorEvent): FlatMonitorRun {
+ const run = event.data;
+ const results = (run?.results ?? []).map(resultOf);
+ const content = run?.content ?? null;
+ const citations = citationsOf(run?.grounding ?? []);
+ return {
+ event_id: event.id ?? null,
+ event_created_at: event.createdAt ?? null,
+ run_id: run?.id ?? null,
+ monitor_id: run?.monitorId ?? null,
+ status: run?.status ?? null,
+ fail_reason: run?.failReason ?? null,
+ summary: typeof content === 'string' ? content : null,
+ run_summary: typeof content === 'string' ? content : null,
+ result_count: results.length,
+ run_result_count: results.length,
+ results,
+ citations,
+ run_citations: citations,
+ };
+}
+
+function resultOf(item: unknown): FlatMonitorResult {
+ const get = (key: string): unknown =>
+ typeof item === 'object' && item !== null ? Reflect.get(item, key) : undefined;
+ const highlights = get('highlights');
+ return {
+ id: stringOf(get('id')),
+ title: stringOf(get('title')),
+ url: stringOf(get('url')),
+ published_date: isoDateOf(get('publishedDate')),
+ author: stringOf(get('author')),
+ text: stringOf(get('text')),
+ highlights: Array.isArray(highlights) ? highlights.map(String).join('\n') : null,
+ summary: stringOf(get('summary')),
+ image: stringOf(get('image')),
+ };
+}
+
+function citationsOf(grounding: unknown[]): MonitorCitation[] {
+ return grounding.flatMap((entry) => {
+ if (typeof entry !== 'object' || entry === null) {
+ return [];
+ }
+ const citations: unknown = Reflect.get(entry, 'citations');
+ if (!Array.isArray(citations)) {
+ return [];
+ }
+ return citations.map((citation: unknown) => ({
+ field: stringOf(Reflect.get(entry, 'field')),
+ url: typeof citation === 'object' && citation !== null ? stringOf(Reflect.get(citation, 'url')) : null,
+ title: typeof citation === 'object' && citation !== null ? stringOf(Reflect.get(citation, 'title')) : null,
+ confidence: stringOf(Reflect.get(entry, 'confidence')),
+ }));
+ });
+}
+
+function isoDateOf(value: unknown): string | null {
+ const text = stringOf(value);
+ if (text === null) {
+ return null;
+ }
+ const match = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(\.\d+)?Z?$/.exec(text);
+ if (!match) {
+ return text;
+ }
+ const millis = (match[3] ?? '.000').slice(1, 4).padEnd(3, '0');
+ return `${match[1]}T${match[2]}.${millis}Z`;
+}
+
+function stringOf(value: unknown): string | null {
+ return typeof value === 'string' ? value : null;
+}
+
+function sampleRun(): Record<string, unknown> {
+ return {
+ event_id: 'event_01k4d9x2m5n8p1q4r7s0t3v6w9',
+ event_created_at: '2026-09-05T20:00:00.000Z',
+ run_id: '01k4d9w8a1b2c3d4e5f6g7h8j9',
+ monitor_id: '01k4d9w6y3h7p2m8n5q1r0s4tv',
+ status: 'completed',
+ fail_reason: null,
+ summary: 'Two new battery recycling facilities were announced in Ontario and Nevada this week. [1]',
+ run_summary: 'Two new battery recycling facilities were announced in Ontario and Nevada this week. [1]',
+ result_count: 1,
+ run_result_count: 1,
+ results: [
+ {
+ id: 'https://example.com/announcement',
+ title: 'New battery recycling facility announced',
+ url: 'https://example.com/announcement',
+ published_date: '2026-09-04T00:00:00.000Z',
+ author: null,
+ text: null,
+ highlights: null,
+ summary: null,
+ image: 'https://example.com/announcement/cover.webp',
+ },
+ ],
+ citations: [
+ {
+ field: 'content',
+ url: 'https://example.com/announcement',
+ title: 'New battery recycling facility announced',
+ confidence: 'high',
+ },
+ ],
+ run_citations: [
+ {
+ field: 'content',
+ url: 'https://example.com/announcement',
+ title: 'New battery recycling facility announced',
+ confidence: 'high',
+ },
+ ],
+ };
+}
+
+const STORE_KEY = 'exa_search_monitor';
+const SEEN_EVENT_LIMIT = 50;
+const SEEN_KEY = 'exa_search_monitor_seen';
+const SEEN_URL_LIMIT = 500;
+const DELETE_RETRY_DELAYS_MS = [500, 1500];
+
+type SeenState = {
+ eventIds: string[];
+ urls: string[];
+};
+
+type MonitorState = {
+ monitorId: string | null;
+ webhookSecret: string | null;
+ stale: string[];
+};
+
+type MonitorRun = {
+ id: string | null;
+ monitorId: string | null;
+ status: string | null;
+ failReason: string | null;
+ content: unknown;
+ results: unknown[];
+ grounding: unknown[];
+};
+
+type MonitorEvent = {
+ id: string | undefined;
+ type: string;
+ createdAt: string | undefined;
+ data: MonitorRun | undefined;
+};
+
+type FlatMonitorResult = {
+ id: string | null;
+ title: string | null;
+ url: string | null;
+ published_date: string | null;
+ author: string | null;
+ text: string | null;
+ highlights: string | null;
+ summary: string | null;
+ image: string | null;
+};
+
+type FlatMonitorRun = {
+ event_id: string | null;
+ event_created_at: string | null;
+ run_id: string | null;
+ monitor_id: string | null;
+ status: string | null;
+ fail_reason: string | null;
+ summary: string | null;
+ run_summary: string | null;
+ result_count: number;
+ run_result_count: number;
+ results: FlatMonitorResult[];
+ citations: MonitorCitation[];
+ run_citations: MonitorCitation[];
+};
+
+type MonitorCitation = {
+ field: string | null;
+ url: string | null;
+ title: string | null;
+ confidence: string | null;
+};
diff --git a/packages/pieces/community/exa/test/ai-twins.test.ts b/packages/pieces/community/exa/test/ai-twins.test.ts
new file mode 100644
index 00000000000..515c2eb5955
--- /dev/null
+++ b/packages/pieces/community/exa/test/ai-twins.test.ts
@@ -0,0 +1,192 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { exaSearchAction } from '../src/lib/actions/ai/exa-search';
+import { exaGetContentsAction } from '../src/lib/actions/ai/exa-get-contents';
+import { exaAnswerAction } from '../src/lib/actions/ai/exa-answer';
+import { lastRequest, ok, runAction, sendRequest } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('exa_search', () => {
+ it('sends include and exclude domains together, as the Exa spec allows', async () => {
+ ok({ body: { results: [] } });
+ await runAction({
+ action: exaSearchAction,
+ propsValue: { query: 'q', includeText: false, includeDomains: ['example.com'], excludeDomains: ['example.com/careers'] },
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().body).toEqual({
+ query: 'q',
+ type: 'auto',
+ includeDomains: ['example.com'],
+ excludeDomains: ['example.com/careers'],
+ });
+ });
+
+ it('refuses date filters with the company category', async () => {
+ await expect(
+ runAction({ action: exaSearchAction, propsValue: { query: 'q', category: 'company', startPublishedDate: '2026-01-01T00:00:00Z' } }),
+ ).rejects.toThrow(/company category/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('refuses an unknown search type and a malformed country before calling Exa', async () => {
+ await expect(runAction({ action: exaSearchAction, propsValue: { query: 'q', type: 'semantic' } })).rejects.toThrow(
+ /Search Type must be one of/,
+ );
+ await expect(runAction({ action: exaSearchAction, propsValue: { query: 'q', userLocation: 'USA' } })).rejects.toThrow(
+ /two-letter country code/,
+ );
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('flattens results to the output schema keys and reports cost', async () => {
+ ok({
+ body: {
+ results: [{ id: 'u', title: 'T', url: 'https://t.com', highlights: ['a', 'b'], favicon: 'https://t.com/f.ico' }],
+ costDollars: { total: 0.007 },
+ },
+ });
+ const result = await runAction({
+ action: exaSearchAction,
+ propsValue: { query: 'q', includeText: true, highlightsQuery: 'why', userLocation: 'de' },
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().body).toEqual({
+ query: 'q',
+ type: 'auto',
+ userLocation: 'DE',
+ contents: { text: true, highlights: { query: 'why' } },
+ });
+ expect(result).toEqual({
+ count: 1,
+ cost_total: 0.007,
+ results: [
+ {
+ id: 'u',
+ title: 'T',
+ url: 'https://t.com',
+ published_date: null,
+ author: null,
+ text: null,
+ highlights: 'a\nb',
+ summary: null,
+ image: null,
+ },
+ ],
+ });
+ });
+});
+
+describe('exa_get_contents', () => {
+ it('surfaces failed URLs', async () => {
+ ok({
+ body: {
+ results: [{ id: 'https://a.com', url: 'https://a.com', text: 'x' }],
+ statuses: [
+ { id: 'https://a.com', status: 'success', source: 'cached' },
+ { id: 'https://bad.example', status: 'error', error: { tag: 'CRAWL_NOT_FOUND', httpStatusCode: 404 } },
+ ],
+ },
+ });
+ const result = await runAction({ action: exaGetContentsAction, propsValue: { urls: ['https://a.com', 'https://bad.example'] } });
+ expect(result).toMatchObject({
+ failed_count: 1,
+ statuses: [
+ { url: 'https://a.com', status: 'success', source: 'cached', error_tag: null },
+ { url: 'https://bad.example', status: 'error', error_tag: 'CRAWL_NOT_FOUND', error_http_status: 404 },
+ ],
+ });
+ });
+
+ it('returns each page\'s subpages instead of dropping them', async () => {
+ ok({
+ body: {
+ results: [{ id: 'https://a.com', url: 'https://a.com', subpages: [{ id: 'https://a.com/pricing', url: 'https://a.com/pricing', title: 'Pricing', text: 'p', favicon: 'f' }] }],
+ statuses: [{ id: 'https://a.com', status: 'success' }],
+ },
+ });
+ const result = await runAction({ action: exaGetContentsAction, propsValue: { urls: ['https://a.com'], subpages: 1, subpageTarget: 'pricing' } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().body).toMatchObject({ subpages: 1, subpageTarget: 'pricing' });
+ expect(result).toMatchObject({
+ results: [{ url: 'https://a.com', subpages: [{ url: 'https://a.com/pricing', title: 'Pricing', text: 'p' }] }],
+ failed_count: 0,
+ });
+ expect(JSON.stringify(result)).not.toContain('favicon');
+ });
+
+ it('counts each failed URL once, and a subpage status cannot hide a failed page', async () => {
+ ok({
+ body: {
+ results: [{ id: 'https://a.com', url: 'https://a.com' }],
+ statuses: [
+ { id: 'https://a.com', status: 'success' },
+ { id: 'https://b.com/sub', status: 'success' },
+ { id: 'https://b.com', status: 'error', error: { tag: 'CRAWL_NOT_FOUND', httpStatusCode: 404 } },
+ ],
+ },
+ });
+ const result = await runAction({ action: exaGetContentsAction, propsValue: { urls: ['https://a.com', 'https://b.com', 'https://b.com'] } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().body.urls).toEqual(['https://a.com', 'https://b.com']);
+ expect(result).toMatchObject({ failed_count: 1 });
+ });
+
+ it('counts a URL missing from the statuses as failed', async () => {
+ ok({ body: { results: [{ id: 'https://a.com', url: 'https://a.com', text: 'x' }] } });
+ const result = await runAction({ action: exaGetContentsAction, propsValue: { urls: ['https://a.com', 'https://b.com'] } });
+ expect(result).toMatchObject({ failed_count: 1, statuses: [] });
+ });
+
+ it('refuses a request that asks for no content before calling Exa', async () => {
+ await expect(runAction({ action: exaGetContentsAction, propsValue: { urls: ['https://a.com'], includeText: false } })).rejects.toThrow(
+ /Choose at least one thing to return/,
+ );
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('refuses more than 100 URLs before calling Exa', async () => {
+ const urls = Array.from({ length: 101 }, (_, index) => `https://a.com/${index}`);
+ await expect(runAction({ action: exaGetContentsAction, propsValue: { urls } })).rejects.toThrow(/at most 100 URLs/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('returns outgoing links per page', async () => {
+ ok({ body: { results: [{ id: 'https://a.com', url: 'https://a.com', extras: { links: ['https://a.com/x', 'https://a.com/y'] } }], statuses: [] } });
+ const result = await runAction({ action: exaGetContentsAction, propsValue: { urls: ['https://a.com'], linksPerPage: 2 } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().body.extras).toEqual({ links: 2 });
+ expect(result).toMatchObject({ results: [{ url: 'https://a.com', links: ['https://a.com/x', 'https://a.com/y'] }] });
+ });
+});
+
+describe('exa_answer', () => {
+ it('returns citations', async () => {
+ ok({ body: { answer: 'yes', citations: [{ id: 'c', title: 'C', url: 'https://c.com' }], costDollars: { total: 0.005 } } });
+ const result = await runAction({ action: exaAnswerAction, propsValue: { query: 'q' } });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().body).toEqual({ query: 'q', model: 'exa', text: false });
+ expect(result).toMatchObject({ answer: 'yes', citations: [{ id: 'c', title: 'C', url: 'https://c.com' }], cost_total: 0.005 });
+ });
+
+ it('returns a null answer, not the text "null", when Exa sends none', async () => {
+ ok({ body: { citations: [] } });
+ const result = await runAction({ action: exaAnswerAction, propsValue: { query: 'q' } });
+ expect(result).toMatchObject({ answer: null, citations: [] });
+ });
+
+ it('refuses an unknown model before calling Exa', async () => {
+ await expect(runAction({ action: exaAnswerAction, propsValue: { query: 'q', model: 'gpt-4' } })).rejects.toThrow(
+ /Model must be one of/,
+ );
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/exa/test/exa.test.ts b/packages/pieces/community/exa/test/exa.test.ts
new file mode 100644
index 00000000000..dd093698fe1
--- /dev/null
+++ b/packages/pieces/community/exa/test/exa.test.ts
@@ -0,0 +1,964 @@
+import crypto from 'crypto';
+import { Store } from '@activepieces/pieces-framework';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { performSearchAction } from '../src/lib/actions/perform-search';
+import { getContentsAction } from '../src/lib/actions/get-contents';
+import { generateAnswerAction } from '../src/lib/actions/generate-answer';
+import { findSimilarLinksAction } from '../src/lib/actions/find-similar-links';
+import { createAgentRunAction } from '../src/lib/actions/agent/create-agent-run';
+import { getAgentRunAction } from '../src/lib/actions/agent/get-agent-run';
+import { listAgentRunsAction } from '../src/lib/actions/agent/list-agent-runs';
+import { cancelAgentRunAction } from '../src/lib/actions/agent/cancel-agent-run';
+import { newSearchMonitorResultsTrigger as monitorTrigger } from '../src/lib/triggers/new-search-monitor-results';
+import { exaWebhookSignature } from '../src/lib/common/webhook-signature';
+import { exaInput } from '../src/lib/common/client';
+import { exa } from '../src/index';
+import { exaAuth } from '../src/lib/auth';
+import { asWebhook, fail, lastRequest, memoryStore, ok, runAction, sendRequest, webhookContext } from './helpers';
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ const { mockHttpClient } = await import('./helpers');
+ return { ...actual, ...mockHttpClient() };
+});
+
+const RUN = {
+ id: 'agent_run_01',
+ object: 'agent_run',
+ status: 'completed',
+ stopReason: 'schema_satisfied',
+ createdAt: '2026-09-29T10:00:00.000Z',
+ completedAt: '2026-09-29T10:01:00.000Z',
+ request: { query: 'q', effort: 'low' },
+ output: {
+ text: 'answer',
+ structured: { companies: [] },
+ grounding: [
+ { field: 'companies', citations: [{ url: 'https://a.com', title: 'A' }, { url: 'https://b.com' }], confidence: 'high' },
+ ],
+ },
+ usage: { agentComputeUnits: 1, searches: 3, emails: 0, phoneNumbers: 0 },
+ costDollars: { total: 0.025, agentCompute: 0, search: 0, emails: 0, phoneNumbers: 0 },
+};
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+function validateKey(auth: string) {
+ return exaAuth.validate?.({
+ auth,
+ server: {
+ apiUrl: 'http://localhost:3000',
+ publicUrl: 'http://localhost:4200',
+ mintOidcToken: async () => 'oidc-token',
+ },
+ });
+}
+
+describe('existing actions keep their default request', () => {
+ it('perform_search sends the same body as 0.2.1 when no new prop is set', async () => {
+ ok({ body: { results: [{ title: 't' }] } });
+ const result = await runAction({ action: performSearchAction, propsValue: { query: 'ai', type: 'auto', numResults: 10 } });
+ expect(lastRequest().body).toEqual({ query: 'ai', contents: { text: true }, type: 'auto', numResults: 10 });
+ expect(lastRequest().url).toBe('https://api.exa.ai/search');
+ expect(result).toEqual([{ title: 't' }]);
+ });
+
+ it('perform_search nests text limit, highlights and maxAgeHours under contents', async () => {
+ ok({ body: { results: [] } });
+ await runAction({
+ action: performSearchAction,
+ propsValue: {
+ query: 'ai',
+ textMaxCharacters: 500,
+ highlights: true,
+ maxAgeHours: 0,
+ userLocation: ' us ',
+ moderation: true,
+ },
+ });
+ expect(lastRequest().body).toEqual({
+ query: 'ai',
+ contents: { text: { maxCharacters: 500 }, highlights: true, maxAgeHours: 0 },
+ userLocation: 'US',
+ moderation: true,
+ });
+ });
+
+ it('perform_search refuses a country that is not a two-letter code before calling Exa', async () => {
+ await expect(
+ runAction({ action: performSearchAction, propsValue: { query: 'ai', userLocation: 'United States' } }),
+ ).rejects.toThrow(/two-letter country code/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('get_contents drops the deprecated livecrawl when maxAgeHours is set', async () => {
+ ok({ body: { results: [] } });
+ await runAction({
+ action: getContentsAction,
+ propsValue: { urls: ['https://a.com'], text: true, livecrawl: 'always', maxAgeHours: 24 },
+ });
+ expect(lastRequest().body).toEqual({ urls: ['https://a.com'], text: true, maxAgeHours: 24 });
+ });
+
+ it('describes only the result fields each action can return', () => {
+ const keysOf = (schema: typeof getContentsAction.outputSchema) => schema?.fields[0]?.listItems?.map((field) => field.key);
+ expect(keysOf(getContentsAction.outputSchema)).not.toContain('score');
+ expect(keysOf(getContentsAction.outputSchema)).toEqual(expect.arrayContaining(['extras', 'subpages', 'summary']));
+ expect(keysOf(performSearchAction.outputSchema)).not.toContain('summary');
+ expect(keysOf(findSimilarLinksAction.outputSchema)).toEqual(expect.not.arrayContaining(['text', 'highlights', 'summary']));
+ });
+
+ it('get_contents keeps livecrawl when maxAgeHours is not set', async () => {
+ ok({ body: { results: [] } });
+ await runAction({
+ action: getContentsAction,
+ propsValue: { urls: ['https://a.com'], text: true, livecrawl: 'fallback', summaryQuery: 'who?', extrasLinks: 5 },
+ });
+ expect(lastRequest().body).toEqual({
+ urls: ['https://a.com'],
+ text: true,
+ livecrawl: 'fallback',
+ summary: { query: 'who?' },
+ extras: { links: 5 },
+ });
+ });
+
+ it('generate_answer still returns the answer string and adds optional instructions', async () => {
+ ok({ body: { answer: '42', citations: [] } });
+ const result = await runAction({
+ action: generateAnswerAction,
+ propsValue: { query: 'q', text: false, model: 'exa-fast', systemPrompt: 'short' },
+ });
+ expect(result).toBe('42');
+ expect(lastRequest().body).toEqual({ query: 'q', text: false, model: 'exa-fast', systemPrompt: 'short' });
+ });
+});
+
+describe('custom API call', () => {
+ const customApiCall = exa.actions()['custom_api_call'];
+
+ function callWithUrl(url: string) {
+ return runAction({
+ action: customApiCall,
+ propsValue: { url: { url }, method: 'GET', headers: {}, queryParams: {}, failsafe: false },
+ });
+ }
+
+ it('sends the secret text, not [object Object]', async () => {
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }));
+ await callWithUrl('/agent/runs');
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy.mock.calls[0][0]).toBe('https://api.exa.ai/agent/runs');
+ expect(new Headers(fetchSpy.mock.calls[0][1]?.headers).get('x-api-key')).toBe('exa_test_key');
+ fetchSpy.mockRestore();
+ });
+
+ it('accepts a full URL on api.exa.ai', async () => {
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }));
+ await callWithUrl('https://api.exa.ai/agent/runs');
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(new Headers(fetchSpy.mock.calls[0][1]?.headers).get('x-api-key')).toBe('exa_test_key');
+ fetchSpy.mockRestore();
+ });
+
+ it.each([
+ 'https://api.exa.ai.evil.io/search',
+ 'https://evil.io/search',
+ 'http://api.exa.ai/search',
+ 'https://[email protected]/search',
+ 'https://api.exa.ai:8443/search',
+ ])('never sends the API key to %s', async (url) => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}', { status: 200 }));
+ await expect(callWithUrl(url)).rejects.toThrow(/only sends your Exa API key/);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+});
+
+describe('custom API call redirects', () => {
+ it('does not follow redirects when the option was never saved on the step', async () => {
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }));
+ await runAction({
+ action: exa.actions()['custom_api_call'],
+ propsValue: { url: { url: '/agent/runs' }, method: 'GET', headers: {}, queryParams: {}, failsafe: false },
+ });
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy.mock.calls[0][1]?.redirect).toBe('manual');
+ fetchSpy.mockRestore();
+ });
+
+ it('refuses Follow redirects, which could carry the key to another host', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}', { status: 200 }));
+ await expect(
+ runAction({
+ action: exa.actions()['custom_api_call'],
+ propsValue: { url: { url: '/agent/runs' }, method: 'GET', headers: {}, queryParams: {}, failsafe: false, followRedirects: true },
+ }),
+ ).rejects.toThrow(/Follow redirects is not supported/);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+});
+
+describe('legacy actions', () => {
+ it('find_similar_links sends the reference URL and filters as before', async () => {
+ ok({ body: { results: [{ url: 'https://b.com', score: 0.9 }] } });
+ const result = await runAction({
+ action: findSimilarLinksAction,
+ propsValue: { url: 'https://a.com', numResults: 2, includeDomains: ['b.com'], startPublishedDate: '2026-01-01T00:00:00Z' },
+ });
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest()).toMatchObject({ method: 'POST', url: 'https://api.exa.ai/findSimilar' });
+ expect(lastRequest().body).toEqual({ url: 'https://a.com', numResults: 2, includeDomains: ['b.com'], startPublishedDate: '2026-01-01T00:00:00Z' });
+ expect(result).toEqual([{ url: 'https://b.com', score: 0.9 }]);
+ });
+
+ it.each([
+ [402, /insufficient credits/],
+ [429, /rate limit/],
+ ])('maps a %s from Exa to a clear message', async (status, message) => {
+ fail({ status, body: { error: 'vendor detail' } });
+ await expect(runAction({ action: performSearchAction, propsValue: { query: 'q' } })).rejects.toThrow(message);
+ });
+});
+
+describe('redirects from Exa', () => {
+ it.each([
+ ['an agent-run action', () => runAction({ action: getAgentRunAction, propsValue: { runId: 'agent_run_01' } })],
+ ['a legacy action', () => runAction({ action: performSearchAction, propsValue: { query: 'q' } })],
+ ])('%s asks not to follow redirects and fails on a 3xx', async (_name, call) => {
+ sendRequest.mockResolvedValueOnce({ status: 302, headers: { location: 'https://elsewhere.example/' }, body: '' });
+ await expect(call()).rejects.toThrow(/redirect \(302\)/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().followRedirects).toBe(false);
+ });
+});
+
+describe('auth.validate', () => {
+ it('uses the non-billable list endpoint', async () => {
+ ok({ body: { data: [] } });
+ await expect(validateKey('k')).resolves.toEqual({ valid: true });
+ expect(lastRequest().method).toBe('GET');
+ expect(lastRequest().url).toBe('https://api.exa.ai/agent/runs');
+ expect(lastRequest().queryParams).toEqual({ limit: '1' });
+ });
+
+ it('says invalid key only on 401', async () => {
+ fail({ status: 401 });
+ await expect(validateKey('k')).resolves.toEqual({ valid: false, error: 'Invalid API Key.' });
+ });
+
+ it('says invalid key on 403', async () => {
+ fail({ status: 403 });
+ await expect(validateKey('k')).resolves.toEqual({ valid: false, error: 'Invalid API Key.' });
+ });
+
+ it('does not blame the key on a server error', async () => {
+ fail({ status: 503 });
+ const result = await validateKey('k');
+ expect(result).toMatchObject({ valid: false });
+ expect(JSON.stringify(result)).toContain('HTTP 503');
+ });
+});
+
+describe('input parsing', () => {
+ it('accepts numbers sent as text', () => {
+ expect(exaInput.optionalInteger({ value: '500', name: 'Limit', min: 1, max: 1000 })).toBe(500);
+ expect(() => exaInput.optionalInteger({ value: '1.5', name: 'Limit', min: 1, max: 1000 })).toThrow(/whole number/);
+ });
+
+ it('drops blank list entries and treats an empty list as not set', () => {
+ expect(exaInput.stringList(['a.com', ' ', 'b.com'])).toEqual(['a.com', 'b.com']);
+ expect(exaInput.stringList([' '])).toBeUndefined();
+ });
+});
+
+describe('agent runs', () => {
+ it('defaults effort to low when the caller omits it', async () => {
+ ok({ body: { ...RUN, status: 'queued', output: { text: '', structured: null, grounding: [] } } });
+ const result = await runAction({ action: createAgentRunAction, propsValue: { query: 'find things' } });
+ expect(lastRequest().body).toEqual({ query: 'find things', effort: 'low' });
+ expect(result).toMatchObject({ id: 'agent_run_01', status: 'queued' });
+ });
+
+ it('refuses a budget on a fixed effort before calling Exa', async () => {
+ await expect(
+ runAction({ action: createAgentRunAction, propsValue: { query: 'q', effort: 'low', maxCostDollars: 2 } }),
+ ).rejects.toThrow(/Auto or Ultra/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('sends budget, schema and metadata for a metered effort', async () => {
+ ok({ body: RUN });
+ await runAction({
+ action: createAgentRunAction,
+ propsValue: {
+ query: 'q',
+ effort: 'auto',
+ maxCostDollars: 3,
+ outputSchema: '{"type":"object"}',
+ metadata: { flow: 'x', empty: '' },
+ previousRunId: 'agent_run_00',
+ },
+ });
+ expect(lastRequest().body).toEqual({
+ query: 'q',
+ effort: 'auto',
+ outputSchema: { type: 'object' },
+ budget: { maxCostDollars: 3 },
+ previousRunId: 'agent_run_00',
+ metadata: { flow: 'x' },
+ });
+ });
+
+ it('rejects an unknown effort', async () => {
+ await expect(runAction({ action: createAgentRunAction, propsValue: { query: 'q', effort: 'max' } })).rejects.toThrow(
+ /Effort must be one of/,
+ );
+ });
+
+ it('flattens a run with citations per grounding entry', async () => {
+ ok({ body: RUN });
+ const result = await runAction({ action: getAgentRunAction, propsValue: { runId: ' agent_run_01 ' } });
+ expect(lastRequest().url).toBe('https://api.exa.ai/agent/runs/agent_run_01');
+ expect(result).toEqual({
+ id: 'agent_run_01',
+ status: 'completed',
+ stop_reason: 'schema_satisfied',
+ created_at: '2026-09-29T10:00:00.000Z',
+ completed_at: '2026-09-29T10:01:00.000Z',
+ query: 'q',
+ effort: 'low',
+ output_text: 'answer',
+ output_structured: { companies: [] },
+ citations: [
+ { field: 'companies', url: 'https://a.com', title: 'A', confidence: 'high' },
+ { field: 'companies', url: 'https://b.com', title: null, confidence: 'high' },
+ ],
+ search_count: 3,
+ agent_compute_units: 1,
+ cost_total: 0.025,
+ });
+ });
+
+ it.each([
+ ['get', getAgentRunAction],
+ ['cancel', cancelAgentRunAction],
+ ])('%s refuses a blank run id instead of calling the list route', async (_name, action) => {
+ await expect(runAction({ action, propsValue: { runId: ' ' } })).rejects.toThrow(/Run ID is required/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('cancel posts to the cancel route', async () => {
+ ok({ body: { ...RUN, status: 'cancelled' } });
+ await runAction({ action: cancelAgentRunAction, propsValue: { runId: 'agent_run_01' } });
+ expect(lastRequest().method).toBe('POST');
+ expect(lastRequest().url).toBe('https://api.exa.ai/agent/runs/agent_run_01/cancel');
+ });
+
+ it('list returns one page with the cursor, not a total', async () => {
+ ok({ body: { object: 'list', data: [RUN], hasMore: true, nextCursor: 'agent_run_00' } });
+ const result = await runAction({ action: listAgentRunsAction, propsValue: { limit: 1, cursor: '' } });
+ expect(lastRequest().queryParams).toEqual({ limit: '1' });
+ expect(result).toMatchObject({ count: 1, has_more: true, next_cursor: 'agent_run_00' });
+ });
+
+ it('maps the Agent API error shape into the message', async () => {
+ fail({ status: 429, body: { error: { type: 'rate_limit', code: 'CONCURRENCY_LIMIT', message: 'too many runs' } } });
+ await expect(runAction({ action: getAgentRunAction, propsValue: { runId: 'x' } })).rejects.toThrow(
+ /429.*CONCURRENCY_LIMIT too many runs/,
+ );
+ });
+});
+
+const SECRET = 'whsec_fixture_secret';
+const STORE_KEY = 'exa_search_monitor';
+const BODY = JSON.stringify({
+ id: 'event_1',
+ object: 'event',
+ type: 'monitor.run.completed',
+ data: {
+ id: 'run_1',
+ monitorId: 'mon_1',
+ status: 'completed',
+ output: {
+ results: [{ title: 'R', url: 'https://r.com', publishedDate: '2026-09-01' }],
+ content: 'summary',
+ grounding: [{ field: 'content', citations: [{ title: 'R', url: 'https://r.com' }], confidence: 'high' }],
+ },
+ failReason: null,
+ metadata: null,
+ },
+ createdAt: '2026-09-29T10:00:00.000Z',
+});
+
+const NOW_T = String(Math.floor(Date.now() / 1000));
+
+function sign({ body, timestamp, secret }: { body: string; timestamp: string; secret: string }) {
+ const v1 = crypto.createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
+ return `t=${timestamp},v1=${v1}`;
+}
+
+describe('signature', () => {
+ it('accepts a signature built as t.rawBody', () => {
+ const header = sign({ body: BODY, timestamp: NOW_T, secret: SECRET });
+ expect(exaWebhookSignature.verify({ secret: SECRET, signatureHeader: header, rawBody: BODY })).toBe(true);
+ });
+
+ it('rejects a tampered body, a wrong secret, a parsed body and a garbage header', () => {
+ const header = sign({ body: BODY, timestamp: NOW_T, secret: SECRET });
+ expect(exaWebhookSignature.verify({ secret: SECRET, signatureHeader: header, rawBody: BODY.replace('R', 'X') })).toBe(false);
+ expect(exaWebhookSignature.verify({ secret: 'other', signatureHeader: header, rawBody: BODY })).toBe(false);
+ expect(exaWebhookSignature.verify({ secret: SECRET, signatureHeader: header, rawBody: JSON.parse(BODY) })).toBe(false);
+ expect(exaWebhookSignature.verify({ secret: SECRET, signatureHeader: 't=1,v1=zz', rawBody: BODY })).toBe(false);
+ expect(exaWebhookSignature.verify({ secret: SECRET, signatureHeader: undefined, rawBody: BODY })).toBe(false);
+ });
+
+ it('accepts a correctly signed delivery only within 15 minutes, in seconds or milliseconds', () => {
+ const nowMs = Date.parse('2026-09-30T12:00:00Z');
+ const at = ({ ms, unit }: { ms: number; unit: 's' | 'ms' }) =>
+ sign({ body: BODY, timestamp: String(unit === 's' ? Math.floor(ms / 1000) : ms), secret: SECRET });
+ const verifyAt = (header: string) => exaWebhookSignature.verify({ secret: SECRET, signatureHeader: header, rawBody: BODY, nowMs });
+ expect(verifyAt(at({ ms: nowMs - 60_000, unit: 's' }))).toBe(true);
+ expect(verifyAt(at({ ms: nowMs - 60_000, unit: 'ms' }))).toBe(true);
+ expect(verifyAt(at({ ms: nowMs - 899_000, unit: 's' }))).toBe(true);
+ expect(verifyAt(at({ ms: nowMs - 899_000, unit: 'ms' }))).toBe(true);
+ expect(verifyAt(at({ ms: nowMs - 901_000, unit: 's' }))).toBe(false);
+ expect(verifyAt(at({ ms: nowMs - 901_000, unit: 'ms' }))).toBe(false);
+ expect(verifyAt(at({ ms: nowMs - 16 * 60_000, unit: 's' }))).toBe(false);
+ expect(verifyAt(at({ ms: nowMs + 16 * 60_000, unit: 's' }))).toBe(false);
+ });
+
+ it('still accepts a delivery that waited 6 minutes in the Activepieces job queue', () => {
+ const nowMs = Date.parse('2026-09-30T12:00:00Z');
+ const header = sign({ body: BODY, timestamp: String(Math.floor((nowMs - 6 * 60_000) / 1000)), secret: SECRET });
+ expect(exaWebhookSignature.verify({ secret: SECRET, signatureHeader: header, rawBody: BODY, nowMs })).toBe(true);
+ });
+});
+
+describe('new_search_monitor_results trigger', () => {
+ const newSearchMonitorResultsTrigger = asWebhook(monitorTrigger);
+ const STATE = { [STORE_KEY]: { monitorId: 'mon_1', webhookSecret: SECRET } };
+
+ it('creates a monitor pointed at the webhook URL and stores its id and secret', async () => {
+ const { store, data } = memoryStore();
+ ok({ status: 201, body: { id: 'mon_1', webhookSecret: SECRET } });
+ await newSearchMonitorResultsTrigger.onEnable(
+ webhookContext({
+ store,
+ propsValue: { query: 'battery recycling', period: '1d', numResults: 5, includeHighlights: true },
+ }),
+ );
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().url).toBe('https://api.exa.ai/monitors');
+ expect(lastRequest().body).toEqual({
+ name: 'Activepieces flow test-flow-id',
+ search: { query: 'battery recycling', numResults: 5, contents: { highlights: true } },
+ trigger: { type: 'interval', period: '1d' },
+ webhook: { url: 'https://hooks.example.com/abc', events: ['monitor.run.completed'] },
+ });
+ expect(data[STORE_KEY]).toEqual({ monitorId: 'mon_1', webhookSecret: SECRET, stale: [] });
+ });
+
+ it('refuses a non-HTTPS webhook URL before creating a monitor', async () => {
+ const { store } = memoryStore();
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(
+ webhookContext({ store, webhookUrl: 'http://localhost:4200/api/v1/webhooks/abc', propsValue: { query: 'q', period: '1d' } }),
+ ),
+ ).rejects.toThrow(/public HTTPS address/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('deletes the monitor and fails when Exa returns no webhook secret', async () => {
+ const { store, data } = memoryStore();
+ ok({ status: 201, body: { id: 'mon_1' } });
+ ok({ body: {} });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/without a webhook secret/);
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(lastRequest().method).toBe('DELETE');
+ expect(lastRequest().url).toBe('https://api.exa.ai/monitors/mon_1');
+ expect(data[STORE_KEY]).toBeUndefined();
+ });
+
+ it('creates the replacement before deleting the monitor left from a failed disable', async () => {
+ const { store, data } = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old' } });
+ ok({ status: 201, body: { id: 'mon_new', webhookSecret: SECRET } });
+ ok({ body: {} });
+ await newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(sendRequest.mock.calls[0][0]).toMatchObject({ method: 'POST', url: 'https://api.exa.ai/monitors' });
+ expect(sendRequest.mock.calls[1][0]).toMatchObject({ method: 'DELETE', url: 'https://api.exa.ai/monitors/mon_old' });
+ expect(data[STORE_KEY]).toEqual({ monitorId: 'mon_new', webhookSecret: SECRET, stale: [] });
+ });
+
+ it('keeps the existing monitor and its secret when creating the replacement fails', async () => {
+ const { store, data } = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old' } });
+ fail({ status: 500 });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/500/);
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest().method).toBe('POST');
+ expect(data[STORE_KEY]).toEqual({ monitorId: 'mon_old', webhookSecret: 'old' });
+ });
+
+ it('remembers a leftover monitor it could not delete and removes it on the next disable', async () => {
+ const { store, data } = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old' } });
+ ok({ status: 201, body: { id: 'mon_new', webhookSecret: SECRET } });
+ fail({ status: 403 });
+ await newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ expect(data[STORE_KEY]).toEqual({ monitorId: 'mon_new', webhookSecret: SECRET, stale: ['mon_old'] });
+
+ sendRequest.mockReset();
+ ok({ body: {} });
+ ok({ body: {} });
+ await newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(sendRequest.mock.calls.map(([request]) => request.url)).toEqual([
+ 'https://api.exa.ai/monitors/mon_new',
+ 'https://api.exa.ai/monitors/mon_old',
+ ]);
+ expect(data[STORE_KEY]).toBeUndefined();
+ });
+
+ it('keeps the old monitor ID when its delete fails and the cleanup write fails too', async () => {
+ const memory = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old', stale: [] } });
+ let puts = 0;
+ const store: Store = {
+ ...memory.store,
+ put: async (key, value) => {
+ puts += 1;
+ if (puts === 2) {
+ throw new Error('store down');
+ }
+ return memory.store.put(key, value);
+ },
+ };
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ ok({ status: 201, body: { id: 'mon_new', webhookSecret: SECRET } });
+ fail({ status: 403 });
+ await newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ warn.mockRestore();
+ expect(puts).toBe(2);
+ expect(memory.data[STORE_KEY]).toEqual({ monitorId: 'mon_new', webhookSecret: SECRET, stale: ['mon_old'] });
+ });
+
+ it.each([1, 2])('never loses a monitor ID when store write %i of an enable fails', async (failingPut) => {
+ const memory = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old', stale: ['mon_older'] } });
+ let puts = 0;
+ const store: Store = {
+ ...memory.store,
+ put: async (key, value) => {
+ puts += 1;
+ if (puts === failingPut) {
+ throw new Error('store down');
+ }
+ return memory.store.put(key, value);
+ },
+ };
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ ok({ status: 201, body: { id: 'mon_new', webhookSecret: SECRET } });
+ fail({ status: 403 });
+ fail({ status: 403 });
+ fail({ status: 403 });
+ await newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })).catch(() => undefined);
+ warn.mockRestore();
+ const deleted = sendRequest.mock.calls
+ .map(([request]) => request)
+ .filter((request) => request.method === 'DELETE')
+ .map((request) => String(request.url).split('/').pop());
+ const state = memory.data[STORE_KEY];
+ const reachable = [state?.monitorId, ...(state?.stale ?? [])];
+ for (const id of ['mon_old', 'mon_older']) {
+ expect(reachable).toContain(id);
+ }
+ if (!reachable.includes('mon_new')) {
+ expect(deleted).toContain('mon_new');
+ }
+ });
+
+ it('records the new monitor for cleanup when Exa sends no secret and the rollback delete fails', async () => {
+ const { store, data } = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old', stale: [] } });
+ ok({ status: 201, body: { id: 'mon_new' } });
+ fail({ status: 403 });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/mon_new could not be deleted/);
+ expect(data[STORE_KEY]).toEqual({ monitorId: 'mon_old', webhookSecret: 'old', stale: ['mon_new'] });
+ });
+
+ it('names the new monitor when Exa sends no secret, the rollback fails and the cleanup write fails', async () => {
+ const memory = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old', stale: [] } });
+ const store: Store = { ...memory.store, put: async () => { throw new Error('store down'); } };
+ ok({ status: 201, body: { id: 'mon_new' } });
+ fail({ status: 403 });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/store down.*mon_new could not be deleted/);
+ });
+
+ it('names the new monitor when saving it fails and the rollback fails', async () => {
+ const memory = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old', stale: [] } });
+ const store: Store = { ...memory.store, put: async () => { throw new Error('store down'); } };
+ ok({ status: 201, body: { id: 'mon_new', webhookSecret: SECRET } });
+ fail({ status: 403 });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/store down.*mon_new could not be deleted/);
+ expect(memory.data[STORE_KEY]).toEqual({ monitorId: 'mon_old', webhookSecret: 'old', stale: [] });
+ });
+
+ it('names the monitor when a disable cannot delete it', async () => {
+ const { store, data } = memoryStore(STATE);
+ fail({ status: 403 });
+ await expect(
+ newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/Could not delete the Exa monitor mon_1/);
+ expect(data[STORE_KEY]).toMatchObject({ monitorId: 'mon_1' });
+ });
+
+ it('names the monitors still to delete when the cleanup list cannot be saved', async () => {
+ const memory = memoryStore({ [STORE_KEY]: { monitorId: 'mon_old', webhookSecret: 'old', stale: [] } });
+ let puts = 0;
+ const store: Store = {
+ ...memory.store,
+ put: async (key, value) => {
+ puts += 1;
+ if (puts === 2) {
+ throw new Error('store down');
+ }
+ return memory.store.put(key, value);
+ },
+ };
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ ok({ status: 201, body: { id: 'mon_new', webhookSecret: SECRET } });
+ fail({ status: 403 });
+ await newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0][0])).toMatch(/Monitors still to delete: mon_old/);
+ warn.mockRestore();
+ });
+
+ it('keeps every monitor ID when a disable cannot finish its cleanup', async () => {
+ const memory = memoryStore({ [STORE_KEY]: { monitorId: 'mon_1', webhookSecret: SECRET, stale: ['mon_old'] } });
+ const store: Store = {
+ ...memory.store,
+ put: async () => {
+ throw new Error('store down');
+ },
+ delete: async () => {
+ throw new Error('store down');
+ },
+ };
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ ok({ body: {} });
+ fail({ status: 403 });
+ await newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ warn.mockRestore();
+ expect(memory.data[STORE_KEY]).toEqual({ monitorId: 'mon_1', webhookSecret: SECRET, stale: ['mon_old'] });
+ });
+
+ it('names the monitor to delete by hand when the rollback delete fails', async () => {
+ const { store } = memoryStore();
+ ok({ status: 201, body: { id: 'mon_1' } });
+ fail({ status: 403 });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/mon_1 could not be deleted/);
+ });
+
+ it('deletes the monitor it created if storing the id fails', async () => {
+ const { store, failNextPut } = memoryStore();
+ failNextPut(new Error('store down'));
+ ok({ status: 201, body: { id: 'mon_1', webhookSecret: SECRET } });
+ ok({ body: {} });
+ await expect(
+ newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1h' } })),
+ ).rejects.toThrow(/store down/);
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(lastRequest().method).toBe('DELETE');
+ expect(lastRequest().url).toBe('https://api.exa.ai/monitors/mon_1');
+ });
+
+ it('forgets the monitor on disable, treating 404 as already deleted', async () => {
+ const { store, data } = memoryStore(STATE);
+ fail({ status: 404 });
+ await newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ expect(data[STORE_KEY]).toBeUndefined();
+ });
+
+ it('keeps the monitor id when the delete is refused, without retrying', async () => {
+ const { store, data } = memoryStore(STATE);
+ fail({ status: 403 });
+ await expect(
+ newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow();
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(data[STORE_KEY]).toBeDefined();
+ });
+
+ it('retries the delete on 429 and 5xx before forgetting the monitor', async () => {
+ vi.useFakeTimers();
+ const { store, data } = memoryStore(STATE);
+ fail({ status: 429 });
+ fail({ status: 503 });
+ ok({ body: {} });
+ const disabling = newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ await vi.runAllTimersAsync();
+ await disabling;
+ vi.useRealTimers();
+ expect(sendRequest).toHaveBeenCalledTimes(3);
+ expect(sendRequest.mock.calls.every(([request]) => request.method === 'DELETE')).toBe(true);
+ expect(data[STORE_KEY]).toBeUndefined();
+ });
+
+ it('gives up after 3 delete attempts and keeps the monitor id', async () => {
+ const { store, data } = memoryStore(STATE);
+ fail({ status: 500 });
+ fail({ status: 500 });
+ fail({ status: 500 });
+ vi.useFakeTimers();
+ const disabling = expect(
+ newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } })),
+ ).rejects.toThrow(/500/);
+ await vi.runAllTimersAsync();
+ await disabling;
+ vi.useRealTimers();
+ expect(sendRequest).toHaveBeenCalledTimes(3);
+ expect(data[STORE_KEY]).toMatchObject({ monitorId: 'mon_1' });
+ });
+
+ it('builder Test runs one search, maps it to the run shape and never creates a monitor', async () => {
+ const { store, data } = memoryStore();
+ ok({ body: { results: [{ id: 'u', title: 'T', url: 'https://t.com', publishedDate: '2026-09-28 00:00:00.000000000', highlights: ['a', 'b'] }] } });
+ const result = await newSearchMonitorResultsTrigger.test(
+ webhookContext({ store, propsValue: { query: 'q', period: '1d', numResults: 3, includeDomains: ['t.com'], includeHighlights: true } }),
+ );
+ expect(monitorTrigger.testStrategy).toBe('TEST_FUNCTION');
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ expect(lastRequest()).toMatchObject({ method: 'POST', url: 'https://api.exa.ai/search' });
+ expect(lastRequest().body).toEqual({ query: 'q', numResults: 3, includeDomains: ['t.com'], contents: { highlights: true } });
+ expect(result).toEqual([
+ expect.objectContaining({
+ status: 'completed',
+ result_count: 1,
+ results: [expect.objectContaining({ url: 'https://t.com', published_date: '2026-09-28T00:00:00.000Z', highlights: 'a\nb' })],
+ }),
+ ]);
+ expect(data).toEqual({});
+ });
+
+ it('emits one flattened run for a correctly signed delivery and dedupes a retry', async () => {
+ const { store } = memoryStore(STATE);
+ const payload = {
+ body: JSON.parse(BODY),
+ rawBody: BODY,
+ headers: { 'Exa-Signature': sign({ body: BODY, timestamp: NOW_T, secret: SECRET }) },
+ queryParams: {},
+ };
+ const context = webhookContext({ store, payload, propsValue: { query: 'q', period: '1d' } });
+ const first = await newSearchMonitorResultsTrigger.run(context);
+ expect(first).toEqual([
+ expect.objectContaining({
+ event_id: 'event_1',
+ run_id: 'run_1',
+ monitor_id: 'mon_1',
+ status: 'completed',
+ summary: 'summary',
+ result_count: 1,
+ results: [expect.objectContaining({ title: 'R', url: 'https://r.com', published_date: '2026-09-01' })],
+ citations: [{ field: 'content', url: 'https://r.com', title: 'R', confidence: 'high' }],
+ }),
+ ]);
+ const retry = await newSearchMonitorResultsTrigger.run(context);
+ expect(retry).toEqual([]);
+ });
+
+ it.each([
+ ['another monitor', { monitorId: 'mon_other' }, 'monitor.run.completed'],
+ ['another event type', {}, 'monitor.run.created'],
+ ])('drops a signed delivery for %s', async (_name, dataPatch, type) => {
+ const { store } = memoryStore(STATE);
+ const parsed = JSON.parse(BODY);
+ const body = JSON.stringify({ ...parsed, type, data: { ...parsed.data, ...dataPatch } });
+ const result = await newSearchMonitorResultsTrigger.run(
+ webhookContext({
+ store,
+ payload: {
+ body: JSON.parse(body),
+ rawBody: body,
+ headers: { 'exa-signature': sign({ body, timestamp: NOW_T, secret: SECRET }) },
+ queryParams: {},
+ },
+ propsValue: { query: 'q', period: '1d' },
+ }),
+ );
+ expect(result).toEqual([]);
+ });
+
+ it('does not re-emit results already delivered, also after a republish', async () => {
+ const { store, data } = memoryStore(STATE);
+ const deliver = async ({ eventId, monitorId, urls }: { eventId: string; monitorId: string; urls: string[] }) => {
+ const parsed = JSON.parse(BODY);
+ const body = JSON.stringify({
+ ...parsed,
+ id: eventId,
+ data: { ...parsed.data, id: `run_${eventId}`, monitorId, output: { ...parsed.data.output, results: urls.map((url) => ({ title: url, url })) } },
+ });
+ return newSearchMonitorResultsTrigger.run(
+ webhookContext({
+ store,
+ payload: { body: JSON.parse(body), rawBody: body, headers: { 'exa-signature': sign({ body, timestamp: NOW_T, secret: SECRET }) }, queryParams: {} },
+ propsValue: { query: 'q', period: '1d' },
+ }),
+ );
+ };
+ const first = await deliver({ eventId: 'e1', monitorId: 'mon_1', urls: ['https://a.com', 'https://b.com'] });
+ expect(first).toEqual([expect.objectContaining({ result_count: 2 })]);
+
+ ok({ body: {} });
+ await newSearchMonitorResultsTrigger.onDisable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ ok({ status: 201, body: { id: 'mon_2', webhookSecret: SECRET } });
+ await newSearchMonitorResultsTrigger.onEnable(webhookContext({ store, propsValue: { query: 'q', period: '1d' } }));
+ expect(data[STORE_KEY]).toMatchObject({ monitorId: 'mon_2' });
+
+ const replayed = await deliver({ eventId: 'e2', monitorId: 'mon_2', urls: ['https://a.com', 'https://b.com'] });
+ expect(replayed).toEqual([]);
+ const mixed = await deliver({ eventId: 'e3', monitorId: 'mon_2', urls: ['https://b.com', 'https://c.com'] });
+ expect(mixed).toEqual([
+ expect.objectContaining({ result_count: 1, results: [expect.objectContaining({ url: 'https://c.com' })] }),
+ ]);
+ });
+
+ it('keeps nothing when saving the dedupe state fails, so Exa\'s retry is still processed', async () => {
+ const memory = memoryStore(STATE);
+ let failSeenWrite = true;
+ const store: Store = {
+ ...memory.store,
+ put: async (key, value) => {
+ if (failSeenWrite && key.startsWith('exa_search_monitor_seen')) {
+ failSeenWrite = false;
+ throw new Error('store down');
+ }
+ return memory.store.put(key, value);
+ },
+ };
+ const payload = {
+ body: JSON.parse(BODY),
+ rawBody: BODY,
+ headers: { 'exa-signature': sign({ body: BODY, timestamp: NOW_T, secret: SECRET }) },
+ queryParams: {},
+ };
+ const context = webhookContext({ store, payload, propsValue: { query: 'q', period: '1d' } });
+ await expect(newSearchMonitorResultsTrigger.run(context)).rejects.toThrow(/store down/);
+ const retry = await newSearchMonitorResultsTrigger.run(context);
+ expect(retry).toEqual([expect.objectContaining({ event_id: 'event_1', result_count: 1 })]);
+ });
+
+ it('logs why a correctly signed but stale delivery was dropped', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ const { store } = memoryStore(STATE);
+ const old = String(Math.floor(Date.now() / 1000) - 3600);
+ const result = await newSearchMonitorResultsTrigger.run(
+ webhookContext({
+ store,
+ payload: { body: JSON.parse(BODY), rawBody: BODY, headers: { 'exa-signature': sign({ body: BODY, timestamp: old, secret: SECRET }) }, queryParams: {} },
+ propsValue: { query: 'q', period: '1d' },
+ }),
+ );
+ expect(result).toEqual([]);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0][0])).toMatch(/signed more than 15 minutes ago/);
+ warn.mockRestore();
+ });
+
+ it('sends only the new results of a mixed run, with their citations and without the run-wide summary', async () => {
+ const { store } = memoryStore({ ...STATE, exa_search_monitor_seen: { eventIds: [], urls: ['https://a.com'] } });
+ const parsed = JSON.parse(BODY);
+ const body = JSON.stringify({
+ ...parsed,
+ id: 'event_mixed',
+ data: {
+ ...parsed.data,
+ output: {
+ results: [
+ { title: 'A', url: 'https://a.com' },
+ { title: 'B', url: 'https://b.com' },
+ ],
+ content: 'A launched X [1]; B launched Y [2].',
+ grounding: [
+ { field: 'content', citations: [{ title: 'A', url: 'https://a.com' }, { title: 'B', url: 'https://b.com' }], confidence: 'high' },
+ ],
+ },
+ },
+ });
+ const result = await newSearchMonitorResultsTrigger.run(
+ webhookContext({
+ store,
+ payload: { body: JSON.parse(body), rawBody: body, headers: { 'exa-signature': sign({ body, timestamp: NOW_T, secret: SECRET }) }, queryParams: {} },
+ propsValue: { query: 'q', period: '1d' },
+ }),
+ );
+ expect(result).toEqual([
+ expect.objectContaining({
+ result_count: 1,
+ results: [expect.objectContaining({ url: 'https://b.com' })],
+ citations: [{ field: 'content', url: 'https://b.com', title: 'B', confidence: 'high' }],
+ run_citations: [
+ { field: 'content', url: 'https://a.com', title: 'A', confidence: 'high' },
+ { field: 'content', url: 'https://b.com', title: 'B', confidence: 'high' },
+ ],
+ summary: null,
+ run_summary: 'A launched X [1]; B launched Y [2].',
+ run_result_count: 2,
+ }),
+ ]);
+ });
+
+ it('keeps the summary when every result in the run is new', async () => {
+ const { store } = memoryStore(STATE);
+ const payload = { body: JSON.parse(BODY), rawBody: BODY, headers: { 'exa-signature': sign({ body: BODY, timestamp: NOW_T, secret: SECRET }) }, queryParams: {} };
+ const result = await newSearchMonitorResultsTrigger.run(webhookContext({ store, payload, propsValue: { query: 'q', period: '1d' } }));
+ expect(result).toEqual([expect.objectContaining({ summary: 'summary', run_summary: 'summary', run_result_count: 1, result_count: 1 })]);
+ });
+
+ it('normalizes the monitor published date to ISO 8601', async () => {
+ const { store } = memoryStore(STATE);
+ const parsed = JSON.parse(BODY);
+ const body = JSON.stringify({
+ ...parsed,
+ data: { ...parsed.data, output: { ...parsed.data.output, results: [{ title: 'R', url: 'https://r.com', publishedDate: '2026-09-28 00:00:00.000000000' }] } },
+ });
+ const result = await newSearchMonitorResultsTrigger.run(
+ webhookContext({
+ store,
+ payload: { body: JSON.parse(body), rawBody: body, headers: { 'exa-signature': sign({ body, timestamp: NOW_T, secret: SECRET }) }, queryParams: {} },
+ propsValue: { query: 'q', period: '1d' },
+ }),
+ );
+ expect(result).toEqual([expect.objectContaining({ results: [expect.objectContaining({ published_date: '2026-09-28T00:00:00.000Z' })] })]);
+ });
+
+ it('drops an unsigned delivery', async () => {
+ const { store } = memoryStore(STATE);
+ const result = await newSearchMonitorResultsTrigger.run(
+ webhookContext({
+ store,
+ payload: { body: JSON.parse(BODY), rawBody: BODY, headers: {}, queryParams: {} },
+ propsValue: { query: 'q', period: '1d' },
+ }),
+ );
+ expect(result).toEqual([]);
+ });
+});
diff --git a/packages/pieces/community/exa/test/helpers.ts b/packages/pieces/community/exa/test/helpers.ts
new file mode 100644
index 00000000000..c3e4c44212f
--- /dev/null
+++ b/packages/pieces/community/exa/test/helpers.ts
@@ -0,0 +1,122 @@
+import {
+ ActionContext,
+ AppConnectionType,
+ AppConnectionValueForAuthProperty,
+ InputPropertyMap,
+ StaticPropsValue,
+ Store,
+ TestOrRunHookContext,
+ TriggerHookContext,
+ TriggerStrategy,
+ createMockActionContext,
+} from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+import type { exaAuth } from '../src/lib/auth';
+
+export const sendRequest = vi.fn();
+
+export function mockHttpClient() {
+ return {
+ httpClient: { sendRequest: (...args: unknown[]) => sendRequest(...args) },
+ };
+}
+
+export const AUTH: AppConnectionValueForAuthProperty<typeof exaAuth> = {
+ type: AppConnectionType.SECRET_TEXT,
+ secret_text: 'exa_test_key',
+};
+
+export function ok({ body, status = 200 }: { body: unknown; status?: number }) {
+ sendRequest.mockResolvedValueOnce({ status, headers: {}, body });
+}
+
+export function fail({ status, body = { error: 'nope' } }: { status: number; body?: unknown }) {
+ sendRequest.mockRejectedValueOnce(Object.assign(new Error(`status ${status}`), { response: { status, body } }));
+}
+
+export function lastRequest() {
+ return sendRequest.mock.calls[sendRequest.mock.calls.length - 1][0];
+}
+
+export function runAction<Props extends InputPropertyMap>({
+ action,
+ propsValue,
+}: {
+ action: { props: Props; run: (context: ActionContext<typeof exaAuth, Props>) => Promise<unknown> };
+ propsValue: StaticPropsValue<Props>;
+}): Promise<unknown> {
+ const base = createMockActionContext<Props>({ propsValue });
+ return action.run({ ...base, auth: AUTH });
+}
+
+export function memoryStore(initial: Record<string, unknown> = {}): {
+ store: Store;
+ data: Record<string, unknown>;
+ failNextPut: (error: Error) => void;
+} {
+ const data: Record<string, unknown> = { ...initial };
+ let nextPutError: Error | undefined;
+ const store: Store = {
+ put: async (key, value) => {
+ if (nextPutError) {
+ const error = nextPutError;
+ nextPutError = undefined;
+ throw error;
+ }
+ data[key] = value;
+ return value;
+ },
+ get: async (key) => {
+ const value = data[key];
+ return value === undefined ? null : JSON.parse(JSON.stringify(value));
+ },
+ delete: async (key) => {
+ delete data[key];
+ },
+ };
+ return {
+ store,
+ data,
+ failNextPut: (error) => {
+ nextPutError = error;
+ },
+ };
+}
+
+export function asWebhook<T extends { type: TriggerStrategy }>(trigger: T): Extract<T, { type: TriggerStrategy.WEBHOOK }> {
+ if (!isWebhook(trigger)) {
+ throw new Error('not a webhook trigger');
+ }
+ return trigger;
+}
+
+export function webhookContext<Props extends InputPropertyMap>({
+ propsValue,
+ store,
+ payload = { body: {}, headers: {}, queryParams: {} },
+ webhookUrl = 'https://hooks.example.com/abc',
+}: {
+ propsValue: StaticPropsValue<Props>;
+ store: Store;
+ payload?: TestOrRunHookContext<typeof exaAuth, Props, TriggerStrategy.WEBHOOK>['payload'];
+ webhookUrl?: string;
+}): TestOrRunHookContext<typeof exaAuth, Props, TriggerStrategy.WEBHOOK> {
+ const base = createMockActionContext<Props>({ propsValue });
+ const context: TriggerHookContext<typeof exaAuth, Props, TriggerStrategy.WEBHOOK> = {
+ auth: AUTH,
+ propsValue,
+ store,
+ project: base.project,
+ flows: base.flows,
+ step: base.step,
+ connections: base.connections,
+ server: base.server,
+ webhookUrl,
+ payload,
+ };
+ return { ...context, files: base.files };
+}
+
+function isWebhook<T extends { type: TriggerStrategy }>(trigger: T): trigger is Extract<T, { type: TriggerStrategy.WEBHOOK }> {
+ return trigger.type === TriggerStrategy.WEBHOOK;
+}
diff --git a/packages/pieces/community/exa/vitest.config.ts b/packages/pieces/community/exa/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/exa/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'),
+ },
+ },
+})