AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(taskade): manage projects, tasks and AI agents from flows and AI agents, and trigger on task and project events (#16172)
Odai Ahmaddf2a8c2bf7cf
diff --git a/bun.lock b/bun.lockindex 7c8c0fbebb8..490b131eec8 100644--- a/bun.lock+++ b/bun.lock@@ -8985,7 +8985,7 @@},"packages/pieces/community/taskade": {"name": "@activepieces/piece-taskade",- "version": "0.2.1",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8994,6 +8994,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/tavily": {diff --git a/packages/pieces/community/taskade/package.json b/packages/pieces/community/taskade/package.jsonindex 49dc2fbd890..898d9259a5b 100644--- a/packages/pieces/community/taskade/package.json+++ b/packages/pieces/community/taskade/package.json@@ -1,12 +1,13 @@{"name": "@activepieces/piece-taskade",- "version": "0.2.2",+ "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/taskade/src/i18n/translation.json b/packages/pieces/community/taskade/src/i18n/translation.jsonindex a6432ee748e..9b23330a88e 100644--- a/packages/pieces/community/taskade/src/i18n/translation.json+++ b/packages/pieces/community/taskade/src/i18n/translation.json@@ -1,13 +1,89 @@{- "collaboration platform for remote teams to organize and manage projects": "collaboration platform for remote teams to organize and manage projects",- "\n\t1. Navigate to https://taskade.com/settings/password and scroll down to Personal Access Tokens.\n\t2. Create your personal access token with any name.": "\n\t1. Navigate to https://taskade.com/settings/password and scroll down to Personal Access Tokens.\n\t2. Create your personal access token with any name.",+ "Collaboration platform for remote teams to organize projects, tasks and AI agents.": "Collaboration platform for remote teams to organize projects, tasks and AI agents.",+ "\n\t1. Go to https://www.taskade.com/settings/api (Settings > API).\n\t2. Under Personal Access Tokens, create a token with any name and copy it (it starts with tskdp_).": "\n\t1. Go to https://www.taskade.com/settings/api (Settings > API).\n\t2. Under Personal Access Tokens, create a token with any name and copy it (it starts with tskdp_).","Create Task": "Create Task","Complete Task": "Complete Task","Delete Task": "Delete Task",+ "List Workspaces": "List Workspaces",+ "List Folders": "List Folders",+ "List Projects": "List Projects",+ "List My Recent Projects": "List My Recent Projects",+ "Get Project": "Get Project",+ "Create Project": "Create Project",+ "Create Project from Template": "Create Project from Template",+ "List Project Templates": "List Project Templates",+ "Copy Project": "Copy Project",+ "Complete (Archive) Project": "Complete (Archive) Project",+ "Restore Project": "Restore Project",+ "List Project Members": "List Project Members",+ "List Custom Fields": "List Custom Fields",+ "Get Project Share Link": "Get Project Share Link",+ "List Tasks": "List Tasks",+ "Find Tasks": "Find Tasks",+ "Get Task": "Get Task",+ "Create Tasks": "Create Tasks",+ "Update Task Text": "Update Task Text",+ "Complete Task (by ID)": "Complete Task (by ID)",+ "Reopen Task": "Reopen Task",+ "Delete Task (by ID)": "Delete Task (by ID)",+ "Move Task": "Move Task",+ "Set Task Date": "Set Task Date",+ "Set Task Note": "Set Task Note",+ "Assign Task": "Assign Task",+ "Unassign Task": "Unassign Task",+ "Set Custom Field Value": "Set Custom Field Value",+ "List AI Agents": "List AI Agents",+ "Get AI Agent": "Get AI Agent",+ "Ask AI Agent": "Ask AI Agent",+ "List Agent Conversations": "List Agent Conversations",+ "Get Agent Conversation": "Get Agent Conversation",+ "Generate AI Agent": "Generate AI Agent",+ "Delete AI Agent": "Delete AI Agent",+ "Add Project to Agent Knowledge": "Add Project to Agent Knowledge",+ "Remove Project from Agent Knowledge": "Remove Project from Agent Knowledge",+ "Trigger Taskade Automation": "Trigger Taskade Automation","Custom API Call": "Custom API Call","Creates a new task.": "Creates a new task.","Complete a task in a project.": "Complete a task in a project.","Delete an existing task in a project.": "Delete an existing task in a project.",+ "Lists the Taskade workspaces you belong to.": "Lists the Taskade workspaces you belong to.",+ "Lists the folders of a workspace, including its home folder.": "Lists the folders of a workspace, including its home folder.",+ "Lists the projects in a workspace or folder, optionally filtered by name.": "Lists the projects in a workspace or folder, optionally filtered by name.",+ "Lists projects you have access to across all workspaces, most recently viewed first.": "Lists projects you have access to across all workspaces, most recently viewed first.",+ "Gets a project by ID or link.": "Gets a project by ID or link.",+ "Creates a project in a workspace or folder, optionally with tasks written as a Markdown list.": "Creates a project in a workspace or folder, optionally with tasks written as a Markdown list.",+ "Creates a project from one of your Taskade project templates.": "Creates a project from one of your Taskade project templates.",+ "Lists the project templates saved in a workspace or folder.": "Lists the project templates saved in a workspace or folder.",+ "Copies a project, with its tasks, into a workspace or folder.": "Copies a project, with its tasks, into a workspace or folder.",+ "Marks a project as completed, which archives it.": "Marks a project as completed, which archives it.",+ "Restores a completed (archived) project.": "Restores a completed (archived) project.",+ "Lists the people who can be assigned to tasks in a project.": "Lists the people who can be assigned to tasks in a project.",+ "Lists the custom fields of a project, with select options.": "Lists the custom fields of a project, with select options.",+ "Gets the view and edit share links of a project, if sharing is on.": "Gets the view and edit share links of a project, if sharing is on.",+ "Lists the tasks of a project in outline order, one page at a time.": "Lists the tasks of a project in outline order, one page at a time.",+ "Finds tasks in a project whose text contains some words.": "Finds tasks in a project whose text contains some words.",+ "Gets a task with its date, note, assignees and custom field values.": "Gets a task with its date, note, assignees and custom field values.",+ "Adds 1-20 tasks to a project, at the top or bottom, or next to or inside another task.": "Adds 1-20 tasks to a project, at the top or bottom, or next to or inside another task.",+ "Replaces the text of a task.": "Replaces the text of a task.",+ "Marks a task as completed, given the project and task ID.": "Marks a task as completed, given the project and task ID.",+ "Marks a completed task as not completed.": "Marks a completed task as not completed.",+ "Permanently deletes a task and its subtasks, given the project and task ID.": "Permanently deletes a task and its subtasks, given the project and task ID.",+ "Moves a task before or after another task, or inside it as a subtask.": "Moves a task before or after another task, or inside it as a subtask.",+ "Sets or clears the start and end date of a task.": "Sets or clears the start and end date of a task.",+ "Sets or clears the note attached to a task.": "Sets or clears the note attached to a task.",+ "Assigns project members to a task by their handle.": "Assigns project members to a task by their handle.",+ "Removes one member from a task's assignees.": "Removes one member from a task's assignees.",+ "Sets or clears the value of a custom field on a task.": "Sets or clears the value of a custom field on a task.",+ "Lists the AI agents in a workspace or folder.": "Lists the AI agents in a workspace or folder.",+ "Gets an AI agent with its commands and their prompts.": "Gets an AI agent with its commands and their prompts.",+ "Sends a prompt to a Taskade AI agent and returns its answer. Uses Taskade AI credits.": "Sends a prompt to a Taskade AI agent and returns its answer. Uses Taskade AI credits.",+ "Lists the conversations of an AI agent.": "Lists the conversations of an AI agent.",+ "Gets one conversation of an AI agent, with its transcript.": "Gets one conversation of an AI agent, with its transcript.",+ "Creates a new AI agent from a plain-language description. Uses Taskade AI credits.": "Creates a new AI agent from a plain-language description. Uses Taskade AI credits.",+ "Permanently deletes an AI agent.": "Permanently deletes an AI agent.",+ "Lets an AI agent use a project as knowledge.": "Lets an AI agent use a project as knowledge.",+ "Stops an AI agent from using a project as knowledge.": "Stops an AI agent from using a project as knowledge.",+ "Starts a Taskade automation that begins with a Webhook trigger, sending a JSON payload.": "Starts a Taskade automation that begins with a Webhook trigger, sending a JSON payload.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Workspace": "Workspace","Folder": "Folder",@@ -16,30 +92,150 @@"Task Content": "Task Content","Placement": "Placement","Task": "Task",+ "Workspace ID": "Workspace ID",+ "Workspace or Folder ID": "Workspace or Folder ID",+ "Name Contains": "Name Contains",+ "Include Archived Projects": "Include Archived Projects",+ "Order": "Order",+ "Limit": "Limit",+ "Page": "Page",+ "Project ID": "Project ID",+ "Project Title": "Project Title",+ "Content (Markdown)": "Content (Markdown)",+ "Template ID": "Template ID",+ "Project to Copy": "Project to Copy",+ "New Title": "New Title",+ "Cursor": "Cursor",+ "Text Contains": "Text Contains",+ "Status": "Status",+ "Max Results": "Max Results",+ "Start Cursor": "Start Cursor",+ "Task ID": "Task ID",+ "Include Details": "Include Details",+ "Tasks": "Tasks",+ "Text Format": "Text Format",+ "Position": "Position",+ "Relative To Task ID": "Relative To Task ID",+ "New Text": "New Text",+ "Task ID to Move": "Task ID to Move",+ "Target Task ID": "Target Task ID",+ "Start Date": "Start Date",+ "Start Time": "Start Time",+ "End Date": "End Date",+ "End Time": "End Time",+ "Timezone": "Timezone",+ "Clear Date": "Clear Date",+ "Note": "Note",+ "Clear Note": "Clear Note",+ "Member Handles": "Member Handles",+ "Member Handle": "Member Handle",+ "Field ID": "Field ID",+ "Value": "Value",+ "Clear Value": "Clear Value",+ "Agent ID": "Agent ID",+ "Prompt": "Prompt",+ "Conversation ID": "Conversation ID",+ "Include Transcript": "Include Transcript",+ "What the Agent Should Do": "What the Agent Should Do",+ "Automation Webhook URL": "Automation Webhook URL",+ "Payload": "Payload",+ "Webhook Bearer Token": "Webhook Bearer Token","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",- "Placement of task in block": "Placement of task in block",+ "Up to 2,000 characters.": "Up to 2,000 characters.",+ "Where to add the task in the project.": "Where to add the task in the project.",+ "Get it from List Workspaces.": "Get it from List Workspaces.",+ "A workspace ID or folder ID. A workspace ID works for its home folder. Get IDs from List Workspaces and List Folders.": "A workspace ID or folder ID. A workspace ID works for its home folder. Get IDs from List Workspaces and List Folders.",+ "Only return projects whose name contains this text (case-insensitive).": "Only return projects whose name contains this text (case-insensitive).",+ "Include completed (archived) projects.": "Include completed (archived) projects.",+ "How many items to return (1-100, default 100).": "How many items to return (1-100, default 100).",+ "Page number, starting at 1. Pass nextPage from the previous result to get more.": "Page number, starting at 1. Pass nextPage from the previous result to get more.",+ "The project ID, or the project link (https://www.taskade.com/d/<project id>). Get it from List Projects or List My Recent Projects.": "The project ID, or the project link (https://www.taskade.com/d/<project id>). Get it from List Projects or List My Recent Projects.",+ "Optional. Each line starting with \"- \" becomes a task; indent with two spaces for subtasks.": "Optional. Each line starting with \"- \" becomes a task; indent with two spaces for subtasks.",+ "Where to create the project. A workspace ID works for its home folder.": "Where to create the project. A workspace ID works for its home folder.",+ "Get it from List Project Templates.": "Get it from List Project Templates.",+ "How many items to return (1-100, default 20).": "How many items to return (1-100, default 20).",+ "Where to put the copy. A workspace ID works for its home folder.": "Where to put the copy. A workspace ID works for its home folder.",+ "Optional title for the copy. Leave empty to keep the original title.": "Optional title for the copy. Leave empty to keep the original title.",+ "How many items to return (1-1000, default 100).": "How many items to return (1-1000, default 100).",+ "Pass nextCursor from the previous result to get the next page. Leave empty to start at the top.": "Pass nextCursor from the previous result to get the next page. Leave empty to start at the top.",+ "Words to look for in the task text (case-insensitive).": "Words to look for in the task text (case-insensitive).",+ "Stop after this many matches (1-500, default 50).": "Stop after this many matches (1-500, default 50).",+ "To continue a truncated search, pass nextCursor from the previous result.": "To continue a truncated search, pass nextCursor from the previous result.",+ "The task ID. Get it from List Tasks or Find Tasks.": "The task ID. Get it from List Tasks or Find Tasks.",+ "Also fetch the date, note, assignees and custom field values (4 more requests).": "Also fetch the date, note, assignees and custom field values (4 more requests).",+ "One entry per task (1-20). Each entry is a single line of up to 2,000 characters.": "One entry per task (1-20). Each entry is a single line of up to 2,000 characters.",+ "Required for Before, After, First subtask and Last subtask positions.": "Required for Before, After, First subtask and Last subtask positions.",+ "Single line, up to 2,000 characters.": "Single line, up to 2,000 characters.",+ "The task to move next to or into.": "The task to move next to or into.",+ "YYYY-MM-DD. Required unless Clear Date is on. For a single due date, set only this.": "YYYY-MM-DD. Required unless Clear Date is on. For a single due date, set only this.",+ "Optional, 24-hour HH:MM or HH:MM:SS.": "Optional, 24-hour HH:MM or HH:MM:SS.",+ "Optional, YYYY-MM-DD, for a date range.": "Optional, YYYY-MM-DD, for a date range.",+ "Optional, 24-hour HH:MM or HH:MM:SS. Needs End Date.": "Optional, 24-hour HH:MM or HH:MM:SS. Needs End Date.",+ "Optional IANA timezone for the times, for example America/New_York.": "Optional IANA timezone for the times, for example America/New_York.",+ "Remove the date from the task. The date fields above are ignored.": "Remove the date from the task. The date fields above are ignored.",+ "Required unless Clear Note is on. Taskade accepts a single line.": "Required unless Clear Note is on. Taskade accepts a single line.",+ "Remove the note from the task. Note is ignored.": "Remove the note from the task. Note is ignored.",+ "Handles of project members, without @. Get them from List Project Members.": "Handles of project members, without @. Get them from List Project Members.",+ "Handle without @, from List Project Members or Get Task.": "Handle without @, from List Project Members or Get Task.",+ "Get it from List Custom Fields.": "Get it from List Custom Fields.",+ "Text, a number for number fields, or the option ID for Select fields. Required unless Clear Value is on.": "Text, a number for number fields, or the option ID for Select fields. Required unless Clear Value is on.",+ "Remove the value from the task. Value is ignored.": "Remove the value from the task. Value is ignored.",+ "The AI agent ID. Get it from List AI Agents.": "The AI agent ID. Get it from List AI Agents.",+ "Optional. The agent's workspace ID; looked up from the agent when empty (one extra request).": "Optional. The agent's workspace ID; looked up from the agent when empty (one extra request).",+ "Get it from List Agent Conversations.": "Get it from List Agent Conversations.",+ "For example: \"An agent that drafts friendly replies to customer support emails\".": "For example: \"An agent that drafts friendly replies to customer support emails\".",+ "In the Taskade automation, add a Webhook trigger and copy its URL (https://www.taskade.com/webhooks/...).": "In the Taskade automation, add a Webhook trigger and copy its URL (https://www.taskade.com/webhooks/...).",+ "JSON object to send. Each field becomes a variable in the automation.": "JSON object to send. Each field becomes a variable in the automation.",+ "Only if the webhook trigger has Bearer Token authentication turned on. This is the webhook's own secret, not your personal access token.": "Only if the webhook trigger has Bearer Token authentication turned on. This is the webhook's own secret, not your personal access token.","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.",- "text/markdown": "text/markdown",- "text/plain": "text/plain",- "afterbegin": "afterbegin",- "beforeend": "beforeend",+ "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.",+ "Markdown": "Markdown",+ "Plain text": "Plain text",+ "Top of project": "Top of project",+ "Bottom of project": "Bottom of project",+ "Most recently viewed first": "Most recently viewed first",+ "Least recently viewed first": "Least recently viewed first",+ "Any": "Any",+ "Open only": "Open only",+ "Completed only": "Completed only",+ "Before a task": "Before a task",+ "After a task": "After a task",+ "First subtask of a task": "First subtask of a task",+ "Last subtask of a task": "Last subtask of a task",+ "Before the target": "Before the target",+ "After the target": "After the target",+ "First subtask of the target": "First subtask of the target",+ "Last subtask of the target": "Last subtask of the target","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE","HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw"+ "Task Due": "Task Due",+ "Task Assigned": "Task Assigned",+ "New Comment": "New Comment",+ "New Project": "New Project",+ "Project Assigned": "Project Assigned",+ "Member Joined Project": "Member Joined Project",+ "Fires when a task's due date arrives. Needs a Taskade Pro plan or above.": "Fires when a task's due date arrives. Needs a Taskade Pro plan or above.",+ "Fires when tasks are assigned to someone. Needs a Taskade Pro plan or above.": "Fires when tasks are assigned to someone. Needs a Taskade Pro plan or above.",+ "Fires when a comment is added to a task. Needs a Taskade Pro plan or above.": "Fires when a comment is added to a task. Needs a Taskade Pro plan or above.",+ "Fires when a project is created. Needs a Taskade Pro plan or above.": "Fires when a project is created. Needs a Taskade Pro plan or above.",+ "Fires when a project is assigned to someone. Needs a Taskade Pro plan or above.": "Fires when a project is assigned to someone. Needs a Taskade Pro plan or above.",+ "Fires when someone joins a project. Needs a Taskade Pro plan or above.": "Fires when someone joins a project. Needs a Taskade Pro plan or above.",+ "Workspaces": "Workspaces",+ "Only fire for events in these workspaces. Leave empty for all workspaces.": "Only fire for events in these workspaces. Leave empty for all workspaces."}\ No newline at end of filediff --git a/packages/pieces/community/taskade/src/index.ts b/packages/pieces/community/taskade/src/index.tsindex e9085fe346a..793f2f328d0 100644--- a/packages/pieces/community/taskade/src/index.ts+++ b/packages/pieces/community/taskade/src/index.ts@@ -1,28 +1,110 @@-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';-import { createTaskAction } from './lib/actions/create-task.action';-import { PieceCategory } from '@activepieces/pieces-framework';+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { PieceCategory, createPiece } from '@activepieces/pieces-framework';+import { addAgentKnowledgeProjectAction } from './lib/actions/add-agent-knowledge-project';+import { completeTaskByIdAction } from './lib/actions/ai/complete-task-by-id';+import { deleteTaskByIdAction } from './lib/actions/ai/delete-task-by-id';+import { askAgentAction } from './lib/actions/ask-agent';+import { assignTaskAction } from './lib/actions/assign-task';+import { completeProjectAction } from './lib/actions/complete-project';import { completeTaskAction } from './lib/actions/complete-task.action';+import { copyProjectAction } from './lib/actions/copy-project';+import { createProjectAction } from './lib/actions/create-project';+import { createProjectFromTemplateAction } from './lib/actions/create-project-from-template';+import { createTaskAction } from './lib/actions/create-task.action';+import { createTasksAction } from './lib/actions/create-tasks';+import { deleteAgentAction } from './lib/actions/delete-agent';import { deleteTaskAction } from './lib/actions/delete-task.action';-import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { findTasksAction } from './lib/actions/find-tasks';+import { generateAgentAction } from './lib/actions/generate-agent';+import { getAgentAction } from './lib/actions/get-agent';+import { getAgentConversationAction } from './lib/actions/get-agent-conversation';+import { getProjectAction } from './lib/actions/get-project';+import { getProjectShareLinkAction } from './lib/actions/get-project-share-link';+import { getTaskAction } from './lib/actions/get-task';+import { listAgentConversationsAction } from './lib/actions/list-agent-conversations';+import { listAgentsAction } from './lib/actions/list-agents';+import { listFoldersAction } from './lib/actions/list-folders';+import { listProjectFieldsAction } from './lib/actions/list-project-fields';+import { listProjectMembersAction } from './lib/actions/list-project-members';+import { listProjectTemplatesAction } from './lib/actions/list-project-templates';+import { listProjectsAction } from './lib/actions/list-projects';+import { listRecentProjectsAction } from './lib/actions/list-recent-projects';+import { listTasksAction } from './lib/actions/list-tasks';+import { listWorkspacesAction } from './lib/actions/list-workspaces';+import { moveTaskAction } from './lib/actions/move-task';+import { removeAgentKnowledgeProjectAction } from './lib/actions/remove-agent-knowledge-project';+import { reopenTaskAction } from './lib/actions/reopen-task';+import { restoreProjectAction } from './lib/actions/restore-project';+import { setTaskDateAction } from './lib/actions/set-task-date';+import { setTaskFieldValueAction } from './lib/actions/set-task-field-value';+import { setTaskNoteAction } from './lib/actions/set-task-note';+import { triggerAutomationAction } from './lib/actions/trigger-automation';+import { unassignTaskAction } from './lib/actions/unassign-task';+import { updateTaskAction } from './lib/actions/update-task';import { taskadeAuth } from './lib/auth';+import { taskadeApi, TASKADE_BASE_URL } from './lib/common/client';+import { commentCreatedTrigger } from './lib/triggers/comment-created';+import { projectAssignedTrigger } from './lib/triggers/project-assigned';+import { projectCreatedTrigger } from './lib/triggers/project-created';+import { projectJoinedTrigger } from './lib/triggers/project-joined';+import { taskAssignedTrigger } from './lib/triggers/task-assigned';+import { taskDueTrigger } from './lib/triggers/task-due';export const taskade = createPiece({displayName: 'Taskade',auth: taskadeAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',categories: [PieceCategory.PRODUCTIVITY],- description: 'collaboration platform for remote teams to organize and manage projects',+ description: 'Collaboration platform for remote teams to organize projects, tasks and AI agents.',logoUrl: 'https://cdn.activepieces.com/pieces/taskade.png',authors: ['kishanprmr'],actions: [createTaskAction,completeTaskAction,deleteTaskAction,+ listWorkspacesAction,+ listFoldersAction,+ listProjectsAction,+ listRecentProjectsAction,+ getProjectAction,+ createProjectAction,+ createProjectFromTemplateAction,+ listProjectTemplatesAction,+ copyProjectAction,+ completeProjectAction,+ restoreProjectAction,+ listProjectMembersAction,+ listProjectFieldsAction,+ getProjectShareLinkAction,+ listTasksAction,+ findTasksAction,+ getTaskAction,+ createTasksAction,+ updateTaskAction,+ completeTaskByIdAction,+ reopenTaskAction,+ deleteTaskByIdAction,+ moveTaskAction,+ setTaskDateAction,+ setTaskNoteAction,+ assignTaskAction,+ unassignTaskAction,+ setTaskFieldValueAction,+ listAgentsAction,+ getAgentAction,+ askAgentAction,+ listAgentConversationsAction,+ getAgentConversationAction,+ generateAgentAction,+ deleteAgentAction,+ addAgentKnowledgeProjectAction,+ removeAgentKnowledgeProjectAction,+ triggerAutomationAction,createCustomApiCallAction({- baseUrl: () => 'https://www.taskade.com/api/v1',+ baseUrl: () => TASKADE_BASE_URL,auth: taskadeAuth,- authMapping: async (auth) => ({ Authorization: `Bearer ${auth.secret_text}` }),+ authMapping: async (auth) => taskadeApi.authHeaders(auth.secret_text),}),],- triggers: [],+ triggers: [taskDueTrigger, taskAssignedTrigger, commentCreatedTrigger, projectCreatedTrigger, projectAssignedTrigger, projectJoinedTrigger],});diff --git a/packages/pieces/community/taskade/src/lib/actions/add-agent-knowledge-project.ts b/packages/pieces/community/taskade/src/lib/actions/add-agent-knowledge-project.tsnew file mode 100644index 00000000000..72be0e6c65f--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/add-agent-knowledge-project.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeOutputSchemas } from '../output-schemas';++export const addAgentKnowledgeProjectAction = createAction({+ auth: taskadeAuth,+ name: 'add_agent_knowledge_project',+ displayName: 'Add Project to Agent Knowledge',+ description: 'Lets an AI agent use a project as knowledge.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Adds a Taskade project to an AI agent\'s knowledge so the agent can read it when answering. Adding a project that is already linked leaves it linked, so it is idempotent.',+ idempotent: true,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['agentKnowledge'],+ async run(context) {+ const agentId = taskadeApi.requireText({ value: context.propsValue.agentId, label: 'Agent ID' });+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ await taskadeApi.request({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `/agents/${taskadeApi.seg({ value: agentId, label: 'Agent ID' })}/knowledge/project`,+ operation: 'add project to agent knowledge',+ body: { projectId },+ });+ return { agentId, projectId, linked: true };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/ai/complete-task-by-id.ts b/packages/pieces/community/taskade/src/lib/actions/ai/complete-task-by-id.tsnew file mode 100644index 00000000000..496f90fedef--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/ai/complete-task-by-id.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../../auth';+import { taskadeAiProps } from '../../common/ai-props';+import { taskadeTasks } from '../../common/tasks';+import { taskadeOutputSchemas } from '../../output-schemas';++export const completeTaskByIdAction = createAction({+ auth: taskadeAuth,+ name: 'complete_task_by_id',+ displayName: 'Complete Task (by ID)',+ description: 'Marks a task as completed, given the project and task ID.',+ classification: 'WRITE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Marks one Taskade task as completed, given its project ID (or link) and task ID (from List Tasks or Find Tasks). Use to check off work; Reopen Task undoes it. Completing an already completed task changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ },+ outputSchema: taskadeOutputSchemas['task'],+ async run(context) {+ const { projectId, taskId } = context.propsValue;+ const token = context.auth.secret_text;+ const { task } = await taskadeTasks.setCompletion({ token, projectId, taskId, completed: true });+ return task;+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/ai/delete-task-by-id.ts b/packages/pieces/community/taskade/src/lib/actions/ai/delete-task-by-id.tsnew file mode 100644index 00000000000..241ab44f44f--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/ai/delete-task-by-id.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../../auth';+import { taskadeAiProps } from '../../common/ai-props';+import { taskadeApi } from '../../common/client';+import { taskadeOutputSchemas } from '../../output-schemas';++export const deleteTaskByIdAction = createAction({+ auth: taskadeAuth,+ name: 'delete_task_by_id',+ displayName: 'Delete Task (by ID)',+ description: 'Permanently deletes a task and its subtasks, given the project and task ID.',+ classification: 'DESTRUCTIVE',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one Taskade task and all its subtasks by project ID and task ID; it cannot be undone. Use only when the user asks to remove a task. A repeat call finds it gone and reports alreadyDeleted=true, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ },+ outputSchema: taskadeOutputSchemas['deleteTask'],+ async run(context) {+ const { projectId, taskId } = context.propsValue;+ const token = context.auth.secret_text;+ const parsedProjectId = taskadeApi.parseProjectId(projectId);+ const parsedTaskId = taskadeApi.requireText({ value: taskId, label: 'Task ID' });+ try {+ await taskadeApi.request({+ token,+ method: HttpMethod.DELETE,+ path: taskadeApi.taskPath({ projectId: parsedProjectId, taskId: parsedTaskId }),+ operation: 'delete task',+ });+ return { projectId: parsedProjectId, taskId: parsedTaskId, deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (!taskadeApi.isNotFound(error)) {+ throw error;+ }+ await taskadeApi.request({+ token,+ method: HttpMethod.GET,+ path: taskadeApi.projectPath(parsedProjectId),+ operation: 'get project',+ });+ return { projectId: parsedProjectId, taskId: parsedTaskId, deleted: true, alreadyDeleted: true };+ }+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/ask-agent.ts b/packages/pieces/community/taskade/src/lib/actions/ask-agent.tsnew file mode 100644index 00000000000..79c5e2066cc--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/ask-agent.ts@@ -0,0 +1,71 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { AgentResponse, ItemAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const askAgentAction = createAction({+ auth: taskadeAuth,+ name: 'ask_agent',+ displayName: 'Ask AI Agent',+ description: 'Sends a prompt to a Taskade AI agent and returns its answer. Uses Taskade AI credits.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sends a prompt to a Taskade AI agent and returns its written answer (can take up to a few minutes). Use to delegate research, writing or summaries to an agent the user set up; get agent IDs from List AI Agents. Uses Taskade AI credits and starts a new conversation each time, so it is not idempotent.',+ idempotent: false,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ prompt: Property.LongText({+ displayName: 'Prompt',+ required: true,+ }),+ workspaceId: Property.ShortText({+ displayName: 'Workspace ID',+ description: 'Optional. The agent\'s workspace ID; looked up from the agent when empty (one extra request).',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['askAgent'],+ async run(context) {+ const token = context.auth.secret_text;+ const agentId = taskadeApi.parseId({ value: context.propsValue.agentId, label: 'Agent ID' });+ const prompt = taskadeApi.requireText({ value: context.propsValue.prompt, label: 'Prompt' });+ if (prompt.length > MAX_PROMPT) {+ throw new Error(`Prompt is ${prompt.length} characters; keep it under ${MAX_PROMPT}.`);+ }+ const given = (context.propsValue.workspaceId ?? '').trim();+ const spaceId = given.length > 0 ? given : await lookupSpaceId({ token, agentId });+ const response = await taskadeApi.request<{ ok: boolean; summary?: string }>({+ token,+ method: HttpMethod.POST,+ version: 'v2',+ path: '/promptAgent',+ operation: 'prompt agent',+ body: { spaceId, agentId, prompt },+ timeoutMs: PROMPT_TIMEOUT_MS,+ });+ return { agentId, spaceId, response: response.summary ?? '' };+ },+});++async function lookupSpaceId({ token, agentId }: { token: string; agentId: string }): Promise<string> {+ const agent = await taskadeApi.request<ItemAPIResponse<AgentResponse>>({+ token,+ method: HttpMethod.GET,+ path: `/agents/${taskadeApi.seg({ value: agentId, label: 'Agent ID' })}`,+ operation: 'get agent',+ });+ const spaceId = agent.item?.space_id;+ if (!spaceId) {+ throw new Error('Taskade did not return the agent\'s workspace ID. Pass Workspace ID explicitly.');+ }+ return spaceId;+}++const PROMPT_TIMEOUT_MS = 240_000;+const MAX_PROMPT = 100_000;diff --git a/packages/pieces/community/taskade/src/lib/actions/assign-task.ts b/packages/pieces/community/taskade/src/lib/actions/assign-task.tsnew file mode 100644index 00000000000..2ddbc2b1134--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/assign-task.ts@@ -0,0 +1,68 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { ItemAPIResponse, ListAPIResponse, MemberResponse, TaskResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const assignTaskAction = createAction({+ auth: taskadeAuth,+ name: 'assign_task',+ displayName: 'Assign Task',+ description: 'Assigns project members to a task by their handle.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Assigns one or more project members (by handle, from List Project Members) to a Taskade task; Taskade notifies them. Returns the task and its full assignee list. Assigning someone already assigned changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ handles: Property.Array({+ displayName: 'Member Handles',+ description: 'Handles of project members, without @. Get them from List Project Members.',+ required: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['assignTask'],+ async run(context) {+ const { projectId, taskId } = context.propsValue;+ const handles = toHandles(context.propsValue.handles);+ if (handles.length === 0) {+ throw new Error('Add at least one member handle.');+ }+ const token = context.auth.secret_text;+ const path = taskadeApi.taskPath({ projectId, taskId });+ const response = await taskadeApi.request<ItemAPIResponse<TaskResponse>>({+ token,+ method: HttpMethod.PUT,+ path: `${path}/assignees`,+ operation: 'assign task',+ body: { handles },+ });+ const task = await taskadeTasks.taskOrFallback({ token, projectId, taskId, item: response.item });+ const assignees = await taskadeApi.request<ListAPIResponse<MemberResponse>>({+ token,+ method: HttpMethod.GET,+ path: `${path}/assignees`,+ operation: 'get task assignees',+ });+ return {+ ...task,+ assignees: (assignees.items ?? []).map((member) => ({ handle: member.handle, displayName: member.displayName ?? null })),+ };+ },+});++function toHandles(value: unknown): string[] {+ const list = Array.isArray(value) ? value : value === undefined || value === null ? [] : [value];+ const handles = list+ .map((entry: unknown) => (taskadeApi.isRecord(entry) ? Object.values(entry)[0] : entry))+ .map((entry) => (entry === undefined || entry === null ? '' : String(entry).trim().replace(/^@/, '')))+ .filter((entry) => entry.length > 0);+ return [...new Set(handles)];+}diff --git a/packages/pieces/community/taskade/src/lib/actions/complete-project.ts b/packages/pieces/community/taskade/src/lib/actions/complete-project.tsnew file mode 100644index 00000000000..eff9833d43f--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/complete-project.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ItemAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const completeProjectAction = createAction({+ auth: taskadeAuth,+ name: 'complete_project',+ displayName: 'Complete (Archive) Project',+ description: 'Marks a project as completed, which archives it.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Marks a whole Taskade project as completed, which archives it; Restore Project undoes it. Repeating it leaves the project completed, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['project'],+ async run(context) {+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const path = `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}`;+ await taskadeApi.request({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `${path}/complete`,+ operation: 'complete project',+ body: {},+ });+ const current = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path,+ operation: 'get project',+ });+ return { ...taskadeNormalize.project(current.item), completed: true };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/complete-task.action.ts b/packages/pieces/community/taskade/src/lib/actions/complete-task.action.tsindex cd13a8609df..846cbdd0402 100644--- a/packages/pieces/community/taskade/src/lib/actions/complete-task.action.ts+++ b/packages/pieces/community/taskade/src/lib/actions/complete-task.action.ts@@ -1,7 +1,8 @@import { taskadeAuth } from '../auth';import { createAction } from '@activepieces/pieces-framework';import { taskadeProps } from '../common/props';-import { TaskadeAPIClient } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { taskadeOutputSchemas } from '../output-schemas';export const completeTaskAction = createAction({auth: taskadeAuth,@@ -9,7 +10,7 @@ export const completeTaskAction = createAction({classification: 'WRITE',displayName: 'Complete Task',description: 'Complete a task in a project.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Marks an existing Taskade task as completed within a given project. Use when an agent needs to check off or close out a task; requires the project id and task id. Idempotent, since re-running leaves the task in the same completed state.', idempotent: true },props: {workspace_id: taskadeProps.workspace_id,@@ -17,11 +18,10 @@ export const completeTaskAction = createAction({project_id: taskadeProps.project_id,task_id: taskadeProps.task_id,},+ outputSchema: taskadeOutputSchemas['legacyTaskItem'],async run(context) {const { project_id, task_id } = context.propsValue;-- const client = new TaskadeAPIClient(context.auth.secret_text);-- return await client.completeTask(project_id, task_id);+ const { task } = await taskadeTasks.setCompletion({ token: context.auth.secret_text, projectId: project_id, taskId: task_id, completed: true });+ return { ok: true, item: { id: task.id, text: task.text, parentId: task.parentId, completed: task.completed } };},});diff --git a/packages/pieces/community/taskade/src/lib/actions/copy-project.ts b/packages/pieces/community/taskade/src/lib/actions/copy-project.tsnew file mode 100644index 00000000000..297ec05f794--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/copy-project.ts@@ -0,0 +1,48 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ItemAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const copyProjectAction = createAction({+ auth: taskadeAuth,+ name: 'copy_project',+ displayName: 'Copy Project',+ description: 'Copies a project, with its tasks, into a workspace or folder.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Duplicates a Taskade project with all its tasks into a workspace or folder, optionally with a new title. Returns the copy\'s project ID and link. Not idempotent: each call makes another copy.',+ idempotent: false,+ },+ props: {+ projectId: taskadeAiProps.projectId({ displayName: 'Project to Copy' }),+ folderId: taskadeAiProps.folderId({ description: 'Where to put the copy. A workspace ID works for its home folder.' }),+ projectTitle: Property.ShortText({+ displayName: 'New Title',+ description: 'Optional title for the copy. Leave empty to keep the original title.',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['project'],+ async run(context) {+ const { projectId, folderId, projectTitle } = context.propsValue;+ const sourceId = taskadeApi.parseProjectId(projectId);+ const title = (projectTitle ?? '').trim();+ const response = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `/projects/${taskadeApi.seg({ value: sourceId, label: 'Project ID' })}/copy`,+ operation: 'copy project',+ body: {+ folderId: taskadeApi.requireText({ value: folderId, label: 'Workspace or Folder ID' }),+ ...(title.length > 0 ? { projectTitle: title } : {}),+ },+ });+ return taskadeNormalize.projectWithName({ token: context.auth.secret_text, item: response.item });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/create-project-from-template.ts b/packages/pieces/community/taskade/src/lib/actions/create-project-from-template.tsnew file mode 100644index 00000000000..3b01d1705a5--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/create-project-from-template.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ItemAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const createProjectFromTemplateAction = createAction({+ auth: taskadeAuth,+ name: 'create_project_from_template',+ displayName: 'Create Project from Template',+ description: 'Creates a project from one of your Taskade project templates.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates a new Taskade project in a workspace or folder from a project template (get template IDs from List Project Templates). Returns the new project ID and link. Not idempotent: each call creates another project.',+ idempotent: false,+ },+ props: {+ folderId: taskadeAiProps.folderId({ description: 'Where to create the project. A workspace ID works for its home folder.' }),+ templateId: Property.ShortText({+ displayName: 'Template ID',+ description: 'Get it from List Project Templates.',+ required: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['project'],+ async run(context) {+ const response = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: '/projects/from-template',+ operation: 'create project from template',+ body: {+ folderId: taskadeApi.requireText({ value: context.propsValue.folderId, label: 'Workspace or Folder ID' }),+ templateId: taskadeApi.requireText({ value: context.propsValue.templateId, label: 'Template ID' }),+ },+ });+ return taskadeNormalize.projectWithName({ token: context.auth.secret_text, item: response.item });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/create-project.ts b/packages/pieces/community/taskade/src/lib/actions/create-project.tsnew file mode 100644index 00000000000..ec06c30d30e--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/create-project.ts@@ -0,0 +1,57 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ItemAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const createProjectAction = createAction({+ auth: taskadeAuth,+ name: 'create_project',+ displayName: 'Create Project',+ description: 'Creates a project in a workspace or folder, optionally with tasks written as a Markdown list.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates a new Taskade project in a workspace or folder (a workspace ID uses its home folder) with the given title, and optional Markdown content where each "- item" line becomes a task. Returns the new project ID and link. Not idempotent: each call creates another project.',+ idempotent: false,+ },+ props: {+ folderId: taskadeAiProps.folderId(),+ title: Property.ShortText({+ displayName: 'Project Title',+ required: true,+ }),+ content: Property.LongText({+ displayName: 'Content (Markdown)',+ description: 'Optional. Each line starting with "- " becomes a task; indent with two spaces for subtasks.',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['project'],+ async run(context) {+ const { folderId, title, content } = context.propsValue;+ const projectTitle = taskadeApi.requireText({ value: title, label: 'Project Title' });+ if (/[\r\n]/.test(projectTitle)) {+ throw new Error('Project Title must be a single line.');+ }+ const body = (content ?? '').trim();+ const markdown = body.length > 0 ? `# ${projectTitle}\n\n${body}` : `# ${projectTitle}`;+ const response = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: '/projects',+ operation: 'create project',+ body: {+ folderId: taskadeApi.requireText({ value: folderId, label: 'Workspace or Folder ID' }),+ contentType: 'text/markdown',+ content: markdown,+ },+ });+ const project = taskadeNormalize.project(response.item);+ return { ...project, name: project.name ?? projectTitle };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/create-task.action.ts b/packages/pieces/community/taskade/src/lib/actions/create-task.action.tsindex f96f8eec49e..87019efed15 100644--- a/packages/pieces/community/taskade/src/lib/actions/create-task.action.ts+++ b/packages/pieces/community/taskade/src/lib/actions/create-task.action.ts@@ -1,7 +1,11 @@import { taskadeAuth } from '../auth';import { createAction, Property } from '@activepieces/pieces-framework';import { taskadeProps } from '../common/props';-import { TaskadeAPIClient } from '../common/client';+import { HttpMethod } from '@activepieces/pieces-common';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { CreateTaskResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';export const createTaskAction = createAction({auth: taskadeAuth,@@ -9,7 +13,7 @@ export const createTaskAction = createAction({classification: 'WRITE',displayName: 'Create Task',description: 'Creates a new task.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Adds a new task to a Taskade project, with the task body supplied as markdown or plain text and positioned at the start or end of the project. Use to append work items to an existing project; requires the target project id. Creates a new task on every call, so it is not idempotent.', idempotent: false },props: {workspace_id: taskadeProps.workspace_id,@@ -23,11 +27,11 @@ export const createTaskAction = createAction({disabled: false,options: [{- label: 'text/markdown',+ label: 'Markdown',value: 'text/markdown',},{- label: 'text/plain',+ label: 'Plain text',value: 'text/plain',},],@@ -35,37 +39,39 @@ export const createTaskAction = createAction({}),content: Property.LongText({displayName: 'Task Content',+ description: 'Up to 2,000 characters.',required: true,}),placement: Property.StaticDropdown({displayName: 'Placement',- description: 'Placement of task in block',+ description: 'Where to add the task in the project.',required: true,defaultValue: 'afterbegin',options: {disabled: false,options: [{- label: 'afterbegin',+ label: 'Top of project',value: 'afterbegin',},{- label: 'beforeend',+ label: 'Bottom of project',value: 'beforeend',},],},}),},+ outputSchema: taskadeOutputSchemas['legacyCreateTask'],async run(context) {const { project_id, content_type, content, placement } = context.propsValue;-- const client = new TaskadeAPIClient(context.auth.secret_text);-- return await client.createTask(project_id, {- content,- contentType: content_type,- placement,+ const text = taskadeTasks.validateTaskText({ value: content, label: 'Task Content', singleLine: false });+ return taskadeApi.request<CreateTaskResponse>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `/projects/${taskadeApi.seg({ value: project_id, label: 'Project' })}/tasks`,+ operation: 'create task',+ body: { tasks: [{ content: text, contentType: content_type, placement }] },});},});diff --git a/packages/pieces/community/taskade/src/lib/actions/create-tasks.ts b/packages/pieces/community/taskade/src/lib/actions/create-tasks.tsnew file mode 100644index 00000000000..ae003c0cb72--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/create-tasks.ts@@ -0,0 +1,132 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { CreateTaskResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const createTasksAction = createAction({+ auth: taskadeAuth,+ name: 'create_tasks',+ displayName: 'Create Tasks',+ description: 'Adds 1-20 tasks to a project, at the top or bottom, or next to or inside another task.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Adds 1-20 tasks to a Taskade project in one request, at the top or bottom of the project, or before, after or inside (as first or last subtask of) an existing task given by Relative To Task ID. Each task text is one line of up to 2,000 characters of Markdown or plain text. Returns the created task IDs. Not idempotent: each call adds new tasks.',+ idempotent: false,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ tasks: Property.Array({+ displayName: 'Tasks',+ description: 'One entry per task (1-20). Each entry is a single line of up to 2,000 characters.',+ required: true,+ }),+ format: taskadeAiProps.format(),+ position: Property.StaticDropdown({+ displayName: 'Position',+ required: false,+ defaultValue: 'bottom',+ options: {+ disabled: false,+ options: [+ { label: 'Bottom of project', value: 'bottom' },+ { label: 'Top of project', value: 'top' },+ { label: 'Before a task', value: 'before' },+ { label: 'After a task', value: 'after' },+ { label: 'First subtask of a task', value: 'first_child' },+ { label: 'Last subtask of a task', value: 'last_child' },+ ],+ },+ }),+ relativeToTaskId: taskadeAiProps.taskId({+ displayName: 'Relative To Task ID',+ description: 'Required for Before, After, First subtask and Last subtask positions.',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['createTasks'],+ async run(context) {+ const { projectId, tasks, format, position, relativeToTaskId } = context.propsValue;+ const texts = toTexts(tasks);+ if (texts.length === 0) {+ throw new Error('Add at least one task.');+ }+ if (texts.length > MAX_TASKS) {+ throw new Error(`Taskade accepts at most ${MAX_TASKS} tasks per call; you passed ${texts.length}. Split them into several calls.`);+ }+ const contents = texts.map((text, index) => taskadeTasks.validateTaskText({ value: text, label: `Task ${index + 1}`, singleLine: true }));+ const placement = toPlacement({ position, relativeToTaskId });+ const contentType = taskadeTasks.contentType(format);+ const ordered = placement.reverseOrder ? [...contents].reverse() : contents;+ const response = await taskadeApi.request<CreateTaskResponse>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `${taskadeApi.projectPath(projectId)}/tasks/`,+ operation: 'create tasks',+ body: {+ tasks: ordered.map((content) => ({+ contentType,+ content,+ placement: placement.placement,+ ...(placement.taskId ? { taskId: placement.taskId } : {}),+ })),+ },+ });+ const created = (response.item ?? []).map((item, index) => ({+ id: item.id,+ text: item.text ?? ordered[index] ?? '',+ completed: item.completed === true,+ }));+ const items = placement.reverseOrder ? [...created].reverse() : created;+ return { items, count: items.length };+ },+});++function toTexts(tasks: unknown): string[] {+ if (tasks === undefined || tasks === null) {+ return [];+ }+ const list = Array.isArray(tasks) ? tasks : [tasks];+ return list+ .map((entry: unknown) => {+ if (taskadeApi.isRecord(entry)) {+ const value = entry['content'] ?? entry['text'] ?? Object.values(entry)[0];+ return value === undefined || value === null ? '' : String(value);+ }+ return entry === undefined || entry === null ? '' : String(entry);+ })+ .map((text) => text.trim())+ .filter((text) => text.length > 0);+}++function toPlacement({ position, relativeToTaskId }: { position: unknown; relativeToTaskId: unknown }): Placement {+ const value = typeof position === 'string' && position.length > 0 ? position : 'bottom';+ if (value === 'top') {+ return { placement: 'afterbegin', reverseOrder: true };+ }+ if (value === 'bottom') {+ return { placement: 'beforeend', reverseOrder: false };+ }+ const anchor = POSITION_TO_PLACEMENT[value];+ if (!anchor) {+ throw new Error(`Unknown position "${value}". Use top, bottom, before, after, first_child or last_child.`);+ }+ const taskId = taskadeApi.requireText({ value: relativeToTaskId, label: 'Relative To Task ID' });+ return { placement: anchor.placement, taskId, reverseOrder: anchor.reverseOrder };+}++const MAX_TASKS = 20;++const POSITION_TO_PLACEMENT: Record<string, { placement: string; reverseOrder: boolean }> = {+ before: { placement: 'beforebegin', reverseOrder: false },+ after: { placement: 'afterend', reverseOrder: true },+ first_child: { placement: 'afterbegin', reverseOrder: true },+ last_child: { placement: 'beforeend', reverseOrder: false },+};++type Placement = { placement: string; taskId?: string; reverseOrder: boolean };diff --git a/packages/pieces/community/taskade/src/lib/actions/delete-agent.ts b/packages/pieces/community/taskade/src/lib/actions/delete-agent.tsnew file mode 100644index 00000000000..2c3af92a810--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/delete-agent.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeOutputSchemas } from '../output-schemas';++export const deleteAgentAction = createAction({+ auth: taskadeAuth,+ name: 'delete_agent',+ displayName: 'Delete AI Agent',+ description: 'Permanently deletes an AI agent.',+ classification: 'DESTRUCTIVE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently deletes one Taskade AI agent by ID, including its commands and settings; it cannot be undone. Use only when the user asks. A repeat call finds it gone and reports alreadyDeleted=true, so it is idempotent.',+ idempotent: true,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ },+ outputSchema: taskadeOutputSchemas['deleteAgent'],+ async run(context) {+ const agentId = taskadeApi.requireText({ value: context.propsValue.agentId, label: 'Agent ID' });+ try {+ await taskadeApi.request({+ token: context.auth.secret_text,+ method: HttpMethod.DELETE,+ path: `/agents/${taskadeApi.seg({ value: agentId, label: 'Agent ID' })}`,+ operation: 'delete agent',+ });+ return { agentId, deleted: true, alreadyDeleted: false };+ } catch (error) {+ if (taskadeApi.isNotFound(error)) {+ return { agentId, deleted: true, alreadyDeleted: true };+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/delete-task.action.ts b/packages/pieces/community/taskade/src/lib/actions/delete-task.action.tsindex bdc97500f66..c287c64ccd9 100644--- a/packages/pieces/community/taskade/src/lib/actions/delete-task.action.ts+++ b/packages/pieces/community/taskade/src/lib/actions/delete-task.action.ts@@ -1,7 +1,9 @@import { taskadeAuth } from '../auth';import { createAction } from '@activepieces/pieces-framework';import { taskadeProps } from '../common/props';-import { TaskadeAPIClient } from '../common/client';+import { HttpMethod } from '@activepieces/pieces-common';+import { taskadeApi } from '../common/client';+import { taskadeOutputSchemas } from '../output-schemas';export const deleteTaskAction = createAction({auth: taskadeAuth,@@ -9,19 +11,33 @@ export const deleteTaskAction = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete Task',description: 'Delete an existing task in a project.',- audience: 'both',- aiMetadata: { description: 'Permanently removes a task from a Taskade project, identified by project id and task id. Use to discard a task an agent no longer needs; this is destructive and cannot be undone. Idempotent, since deleting an already-removed task leaves the project in the same state.', idempotent: true },+ audience: 'human',+ aiMetadata: { description: 'Permanently removes a task from a Taskade project, identified by project id and task id. Use to discard a task an agent no longer needs; this is destructive and cannot be undone. A repeat call finds the task gone and returns ok with alreadyDeleted=true, so it is idempotent.', idempotent: true },props: {workspace_id: taskadeProps.workspace_id,folder_id: taskadeProps.folder_id,project_id: taskadeProps.project_id,task_id: taskadeProps.task_id,},+ outputSchema: taskadeOutputSchemas['legacyDelete'],async run(context) {const { project_id, task_id } = context.propsValue;-- const client = new TaskadeAPIClient(context.auth.secret_text);-- return await client.deleteTask(project_id, task_id);+ const token = context.auth.secret_text;+ const projectPath = `/projects/${taskadeApi.seg({ value: project_id, label: 'Project' })}`;+ try {+ await taskadeApi.request({+ token,+ method: HttpMethod.DELETE,+ path: `${projectPath}/tasks/${taskadeApi.seg({ value: task_id, label: 'Task' })}`,+ operation: 'delete task',+ });+ return { ok: true, alreadyDeleted: false };+ } catch (error) {+ if (!taskadeApi.isNotFound(error)) {+ throw error;+ }+ await taskadeApi.request({ token, method: HttpMethod.GET, path: projectPath, operation: 'get project' });+ return { ok: true, alreadyDeleted: true };+ }},});diff --git a/packages/pieces/community/taskade/src/lib/actions/find-tasks.ts b/packages/pieces/community/taskade/src/lib/actions/find-tasks.tsnew file mode 100644index 00000000000..bac916832eb--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/find-tasks.ts@@ -0,0 +1,104 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { Task, TaskPageResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const findTasksAction = createAction({+ auth: taskadeAuth,+ name: 'find_tasks',+ displayName: 'Find Tasks',+ description: 'Finds tasks in a project whose text contains some words.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Finds tasks in one Taskade project whose text contains the given words (case-insensitive), optionally only open or only completed ones, scanning up to 5,000 tasks per call (truncated=true and nextCursor when more remain). Use when the user names a task instead of giving its ID. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ textContains: Property.ShortText({+ displayName: 'Text Contains',+ description: 'Words to look for in the task text (case-insensitive).',+ required: true,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ required: false,+ defaultValue: 'any',+ options: {+ disabled: false,+ options: [+ { label: 'Any', value: 'any' },+ { label: 'Open only', value: 'open' },+ { label: 'Completed only', value: 'completed' },+ ],+ },+ }),+ maxResults: Property.Number({+ displayName: 'Max Results',+ description: 'Stop after this many matches (1-500, default 50).',+ required: false,+ defaultValue: 50,+ }),+ startCursor: Property.ShortText({+ displayName: 'Start Cursor',+ description: 'To continue a truncated search, pass nextCursor from the previous result.',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['findTasks'],+ async run(context) {+ const { projectId, textContains, status, startCursor } = context.propsValue;+ const needle = taskadeApi.requireText({ value: textContains, label: 'Text Contains' }).toLowerCase();+ const maxResults = taskadeApi.validateInteger({ value: context.propsValue.maxResults, label: 'Max Results', min: 1, max: 500 }) ?? 50;+ const path = `${taskadeApi.projectPath(projectId)}/tasks`;+ const matches: Task[] = [];+ let scanned = 0;+ let after: string | undefined = (startCursor ?? '').trim() || undefined;+ for (let page = 0; page < MAX_PAGES; page++) {+ const response = await taskadeApi.request<TaskPageResponse>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path,+ operation: 'list tasks',+ query: { limit: PAGE_SIZE, after },+ });+ const items = (response.items ?? []).map((item) => taskadeNormalize.task(item));+ scanned += items.length;+ const pageMatches = items.filter((task) => !task.isRoot && matchesStatus({ task, status }) && task.text.toLowerCase().includes(needle));+ matches.push(...pageMatches);+ const hasMore = response.hasMore ?? items.length === PAGE_SIZE;+ const nextCursor = response.nextCursor ?? items[items.length - 1]?.id;+ if (matches.length >= maxResults) {+ const cut = matches.slice(0, maxResults);+ const lastMatch = cut[cut.length - 1];+ const remainderOnPage = items.findIndex((task) => task.id === lastMatch.id) < items.length - 1;+ const truncated = remainderOnPage || hasMore;+ return { found: true, items: cut, scanned, truncated, nextCursor: truncated ? lastMatch.id : null };+ }+ if (!hasMore || items.length === 0 || !nextCursor) {+ return { found: matches.length > 0, items: matches, scanned, truncated: false, nextCursor: null };+ }+ after = nextCursor;+ }+ return { found: matches.length > 0, items: matches, scanned, truncated: true, nextCursor: after ?? null };+ },+});++function matchesStatus({ task, status }: { task: Task; status: unknown }): boolean {+ if (status === 'open') {+ return !task.completed;+ }+ if (status === 'completed') {+ return task.completed;+ }+ return true;+}++const PAGE_SIZE = 1000;+const MAX_PAGES = 5;diff --git a/packages/pieces/community/taskade/src/lib/actions/generate-agent.ts b/packages/pieces/community/taskade/src/lib/actions/generate-agent.tsnew file mode 100644index 00000000000..9c35c0078b0--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/generate-agent.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { AgentResponse, ItemAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const generateAgentAction = createAction({+ auth: taskadeAuth,+ name: 'generate_agent',+ displayName: 'Generate AI Agent',+ description: 'Creates a new AI agent from a plain-language description. Uses Taskade AI credits.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Creates a new Taskade AI agent in a workspace or folder from a plain-language description of what it should do; Taskade writes its name, system prompt and commands. Returns the new agent ID. Uses Taskade AI credits; not idempotent: each call creates another agent.',+ idempotent: false,+ },+ props: {+ folderId: taskadeAiProps.folderId(),+ description: Property.LongText({+ displayName: 'What the Agent Should Do',+ description: 'For example: "An agent that drafts friendly replies to customer support emails".',+ required: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['agent'],+ async run(context) {+ const text = taskadeApi.requireText({ value: context.propsValue.description, label: 'What the Agent Should Do' });+ const response = await taskadeApi.request<ItemAPIResponse<AgentResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `/folders/${taskadeApi.seg({ value: context.propsValue.folderId, label: 'Folder ID' })}/agent-generate`,+ operation: 'generate agent',+ body: { text },+ timeoutMs: GENERATE_TIMEOUT_MS,+ });+ return taskadeNormalize.agent({ raw: response.item, includePrompts: true });+ },+});++const GENERATE_TIMEOUT_MS = 180_000;diff --git a/packages/pieces/community/taskade/src/lib/actions/get-agent-conversation.ts b/packages/pieces/community/taskade/src/lib/actions/get-agent-conversation.tsnew file mode 100644index 00000000000..5aa478a022b--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/get-agent-conversation.ts@@ -0,0 +1,64 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ConversationResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const getAgentConversationAction = createAction({+ auth: taskadeAuth,+ name: 'get_agent_conversation',+ displayName: 'Get Agent Conversation',+ description: 'Gets one conversation of an AI agent, with its transcript.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one conversation of a Taskade AI agent (title, status) and, unless turned off, its transcript as text, capped at 100,000 characters (truncated=true when cut). Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ conversationId: Property.ShortText({+ displayName: 'Conversation ID',+ description: 'Get it from List Agent Conversations.',+ required: true,+ }),+ includeTranscript: Property.Checkbox({+ displayName: 'Include Transcript',+ required: false,+ defaultValue: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['conversation'],+ async run(context) {+ const { agentId, conversationId, includeTranscript } = context.propsValue;+ const withTranscript = includeTranscript !== false;+ const response = await taskadeApi.request<{ ok: boolean; item?: ConversationResponse; transcript?: string }>({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ version: 'v2',+ path: '/getConversation',+ operation: 'get agent conversation',+ body: {+ agentId: taskadeApi.requireText({ value: agentId, label: 'Agent ID' }),+ convoId: taskadeApi.requireText({ value: conversationId, label: 'Conversation ID' }),+ includeTranscript: withTranscript,+ },+ });+ if (!response.item) {+ throw new Error('Taskade returned no conversation in its response.');+ }+ const transcript = withTranscript ? response.transcript ?? '' : null;+ const truncated = transcript !== null && transcript.length > MAX_TRANSCRIPT;+ return {+ ...taskadeNormalize.conversation(response.item),+ transcript: truncated && transcript !== null ? transcript.slice(0, MAX_TRANSCRIPT) : transcript,+ truncated,+ };+ },+});++const MAX_TRANSCRIPT = 100_000;diff --git a/packages/pieces/community/taskade/src/lib/actions/get-agent.ts b/packages/pieces/community/taskade/src/lib/actions/get-agent.tsnew file mode 100644index 00000000000..9aa0ac6e1d6--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/get-agent.ts@@ -0,0 +1,35 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { AgentResponse, ItemAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const getAgentAction = createAction({+ auth: taskadeAuth,+ name: 'get_agent',+ displayName: 'Get AI Agent',+ description: 'Gets an AI agent with its commands and their prompts.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Taskade AI agent by ID: name, workspace ID, description (its system prompt), whether knowledge is on, and its commands with their prompts. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ },+ outputSchema: taskadeOutputSchemas['agent'],+ async run(context) {+ const response = await taskadeApi.request<ItemAPIResponse<AgentResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/agents/${taskadeApi.seg({ value: context.propsValue.agentId, label: 'Agent ID' })}`,+ operation: 'get agent',+ });+ return taskadeNormalize.agent({ raw: response.item, includePrompts: true });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/get-project-share-link.ts b/packages/pieces/community/taskade/src/lib/actions/get-project-share-link.tsnew file mode 100644index 00000000000..922388b69f4--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/get-project-share-link.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { ItemAPIResponse, ShareLinkResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const getProjectShareLinkAction = createAction({+ auth: taskadeAuth,+ name: 'get_project_share_link',+ displayName: 'Get Project Share Link',+ description: 'Gets the view and edit share links of a project, if sharing is on.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns the share links of one Taskade project (view link, edit link, and a check-only link when present), or enabled=false when the project has no share link. It does not turn sharing on. Anyone with the edit link can change the project, so only pass it to people the user names. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['shareLink'],+ async run(context) {+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const response = await taskadeApi.request<ItemAPIResponse<ShareLinkResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}/shareLink`,+ operation: 'get share link',+ });+ const item = response.item;+ return {+ projectId,+ enabled: Boolean(item && (item.viewUrl || item.editUrl)),+ viewUrl: item?.viewUrl ?? null,+ editUrl: item?.editUrl ?? null,+ checkUrl: item?.checkUrl ?? null,+ };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/get-project.ts b/packages/pieces/community/taskade/src/lib/actions/get-project.tsnew file mode 100644index 00000000000..81ae7cba08f--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/get-project.ts@@ -0,0 +1,36 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ItemAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const getProjectAction = createAction({+ auth: taskadeAuth,+ name: 'get_project',+ displayName: 'Get Project',+ description: 'Gets a project by ID or link.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Taskade project (ID, name, icon, archived state and link) from its ID or https://www.taskade.com/d/ link. Use to check a project exists or is archived before working on it. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['project'],+ async run(context) {+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const response = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}`,+ operation: 'get project',+ });+ return taskadeNormalize.project(response.item);+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/get-task.ts b/packages/pieces/community/taskade/src/lib/actions/get-task.tsnew file mode 100644index 00000000000..0b2acf6b1a1--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/get-task.ts@@ -0,0 +1,76 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { FieldValueResponse, ItemAPIResponse, ListAPIResponse, MemberResponse, TaskDateResponse, TaskNoteResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const getTaskAction = createAction({+ auth: taskadeAuth,+ name: 'get_task',+ displayName: 'Get Task',+ description: 'Gets a task with its date, note, assignees and custom field values.',+ classification: 'READ',+ audience: 'both',+ aiMetadata: {+ description:+ 'Returns one Taskade task by project and task ID: text, parent, completion and, unless Include Details is off, its date, note, assignees and custom field values (empty when not set). With details it makes 5 requests, so turn details off when you only need the text. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ includeDetails: Property.Checkbox({+ displayName: 'Include Details',+ description: 'Also fetch the date, note, assignees and custom field values (4 more requests).',+ required: false,+ defaultValue: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['taskDetails'],+ async run(context) {+ const { projectId, taskId, includeDetails } = context.propsValue;+ const token = context.auth.secret_text;+ const task = await taskadeTasks.getTask({ token, projectId, taskId });+ if (includeDetails === false) {+ return task;+ }+ const path = taskadeApi.taskPath({ projectId, taskId });+ const optional = <T>({ call, whenMissing }: { call: () => Promise<T>; whenMissing: T }): Promise<T> =>+ call().catch((error: unknown) => {+ if (taskadeApi.isNotFound(error)) {+ return whenMissing;+ }+ throw error;+ });+ const date = await optional({+ call: async () =>+ (await taskadeApi.request<ItemAPIResponse<TaskDateResponse>>({ token, method: HttpMethod.GET, path: `${path}/date`, operation: 'get task date' })).item ?? null,+ whenMissing: null,+ });+ const note = await optional({+ call: async () =>+ (await taskadeApi.request<ItemAPIResponse<TaskNoteResponse>>({ token, method: HttpMethod.GET, path: `${path}/note`, operation: 'get task note' })).item ?? null,+ whenMissing: null,+ });+ const assignees = await optional({+ call: async () =>+ (await taskadeApi.request<ListAPIResponse<MemberResponse>>({ token, method: HttpMethod.GET, path: `${path}/assignees`, operation: 'get task assignees' })).items ?? [],+ whenMissing: [],+ });+ const fields = await optional({+ call: async () =>+ (await taskadeApi.request<ListAPIResponse<FieldValueResponse>>({ token, method: HttpMethod.GET, path: `${path}/fields`, operation: 'get task field values' })).items ?? [],+ whenMissing: [],+ });+ return {+ ...task,+ date,+ note,+ assignees: assignees.map((member) => ({ handle: member.handle, displayName: member.displayName ?? null })),+ fields: fields.map((field) => ({ fieldId: field.fieldId, value: field.value ?? null })),+ };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-agent-conversations.ts b/packages/pieces/community/taskade/src/lib/actions/list-agent-conversations.tsnew file mode 100644index 00000000000..6225b1c98f0--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-agent-conversations.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ConversationResponse, ListAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listAgentConversationsAction = createAction({+ auth: taskadeAuth,+ name: 'list_agent_conversations',+ displayName: 'List Agent Conversations',+ description: 'Lists the conversations of an AI agent.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the conversations of one Taskade AI agent with ID, title and status, one page at a time. Use to get a conversation ID for Get Agent Conversation; pass nextPage to continue. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ limit: taskadeAiProps.limit({ max: 100, defaultValue: 20 }),+ page: taskadeAiProps.page(),+ },+ outputSchema: taskadeOutputSchemas['listConversations'],+ async run(context) {+ const limit = taskadeApi.validateInteger({ value: context.propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 20;+ const page = taskadeApi.validateInteger({ value: context.propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;+ const response = await taskadeApi.request<ListAPIResponse<ConversationResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/agents/${taskadeApi.seg({ value: context.propsValue.agentId, label: 'Agent ID' })}/convos/`,+ operation: 'list agent conversations',+ query: { limit, page },+ });+ const rawItems = response.items ?? [];+ const items = rawItems.map((item) => taskadeNormalize.conversation(item));+ return taskadeNormalize.pageOutput({ items, fetched: rawItems.length, page, limit });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-agents.ts b/packages/pieces/community/taskade/src/lib/actions/list-agents.tsnew file mode 100644index 00000000000..d4b47da240c--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-agents.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { AgentResponse, ListAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listAgentsAction = createAction({+ auth: taskadeAuth,+ name: 'list_agents',+ displayName: 'List AI Agents',+ description: 'Lists the AI agents in a workspace or folder.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the Taskade AI agents in one workspace or folder (a workspace ID lists its home folder), with ID, name, workspace ID, description and command names, one page at a time. Use to get an agent ID for Ask AI Agent; pass nextPage to continue. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ folderId: taskadeAiProps.folderId(),+ limit: taskadeAiProps.limit({ max: 100, defaultValue: 20 }),+ page: taskadeAiProps.page(),+ },+ outputSchema: taskadeOutputSchemas['listAgents'],+ async run(context) {+ const limit = taskadeApi.validateInteger({ value: context.propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 20;+ const page = taskadeApi.validateInteger({ value: context.propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;+ const response = await taskadeApi.request<ListAPIResponse<AgentResponse | null>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/folders/${taskadeApi.seg({ value: context.propsValue.folderId, label: 'Folder ID' })}/agents`,+ operation: 'list agents',+ query: { limit, page },+ });+ const rawItems = response.items ?? [];+ const items = rawItems+ .filter((item): item is AgentResponse => item !== null)+ .map((raw) => taskadeNormalize.agent({ raw, includePrompts: false }));+ return taskadeNormalize.pageOutput({ items, fetched: rawItems.length, page, limit });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-folders.ts b/packages/pieces/community/taskade/src/lib/actions/list-folders.tsnew file mode 100644index 00000000000..45ea6758094--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-folders.ts@@ -0,0 +1,37 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeApi } from '../common/client';+import { ListAPIResponse, WorkspaceFolderResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listFoldersAction = createAction({+ auth: taskadeAuth,+ name: 'list_folders',+ displayName: 'List Folders',+ description: 'Lists the folders of a workspace, including its home folder.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the folders of one Taskade workspace, with ID and name. The list includes the workspace home folder, whose ID equals the workspace ID. Use to pick a folder ID for List Projects, Create Project or List AI Agents. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ workspaceId: Property.ShortText({+ displayName: 'Workspace ID',+ description: 'Get it from List Workspaces.',+ required: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['listFolders'],+ async run(context) {+ const response = await taskadeApi.request<ListAPIResponse<WorkspaceFolderResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/workspaces/${taskadeApi.seg({ value: context.propsValue.workspaceId, label: 'Workspace ID' })}/folders`,+ operation: 'list folders',+ });+ return { items: (response.items ?? []).filter((item) => item !== null).map((item) => ({ id: item.id, name: item.name })) };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-project-fields.ts b/packages/pieces/community/taskade/src/lib/actions/list-project-fields.tsnew file mode 100644index 00000000000..ebdaddb6287--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-project-fields.ts@@ -0,0 +1,36 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { FieldResponse, ListAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listProjectFieldsAction = createAction({+ auth: taskadeAuth,+ name: 'list_project_fields',+ displayName: 'List Custom Fields',+ description: 'Lists the custom fields of a project, with select options.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the custom fields defined on one Taskade project: field ID, type (for example number, string, Select), name and, for Select fields, the option IDs and names. Use before Set Custom Field Value to get the field ID and a valid option ID. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['listProjectFields'],+ async run(context) {+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const response = await taskadeApi.request<ListAPIResponse<FieldResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}/fields`,+ operation: 'list custom fields',+ });+ return { items: (response.items ?? []).map((field) => taskadeNormalize.field(field)) };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-project-members.ts b/packages/pieces/community/taskade/src/lib/actions/list-project-members.tsnew file mode 100644index 00000000000..022ca5d0974--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-project-members.ts@@ -0,0 +1,45 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ListAPIResponse, MemberResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listProjectMembersAction = createAction({+ auth: taskadeAuth,+ name: 'list_project_members',+ displayName: 'List Project Members',+ description: 'Lists the people who can be assigned to tasks in a project.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the members of one Taskade project with their handle and display name, one page at a time. Use to get the handle to pass to Assign Task; pass nextPage to continue. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ limit: taskadeAiProps.limit({ max: 100, defaultValue: 100 }),+ page: taskadeAiProps.page(),+ },+ outputSchema: taskadeOutputSchemas['listProjectMembers'],+ async run(context) {+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const limit = taskadeApi.validateInteger({ value: context.propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;+ const page = taskadeApi.validateInteger({ value: context.propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;+ const response = await taskadeApi.request<ListAPIResponse<MemberResponse | null>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}/members`,+ operation: 'list project members',+ query: { limit, page },+ });+ const rawItems = response.items ?? [];+ const items = rawItems+ .filter((item): item is MemberResponse => item !== null)+ .map((item) => ({ handle: item.handle, displayName: item.displayName ?? null }));+ return taskadeNormalize.pageOutput({ items, fetched: rawItems.length, page, limit });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-project-templates.ts b/packages/pieces/community/taskade/src/lib/actions/list-project-templates.tsnew file mode 100644index 00000000000..7f3d53fd769--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-project-templates.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { BaseResponse, ListAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listProjectTemplatesAction = createAction({+ auth: taskadeAuth,+ name: 'list_project_templates',+ displayName: 'List Project Templates',+ description: 'Lists the project templates saved in a workspace or folder.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists the project templates saved in one Taskade workspace or folder, with ID and name, one page at a time. Use to get a template ID for Create Project from Template; pass nextPage to continue. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ folderId: taskadeAiProps.folderId(),+ limit: taskadeAiProps.limit({ max: 100, defaultValue: 20 }),+ page: taskadeAiProps.page(),+ },+ outputSchema: taskadeOutputSchemas['listProjectTemplates'],+ async run(context) {+ const limit = taskadeApi.validateInteger({ value: context.propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 20;+ const page = taskadeApi.validateInteger({ value: context.propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;+ const response = await taskadeApi.request<ListAPIResponse<Partial<BaseResponse> | null>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/folders/${taskadeApi.seg({ value: context.propsValue.folderId, label: 'Folder ID' })}/project-templates`,+ operation: 'list project templates',+ query: { limit, page },+ });+ const rawItems = response.items ?? [];+ const items = rawItems+ .filter((item): item is Partial<BaseResponse> => item !== null && typeof item.id === 'string')+ .map((item) => ({ id: item.id ?? '', name: item.name ?? null }));+ return taskadeNormalize.pageOutput({ items, fetched: rawItems.length, page, limit });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-projects.ts b/packages/pieces/community/taskade/src/lib/actions/list-projects.tsnew file mode 100644index 00000000000..2368f67a220--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-projects.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ListAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listProjectsAction = createAction({+ auth: taskadeAuth,+ name: 'list_projects',+ displayName: 'List Projects',+ description: 'Lists the projects in a workspace or folder, optionally filtered by name.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists all projects in one Taskade workspace or folder (a workspace ID lists its home folder), with ID, name, archived state and link. Optionally keeps only names containing some text (case-insensitive) and can hide archived projects. Use to find a project ID by name. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ folderId: taskadeAiProps.folderId(),+ nameContains: Property.ShortText({+ displayName: 'Name Contains',+ description: 'Only return projects whose name contains this text (case-insensitive).',+ required: false,+ }),+ includeCompleted: Property.Checkbox({+ displayName: 'Include Archived Projects',+ description: 'Include completed (archived) projects.',+ required: false,+ defaultValue: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['listProjects'],+ async run(context) {+ const { folderId, nameContains, includeCompleted } = context.propsValue;+ const response = await taskadeApi.request<ListAPIResponse<ProjectResponse | null>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `/folders/${taskadeApi.seg({ value: folderId, label: 'Folder ID' })}/projects`,+ operation: 'list projects',+ });+ const needle = (nameContains ?? '').trim().toLowerCase();+ const items = (response.items ?? [])+ .filter((item): item is ProjectResponse => item !== null)+ .map((item) => taskadeNormalize.project(item))+ .filter((project) => includeCompleted !== false || !project.completed)+ .filter((project) => needle.length === 0 || (project.name ?? '').toLowerCase().includes(needle));+ return { items };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-recent-projects.ts b/packages/pieces/community/taskade/src/lib/actions/list-recent-projects.tsnew file mode 100644index 00000000000..49bc7acadea--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-recent-projects.ts@@ -0,0 +1,54 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ListAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listRecentProjectsAction = createAction({+ auth: taskadeAuth,+ name: 'list_recent_projects',+ displayName: 'List My Recent Projects',+ description: 'Lists projects you have access to across all workspaces, most recently viewed first.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists Taskade projects the connected user can access across all workspaces, ordered by when they were last viewed, one page at a time. Use when you do not know which workspace or folder a project is in; pass nextPage to continue. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ sort: Property.StaticDropdown({+ displayName: 'Order',+ required: false,+ defaultValue: 'viewed-desc',+ options: {+ disabled: false,+ options: [+ { label: 'Most recently viewed first', value: 'viewed-desc' },+ { label: 'Least recently viewed first', value: 'viewed-asc' },+ ],+ },+ }),+ limit: taskadeAiProps.limit({ max: 100, defaultValue: 100 }),+ page: taskadeAiProps.page(),+ },+ outputSchema: taskadeOutputSchemas['listRecentProjects'],+ async run(context) {+ const limit = taskadeApi.validateInteger({ value: context.propsValue.limit, label: 'Limit', min: 1, max: 100 }) ?? 100;+ const page = taskadeApi.validateInteger({ value: context.propsValue.page, label: 'Page', min: 1, max: 100_000 }) ?? 1;+ const sort = context.propsValue.sort === 'viewed-asc' ? 'viewed-asc' : 'viewed-desc';+ const response = await taskadeApi.request<ListAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: '/me/projects',+ operation: 'list my projects',+ query: { limit, page, sort },+ });+ const rawItems = response.items ?? [];+ const items = rawItems.map((item) => taskadeNormalize.project(item));+ return taskadeNormalize.pageOutput({ items, fetched: rawItems.length, page, limit });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-tasks.ts b/packages/pieces/community/taskade/src/lib/actions/list-tasks.tsnew file mode 100644index 00000000000..86b26473e93--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-tasks.ts@@ -0,0 +1,47 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { TaskPageResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listTasksAction = createAction({+ auth: taskadeAuth,+ name: 'list_tasks',+ displayName: 'List Tasks',+ description: 'Lists the tasks of a project in outline order, one page at a time.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists tasks of one Taskade project in outline order, one page at a time, with ID, text, parent task ID and completion. Use to get task IDs before updating, completing, moving or deleting; pass nextCursor as Cursor to continue. The first item of the first page is the project root (isRoot=true), not a real task. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ limit: taskadeAiProps.limit({ max: 1000, defaultValue: 100 }),+ cursor: Property.ShortText({+ displayName: 'Cursor',+ description: 'Pass nextCursor from the previous result to get the next page. Leave empty to start at the top.',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['listTasks'],+ async run(context) {+ const { projectId, cursor } = context.propsValue;+ const limit = taskadeApi.validateInteger({ value: context.propsValue.limit, label: 'Limit', min: 1, max: 1000 }) ?? 100;+ const after = (cursor ?? '').trim();+ const response = await taskadeApi.request<TaskPageResponse>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: `${taskadeApi.projectPath(projectId)}/tasks`,+ operation: 'list tasks',+ query: { limit, after: after.length > 0 ? after : undefined },+ });+ const items = (response.items ?? []).map((item) => taskadeNormalize.task(item));+ const hasMore = response.hasMore ?? items.length === limit;+ return { items, nextCursor: hasMore ? response.nextCursor ?? items[items.length - 1]?.id ?? null : null, hasMore };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/list-workspaces.ts b/packages/pieces/community/taskade/src/lib/actions/list-workspaces.tsnew file mode 100644index 00000000000..69b7dbd9678--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/list-workspaces.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeApi } from '../common/client';+import { ListAPIResponse, WorkspaceResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const listWorkspacesAction = createAction({+ auth: taskadeAuth,+ name: 'list_workspaces',+ displayName: 'List Workspaces',+ description: 'Lists the Taskade workspaces you belong to.',+ classification: 'SEARCH',+ audience: 'both',+ aiMetadata: {+ description:+ 'Lists every Taskade workspace the connected user belongs to, with ID and name. Use first to get a workspace ID for List Folders, List Projects, Create Project or List AI Agents (a workspace ID also works as its home folder ID). Read-only and idempotent.',+ idempotent: true,+ },+ props: {},+ outputSchema: taskadeOutputSchemas['listWorkspaces'],+ async run(context) {+ const response = await taskadeApi.request<ListAPIResponse<WorkspaceResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path: '/workspaces',+ operation: 'list workspaces',+ });+ return { items: (response.items ?? []).filter((item) => item !== null).map((item) => ({ id: item.id, name: item.name })) };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/move-task.ts b/packages/pieces/community/taskade/src/lib/actions/move-task.tsnew file mode 100644index 00000000000..149037f0045--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/move-task.ts@@ -0,0 +1,70 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { ItemAPIResponse, TaskResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const moveTaskAction = createAction({+ auth: taskadeAuth,+ name: 'move_task',+ displayName: 'Move Task',+ description: 'Moves a task before or after another task, or inside it as a subtask.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Moves one Taskade task (with its subtasks) within the same project: before or after a target task, or inside it as its first or last subtask. Moving it to where it already is changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId({ displayName: 'Task ID to Move' }),+ targetTaskId: taskadeAiProps.taskId({ displayName: 'Target Task ID', description: 'The task to move next to or into.' }),+ position: Property.StaticDropdown({+ displayName: 'Position',+ required: true,+ defaultValue: 'afterend',+ options: {+ disabled: false,+ options: [+ { label: 'Before the target', value: 'beforebegin' },+ { label: 'After the target', value: 'afterend' },+ { label: 'First subtask of the target', value: 'afterbegin' },+ { label: 'Last subtask of the target', value: 'beforeend' },+ ],+ },+ }),+ },+ outputSchema: taskadeOutputSchemas['task'],+ async run(context) {+ const { projectId, taskId, targetTaskId, position } = context.propsValue;+ const movingId = taskadeApi.requireText({ value: taskId, label: 'Task ID to Move' });+ const targetId = taskadeApi.requireText({ value: targetTaskId, label: 'Target Task ID' });+ if (movingId === targetId) {+ throw new Error('A task cannot be moved relative to itself. Pick a different Target Task ID.');+ }+ const mapped = POSITIONS[String(position)] ?? (Object.values(POSITIONS).includes(String(position)) ? String(position) : undefined);+ if (!mapped) {+ throw new Error('Position must be one of: before, after, first_child, last_child.');+ }+ const token = context.auth.secret_text;+ const response = await taskadeApi.request<ItemAPIResponse<TaskResponse>>({+ token,+ method: HttpMethod.PUT,+ path: `${taskadeApi.taskPath({ projectId, taskId: movingId })}/move`,+ operation: 'move task',+ body: { target: { taskId: targetId, position: mapped } },+ });+ return taskadeTasks.taskOrFallback({ token, projectId, taskId: movingId, item: response.item });+ },+});++const POSITIONS: Record<string, string> = {+ before: 'beforebegin',+ after: 'afterend',+ first_child: 'afterbegin',+ last_child: 'beforeend',+};diff --git a/packages/pieces/community/taskade/src/lib/actions/remove-agent-knowledge-project.ts b/packages/pieces/community/taskade/src/lib/actions/remove-agent-knowledge-project.tsnew file mode 100644index 00000000000..bae36f6bc64--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/remove-agent-knowledge-project.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeOutputSchemas } from '../output-schemas';++export const removeAgentKnowledgeProjectAction = createAction({+ auth: taskadeAuth,+ name: 'remove_agent_knowledge_project',+ displayName: 'Remove Project from Agent Knowledge',+ description: 'Stops an AI agent from using a project as knowledge.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes a Taskade project from an AI agent\'s knowledge; the project itself is not changed. Removing a project that is not linked also succeeds, so it is idempotent.',+ idempotent: true,+ },+ props: {+ agentId: taskadeAiProps.agentId(),+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['agentKnowledge'],+ async run(context) {+ const token = context.auth.secret_text;+ const agentId = taskadeApi.requireText({ value: context.propsValue.agentId, label: 'Agent ID' });+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const agentPath = `/agents/${taskadeApi.seg({ value: agentId, label: 'Agent ID' })}`;+ try {+ await taskadeApi.request({+ token,+ method: HttpMethod.DELETE,+ path: `${agentPath}/knowledge/project/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}`,+ operation: 'remove project from agent knowledge',+ });+ return { agentId, projectId, linked: false };+ } catch (error) {+ if (!taskadeApi.isNotFound(error)) {+ throw error;+ }+ await taskadeApi.request({ token, method: HttpMethod.GET, path: agentPath, operation: 'get agent' });+ return { agentId, projectId, linked: false };+ }+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/reopen-task.ts b/packages/pieces/community/taskade/src/lib/actions/reopen-task.tsnew file mode 100644index 00000000000..aefac8c10c6--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/reopen-task.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeTasks } from '../common/tasks';+import { taskadeOutputSchemas } from '../output-schemas';++export const reopenTaskAction = createAction({+ auth: taskadeAuth,+ name: 'reopen_task',+ displayName: 'Reopen Task',+ description: 'Marks a completed task as not completed.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Marks a completed Taskade task as open again, by project and task ID. Use to undo Complete Task. Reopening an open task changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ },+ outputSchema: taskadeOutputSchemas['task'],+ async run(context) {+ const { projectId, taskId } = context.propsValue;+ const token = context.auth.secret_text;+ const { task } = await taskadeTasks.setCompletion({ token, projectId, taskId, completed: false });+ return task;+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/restore-project.ts b/packages/pieces/community/taskade/src/lib/actions/restore-project.tsnew file mode 100644index 00000000000..8009d85811a--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/restore-project.ts@@ -0,0 +1,44 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { ItemAPIResponse, ProjectResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const restoreProjectAction = createAction({+ auth: taskadeAuth,+ name: 'restore_project',+ displayName: 'Restore Project',+ description: 'Restores a completed (archived) project.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Restores a completed (archived) Taskade project so it is active again; the opposite of Complete (Archive) Project. Repeating it leaves the project active, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ },+ outputSchema: taskadeOutputSchemas['project'],+ async run(context) {+ const projectId = taskadeApi.parseProjectId(context.propsValue.projectId);+ const path = `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}`;+ await taskadeApi.request({+ token: context.auth.secret_text,+ method: HttpMethod.POST,+ path: `${path}/restore`,+ operation: 'restore project',+ body: {},+ });+ const current = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token: context.auth.secret_text,+ method: HttpMethod.GET,+ path,+ operation: 'get project',+ });+ return { ...taskadeNormalize.project(current.item), completed: false };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/set-task-date.ts b/packages/pieces/community/taskade/src/lib/actions/set-task-date.tsnew file mode 100644index 00000000000..4adeb48b27c--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/set-task-date.ts@@ -0,0 +1,136 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { TaskadeDate } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const setTaskDateAction = createAction({+ auth: taskadeAuth,+ name: 'set_task_date',+ displayName: 'Set Task Date',+ description: 'Sets or clears the start and end date of a task.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sets a Taskade task\'s start date and optional end date (YYYY-MM-DD, optional HH:MM time, optional IANA timezone such as Europe/Berlin), or removes the date when Clear Date is on. Use for due dates and schedules. Setting the same date again changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ startDate: Property.ShortText({+ displayName: 'Start Date',+ description: 'YYYY-MM-DD. Required unless Clear Date is on. For a single due date, set only this.',+ required: false,+ }),+ startTime: Property.ShortText({+ displayName: 'Start Time',+ description: 'Optional, 24-hour HH:MM or HH:MM:SS.',+ required: false,+ }),+ endDate: Property.ShortText({+ displayName: 'End Date',+ description: 'Optional, YYYY-MM-DD, for a date range.',+ required: false,+ }),+ endTime: Property.ShortText({+ displayName: 'End Time',+ description: 'Optional, 24-hour HH:MM or HH:MM:SS. Needs End Date.',+ required: false,+ }),+ timezone: Property.ShortText({+ displayName: 'Timezone',+ description: 'Optional IANA timezone for the times, for example America/New_York.',+ required: false,+ }),+ clearDate: Property.Checkbox({+ displayName: 'Clear Date',+ description: 'Remove the date from the task. The date fields above are ignored.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['taskDate'],+ async run(context) {+ const { projectId, taskId, startDate, startTime, endDate, endTime, timezone, clearDate } = context.propsValue;+ const token = context.auth.secret_text;+ const parsedProjectId = taskadeApi.parseProjectId(projectId);+ const parsedTaskId = taskadeApi.requireText({ value: taskId, label: 'Task ID' });+ const path = `${taskadeApi.taskPath({ projectId: parsedProjectId, taskId: parsedTaskId })}/date`;+ if (clearDate === true) {+ await taskadeTasks.ignoreMissingSubResource({+ token,+ projectId: parsedProjectId,+ taskId: parsedTaskId,+ call: () => taskadeApi.request({ token, method: HttpMethod.DELETE, path, operation: 'clear task date' }),+ whenMissing: undefined,+ });+ return { projectId: parsedProjectId, taskId: parsedTaskId, cleared: true, date: null };+ }+ const zone = optionalText(timezone);+ const start = buildDate({ date: startDate, time: startTime, timezone: zone, label: 'Start' });+ if (!start) {+ throw new Error('Start Date is required (YYYY-MM-DD), or turn on Clear Date to remove the date.');+ }+ const end = buildDate({ date: endDate, time: endTime, timezone: zone, label: 'End' });+ if (end && end.date < start.date) {+ throw new Error('End Date must be on or after Start Date.');+ }+ if (end && end.date === start.date && start.time && end.time && toSeconds(end.time) < toSeconds(start.time)) {+ throw new Error(`End Time ${end.time} is before Start Time ${start.time} on ${start.date}. Use a later End Time or a later End Date.`);+ }+ const date = end ? { start, end } : { start };+ await taskadeApi.request({ token, method: HttpMethod.PUT, path, operation: 'set task date', body: date });+ return { projectId: parsedProjectId, taskId: parsedTaskId, cleared: false, date };+ },+});++function optionalText(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ const text = String(value).trim();+ return text.length > 0 ? text : undefined;+}++function buildDate({ date, time, timezone, label }: { date: unknown; time: unknown; timezone: string | undefined; label: string }): TaskadeDate | undefined {+ const dateText = optionalText(date);+ const timeText = optionalText(time);+ if (!dateText) {+ if (timeText) {+ throw new Error(`${label} Time needs ${label} Date.`);+ }+ return undefined;+ }+ if (!isRealDate(dateText)) {+ throw new Error(`${label} Date "${dateText}" must be a real date in YYYY-MM-DD format.`);+ }+ if (timeText && !TIME_PATTERN.test(timeText)) {+ throw new Error(`${label} Time "${timeText}" must be 24-hour HH:MM or HH:MM:SS.`);+ }+ return {+ date: dateText,+ ...(timeText ? { time: timeText } : {}),+ ...(timezone ? { timezone } : {}),+ };+}++function isRealDate(text: string): boolean {+ if (!DATE_PATTERN.test(text)) {+ return false;+ }+ const parsed = new Date(`${text}T00:00:00Z`);+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === text;+}++function toSeconds(time: string): number {+ const [hours, minutes, seconds] = time.split(':').map(Number);+ return hours * 3600 + minutes * 60 + (seconds ?? 0);+}++const DATE_PATTERN = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;+const TIME_PATTERN = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/;diff --git a/packages/pieces/community/taskade/src/lib/actions/set-task-field-value.ts b/packages/pieces/community/taskade/src/lib/actions/set-task-field-value.tsnew file mode 100644index 00000000000..d7d0c73e3b3--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/set-task-field-value.ts@@ -0,0 +1,102 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeNormalize } from '../common/normalize';+import { taskadeTasks } from '../common/tasks';+import { FieldResponse, ListAPIResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const setTaskFieldValueAction = createAction({+ auth: taskadeAuth,+ name: 'set_task_field_value',+ displayName: 'Set Custom Field Value',+ description: 'Sets or clears the value of a custom field on a task.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Sets the value of one custom field on a Taskade task, or clears it when Clear Value is on. Get the field ID and, for Select fields, the option ID from List Custom Fields; number fields need a number. Setting the same value again changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ fieldId: Property.ShortText({+ displayName: 'Field ID',+ description: 'Get it from List Custom Fields.',+ required: true,+ }),+ value: Property.ShortText({+ displayName: 'Value',+ description: 'Text, a number for number fields, or the option ID for Select fields. Required unless Clear Value is on.',+ required: false,+ }),+ clearValue: Property.Checkbox({+ displayName: 'Clear Value',+ description: 'Remove the value from the task. Value is ignored.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['taskFieldValue'],+ async run(context) {+ const { projectId, taskId, value, clearValue } = context.propsValue;+ const token = context.auth.secret_text;+ const parsedProjectId = taskadeApi.parseProjectId(projectId);+ const parsedTaskId = taskadeApi.requireText({ value: taskId, label: 'Task ID' });+ const fieldId = taskadeApi.requireText({ value: context.propsValue.fieldId, label: 'Field ID' });+ const path = `${taskadeApi.taskPath({ projectId: parsedProjectId, taskId: parsedTaskId })}/fields/${taskadeApi.seg({ value: fieldId, label: 'Field ID' })}`;+ const fields = await taskadeApi.request<ListAPIResponse<FieldResponse>>({+ token,+ method: HttpMethod.GET,+ path: `${taskadeApi.projectPath(parsedProjectId)}/fields`,+ operation: 'list custom fields',+ });+ const field = (fields.items ?? []).map((item) => taskadeNormalize.field(item)).find((item) => item.id === fieldId);+ if (!field) {+ const known = (fields.items ?? []).map((item) => taskadeNormalize.field(item)).map((item) => `${item.displayName ?? item.type ?? 'field'} (${item.id})`);+ throw new Error(`This project has no custom field with ID "${fieldId}". ${known.length > 0 ? `Fields: ${known.join(', ').slice(0, 500)}` : 'It has no custom fields.'}`);+ }+ if (clearValue === true) {+ await taskadeTasks.ignoreMissingSubResource({+ token,+ projectId: parsedProjectId,+ taskId: parsedTaskId,+ call: () => taskadeApi.request({ token, method: HttpMethod.DELETE, path, operation: 'clear field value' }),+ whenMissing: undefined,+ });+ return { projectId: parsedProjectId, taskId: parsedTaskId, fieldId, value: null, cleared: true };+ }+ const text = value === undefined || value === null ? '' : String(value).trim();+ if (text.length === 0) {+ throw new Error('Value is required, or turn on Clear Value to remove it.');+ }+ const sent = toFieldValue({ text, type: field.type, options: field.options });+ await taskadeApi.request({ token, method: HttpMethod.PUT, path, operation: 'set field value', body: { value: sent } });+ return { projectId: parsedProjectId, taskId: parsedTaskId, fieldId, value: sent, cleared: false };+ },+});++function toFieldValue({ text, type, options }: { text: string; type: string | null; options: Array<{ id: string; name: string }> }): string | number {+ if (type === 'number' || type === 'Rating') {+ const number = Number(text);+ if (!Number.isFinite(number)) {+ throw new Error(`This is a ${type} field, so Value must be a number; got "${text.slice(0, 100)}".`);+ }+ return number;+ }+ if (type === 'Select' && options.length > 0) {+ const byId = options.find((option) => option.id === text);+ if (byId) {+ return byId.id;+ }+ const byName = options.find((option) => option.name.toLowerCase() === text.toLowerCase());+ if (byName) {+ return byName.id;+ }+ throw new Error(`"${text.slice(0, 100)}" is not an option of this Select field. Options: ${options.map((option) => `${option.name} (${option.id})`).join(', ').slice(0, 500)}`);+ }+ return text;+}diff --git a/packages/pieces/community/taskade/src/lib/actions/set-task-note.ts b/packages/pieces/community/taskade/src/lib/actions/set-task-note.tsnew file mode 100644index 00000000000..eb93bab6577--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/set-task-note.ts@@ -0,0 +1,62 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { taskadeOutputSchemas } from '../output-schemas';++export const setTaskNoteAction = createAction({+ auth: taskadeAuth,+ name: 'set_task_note',+ displayName: 'Set Task Note',+ description: 'Sets or clears the note attached to a task.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Replaces the note attached to a Taskade task (single line, Markdown or plain text), or removes it when Clear Note is on. Use for details that do not fit in the task text. Setting the same note again changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ note: Property.LongText({+ displayName: 'Note',+ description: 'Required unless Clear Note is on. Taskade accepts a single line.',+ required: false,+ }),+ format: taskadeAiProps.format(),+ clearNote: Property.Checkbox({+ displayName: 'Clear Note',+ description: 'Remove the note from the task. Note is ignored.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['taskNote'],+ async run(context) {+ const { projectId, taskId, note, format, clearNote } = context.propsValue;+ const token = context.auth.secret_text;+ const parsedProjectId = taskadeApi.parseProjectId(projectId);+ const parsedTaskId = taskadeApi.requireText({ value: taskId, label: 'Task ID' });+ const path = `${taskadeApi.taskPath({ projectId: parsedProjectId, taskId: parsedTaskId })}/note`;+ if (clearNote === true) {+ await taskadeTasks.ignoreMissingSubResource({+ token,+ projectId: parsedProjectId,+ taskId: parsedTaskId,+ call: () => taskadeApi.request({ token, method: HttpMethod.DELETE, path, operation: 'clear task note' }),+ whenMissing: undefined,+ });+ return { projectId: parsedProjectId, taskId: parsedTaskId, cleared: true, note: null };+ }+ const value = taskadeApi.requireText({ value: note, label: 'Note' });+ if (/[\r\n]/.test(value)) {+ throw new Error('Taskade task notes must be a single line. Remove the line breaks (for example join lines with " / ").');+ }+ const body = { type: taskadeTasks.contentType(format), value };+ await taskadeApi.request({ token, method: HttpMethod.PUT, path, operation: 'set task note', body });+ return { projectId: parsedProjectId, taskId: parsedTaskId, cleared: false, note: body };+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/trigger-automation.ts b/packages/pieces/community/taskade/src/lib/actions/trigger-automation.tsnew file mode 100644index 00000000000..b47ff9307fe--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/trigger-automation.ts@@ -0,0 +1,114 @@+import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeApi } from '../common/client';+import { taskadeOutputSchemas } from '../output-schemas';++export const triggerAutomationAction = createAction({+ auth: taskadeAuth,+ name: 'trigger_automation',+ displayName: 'Trigger Taskade Automation',+ description: 'Starts a Taskade automation that begins with a Webhook trigger, sending a JSON payload.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Starts a Taskade automation whose trigger is a Webhook, by POSTing a JSON object to the automation\'s https://www.taskade.com/webhooks/... URL; the payload fields become automation variables. Use when the user gives that URL. Not idempotent: each call runs the automation again.',+ idempotent: false,+ },+ props: {+ webhookUrl: Property.ShortText({+ displayName: 'Automation Webhook URL',+ description: 'In the Taskade automation, add a Webhook trigger and copy its URL (https://www.taskade.com/webhooks/...).',+ required: true,+ }),+ payload: Property.Json({+ displayName: 'Payload',+ description: 'JSON object to send. Each field becomes a variable in the automation.',+ required: false,+ defaultValue: {},+ }),+ bearerToken: Property.ShortText({+ displayName: 'Webhook Bearer Token',+ description: 'Only if the webhook trigger has Bearer Token authentication turned on. This is the webhook\'s own secret, not your personal access token.',+ required: false,+ }),+ },+ outputSchema: taskadeOutputSchemas['triggerAutomation'],+ async run(context) {+ const url = parseAutomationUrl(context.propsValue.webhookUrl);+ const payload = parsePayload(context.propsValue.payload);+ const bearer = (context.propsValue.bearerToken ?? '').trim();+ try {+ const response = await httpClient.sendRequest({+ method: HttpMethod.POST,+ url,+ headers: {+ 'Content-Type': 'application/json',+ ...(bearer.length > 0 ? { Authorization: `Bearer ${bearer}` } : {}),+ },+ body: payload,+ timeout: 30_000,+ followRedirects: false,+ });+ if (response.status >= 300) {+ throw new Error(`Taskade automation webhook answered with HTTP ${response.status} (redirects are not followed). Check the webhook URL.`);+ }+ return { status: response.status, ok: true };+ } catch (error) {+ const status = taskadeApi.statusOf(error);+ if (status === undefined) {+ throw error;+ }+ if (status === 401 || status === 403) {+ throw new Error(`Taskade rejected the call (HTTP ${status}). The webhook needs a valid Webhook Bearer Token.`);+ }+ if (status === 404 || status === 410) {+ throw new Error(`Taskade does not know this webhook URL (HTTP ${status}). The automation or its trigger may have been deleted; copy the current URL.`);+ }+ if (status === 402) {+ throw new Error('Taskade webhook automations need a Pro plan or above (HTTP 402).');+ }+ throw new Error(`Taskade automation webhook failed with HTTP ${status}.`);+ }+ },+});++function parseAutomationUrl(value: unknown): string {+ const text = taskadeApi.requireText({ value, label: 'Automation Webhook URL' });+ const url = taskadeApi.safeUrl(text);+ if (+ !url ||+ url.protocol !== 'https:' ||+ url.username !== '' ||+ url.password !== '' ||+ url.port !== '' ||+ !ALLOWED_HOSTS.includes(url.hostname.toLowerCase()) ||+ !url.pathname.startsWith('/webhooks/') ||+ url.pathname.split('/').some((part) => part === '..' || part === '.')+ ) {+ throw new Error('Automation Webhook URL must be a Taskade webhook URL starting with https://www.taskade.com/webhooks/.');+ }+ return url.toString();+}++function parsePayload(value: unknown): Record<string, unknown> {+ if (value === undefined || value === null || value === '') {+ return {};+ }+ const parsed: unknown = typeof value === 'string' ? safeJson(value) : value;+ if (!taskadeApi.isRecord(parsed)) {+ throw new Error('Payload must be a JSON object, for example {"customer": "Jane"}.');+ }+ return parsed;+}++function safeJson(text: string): unknown {+ try {+ return JSON.parse(text);+ } catch {+ throw new Error('Payload must be valid JSON.');+ }+}++const ALLOWED_HOSTS = ['www.taskade.com', 'taskade.com'];diff --git a/packages/pieces/community/taskade/src/lib/actions/unassign-task.ts b/packages/pieces/community/taskade/src/lib/actions/unassign-task.tsnew file mode 100644index 00000000000..81a3a471ad2--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/unassign-task.ts@@ -0,0 +1,63 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { ItemAPIResponse, ListAPIResponse, MemberResponse, TaskResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const unassignTaskAction = createAction({+ auth: taskadeAuth,+ name: 'unassign_task',+ displayName: 'Unassign Task',+ description: 'Removes one member from a task\'s assignees.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Removes one member (by handle) from the assignees of a Taskade task. If that person was not assigned, nothing changes and wasAssigned is false, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ handle: Property.ShortText({+ displayName: 'Member Handle',+ description: 'Handle without @, from List Project Members or Get Task.',+ required: true,+ }),+ },+ outputSchema: taskadeOutputSchemas['unassignTask'],+ async run(context) {+ const { projectId, taskId } = context.propsValue;+ const handle = taskadeApi.requireText({ value: context.propsValue.handle, label: 'Member Handle' }).replace(/^@/, '');+ const token = context.auth.secret_text;+ try {+ const response = await taskadeApi.request<ItemAPIResponse<TaskResponse>>({+ token,+ method: HttpMethod.DELETE,+ path: `${taskadeApi.taskPath({ projectId, taskId })}/assignees/${taskadeApi.seg({ value: handle, label: 'Member Handle' })}`,+ operation: 'unassign task',+ });+ const task = await taskadeTasks.taskOrFallback({ token, projectId, taskId, item: response.item });+ return { ...task, removedHandle: handle, wasAssigned: true };+ } catch (error) {+ const status = taskadeApi.statusOf(error);+ if (status !== 400 && status !== 404) {+ throw error;+ }+ const task = await taskadeTasks.getTask({ token, projectId, taskId });+ const assignees = await taskadeApi.request<ListAPIResponse<MemberResponse>>({+ token,+ method: HttpMethod.GET,+ path: `${taskadeApi.taskPath({ projectId, taskId })}/assignees`,+ operation: 'get task assignees',+ });+ if ((assignees.items ?? []).some((member) => member.handle.toLowerCase() === handle.toLowerCase())) {+ throw error;+ }+ return { ...task, removedHandle: handle, wasAssigned: false };+ }+ },+});diff --git a/packages/pieces/community/taskade/src/lib/actions/update-task.ts b/packages/pieces/community/taskade/src/lib/actions/update-task.tsnew file mode 100644index 00000000000..a340f7156ce--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/actions/update-task.ts@@ -0,0 +1,46 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, createAction } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeAiProps } from '../common/ai-props';+import { taskadeApi } from '../common/client';+import { taskadeTasks } from '../common/tasks';+import { ItemAPIResponse, TaskResponse } from '../common/types';+import { taskadeOutputSchemas } from '../output-schemas';++export const updateTaskAction = createAction({+ auth: taskadeAuth,+ name: 'update_task',+ displayName: 'Update Task Text',+ description: 'Replaces the text of a task.',+ classification: 'WRITE',+ audience: 'both',+ aiMetadata: {+ description:+ 'Replaces the text of one Taskade task (a single line, up to 2,000 characters, Markdown or plain text). Use to rename or rewrite a task; use Set Task Note for longer details. Setting the same text again changes nothing, so it is idempotent.',+ idempotent: true,+ },+ props: {+ projectId: taskadeAiProps.projectId(),+ taskId: taskadeAiProps.taskId(),+ text: Property.ShortText({+ displayName: 'New Text',+ description: 'Single line, up to 2,000 characters.',+ required: true,+ }),+ format: taskadeAiProps.format(),+ },+ outputSchema: taskadeOutputSchemas['task'],+ async run(context) {+ const { projectId, taskId, text, format } = context.propsValue;+ const content = taskadeTasks.validateTaskText({ value: text, label: 'New Text', singleLine: true });+ const token = context.auth.secret_text;+ const response = await taskadeApi.request<ItemAPIResponse<TaskResponse>>({+ token,+ method: HttpMethod.PUT,+ path: taskadeApi.taskPath({ projectId, taskId }),+ operation: 'update task',+ body: { contentType: taskadeTasks.contentType(format), content },+ });+ return taskadeTasks.taskOrFallback({ token, projectId, taskId, item: response.item });+ },+});diff --git a/packages/pieces/community/taskade/src/lib/auth.ts b/packages/pieces/community/taskade/src/lib/auth.tsindex c161679c61a..222af671930 100644--- a/packages/pieces/community/taskade/src/lib/auth.ts+++ b/packages/pieces/community/taskade/src/lib/auth.ts@@ -1,9 +1,30 @@+import { HttpMethod } from '@activepieces/pieces-common';import { PieceAuth } from '@activepieces/pieces-framework';+import { taskadeApi } from './common/client';export const taskadeAuth = PieceAuth.SecretText({displayName: 'Personal Token',required: true,description: `- 1. Navigate to https://taskade.com/settings/password and scroll down to Personal Access Tokens.- 2. Create your personal access token with any name.`,+ 1. Go to https://www.taskade.com/settings/api (Settings > API).+ 2. Under Personal Access Tokens, create a token with any name and copy it (it starts with tskdp_).`,+ validate: async ({ auth }) => {+ try {+ await taskadeApi.request({+ token: auth,+ method: HttpMethod.GET,+ path: '/workspaces',+ operation: 'check token',+ timeoutMs: 15_000,+ });+ return { valid: true };+ } catch (error) {+ const status = taskadeApi.statusOf(error);+ if (status === 401 || status === 403) {+ return { valid: false, error: 'Invalid personal access token. Create a new one at https://www.taskade.com/settings/api.' };+ }+ const message = error instanceof Error ? error.message : String(error);+ return { valid: false, error: `Could not check the token with Taskade: ${message.slice(0, 300)}` };+ }+ },});diff --git a/packages/pieces/community/taskade/src/lib/common/ai-props.ts b/packages/pieces/community/taskade/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..a95e69de0b4--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/common/ai-props.ts@@ -0,0 +1,72 @@+import { Property } from '@activepieces/pieces-framework';++function projectId({ displayName = 'Project ID', description }: { displayName?: string; description?: string } = {}) {+ return Property.ShortText({+ displayName,+ description:+ description ??+ 'The project ID, or the project link (https://www.taskade.com/d/<project id>). Get it from List Projects or List My Recent Projects.',+ required: true,+ });+}++function taskId({ displayName = 'Task ID', description, required = true }: { displayName?: string; description?: string; required?: boolean } = {}) {+ return Property.ShortText({+ displayName,+ description: description ?? 'The task ID. Get it from List Tasks or Find Tasks.',+ required,+ });+}++function folderId({ description }: { description?: string } = {}) {+ return Property.ShortText({+ displayName: 'Workspace or Folder ID',+ description:+ description ??+ 'A workspace ID or folder ID. A workspace ID works for its home folder. Get IDs from List Workspaces and List Folders.',+ required: true,+ });+}++function agentId() {+ return Property.ShortText({+ displayName: 'Agent ID',+ description: 'The AI agent ID. Get it from List AI Agents.',+ required: true,+ });+}++function limit({ max, defaultValue }: { max: number; defaultValue: number }) {+ return Property.Number({+ displayName: 'Limit',+ description: `How many items to return (1-${max}, default ${defaultValue}).`,+ required: false,+ defaultValue,+ });+}++function page() {+ return Property.Number({+ displayName: 'Page',+ description: 'Page number, starting at 1. Pass nextPage from the previous result to get more.',+ required: false,+ defaultValue: 1,+ });+}++function format() {+ return Property.StaticDropdown({+ displayName: 'Text Format',+ required: false,+ defaultValue: 'text/markdown',+ options: {+ disabled: false,+ options: [+ { label: 'Markdown', value: 'text/markdown' },+ { label: 'Plain text', value: 'text/plain' },+ ],+ },+ });+}++export const taskadeAiProps = { projectId, taskId, folderId, agentId, limit, page, format };diff --git a/packages/pieces/community/taskade/src/lib/common/client.ts b/packages/pieces/community/taskade/src/lib/common/client.tsindex 9cdeff7b62f..ec85e659151 100644--- a/packages/pieces/community/taskade/src/lib/common/client.ts+++ b/packages/pieces/community/taskade/src/lib/common/client.ts@@ -1,105 +1,274 @@-import {- HttpMessageBody,- HttpMethod,- QueryParams,- httpClient,- HttpRequest,- AuthenticationType,-} from '@activepieces/pieces-common';-import {- CreateTaskDateParams,- CreateTaskParams,- ListAPIResponse,- ProjectResponse,- CreateTaskResponse,- WorkspaceFolderResponse,- WorkspaceResponse,- TaskResponse,-} from './types';--type RequestParams = Record<string, string | number | string[] | undefined>;--export class TaskadeAPIClient {- constructor(private personalToken: string) {}-- async makeRequest<T extends HttpMessageBody>(- method: HttpMethod,- resourceUri: string,- query?: RequestParams,- body: any | undefined = undefined,- ): Promise<T> {- const baseUrl = 'https://www.taskade.com/api/v1';- const qs: QueryParams = {};-- if (query) {- for (const [key, value] of Object.entries(query)) {- if (value !== null && value !== undefined) {- qs[key] = String(value);- }- }+import { AuthenticationType, HttpMethod, HttpRequest, httpClient } from '@activepieces/pieces-common';++const TASKADE_ORIGIN = 'https://www.taskade.com';+const TASKADE_API = `${TASKADE_ORIGIN}/api`;+const REQUEST_TIMEOUT_MS = 30_000;+const RATE_LIMIT_RETRY_DELAYS_MS = [10_000, 20_000];+const MAX_ERROR_TEXT = 500;+const ID_PATTERN = /^[A-Za-z0-9_-]+$/;+const PROJECT_LINK_HOSTS = ['taskade.com', 'www.taskade.com'];++export class TaskadeApiError extends Error {+ readonly status: number;+ readonly code: string | undefined;+ readonly responseBody: unknown;++ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {+ const code = isRecord(responseBody) && typeof responseBody['code'] === 'string' ? responseBody['code'] : undefined;+ super(`Taskade ${operation} failed (${status}${code ? ` ${code}` : ''}): ${describeStatus({ status, responseBody })}`);+ this.name = 'TaskadeApiError';+ this.status = status;+ this.code = code;+ this.responseBody = responseBody;+ }+}++function vendorMessage(responseBody: unknown): string {+ if (typeof responseBody === 'string' && responseBody.length > 0) {+ return responseBody.slice(0, MAX_ERROR_TEXT);+ }+ if (isRecord(responseBody)) {+ const message = responseBody['message'] ?? responseBody['statusMessage'];+ if (typeof message === 'string' && message.length > 0) {+ return message.slice(0, MAX_ERROR_TEXT);}+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);+ }+ return 'no details returned';+}- const request: HttpRequest = {- method,- url: baseUrl + resourceUri,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: this.personalToken,- },- queryParams: qs,- body,- };+function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {+ const detail = vendorMessage(responseBody);+ switch (status) {+ case 401:+ return `the personal access token is invalid or was revoked. ${detail}`;+ case 402: {+ const featureId = isRecord(responseBody) && typeof responseBody['featureId'] === 'string' ? ` (feature: ${responseBody['featureId']})` : '';+ return `this needs more Taskade AI credits or a higher Taskade plan${featureId}. ${detail}`;+ }+ case 403:+ return `Taskade refused the request (no access to this item). ${detail}`;+ case 404:+ return `not found. Check the IDs you passed. ${detail}`;+ case 429:+ return `Taskade rate limit reached (30 requests per minute per token); try again in a minute. ${detail}`;+ default:+ return detail;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}- const response = await httpClient.sendRequest<T>(request);- return response.body;+function statusOf(error: unknown): number | undefined {+ if (error instanceof TaskadeApiError) {+ return error.status;}+ if (!isRecord(error) && !(error instanceof Error)) {+ return undefined;+ }+ const response: unknown = Reflect.get(error, 'response');+ if (isRecord(response) && typeof response['status'] === 'number') {+ return response['status'];+ }+ return undefined;+}- async listWorkspaces(): Promise<ListAPIResponse<WorkspaceResponse>> {- return await this.makeRequest(HttpMethod.GET, '/workspaces');+function responseBodyOf(error: unknown): unknown {+ if (!isRecord(error) && !(error instanceof Error)) {+ return undefined;}+ const response: unknown = Reflect.get(error, 'response');+ return isRecord(response) ? response['body'] : undefined;+}- async listWorkspaceFolders(- workspace_id: string,- ): Promise<ListAPIResponse<WorkspaceFolderResponse>> {- return await this.makeRequest(HttpMethod.GET, `/workspaces/${workspace_id}/folders`);+function isNotFound(error: unknown): boolean {+ return statusOf(error) === 404;+}++function seg({ value, label }: { value: unknown; label: string }): string {+ if (value === undefined || value === null) {+ throw new Error(`${label} is required.`);+ }+ const text = String(value).trim();+ if (text.length === 0) {+ throw new Error(`${label} is required.`);}+ if (text === '.' || text === '..') {+ throw new Error(`${label} "${text}" is not a valid Taskade ID.`);+ }+ return encodeURIComponent(text);+}- async listProjects(folder_id: string): Promise<ListAPIResponse<ProjectResponse>> {- return await this.makeRequest(HttpMethod.GET, `/folders/${folder_id}/projects`);+function requireText({ value, label }: { value: unknown; label: string }): string {+ if (value === undefined || value === null || String(value).trim() === '') {+ throw new Error(`${label} is required.`);}+ return String(value).trim();+}- async createTask(projectId: string, params: CreateTaskParams): Promise<CreateTaskResponse> {- return await this.makeRequest(HttpMethod.POST, `/projects/${projectId}/tasks`, undefined, {- tasks: [params],- });+function parseId({ value, label }: { value: unknown; label: string }): string {+ const text = requireText({ value, label });+ if (!ID_PATTERN.test(text)) {+ throw new Error(`"${text.slice(0, 100)}" is not a valid ${label}. Pass the ID only (letters, digits, - and _).`);}+ return text;+}- async createTaskDate(projectId: string, taskId: string, params: CreateTaskDateParams) {- return await this.makeRequest(- HttpMethod.PUT,- `/projects/${projectId}/tasks/${taskId}/date`,- undefined,- params,- );+function safeUrl(text: string): URL | undefined {+ try {+ return new URL(text);+ } catch {+ return undefined;}+}- async listTasks(- projectId: string,- params: RequestParams,- ): Promise<ListAPIResponse<TaskResponse>> {- return await this.makeRequest(HttpMethod.GET, `/projects/${projectId}/tasks`, params);+function parseProjectId(input: unknown): string {+ const text = requireText({ value: input, label: 'Project ID' });+ if (!/^https?:\/\//i.test(text)) {+ return parseId({ value: text, label: 'Project ID' });+ }+ const url = safeUrl(text);+ if (!url || url.protocol !== 'https:' || url.username || url.password || url.port || !PROJECT_LINK_HOSTS.includes(url.hostname.toLowerCase())) {+ throw new Error(`"${text.slice(0, 200)}" is not a Taskade project link (expected https://www.taskade.com/d/<project id>).`);+ }+ const parts = url.pathname.split('/').filter((part) => part.length > 0);+ const id = parts[0] === 'd' ? parts[1] : undefined;+ if (!id || !ID_PATTERN.test(id)) {+ throw new Error(`Could not find a project ID in "${text.slice(0, 200)}". Paste a link like https://www.taskade.com/d/AbCdEfGh12345678 or the project ID itself.`);}+ return id;+}++function projectPath(projectId: unknown): string {+ return `/projects/${seg({ value: parseProjectId(projectId), label: 'Project ID' })}`;+}++function taskPath({ projectId, taskId }: { projectId: unknown; taskId: unknown }): string {+ return `${projectPath(projectId)}/tasks/${seg({ value: taskId, label: 'Task ID' })}`;+}++function projectUrl(projectId: string): string {+ return `${TASKADE_ORIGIN}/d/${encodeURIComponent(projectId)}`;+}- async completeTask(projectId: string, taskId: string) {- return await this.makeRequest(- HttpMethod.POST,- `/projects/${projectId}/tasks/${taskId}/complete`,- undefined,- {},- );+function validateInteger({ value, label, min, max }: { value: unknown; label: string; min: number; max: number }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;}+ const number = Number(value);+ if (!Number.isInteger(number) || number < min || number > max) {+ throw new Error(`${label} must be a whole number between ${min} and ${max}.`);+ }+ return number;+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function toQueryParams(query: Record<string, TaskadeQueryValue> | undefined): Record<string, string> {+ if (!query) {+ return {};+ }+ return Object.fromEntries(+ Object.entries(query)+ .filter(([, value]) => value !== undefined && value !== null && value !== '')+ .map(([key, value]) => [key, String(value)]),+ );+}- async deleteTask(projectId: string, taskId: string) {- return await this.makeRequest(HttpMethod.DELETE, `/projects/${projectId}/tasks/${taskId}`);+function authHeaders(token: string): Record<string, string> {+ return { Authorization: `Bearer ${token.trim()}` };+}++async function request<T>({+ token,+ method,+ path,+ version = 'v1',+ operation,+ query,+ body,+ timeoutMs = REQUEST_TIMEOUT_MS,+ wait = sleep,+}: TaskadeRequest): Promise<T> {+ if (!path.startsWith('/')) {+ throw new Error(`Internal error: Taskade path must start with "/" (${operation}).`);+ }+ const httpRequest: HttpRequest = {+ method,+ url: `${TASKADE_API}/${version}${path}`,+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: token.trim() },+ queryParams: toQueryParams(query),+ timeout: timeoutMs,+ followRedirects: false,+ };+ if (body !== undefined) {+ httpRequest.body = body;+ httpRequest.headers = { 'Content-Type': 'application/json' };+ }+ for (let attempt = 0; ; attempt++) {+ try {+ const response = await httpClient.sendRequest<T>(httpRequest);+ if (response.status >= 300) {+ throw new TaskadeApiError({ operation, status: response.status, responseBody: response.body });+ }+ const responseBody: unknown = response.body;+ if (isRecord(responseBody) && responseBody['ok'] === false) {+ throw new TaskadeApiError({ operation, status: response.status, responseBody });+ }+ return response.body;+ } catch (error) {+ if (error instanceof TaskadeApiError) {+ throw error;+ }+ const status = statusOf(error);+ if (status === undefined) {+ throw error;+ }+ if (status === 429 && attempt < RATE_LIMIT_RETRY_DELAYS_MS.length) {+ await wait(RATE_LIMIT_RETRY_DELAYS_MS[attempt]);+ continue;+ }+ throw new TaskadeApiError({ operation, status, responseBody: responseBodyOf(error) });+ }}}++export const TASKADE_BASE_URL = `${TASKADE_API}/v1`;++export const taskadeApi = {+ request,+ authHeaders,+ seg,+ parseId,+ parseProjectId,+ requireText,+ projectUrl,+ projectPath,+ taskPath,+ validateInteger,+ isNotFound,+ statusOf,+ isRecord,+ safeUrl,+ sleep,+ TASKADE_ORIGIN,+ RATE_LIMIT_RETRY_DELAYS_MS,+};++export type TaskadeQueryValue = string | number | boolean | undefined | null;++export type TaskadeRequest = {+ token: string;+ method: HttpMethod;+ path: string;+ version?: 'v1' | 'v2';+ operation: string;+ query?: Record<string, TaskadeQueryValue>;+ body?: unknown;+ timeoutMs?: number;+ wait?: (ms: number) => Promise<void>;+};diff --git a/packages/pieces/community/taskade/src/lib/common/normalize.ts b/packages/pieces/community/taskade/src/lib/common/normalize.tsnew file mode 100644index 00000000000..f74291160f8--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/common/normalize.ts@@ -0,0 +1,89 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { taskadeApi } from './client';+import { Agent, AgentResponse, Conversation, ConversationResponse, CustomField, FieldResponse, ItemAPIResponse, Project, ProjectResponse, Task, TaskResponse } from './types';++function project(raw: ProjectResponse | null | undefined): Project {+ if (!raw || typeof raw.id !== 'string') {+ throw new Error('Taskade returned no project in its response.');+ }+ return {+ id: raw.id,+ name: raw.name ?? null,+ icon: raw.icon?.value ?? null,+ completed: raw.completed === true,+ url: taskadeApi.projectUrl(raw.id),+ };+}++function task(raw: TaskResponse | null | undefined): Task {+ if (!raw || typeof raw.id !== 'string') {+ throw new Error('Taskade returned no task in its response.');+ }+ return {+ id: raw.id,+ text: raw.text ?? '',+ parentId: raw.parentId ?? null,+ completed: raw.completed === true,+ isRoot: !raw.parentId,+ };+}++function agent({ raw, includePrompts }: { raw: AgentResponse | null | undefined; includePrompts: boolean }): Agent {+ if (!raw || typeof raw.id !== 'string') {+ throw new Error('Taskade returned no agent in its response.');+ }+ const commands = (raw.data?.commands ?? []).map((command) =>+ includePrompts ? { id: command.id, name: command.name, prompt: command.prompt ?? '' } : { id: command.id, name: command.name },+ );+ return {+ id: raw.id,+ name: raw.name ?? null,+ spaceId: raw.space_id ?? null,+ description: raw.data?.description ?? null,+ knowledgeEnabled: raw.data?.knowledgeEnabled === true,+ commands,+ };+}++function conversation(raw: ConversationResponse): Conversation {+ return {+ id: raw.id,+ agentId: raw.space_agent_id ?? null,+ title: raw.title ?? null,+ status: raw.status ?? null,+ };+}++function pageOutput<T>({ items, fetched, page, limit }: { items: T[]; fetched: number; page: number; limit: number }): { items: T[]; page: number; nextPage: number | null; hasMore: boolean } {+ const hasMore = fetched >= limit;+ return { items, page, nextPage: hasMore ? page + 1 : null, hasMore };+}++function field(raw: FieldResponse): CustomField {+ const data = raw.data ?? {};+ const type = typeof data['type'] === 'string' ? data['type'] : null;+ const name = data['displayName'] ?? data['title'];+ const rawOptions = data['options'];+ const options = taskadeApi.isRecord(rawOptions)+ ? Object.values(rawOptions)+ .filter(taskadeApi.isRecord)+ .map((option) => ({ id: String(option['id'] ?? ''), name: String(option['name'] ?? '') }))+ : [];+ return { id: raw.id, type, displayName: typeof name === 'string' ? name : null, options, data };+}++async function projectWithName({ token, item }: { token: string; item: ProjectResponse | null | undefined }): Promise<Project> {+ const normalized = project(item);+ if (normalized.name !== null) {+ return normalized;+ }+ const response = await taskadeApi.request<ItemAPIResponse<ProjectResponse>>({+ token,+ method: HttpMethod.GET,+ path: taskadeApi.projectPath(normalized.id),+ operation: 'get project',+ });+ return { ...normalized, ...project(response.item) };+}++export const taskadeNormalize = { projectWithName, project, task, agent, conversation, field, pageOutput };diff --git a/packages/pieces/community/taskade/src/lib/common/props.ts b/packages/pieces/community/taskade/src/lib/common/props.tsindex 25ee76c7757..78768907758 100644--- a/packages/pieces/community/taskade/src/lib/common/props.ts+++ b/packages/pieces/community/taskade/src/lib/common/props.ts@@ -1,133 +1,162 @@-import { DropdownOption, Property } from '@activepieces/pieces-framework';-import { TaskadeAPIClient } from './client';+import { DropdownOption, DropdownState, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';import { taskadeAuth } from '../auth';--const createEmptyOptions = (placeholder: string) => {- return {- disabled: true,- options: [],- placeholder,- };-};+import { taskadeApi } from './client';+import { ListAPIResponse, ProjectResponse, TaskPageResponse, WorkspaceFolderResponse, WorkspaceResponse } from './types';export const taskadeProps = {workspace_id: Property.Dropdown({- auth: taskadeAuth,+ auth: taskadeAuth,displayName: 'Workspace',refreshers: [],required: true,options: async ({ auth }) => {if (!auth) {- return createEmptyOptions('Please connect account first.');- }-- const client = new TaskadeAPIClient(auth.secret_text);- const response = await client.listWorkspaces();-- const options: DropdownOption<string>[] = [];-- for (const workspace of response.items) {- options.push({ label: workspace.name, value: workspace.id });+ return emptyOptions('Please connect account first.');}-- return {- disabled: false,- options,- };+ return dropdownOrError(async () => {+ const response = await listWorkspaces(auth.secret_text);+ return response.items.map((workspace) => ({ label: workspace.name, value: workspace.id }));+ });},}),folder_id: Property.Dropdown({- auth: taskadeAuth,+ auth: taskadeAuth,displayName: 'Folder',refreshers: ['workspace_id'],required: false,options: async ({ auth, workspace_id }) => {if (!auth) {- return createEmptyOptions('Please connect account first.');+ return emptyOptions('Please connect account first.');}if (!workspace_id) {- return createEmptyOptions('Please select workspace.');- }-- const client = new TaskadeAPIClient(auth.secret_text);- const response = await client.listWorkspaceFolders(workspace_id as string);-- const options: DropdownOption<string>[] = [];-- for (const folder of response.items) {- options.push({ label: folder.name, value: folder.id });+ return emptyOptions('Please select workspace.');}-- return {- disabled: false,- options,- };+ return dropdownOrError(async () => {+ const response = await taskadeApi.request<ListAPIResponse<WorkspaceFolderResponse>>({+ token: auth.secret_text,+ method: HttpMethod.GET,+ path: `/workspaces/${taskadeApi.seg({ value: workspace_id, label: 'Workspace ID' })}/folders`,+ operation: 'list folders',+ });+ return response.items.map((folder) => ({ label: folder.name, value: folder.id }));+ });},}),project_id: Property.Dropdown({- auth: taskadeAuth,+ auth: taskadeAuth,displayName: 'Project',refreshers: ['workspace_id', 'folder_id'],required: true,options: async ({ auth, workspace_id, folder_id }) => {if (!auth) {- return createEmptyOptions('Please connect account first.');+ return emptyOptions('Please connect account first.');}if (!workspace_id) {- return createEmptyOptions('Please select workspace.');- }-- const workspaceId = workspace_id as string;- const folderId = (folder_id as string) ?? workspaceId;-- const client = new TaskadeAPIClient(auth.secret_text);- const response = await client.listProjects(folderId as string);-- const options: DropdownOption<string>[] = [];-- for (const project of response.items) {- options.push({ label: project.name, value: project.id });+ return emptyOptions('Please select workspace.');}-- return {- disabled: false,- options,- };+ const folderId = typeof folder_id === 'string' && folder_id.length > 0 ? folder_id : workspace_id;+ return dropdownOrError(async () => {+ const response = await taskadeApi.request<ListAPIResponse<ProjectResponse>>({+ token: auth.secret_text,+ method: HttpMethod.GET,+ path: `/folders/${taskadeApi.seg({ value: folderId, label: 'Folder ID' })}/projects`,+ operation: 'list projects',+ });+ return response.items.map((project) => ({ label: project.name ?? project.id, value: project.id }));+ });},}),task_id: Property.Dropdown({- auth: taskadeAuth,+ auth: taskadeAuth,displayName: 'Task',refreshers: ['project_id'],required: true,options: async ({ auth, project_id }) => {if (!auth) {- return createEmptyOptions('Please connect account first.');+ return emptyOptions('Please connect account first.');}if (!project_id) {- return createEmptyOptions('Please select project.');+ return emptyOptions('Please select project.');}-- const client = new TaskadeAPIClient(auth.secret_text);- const options: DropdownOption<string>[] = [];-- let after;- let moreTasks = true;- while (moreTasks) {- const response = await client.listTasks(project_id as string, { limit: 100, after });- if (response.items.length === 0) {- moreTasks = false;- } else {- after = response.items[response.items.length - 1].id;- for (const task of response.items) {- options.push({ label: task.text, value: task.id });- }- }+ try {+ const { options, truncated } = await listTaskOptions({ token: auth.secret_text, projectId: String(project_id) });+ return {+ disabled: false,+ options,+ placeholder: truncated+ ? `Showing the first ${TASK_DROPDOWN_PAGE_SIZE * TASK_DROPDOWN_MAX_PAGES} tasks. Use the Task ID in a custom expression for others.`+ : undefined,+ };+ } catch (error) {+ return emptyOptions(dropdownErrorMessage(error));}- return {- disabled: false,- options,- };},}),};++export const taskadeDropdowns = { listWorkspaces, listTaskOptions, dropdownErrorMessage };++async function listWorkspaces(token: string): Promise<ListAPIResponse<WorkspaceResponse>> {+ return taskadeApi.request<ListAPIResponse<WorkspaceResponse>>({+ token,+ method: HttpMethod.GET,+ path: '/workspaces',+ operation: 'list workspaces',+ });+}++async function listTaskOptions({ token, projectId }: { token: string; projectId: string }): Promise<{ options: DropdownOption<string>[]; truncated: boolean }> {+ const pages: DropdownOption<string>[][] = [];+ let after: string | undefined = undefined;+ for (let page = 0; page < TASK_DROPDOWN_MAX_PAGES; page++) {+ const response: TaskPageResponse = await taskadeApi.request<TaskPageResponse>({+ token,+ method: HttpMethod.GET,+ path: `/projects/${taskadeApi.seg({ value: projectId, label: 'Project ID' })}/tasks`,+ operation: 'list tasks',+ query: { limit: TASK_DROPDOWN_PAGE_SIZE, after },+ });+ const items = response.items ?? [];+ pages.push(+ items.map((task) => ({+ label: task.parentId ? task.text || '(empty task)' : `${task.text || 'Project'} (project root)`,+ value: task.id,+ })),+ );+ const nextCursor = response.nextCursor ?? items[items.length - 1]?.id;+ const hasMore = response.hasMore ?? items.length === TASK_DROPDOWN_PAGE_SIZE;+ if (!hasMore || items.length === 0 || !nextCursor) {+ return { options: pages.flat(), truncated: false };+ }+ after = nextCursor;+ }+ return { options: pages.flat(), truncated: true };+}++function emptyOptions(placeholder: string): DropdownState<string> {+ return { disabled: true, options: [], placeholder };+}++async function dropdownOrError(load: () => Promise<DropdownOption<string>[]>): Promise<DropdownState<string>> {+ try {+ return { disabled: false, options: await load() };+ } catch (error) {+ return emptyOptions(dropdownErrorMessage(error));+ }+}++function dropdownErrorMessage(error: unknown): string {+ const status = taskadeApi.statusOf(error);+ if (status === 401 || status === 403) {+ return 'Taskade rejected the personal access token. Reconnect the account.';+ }+ if (status === 429) {+ return 'Taskade rate limit reached (30 requests per minute). Wait a minute and refresh.';+ }+ const message = error instanceof Error ? error.message : String(error);+ return `Could not load options from Taskade: ${message.slice(0, 200)}`;+}++const TASK_DROPDOWN_PAGE_SIZE = 1000;+const TASK_DROPDOWN_MAX_PAGES = 10;diff --git a/packages/pieces/community/taskade/src/lib/common/tasks.ts b/packages/pieces/community/taskade/src/lib/common/tasks.tsnew file mode 100644index 00000000000..19f55723316--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/common/tasks.ts@@ -0,0 +1,98 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { TaskadeApiError, taskadeApi } from './client';+import { taskadeNormalize } from './normalize';+import { ItemAPIResponse, Task, TaskResponse } from './types';++async function getTask({ token, projectId, taskId }: { token: string; projectId: unknown; taskId: unknown }): Promise<Task> {+ const response = await taskadeApi.request<ItemAPIResponse<TaskResponse>>({+ token,+ method: HttpMethod.GET,+ path: taskadeApi.taskPath({ projectId, taskId }),+ operation: 'get task',+ });+ return taskadeNormalize.task(response.item);+}++async function taskOrFallback({ token, projectId, taskId, item }: { token: string; projectId: unknown; taskId: unknown; item: TaskResponse | null | undefined }): Promise<Task> {+ if (item && typeof item.id === 'string' && typeof item.text === 'string' && typeof item.parentId === 'string') {+ return taskadeNormalize.task(item);+ }+ return getTask({ token, projectId, taskId });+}++async function ignoreMissingSubResource<T>({+ token,+ projectId,+ taskId,+ call,+ whenMissing,+}: {+ token: string;+ projectId: unknown;+ taskId: unknown;+ call: () => Promise<T>;+ whenMissing: T;+}): Promise<T> {+ try {+ return await call();+ } catch (error) {+ if (!isMissing(error)) {+ throw error;+ }+ await getTask({ token, projectId, taskId });+ return whenMissing;+ }+}++async function setCompletion({ token, projectId, taskId, completed }: { token: string; projectId: unknown; taskId: unknown; completed: boolean }): Promise<{ task: Task; changed: boolean }> {+ try {+ const response = await taskadeApi.request<ItemAPIResponse<TaskResponse>>({+ token,+ method: HttpMethod.POST,+ path: `${taskadeApi.taskPath({ projectId, taskId })}/${completed ? 'complete' : 'uncomplete'}`,+ operation: completed ? 'complete task' : 'reopen task',+ body: {},+ });+ return { task: await taskOrFallback({ token, projectId, taskId, item: response.item }), changed: true };+ } catch (error) {+ if (taskadeApi.statusOf(error) !== 400) {+ throw error;+ }+ const task = await getTask({ token, projectId, taskId });+ if (task.completed !== completed) {+ throw error;+ }+ return { task, changed: false };+ }+}++function isMissing(error: unknown): boolean {+ if (taskadeApi.isNotFound(error)) {+ return true;+ }+ if (!(error instanceof TaskadeApiError) || error.status !== 400) {+ return false;+ }+ const body = error.responseBody;+ const message = taskadeApi.isRecord(body) && typeof body['message'] === 'string' ? body['message'] : '';+ return /does not exist/i.test(message);+}++function validateTaskText({ value, label, singleLine }: { value: unknown; label: string; singleLine: boolean }): string {+ const text = taskadeApi.requireText({ value, label });+ if (text.length > MAX_TASK_TEXT) {+ throw new Error(`${label} is ${text.length} characters; Taskade allows at most ${MAX_TASK_TEXT}.`);+ }+ if (singleLine && /[\r\n]/.test(text)) {+ throw new Error(`${label} must be a single line. Put longer details in the task note (Set Task Note).`);+ }+ return text;+}++function contentType(format: unknown): 'text/markdown' | 'text/plain' {+ return format === 'text/plain' ? 'text/plain' : 'text/markdown';+}++export const taskadeTasks = { getTask, setCompletion, taskOrFallback, ignoreMissingSubResource, validateTaskText, contentType, MAX_TASK_TEXT: 2000 };++const MAX_TASK_TEXT = 2000;diff --git a/packages/pieces/community/taskade/src/lib/common/types.ts b/packages/pieces/community/taskade/src/lib/common/types.tsindex 23463504a03..525d304ddb9 100644--- a/packages/pieces/community/taskade/src/lib/common/types.ts+++ b/packages/pieces/community/taskade/src/lib/common/types.ts@@ -1,42 +1,146 @@-export interface ListAPIResponse<T> {+export type ListAPIResponse<T> = {ok: boolean;items: Array<T>;-}+};-export interface BaseResponse {+export type ItemAPIResponse<T> = {+ ok: boolean;+ item: T | null;+};++export type BaseResponse = {id: string;name: string;-}+};export type WorkspaceResponse = BaseResponse;export type WorkspaceFolderResponse = BaseResponse;-export type ProjectResponse = BaseResponse;-export interface CreateTaskParams {- contentType: string;- content: string;- placement: string;-}+export type ProjectResponse = {+ id: string;+ name?: string;+ icon?: { type: string; value: string } | null;+ completed?: boolean;+};-export interface TaskResponse {+export type TaskResponse = {id: string;- parentId: string;- text: string;- completed: boolean;-}+ parentId?: string;+ text?: string;+ completed?: boolean;+};-export interface CreateTaskResponse {+export type TaskPageResponse = ListAPIResponse<TaskResponse> & {+ hasMore?: boolean;+ nextCursor?: string | null;+};++export type CreateTaskResponse = {ok: boolean;item: TaskResponse[];-}+};-export interface CreateTaskDateParams {- start: {- date: string;- time: string;- };- end?: {- date: string;- time: string;+export type TaskadeDate = {+ date: string;+ time?: string | null;+ timezone?: string | null;+};++export type TaskDateResponse = {+ start: TaskadeDate;+ end?: TaskadeDate | { period: string } | null;+};++export type TaskNoteResponse = {+ type: string;+ value: string;+};++export type MemberResponse = {+ handle: string;+ displayName?: string;+};++export type FieldValueResponse = {+ fieldId: string;+ value?: unknown;+};++export type FieldResponse = {+ id: string;+ data?: Record<string, unknown>;+};++export type AgentCommandResponse = {+ id: string;+ name: string;+ prompt?: string;+ mode?: string;+};++export type AgentResponse = {+ id: string;+ name?: string;+ space_id?: string;+ data?: {+ commands?: AgentCommandResponse[];+ description?: string;+ knowledgeEnabled?: boolean;+ avatar?: unknown;+ tone?: string;+ language?: string;};-}+};++export type ConversationResponse = {+ id: string;+ space_agent_id?: string;+ status?: string;+ title?: string;+};++export type ShareLinkResponse = {+ editUrl?: string;+ viewUrl?: string;+ checkUrl?: string;+};++export type Project = {+ id: string;+ name: string | null;+ icon: string | null;+ completed: boolean;+ url: string;+};++export type Task = {+ id: string;+ text: string;+ parentId: string | null;+ completed: boolean;+ isRoot: boolean;+};++export type Agent = {+ id: string;+ name: string | null;+ spaceId: string | null;+ description: string | null;+ knowledgeEnabled: boolean;+ commands: Array<{ id: string; name: string; prompt?: string }>;+};++export type Conversation = {+ id: string;+ agentId: string | null;+ title: string | null;+ status: string | null;+};++export type CustomField = {+ id: string;+ type: string | null;+ displayName: string | null;+ options: Array<{ id: string; name: string }>;+ data: Record<string, unknown>;+};diff --git a/packages/pieces/community/taskade/src/lib/common/webhook.ts b/packages/pieces/community/taskade/src/lib/common/webhook.tsnew file mode 100644index 00000000000..78ad49721fb--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/common/webhook.ts@@ -0,0 +1,159 @@+import { createHmac, timingSafeEqual } from 'node:crypto';+import { HttpMethod } from '@activepieces/pieces-common';+import { Property, Store, TestOrRunHookContext, TriggerHookContext, TriggerStrategy } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeApi } from './client';+import { taskadeDropdowns } from './props';++function verifySignature({ secret, headers, rawBody }: { secret: string; headers: Record<string, string | string[] | undefined>; rawBody: unknown }): boolean {+ const body = typeof rawBody === 'string' ? Buffer.from(rawBody, 'utf8') : Buffer.isBuffer(rawBody) ? rawBody : undefined;+ if (body === undefined || secret.length === 0) {+ return false;+ }+ const header = Object.entries(headers).find(([name]) => name.toLowerCase() === SIGNATURE_HEADER)?.[1];+ const given = Array.isArray(header) ? header[0] : header;+ if (typeof given !== 'string' || given.length === 0) {+ return false;+ }+ const expected = Buffer.from(sign({ secret, body }), 'utf8');+ const received = Buffer.from(given.trim(), 'utf8');+ return expected.length === received.length && timingSafeEqual(expected, received);+}++function sign({ secret, body }: { secret: string; body: Buffer | string }): string {+ return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`;+}++async function registerWebhook({ token, targetUrl, event, spaceIds }: { token: string; targetUrl: string; event: TaskadeWebhookEvent; spaceIds: string[] }): Promise<{ id: string; secret: string }> {+ const create = () =>+ taskadeApi.request<{ ok: boolean; webhook?: { id?: string }; secret?: string }>({+ token,+ method: HttpMethod.POST,+ version: 'v2',+ path: '/webhooks',+ operation: 'register webhook',+ body: { targetUrl, events: [event], spaceIds },+ });+ const response = await create().catch(async (error: unknown) => {+ const status = taskadeApi.statusOf(error);+ if (status === 402) {+ throw new Error('Taskade webhooks need a Pro plan or above (HTTP 402). Upgrade the Taskade account, or use a scheduled flow with List Tasks instead.');+ }+ if (status !== 409) {+ throw error;+ }+ await deleteWebhook({ token, id: targetUrl });+ return create();+ });+ const id = response.webhook?.id;+ const secret = response.secret;+ if (typeof id !== 'string' || id.length === 0 || typeof secret !== 'string' || secret.length === 0) {+ throw new Error('Taskade registered the webhook but did not return its ID and signing secret. Disable and enable the flow again.');+ }+ return { id, secret };+}++async function deleteWebhook({ token, id }: { token: string; id: string }): Promise<void> {+ try {+ await taskadeApi.request({+ token,+ method: HttpMethod.DELETE,+ version: 'v2',+ path: `/webhooks/${encodeURIComponent(id)}`,+ operation: 'delete webhook',+ });+ } catch (error) {+ if (!taskadeApi.isNotFound(error)) {+ throw error;+ }+ }+}++async function saveRegistration({ store, token, registration }: { store: Store; token: string; registration: WebhookRegistration }): Promise<void> {+ try {+ await store.put<WebhookRegistration>(STORE_KEY, registration);+ } catch (error) {+ await deleteWebhook({ token, id: registration.id }).catch(() => undefined);+ throw error;+ }+}++function toSpaceIds(value: unknown): string[] {+ const list = Array.isArray(value) ? value : [];+ return [...new Set(list.filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0).map((entry) => entry.trim()))];+}++const webhookTriggerProps = {+ workspaceIds: Property.MultiSelectDropdown({+ auth: taskadeAuth,+ displayName: 'Workspaces',+ description: 'Only fire for events in these workspaces. Leave empty for all workspaces.',+ required: false,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Please connect account first.' };+ }+ try {+ const response = await taskadeDropdowns.listWorkspaces(auth.secret_text);+ return { disabled: false, options: response.items.map((workspace) => ({ label: workspace.name, value: workspace.id })) };+ } catch (error) {+ return { disabled: true, options: [], placeholder: taskadeDropdowns.dropdownErrorMessage(error) };+ }+ },+ }),+};++function webhookTriggerHooks(event: TaskadeWebhookEvent) {+ return {+ async onEnable(context: WebhookHookContext): Promise<void> {+ const token = context.auth.secret_text;+ const registration = await registerWebhook({+ token,+ targetUrl: context.webhookUrl,+ event,+ spaceIds: toSpaceIds(context.propsValue.workspaceIds),+ });+ await saveRegistration({ store: context.store, token, registration });+ },+ async onDisable(context: WebhookHookContext): Promise<void> {+ const registration = await context.store.get<WebhookRegistration>(STORE_KEY);+ if (registration?.id) {+ await deleteWebhook({ token: context.auth.secret_text, id: registration.id });+ }+ await context.store.delete(STORE_KEY);+ },+ async run(context: WebhookRunContext): Promise<unknown[]> {+ const registration = await context.store.get<WebhookRegistration>(STORE_KEY);+ if (!registration?.secret) {+ return [];+ }+ const valid = verifySignature({ secret: registration.secret, headers: context.payload.headers ?? {}, rawBody: context.payload.rawBody });+ if (!valid) {+ return [];+ }+ return [context.payload.body];+ },+ };+}++const SIGNATURE_HEADER = 'x-taskade-signature';+const STORE_KEY = 'taskade_webhook';++export const taskadeWebhook = {+ verifySignature,+ sign,+ registerWebhook,+ deleteWebhook,+ webhookTriggerProps,+ webhookTriggerHooks,+ STORE_KEY,+};++type WebhookRegistration = { id: string; secret: string };++export type TaskadeWebhookEvent = 'task.due' | 'task.assigned' | 'comment.created' | 'project.created' | 'project.assigned' | 'project.joined';++type WebhookHookContext = TriggerHookContext<typeof taskadeAuth, typeof webhookTriggerProps, TriggerStrategy.WEBHOOK>;++type WebhookRunContext = TestOrRunHookContext<typeof taskadeAuth, typeof webhookTriggerProps, TriggerStrategy.WEBHOOK>;diff --git a/packages/pieces/community/taskade/src/lib/output-schemas.ts b/packages/pieces/community/taskade/src/lib/output-schemas.tsnew file mode 100644index 00000000000..d457e5738f1--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/output-schemas.ts@@ -0,0 +1,373 @@+import { OutputSchema } from '@activepieces/pieces-framework';++type Fields = OutputSchema['fields'];++const idName: Fields = [+ { key: 'id', label: 'ID' },+ { key: 'name', label: 'Name' },+];++const projectFields: Fields = [+ { key: 'id', label: 'Project ID', description: 'Use this ID in other Taskade steps.' },+ { key: 'name', label: 'Name' },+ { key: 'icon', label: 'Icon Emoji' },+ { key: 'completed', label: 'Completed (Archived)', format: 'boolean' },+ { key: 'url', label: 'Project Link', format: 'url' },+];++const taskFields: Fields = [+ { key: 'id', label: 'Task ID', description: 'Use this ID in other Taskade task steps.' },+ { key: 'text', label: 'Text' },+ { key: 'parentId', label: 'Parent Task ID', description: 'Empty for the project root node.' },+ { key: 'completed', label: 'Completed', format: 'boolean' },+ { key: 'isRoot', label: 'Is Project Root', format: 'boolean', description: 'True for the project title node, which is not a real task.' },+];++const rawTaskFields: Fields = [+ { key: 'id', label: 'Task ID' },+ { key: 'text', label: 'Text' },+ { key: 'parentId', label: 'Parent Task ID' },+ { key: 'completed', label: 'Completed', format: 'boolean' },+];++const memberFields: Fields = [+ { key: 'handle', label: 'Handle', description: 'Pass this to Assign Task.' },+ { key: 'displayName', label: 'Display Name' },+];++const dateFields: Fields = [+ { key: 'date', label: 'Date', format: 'date' },+ { key: 'time', label: 'Time' },+ { key: 'timezone', label: 'Timezone' },+];++const agentFields: Fields = [+ { key: 'id', label: 'Agent ID' },+ { key: 'name', label: 'Name' },+ { key: 'spaceId', label: 'Workspace ID' },+ { key: 'description', label: 'Description (System Prompt)' },+ { key: 'knowledgeEnabled', label: 'Knowledge Enabled', format: 'boolean' },+ {+ key: 'commands',+ label: 'Commands',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Command ID' },+ { key: 'name', label: 'Command Name' },+ { key: 'prompt', label: 'Command Prompt' },+ ],+ },+];++const conversationFields: Fields = [+ { key: 'id', label: 'Conversation ID' },+ { key: 'agentId', label: 'Agent ID' },+ { key: 'title', label: 'Title' },+ { key: 'status', label: 'Status', description: 'in_progress, idle or requires_review.' },+];++const pageFields: Fields = [+ { key: 'page', label: 'Page', format: 'number' },+ { key: 'nextPage', label: 'Next Page', format: 'number', description: 'Pass this as Page to get the next page. Empty when there are no more.' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+];++function list({ label, itemLabel, items, extra = [] }: { label: string; itemLabel?: string; items: Fields; extra?: Fields }): OutputSchema {+ return {+ fields: [{ key: 'items', label, labelKey: itemLabel, listItems: items }, ...extra],+ };+}++export const taskadeOutputSchemas: Record<string, OutputSchema> = {+ legacyCreateTask: {+ fields: [+ { key: 'ok', label: 'OK', format: 'boolean' },+ {+ key: 'item',+ label: 'Created Tasks',+ listItems: [+ { key: 'id', label: 'Task ID' },+ { key: 'completed', label: 'Completed', format: 'boolean' },+ ],+ },+ ],+ },+ legacyTaskItem: {+ fields: [+ { key: 'ok', label: 'OK', format: 'boolean' },+ { key: 'item', label: 'Task', children: rawTaskFields },+ ],+ },+ legacyDelete: {+ fields: [+ { key: 'ok', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Was Already Deleted', format: 'boolean', description: 'True when the task did not exist any more, so nothing was changed.' },+ ],+ },+ listWorkspaces: list({ label: 'Workspaces', itemLabel: 'name', items: idName }),+ listFolders: list({ label: 'Folders', itemLabel: 'name', items: idName }),+ listProjects: list({ label: 'Projects', itemLabel: 'name', items: projectFields }),+ listRecentProjects: list({ label: 'Projects', itemLabel: 'name', items: projectFields, extra: pageFields }),+ project: { fields: projectFields },+ listProjectTemplates: list({ label: 'Templates', itemLabel: 'name', items: idName, extra: pageFields }),+ listProjectMembers: list({ label: 'Members', itemLabel: 'displayName', items: memberFields, extra: pageFields }),+ listProjectFields: list({+ label: 'Custom Fields',+ itemLabel: 'displayName',+ items: [+ { key: 'id', label: 'Field ID', description: 'Pass this to Set Custom Field Value.' },+ { key: 'type', label: 'Type' },+ { key: 'displayName', label: 'Name' },+ { key: 'options', label: 'Options', labelKey: 'name', listItems: idName },+ { key: 'data', label: 'Raw Field Settings' },+ ],+ }),+ shareLink: {+ fields: [+ { key: 'projectId', label: 'Project ID' },+ { key: 'enabled', label: 'Share Link Enabled', format: 'boolean' },+ { key: 'viewUrl', label: 'View Link', format: 'url' },+ { key: 'editUrl', label: 'Edit Link', format: 'url' },+ { key: 'checkUrl', label: 'Check-only Link', format: 'url' },+ ],+ },+ listTasks: list({+ label: 'Tasks',+ itemLabel: 'text',+ items: taskFields,+ extra: [+ { key: 'nextCursor', label: 'Next Cursor', description: 'Pass this as Cursor to get the next page. Empty when there are no more.' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ ],+ }),+ findTasks: list({+ label: 'Matching Tasks',+ itemLabel: 'text',+ items: taskFields,+ extra: [+ { key: 'found', label: 'Found', format: 'boolean' },+ { key: 'scanned', label: 'Tasks Scanned', format: 'number' },+ { key: 'truncated', label: 'Scan Truncated', format: 'boolean', description: 'True when the project has more tasks than the scan limit; pass nextCursor as Start Cursor to keep searching.' },+ { key: 'nextCursor', label: 'Next Cursor' },+ ],+ }),+ task: { fields: taskFields },+ taskDetails: {+ fields: [+ ...taskFields,+ {+ key: 'date',+ label: 'Date',+ description: 'Empty when the task has no date.',+ children: [+ { key: 'start', label: 'Start', children: dateFields },+ { key: 'end', label: 'End', children: dateFields },+ ],+ },+ {+ key: 'note',+ label: 'Note',+ description: 'Empty when the task has no note.',+ children: [+ { key: 'type', label: 'Note Format' },+ { key: 'value', label: 'Note Text' },+ ],+ },+ { key: 'assignees', label: 'Assignees', labelKey: 'displayName', listItems: memberFields },+ {+ key: 'fields',+ label: 'Custom Field Values',+ labelKey: 'fieldId',+ listItems: [+ { key: 'fieldId', label: 'Field ID' },+ { key: 'value', label: 'Value' },+ ],+ },+ ],+ },+ createTasks: list({+ label: 'Created Tasks',+ itemLabel: 'text',+ items: [+ { key: 'id', label: 'Task ID', description: 'Use this ID in other Taskade task steps.' },+ { key: 'text', label: 'Text', description: 'The text that was sent.' },+ { key: 'completed', label: 'Completed', format: 'boolean' },+ ],+ extra: [{ key: 'count', label: 'Created Count', format: 'number' }],+ }),+ deleteTask: {+ fields: [+ { key: 'projectId', label: 'Project ID' },+ { key: 'taskId', label: 'Task ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Was Already Deleted', format: 'boolean', description: 'True when the task did not exist any more, so nothing was changed.' },+ ],+ },+ taskDate: {+ fields: [+ { key: 'projectId', label: 'Project ID' },+ { key: 'taskId', label: 'Task ID' },+ { key: 'cleared', label: 'Date Cleared', format: 'boolean' },+ {+ key: 'date',+ label: 'Date',+ description: 'Empty when the date was cleared.',+ children: [+ { key: 'start', label: 'Start', children: dateFields },+ { key: 'end', label: 'End', children: dateFields },+ ],+ },+ ],+ },+ taskNote: {+ fields: [+ { key: 'projectId', label: 'Project ID' },+ { key: 'taskId', label: 'Task ID' },+ { key: 'cleared', label: 'Note Cleared', format: 'boolean' },+ {+ key: 'note',+ label: 'Note',+ description: 'Empty when the note was cleared.',+ children: [+ { key: 'type', label: 'Note Format' },+ { key: 'value', label: 'Note Text' },+ ],+ },+ ],+ },+ assignTask: {+ fields: [...taskFields, { key: 'assignees', label: 'Assignees', labelKey: 'displayName', listItems: memberFields }],+ },+ unassignTask: {+ fields: [+ ...taskFields,+ { key: 'removedHandle', label: 'Removed Handle' },+ { key: 'wasAssigned', label: 'Was Assigned', format: 'boolean', description: 'False when the person was not assigned, so nothing changed.' },+ ],+ },+ taskFieldValue: {+ fields: [+ { key: 'projectId', label: 'Project ID' },+ { key: 'taskId', label: 'Task ID' },+ { key: 'fieldId', label: 'Field ID' },+ { key: 'value', label: 'Value', description: 'The value sent to Taskade. Empty when cleared.' },+ { key: 'cleared', label: 'Value Cleared', format: 'boolean' },+ ],+ },+ listAgents: list({ label: 'Agents', itemLabel: 'name', items: agentFields, extra: pageFields }),+ agent: { fields: agentFields },+ askAgent: {+ fields: [+ { key: 'agentId', label: 'Agent ID' },+ { key: 'spaceId', label: 'Workspace ID' },+ { key: 'response', label: 'Agent Response', description: 'What the agent answered.' },+ ],+ },+ listConversations: list({ label: 'Conversations', itemLabel: 'title', items: conversationFields, extra: pageFields }),+ conversation: {+ fields: [+ ...conversationFields,+ { key: 'transcript', label: 'Transcript', description: 'The conversation as text. Empty when not requested.' },+ { key: 'truncated', label: 'Transcript Truncated', format: 'boolean' },+ ],+ },+ deleteAgent: {+ fields: [+ { key: 'agentId', label: 'Agent ID' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'alreadyDeleted', label: 'Was Already Deleted', format: 'boolean' },+ ],+ },+ agentKnowledge: {+ fields: [+ { key: 'agentId', label: 'Agent ID' },+ { key: 'projectId', label: 'Project ID' },+ { key: 'linked', label: 'Project Is In Knowledge', format: 'boolean' },+ ],+ },+ triggerAutomation: {+ fields: [+ { key: 'status', label: 'HTTP Status', format: 'number' },+ { key: 'ok', label: 'Accepted', format: 'boolean' },+ ],+ },+ taskDueTrigger: {+ fields: [+ { key: 'id', label: 'Task ID' },+ { key: 'text', label: 'Task Text' },+ { key: 'isCompleted', label: 'Completed', format: 'boolean' },+ { key: 'projectName', label: 'Project Name' },+ { key: 'projectID', label: 'Project ID' },+ { key: 'spaceName', label: 'Workspace Name' },+ { key: 'spaceID', label: 'Workspace ID' },+ { key: 'assignees', label: 'Assignees' },+ { key: 'taskStartDate', label: 'Start Date', format: 'date' },+ { key: 'taskStartTime', label: 'Start Time' },+ { key: 'taskStartTimezone', label: 'Start Timezone' },+ { key: 'taskEndDate', label: 'End Date', format: 'date' },+ { key: 'taskEndTime', label: 'End Time' },+ { key: 'taskEndTimezone', label: 'End Timezone' },+ ],+ },+ taskAssignedTrigger: {+ fields: [+ { key: 'projectName', label: 'Project Name' },+ { key: 'projectId', label: 'Project ID' },+ { key: 'assignerName', label: 'Assigned By' },+ {+ key: 'nodes',+ label: 'Assigned Tasks',+ labelKey: 'nodeText',+ listItems: [+ { key: 'nodeId', label: 'Task ID' },+ { key: 'nodeText', label: 'Task Text' },+ { key: 'isCompleted', label: 'Completed', format: 'boolean' },+ { key: 'assignees', label: 'Assignee Handles' },+ ],+ },+ ],+ },+ commentCreatedTrigger: {+ fields: [+ { key: 'projectName', label: 'Project Name' },+ { key: 'projectId', label: 'Project ID' },+ { key: 'nodeId', label: 'Task ID' },+ { key: 'nodeText', label: 'Task Text' },+ { key: 'commenterDisplayName', label: 'Commenter Name' },+ { key: 'commenterHandle', label: 'Commenter Handle' },+ { key: 'commentBody', label: 'Comment' },+ { key: 'commentBodyType', label: 'Comment Format' },+ { key: 'assignees', label: 'Task Assignees' },+ { key: 'mentionedHandles', label: 'Mentioned Handles' },+ ],+ },+ projectCreatedTrigger: {+ fields: [+ { key: 'projectName', label: 'Project Name' },+ { key: 'projectId', label: 'Project ID' },+ { key: 'spaceName', label: 'Workspace Name' },+ { key: 'spaceId', label: 'Workspace ID' },+ { key: 'creatorName', label: 'Created By' },+ ],+ },+ projectAssignedTrigger: {+ fields: [+ { key: 'projectName', label: 'Project Name' },+ { key: 'projectId', label: 'Project ID' },+ { key: 'spaceName', label: 'Workspace Name' },+ { key: 'spaceId', label: 'Workspace ID' },+ { key: 'assignerName', label: 'Assigned By' },+ { key: 'assigneeName', label: 'Assignee Name' },+ { key: 'assigneeId', label: 'Assignee User ID' },+ ],+ },+ projectJoinedTrigger: {+ fields: [+ { key: 'projectName', label: 'Project Name' },+ { key: 'projectId', label: 'Project ID' },+ { key: 'spaceId', label: 'Workspace ID' },+ { key: 'joinerName', label: 'Member Name' },+ { key: 'joinerUserId', label: 'Member User ID' },+ ],+ },+};diff --git a/packages/pieces/community/taskade/src/lib/triggers/comment-created.ts b/packages/pieces/community/taskade/src/lib/triggers/comment-created.tsnew file mode 100644index 00000000000..f1925cc16f0--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/triggers/comment-created.ts@@ -0,0 +1,32 @@+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeWebhook } from '../common/webhook';+import { taskadeOutputSchemas } from '../output-schemas';++export const commentCreatedTrigger = createTrigger({+ auth: taskadeAuth,+ name: 'comment_created',+ displayName: 'New Comment',+ description: 'Fires when a comment is added to a task. Needs a Taskade Pro plan or above.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when someone comments on a Taskade task, with the comment text, the commenter, the task ID and text, and the project. Deliveries are signature-checked. Taskade sends no delivery ID, so a delivery Taskade resends can run the flow again. Needs a Taskade Pro plan.',+ },+ outputSchema: taskadeOutputSchemas['commentCreatedTrigger'],+ sampleData: {+ projectName: 'Customer Projects',+ projectId: 'A1b2C3d4E5f6G7h8',+ nodeId: '099630d4-267e-4b22-894b-08b69f3a4d79',+ nodeText: 'Follow up with the client',+ commenterDisplayName: 'Jane Doe',+ commenterHandle: 'janedoe',+ commentBody: 'Done, sent the proposal.',+ commentBodyType: 'text/markdown',+ assignees: [],+ mentionedHandles: [],+ },+ props: taskadeWebhook.webhookTriggerProps,+ type: TriggerStrategy.WEBHOOK,+ ...taskadeWebhook.webhookTriggerHooks('comment.created'),+});diff --git a/packages/pieces/community/taskade/src/lib/triggers/project-assigned.ts b/packages/pieces/community/taskade/src/lib/triggers/project-assigned.tsnew file mode 100644index 00000000000..3e8f79738b4--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/triggers/project-assigned.ts@@ -0,0 +1,29 @@+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeWebhook } from '../common/webhook';+import { taskadeOutputSchemas } from '../output-schemas';++export const projectAssignedTrigger = createTrigger({+ auth: taskadeAuth,+ name: 'project_assigned',+ displayName: 'Project Assigned',+ description: 'Fires when a project is assigned to someone. Needs a Taskade Pro plan or above.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a Taskade project is assigned to someone, with the project, its workspace, who assigned it and the assignee. Deliveries are signature-checked. Taskade sends no delivery ID, so a delivery Taskade resends can run the flow again. Needs a Taskade Pro plan.',+ },+ outputSchema: taskadeOutputSchemas['projectAssignedTrigger'],+ sampleData: {+ spaceName: 'Acme Workspace',+ spaceId: '1UsRFaZu9XgyTFej',+ projectName: 'Q3 Launch Plan',+ projectId: 'A1b2C3d4E5f6G7h8',+ assignerName: 'Jane Doe',+ assigneeName: 'John Smith',+ assigneeId: 12345,+ },+ props: taskadeWebhook.webhookTriggerProps,+ type: TriggerStrategy.WEBHOOK,+ ...taskadeWebhook.webhookTriggerHooks('project.assigned'),+});diff --git a/packages/pieces/community/taskade/src/lib/triggers/project-created.ts b/packages/pieces/community/taskade/src/lib/triggers/project-created.tsnew file mode 100644index 00000000000..0c2eece627c--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/triggers/project-created.ts@@ -0,0 +1,27 @@+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeWebhook } from '../common/webhook';+import { taskadeOutputSchemas } from '../output-schemas';++export const projectCreatedTrigger = createTrigger({+ auth: taskadeAuth,+ name: 'project_created',+ displayName: 'New Project',+ description: 'Fires when a project is created. Needs a Taskade Pro plan or above.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when a Taskade project is created, with the project ID and name, its workspace and who created it. Deliveries are signature-checked. Taskade sends no delivery ID, so a delivery Taskade resends can run the flow again. Needs a Taskade Pro plan.',+ },+ outputSchema: taskadeOutputSchemas['projectCreatedTrigger'],+ sampleData: {+ spaceName: 'Acme Workspace',+ spaceId: '1UsRFaZu9XgyTFej',+ projectName: 'Q3 Launch Plan',+ projectId: 'A1b2C3d4E5f6G7h8',+ creatorName: 'Jane Doe',+ },+ props: taskadeWebhook.webhookTriggerProps,+ type: TriggerStrategy.WEBHOOK,+ ...taskadeWebhook.webhookTriggerHooks('project.created'),+});diff --git a/packages/pieces/community/taskade/src/lib/triggers/project-joined.ts b/packages/pieces/community/taskade/src/lib/triggers/project-joined.tsnew file mode 100644index 00000000000..c6a6e607ae5--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/triggers/project-joined.ts@@ -0,0 +1,27 @@+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeWebhook } from '../common/webhook';+import { taskadeOutputSchemas } from '../output-schemas';++export const projectJoinedTrigger = createTrigger({+ auth: taskadeAuth,+ name: 'project_joined',+ displayName: 'Member Joined Project',+ description: 'Fires when someone joins a project. Needs a Taskade Pro plan or above.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when someone joins a Taskade project, with the project, its workspace and the new member\'s name and user ID. Deliveries are signature-checked. Taskade sends no delivery ID, so a delivery Taskade resends can run the flow again. Needs a Taskade Pro plan.',+ },+ outputSchema: taskadeOutputSchemas['projectJoinedTrigger'],+ sampleData: {+ spaceId: '1UsRFaZu9XgyTFej',+ projectName: 'Q3 Launch Plan',+ projectId: 'A1b2C3d4E5f6G7h8',+ joinerName: 'John Smith',+ joinerUserId: 12345,+ },+ props: taskadeWebhook.webhookTriggerProps,+ type: TriggerStrategy.WEBHOOK,+ ...taskadeWebhook.webhookTriggerHooks('project.joined'),+});diff --git a/packages/pieces/community/taskade/src/lib/triggers/task-assigned.ts b/packages/pieces/community/taskade/src/lib/triggers/task-assigned.tsnew file mode 100644index 00000000000..5fef5fd0d66--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/triggers/task-assigned.ts@@ -0,0 +1,33 @@+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeWebhook } from '../common/webhook';+import { taskadeOutputSchemas } from '../output-schemas';++export const taskAssignedTrigger = createTrigger({+ auth: taskadeAuth,+ name: 'task_assigned',+ displayName: 'Task Assigned',+ description: 'Fires when tasks are assigned to someone. Needs a Taskade Pro plan or above.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when one or more Taskade tasks are assigned to someone, with the project, who assigned them and each task\'s ID, text, completion and assignee handles. Deliveries are signature-checked. Taskade sends no delivery ID, so a delivery Taskade resends can run the flow again. Needs a Taskade Pro plan.',+ },+ outputSchema: taskadeOutputSchemas['taskAssignedTrigger'],+ sampleData: {+ projectName: 'Customer Projects',+ projectId: 'A1b2C3d4E5f6G7h8',+ assignerName: 'Jane Doe',+ nodes: [+ {+ nodeId: '099630d4-267e-4b22-894b-08b69f3a4d79',+ nodeText: 'Prepare the quote',+ isCompleted: false,+ assignees: ['johnsmith'],+ },+ ],+ },+ props: taskadeWebhook.webhookTriggerProps,+ type: TriggerStrategy.WEBHOOK,+ ...taskadeWebhook.webhookTriggerHooks('task.assigned'),+});diff --git a/packages/pieces/community/taskade/src/lib/triggers/task-due.ts b/packages/pieces/community/taskade/src/lib/triggers/task-due.tsnew file mode 100644index 00000000000..ab64653c587--- /dev/null+++ b/packages/pieces/community/taskade/src/lib/triggers/task-due.ts@@ -0,0 +1,36 @@+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';+import { taskadeAuth } from '../auth';+import { taskadeWebhook } from '../common/webhook';+import { taskadeOutputSchemas } from '../output-schemas';++export const taskDueTrigger = createTrigger({+ auth: taskadeAuth,+ name: 'task_due',+ displayName: 'Task Due',+ description: 'Fires when a task\'s due date arrives. Needs a Taskade Pro plan or above.',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Fires when the due date of a Taskade task arrives, with the task ID and text, its project and workspace, assignees and start/end date. Deliveries are signature-checked. Taskade sends no delivery ID, so a delivery Taskade resends can run the flow again. Needs a Taskade Pro plan.',+ },+ outputSchema: taskadeOutputSchemas['taskDueTrigger'],+ sampleData: {+ spaceName: 'Acme Workspace',+ spaceID: '1UsRFaZu9XgyTFej',+ projectName: 'Q3 Launch Plan',+ projectID: 'A1b2C3d4E5f6G7h8',+ id: '099630d4-267e-4b22-894b-08b69f3a4d79',+ text: 'Send the launch email',+ isCompleted: false,+ assignees: ['janedoe'],+ taskStartDate: null,+ taskStartTime: null,+ taskStartTimezone: null,+ taskEndDate: '2026-06-16',+ taskEndTime: '09:00',+ taskEndTimezone: 'Europe/Berlin',+ },+ props: taskadeWebhook.webhookTriggerProps,+ type: TriggerStrategy.WEBHOOK,+ ...taskadeWebhook.webhookTriggerHooks('task.due'),+});diff --git a/packages/pieces/community/taskade/test/agents.test.ts b/packages/pieces/community/taskade/test/agents.test.tsnew file mode 100644index 00000000000..3c3395f7cb2--- /dev/null+++ b/packages/pieces/community/taskade/test/agents.test.ts@@ -0,0 +1,121 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { addAgentKnowledgeProjectAction } from '../src/lib/actions/add-agent-knowledge-project';+import { askAgentAction } from '../src/lib/actions/ask-agent';+import { deleteAgentAction } from '../src/lib/actions/delete-agent';+import { generateAgentAction } from '../src/lib/actions/generate-agent';+import { getAgentAction } from '../src/lib/actions/get-agent';+import { getAgentConversationAction } from '../src/lib/actions/get-agent-conversation';+import { listAgentConversationsAction } from '../src/lib/actions/list-agent-conversations';+import { listAgentsAction } from '../src/lib/actions/list-agents';+import { removeAgentKnowledgeProjectAction } from '../src/lib/actions/remove-agent-knowledge-project';+import { replies, run, stubFetch } from './helpers';++const AGENT = {+ id: 'A1',+ name: 'Helper',+ space_id: 'W',+ data: { description: 'sys', knowledgeEnabled: true, commands: [{ id: 'c1', name: 'Cmd', prompt: 'do', mode: 'default' }] },+};++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('agents', () => {+ test('list_agents drops command prompts and pages', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [AGENT, null] } }));+ const result = await run(listAgentsAction)({ folderId: 'W', limit: 1 });+ expect(seen[0].path).toBe('/folders/W/agents');+ expect(result).toEqual({+ items: [{ id: 'A1', name: 'Helper', spaceId: 'W', description: 'sys', knowledgeEnabled: true, commands: [{ id: 'c1', name: 'Cmd' }] }],+ page: 1,+ nextPage: 2,+ hasMore: true,+ });+ });+ test('list_agents reports hasMore from the raw page size when a null entry is dropped', async () => {+ stubFetch(() => ({ body: { ok: true, items: [AGENT, null] } }));+ await expect(run(listAgentsAction)({ folderId: 'W', limit: 2 })).resolves.toMatchObject({ items: [{ id: 'A1' }], nextPage: 2, hasMore: true });+ });+ test('get_agent keeps prompts', async () => {+ stubFetch(() => ({ body: { ok: true, item: AGENT } }));+ await expect(run(getAgentAction)({ agentId: 'A1' })).resolves.toMatchObject({ commands: [{ id: 'c1', name: 'Cmd', prompt: 'do' }] });+ });+ test('ask_agent looks up the workspace and calls v2 promptAgent', async () => {+ const seen = stubFetch(replies([{ body: { ok: true, item: AGENT } }, { body: { ok: true, summary: 'Answer' } }]));+ const result = await run(askAgentAction)({ agentId: 'A1', prompt: 'Hi' });+ expect(seen[0].url).toBe('https://www.taskade.com/api/v1/agents/A1');+ expect(seen[1].url).toBe('https://www.taskade.com/api/v2/promptAgent');+ expect(seen[1].body).toEqual({ spaceId: 'W', agentId: 'A1', prompt: 'Hi' });+ expect(result).toEqual({ agentId: 'A1', spaceId: 'W', response: 'Answer' });+ });+ test('ask_agent with a workspace id makes one request', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, summary: 'A' } }));+ await run(askAgentAction)({ agentId: 'A1', prompt: 'Hi', workspaceId: 'W2' });+ expect(seen).toHaveLength(1);+ expect(seen[0].body).toMatchObject({ spaceId: 'W2' });+ });+ test('ask_agent explains a 402', async () => {+ stubFetch(() => ({ status: 402, body: { ok: false, code: 'PAYMENT_REQUIRED', message: 'Out of credits' } }));+ await expect(run(askAgentAction)({ agentId: 'A1', prompt: 'Hi', workspaceId: 'W' })).rejects.toThrow('AI credits');+ });+ test('ask_agent refuses bad ids and empty prompts before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(askAgentAction)({ agentId: '../x', prompt: 'Hi' })).rejects.toThrow('not a valid Agent ID');+ await expect(run(askAgentAction)({ agentId: 'A1', prompt: ' ' })).rejects.toThrow('Prompt is required');+ expect(seen).toHaveLength(0);+ });+ test('list_agent_conversations normalizes items', async () => {+ stubFetch(() => ({ body: { ok: true, items: [{ id: 'c1', space_agent_id: 'A1', status: 'idle', title: 'T', data: {} }] } }));+ await expect(run(listAgentConversationsAction)({ agentId: 'A1' })).resolves.toMatchObject({+ items: [{ id: 'c1', agentId: 'A1', status: 'idle', title: 'T' }],+ hasMore: false,+ });+ });+ test('get_agent_conversation caps the transcript', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: { id: 'c1', space_agent_id: 'A1' }, transcript: 'x'.repeat(100_010) } }));+ const result = await run(getAgentConversationAction)({ agentId: 'A1', conversationId: 'c1' });+ expect(seen[0].url).toBe('https://www.taskade.com/api/v2/getConversation');+ expect(seen[0].body).toEqual({ agentId: 'A1', convoId: 'c1', includeTranscript: true });+ expect(result).toMatchObject({ truncated: true });+ expect(String(Reflect.get(Object(result), 'transcript')).length).toBe(100_000);+ });+ test('get_agent_conversation without transcript', async () => {+ stubFetch(() => ({ body: { ok: true, item: { id: 'c1' } } }));+ await expect(run(getAgentConversationAction)({ agentId: 'A1', conversationId: 'c1', includeTranscript: false })).resolves.toMatchObject({+ transcript: null,+ truncated: false,+ });+ });+ test('generate_agent posts the description', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: AGENT } }));+ await expect(run(generateAgentAction)({ folderId: 'W', description: 'An agent' })).resolves.toMatchObject({ id: 'A1' });+ expect(seen[0].path).toBe('/folders/W/agent-generate');+ expect(seen[0].body).toEqual({ text: 'An agent' });+ });+ test('delete_agent: 404 is already deleted, other errors are thrown', async () => {+ stubFetch(() => ({ status: 404, body: { ok: false, message: 'Not Found' } }));+ await expect(run(deleteAgentAction)({ agentId: 'A1' })).resolves.toEqual({ agentId: 'A1', deleted: true, alreadyDeleted: true });+ stubFetch(() => ({ status: 500, body: { ok: false, message: 'boom' } }));+ await expect(run(deleteAgentAction)({ agentId: 'A1' })).rejects.toThrow('boom');+ });+ test('knowledge add and remove', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: AGENT } }));+ await expect(run(addAgentKnowledgeProjectAction)({ agentId: 'A1', projectId: 'https://www.taskade.com/d/P1' })).resolves.toEqual({ agentId: 'A1', projectId: 'P1', linked: true });+ expect(seen[0].body).toEqual({ projectId: 'P1' });+ await expect(run(removeAgentKnowledgeProjectAction)({ agentId: 'A1', projectId: 'P1' })).resolves.toEqual({ agentId: 'A1', projectId: 'P1', linked: false });+ expect(seen[1].method).toBe('DELETE');+ expect(seen[1].path).toBe('/agents/A1/knowledge/project/P1');+ });+ test('knowledge remove: 404 with an existing agent still succeeds, with a missing agent fails', async () => {+ stubFetch((request) => (request.method === 'DELETE' ? { status: 404, body: { ok: false } } : { body: { ok: true, item: AGENT } }));+ await expect(run(removeAgentKnowledgeProjectAction)({ agentId: 'A1', projectId: 'P1' })).resolves.toMatchObject({ linked: false });+ stubFetch(() => ({ status: 404, body: { ok: false, message: 'Not Found' } }));+ await expect(run(removeAgentKnowledgeProjectAction)({ agentId: 'A1', projectId: 'P1' })).rejects.toThrow('get agent failed');+ });+});diff --git a/packages/pieces/community/taskade/test/auth.test.ts b/packages/pieces/community/taskade/test/auth.test.tsnew file mode 100644index 00000000000..37e3faca7fe--- /dev/null+++ b/packages/pieces/community/taskade/test/auth.test.ts@@ -0,0 +1,42 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { taskadeAuth } from '../src/lib/auth';+import { runStep, stubFetch } from './helpers';++const server = { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', mintOidcToken: async () => 'oidc-token' };++function validate(auth: string) {+ const check = taskadeAuth.validate;+ if (!check) {+ throw new Error('taskadeAuth has no validate');+ }+ return runStep(check({ auth, server }));+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('taskadeAuth.validate', () => {+ test('valid token calls GET /v1/workspaces with the same trimmed bearer header as actions', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [] } }));+ await expect(validate(' tskdp_x ')).resolves.toEqual({ valid: true });+ expect(seen[0].url).toBe('https://www.taskade.com/api/v1/workspaces');+ expect(seen[0].auth).toBe('Bearer tskdp_x');+ });+ test.each([401, 403])('%s means invalid token', async (status) => {+ stubFetch(() => ({ status, body: { ok: false, message: 'Unauthorized' } }));+ await expect(validate('bad')).resolves.toMatchObject({ valid: false, error: expect.stringContaining('Invalid personal access token') });+ });+ test('other failures are reported without calling the token invalid', async () => {+ stubFetch(() => ({ status: 500, body: { ok: false, message: 'boom' } }));+ const result = await validate('tok');+ expect(result).toMatchObject({ valid: false });+ expect(JSON.stringify(result)).not.toContain('Invalid personal access token');+ expect(JSON.stringify(result)).toContain('boom');+ });+});diff --git a/packages/pieces/community/taskade/test/client.test.ts b/packages/pieces/community/taskade/test/client.test.tsnew file mode 100644index 00000000000..67d745de40e--- /dev/null+++ b/packages/pieces/community/taskade/test/client.test.ts@@ -0,0 +1,100 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { TaskadeApiError, taskadeApi } from '../src/lib/common/client';+import { replies, runStep, stubFetch } from './helpers';++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++function get({ path, version = 'v1' }: { path: string; version?: 'v1' | 'v2' }) {+ return runStep(taskadeApi.request({ token: ' tok ', method: HttpMethod.GET, path, version, operation: 'test op' }));+}++describe('request', () => {+ test('builds v1 and v2 URLs on www.taskade.com with a trimmed bearer token', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await get({ path: '/workspaces' });+ await get({ path: '/webhooks', version: 'v2' });+ expect(seen[0].url).toBe('https://www.taskade.com/api/v1/workspaces');+ expect(seen[1].url).toBe('https://www.taskade.com/api/v2/webhooks');+ expect(seen[0].auth).toBe('Bearer tok');+ });+ test('refuses a path without a leading slash', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(get({ path: 'evil.com/x' })).rejects.toThrow('must start with');+ });+ test('retries 429 twice, then fails with a rate-limit message', async () => {+ const seen = stubFetch(() => ({ status: 429, body: { ok: false, code: 'TOO_MANY_REQUESTS', message: 'slow down' } }));+ const error = await get({ path: '/workspaces' }).catch((e: unknown) => e);+ expect(seen).toHaveLength(3);+ expect(error).toBeInstanceOf(TaskadeApiError);+ expect(String(error)).toContain('rate limit');+ });+ test('a 429 followed by success returns the body', async () => {+ stubFetch(replies([{ status: 429, body: {} }, { body: { ok: true, items: [1] } }]));+ await expect(get({ path: '/workspaces' })).resolves.toEqual({ ok: true, items: [1] });+ });+ test('total 429 wait stays bounded', () => {+ expect(taskadeApi.RATE_LIMIT_RETRY_DELAYS_MS.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(30_000);+ });+ test('errors carry status, code and responseBody but never a body field', async () => {+ stubFetch(() => ({ status: 404, body: { ok: false, code: 'NOT_FOUND', message: 'Document not found' } }));+ const error = await get({ path: '/projects/x' }).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(TaskadeApiError);+ if (!(error instanceof TaskadeApiError)) {+ return;+ }+ expect(error.status).toBe(404);+ expect(error.code).toBe('NOT_FOUND');+ expect(error.responseBody).toMatchObject({ message: 'Document not found' });+ expect(Reflect.has(error, 'body')).toBe(false);+ expect(error.message).toBe('Taskade test op failed (404 NOT_FOUND): not found. Check the IDs you passed. Document not found');+ expect(taskadeApi.isNotFound(error)).toBe(true);+ });+ test('402 explains credits or plan with the feature id', async () => {+ stubFetch(() => ({ status: 402, body: { ok: false, code: 'PAYMENT_REQUIRED', message: 'No', featureId: 'ai' } }));+ await expect(get({ path: '/x' })).rejects.toThrow('AI credits or a higher Taskade plan (feature: ai)');+ });+ test('a 200 with ok:false is an error', async () => {+ stubFetch(() => ({ body: { ok: false, message: 'nope' } }));+ await expect(get({ path: '/x' })).rejects.toThrow('nope');+ });+ test('vendor messages are capped at 500 characters', async () => {+ stubFetch(() => ({ status: 500, body: { ok: false, message: 'x'.repeat(2000) } }));+ const error = await get({ path: '/x' }).catch((e: unknown) => e);+ expect(String(error instanceof Error ? error.message : '').length).toBeLessThan(600);+ });+});++describe('ids and paths', () => {+ test('seg encodes and rejects dot segments and empties', () => {+ expect(taskadeApi.seg({ value: 'a/b?c', label: 'X' })).toBe('a%2Fb%3Fc');+ expect(() => taskadeApi.seg({ value: '..', label: 'X' })).toThrow('not a valid');+ expect(() => taskadeApi.seg({ value: ' ', label: 'X' })).toThrow('X is required');+ });+ test('parseProjectId accepts ids and taskade links only', () => {+ expect(taskadeApi.parseProjectId('DkZoeHwNZ5SJ2vGA')).toBe('DkZoeHwNZ5SJ2vGA');+ expect(taskadeApi.parseProjectId('https://www.taskade.com/d/DkZoeHwNZ5SJ2vGA?x=1')).toBe('DkZoeHwNZ5SJ2vGA');+ expect(taskadeApi.parseProjectId('https://taskade.com/d/abc')).toBe('abc');+ expect(() => taskadeApi.parseProjectId('https://www.taskade.com.evil.io/d/abc')).toThrow('not a Taskade project link');+ expect(() => taskadeApi.parseProjectId('https://[email protected]/d/abc')).toThrow('not a Taskade project link');+ expect(() => taskadeApi.parseProjectId('http://www.taskade.com/d/abc')).toThrow('not a Taskade project link');+ expect(() => taskadeApi.parseProjectId('https://www.taskade.com/settings')).toThrow('Could not find a project ID');+ expect(() => taskadeApi.parseProjectId('../workspaces')).toThrow('not a valid Project ID');+ });+ test('taskPath builds an encoded task path', () => {+ expect(taskadeApi.taskPath({ projectId: 'https://www.taskade.com/d/P1', taskId: 't 1' })).toBe('/projects/P1/tasks/t%201');+ });+ test('validateInteger enforces ranges', () => {+ expect(taskadeApi.validateInteger({ value: '5', label: 'Limit', min: 1, max: 10 })).toBe(5);+ expect(taskadeApi.validateInteger({ value: undefined, label: 'Limit', min: 1, max: 10 })).toBeUndefined();+ expect(() => taskadeApi.validateInteger({ value: 11, label: 'Limit', min: 1, max: 10 })).toThrow('between 1 and 10');+ expect(() => taskadeApi.validateInteger({ value: 1.5, label: 'Limit', min: 1, max: 10 })).toThrow('whole number');+ });+});diff --git a/packages/pieces/community/taskade/test/helpers.ts b/packages/pieces/community/taskade/test/helpers.tsnew file mode 100644index 00000000000..702d330cdfa--- /dev/null+++ b/packages/pieces/community/taskade/test/helpers.ts@@ -0,0 +1,122 @@+import { AppConnectionType, Store } from '@activepieces/pieces-framework';+import { vi } from 'vitest';++export type SeenRequest = {+ url: string;+ method: string;+ path: string;+ version: string;+ headers: Headers;+ query: URLSearchParams;+ auth: string | null;+ accept: string | null;+ body: unknown;+};++export type FakeReply = {+ status?: number;+ body?: unknown;+ text?: string;+ headers?: Record<string, string>;+};++export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {+ const seen: SeenRequest[] = [];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = input instanceof Request ? input.url : String(input);+ const headers = new Headers(init?.headers);+ const parsed = new URL(url);+ const rawBody = typeof init?.body === 'string' ? init.body : null;+ const request: SeenRequest = {+ url,+ method: (init?.method ?? 'GET').toUpperCase(),+ path: parsed.pathname.replace(/^\/api\/v[12]/, ''),+ version: parsed.pathname.startsWith('/api/v2') ? 'v2' : parsed.pathname.startsWith('/api/v1') ? 'v1' : 'other',+ headers,+ query: parsed.searchParams,+ auth: headers.get('authorization'),+ accept: headers.get('accept'),+ body: rawBody ? JSON.parse(rawBody) : null,+ };+ seen.push(request);+ const reply = respond(request, seen.length - 1);+ const payload = reply.text ?? JSON.stringify(reply.body ?? {});+ return new Response(payload, {+ status: reply.status ?? 200,+ headers: { 'content-type': reply.text !== undefined ? 'text/plain' : 'application/json', ...(reply.headers ?? {}) },+ });+ }),+ );+ return seen;+}++export function replies(list: FakeReply[]): (request: SeenRequest, index: number) => FakeReply {+ return (_request, index) => list[Math.min(index, list.length - 1)];+}++export const TOKEN = 'test-token';++export const SERVER = { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' };++export function taskadeConnection() {+ return { type: AppConnectionType.SECRET_TEXT as const, secret_text: TOKEN };+}++export function actionContext(propsValue: Record<string, unknown>): TestActionContext {+ return { auth: taskadeConnection(), propsValue, store: memoryStore(), server: SERVER };+}++export function memoryStore(initial: Record<string, unknown> = {}): MemoryStore {+ const data = new Map<string, string>(Object.entries(initial).map(([key, value]) => [key, JSON.stringify(value)]));+ return {+ read: (key: string): unknown => {+ const raw = data.get(key);+ return raw === undefined ? undefined : JSON.parse(raw);+ },+ put: async <T>(key: string, value: T): Promise<T> => {+ data.set(key, JSON.stringify(value));+ return value;+ },+ get: async <T>(key: string): Promise<T | null> => {+ const raw = data.get(key);+ return raw === undefined ? null : JSON.parse(raw);+ },+ delete: async (key: string): Promise<void> => {+ data.delete(key);+ },+ };+}++export async function runStep<T>(promise: Promise<T>): Promise<T> {+ const settled = promise.then(+ (value) => ({ ok: true as const, value }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ await vi.runAllTimersAsync();+ const result = await settled;+ if (!result.ok) {+ throw result.error;+ }+ return result.value;+}++export function run(action: Runnable) {+ return (propsValue: Record<string, unknown>): Promise<unknown> => runStep(action.run(actionContext(propsValue)));+}++export function idsOf(items: unknown): unknown[] {+ return Array.isArray(items) ? items.map((item: unknown) => (item !== null && typeof item === 'object' ? Reflect.get(item, 'id') : undefined)) : [];+}++export type MemoryStore = Store & { read: (key: string) => unknown };++type TestActionContext = {+ auth: { type: AppConnectionType.SECRET_TEXT; secret_text: string };+ propsValue: Record<string, unknown>;+ store: Store;+ server: typeof SERVER;+};++type Runnable = { run(context: TestActionContext): Promise<unknown> };diff --git a/packages/pieces/community/taskade/test/legacy.test.ts b/packages/pieces/community/taskade/test/legacy.test.tsnew file mode 100644index 00000000000..06f80325d6a--- /dev/null+++ b/packages/pieces/community/taskade/test/legacy.test.ts@@ -0,0 +1,54 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { completeTaskAction } from '../src/lib/actions/complete-task.action';+import { createTaskAction } from '../src/lib/actions/create-task.action';+import { deleteTaskAction } from '../src/lib/actions/delete-task.action';+import { run, SeenRequest, stubFetch } from './helpers';++const TASK = { id: 't1', text: 'Do it', parentId: 'root', completed: true };++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('existing actions keep their names, props and output shape', () => {+ test('names and props are unchanged', () => {+ expect(createTaskAction.name).toBe('taskade-create-task');+ expect(completeTaskAction.name).toBe('taskade-complete-task');+ expect(deleteTaskAction.name).toBe('taskade-delete-task');+ expect(Object.keys(createTaskAction.props)).toEqual(['workspace_id', 'folder_id', 'project_id', 'content_type', 'content', 'placement']);+ expect(Object.keys(completeTaskAction.props)).toEqual(['workspace_id', 'folder_id', 'project_id', 'task_id']);+ expect(Object.keys(deleteTaskAction.props)).toEqual(['workspace_id', 'folder_id', 'project_id', 'task_id']);+ });+ test('create-task sends the original body and returns the raw envelope', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: [{ id: 'a', completed: false }] } }));+ const result = await run(createTaskAction)({ project_id: 'P1', content_type: 'text/markdown', content: 'Hello', placement: 'afterbegin' });+ expect(seen[0].path).toBe('/projects/P1/tasks');+ expect(seen[0].body).toEqual({ tasks: [{ content: 'Hello', contentType: 'text/markdown', placement: 'afterbegin' }] });+ expect(result).toEqual({ ok: true, item: [{ id: 'a', completed: false }] });+ });+ test('create-task refuses content over 2000 characters', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(createTaskAction)({ project_id: 'P1', content_type: 'text/plain', content: 'x'.repeat(2001), placement: 'beforeend' })).rejects.toThrow('2000');+ expect(seen).toHaveLength(0);+ });+ test('complete-task returns ok + item, also when the task was already completed', async () => {+ stubFetch((request: SeenRequest) => (request.method === 'POST' ? { status: 400, body: { ok: false, message: 'Bad Request' } } : { body: { ok: true, item: TASK } }));+ await expect(run(completeTaskAction)({ project_id: 'P1', task_id: 't1' })).resolves.toEqual({ ok: true, item: TASK });+ });+ test('delete-task is idempotent: 404 after confirming the project', async () => {+ stubFetch(() => ({ body: { ok: true } }));+ await expect(run(deleteTaskAction)({ project_id: 'P1', task_id: 't1' })).resolves.toEqual({ ok: true, alreadyDeleted: false });+ const seen = stubFetch((request: SeenRequest) => (request.method === 'DELETE' ? { status: 404, body: { ok: false, message: 'Not Found' } } : { body: { ok: true, item: { id: 'P1' } } }));+ await expect(run(deleteTaskAction)({ project_id: 'P1', task_id: 't1' })).resolves.toEqual({ ok: true, alreadyDeleted: true });+ expect(seen[1].path).toBe('/projects/P1');+ });+ test('delete-task fails when the project is missing', async () => {+ stubFetch(() => ({ status: 404, body: { ok: false, message: 'Document not found' } }));+ await expect(run(deleteTaskAction)({ project_id: 'P1', task_id: 't1' })).rejects.toThrow('Document not found');+ });+});diff --git a/packages/pieces/community/taskade/test/metadata.test.ts b/packages/pieces/community/taskade/test/metadata.test.tsnew file mode 100644index 00000000000..5af19f441ba--- /dev/null+++ b/packages/pieces/community/taskade/test/metadata.test.ts@@ -0,0 +1,42 @@+import { describe, expect, test } from 'vitest';+import { taskade } from '../src';++const actions = Object.values(taskade.actions());+const nonCustom = actions.filter((action) => action.name !== 'custom_api_call');++describe('piece metadata', () => {+ test('42 actions and 6 triggers', () => {+ expect(actions).toHaveLength(42);+ expect(Object.keys(taskade.triggers())).toHaveLength(6);+ });+ test.each(nonCustom.map((action) => [action.name, action]))('%s declares audience, classification, aiMetadata and outputSchema', (_name, action) => {+ expect(['both', 'ai', 'human']).toContain(action.audience);+ expect(['READ', 'SEARCH', 'WRITE', 'DESTRUCTIVE']).toContain(action.classification);+ expect(action.aiMetadata?.description?.length ?? 0).toBeGreaterThan(60);+ expect(typeof action.aiMetadata?.idempotent).toBe('boolean');+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ });+ test('dropdown actions are human-only and their AI twins take IDs as text', () => {+ const byName = Object.fromEntries(actions.map((action) => [action.name, action]));+ expect(byName['taskade-create-task'].audience).toBe('human');+ expect(byName['taskade-complete-task'].audience).toBe('human');+ expect(byName['taskade-delete-task'].audience).toBe('human');+ expect(byName['complete_task_by_id'].audience).toBe('ai');+ expect(byName['delete_task_by_id'].audience).toBe('ai');+ const aiVisible = actions.filter((action) => action.audience !== 'human' && action.name !== 'custom_api_call');+ for (const action of aiVisible) {+ const types = Object.values(action.props).map((prop: unknown) => (prop !== null && typeof prop === 'object' ? Reflect.get(prop, 'type') : undefined));+ expect(types).not.toContain('DROPDOWN');+ }+ });+ test('destructive actions are the deletes', () => {+ expect(nonCustom.filter((action) => action.classification === 'DESTRUCTIVE').map((action) => action.name).sort()).toEqual([+ 'delete_agent',+ 'delete_task_by_id',+ 'taskade-delete-task',+ ]);+ });+ test('minimum release supports ai audience', () => {+ expect(taskade.minimumSupportedRelease).toBe('0.88.2');+ });+});diff --git a/packages/pieces/community/taskade/test/projects.test.ts b/packages/pieces/community/taskade/test/projects.test.tsnew file mode 100644index 00000000000..36a3de630f6--- /dev/null+++ b/packages/pieces/community/taskade/test/projects.test.ts@@ -0,0 +1,149 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { completeProjectAction } from '../src/lib/actions/complete-project';+import { copyProjectAction } from '../src/lib/actions/copy-project';+import { createProjectAction } from '../src/lib/actions/create-project';+import { createProjectFromTemplateAction } from '../src/lib/actions/create-project-from-template';+import { getProjectAction } from '../src/lib/actions/get-project';+import { getProjectShareLinkAction } from '../src/lib/actions/get-project-share-link';+import { listFoldersAction } from '../src/lib/actions/list-folders';+import { listProjectFieldsAction } from '../src/lib/actions/list-project-fields';+import { listProjectMembersAction } from '../src/lib/actions/list-project-members';+import { listProjectTemplatesAction } from '../src/lib/actions/list-project-templates';+import { listProjectsAction } from '../src/lib/actions/list-projects';+import { listRecentProjectsAction } from '../src/lib/actions/list-recent-projects';+import { listWorkspacesAction } from '../src/lib/actions/list-workspaces';+import { restoreProjectAction } from '../src/lib/actions/restore-project';+import { replies, run, stubFetch } from './helpers';++const PROJECT = { id: 'P1', name: 'Plan', icon: { type: 'emoji', value: '📝' }, completed: false };+const NORMALIZED = { id: 'P1', name: 'Plan', icon: '📝', completed: false, url: 'https://www.taskade.com/d/P1' };++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('workspaces and folders', () => {+ test('list_workspaces', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [{ id: 'W', name: 'Workspace' }, null] } }));+ await expect(run(listWorkspacesAction)({})).resolves.toEqual({ items: [{ id: 'W', name: 'Workspace' }] });+ expect(seen[0].path).toBe('/workspaces');+ });+ test('list_folders encodes the workspace id', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [{ id: 'W', name: 'Home' }] } }));+ await run(listFoldersAction)({ workspaceId: 'W/../x' });+ expect(seen[0].url).toBe('https://www.taskade.com/api/v1/workspaces/W%2F..%2Fx/folders');+ });+});++describe('projects', () => {+ test('list_projects filters by name and archived state', async () => {+ stubFetch(() => ({+ body: { ok: true, items: [PROJECT, { id: 'P2', name: 'Old plan', completed: true }, { id: 'P3', name: 'Other' }, null] },+ }));+ const result = await run(listProjectsAction)({ folderId: 'W', nameContains: 'PLAN', includeCompleted: false });+ expect(result).toEqual({ items: [NORMALIZED] });+ });+ test('list_recent_projects passes paging and reports hasMore from a full page', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [PROJECT, PROJECT] } }));+ const result = await run(listRecentProjectsAction)({ limit: 2, page: 3, sort: 'viewed-asc' });+ expect(Object.fromEntries(seen[0].query)).toEqual({ limit: '2', page: '3', sort: 'viewed-asc' });+ expect(result).toMatchObject({ page: 3, nextPage: 4, hasMore: true });+ });+ test('list_recent_projects refuses a limit over 100', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(run(listRecentProjectsAction)({ limit: 500 })).rejects.toThrow('between 1 and 100');+ });+ test('get_project accepts a project link', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: PROJECT } }));+ await expect(run(getProjectAction)({ projectId: 'https://www.taskade.com/d/P1' })).resolves.toEqual(NORMALIZED);+ expect(seen[0].path).toBe('/projects/P1');+ });+ test('get_project refuses a lookalike host before any request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(getProjectAction)({ projectId: 'https://www.taskade.com.evil.io/d/P1' })).rejects.toThrow('not a Taskade project link');+ expect(seen).toHaveLength(0);+ });+ test('create_project sends a markdown title and body and fills the missing name', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: { id: 'P9', icon: null } } }));+ const result = await run(createProjectAction)({ folderId: 'W', title: 'AP-TEST', content: '- a\n- b' });+ expect(seen[0].method).toBe('POST');+ expect(seen[0].body).toEqual({ folderId: 'W', contentType: 'text/markdown', content: '# AP-TEST\n\n- a\n- b' });+ expect(result).toMatchObject({ id: 'P9', name: 'AP-TEST', url: 'https://www.taskade.com/d/P9' });+ });+ test('create_project refuses a multi-line title', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(run(createProjectAction)({ folderId: 'W', title: 'a\nb' })).rejects.toThrow('single line');+ });+ test('create_project_from_template re-reads the project when the name is missing', async () => {+ const seen = stubFetch(replies([{ body: { ok: true, item: { id: 'P9' } } }, { body: { ok: true, item: { ...PROJECT, id: 'P9' } } }]));+ const result = await run(createProjectFromTemplateAction)({ folderId: 'W', templateId: 'T1' });+ expect(seen[0].body).toEqual({ folderId: 'W', templateId: 'T1' });+ expect(seen[1].path).toBe('/projects/P9');+ expect(result).toMatchObject({ id: 'P9', name: 'Plan' });+ });+ test('copy_project omits an empty title', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: { ...PROJECT, id: 'P2' } } }));+ await run(copyProjectAction)({ projectId: 'P1', folderId: 'W', projectTitle: ' ' });+ expect(seen[0].path).toBe('/projects/P1/copy');+ expect(seen[0].body).toEqual({ folderId: 'W' });+ expect(seen).toHaveLength(1);+ });+ test('complete_project re-reads the project and reports it completed', async () => {+ const seen = stubFetch(replies([{ body: { ok: true, item: { id: 'P1' } } }, { body: { ok: true, item: PROJECT } }]));+ await expect(run(completeProjectAction)({ projectId: 'P1' })).resolves.toEqual({ ...NORMALIZED, completed: true });+ expect(seen.map((r) => `${r.method} ${r.path}`)).toEqual(['POST /projects/P1/complete', 'GET /projects/P1']);+ });+ test('restore_project reports it active', async () => {+ stubFetch(replies([{ body: { ok: true, item: null } }, { body: { ok: true, item: { ...PROJECT, completed: true } } }]));+ await expect(run(restoreProjectAction)({ projectId: 'P1' })).resolves.toMatchObject({ completed: false });+ });+ test('list_project_templates and members page', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [{ id: 'T1', name: 'Sprint' }, null] } }));+ await expect(run(listProjectTemplatesAction)({ folderId: 'W' })).resolves.toEqual({ items: [{ id: 'T1', name: 'Sprint' }], page: 1, nextPage: null, hasMore: false });+ expect(seen[0].query.get('limit')).toBe('20');+ stubFetch(() => ({ body: { ok: true, items: [{ id: 'T1', name: 'Sprint' }, null] } }));+ await expect(run(listProjectTemplatesAction)({ folderId: 'W', limit: 2 })).resolves.toMatchObject({ items: [{ id: 'T1' }], nextPage: 2, hasMore: true });+ stubFetch(() => ({ body: { ok: true, items: [{ handle: 'pieces', displayName: 'P' }, null] } }));+ await expect(run(listProjectMembersAction)({ projectId: 'P1', limit: 2 })).resolves.toMatchObject({ items: [{ handle: 'pieces' }], nextPage: 2, hasMore: true });+ stubFetch(() => ({ body: { ok: true, items: [{ handle: 'pieces', displayName: 'P' }] } }));+ await expect(run(listProjectMembersAction)({ projectId: 'P1', limit: 1 })).resolves.toEqual({+ items: [{ handle: 'pieces', displayName: 'P' }],+ page: 1,+ nextPage: 2,+ hasMore: true,+ });+ });+ test('list_project_fields normalizes select options', async () => {+ stubFetch(() => ({+ body: {+ ok: true,+ items: [+ { id: 'f1', data: { type: 'Select', displayName: 'Status', options: { a: { id: 'o1', name: 'Open', rank: 'a' } } } },+ { id: 'f2', data: { type: 'Assign', title: 'Owner' } },+ ],+ },+ }));+ const result = await run(listProjectFieldsAction)({ projectId: 'P1' });+ expect(result).toMatchObject({+ items: [+ { id: 'f1', type: 'Select', displayName: 'Status', options: [{ id: 'o1', name: 'Open' }] },+ { id: 'f2', type: 'Assign', displayName: 'Owner', options: [] },+ ],+ });+ });+ test('get_project_share_link reports enabled false for a null item', async () => {+ stubFetch(() => ({ body: { ok: true, item: null } }));+ await expect(run(getProjectShareLinkAction)({ projectId: 'P1' })).resolves.toEqual({+ projectId: 'P1',+ enabled: false,+ viewUrl: null,+ editUrl: null,+ checkUrl: null,+ });+ });+});diff --git a/packages/pieces/community/taskade/test/props.test.ts b/packages/pieces/community/taskade/test/props.test.tsnew file mode 100644index 00000000000..df1041b784c--- /dev/null+++ b/packages/pieces/community/taskade/test/props.test.ts@@ -0,0 +1,67 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { taskadeProps } from '../src/lib/common/props';+import { runStep, SERVER, stubFetch, taskadeConnection } from './helpers';++const ctx = { server: SERVER, project: { id: 'p', externalId: () => undefined }, flows: {}, step: { name: 's' } };++function options({ prop, propsValue }: { prop: { options: (propsValue: never, context: never) => Promise<unknown> }; propsValue: Record<string, unknown> }) {+ return runStep(Reflect.apply(prop.options, prop, [{ auth: taskadeConnection(), ...propsValue }, ctx]));+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('task dropdown', () => {+ test('follows nextCursor until hasMore is false and labels the root', async () => {+ const seen = stubFetch((_request, index) =>+ index === 0+ ? { body: { ok: true, items: [{ id: 'r', text: 'Proj' }, { id: 'a', text: 'A', parentId: 'r' }], hasMore: true, nextCursor: 'a' } }+ : { body: { ok: true, items: [{ id: 'b', text: '', parentId: 'r' }], hasMore: false, nextCursor: null } },+ );+ const result = await options({ prop: taskadeProps.task_id, propsValue: { project_id: 'P1' } });+ expect(seen).toHaveLength(2);+ expect(seen[0].query.get('limit')).toBe('1000');+ expect(seen[1].query.get('after')).toBe('a');+ expect(result).toMatchObject({+ disabled: false,+ options: [+ { label: 'Proj (project root)', value: 'r' },+ { label: 'A', value: 'a' },+ { label: '(empty task)', value: 'b' },+ ],+ });+ });+ test('caps at 10 pages and says so', async () => {+ const seen = stubFetch((_request, index) => ({ body: { ok: true, items: [{ id: `t${index}`, text: 'x', parentId: 'r' }], hasMore: true, nextCursor: `t${index}` } }));+ const result = await options({ prop: taskadeProps.task_id, propsValue: { project_id: 'P1' } });+ expect(seen).toHaveLength(10);+ expect(result).toMatchObject({ disabled: false, placeholder: expect.stringContaining('first 10000 tasks') });+ });+ test('errors become a disabled dropdown with a reason', async () => {+ stubFetch(() => ({ status: 401, body: { ok: false, message: 'Unauthorized' } }));+ await expect(options({ prop: taskadeProps.task_id, propsValue: { project_id: 'P1' } })).resolves.toMatchObject({ disabled: true, placeholder: expect.stringContaining('Reconnect') });+ stubFetch(() => ({ status: 500, body: { ok: false, message: 'boom' } }));+ await expect(options({ prop: taskadeProps.workspace_id, propsValue: {} })).resolves.toMatchObject({ disabled: true, placeholder: expect.stringContaining('boom') });+ });+ test('429 after retries is explained', async () => {+ stubFetch(() => ({ status: 429, body: { ok: false } }));+ await expect(options({ prop: taskadeProps.folder_id, propsValue: { workspace_id: 'W' } })).resolves.toMatchObject({ disabled: true, placeholder: expect.stringContaining('rate limit') });+ });+ test('project dropdown falls back to the workspace home folder', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [{ id: 'P1', name: 'Plan' }] } }));+ await expect(options({ prop: taskadeProps.project_id, propsValue: { workspace_id: 'W' } })).resolves.toMatchObject({ options: [{ label: 'Plan', value: 'P1' }] });+ expect(seen[0].path).toBe('/folders/W/projects');+ });+ test('missing parents disable the dropdown without a request', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(options({ prop: taskadeProps.task_id, propsValue: {} })).resolves.toMatchObject({ disabled: true });+ await expect(options({ prop: taskadeProps.folder_id, propsValue: {} })).resolves.toMatchObject({ disabled: true });+ expect(seen).toHaveLength(0);+ });+});diff --git a/packages/pieces/community/taskade/test/tasks.test.ts b/packages/pieces/community/taskade/test/tasks.test.tsnew file mode 100644index 00000000000..99a2b8665da--- /dev/null+++ b/packages/pieces/community/taskade/test/tasks.test.ts@@ -0,0 +1,376 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { assignTaskAction } from '../src/lib/actions/assign-task';+import { completeTaskByIdAction } from '../src/lib/actions/ai/complete-task-by-id';+import { deleteTaskByIdAction } from '../src/lib/actions/ai/delete-task-by-id';+import { createTasksAction } from '../src/lib/actions/create-tasks';+import { findTasksAction } from '../src/lib/actions/find-tasks';+import { getTaskAction } from '../src/lib/actions/get-task';+import { listTasksAction } from '../src/lib/actions/list-tasks';+import { moveTaskAction } from '../src/lib/actions/move-task';+import { reopenTaskAction } from '../src/lib/actions/reopen-task';+import { setTaskDateAction } from '../src/lib/actions/set-task-date';+import { setTaskFieldValueAction } from '../src/lib/actions/set-task-field-value';+import { setTaskNoteAction } from '../src/lib/actions/set-task-note';+import { unassignTaskAction } from '../src/lib/actions/unassign-task';+import { updateTaskAction } from '../src/lib/actions/update-task';+import { replies, run, SeenRequest, stubFetch } from './helpers';++const TASK = { id: 't1', text: 'Do it', parentId: 'root', completed: false };+const NORMALIZED = { id: 't1', text: 'Do it', parentId: 'root', completed: false, isRoot: false };+const NOT_FOUND = { status: 404, body: { ok: false, code: 'NOT_FOUND', message: 'Not Found' } };+const BAD_REQUEST = { status: 400, body: { ok: false, code: 'BAD_REQUEST', message: 'Bad Request' } };++function route(map: Record<string, { status?: number; body?: unknown }>) {+ return (request: SeenRequest) => map[`${request.method} ${request.path}`] ?? { status: 599, body: { ok: false, message: `unexpected ${request.method} ${request.path}` } };+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('list_tasks', () => {+ test('passes limit and cursor and flags the root node', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, items: [{ id: 'r', text: 'Project' }, TASK], hasMore: true, nextCursor: 't1' } }));+ const result = await run(listTasksAction)({ projectId: 'P1', limit: 2, cursor: 'c0' });+ expect(Object.fromEntries(seen[0].query)).toEqual({ limit: '2', after: 'c0' });+ expect(result).toEqual({ items: [{ id: 'r', text: 'Project', parentId: null, completed: false, isRoot: true }, NORMALIZED], nextCursor: 't1', hasMore: true });+ });+ test('last page has no cursor', async () => {+ stubFetch(() => ({ body: { ok: true, items: [TASK], hasMore: false, nextCursor: null } }));+ await expect(run(listTasksAction)({ projectId: 'P1' })).resolves.toMatchObject({ nextCursor: null, hasMore: false });+ });+ test('limit over 1000 is refused', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(run(listTasksAction)({ projectId: 'P1', limit: 1001 })).rejects.toThrow('between 1 and 1000');+ });+});++describe('find_tasks', () => {+ test('matches case-insensitively, skips the root and filters by status', async () => {+ stubFetch(() => ({+ body: {+ ok: true,+ items: [{ id: 'r', text: 'Invoice project' }, { ...TASK, id: 'a', text: 'Send INVOICE' }, { ...TASK, id: 'b', text: 'invoice paid', completed: true }],+ hasMore: false,+ nextCursor: null,+ },+ }));+ const result = await run(findTasksAction)({ projectId: 'P1', textContains: 'invoice', status: 'open' });+ expect(result).toMatchObject({ found: true, scanned: 3, truncated: false, nextCursor: null });+ expect(result).toHaveProperty('items', [expect.objectContaining({ id: 'a' })]);+ });+ test('stops after 5 pages of 1000 and returns a cursor', async () => {+ const page = Array.from({ length: 1000 }, (_, i) => ({ ...TASK, id: `t${i}`, text: 'x' }));+ const seen = stubFetch(() => ({ body: { ok: true, items: page, hasMore: true, nextCursor: 'next' } }));+ const result = await run(findTasksAction)({ projectId: 'P1', textContains: 'nomatch' });+ expect(seen).toHaveLength(5);+ expect(seen[0].query.get('limit')).toBe('1000');+ expect(result).toMatchObject({ found: false, scanned: 5000, truncated: true, nextCursor: 'next' });+ });+ test('max results cut mid-page returns the last match as cursor', async () => {+ stubFetch(() => ({ body: { ok: true, items: [{ ...TASK, id: 'a', text: 'hit' }, { ...TASK, id: 'b', text: 'hit' }, { ...TASK, id: 'c', text: 'hit' }], hasMore: false } }));+ const result = await run(findTasksAction)({ projectId: 'P1', textContains: 'hit', maxResults: 2 });+ expect(result).toMatchObject({ truncated: true, nextCursor: 'b' });+ });+});++describe('get_task', () => {+ test('missing date and note become null after the task is found', async () => {+ const seen = stubFetch(+ route({+ 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } },+ 'GET /projects/P1/tasks/t1/date': NOT_FOUND,+ 'GET /projects/P1/tasks/t1/note': NOT_FOUND,+ 'GET /projects/P1/tasks/t1/assignees': { body: { ok: true, items: [{ handle: 'pieces' }] } },+ 'GET /projects/P1/tasks/t1/fields': { body: { ok: true, items: [{ fieldId: 'f1', value: 3 }] } },+ }),+ );+ const result = await run(getTaskAction)({ projectId: 'P1', taskId: 't1' });+ expect(result).toEqual({ ...NORMALIZED, date: null, note: null, assignees: [{ handle: 'pieces', displayName: null }], fields: [{ fieldId: 'f1', value: 3 }] });+ expect(seen).toHaveLength(5);+ });+ test('a missing task fails instead of returning empty details', async () => {+ const seen = stubFetch(() => NOT_FOUND);+ await expect(run(getTaskAction)({ projectId: 'P1', taskId: 't1' })).rejects.toThrow('404');+ expect(seen).toHaveLength(1);+ });+ test('details off makes one request', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: TASK } }));+ await expect(run(getTaskAction)({ projectId: 'P1', taskId: 't1', includeDetails: false })).resolves.toEqual(NORMALIZED);+ expect(seen).toHaveLength(1);+ });+});++describe('create_tasks', () => {+ test('bottom placement keeps order', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: [{ id: 'a', completed: false }, { id: 'b', completed: false }] } }));+ const result = await run(createTasksAction)({ projectId: 'P1', tasks: ['one', 'two'] });+ expect(seen[0].path).toBe('/projects/P1/tasks/');+ expect(seen[0].body).toEqual({+ tasks: [+ { contentType: 'text/markdown', content: 'one', placement: 'beforeend' },+ { contentType: 'text/markdown', content: 'two', placement: 'beforeend' },+ ],+ });+ expect(result).toEqual({ items: [{ id: 'a', text: 'one', completed: false }, { id: 'b', text: 'two', completed: false }], count: 2 });+ });+ test('top placement sends reversed so the list reads in order, and reverses the result back', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: [{ id: 'b' }, { id: 'a' }] } }));+ const result = await run(createTasksAction)({ projectId: 'P1', tasks: ['one', 'two'], position: 'top', format: 'text/plain' });+ expect(seen[0].body).toEqual({+ tasks: [+ { contentType: 'text/plain', content: 'two', placement: 'afterbegin' },+ { contentType: 'text/plain', content: 'one', placement: 'afterbegin' },+ ],+ });+ expect(result).toMatchObject({ items: [{ id: 'a', text: 'one' }, { id: 'b', text: 'two' }] });+ });+ test.each([+ ['before', 'beforebegin'],+ ['after', 'afterend'],+ ['first_child', 'afterbegin'],+ ['last_child', 'beforeend'],+ ])('%s uses %s with the anchor task', async (position, placement) => {+ const seen = stubFetch(() => ({ body: { ok: true, item: [{ id: 'a' }] } }));+ await run(createTasksAction)({ projectId: 'P1', tasks: ['one'], position, relativeToTaskId: 'anchor' });+ expect(seen[0].body).toEqual({ tasks: [{ contentType: 'text/markdown', content: 'one', placement, taskId: 'anchor' }] });+ });+ test.each([+ [{ tasks: [] }, 'at least one'],+ [{ tasks: Array.from({ length: 21 }, (_, i) => `t${i}`) }, 'at most 20'],+ [{ tasks: ['x'.repeat(2001)] }, 'at most 2000'],+ [{ tasks: ['a\nb'] }, 'single line'],+ [{ tasks: ['a'], position: 'after' }, 'Relative To Task ID is required'],+ ])('refuses %j before any request', async (props, message) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(createTasksAction)({ projectId: 'P1', ...props })).rejects.toThrow(message);+ expect(seen).toHaveLength(0);+ });+ test('accepts array items given as objects', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: [{ id: 'a' }] } }));+ await run(createTasksAction)({ projectId: 'P1', tasks: [{ content: 'obj' }] });+ expect(seen[0].body).toMatchObject({ tasks: [{ content: 'obj' }] });+ });+});++describe('task writes', () => {+ test('update_task refuses newlines and re-reads a partial item', async () => {+ const seen = stubFetch(replies([{ body: { ok: true, item: { id: 't1' } } }, { body: { ok: true, item: TASK } }]));+ await expect(run(updateTaskAction)({ projectId: 'P1', taskId: 't1', text: 'a\nb' })).rejects.toThrow('single line');+ expect(seen).toHaveLength(0);+ await expect(run(updateTaskAction)({ projectId: 'P1', taskId: 't1', text: 'Do it' })).resolves.toEqual(NORMALIZED);+ expect(seen[0].method).toBe('PUT');+ expect(seen[0].body).toEqual({ contentType: 'text/markdown', content: 'Do it' });+ expect(seen[1].method).toBe('GET');+ });+ test('complete_task_by_id on an already completed task (400) succeeds', async () => {+ stubFetch(route({ 'POST /projects/P1/tasks/t1/complete': BAD_REQUEST, 'GET /projects/P1/tasks/t1': { body: { ok: true, item: { ...TASK, completed: true } } } }));+ await expect(run(completeTaskByIdAction)({ projectId: 'P1', taskId: 't1' })).resolves.toMatchObject({ completed: true });+ });+ test('complete_task_by_id rethrows a 400 when the task is still open', async () => {+ stubFetch(route({ 'POST /projects/P1/tasks/t1/complete': BAD_REQUEST, 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } } }));+ await expect(run(completeTaskByIdAction)({ projectId: 'P1', taskId: 't1' })).rejects.toThrow('400');+ });+ test('reopen_task on an open task (400) succeeds', async () => {+ stubFetch(route({ 'POST /projects/P1/tasks/t1/uncomplete': BAD_REQUEST, 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } } }));+ await expect(run(reopenTaskAction)({ projectId: 'P1', taskId: 't1' })).resolves.toMatchObject({ completed: false });+ });+ test('delete_task_by_id: 200 deletes, 404 is already deleted once the project is confirmed', async () => {+ stubFetch(() => ({ body: { ok: true } }));+ await expect(run(deleteTaskByIdAction)({ projectId: 'P1', taskId: 't1' })).resolves.toEqual({ projectId: 'P1', taskId: 't1', deleted: true, alreadyDeleted: false });+ const seen = stubFetch(route({ 'DELETE /projects/P1/tasks/t1': NOT_FOUND, 'GET /projects/P1': { body: { ok: true, item: { id: 'P1' } } } }));+ await expect(run(deleteTaskByIdAction)({ projectId: 'P1', taskId: 't1' })).resolves.toMatchObject({ alreadyDeleted: true });+ expect(seen.map((r) => r.method)).toEqual(['DELETE', 'GET']);+ });+ test('delete_task_by_id fails when the project itself is missing', async () => {+ stubFetch(() => NOT_FOUND);+ await expect(run(deleteTaskByIdAction)({ projectId: 'P1', taskId: 't1' })).rejects.toThrow('get project failed (404');+ });+ test('delete_task_by_id rethrows other errors', async () => {+ stubFetch(() => ({ status: 403, body: { ok: false, message: 'no' } }));+ await expect(run(deleteTaskByIdAction)({ projectId: 'P1', taskId: 't1' })).rejects.toThrow('403');+ });+ test('move_task maps positions and refuses moving next to itself', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: TASK } }));+ await run(moveTaskAction)({ projectId: 'P1', taskId: 't1', targetTaskId: 't2', position: 'beforeend' });+ expect(seen[0].body).toEqual({ target: { taskId: 't2', position: 'beforeend' } });+ await run(moveTaskAction)({ projectId: 'P1', taskId: 't1', targetTaskId: 't2', position: 'before' });+ expect(seen[1].body).toEqual({ target: { taskId: 't2', position: 'beforebegin' } });+ await expect(run(moveTaskAction)({ projectId: 'P1', taskId: 't1', targetTaskId: 't1', position: 'afterend' })).rejects.toThrow('itself');+ await expect(run(moveTaskAction)({ projectId: 'P1', taskId: 't1', targetTaskId: 't2', position: 'sideways' })).rejects.toThrow('Position must be');+ });+});++describe('set_task_date', () => {+ test('date only', async () => {+ const seen = stubFetch(() => ({ body: { ok: true, item: { id: 't1' } } }));+ const result = await run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', startDate: '2026-10-20' });+ expect(seen[0].body).toEqual({ start: { date: '2026-10-20' } });+ expect(result).toEqual({ projectId: 'P1', taskId: 't1', cleared: false, date: { start: { date: '2026-10-20' } } });+ });+ test('same-day range with the end time after the start time is sent', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', startDate: '2026-10-20', startTime: '09:00', endDate: '2026-10-20', endTime: '17:00' });+ expect(seen[0].body).toEqual({ start: { date: '2026-10-20', time: '09:00' }, end: { date: '2026-10-20', time: '17:00' } });+ });+ test('range with times and timezone', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', startDate: '2026-10-20', startTime: '09:30', endDate: '2026-10-21', endTime: '17:00:00', timezone: 'Europe/Berlin' });+ expect(seen[0].body).toEqual({+ start: { date: '2026-10-20', time: '09:30', timezone: 'Europe/Berlin' },+ end: { date: '2026-10-21', time: '17:00:00', timezone: 'Europe/Berlin' },+ });+ });+ test.each([+ [{}, 'Start Date is required'],+ [{ startDate: '20-10-2026' }, 'YYYY-MM-DD'],+ [{ startDate: '2026-13-01' }, 'YYYY-MM-DD'],+ [{ startDate: '2026-02-30' }, 'real date'],+ [{ startDate: '2026-10-20', endDate: '2026-04-31' }, 'real date'],+ [{ startDate: '2026-10-20', startTime: '9am' }, 'HH:MM'],+ [{ startDate: '2026-10-20', endTime: '10:00' }, 'End Time needs End Date'],+ [{ startDate: '2026-10-20', endDate: '2026-10-19' }, 'on or after'],+ [{ startDate: '2026-10-20', startTime: '17:00', endDate: '2026-10-20', endTime: '09:00' }, 'is before Start Time'],+ [{ startDate: '2026-10-20', startTime: '09:00:30', endDate: '2026-10-20', endTime: '09:00' }, 'is before Start Time'],+ ])('refuses %j', async (props, message) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', ...props })).rejects.toThrow(message);+ expect(seen).toHaveLength(0);+ });+ test('clear sends DELETE; "Date does not exist" (400) counts as cleared when the task exists', async () => {+ const seen = stubFetch(+ route({+ 'DELETE /projects/P1/tasks/t1/date': { status: 400, body: { ok: false, code: 'BAD_REQUEST', message: 'Date does not exist' } },+ 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } },+ }),+ );+ await expect(run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', clearDate: true, startDate: 'ignored' })).resolves.toEqual({+ projectId: 'P1',+ taskId: 't1',+ cleared: true,+ date: null,+ });+ expect(seen.map((r) => r.method)).toEqual(['DELETE', 'GET']);+ });+ test('clear on a missing task fails', async () => {+ stubFetch(() => NOT_FOUND);+ await expect(run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', clearDate: true })).rejects.toThrow('404');+ });+ test('a different 400 on clear is rethrown', async () => {+ stubFetch(() => BAD_REQUEST);+ await expect(run(setTaskDateAction)({ projectId: 'P1', taskId: 't1', clearDate: true })).rejects.toThrow('400');+ });+});++describe('set_task_note', () => {+ test('sets a single-line note', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await expect(run(setTaskNoteAction)({ projectId: 'P1', taskId: 't1', note: 'hello', format: 'text/plain' })).resolves.toMatchObject({+ note: { type: 'text/plain', value: 'hello' },+ cleared: false,+ });+ expect(seen[0].method).toBe('PUT');+ expect(seen[0].body).toEqual({ type: 'text/plain', value: 'hello' });+ });+ test('refuses newlines and empty notes', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(setTaskNoteAction)({ projectId: 'P1', taskId: 't1', note: 'a\nb' })).rejects.toThrow('single line');+ await expect(run(setTaskNoteAction)({ projectId: 'P1', taskId: 't1', note: '' })).rejects.toThrow('Note is required');+ expect(seen).toHaveLength(0);+ });+ test('clear uses DELETE', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await expect(run(setTaskNoteAction)({ projectId: 'P1', taskId: 't1', clearNote: true })).resolves.toMatchObject({ cleared: true, note: null });+ expect(seen[0].method).toBe('DELETE');+ });+});++describe('assignees', () => {+ test('assign_task dedupes handles, strips @ and returns the full list', async () => {+ const seen = stubFetch(+ route({+ 'PUT /projects/P1/tasks/t1/assignees': { body: { ok: true, item: { id: 't1' } } },+ 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } },+ 'GET /projects/P1/tasks/t1/assignees': { body: { ok: true, items: [{ handle: 'pieces', displayName: 'P' }] } },+ }),+ );+ const result = await run(assignTaskAction)({ projectId: 'P1', taskId: 't1', handles: ['@pieces', 'pieces', ' '] });+ expect(seen[0].body).toEqual({ handles: ['pieces'] });+ expect(result).toEqual({ ...NORMALIZED, assignees: [{ handle: 'pieces', displayName: 'P' }] });+ });+ test('assign_task refuses an empty list', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(assignTaskAction)({ projectId: 'P1', taskId: 't1', handles: [] })).rejects.toThrow('at least one');+ expect(seen).toHaveLength(0);+ });+ test('unassign_task: a 400 for someone not assigned reports wasAssigned false', async () => {+ stubFetch(+ route({+ 'DELETE /projects/P1/tasks/t1/assignees/pieces': BAD_REQUEST,+ 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } },+ 'GET /projects/P1/tasks/t1/assignees': { body: { ok: true, items: [] } },+ }),+ );+ await expect(run(unassignTaskAction)({ projectId: 'P1', taskId: 't1', handle: '@pieces' })).resolves.toEqual({+ ...NORMALIZED,+ removedHandle: 'pieces',+ wasAssigned: false,+ });+ });+ test('unassign_task rethrows a 400 when the person is still assigned', async () => {+ stubFetch(+ route({+ 'DELETE /projects/P1/tasks/t1/assignees/pieces': BAD_REQUEST,+ 'GET /projects/P1/tasks/t1': { body: { ok: true, item: TASK } },+ 'GET /projects/P1/tasks/t1/assignees': { body: { ok: true, items: [{ handle: 'pieces' }] } },+ }),+ );+ await expect(run(unassignTaskAction)({ projectId: 'P1', taskId: 't1', handle: 'pieces' })).rejects.toThrow('400');+ });+});++describe('set_task_field_value', () => {+ const fields = {+ ok: true,+ items: [+ { id: 'num', data: { type: 'number', displayName: 'Points' } },+ { id: 'sel', data: { type: 'Select', displayName: 'Status', options: { x: { id: 'o1', name: 'Open', rank: 'a' } } } },+ { id: 'txt', data: { type: 'string', displayName: 'Notes' } },+ ],+ };+ function server() {+ return stubFetch((request) => (request.method === 'GET' ? { body: fields } : { body: { ok: true } }));+ }+ test('number fields get a number', async () => {+ const seen = server();+ await expect(run(setTaskFieldValueAction)({ projectId: 'P1', taskId: 't1', fieldId: 'num', value: '5' })).resolves.toMatchObject({ value: 5 });+ expect(seen[1].path).toBe('/projects/P1/tasks/t1/fields/num');+ expect(seen[1].body).toEqual({ value: 5 });+ });+ test('select fields accept an option name and send its id', async () => {+ const seen = server();+ await run(setTaskFieldValueAction)({ projectId: 'P1', taskId: 't1', fieldId: 'sel', value: 'open' });+ expect(seen[1].body).toEqual({ value: 'o1' });+ });+ test.each([+ [{ fieldId: 'num', value: 'abc' }, 'must be a number'],+ [{ fieldId: 'sel', value: 'Closed' }, 'not an option'],+ [{ fieldId: 'nope', value: '1' }, 'no custom field with ID "nope"'],+ [{ fieldId: 'nope', clearValue: true }, 'no custom field with ID "nope"'],+ [{ fieldId: 'txt' }, 'Value is required'],+ ])('refuses %j without writing', async (props, message) => {+ const seen = server();+ await expect(run(setTaskFieldValueAction)({ projectId: 'P1', taskId: 't1', ...props })).rejects.toThrow(message);+ expect(seen.filter((r) => r.method !== 'GET')).toHaveLength(0);+ });+ test('clear sends DELETE for a known field', async () => {+ const seen = server();+ await expect(run(setTaskFieldValueAction)({ projectId: 'P1', taskId: 't1', fieldId: 'txt', clearValue: true })).resolves.toMatchObject({ cleared: true, value: null });+ expect(seen[1].method).toBe('DELETE');+ });+});diff --git a/packages/pieces/community/taskade/test/trigger-automation.test.ts b/packages/pieces/community/taskade/test/trigger-automation.test.tsnew file mode 100644index 00000000000..0b8aad7c772--- /dev/null+++ b/packages/pieces/community/taskade/test/trigger-automation.test.ts@@ -0,0 +1,59 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { triggerAutomationAction } from '../src/lib/actions/trigger-automation';+import { run, stubFetch, TOKEN } from './helpers';++const URL_OK = 'https://www.taskade.com/webhooks/automation/abc123';++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('trigger_automation', () => {+ test('posts the payload without the personal access token', async () => {+ const seen = stubFetch(() => ({ body: { ok: true } }));+ await expect(run(triggerAutomationAction)({ webhookUrl: URL_OK, payload: { name: 'Jane' } })).resolves.toEqual({ status: 200, ok: true });+ expect(seen[0].url).toBe(URL_OK);+ expect(seen[0].method).toBe('POST');+ expect(seen[0].body).toEqual({ name: 'Jane' });+ expect(seen[0].auth).toBeNull();+ expect(JSON.stringify([...seen[0].headers])).not.toContain(TOKEN);+ });+ test('sends the webhook bearer token when given', async () => {+ const seen = stubFetch(() => ({ body: {} }));+ await run(triggerAutomationAction)({ webhookUrl: URL_OK, bearerToken: 'hook-secret' });+ expect(seen[0].auth).toBe('Bearer hook-secret');+ expect(seen[0].body).toEqual({});+ });+ test.each([+ 'http://www.taskade.com/webhooks/x',+ 'https://www.taskade.com.evil.io/webhooks/x',+ 'https://evil.io/webhooks/x',+ 'https://user:[email protected]/webhooks/x',+ 'https://www.taskade.com:8443/webhooks/x',+ 'https://www.taskade.com/api/v1/workspaces',+ 'not a url',+ ])('refuses %s before any request', async (webhookUrl) => {+ const seen = stubFetch(() => ({ body: {} }));+ await expect(run(triggerAutomationAction)({ webhookUrl })).rejects.toThrow('must be a Taskade webhook URL');+ expect(seen).toHaveLength(0);+ });+ test('refuses non-object payloads', async () => {+ stubFetch(() => ({ body: {} }));+ await expect(run(triggerAutomationAction)({ webhookUrl: URL_OK, payload: '[1,2]' })).rejects.toThrow('JSON object');+ await expect(run(triggerAutomationAction)({ webhookUrl: URL_OK, payload: '{bad' })).rejects.toThrow('valid JSON');+ });+ test.each([+ [401, 'Webhook Bearer Token'],+ [404, 'copy the current URL'],+ [402, 'Pro plan'],+ [500, 'HTTP 500'],+ ])('HTTP %s is explained', async (status, message) => {+ stubFetch(() => ({ status, body: { ok: false } }));+ await expect(run(triggerAutomationAction)({ webhookUrl: URL_OK })).rejects.toThrow(message);+ });+});diff --git a/packages/pieces/community/taskade/test/webhook.test.ts b/packages/pieces/community/taskade/test/webhook.test.tsnew file mode 100644index 00000000000..e16148da24a--- /dev/null+++ b/packages/pieces/community/taskade/test/webhook.test.ts@@ -0,0 +1,151 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { taskadeWebhook } from '../src/lib/common/webhook';+import { commentCreatedTrigger } from '../src/lib/triggers/comment-created';+import { projectAssignedTrigger } from '../src/lib/triggers/project-assigned';+import { projectCreatedTrigger } from '../src/lib/triggers/project-created';+import { projectJoinedTrigger } from '../src/lib/triggers/project-joined';+import { taskAssignedTrigger } from '../src/lib/triggers/task-assigned';+import { taskDueTrigger } from '../src/lib/triggers/task-due';+import { memoryStore, MemoryStore, runStep, stubFetch, taskadeConnection } from './helpers';++const SECRET = 'whsec-test';+const HOOK_URL = 'https://cloud.example.com/api/v1/webhooks/flow1';+const REGISTERED = { ok: true, webhook: { id: HOOK_URL, url: HOOK_URL, events: ['task.due'], spaceIds: [], createdAt: '2026-10-06T00:00:00Z' }, secret: SECRET };++function context({ store, propsValue = {}, payload }: { store: MemoryStore; propsValue?: Record<string, unknown>; payload?: unknown }) {+ return { auth: taskadeConnection(), propsValue, store, webhookUrl: HOOK_URL, payload };+}++function call<T>({ fn, ctx }: { fn: (ctx: never) => Promise<T>; ctx: unknown }): Promise<T> {+ return runStep(Reflect.apply(fn, taskDueTrigger, [ctx]));+}++function delivery({ body = { id: 't1', text: 'Due' }, secret = SECRET, header = 'X-Taskade-Signature' }: { body?: unknown; secret?: string; header?: string } = {}) {+ const raw = JSON.stringify(body);+ return { body, rawBody: raw, headers: { [header]: taskadeWebhook.sign({ secret, body: raw }) } };+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe('signature', () => {+ test('accepts the documented sha256= hex HMAC of the raw body, any header case', () => {+ const d = delivery({ header: 'x-taskade-signature' });+ expect(taskadeWebhook.verifySignature({ secret: SECRET, headers: d.headers, rawBody: d.rawBody })).toBe(true);+ expect(taskadeWebhook.verifySignature({ secret: SECRET, headers: d.headers, rawBody: Buffer.from(d.rawBody) })).toBe(true);+ });+ test('rejects wrong secret, tampered body, missing header, missing raw body and length mismatch', () => {+ const d = delivery();+ expect(taskadeWebhook.verifySignature({ secret: 'other', headers: d.headers, rawBody: d.rawBody })).toBe(false);+ expect(taskadeWebhook.verifySignature({ secret: SECRET, headers: d.headers, rawBody: `${d.rawBody} ` })).toBe(false);+ expect(taskadeWebhook.verifySignature({ secret: SECRET, headers: {}, rawBody: d.rawBody })).toBe(false);+ expect(taskadeWebhook.verifySignature({ secret: SECRET, headers: d.headers, rawBody: undefined })).toBe(false);+ expect(taskadeWebhook.verifySignature({ secret: SECRET, headers: { 'X-Taskade-Signature': 'sha256=abc' }, rawBody: d.rawBody })).toBe(false);+ });+});++describe('lifecycle', () => {+ test('onEnable registers the event for the chosen workspaces on v2 and stores id + secret', async () => {+ const seen = stubFetch(() => ({ body: REGISTERED }));+ const store = memoryStore();+ await call({ fn: taskDueTrigger.onEnable, ctx: context({ store, propsValue: { workspaceIds: ['W1', 'W1', ''] } }) });+ expect(seen[0].url).toBe('https://www.taskade.com/api/v2/webhooks');+ expect(seen[0].body).toEqual({ targetUrl: HOOK_URL, events: ['task.due'], spaceIds: ['W1'] });+ expect(store.read(taskadeWebhook.STORE_KEY)).toEqual({ id: HOOK_URL, secret: SECRET });+ });+ test('onEnable explains the Pro plan requirement on 402', async () => {+ stubFetch(() => ({ status: 402, body: { ok: false, code: 'PAYMENT_REQUIRED', message: 'Webhooks require a Pro plan or higher.' } }));+ await expect(call({ fn: taskDueTrigger.onEnable, ctx: context({ store: memoryStore() }) })).rejects.toThrow('Pro plan');+ });+ test('onEnable on 409 deletes the old registration for this URL and registers again', async () => {+ const seen = stubFetch((_request, index) => (index === 0 ? { status: 409, body: { ok: false } } : index === 1 ? { body: { ok: true, deleted: true } } : { body: REGISTERED }));+ await call({ fn: taskDueTrigger.onEnable, ctx: context({ store: memoryStore() }) });+ expect(seen.map((r) => r.method)).toEqual(['POST', 'DELETE', 'POST']);+ expect(seen[1].url).toBe(`https://www.taskade.com/api/v2/webhooks/${encodeURIComponent(HOOK_URL)}`);+ });+ test('onEnable deletes the webhook it created when store.put fails', async () => {+ const seen = stubFetch((request) => (request.method === 'POST' ? { body: REGISTERED } : { body: { ok: true, deleted: true } }));+ const store = memoryStore();+ store.put = async () => {+ throw new Error('store down');+ };+ await expect(call({ fn: taskDueTrigger.onEnable, ctx: context({ store }) })).rejects.toThrow('store down');+ expect(seen.map((r) => r.method)).toEqual(['POST', 'DELETE']);+ });+ test('onEnable fails when Taskade returns no secret', async () => {+ stubFetch(() => ({ body: { ok: true, webhook: { id: HOOK_URL } } }));+ await expect(call({ fn: taskDueTrigger.onEnable, ctx: context({ store: memoryStore() }) })).rejects.toThrow('signing secret');+ });+ test('onDisable deletes by encoded id and forgets state; 404 counts as deleted', async () => {+ const seen = stubFetch(() => ({ status: 404, body: { ok: false } }));+ const store = memoryStore({ [taskadeWebhook.STORE_KEY]: { id: HOOK_URL, secret: SECRET } });+ await call({ fn: taskDueTrigger.onDisable, ctx: context({ store }) });+ expect(seen[0].method).toBe('DELETE');+ expect(seen[0].path).toBe(`/webhooks/${encodeURIComponent(HOOK_URL)}`);+ expect(store.read(taskadeWebhook.STORE_KEY)).toBeUndefined();+ });+ test('onDisable keeps the stored id when the delete fails', async () => {+ stubFetch(() => ({ status: 500, body: { ok: false, message: 'boom' } }));+ const store = memoryStore({ [taskadeWebhook.STORE_KEY]: { id: HOOK_URL, secret: SECRET } });+ await expect(call({ fn: taskDueTrigger.onDisable, ctx: context({ store }) })).rejects.toThrow('boom');+ expect(store.read(taskadeWebhook.STORE_KEY)).toEqual({ id: HOOK_URL, secret: SECRET });+ });+});++describe('run', () => {+ function storeWithSecret() {+ return memoryStore({ [taskadeWebhook.STORE_KEY]: { id: HOOK_URL, secret: SECRET } });+ }+ test('emits every correctly signed delivery and writes no dedupe state, so a failed submission can be retried', async () => {+ const store = storeWithSecret();+ const payload = delivery();+ await expect(call({ fn: taskDueTrigger.run, ctx: context({ store, payload }) })).resolves.toEqual([payload.body]);+ await expect(call({ fn: taskDueTrigger.run, ctx: context({ store, payload }) })).resolves.toEqual([payload.body]);+ expect(store.read('taskade_webhook_seen')).toBeUndefined();+ });+ test('drops unsigned, badly signed and raw-body-less deliveries', async () => {+ const store = storeWithSecret();+ const good = delivery();+ await expect(call({ fn: taskDueTrigger.run, ctx: context({ store, payload: { ...good, headers: {} } }) })).resolves.toEqual([]);+ await expect(call({ fn: taskDueTrigger.run, ctx: context({ store, payload: delivery({ secret: 'wrong' }) }) })).resolves.toEqual([]);+ await expect(call({ fn: taskDueTrigger.run, ctx: context({ store, payload: { ...good, rawBody: undefined } }) })).resolves.toEqual([]);+ });+ test('without a stored registration nothing is emitted', async () => {+ await expect(call({ fn: taskDueTrigger.run, ctx: context({ store: memoryStore(), payload: delivery() }) })).resolves.toEqual([]);+ });+});++describe('trigger definitions', () => {+ test.each([+ [taskDueTrigger, 'task_due'],+ [taskAssignedTrigger, 'task_assigned'],+ [commentCreatedTrigger, 'comment_created'],+ [projectCreatedTrigger, 'project_created'],+ [projectAssignedTrigger, 'project_assigned'],+ [projectJoinedTrigger, 'project_joined'],+ ])('%s has sample data and an output schema covering its keys', (trigger, name) => {+ expect(trigger.name).toBe(name);+ const keys = (trigger.outputSchema?.fields ?? []).map((field) => field.key);+ expect(Object.keys(trigger.sampleData ?? {}).sort()).toEqual([...keys].sort());+ });+ test('each trigger registers its own event', async () => {+ const pairs: Array<[typeof taskDueTrigger, string]> = [+ [taskAssignedTrigger, 'task.assigned'],+ [commentCreatedTrigger, 'comment.created'],+ [projectCreatedTrigger, 'project.created'],+ [projectAssignedTrigger, 'project.assigned'],+ [projectJoinedTrigger, 'project.joined'],+ ];+ for (const [trigger, event] of pairs) {+ const seen = stubFetch(() => ({ body: REGISTERED }));+ await runStep(Reflect.apply(trigger.onEnable, trigger, [context({ store: memoryStore() })]));+ expect(seen[0].body).toMatchObject({ events: [event], spaceIds: [] });+ }+ });+});diff --git a/packages/pieces/community/taskade/vitest.config.ts b/packages/pieces/community/taskade/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/taskade/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})