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(chat): hand focused goals to task agents (#16130)
Hazem Adelfcfb11c4f68c
diff --git a/brain/knowledge/decisions/000048-chat-sub-agents-are-general-task-runners.md b/brain/knowledge/decisions/000048-chat-sub-agents-are-general-task-runners.mdnew file mode 100644index 00000000000..aab753ab38e--- /dev/null+++ b/brain/knowledge/decisions/000048-chat-sub-agents-are-general-task-runners.md@@ -0,0 +1,23 @@+---+title: Chat sub-agents are general task runners, not role tools+status: accepted+icon: 🧵+---++# Chat sub-agents are general task runners, not role tools++## Decision++The chat has one delegation tool, `ap_run_task`. A task gets the same tools as the main chat, apart from the user-facing ones, plus a fresh context and one goal. Building, verifying, debugging and research are just different briefs. Tasks are stored per conversation in `agent_task`, and the same sub-agent can be resumed.++## Context++The first version (#16130) was a flow-builder-only sub-agent. 000046 planned separate architect, builder, verifier and debug roles. In practice, the work worth delegating (researching an app, triaging hundreds of records, fixing a failed run) did not fit a builder.++## Why++The value is the small, focused context, not a special toolset. One general tool keeps the main prompt small and avoids a tool per role. We rejected fresh sub-agents on every call: blocked tasks and follow-up edits would lose everything the task had learned.++## Consequences++Tasks cannot ask the user questions. They finish as `blocked`, and the main chat asks instead. They can still trigger approvals, which show the task's name. Parallel tasks need ownership written into their briefs, because flow draft edits are last-write-wins. Nesting is one level deep.diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.mdindex 07cc0225d13..82231fff95d 100644--- a/brain/knowledge/flows-execution/chat.md+++ b/brain/knowledge/flows-execution/chat.md@@ -56,6 +56,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **`ap_set_phase` and `ap_load_guide` are gone.** Skills replaced both: `ap_load_skill` returns the guide and its tools' schemas, and the build phase flips on its own. `BUILD_ONLY_TOOL_NAMES` now only decides when thinking turns on, and only hides tools on surfaces outside skills mode. The web app keeps both names so old conversations still render.- **Read-only checks don't belong in `BUILD_ONLY_TOOL_NAMES`.** `ap_validate_flow` was in it, so "check that this solution fits together" never saw the tool. The agent inspected flows by hand instead and misread a Call Flow `flowId` (an externalId) as a mismatch with the flow's id. It now stays visible in discovery, like `ap_flow_structure`.- **A dynamic property only runs with a saved schema.** The engine processes a `DYNAMIC` prop's sub-fields (JSON parse, numbers, arrays) only from `propertySettings[prop].schema`, which the builder saves when it resolves the prop. Chat tools used to save `propertySettings: {}`, so an advanced-mode Call Flow payload reached the subflow as one string and a live run saved empty fields. `mcpUtils.resolveDynamicPropertySettings` now resolves and saves it on build, add and update.+- **Focused goals run as task sub-agents.** `ap_run_task` (`task-subagent-tools.ts`) runs a second `runAgentTurn` with a fresh context and the main's tools, minus anything that talks to the user, nests, tests, publishes or flips flow status. The prompt is `task-subagent-prompt.md`. Tasks start in the build phase with their own `ap_set_phase`: any tool whose closure holds run state must be rebuilt per task, because reusing the main's copy flipped the main's phase. A task must end with `updateTaskStatus`. If it's cut off it continues (up to 2 times), and if it forgets to report it gets one forced report step, so `failed` is rare and the main retries it. Histories live in `agent_task`, so `taskId` resumes the same sub-agent. Approvals inside a task carry `taskTitle` (via `AsyncLocalStorage`). Flat-billed calls come back as `billedToolCalls`, and `toModelOutput` keeps the card data out of the main's context. Delegation happens only when it buys something: multi-flow solutions build in dependency waves, one task per flow; single flows stay with the main.- **Capability notes are built where `discoveryOnly` is not known, so a prompt can promise tools the worker has stripped.** `getAgentConfig` composes the system prompt in the api, while `discoveryOnly` rides on the job data; before Aug 2026 it never crossed that boundary. Meanwhile the worker strips image tools, email tools and the agent tools on such a run, so the notes claimed all three. Two of the three had been wrong since long before anyone noticed, because each note computed its own availability term. The flag now travels with the config request and the three notes read one shared `actingRun = !dryRun && !discoveryOnly`. Whenever a tool group is gated on a run mode in the worker, the note that advertises it has to be gated on the same term, in one place.- **Tool output can't be trusted to waive a charge.** A user's own MCP server or `ap_run_code` controls its output's top-level keys, and they reach the persisted part unchanged. Chat billing only honours `billedAtCost` from `ap_web_search` and `ap_generate_image`; a new built-in tool that bills at cost must be added to `TOOLS_THAT_BILL_AT_COST` in `chatBilling`.- **Credits are checked after every step, not just before the turn.** `runAgentTurn` asks the API (`agentHasCredits`) after each tool step, sending what the turn has used so far (`chatBilling.creditsForTurn`, the same rule end-of-turn billing uses), and stops once the remaining balance no longer covers it. Flat credits are only charged when the turn ends, so without that pending count the balance never moves mid-turn. The check fails open if the RPC errors.@@ -70,6 +71,8 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **On a saved-agent run, choosing a different account in the connection card does nothing.** `onConnectionSelected` writes into `selectedConnectionByPiece` (`execute-agent-run.ts`), which is read only through `getSelectedAuth`, passed only to the MCP tool set — and `AgentRunSource.AGENT` is not granted `groups.mcp` at all. Configured piece tools carry the agent's stored `pieceMetadata` auth instead. So the card reports the account as connected while the tool keeps calling on the pinned one. Only the in-place Reconnect actually repairs an agent run, because it re-authorizes the same connection row the agent is pinned to. So `/v1/agents/conversations/:id/connections` answers `{ connections, reconnectOnly }`, and for an `AGENT`-source conversation returns only the accounts that agent's tools pin. Three things that branch has to get right, each of which was a live bug first: match on `(projectId, externalId)`, because `externalId` is caller-supplied and its index is **not** unique, so a same-id row in another project can pose as the pinned one; read the pin through `published ?? draft`, the same as the run; and unwrap the pre-0.87 `{{connections['id']}}` template form, or an older agent reads as having no pinned account and the card tells the user their live account is gone. The card must also carry the row's own `projectId` into the reconnect dialog, which otherwise falls back to the session project and repairs the wrong one.+- **A task agent's cost is steps × context, and a cache read isn't free.** A cache read still costs 10% of the normal input price, so a 30-step task over a 30k context costs about $0.60 on Sonnet even with 92% cache hits. Three things broke task cost (measured 2026-10-11): a status-only step every other step (tasks get no `ap_update_thinking_status`; the card falls back to the latest tool title), a report turn that swapped the tool set (any change to the tools, or `activeTools`, re-writes the whole cached context: 25–44k at write price), and researchers on Sonnet with full 128KB pages. After the fixes a researcher costs 3–5¢ on Haiku. Builds are the opposite: a task per flow costs $0.21–0.38 because it repeats the chat's setup, while the main chat builds four flows with parallel `ap_build_flow` calls for about $0.51, so builds stay in the main chat.+- **The chat's internal MCP token lives as long as a turn can (2 hours), not 15 minutes.** It's issued once per turn by `issueChatTurnAccessToken` (called from `agentMcp.getCredentials`) and kept in worker memory. `issueInternalAccessToken`, which the `/mcp-server/token` route hands to callers, keeps 15 minutes. With the 15-minute outside-client lifetime, any turn that waited on a card long enough lost every `ap_*` tool with "authentication failed" and stopped half done. Outside MCP clients keep their 15-minute tokens.### Key filesdiff --git a/bun.lock b/bun.lockindex 5dc60e1b142..6994b83862f 100644--- a/bun.lock+++ b/bun.lock@@ -167,7 +167,7 @@},"packages/core/shared": {"name": "@activepieces/shared",- "version": "0.201.1",+ "version": "0.201.2","dependencies": {"@activepieces/core-execution": "workspace:*","@activepieces/core-formula": "workspace:*",@@ -631,7 +631,7 @@},"packages/pieces/community/amazon-textract": {"name": "@activepieces/piece-amazon-textract",- "version": "0.3.9",+ "version": "0.3.10","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -2955,7 +2955,7 @@},"packages/pieces/community/emailit": {"name": "@activepieces/piece-emailit",- "version": "0.2.0",+ "version": "0.2.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3227,7 +3227,7 @@},"packages/pieces/community/firecrawl": {"name": "@activepieces/piece-firecrawl",- "version": "0.6.0",+ "version": "0.6.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3899,7 +3899,7 @@},"packages/pieces/community/google-drive": {"name": "@activepieces/piece-google-drive",- "version": "0.12.1",+ "version": "0.12.2","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4814,7 +4814,7 @@},"packages/pieces/community/json": {"name": "@activepieces/piece-json",- "version": "0.1.13",+ "version": "0.1.14","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -5945,7 +5945,7 @@},"packages/pieces/community/microsoft-outlook": {"name": "@activepieces/piece-microsoft-outlook",- "version": "0.7.2",+ "version": "0.7.3","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6022,7 +6022,7 @@},"packages/pieces/community/microsoft-teams": {"name": "@activepieces/piece-microsoft-teams",- "version": "0.7.2",+ "version": "0.7.3","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8623,7 +8623,7 @@},"packages/pieces/community/smartsuite": {"name": "@activepieces/piece-smartsuite",- "version": "0.3.0",+ "version": "0.3.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/core/execution/src/lib/workers/agent-events.ts b/packages/core/execution/src/lib/workers/agent-events.tsindex c01d4c57588..7f4d3fdb8ab 100644--- a/packages/core/execution/src/lib/workers/agent-events.ts+++ b/packages/core/execution/src/lib/workers/agent-events.ts@@ -9,6 +9,7 @@ export enum AgentEventType {IMAGE = 'IMAGE',FILE = 'FILE',BUILD_PLAN = 'BUILD_PLAN',+ SUBAGENT_PROGRESS = 'SUBAGENT_PROGRESS',}export type ToolProgressEvent = {@@ -34,6 +35,7 @@ export type ActionPreviewEvent = {isBatch: booleanbatchCount?: numberbatchSamples?: Record<string, unknown>[]+ taskTitle?: string}export type ActionReceiptEvent = {@@ -91,6 +93,25 @@ export type BuildPlanEvent = {updatedAt: string}+export type SubagentActivity = {+ taskId?: string+ title: string+ status: 'running' | 'done' | 'blocked' | 'failed'+ statusLine?: string+ stepCount: number+ pieces?: string[]+ artifacts?: { type: string, id: string, name: string }[]+ needs?: string+ summary?: string+ startedAt: string+ durationMs?: number+}++export type SubagentProgressEvent = {+ toolCallId: string+ data: SubagentActivity+}+export type AgentEvent =| { type: AgentEventType.CHUNK, data: unknown }| { type: AgentEventType.FINISHED, data: { conversationId: string } }@@ -102,3 +123,4 @@ export type AgentEvent =| { type: AgentEventType.IMAGE, data: ImageGeneratedEvent }| { type: AgentEventType.FILE, data: FileProducedEvent }| { type: AgentEventType.BUILD_PLAN, data: BuildPlanEvent }+ | { type: AgentEventType.SUBAGENT_PROGRESS, data: SubagentProgressEvent }diff --git a/packages/core/execution/src/lib/workers/worker-contract.ts b/packages/core/execution/src/lib/workers/worker-contract.tsindex 2d7e536930b..702ec9630d6 100644--- a/packages/core/execution/src/lib/workers/worker-contract.ts+++ b/packages/core/execution/src/lib/workers/worker-contract.ts@@ -89,6 +89,8 @@ export type WorkerToApiContract = {sendAgentEvent(input: SendAgentEventRequest): Promise<void>getAgentConfig(input: GetAgentConfigRequest): Promise<AgentConfigResponse>saveAgentMessages(input: SaveAgentMessagesRequest): Promise<void>+ beginAgentTask(input: BeginAgentTaskRequest): Promise<BeginAgentTaskResponse>+ finishAgentTask(input: FinishAgentTaskRequest): Promise<void>saveAgentFile(input: SaveAgentFileRequest): Promise<SaveAgentFileResponse>readAgentFile(input: ReadAgentFileRequest): Promise<ReadFlowStepFileResponse>updateAgentProgress(input: UpdateAgentProgressRequest): Promise<void>@@ -174,6 +176,7 @@ export type AgentConfigResponse = {mcpCredentials: { mcpServerUrl: string, mcpToken: string } | nullprojects: Array<{ id: string, displayName: string, type: string }>guides: Record<string, string>+ taskSystemPrompt?: stringaiTools: AgentAiToolsConfigemailEnabled: booleanagentsAvailable: boolean@@ -199,6 +202,30 @@ export type SaveAgentMessagesRequest = {failure?: { message: string, userMessage?: string }}+export type BeginAgentTaskRequest = {+ platformId: string+ conversationId: string+ title: string+ taskId?: string+}++export type BeginAgentTaskResponse = {+ taskId: string+ claimId: string+ messages: unknown[]+}++export type FinishAgentTaskRequest = {+ platformId: string+ conversationId: string+ taskId: string+ claimId: string+ status: 'DONE' | 'BLOCKED' | 'FAILED'+ messages: unknown[]+ summary: string | null+ artifacts: { type: string, id: string, name: string }[]+}+export type AgentTurnModel = {provider: AIProviderNamemodelId: stringdiff --git a/packages/core/piece-types/src/lib/ai-providers.test.ts b/packages/core/piece-types/src/lib/ai-providers.test.tsindex 4373cad6fd8..fdd76c4c65b 100644--- a/packages/core/piece-types/src/lib/ai-providers.test.ts+++ b/packages/core/piece-types/src/lib/ai-providers.test.ts@@ -117,14 +117,14 @@ describe('managed chat model vocabulary', () => {})describe('canDisableReasoning', () => {- it('is true for every tier model, so the default path keeps its zero-reasoning first step', () => {- for (const tier of ACTIVEPIECES_CHAT_TIERS) {- expect(aiProviderUtils.canDisableReasoning({ modelId: tier.modelId }), tier.modelId).toBe(true)+ it('is true for the models observed accepting a disable directive', () => {+ for (const id of ['anthropic/claude-haiku-4.5', 'anthropic/claude-sonnet-4.6', 'deepseek/deepseek-v4.1-flash']) {+ expect(aiProviderUtils.canDisableReasoning({ modelId: id }), id).toBe(true)}})- it('is false for the reasoning-native models that rejected a disable directive in production', () => {- for (const id of ['google/gemini-3.8-flash', 'openai/gpt-6-astra', 'openai/gpt-6-astra-pro', 'anthropic/claude-fable-5.1']) {+ it('is false for the reasoning-native models that rejected a disable directive', () => {+ for (const id of ['google/gemini-3.8-flash', 'openai/gpt-6-astra', 'openai/gpt-6-astra-pro', 'anthropic/claude-fable-5.1', 'minimax/minimax-m3', 'z-ai/glm-5.3']) {expect(aiProviderUtils.canDisableReasoning({ modelId: id }), id).toBe(false)}})diff --git a/packages/core/piece-types/src/lib/ai-providers.ts b/packages/core/piece-types/src/lib/ai-providers.tsindex 5e10daeb668..58c7bb1f66a 100644--- a/packages/core/piece-types/src/lib/ai-providers.ts+++ b/packages/core/piece-types/src/lib/ai-providers.ts@@ -245,7 +245,10 @@ const DEPRECATED_CHAT_MODELS_BY_PROVIDER: Partial<Record<AIProviderName, readonl[AIProviderName.VERTEX]: DEPRECATED_GOOGLE_CHAT_MODELS,}-const REASONING_OPTIONAL_CHAT_MODELS: readonly string[] = ANTHROPIC_OPENROUTER_CHAT_MODELS.map((model) => `${AIProviderName.ANTHROPIC}/${model}`)+const REASONING_OPTIONAL_CHAT_MODELS: readonly string[] = [+ ...ANTHROPIC_OPENROUTER_CHAT_MODELS.map((model) => `${AIProviderName.ANTHROPIC}/${model}`),+ 'deepseek/deepseek-v4.1-flash',+]export const ALLOWED_CHAT_MODELS_BY_PROVIDER: Partial<Record<AIProviderName, readonly string[]>> = {[AIProviderName.OPENAI]: OPENAI_CHAT_MODELS,diff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex 01b0bccc3a5..51138b7f32f 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.201.1",+ "version": "0.201.2","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/ee/agent/index.ts b/packages/core/shared/src/lib/ee/agent/index.tsindex 30d15049bea..17c612ac9b7 100644--- a/packages/core/shared/src/lib/ee/agent/index.ts+++ b/packages/core/shared/src/lib/ee/agent/index.ts@@ -247,6 +247,33 @@ export const UserMemory = z.object({})export type UserMemory = z.infer<typeof UserMemory>+export enum SubagentTaskStatus {+ RUNNING = 'RUNNING',+ DONE = 'DONE',+ BLOCKED = 'BLOCKED',+ FAILED = 'FAILED',+}++export const SubagentTaskArtifact = z.object({+ type: z.string(),+ id: z.string(),+ name: z.string(),+})+export type SubagentTaskArtifact = z.infer<typeof SubagentTaskArtifact>++export const SubagentTask = z.object({+ ...BaseModelSchema,+ platformId: z.string(),+ projectId: Nullable(z.string()),+ conversationId: z.string(),+ title: z.string(),+ status: z.enum(SubagentTaskStatus),+ messages: z.array(z.record(z.string(), z.unknown())).default([]),+ summary: Nullable(z.string()),+ artifacts: z.array(SubagentTaskArtifact).default([]),+})+export type SubagentTask = z.infer<typeof SubagentTask>+export const GetAgentMemoryResponse = z.object({instructions: z.string().nullable(),memories: z.array(z.string()),diff --git a/packages/core/shared/src/lib/ee/agent/tool-skills.ts b/packages/core/shared/src/lib/ee/agent/tool-skills.tsindex f689230154d..ebdf22aa1b0 100644--- a/packages/core/shared/src/lib/ee/agent/tool-skills.ts+++ b/packages/core/shared/src/lib/ee/agent/tool-skills.ts@@ -100,6 +100,7 @@ const CORE_TOOL_NAMES: Record<SkillSurface, readonly string[]> = {'ap_get_piece_props','ap_resolve_property_options','ap_resolve_property_chain',+ 'ap_run_task',],AGENT: [LOAD_SKILL_NAME,diff --git a/packages/core/shared/test/ee/agent-tool-phases.test.ts b/packages/core/shared/test/ee/agent-tool-phases.test.tsindex 73ec838756c..7aced744bfd 100644--- a/packages/core/shared/test/ee/agent-tool-phases.test.ts+++ b/packages/core/shared/test/ee/agent-tool-phases.test.ts@@ -10,6 +10,7 @@ const ALL = ['ap_validate_flow','ap_show_questions','ap_build_flow',+ 'ap_run_task','ap_add_step','ap_test_flow','ap_lock_and_publish',@@ -37,7 +38,7 @@ describe('agentToolPhases.activeToolsForPhase', () => {it('keeps read/discovery tools available in both phases', () => {const discovery = agentToolPhases.activeToolsForPhase({ phase: 'discovery', allToolNames: ALL })const build = agentToolPhases.activeToolsForPhase({ phase: 'build', allToolNames: ALL })- for (const tool of ['ap_research_pieces', 'ap_get_piece_props', 'ap_list_connections', 'ap_explore_data', 'ap_validate_flow']) {+ for (const tool of ['ap_research_pieces', 'ap_get_piece_props', 'ap_list_connections', 'ap_explore_data', 'ap_validate_flow', 'ap_run_task']) {expect(discovery).toContain(tool)expect(build).toContain(tool)}diff --git a/packages/core/shared/test/ee/agent-tool-skills.test.ts b/packages/core/shared/test/ee/agent-tool-skills.test.tsindex 0d1b5ffbf32..0836b1327f8 100644--- a/packages/core/shared/test/ee/agent-tool-skills.test.ts+++ b/packages/core/shared/test/ee/agent-tool-skills.test.ts@@ -63,6 +63,10 @@ describe('agentToolSkills', () => {expect(names).toEqual(['mcp__gmail__send'])})+ it('attaches the task tool to chat directly, so the chat can decide to delegate before loading any skill', () => {+ expect(CORE_TOOL_NAMES.CHAT).toContain('ap_run_task')+ })+it('renders a sorted one-line catalog', () => {const catalog = agentToolSkills.renderToolCatalog({ tools: [{ name: 'b_tool', description: 'Does b. More text.' }, { name: 'a_tool' }] })expect(catalog).toBe('- a_tool — \n- b_tool — Does b.')diff --git a/packages/server/api/src/app/database/database-connection.ts b/packages/server/api/src/app/database/database-connection.tsindex c5aeb156f92..37027f53738 100644--- a/packages/server/api/src/app/database/database-connection.ts+++ b/packages/server/api/src/app/database/database-connection.ts@@ -12,6 +12,7 @@ import { OtpEntity } from '../authentication/otp/otp-entity'import { UserIdentityEntity } from '../authentication/user-identity/user-identity-entity'import { AgentConversationEntity } from '../ee/agent/agent-conversation-entity'import { AgentEntity } from '../ee/agent/agent-entity'+import { AgentTaskEntity } from '../ee/agent/agent-task-entity'import { ChatRolloutUserEntity } from '../ee/agent/chat-rollout-user-entity'import { ChatPersonalizationEntity } from '../ee/agent/personalization/chat-personalization-entity'import { UserMemoryEntity } from '../ee/agent/user-memory-entity'@@ -115,6 +116,7 @@ function getEntities(): EntitySchema<unknown>[] {ToolSearchIndexEntity,AgentEntity,AgentConversationEntity,+ AgentTaskEntity,ChatPersonalizationEntity,ChatRolloutUserEntity,UserMemoryEntity,diff --git a/packages/server/api/src/app/database/migration/postgres/1867000000000-AddAgentTask.ts b/packages/server/api/src/app/database/migration/postgres/1867000000000-AddAgentTask.tsnew file mode 100644index 00000000000..f7b1288c224--- /dev/null+++ b/packages/server/api/src/app/database/migration/postgres/1867000000000-AddAgentTask.ts@@ -0,0 +1,53 @@+import { QueryRunner } from 'typeorm'+import { Migration } from '../../migration'++export class AddAgentTask1867000000000 implements Migration {+ name = 'AddAgentTask1867000000000'+ breaking = false+ release = '0.93.0'++ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ CREATE TABLE IF NOT EXISTS "agent_task" (+ "id" character varying(21) NOT NULL,+ "created" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),+ "updated" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),+ "platformId" character varying(21) NOT NULL,+ "projectId" character varying(21),+ "conversationId" character varying(21) NOT NULL,+ "title" character varying NOT NULL,+ "status" character varying NOT NULL,+ "messages" jsonb NOT NULL DEFAULT '[]',+ "summary" character varying,+ "artifacts" jsonb NOT NULL DEFAULT '[]',+ "claimId" character varying(21),+ CONSTRAINT "pk_agent_task" PRIMARY KEY ("id")+ )+ `)+ await queryRunner.query(`+ CREATE INDEX IF NOT EXISTS "idx_agent_task_platform_conversation_created" ON "agent_task" ("platformId", "conversationId", "created")+ `)+ await queryRunner.query(`+ DO $$+ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_agent_task_platform_id') THEN+ ALTER TABLE "agent_task" ADD CONSTRAINT "fk_agent_task_platform_id" FOREIGN KEY ("platformId") REFERENCES "platform"("id") ON DELETE CASCADE ON UPDATE NO ACTION;+ END IF;+ END $$+ `)+ await queryRunner.query(`+ DO $$+ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'fk_agent_task_conversation_id') THEN+ ALTER TABLE "agent_task" ADD CONSTRAINT "fk_agent_task_conversation_id" FOREIGN KEY ("conversationId") REFERENCES "agent_conversation"("id") ON DELETE CASCADE ON UPDATE NO ACTION;+ END IF;+ END $$+ `)+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`+ DROP TABLE IF EXISTS "agent_task"+ `)+ }+}diff --git a/packages/server/api/src/app/database/postgres-connection.ts b/packages/server/api/src/app/database/postgres-connection.tsindex 2a188f75af4..4374d32ee0f 100644--- a/packages/server/api/src/app/database/postgres-connection.ts+++ b/packages/server/api/src/app/database/postgres-connection.ts@@ -455,6 +455,7 @@ import { AddEventDestinationHeaders1863000000000 } from './migration/postgres/18import { AddPlatformTierFastAndConversationTier1864000000000 } from './migration/postgres/1864000000000-AddPlatformTierFastAndConversationTier'import { AddAuditLogRetentionDaysToPlatform1865000000000 } from './migration/postgres/1865000000000-AddAuditLogRetentionDaysToPlatform'import { AddAiSpecificModelsVisibleToPlatformConfiguration1866000000000 } from './migration/postgres/1866000000000-AddAiSpecificModelsVisibleToPlatformConfiguration'+import { AddAgentTask1867000000000 } from './migration/postgres/1867000000000-AddAgentTask'const getSslConfig = (): boolean | TlsOptions => {const useSsl = system.get(AppSystemProp.POSTGRES_USE_SSL)@@ -928,6 +929,7 @@ export const getMigrations = (): (new () => Migration)[] => {AddPlatformTierFastAndConversationTier1864000000000,AddAuditLogRetentionDaysToPlatform1865000000000,AddAiSpecificModelsVisibleToPlatformConfiguration1866000000000,+ AddAgentTask1867000000000,]return migrations}diff --git a/packages/server/api/src/app/ee/agent/agent-approval-gate.ts b/packages/server/api/src/app/ee/agent/agent-approval-gate.tsindex d8ff53db8a4..42d81904c70 100644--- a/packages/server/api/src/app/ee/agent/agent-approval-gate.ts+++ b/packages/server/api/src/app/ee/agent/agent-approval-gate.ts@@ -208,4 +208,5 @@ type PendingGate = {displayName: stringtoolInput: Record<string, unknown>runId?: string+ taskTitle?: string}diff --git a/packages/server/api/src/app/ee/agent/agent-rpc-handlers.ts b/packages/server/api/src/app/ee/agent/agent-rpc-handlers.tsindex 73a8988b37c..1458edd922a 100644--- a/packages/server/api/src/app/ee/agent/agent-rpc-handlers.ts+++ b/packages/server/api/src/app/ee/agent/agent-rpc-handlers.ts@@ -4,6 +4,7 @@ import { agentConfigRpc } from './rpc/agent-config-rpc'import { conversationRpc } from './rpc/conversation-rpc'import { emailRpc } from './rpc/email-rpc'import { flowStepRpc } from './rpc/flow-step-rpc'+import { taskRpc } from './rpc/task-rpc'import { toolExecutionRpc } from './rpc/tool-execution-rpc'export const agentRpcHandlers = (log: FastifyBaseLogger) => ({@@ -12,4 +13,5 @@ export const agentRpcHandlers = (log: FastifyBaseLogger) => ({...flowStepRpc(log),...toolExecutionRpc(log),...emailRpc(log),+ ...taskRpc(log),})diff --git a/packages/server/api/src/app/ee/agent/agent-task-entity.ts b/packages/server/api/src/app/ee/agent/agent-task-entity.tsnew file mode 100644index 00000000000..b216f937665--- /dev/null+++ b/packages/server/api/src/app/ee/agent/agent-task-entity.ts@@ -0,0 +1,82 @@+import { AgentConversation, Platform, SubagentTask } from '@activepieces/shared'+import { EntitySchema } from 'typeorm'+import { ApIdSchema, BaseColumnSchemaPart } from '../../database/database-common'++type AgentTaskWithRelations = SubagentTask & {+ claimId: string | null+ platform: Platform+ conversation: AgentConversation+}++export const AgentTaskEntity = new EntitySchema<AgentTaskWithRelations>({+ name: 'agent_task',+ columns: {+ ...BaseColumnSchemaPart,+ platformId: {+ ...ApIdSchema,+ nullable: false,+ },+ projectId: {+ ...ApIdSchema,+ nullable: true,+ },+ conversationId: {+ ...ApIdSchema,+ nullable: false,+ },+ title: {+ type: String,+ nullable: false,+ },+ status: {+ type: String,+ nullable: false,+ },+ messages: {+ type: 'jsonb',+ nullable: false,+ default: '[]',+ },+ summary: {+ type: String,+ nullable: true,+ },+ artifacts: {+ type: 'jsonb',+ nullable: false,+ default: '[]',+ },+ claimId: {+ ...ApIdSchema,+ nullable: true,+ },+ },+ indices: [+ {+ name: 'idx_agent_task_platform_conversation_created',+ columns: ['platformId', 'conversationId', 'created'],+ },+ ],+ relations: {+ platform: {+ type: 'many-to-one',+ target: 'platform',+ cascade: true,+ onDelete: 'CASCADE',+ joinColumn: {+ name: 'platformId',+ foreignKeyConstraintName: 'fk_agent_task_platform_id',+ },+ },+ conversation: {+ type: 'many-to-one',+ target: 'agent_conversation',+ cascade: true,+ onDelete: 'CASCADE',+ joinColumn: {+ name: 'conversationId',+ foreignKeyConstraintName: 'fk_agent_task_conversation_id',+ },+ },+ },+})diff --git a/packages/server/api/src/app/ee/agent/agent-task-service.ts b/packages/server/api/src/app/ee/agent/agent-task-service.tsnew file mode 100644index 00000000000..6252a5fb1e3--- /dev/null+++ b/packages/server/api/src/app/ee/agent/agent-task-service.ts@@ -0,0 +1,89 @@+import { ActivepiecesError, apId, ErrorCode, isNil, isObject, sanitizeObjectForPostgresql } from '@activepieces/core-utils'+import { MAX_AGENT_TURN_WALL_CLOCK_MS, SubagentTask, SubagentTaskArtifact, SubagentTaskStatus } from '@activepieces/shared'+import dayjs from 'dayjs'+import { repoFactory } from '../../core/db/repo-factory'+import { agentHelpers } from './agent-helpers'+import { AgentTaskEntity } from './agent-task-entity'++const agentTaskRepo = repoFactory(AgentTaskEntity)++async function begin({ platformId, conversationId, title, taskId }: {+ platformId: string+ conversationId: string+ title: string+ taskId?: string+}): Promise<{ taskId: string, claimId: string, messages: Record<string, unknown>[] }> {+ const claimId = apId()+ if (isNil(taskId)) {+ const conversation = await agentHelpers.conversationRepo().findOneBy({ id: conversationId, platformId })+ if (isNil(conversation)) {+ throw new ActivepiecesError({ code: ErrorCode.ENTITY_NOT_FOUND, params: { entityType: 'agent_conversation', entityId: conversationId } })+ }+ const id = apId()+ await agentTaskRepo().insert({+ id,+ platformId,+ projectId: conversation.projectId ?? null,+ conversationId,+ title,+ status: SubagentTaskStatus.RUNNING,+ messages: [],+ summary: null,+ artifacts: [],+ claimId,+ })+ return { taskId: id, claimId, messages: [] }+ }+ const staleBefore = dayjs().subtract(MAX_AGENT_TURN_WALL_CLOCK_MS, 'millisecond').toISOString()+ const claimed = await agentTaskRepo().createQueryBuilder()+ .update()+ .set({ status: SubagentTaskStatus.RUNNING, title, claimId })+ .where('id = :taskId AND "platformId" = :platformId AND "conversationId" = :conversationId', { taskId, platformId, conversationId })+ .andWhere('(status != :running OR updated < :staleBefore)', { running: SubagentTaskStatus.RUNNING, staleBefore })+ .returning(['id', 'messages'])+ .execute()+ const claimedRows: unknown = claimed.raw+ const row: unknown = Array.isArray(claimedRows) && claimedRows.length === 1 ? claimedRows[0] : undefined+ if (!isObject(row)) {+ throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: `Task ${taskId} does not exist in this conversation or is still running` } })+ }+ const messages = Array.isArray(row['messages']) ? row['messages'].filter(isObject) : []+ return { taskId, claimId, messages }+}++async function finish({ platformId, conversationId, taskId, claimId, status, messages, summary, artifacts }: {+ platformId: string+ conversationId: string+ taskId: string+ claimId: string+ status: SubagentTaskStatus+ messages: Record<string, unknown>[]+ summary: string | null+ artifacts: SubagentTaskArtifact[]+}): Promise<void> {+ const updates: Record<string, unknown> = {+ status,+ messages: sanitizeObjectForPostgresql(messages),+ summary,+ artifacts: sanitizeObjectForPostgresql(artifacts),+ }+ await agentTaskRepo().createQueryBuilder()+ .update()+ .set(updates)+ .where('id = :taskId AND "platformId" = :platformId AND "conversationId" = :conversationId AND "claimId" = :claimId', { taskId, platformId, conversationId, claimId })+ .execute()+}++async function list({ platformId, conversationId }: { platformId: string, conversationId: string }): Promise<Pick<SubagentTask, 'id' | 'title' | 'status' | 'artifacts'>[]> {+ return agentTaskRepo().find({+ where: { platformId, conversationId },+ select: ['id', 'title', 'status', 'artifacts'],+ order: { created: 'ASC' },+ })+}++export const agentTaskService = {+ begin,+ finish,+ list,+}diff --git a/packages/server/api/src/app/ee/agent/chat-tool-billing.ts b/packages/server/api/src/app/ee/agent/chat-tool-billing.tsindex 97a0162af2e..ed9d2944bbd 100644--- a/packages/server/api/src/app/ee/agent/chat-tool-billing.ts+++ b/packages/server/api/src/app/ee/agent/chat-tool-billing.ts@@ -1,4 +1,4 @@-import { isNil, spreadIfDefined } from '@activepieces/core-utils'+import { isNil, isObject, spreadIfDefined } from '@activepieces/core-utils'import { AgentConversation, AgentTurnModel, chatBilling, ChatToolCall, isAppSumoCreditedPlan, PersistedAgentMessage, PersistedAgentPartType, PersistedAgentRole, PersistedToolCallStatus } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { LicenseKeyPostHogEvents } from '../../helper/telemetry.utils'@@ -14,11 +14,18 @@ function latestTurnToolCalls({ messages }: { messages: PersistedAgentMessage[] }const turn = lastUserIndex === -1 ? messages : messages.slice(lastUserIndex + 1)return turn.flatMap((message) => message.parts.flatMap((part) =>part.type === PersistedAgentPartType.TOOL_CALL && part.status === PersistedToolCallStatus.COMPLETED- ? [{ toolName: part.toolName, output: part.output }]+ ? [{ toolName: part.toolName, output: part.output }, ...(part.toolName === TASK_TOOL_NAME ? taskToolCalls(part.output) : [])]: [],))}+function taskToolCalls(output: unknown): ChatToolCall[] {+ if (!isObject(output) || !Array.isArray(output['billedToolCalls'])) {+ return []+ }+ return output['billedToolCalls'].flatMap((call) => isObject(call) && typeof call['toolName'] === 'string' ? [{ toolName: call['toolName'], output: call['output'] }] : [])+}+function countBillableToolCallsInLatestTurn({ messages }: { messages: PersistedAgentMessage[] }): number {return latestTurnToolCalls({ messages }).filter(chatBilling.isFlatBilledToolCall).length}@@ -98,3 +105,5 @@ type ChargeForLatestTurnParams = {answeredBy?: AgentTurnModellog: FastifyBaseLogger}++const TASK_TOOL_NAME = 'ap_run_task'diff --git a/packages/server/api/src/app/ee/agent/prompt/agent-prompt.ts b/packages/server/api/src/app/ee/agent/prompt/agent-prompt.tsindex ec53fd9cd40..e02ce5665bf 100644--- a/packages/server/api/src/app/ee/agent/prompt/agent-prompt.ts+++ b/packages/server/api/src/app/ee/agent/prompt/agent-prompt.ts@@ -20,6 +20,10 @@ const GUIDES: Record<string, string> = Object.fromEntries(GUIDE_TOPICS.map((topic) => [topic, loadPromptTemplate(`guides/${topic}.md`)]),)+const TASK_TEMPLATE = loadPromptTemplate('task-subagent-prompt.md')++const SUBAGENTS_NOTE = loadPromptTemplate('chat-subagents-note.md').trim()+function sanitizeProjectName(name: string): string {return name.replace(/[^a-zA-Z0-9 \-_.]/g, '').slice(0, 64)}@@ -68,6 +72,14 @@ function buildAgentSystemPrompt({ projects, currentProjectId, frontendUrl, templ.replaceAll('{{FRONTEND_URL}}', frontendUrl)}+function buildTaskSystemPrompt({ projects, currentProjectId, frontendUrl }: {+ projects: Project[]+ currentProjectId: string | null+ frontendUrl: string+}): string {+ return buildAgentSystemPrompt({ projects, currentProjectId, frontendUrl, templates: { system: TASK_TEMPLATE } })+}+function buildBuilderSystemPrompt({ agent }: { agent: Agent | null }): string {const state = isNil(agent)? 'No agent yet. Create one as soon as you know what job it should do, then keep changing that one.'@@ -93,7 +105,9 @@ function describeTools(tools: AgentConfig['tools']): string {export const agentPrompt = {buildSystemPrompt: buildAgentSystemPrompt,buildBuilderSystemPrompt,+ buildTaskSystemPrompt,guides: GUIDES,+ subagentsNote: SUBAGENTS_NOTE,projectDisplayName,sources: {...PROMPT_TEMPLATES,diff --git a/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.ts b/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.tsindex 442bd2154dd..65331083e56 100644--- a/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.ts+++ b/packages/server/api/src/app/ee/agent/prompt/agent-surface-notes.ts@@ -1,8 +1,9 @@import { isNil } from '@activepieces/core-utils'-import { AgentRunSource, agentToolSkills, SKILLS_NOTE_HEADING } from '@activepieces/shared'+import { AgentRunSource, agentToolSkills, SKILLS_NOTE_HEADING, SubagentTask } from '@activepieces/shared'+import { agentPrompt } from './agent-prompt'import { agentUserIdentity, UserIdentity } from './agent-user-identity'-function buildRunNotes({ source, currentDate, searchAvailable, fetchAvailable, scrapeAvailable, imageAvailable, imageEditAvailable, emailAvailable, agentsAvailable, userEmail, userIdentity, connections, memory }: {+function buildRunNotes({ source, currentDate, searchAvailable, fetchAvailable, scrapeAvailable, imageAvailable, imageEditAvailable, emailAvailable, agentsAvailable, tasksAvailable, tasks, userEmail, userIdentity, connections, memory }: {source: AgentRunSourcecurrentDate: stringsearchAvailable: boolean@@ -12,6 +13,8 @@ function buildRunNotes({ source, currentDate, searchAvailable, fetchAvailable, simageEditAvailable: booleanemailAvailable: booleanagentsAvailable: boolean+ tasksAvailable: boolean+ tasks?: ConversationTask[]userEmail: stringuserIdentity: UserIdentity | nullconnections: ConnectionInventory | null@@ -32,6 +35,8 @@ function buildRunNotes({ source, currentDate, searchAvailable, fetchAvailable, suserEmail,})+ (isChat && agentsAvailable ? AGENTS_NOTE : '')+ + (isChat && tasksAvailable ? `\n\n${agentPrompt.subagentsNote}` : '')+ + (isChat && tasksAvailable && !isNil(tasks) && tasks.length > 0 ? buildTasksNote(tasks) : '')+ (isChat && !isNil(connections) ? buildConnectionInventoryNote(connections) : '')+ (isChat ? buildMemoryNote(memory) : '')+ (source === AgentRunSource.AGENT ? RECONNECT_NOTE : '')@@ -129,6 +134,14 @@ function buildConnectionInventoryNote({ connections, truncated }: ConnectionInvereturn lines.join('\n')}+function buildTasksNote(tasks: ConversationTask[]): string {+ const lines = tasks.map((task) => {+ const made = task.artifacts.length === 0 ? '' : `; made ${task.artifacts.map((artifact) => `${artifact.type} "${artifact.name}" (${artifact.id})`).join(', ')}`+ return `- taskId ${task.id}, "${task.title}", ${task.status.toLowerCase()}${made}`+ })+ return ['', '', '## Tasks in this conversation', 'Continue one with `ap_run_task` and its taskId instead of starting over. The task remembers everything it did, so ask it when you need details its result no longer shows.', ...lines].join('\n')+}+function buildMemoryNote({ instructions, memories }: RunMemory): string {const trimmedInstructions = instructions?.trim()const lines: string[] = [@@ -213,3 +226,5 @@ const RUN_NOTE_HEADINGS: readonly string[] = []const RUN_NOTE_HEADINGS_THAT_PROVE_A_COPY = 2++type ConversationTask = Pick<SubagentTask, 'id' | 'title' | 'status' | 'artifacts'>diff --git a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.tsindex 1e89fc3e2c5..3081b0f4482 100644--- a/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts+++ b/packages/server/api/src/app/ee/agent/rpc/agent-config-rpc.ts@@ -20,6 +20,7 @@ import { AppSystemProp } from '../../../helper/system/system-props'import { platformService } from '../../../platform/platform.service'import { userService } from '../../../user/user-service'import { smtpEmailSender } from '../../helper/email/email-sender/smtp-email-sender'+import { agentTaskService } from '../agent-task-service'import { chosenProviders } from './chosen-providers'import { CONNECTION_INVENTORY_LIMIT, loadOrStartConversation } from './rpc-shared'@@ -166,35 +167,36 @@ export const agentConfigRpc = (log: FastifyBaseLogger) => ({// that is right there. Best-effort: a lookup failure must not block the turn.// Chat picks a connection mid-run; a configured surface had one pinned when it was set up,// so handing it the inventory only teaches it to renegotiate what it cannot change.- const inventoryResult = (!dryRun && carriesChatContext && !isNil(selectedProjectId))- ? await tryCatch(() => appConnectionService(log).list({- projectId: selectedProjectId,- platformId,- pieceName: undefined,- displayName: undefined,- status: undefined,- cursorRequest: null,- scope: undefined,- externalIds: undefined,- limit: CONNECTION_INVENTORY_LIMIT,- }))- : null+ const tasksAvailable = !dryRun && carriesChatContext+ const [inventoryResult, conversationTasks] = await Promise.all([+ (!dryRun && carriesChatContext && !isNil(selectedProjectId))+ ? tryCatch(() => appConnectionService(log).list({+ projectId: selectedProjectId,+ platformId,+ pieceName: undefined,+ displayName: undefined,+ status: undefined,+ cursorRequest: null,+ scope: undefined,+ externalIds: undefined,+ limit: CONNECTION_INVENTORY_LIMIT,+ }))+ : null,+ tasksAvailable ? agentTaskService.list({ platformId, conversationId }) : [],+ ])const frontendUrl = system.getOrThrow(AppSystemProp.FRONTEND_URL)- const systemPromptText = agentPrompt.buildSystemPrompt({- projects: scopedProjects,- currentProjectId: selectedProjectId,- frontendUrl,- templates: promptOverride,- }) + agentSurfaceNotes.buildRunNotes({+ const runNotesFor = ({ forTask }: { forTask: boolean }): string => agentSurfaceNotes.buildRunNotes({source: conversation.source,currentDate: new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }),searchAvailable: webSearchAvailable,fetchAvailable,scrapeAvailable: fetchAvailable && !isNil(aiTools.webScraping),- imageAvailable: actingRun && (!isNil(aiTools.imageGeneration) || !isNil(imageModelId)),- imageEditAvailable: !isNil(imageModelId),- emailAvailable: emailEnabled,- agentsAvailable,+ imageAvailable: !forTask && actingRun && (!isNil(aiTools.imageGeneration) || !isNil(imageModelId)),+ imageEditAvailable: !forTask && !isNil(imageModelId),+ emailAvailable: !forTask && emailEnabled,+ agentsAvailable: !forTask && agentsAvailable,+ tasksAvailable: !forTask && tasksAvailable,+ tasks: conversationTasks,userEmail: runUserEmail,userIdentity,connections: inventoryResult && !inventoryResult.error@@ -202,6 +204,15 @@ export const agentConfigRpc = (log: FastifyBaseLogger) => ({: null,memory: runMemory,})+ const systemPromptText = agentPrompt.buildSystemPrompt({+ projects: scopedProjects,+ currentProjectId: selectedProjectId,+ frontendUrl,+ templates: promptOverride,+ }) + runNotesFor({ forTask: false })+ const taskSystemPrompt = tasksAvailable+ ? agentPrompt.buildTaskSystemPrompt({ projects: scopedProjects, currentProjectId: selectedProjectId, frontendUrl }) + runNotesFor({ forTask: true })+ : undefined// Merge over defaults, not replace: an override carries only the changed guide topics// (the eval fix-flow sends a partial), so a bare assignment would drop every other guide.const guides = promptOverride?.guides@@ -301,6 +312,7 @@ export const agentConfigRpc = (log: FastifyBaseLogger) => ({: null,projects: scopedProjects.map((p) => ({ id: p.id, displayName: p.displayName, type: p.type })),guides,+ ...spreadIfDefined('taskSystemPrompt', taskSystemPrompt),aiTools,emailEnabled,agentsAvailable,diff --git a/packages/server/api/src/app/ee/agent/rpc/task-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/task-rpc.tsnew file mode 100644index 00000000000..680aa286cbe--- /dev/null+++ b/packages/server/api/src/app/ee/agent/rpc/task-rpc.ts@@ -0,0 +1,18 @@+import { isObject } from '@activepieces/core-utils'+import { BeginAgentTaskRequest, BeginAgentTaskResponse, FinishAgentTaskRequest, SubagentTaskStatus } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'+import { agentTaskService } from '../agent-task-service'++export const taskRpc = (_log: FastifyBaseLogger) => ({+ async beginAgentTask(input: BeginAgentTaskRequest): Promise<BeginAgentTaskResponse> {+ return agentTaskService.begin(input)+ },++ async finishAgentTask(input: FinishAgentTaskRequest): Promise<void> {+ await agentTaskService.finish({+ ...input,+ status: SubagentTaskStatus[input.status],+ messages: input.messages.filter(isObject),+ })+ },+})diff --git a/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.tsindex a10ac60540a..72e3cd1df7e 100644--- a/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts+++ b/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts@@ -194,7 +194,7 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({return { result: decision }}if (input.toolName === '__store_pending_gate') {- const { conversationId: convId, runId: gateRunId, gateId, toolName: gateTool, displayName, toolInput: gateInput } = input.toolInput+ const { conversationId: convId, runId: gateRunId, gateId, toolName: gateTool, displayName, toolInput: gateInput, taskTitle } = input.toolInputif (typeof convId === 'string' && typeof gateId === 'string' && typeof gateTool === 'string') {await agentApprovalGate.storePendingGate({conversationId: convId,@@ -204,6 +204,7 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({displayName: typeof displayName === 'string' ? displayName : gateTool,toolInput: typeof gateInput === 'object' && gateInput !== null ? gateInput as Record<string, unknown> : {},...(typeof gateRunId === 'string' ? { runId: gateRunId } : {}),+ ...(typeof taskTitle === 'string' ? { taskTitle } : {}),},})}diff --git a/packages/server/api/src/app/mcp/tools/ap-add-step.ts b/packages/server/api/src/app/mcp/tools/ap-add-step.tsindex bb5cd6d314e..509c249f768 100644--- a/packages/server/api/src/app/mcp/tools/ap-add-step.ts+++ b/packages/server/api/src/app/mcp/tools/ap-add-step.ts@@ -39,7 +39,7 @@ export const apAddStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseLpieceName: z.string().optional().describe('For PIECE steps: the piece name (e.g. "@activepieces/piece-gmail"). Use ap_research_pieces to get valid values.'),actionName: z.string().optional().describe('For PIECE steps: the action name within the piece. Use ap_research_pieces with includeActions=true to get valid values.'),input: z.record(z.string(), z.unknown()).optional().describe(`For PIECE/CODE steps: input config (key-value pairs). ${mcpUtils.STEP_REFERENCE_HINT}`),- auth: z.string().optional().describe('Connection externalId from ap_list_connections. Auto-wrapped as {{connections[\'externalId\']}}.'),+ auth: z.string().optional().describe('Connection externalId from ap_list_connections. Pass the plain id, not a template.'),sourceCode: z.string().optional().describe('For CODE steps: JavaScript/TypeScript source. Must export a `code` function.'),packageJson: z.string().optional().describe('For CODE steps: package.json as JSON string. Defaults to "{}".'),loopItems: z.string().optional().describe('For LOOP steps: expression for items to iterate (e.g. "{{step_1[\'output\'].items}}").'),@@ -48,7 +48,8 @@ export const apAddStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseL},annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },execute: async (args) => {- const { flowId, parentStepName, stepLocationRelativeToParent, branchIndex, stepType, displayName, pieceName, actionName, input, auth, sourceCode, packageJson, loopItems, continueOnFailure, retryOnFailure } = addStepInput.parse(args)+ const { flowId, parentStepName, stepLocationRelativeToParent, branchIndex, stepType, displayName, pieceName, actionName, input, auth: rawAuth, sourceCode, packageJson, loopItems, continueOnFailure, retryOnFailure } = addStepInput.parse(args)+ const auth = mcpUtils.normalizeAuth(rawAuth)const [flow, project] = await Promise.all([flowService(log).getOnePopulated({ id: flowId, projectId: mcp.projectId }),diff --git a/packages/server/api/src/app/mcp/tools/ap-build-flow.ts b/packages/server/api/src/app/mcp/tools/ap-build-flow.tsindex e913d4aece1..5c3124efc6c 100644--- a/packages/server/api/src/app/mcp/tools/ap-build-flow.ts+++ b/packages/server/api/src/app/mcp/tools/ap-build-flow.ts@@ -61,7 +61,10 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBaslet flowId: string | undefinedconst projectId = mcp.projectIdtry {- const { flowName, trigger, steps, folderName } = buildFlowInput.parse(args)+ const parsed = buildFlowInput.parse(args)+ const { flowName, folderName } = parsed+ const trigger = { ...parsed.trigger, auth: mcpUtils.normalizeAuth(parsed.trigger.auth) }+ const steps = parsed.steps.map((step) => ({ ...step, auth: mcpUtils.normalizeAuth(step.auth) }))const triggerAuthError = mcpUtils.validateAuth(trigger.auth)if (triggerAuthError) {return triggerAuthErrordiff --git a/packages/server/api/src/app/mcp/tools/ap-research-pieces.ts b/packages/server/api/src/app/mcp/tools/ap-research-pieces.tsindex 71600003ffe..5776cc7feff 100644--- a/packages/server/api/src/app/mcp/tools/ap-research-pieces.ts+++ b/packages/server/api/src/app/mcp/tools/ap-research-pieces.ts@@ -77,11 +77,8 @@ function summarizeComponent(c: { name: string, displayName: string, description:}}-function detailOnlyFor({ components, recommended }: { components: ComponentSummary[], recommended: string[] | undefined }): Partial<ComponentSummary>[] {- if (isNil(recommended)) {- return components- }- return components.map((component) => recommended.includes(component.name) ? component : { name: component.name, displayName: component.displayName })+function detailOnlyFor({ components, recommended, trim }: { components: ComponentSummary[], recommended: string[] | undefined, trim: ComponentTrim }): Partial<ComponentSummary>[] {+ return components.map((component) => isNil(recommended) || recommended.includes(component.name) ? trim(component) : { name: component.name, displayName: component.displayName })}async function bulkLookup({ pieceNames, forIntent, projectId, platformId, log }: {@@ -90,51 +87,73 @@ async function bulkLookup({ pieceNames, forIntent, projectId, platformId, log }:projectId: string | undefinedplatformId: stringlog: FastifyBaseLogger-}): Promise<{ content: [{ type: 'text', text: string }], structuredContent: Record<string, unknown> }> {+}): Promise<PieceSearchResult> {const capped = pieceNames.slice(0, BULK_LOOKUP_CAP)const svc = pieceMetadataService(log)- const results = await Promise.all(capped.map(async (rawName) => {+ const results = await Promise.all(capped.map(async (rawName): Promise<BulkLookupEntry> => {const normalized = mcpUtils.normalizePieceName(rawName)if (isNil(normalized)) {- return { name: rawName, found: false as const }+ return { name: rawName, found: false }}const piece = await svc.get({ name: normalized, projectId, platformId })if (isNil(piece)) {- return { name: normalized, found: false as const }+ return { name: normalized, found: false }}const actions = Object.values(piece.actions).map(summarizeComponent)const triggers = Object.values(piece.triggers).map(summarizeComponent)- const recommendedActions = isNil(forIntent) ? undefined : mcpUtils.rankActionsByIntent({ actions, forIntent })- const recommendedTriggers = isNil(forIntent) ? undefined : mcpUtils.rankActionsByIntent({ actions: triggers, forIntent })return {name: piece.name,- found: true as const,+ found: true,displayName: piece.displayName,description: piece.description,- actions: detailOnlyFor({ components: actions, recommended: recommendedActions }),- triggers: detailOnlyFor({ components: triggers, recommended: recommendedTriggers }),- ...(!isNil(recommendedActions) && recommendedActions.length > 0 && { recommendedActions }),+ actions,+ triggers,+ recommendedActions: isNil(forIntent) ? undefined : mcpUtils.rankActionsByIntent({ actions, forIntent }),+ recommendedTriggers: isNil(forIntent) ? undefined : mcpUtils.rankActionsByIntent({ actions: triggers, forIntent }),}}))- const found = results.filter((r) => r.found)- const missing = results.filter((r) => !r.found)- const hints: string[] = []- if (missing.length > 0) {- hints.push(`⚠️ Not found: ${missing.map((m) => m.name).join(', ')}`)+ const found = results.filter((r): r is FoundPiece => r.found)+ const missing = results.filter((r) => !r.found).map((r) => r.name)+ const hints = [+ ...(missing.length > 0 ? [`⚠️ Not found: ${missing.join(', ')}`] : []),+ ...(pieceNames.length > BULK_LOOKUP_CAP ? [`⚠️ Only the first ${BULK_LOOKUP_CAP} pieces were looked up (${pieceNames.length} requested)`] : []),+ ]+ return fitBulkLookup({ found, missing, hints, forIntent })+}++export function fitBulkLookup({ found, missing, hints, forIntent }: { found: FoundPiece[], missing: string[], hints: string[], forIntent: string | undefined }): PieceSearchResult {+ const trimHint = isNil(forIntent)+ ? '⚠️ Trimmed to fit: pass forIntent with what you are trying to do to get full details on the actions that match it.'+ : '⚠️ Trimmed to fit: look up fewer pieces at once for full details.'+ for (const [rung, trim] of DETAIL_LADDER.entries()) {+ const result = bulkResult({ pieces: found.map((piece) => shapeFoundPiece({ piece, trim })), missing, hints: rung === 0 ? hints : [...hints, trimHint] })+ if (fitsBudget(result)) {+ return result+ }}- if (pieceNames.length > BULK_LOOKUP_CAP) {- hints.push(`⚠️ Only the first ${BULK_LOOKUP_CAP} pieces were looked up (${pieceNames.length} requested)`)+ return bulkResult({+ pieces: found.map(({ name, displayName, actions, triggers }) => ({ name, displayName, actionCount: actions.length, triggerCount: triggers.length })),+ missing,+ hints: [...hints, '⚠️ Too many actions to list for these pieces together: look up one piece at a time, with forIntent.'],+ })+}++function shapeFoundPiece({ piece, trim }: { piece: FoundPiece, trim: ComponentTrim }): Record<string, unknown> {+ const { actions, triggers, recommendedActions, recommendedTriggers, ...rest } = piece+ return {+ ...rest,+ actions: detailOnlyFor({ components: actions, recommended: recommendedActions, trim }),+ triggers: detailOnlyFor({ components: triggers, recommended: recommendedTriggers, trim }),+ ...(!isNil(recommendedActions) && recommendedActions.length > 0 && { recommendedActions }),}- const hintText = hints.length > 0 ? `\n\n${hints.join('\n')}` : ''+}+function bulkResult({ pieces, missing, hints }: { pieces: Record<string, unknown>[], missing: string[], hints: string[] }): PieceSearchResult {+ const hintText = hints.length > 0 ? `\n\n${hints.join('\n')}` : ''return {- content: [{ type: 'text', text: `✅ Researched ${found.length} piece(s)${hintText}:\n${JSON.stringify(found)}` }],- structuredContent: {- pieces: found,- missing: missing.map((m) => m.name),- count: found.length,- },+ content: [{ type: 'text', text: `✅ Researched ${pieces.length} piece(s)${hintText}:\n${JSON.stringify(pieces)}` }],+ structuredContent: { pieces, missing, count: pieces.length },}}@@ -213,7 +232,7 @@ async function searchPieces({ params, projectId, platformId, log }: {return fitEnrichedResponse({ pieces: enrichedPieces, overflowHint, totalCount })}-const DETAIL_LADDER: Array<(component: ComponentSummary) => Partial<ComponentSummary>> = [+const DETAIL_LADDER: ComponentTrim[] = [(component) => component,({ aiDescription: _aiDescription, ...rest }) => rest,({ name, displayName }) => ({ name, displayName }),@@ -282,6 +301,21 @@ type ComponentSummary = {aiDescription?: string}+type ComponentTrim = (component: ComponentSummary) => Partial<ComponentSummary>++export type FoundPiece = {+ name: string+ found: true+ displayName: string+ description: string+ actions: ComponentSummary[]+ triggers: ComponentSummary[]+ recommendedActions: string[] | undefined+ recommendedTriggers: string[] | undefined+}++type BulkLookupEntry = FoundPiece | { name: string, found: false }+type PieceSearchResult = { content: [{ type: 'text', text: string }], structuredContent: Record<string, unknown> }type TrimmedPiece = Omit<EnrichedPiece, 'actions' | 'triggers'> & {diff --git a/packages/server/api/src/app/mcp/tools/ap-run-action.ts b/packages/server/api/src/app/mcp/tools/ap-run-action.tsindex 2bc9d60ef34..e6b83c5050c 100644--- a/packages/server/api/src/app/mcp/tools/ap-run-action.ts+++ b/packages/server/api/src/app/mcp/tools/ap-run-action.ts@@ -42,5 +42,5 @@ export const runActionInput = z.object({const parsed = parseToJsonIfPossible(value)return isObject(parsed) ? parsed : value}, z.record(z.string(), z.unknown()).optional()).describe('Fully-resolved input for the action. Keys must match the piece action\'s props. Pass raw values — do NOT wrap in {{...}}. Omit if the action has no props.'),- connectionExternalId: z.string().optional().describe('externalId from ap_list_connections. Required if the piece needs auth. Auto-wrapped as {{connections[\'externalId\']}}.'),+ connectionExternalId: z.string().optional().describe('externalId from ap_list_connections. Required if the piece needs auth. Pass the plain id, not a template.'),})diff --git a/packages/server/api/src/app/mcp/tools/ap-update-step.ts b/packages/server/api/src/app/mcp/tools/ap-update-step.tsindex dfe58ad7761..d0f37eb4abb 100644--- a/packages/server/api/src/app/mcp/tools/ap-update-step.ts+++ b/packages/server/api/src/app/mcp/tools/ap-update-step.ts@@ -32,7 +32,7 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBastepName: z.string().describe('The name of the step to update (e.g. "step_1"). Use ap_flow_structure to get valid values.'),displayName: z.string().optional().describe('New display name for the step'),input: z.record(z.string(), z.unknown()).optional().describe(`Input settings for the step (key-value pairs matching the action schema). ${mcpUtils.STEP_REFERENCE_HINT}`),- auth: z.string().optional().describe('Connection `externalId` from `ap_list_connections`. The tool wraps it automatically as `{{connections[\'externalId\']}}`.'),+ auth: z.string().optional().describe('Connection `externalId` from `ap_list_connections`. Pass the plain id, not a template.'),actionName: z.string().optional().describe('For PIECE steps: the action to perform. Use ap_research_pieces to get valid values.'),loopItems: z.string().optional().describe('For LOOP steps: expression for the items to iterate over'),skip: z.boolean().optional().describe('Whether to skip this step during execution'),@@ -43,7 +43,8 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBa},annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },execute: async (args) => {- const { flowId, stepName, displayName, input, auth, actionName, loopItems, skip, sourceCode, packageJson, continueOnFailure, retryOnFailure } = updateStepInput.parse(args)+ const { flowId, stepName, displayName, input, auth: rawAuth, actionName, loopItems, skip, sourceCode, packageJson, continueOnFailure, retryOnFailure } = updateStepInput.parse(args)+ const auth = mcpUtils.normalizeAuth(rawAuth)const [flow, project] = await Promise.all([flowService(log).getOnePopulated({ id: flowId, projectId: mcp.projectId }),diff --git a/packages/server/api/src/app/mcp/tools/ap-update-trigger.ts b/packages/server/api/src/app/mcp/tools/ap-update-trigger.tsindex 9083368c4b1..c847c145f08 100644--- a/packages/server/api/src/app/mcp/tools/ap-update-trigger.ts+++ b/packages/server/api/src/app/mcp/tools/ap-update-trigger.ts@@ -26,12 +26,13 @@ export const apUpdateTriggerTool = ({ mcp, userId }: McpToolContext, log: FastifpieceName: z.string().describe('The piece name for the trigger (e.g. "@activepieces/piece-gmail"). Use ap_research_pieces to get valid values.'),triggerName: z.string().describe('The trigger name within the piece (e.g. "new_email"). Use ap_research_pieces with includeTriggers=true to get valid values.'),input: z.record(z.string(), z.unknown()).optional().describe(`Input settings for the trigger (key-value pairs). ${mcpUtils.STEP_REFERENCE_HINT}`),- auth: z.string().optional().describe('Connection `externalId` from `ap_list_connections`. The tool wraps it automatically as `{{connections[\'externalId\']}}`.'),+ auth: z.string().optional().describe('Connection `externalId` from `ap_list_connections`. Pass the plain id, not a template.'),displayName: z.string().optional().describe('Display name for the trigger step'),},annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },execute: async (args) => {- const { flowId, pieceName, triggerName, input: rawInput, auth, displayName: rawDisplayName } = updateTriggerInput.parse(args)+ const { flowId, pieceName, triggerName, input: rawInput, auth: rawAuth, displayName: rawDisplayName } = updateTriggerInput.parse(args)+ const auth = mcpUtils.normalizeAuth(rawAuth)const authError = mcpUtils.validateAuth(auth)if (authError) {diff --git a/packages/server/api/src/app/mcp/tools/mcp-utils.ts b/packages/server/api/src/app/mcp/tools/mcp-utils.tsindex 9a5627c78c1..dcdd6b019bc 100644--- a/packages/server/api/src/app/mcp/tools/mcp-utils.ts+++ b/packages/server/api/src/app/mcp/tools/mcp-utils.ts@@ -1,4 +1,4 @@-import { applyFunctionToValuesSync, extractMustacheTokens, isNil, isObject, spreadIfDefined, tryCatch } from '@activepieces/core-utils'+import { applyFunctionToValuesSync, connectionTemplate, extractMustacheTokens, isNil, isObject, spreadIfDefined, tryCatch } from '@activepieces/core-utils'import { AiMetadata, OutputSchema, OutputSchemaField, PieceMetadataModel, PiecePropertyMap, PropertyType } from '@activepieces/pieces-framework'import { BranchOperator, EngineResponse, EngineResponseStatus, flowStructureUtil, McpServerType, McpToolResult, ProjectScopedMcpServer, PropertyExecutionType, PropertySettings, singleValueConditions, WorkerJobType } from '@activepieces/shared'import type { BranchedAction, Step } from '@activepieces/shared'@@ -528,10 +528,10 @@ function publishedFlowWarning(publishedVersionId: string | null | undefined): stfunction resolveConnectionExternalId({ connectionExternalId, input }: { connectionExternalId: unknown, input: unknown }): string | undefined {if (typeof connectionExternalId === 'string') {- return connectionExternalId+ return normalizeAuth(connectionExternalId)}const inlineAuth = isObject(input) ? input.auth : undefined- return typeof inlineAuth === 'string' ? inlineAuth : undefined+ return typeof inlineAuth === 'string' ? normalizeAuth(inlineAuth) : undefined}async function resolveFolder({ projectId, folderName, log }: { projectId: string, folderName: string | undefined, log: FastifyBaseLogger }): Promise<ResolveFolderResult> {@@ -549,6 +549,10 @@ function folderSuffix(folderName: string | undefined): string {return isNil(folderName) ? '' : ` in folder "${folderName}"`}+function normalizeAuth(auth: string | undefined): string | undefined {+ return connectionTemplate.unwrapExternalId(auth) ?? auth+}+function validateAuth(auth: string | undefined): McpToolResult | null {if (auth !== undefined && /['{}\[\]]/.test(auth)) {return { content: [{ type: 'text', text: '❌ auth must be a plain externalId with no special characters. Use the exact value from ap_list_connections.' }], isError: true }@@ -938,6 +942,7 @@ export const mcpUtils = {findResolvableProps,resolveConnectionExternalId,validateAuth,+ normalizeAuth,folderSuffix,resolveFolder,fillDefaultsForMissingOptionalProps,diff --git a/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts b/packages/server/api/src/app/workers/rpc/worker-rpc-service.tsindex 826d71023d5..63bc70c901f 100644--- a/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts+++ b/packages/server/api/src/app/workers/rpc/worker-rpc-service.ts@@ -356,6 +356,12 @@ export function createHandlers(log: FastifyBaseLogger, assignment: WorkerGroupAsasync saveAgentMessages(input) {return agentRpcHandlers(agentRpcLog(log, input)).saveAgentMessages(input)},+ async beginAgentTask(input) {+ return agentRpcHandlers(agentRpcLog(log, input)).beginAgentTask(input)+ },+ async finishAgentTask(input) {+ return agentRpcHandlers(agentRpcLog(log, input)).finishAgentTask(input)+ },async saveAgentFile(input) {return agentRpcHandlers(agentRpcLog(log, input)).saveAgentFile(input)diff --git a/packages/server/api/src/assets/prompts/chat-subagents-note.md b/packages/server/api/src/assets/prompts/chat-subagents-note.mdnew file mode 100644index 00000000000..437bde46c33--- /dev/null+++ b/packages/server/api/src/assets/prompts/chat-subagents-note.md@@ -0,0 +1,15 @@+## Hand focused work to task agents+`ap_run_task` hands one self-contained goal to a task agent: same tools as you, a fresh context, works until done and reports back. A task costs a second context and a brief, so use one only when it buys something:+- **Parallel work:** two or more independent goals that each need their own digging, like researching several vendors.+- **Noisy preparation:** work whose middle is big but whose answer is short, like researching how to reach an app, going through many records or runs, or investigating why something failed. The task brings back the answer and you act on it.++Do everything else yourself, including building flows (one or several: parallel `ap_build_flow` calls are cheaper than a task per flow), small edits, and anything you already have the context for. A goal one or two tool calls can finish (a single read, lookup or schema check) is yours, never a task. Anything that talks to the user stays with you too.++The moment to reach for a task: a result comes back too large to load (marked LARGE RESPONSE, truncated or saved as a file), or you have spent three or more calls digging through output for one answer. Hand the rest of that digging to a task and act on what it brings back.+- Write a self-contained brief: the goal and when it's done, what the task owns and must not change, ids and decisions already made, connections to use. The task sees nothing of this conversation.+- Run independent goals in the same step so they work in parallel. Never give two tasks the same flow or table to change.+- `blocked` means the task needs something only the user can give: ask the user once, then continue the same task with `taskId` and their answer.+- `failed` is yours to fix, never the user's: continue the same task with `taskId`, saying what went wrong and what to try differently, or finish the work yourself. Tell the user about a failure only after that also fails, and then say what you will do next.+- When the user cancelled an approval inside a task, that is their answer. Never repeat that action or ask for it again unless they bring it up.+- For a follow-up on something a task built, make a small change yourself. Continue the task with its `taskId` only when the follow-up is more work on its goal.+- Relay results in your own words. Tasks can't publish on their own initiative, ask questions, or show quick replies; testing and "Turn it on?" stay with you.diff --git a/packages/server/api/src/assets/prompts/chat-system-prompt.md b/packages/server/api/src/assets/prompts/chat-system-prompt.mdindex 106972666ef..c12177fdca3 100644--- a/packages/server/api/src/assets/prompts/chat-system-prompt.md+++ b/packages/server/api/src/assets/prompts/chat-system-prompt.md@@ -148,7 +148,7 @@ These rules decide how your conversational text reads, and they outrank the form- No filler: no "Great question!", "Certainly!", "I hope this helps", "Let's dive in", "The key insight is". No flattery. Start with the answer, stop when done.- No labelled sections or bold inline headers ("The core problem:", "The play I'd run:", "**Pull your leads:**"), no emoji decoration. Plain sentences, or one plain list.- No inflated words (seamless, robust, leverage, streamline, crucial, delve, journey), no forced groups of three, no "it's not just X, it's Y", no "-ing" tails like ", ensuring reliability".-- The closing brief (after you build, do or advise something) is a few plain sentences: what you did, and the important choices you made with their actual values, said inline ("Billing questions go to Sara and the rest to support@. I picked a 3-day window, tell me if you'd rather 5."). Offer `ap_show_quick_replies` chips for the likely tweaks. Never a heading.+- The closing brief (after you build, do or advise something) is a few plain sentences: what you did, and the important choices you made with their actual values, said inline ("Billing questions go to Sara and the rest to support@. I picked a 3-day window, tell me if you'd rather 5."). Offer `ap_show_quick_replies` chips for the likely tweaks. Never a heading. Never restate what the reply already said: if you led with the answer, the brief adds only what is new (what you didn't check or do), or nothing.- No internal details nobody asked for: ids, tool names, step names or raw JSON. When the user asks for JSON, code or config, give it.Robotic (never):diff --git a/packages/server/api/src/assets/prompts/guides/build_flow.md b/packages/server/api/src/assets/prompts/guides/build_flow.mdindex 62643dd3cfc..b6755760cee 100644--- a/packages/server/api/src/assets/prompts/guides/build_flow.md+++ b/packages/server/api/src/assets/prompts/guides/build_flow.md@@ -65,7 +65,7 @@ List the jobs in the request first: intake, processing, storage, reporting, apprHow to build one:1. **Folder:** `ap_create_folder` with a name for the whole solution; pass that `folderName` to every `ap_build_flow` and `ap_create_table` in it.2. **Names:** each flow named for its one job in plain words ("Save order", never "Flow 2").-3. **Order:** tables, then subflows, then the flows that call them; each needs an id the previous one returned.+3. **Order:** tables, then every flow that needs nothing else built first (a shared subflow, a digest that only reads a table) in one step with parallel `ap_build_flow` calls, then the flows that call them, given the ids the first ones returned. Build the flows yourself, not through tasks: a task repeats your setup for each flow and costs about twice as much.4. **Subflow:** trigger `@activepieces/piece-subflows` `callableFlow` with `exampleData.sampleData` listing every input, e.g. `{"orderId": "123", "email": "[email protected]"}`. Its steps read inputs as `{{trigger['output'].data.<key>}}`, never `{{trigger['output'].<key>}}` (empty at run time). Add `returnResponse` only if a caller needs data back.5. **Caller:** a `callFlow` step with `flowId` = the subflow's **externalId** (from `ap_build_flow`, not its flow id), `mode: "simple"`, every sample-data key in `flowProps.payload` as an object, and `waitForResponse` only when the subflow returns a response.6. **Tables steps:** `table_id` is the table's **externalId**; form `values` are keyed by field externalId.diff --git a/packages/server/api/src/assets/prompts/task-subagent-prompt.md b/packages/server/api/src/assets/prompts/task-subagent-prompt.mdnew file mode 100644index 00000000000..aae7e6556de--- /dev/null+++ b/packages/server/api/src/assets/prompts/task-subagent-prompt.md@@ -0,0 +1,28 @@+# You are a focused task agent++The Activepieces assistant handed you one goal. You have the same tools it has and a fresh context. Work until the goal in the brief is done, then hand your result back. Nobody sees your messages; only your result reaches the assistant.++## Where you are+{{PROJECT_CONTEXT}}++Projects you can reach:+{{PROJECT_LIST}}++## How you work+- Do the work end to end: read what you need, build, update and check. Verify your own result before you finish, the way an expert would (validate a flow you built, re-read a record you wrote). Never run a flow you built in any way, including calling it through an action, and never publish it or turn it on. Validation is your check. Test runs, publishing and turning flows on belong to the assistant.+- Stay inside the brief. It says what you own. Read anything else, change only what you own.+- When you have `ap_load_skill`, load every skill you need in one call at the start: `flow_building` before building or changing an automation, `one_time_task` before running something now, and the others as they apply. Ignore the parts of a guide about build cards, quick replies, test runs, publishing, "Turn it on?" and talking to the user: the assistant does those, and you have no tools for them, so don't look for any.+- Facts in the brief (ids, field names, connections, apps and actions) are already checked. Use them as given instead of looking them up again.+- Every step costs the same whether it does a lot or a little. Send independent calls together in one step, and never spend a step on a call that does no work.+- You cannot ask the user anything. Risky actions still show the user an approval card, and you wait for it like the assistant would. If you need something only the user can give (a connection, a choice you cannot infer, a missing permission), stop and finish as blocked, saying exactly what you need.+- When the user cancels an approval, that is their answer, not a block. Do not try that action again. Finish as done with what you did, and say the user cancelled it.+- If the brief turns out to be several separate goals, do the first and say so in your summary.++## Finishing+Call `updateTaskStatus` exactly once, as your last action:+- `status`: `done` when the goal is achieved, `blocked` when only the user can unblock you, `failed` when you tried and could not.+- `summary`: a few plain sentences the assistant can pass on. No ids or tool names in it.+- `artifacts`: only what you created or changed, with type, id and name. Leave it empty when you only read.+- `needs`: when blocked, exactly what you need.++When the assistant continues your task later, its new message is the follow-up or the user's answer, and your earlier work is above it.diff --git a/packages/server/api/test/integration/ee/agent/agent-task-service.test.ts b/packages/server/api/test/integration/ee/agent/agent-task-service.test.tsnew file mode 100644index 00000000000..1656f6944e2--- /dev/null+++ b/packages/server/api/test/integration/ee/agent/agent-task-service.test.ts@@ -0,0 +1,94 @@+import { AgentRunSource, apId, SubagentTaskStatus } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { agentTaskService } from '../../../../src/app/ee/agent/agent-task-service'+import { db } from '../../../helpers/db'+import { createTestContext, TestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('agentTaskService', () => {+ it('starts a task, saves its result and resumes it with its history', async () => {+ const ctx = await createTestContext(app)+ const conversationId = await conversation(ctx)++ const started = await agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Build Save order' })+ await agentTaskService.finish({ platformId: ctx.platform.id, conversationId, taskId: started.taskId, claimId: started.claimId, status: SubagentTaskStatus.BLOCKED, messages: [{ role: 'user', content: 'build it' }], summary: 'Needs a Gmail connection.', artifacts: [{ type: 'flow', id: 'f1', name: 'Save order' }] })+ const resumed = await agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Build Save order', taskId: started.taskId })+ const tasks = await agentTaskService.list({ platformId: ctx.platform.id, conversationId })++ expect(started.messages).toEqual([])+ expect(resumed).toEqual({ taskId: started.taskId, claimId: expect.any(String), messages: [{ role: 'user', content: 'build it' }] })+ expect(resumed.claimId).not.toBe(started.claimId)+ expect(tasks).toEqual([{ id: started.taskId, title: 'Build Save order', status: SubagentTaskStatus.RUNNING, artifacts: [{ type: 'flow', id: 'f1', name: 'Save order' }] }])+ })++ it('refuses to resume a task that is still running', async () => {+ const ctx = await createTestContext(app)+ const conversationId = await conversation(ctx)+ const started = await agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Research' })++ await expect(agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Research', taskId: started.taskId })).rejects.toThrow()+ })++ it('never resumes or lists a task from another platform', async () => {+ const owner = await createTestContext(app)+ const other = await createTestContext(app)+ const conversationId = await conversation(owner)+ const started = await agentTaskService.begin({ platformId: owner.platform.id, conversationId, title: 'Private' })+ await agentTaskService.finish({ platformId: owner.platform.id, conversationId, taskId: started.taskId, claimId: started.claimId, status: SubagentTaskStatus.DONE, messages: [], summary: null, artifacts: [] })++ await expect(agentTaskService.begin({ platformId: other.platform.id, conversationId, title: 'Private', taskId: started.taskId })).rejects.toThrow()+ expect(await agentTaskService.list({ platformId: other.platform.id, conversationId })).toEqual([])+ })++ it('never lets an older run overwrite the run that claimed the task after it', async () => {+ const ctx = await createTestContext(app)+ const conversationId = await conversation(ctx)+ const first = await agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Research' })+ await db.update('agent_task', first.taskId, { updated: '2000-01-01T00:00:00.000Z' })+ const second = await agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Research', taskId: first.taskId })++ await agentTaskService.finish({ platformId: ctx.platform.id, conversationId, taskId: second.taskId, claimId: second.claimId, status: SubagentTaskStatus.DONE, messages: [{ role: 'user', content: 'new' }], summary: 'new result', artifacts: [] })+ await agentTaskService.finish({ platformId: ctx.platform.id, conversationId, taskId: first.taskId, claimId: first.claimId, status: SubagentTaskStatus.FAILED, messages: [{ role: 'user', content: 'old' }], summary: 'old result', artifacts: [] })+ const task = await db.findOneBy('agent_task', { id: first.taskId })++ expect(task).toMatchObject({ status: SubagentTaskStatus.DONE, summary: 'new result' })+ })++ it('deletes tasks with their conversation', async () => {+ const ctx = await createTestContext(app)+ const conversationId = await conversation(ctx)+ await agentTaskService.begin({ platformId: ctx.platform.id, conversationId, title: 'Doomed' })++ await db.delete('agent_conversation', conversationId)++ expect(await agentTaskService.list({ platformId: ctx.platform.id, conversationId })).toEqual([])+ })+})++async function conversation(ctx: TestContext): Promise<string> {+ const conversationId = apId()+ await db.save('agent_conversation', {+ id: conversationId,+ created: new Date().toISOString(),+ updated: new Date().toISOString(),+ platformId: ctx.platform.id,+ projectId: ctx.project.id,+ userId: ctx.user.id,+ source: AgentRunSource.CHAT,+ status: 'IDLE',+ messages: [],+ uiMessages: [],+ })+ return conversationId+}diff --git a/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.ts b/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.tsindex 609557f75e2..11671d01f49 100644--- a/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.ts+++ b/packages/server/api/test/unit/app/ee/agent/agent-surface-notes.test.ts@@ -1,4 +1,4 @@-import { AgentRunSource } from '@activepieces/shared'+import { AgentRunSource, SubagentTaskStatus } from '@activepieces/shared'import { describe, expect, it } from 'vitest'import { agentSurfaceNotes } from '../../../../../src/app/ee/agent/prompt/agent-surface-notes'@@ -24,7 +24,7 @@ const IDENTITY = {},}-const EVERYTHING_AVAILABLE = { searchAvailable: true, fetchAvailable: true, scrapeAvailable: true, imageAvailable: true, imageEditAvailable: true, emailAvailable: true, agentsAvailable: true }+const EVERYTHING_AVAILABLE = { searchAvailable: true, fetchAvailable: true, scrapeAvailable: true, imageAvailable: true, imageEditAvailable: true, emailAvailable: true, agentsAvailable: true, tasksAvailable: true }function notesFor(source: AgentRunSource): string {return agentSurfaceNotes.buildRunNotes({@@ -126,7 +126,7 @@ describe('what each surface is told it can do', () => {const notes = agentSurfaceNotes.buildRunNotes({source: AgentRunSource.CHAT,currentDate: 'Tuesday, August 18, 2026',- searchAvailable: false, fetchAvailable: false, scrapeAvailable: false, imageAvailable: false, imageEditAvailable: false, emailAvailable: false, agentsAvailable: false,+ searchAvailable: false, fetchAvailable: false, scrapeAvailable: false, imageAvailable: false, imageEditAvailable: false, emailAvailable: false, agentsAvailable: false, tasksAvailable: false,userEmail: '[email protected]',userIdentity: null,connections: null,@@ -137,6 +137,22 @@ describe('what each surface is told it can do', () => {expect(notes).not.toContain('Saved agents')expect(notes).not.toContain('ap_web_search')expect(notes).not.toContain('ap_send_email')+ expect(notes).not.toContain('ap_run_task')+ })++ it('tells chat about task agents only when they exist, and lists the conversation tasks to resume', () => {+ expect(notesFor(AgentRunSource.CHAT)).toContain('ap_run_task')+ const withTasks = agentSurfaceNotes.buildRunNotes({+ source: AgentRunSource.CHAT,+ currentDate: 'Tuesday, August 18, 2026',+ ...EVERYTHING_AVAILABLE,+ tasks: [{ id: 'task1', title: 'Build Save order', status: SubagentTaskStatus.DONE, artifacts: [{ type: 'flow', id: 'f1', name: 'Save order' }] }],+ userEmail: '[email protected]',+ userIdentity: IDENTITY,+ connections: null,+ memory: { instructions: null, memories: [] },+ })+ expect(withTasks).toContain('- taskId task1, "Build Save order", done; made flow "Save order" (f1)')})})diff --git a/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.ts b/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.tsindex 3f8d4c68805..362457049de 100644--- a/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.ts+++ b/packages/server/api/test/unit/app/ee/agent/chat-tool-billing.test.ts@@ -66,6 +66,34 @@ describe('chatToolBilling.countBillableToolCallsInLatestTurn', () => {expect(chatToolBilling.countBillableToolCallsInLatestTurn({ messages })).toBe(1)})+ it('bills the paid tool calls a task agent made inside its run', () => {+ const taskPart: PersistedAgentPart = {+ type: PersistedAgentPartType.TOOL_CALL,+ toolCallId: 'task-1',+ toolName: 'ap_run_task',+ input: {},+ status: PersistedToolCallStatus.COMPLETED,+ output: { status: 'done', billedToolCalls: [{ toolName: 'ap_execute_action', output: {} }, { toolName: 'ap_web_search', output: { billedAtCost: true } }, { toolName: 'ap_explore_data', output: {} }] },+ }+ const messages = [user('build it'), assistant([taskPart])]++ expect(chatToolBilling.countBillableToolCallsInLatestTurn({ messages })).toBe(2)+ })++ it('never bills inner calls reported by a tool that is not a task', () => {+ const connectedPart: PersistedAgentPart = {+ type: PersistedAgentPartType.TOOL_CALL,+ toolCallId: 'mcp-1',+ toolName: 'mcp__attio__list_records',+ input: {},+ status: PersistedToolCallStatus.COMPLETED,+ output: { billedToolCalls: [{ toolName: 'ap_execute_action', output: {} }, { toolName: 'ap_web_search', output: {} }] },+ }+ const messages = [user('list them'), assistant([connectedPart])]++ expect(chatToolBilling.countBillableToolCallsInLatestTurn({ messages })).toBe(1)+ })+it('bills nothing when every billable call errored', () => {const messages = [user('do it'),diff --git a/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts b/packages/server/api/test/unit/app/mcp/mcp-utils.test.tsindex 354501d60b0..193932d58a5 100644--- a/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts+++ b/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts@@ -650,3 +650,19 @@ describe('mcpUtils.normalizeFormulaText — double braces around a formula', ()expect(mcpUtils.normalizeFormulaText(correct)).toBe(correct)})})++describe('mcpUtils.normalizeAuth', () => {+ it('unwraps the connection template the research tools hand out', () => {+ expect(mcpUtils.normalizeAuth('{{connections[\'conn_test_id\']}}')).toBe('conn_test_id')+ })++ it('leaves a plain externalId and undefined alone', () => {+ expect(mcpUtils.normalizeAuth('conn_test_id')).toBe('conn_test_id')+ expect(mcpUtils.normalizeAuth(undefined)).toBeUndefined()+ })++ it('still lets validateAuth reject anything that is not a clean id', () => {+ const garbage = mcpUtils.normalizeAuth('{{trigger[\'output\'].auth}}')+ expect(mcpUtils.validateAuth(garbage)).not.toBeNull()+ })+})diff --git a/packages/server/api/test/unit/app/mcp/research-pieces-budget.test.ts b/packages/server/api/test/unit/app/mcp/research-pieces-budget.test.tsindex d22b98711b4..aa8c987fcce 100644--- a/packages/server/api/test/unit/app/mcp/research-pieces-budget.test.ts+++ b/packages/server/api/test/unit/app/mcp/research-pieces-budget.test.ts@@ -1,6 +1,6 @@import { MAX_TOOL_RESULT_BYTES } from '@activepieces/server-utils'import { describe, expect, it } from 'vitest'-import { fitEnrichedResponse } from '../../../../src/app/mcp/tools/ap-research-pieces'+import { fitBulkLookup, fitEnrichedResponse, FoundPiece } from '../../../../src/app/mcp/tools/ap-research-pieces'const SLIM_PIECE = { name: '@activepieces/piece-webhook', displayName: 'Webhook', description: 'Receive HTTP requests.' }@@ -73,3 +73,25 @@ describe('what ap_research_pieces is allowed to return', () => {expect(result.structuredContent).toMatchObject({ pieces: [], trimmed: true })})})++describe('what a pieceNames lookup is allowed to return', () => {+ function foundPiece(index: number): FoundPiece {+ const { actions, ...rest } = piece({ index, actionCount: 60, detailLength: 600, aiLength: 600 })+ return { ...rest, found: true, actions, triggers: actions, recommendedActions: undefined, recommendedTriggers: undefined }+ }++ it('trims three big CRMs to fit and tells the model to pass forIntent', () => {+ const result = fitBulkLookup({ found: [foundPiece(1), foundPiece(2), foundPiece(3)], missing: [], hints: [], forIntent: undefined })++ expect(byteSize(result)).toBeLessThanOrEqual(MAX_TOOL_RESULT_BYTES)+ expect(result.structuredContent['count']).toBe(3)+ expect(result.content[0].text).toContain('forIntent')+ })++ it('leaves a small lookup untouched with no trim hint', () => {+ const small = { ...foundPiece(1), actions: [], triggers: [] }+ const result = fitBulkLookup({ found: [small], missing: [], hints: [], forIntent: undefined })++ expect(result.content[0].text).not.toContain('Trimmed to fit')+ })+})diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-title.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-title.tsnew file mode 100644index 00000000000..d241d8453f6--- /dev/null+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-title.ts@@ -0,0 +1,45 @@+import { tryCatch } from '@activepieces/core-utils'+import { agentAiUtils } from '@activepieces/server-utils'+import { generateText, LanguageModel } from 'ai'+import { JobContext } from '../../../types'++async function generateIfFirstTurn({ model, userMessage, previousUiMessages, log, conversationId, abortSignal }: {+ model: LanguageModel+ userMessage: string+ previousUiMessages: unknown[]+ log: JobContext['log']+ conversationId: string+ abortSignal?: AbortSignal+}): Promise<string | undefined> {+ const isFirstTurn = previousUiMessages.length === 1+ if (!isFirstTurn) return undefined++ const { data: generatedTitle } = await tryCatch(async () => {+ const { text } = await generateText({+ model,+ abortSignal,+ telemetry: agentAiUtils.buildTelemetry({ functionId: 'agent-title' }),+ system: 'You name conversations. Never answer, refuse or comment on the message. Output only a concise 3-6 word title for it, nothing else.',+ prompt: `<message>\n${userMessage}\n</message>`,+ })+ return finalize(text)+ })++ if (!generatedTitle) {+ log.warn({ conversation: { id: conversationId } }, 'Failed to auto-generate title')+ }+ return generatedTitle ?? undefined+}++function finalize(rawTitle: string): string {+ return rawTitle+ .replace(/[*_`~#]/g, '')+ .replace(/^["']+|["']+$/g, '')+ .trim()+ .slice(0, 100)+}++export const agentTitle = {+ generateIfFirstTurn,+ finalize,+}diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/credit-ledger.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/credit-ledger.tsnew file mode 100644index 00000000000..22febe020be--- /dev/null+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/credit-ledger.ts@@ -0,0 +1,13 @@+function create({ creditsLeft, messageCredits }: { creditsLeft: (pendingCredits: number) => Promise<number | null>, messageCredits: number }): (runKey: string) => (pendingCredits: number) => Promise<number | null> {+ const pendingByRun = new Map<string, number>()+ return (runKey) => (pendingCredits) => {+ pendingByRun.set(runKey, pendingCredits)+ const runs = [...pendingByRun.values()]+ const messageChargedOnce = messageCredits * (runs.length - 1)+ return creditsLeft(runs.reduce((sum, value) => sum + value, 0) - messageChargedOnce)+ }+}++export const creditLedger = {+ create,+}diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/declined-actions.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/declined-actions.tsnew file mode 100644index 00000000000..f078a5ee836--- /dev/null+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/declined-actions.ts@@ -0,0 +1,41 @@+import { isNil, omit } from '@activepieces/core-utils'+import { AgentEventEmitter, stableStringify } from './tools/tool-primitives'++function create({ eventEmitter }: { eventEmitter: AgentEventEmitter }): DeclinedActions {+ const declined = new Set<string>()+ const actionByGate = new Map<string, string>()+ const isDeclined = (gateId: string): boolean => {+ const action = actionByGate.get(gateId)+ return !isNil(action) && declined.has(action)+ }+ return {+ eventEmitter: {+ ...eventEmitter,+ emitActionPreview: (data) => {+ actionByGate.set(data.toolCallId, `${data.pieceName}:${data.actionName}:${stableStringify(omit(data.input, CARD_LABEL_KEYS))}`)+ if (!isDeclined(data.toolCallId)) {+ eventEmitter.emitActionPreview(data)+ }+ },+ },+ isDeclined,+ recordDecision: ({ gateId, approved }) => {+ const action = actionByGate.get(gateId)+ if (!approved && !isNil(action)) {+ declined.add(action)+ }+ },+ }+}++export const declinedActions = {+ create,+}++type DeclinedActions = {+ eventEmitter: AgentEventEmitter+ isDeclined: (gateId: string) => boolean+ recordDecision: (input: { gateId: string, approved: boolean }) => void+}++const CARD_LABEL_KEYS = ['title', 'activeTitle', 'doneTitle']diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.tsindex 1e4cc9a0650..89f8c66d99f 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts@@ -1,14 +1,19 @@import { ActivepiecesAiBilling, ActivepiecesAiConsumerSource, AIProviderName, ErrorCode, formatPieceError, isNil, isObject, spreadIfDefined, tryCatch, tryCatchSync } from '@activepieces/core-utils'-import { agentAiUtils, aiUtils } from '@activepieces/server-utils'-import { AgentConfigResponse, AgentEvent, AgentEventType, AgentKnowledgeBaseTool, AgentMcpTool, AgentModelCandidate, AgentOutputField, AgentPhase, AgentPieceTool, AgentResult, AgentRunSource, AgentTool, agentToolSkills, AgentToolType, AiProviderCredentials, apErrorOf, EngineResponseStatus, ExecuteAgentRunJobData, MAX_AGENT_TURN_WALL_CLOCK_MS, PersistedAgentMessage, PersistedAgentMessageSchema, PersistedAgentPart, PersistedAgentPartType, PersistedAgentRole, ResolvedAgentFlowTool, SaveAgentMessagesRequest, SkillSurface, WorkerJobType } from '@activepieces/shared'-import { createUIMessageStream, generateText, LanguageModel, ModelMessage, streamText, ToolSet, toUIMessageStream } from 'ai'+import { aiUtils } from '@activepieces/server-utils'+import { AgentConfigResponse, AgentEvent, AgentEventType, AgentKnowledgeBaseTool, AgentMcpTool, AgentModelCandidate, AgentOutputField, AgentPhase, AgentPieceTool, AgentResult, AgentRunSource, AgentTool, agentToolSkills, AgentToolType, AiProviderCredentials, apErrorOf, chatBilling, EngineResponseStatus, ExecuteAgentRunJobData, MAX_AGENT_TURN_WALL_CLOCK_MS, PersistedAgentMessage, PersistedAgentMessageSchema, PersistedAgentPart, PersistedAgentPartType, PersistedAgentRole, ResolvedAgentFlowTool, SaveAgentMessagesRequest, SkillSurface, WorkerJobType } from '@activepieces/shared'+import { createUIMessageStream, LanguageModel, ModelMessage, streamText, ToolSet, toUIMessageStream } from 'ai'import { FireAndForgetJobResult, JobContext, JobHandler, JobResultKind } from '../../../types'import { toResolvedAiFile } from '../../ai/ai-files'import { agentMcpClient, McpConnection } from './agent-mcp-client'import { stepResultFrom } from './agent-step-result'+import { agentTitle } from './agent-title'import { agentToolPolicy } from './agent-tool-policy'import { agentWorkerTools, GateDecision, TaintState } from './agent-worker-tools'+import { creditLedger } from './credit-ledger'+import { declinedActions } from './declined-actions'import { classifyAgentRunError, delayWithJitter, drainOf, firstStepUsesFastModel, isTransientFailureText, NO_STEP_CONTENT, runAgentTurn, StreamDrain, trackStepContent, TurnModel } from './run-agent-turn'+import { taskContext } from './tools/task-context'+import { createTaskSubagentTools } from './tools/task-subagent-tools'const BATCH_SIZE = 10const BATCH_FLUSH_MS = 50@@ -16,6 +21,7 @@ const APPROVAL_TIMEOUT_MS = 5 * 60 * 1_000const APPROVAL_BLOCK_MS = 50_000const DISPLAY_TOOL_TIMEOUT_MS = 5 * 60 * 1_000const HEARTBEAT_INTERVAL_MS = 15_000+const MAIN_RUN_CREDIT_KEY = 'main'const RETRY_MAX_ATTEMPTS = 3const RETRY_BASE_DELAY_MS = 1_000// A turn quiet this long with NO tool call and NO reasoning block in flight is REPORTED as idle —@@ -242,10 +248,15 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForge},})+ const creditsLeftFor = creditLedger.create({+ creditsLeft: (pendingCredits) => ctx.apiClient.agentCreditsLeft({ platformId, conversationId, pendingCredits }),+ messageCredits: chatBilling.creditsForTurn({ provider, toolCalls: [] }).messageCredits,+ })+const thinkingStartTime = Date.now()- const autoTitlePromise = generateTitleIfFirstTurn({- model, userMessage, previousUiMessages: config.previousUiMessages as unknown[], log, conversationId, abortSignal: abortController.signal,+ const autoTitlePromise = agentTitle.generateIfFirstTurn({+ model: fastTurnModel?.model ?? model, userMessage, previousUiMessages: config.previousUiMessages as unknown[], log, conversationId, abortSignal: abortController.signal,})const turn = await agentMcpClient.withStepMcpTools({@@ -253,14 +264,21 @@ export const executeAgentRunJob: JobHandler<ExecuteAgentRunJobData, FireAndForgeskip: (dryRun ?? false) || (discoveryOnly ?? false),log,run: (stepMcpToolSet) => {- const mergedTools = { ...allTools, ...agentWorkerTools.wrapToolsWithTaint({ tools: stepMcpToolSet, taintState }) }+ const baseTools = { ...allTools, ...agentWorkerTools.wrapToolsWithTaint({ tools: stepMcpToolSet, taintState }) }+ const taskTools = createTaskSubagentTools({+ tools: baseTools, guides: config.guides, models: turnModels, tier: config.tier,+ taskPrompt: config.taskSystemPrompt, creditsLeftFor, eventEmitter, abortSignal: abortController.signal, log,+ beginTask: (input) => ctx.apiClient.beginAgentTask({ platformId, conversationId, ...input }),+ finishTask: (input) => ctx.apiClient.finishAgentTask({ platformId, conversationId, ...input }),+ })+ const mergedTools = { ...baseTools, ...taskTools }const allToolNames = Object.keys(mergedTools)log.info({ toolCount: allToolNames.length, mcpToolCount: Object.keys(mcpToolSet).length, phase: phaseState.phase }, '[executeAgentRun] Tool set assembled')log.debug({ toolNames: allToolNames }, '[executeAgentRun] Tool set details')return runAgentTurn({...spreadIfDefined('stepCeiling', data.maxSteps),- creditsLeft: (pendingCredits) => ctx.apiClient.agentCreditsLeft({ platformId, conversationId, pendingCredits }),+ creditsLeft: creditsLeftFor(MAIN_RUN_CREDIT_KEY),models: turnModels,fastModel: firstStepUsesFastModel({ source, dryRun, runsASavedAgent: !isNil(data.promptOverride) }) ? fastTurnModel : undefined,onStepModel: (stepModel) => {@@ -622,6 +640,8 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webToolscaptureStructured: (output: Record<string, unknown>) => voidsource: AgentRunSource}): ToolSet {+ const declines = declinedActions.create({ eventEmitter })+ const toolEventEmitter = declines.eventEmitterconst brokenConnectors = new Set<string>()const executeCrossProjectTool = async (toolName: string, toolInput: Record<string, unknown>) => {@@ -646,6 +666,9 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webToolsif (dryRun || discoveryOnly) {return { outcome: 'approved' }}+ if (declines.isDeclined(gateId)) {+ return { outcome: 'declined' }+ }const deadline = Date.now() + (timeoutMs ?? APPROVAL_TIMEOUT_MS)while (Date.now() < deadline) {// A preempted/cancelled turn must stop waiting immediately instead of@@ -673,6 +696,7 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webTools}if (response.result !== 'pending') {const decision = response.result as { approved: boolean, payload?: Record<string, unknown> }+ declines.recordDecision({ gateId, approved: decision.approved })return { outcome: decision.approved ? 'approved' : 'declined', payload: decision.payload }}}@@ -708,7 +732,7 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webTools}) => {await tryCatch(() => ctx.apiClient.executeAgentTool({toolName: '__store_pending_gate',- toolInput: { conversationId, runId, gateId, toolName: gateTool, displayName, toolInput: gateInput },+ toolInput: { conversationId, runId, gateId, toolName: gateTool, displayName, toolInput: gateInput, ...spreadIfDefined('taskTitle', taskContext.currentTitle()) },platformId, userId, source, conversationId,}))}@@ -750,13 +774,13 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webToolsonConnectorReconnected: (connectorUuid) => brokenConnectors.delete(connectorUuid),onGateOpened: storePendingGate,})- const crossProjectTools = agentWorkerTools.createCrossProjectTools({ executeTool: executeCrossProjectTool, eventEmitter, waitForApproval, onGateOpened: storePendingGate, taintState })+ const crossProjectTools = agentWorkerTools.createCrossProjectTools({ executeTool: executeCrossProjectTool, eventEmitter: toolEventEmitter, waitForApproval, onGateOpened: storePendingGate, taintState })const agentSurfaceTools = agentsAvailable && !dryRun && !discoveryOnly- ? agentWorkerTools.createAgentSurfaceTools({ executeTool: executeCrossProjectTool, taintState, eventEmitter, waitForApproval, onGateOpened: storePendingGate })+ ? agentWorkerTools.createAgentSurfaceTools({ executeTool: executeCrossProjectTool, taintState, eventEmitter: toolEventEmitter, waitForApproval, onGateOpened: storePendingGate }): {}const thinkingTools = agentWorkerTools.createThinkingTools()const buildPlanTools = agentWorkerTools.createBuildPlanTools({- eventEmitter,+ eventEmitter: toolEventEmitter,getProjectId: () => projectState.projectId,})const timedMcpTools = agentMcpClient.withToolTimeouts({@@ -773,20 +797,20 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webTools},})const mcpTools = agentWorkerTools.wrapTestFlowGate({- mcpTools: agentWorkerTools.wrapDeleteGate({ mcpTools: timedMcpTools, waitForApproval, storePendingGate, eventEmitter }),+ mcpTools: agentWorkerTools.wrapDeleteGate({ mcpTools: timedMcpTools, waitForApproval, storePendingGate, eventEmitter: toolEventEmitter }),checkFlowWrites: async (flowId) => {const response = await ctx.apiClient.executeAgentTool({ toolName: '__flow_write_check', toolInput: { flowId }, platformId, userId, source, conversationId })return response.result},waitForApproval,storePendingGate,- eventEmitter,+ eventEmitter: toolEventEmitter,log,})const emailTools = emailEnabled && !dryRun && !discoveryOnly? agentWorkerTools.createEmailTools({sendEmail: ({ to, subject, body, gateId }) => ctx.apiClient.sendAgentEmail({ conversationId, runId, platformId, userId, to, subject, body, gateId }),- eventEmitter,+ eventEmitter: toolEventEmitter,userEmail,waitForApproval,onGateOpened: storePendingGate,@@ -799,7 +823,7 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webToolstools: dryRun || discoveryOnly ? [] : configuredPieceTools,runPieceTool: ({ toolName, instruction, piece }) => ctx.apiClient.executePieceTool({ conversationId, ...spreadIfDefined('runId', runId), toolName, instruction, piece, ...runKey(), ...spreadIfDefined('flowRunId', flowRunId) }),taintState,- eventEmitter,+ eventEmitter: toolEventEmitter,log,})const configuredFlowToolSet = agentWorkerTools.createConfiguredFlowTools({@@ -956,42 +980,6 @@ async function streamChunksToClient({ result, ctx, userId, conversationId, runIdreturn drainOf({ state: stepContent })}-async function generateTitleIfFirstTurn({ model, userMessage, previousUiMessages, log, conversationId, abortSignal }: {- model: ReturnType<typeof aiUtils.createModel>- userMessage: string- previousUiMessages: unknown[]- log: JobContext['log']- conversationId: string- abortSignal?: AbortSignal-}): Promise<string | undefined> {- // getAgentConfig includes the just-saved user message, so length 1 = first turn- const isFirstTurn = previousUiMessages.length === 1- if (!isFirstTurn) return undefined-- const { data: generatedTitle } = await tryCatch(async () => {- const { text } = await generateText({- model,- abortSignal,- telemetry: agentAiUtils.buildTelemetry({ functionId: 'agent-title' }),- prompt: `Generate a concise 3-6 word title for this conversation. Return ONLY the title, nothing else.\n\nUser: ${userMessage}`,- })- return sanitizeGeneratedTitle(text)- })-- if (!generatedTitle) {- log.warn({ conversation: { id: conversationId } }, 'Failed to auto-generate title')- }- return generatedTitle ?? undefined-}--function sanitizeGeneratedTitle(rawTitle: string): string {- return rawTitle- .replace(/[*_`~#]/g, '')- .replace(/^["']+|["']+$/g, '')- .trim()- .slice(0, 100)-}-function waitForAbort(signal: AbortSignal): Promise<void> {if (signal.aborted) {return Promise.resolve()diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.tsindex 3255ef47c10..52ad072966e 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/run-agent-turn.ts@@ -64,13 +64,13 @@ export function drainOf({ state }: { state: StepContentState }): StreamDrain {return { lastStepSentContent: state.sentWhenFailed ?? state.sentInStep }}-export async function runAgentTurn({ models, fastModel, systemPrompt, messages, tools, allToolNames, tier, phaseState, abortSignal, log, sinks, stopWhen, stepCeiling, creditsLeft, onModelOutcome, onStepModel, skills }: RunAgentTurnParams): Promise<AgentTurnResult> {+export async function runAgentTurn({ models, fastModel, systemPrompt, messages, tools, allToolNames, tier, phaseState, abortSignal, log, sinks, stopWhen, stepCeiling, creditsLeft, priorToolCalls, onModelOutcome, onStepModel, skills }: RunAgentTurnParams): Promise<AgentTurnResult> {const drainStream = sinks?.drainStream ?? ((result: ReturnType<typeof streamText>) => result.consumeStream())const onProgress = sinks?.onProgress ?? (() => {})const baseStopCondition = stopWhen ?? isLoopFinished()let creditsExhausted = falselet paidToolsAffordable = true- let earlierAttemptToolCalls: ChatToolCall[] = []+ let earlierAttemptToolCalls: ChatToolCall[] = priorToolCalls ?? []const creditsRanOut: StopCondition<ToolSet> = async ({ steps }) => {if (isNil(creditsLeft)) {return false@@ -172,7 +172,7 @@ export async function runAgentTurn({ models, fastModel, systemPrompt, messages,const stepModel = isFirstStep && !isNil(fast) ? fast : current()const usesFastModel = stepModel !== current()const stepBudget = stepModel.budget- const visibleTools = skillSurface?.coreToolNames ?? agentToolPhases.activeToolsForPhase({ phase: phaseState.phase, allToolNames })+ const visibleTools = skillSurface?.attachedToolNames() ?? agentToolPhases.activeToolsForPhase({ phase: phaseState.phase, allToolNames })const phaseTools = isNil(skillSurface) ? visibleTools.filter((name) => paidToolsAffordable || !chatBilling.isPaidTool(name)) : visibleToolsconst activeTools = forcesCompletion ? [TASK_COMPLETION_TOOL_NAME] : phaseToolsconst boundedContext = boundContextForStep({ baseMessages: attemptMessages, steps, systemPrompt: turnSystemPrompt, provider: stepModel.provider })@@ -655,6 +655,7 @@ export type RunAgentTurnParams = {stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>stepCeiling?: numbercreditsLeft?: (pendingCredits: number) => Promise<number | null>+ priorToolCalls?: ChatToolCall[]onModelOutcome?: (outcome: { turnModel: TurnModel, signal: ProviderOutcomeSignal }) => voidonStepModel?: (turnModel: TurnModel) => voidskills?: { surface: SkillSurface, guides: Record<string, string> }diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/event-emitter.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/event-emitter.tsindex fc2fc068f94..470cbef539d 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/event-emitter.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/event-emitter.ts@@ -1,5 +1,6 @@-import { tryCatch } from '@activepieces/core-utils'-import { ActionPreviewEvent, ActionReceiptEvent, AgentEventType, BuildPlanEvent, FileProducedEvent, ImageGeneratedEvent, SendAgentEventRequest, ToolProgressEvent } from '@activepieces/shared'+import { isNil, tryCatch } from '@activepieces/core-utils'+import { ActionPreviewEvent, ActionReceiptEvent, AgentEventType, BuildPlanEvent, FileProducedEvent, ImageGeneratedEvent, SendAgentEventRequest, SubagentProgressEvent, ToolProgressEvent } from '@activepieces/shared'+import { taskContext } from './task-context'import { AgentEventEmitter } from './tool-primitives'export function createEventEmitter({ sendEvent, userId, conversationId, log }: {@@ -30,8 +31,9 @@ export function createEventEmitter({ sendEvent, userId, conversationId, log }: {})},emitActionPreview(data: ActionPreviewEvent): void {+ const taskTitle = taskContext.currentTitle()void sendWithRetry({- event: { type: AgentEventType.ACTION_PREVIEW, data },+ event: { type: AgentEventType.ACTION_PREVIEW, data: isNil(taskTitle) ? data : { ...data, taskTitle } },maxAttempts: 3,})},@@ -59,6 +61,12 @@ export function createEventEmitter({ sendEvent, userId, conversationId, log }: {maxAttempts: 2,})},+ emitSubagentProgress(data: SubagentProgressEvent): void {+ sendWithRetry({+ event: { type: AgentEventType.SUBAGENT_PROGRESS, data },+ maxAttempts: 2,+ }).catch(() => undefined)+ },}}diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/skill-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/skill-tools.tsindex 3eecf5181e5..0fe6615ae69 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/skill-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/skill-tools.ts@@ -1,4 +1,4 @@-import { isNil, isObject, tryCatch } from '@activepieces/core-utils'+import { isNil, isObject, tryCatch, unique } from '@activepieces/core-utils'import { AGENT_SKILLS, AgentSkill, agentToolSkills, chatBilling, GET_TOOL_SCHEMA_NAME, LAZY_TOOL_NAME, LOAD_SKILL_NAME, MAX_CORE_TOOLS, SkillSurface } from '@activepieces/shared'import { asSchema, jsonSchema, JSONValue, Schema, tool, ToolExecutionOptions, ToolResultPart, ToolSet } from 'ai'import { z } from 'zod'@@ -12,7 +12,8 @@ export function buildSkillSurface({ tools: registry, surface, guides, onSkillLoacanAffordPaidTool: () => booleanwasRerouted?: (toolCallId: string) => boolean}): SkillSurfaceResult {- const skillTools = createSkillTools({ registry, surface, guides, onSkillLoaded, canAffordPaidTool, wasRerouted })+ const loadedSkills = new Set<string>()+ const skillTools = createSkillTools({ registry, surface, guides, loadedSkills, onSkillLoaded, canAffordPaidTool, wasRerouted })const surfaceTools = { ...registry, ...skillTools }const allToolNames = Object.keys(surfaceTools)const directToolNames = allToolNames.length <= MAX_CORE_TOOLS@@ -23,6 +24,7 @@ export function buildSkillSurface({ tools: registry, surface, guides, onSkillLoareturn {tools: surfaceTools,coreToolNames,+ attachedToolNames: () => unique([...coreToolNames, ...[...loadedSkills].flatMap((name) => attachableToolNames({ skill: agentToolSkills.findSkill({ name }), registry }))]),catalogNote: uncatalogued.length === 0? '': `\n\n${OTHER_TOOLS_HEADING}\nThese are not attached to you, so calling one by its own name fails. Fetch its schema with \`${GET_TOOL_SCHEMA_NAME}\`, then call \`${LAZY_TOOL_NAME}\` with the name as \`tool\` and the arguments as \`input\`.\n${agentToolSkills.renderToolCatalog({ tools: uncatalogued.map((name) => ({ name, description: descriptionOf(registry[name]) })) })}`,@@ -58,22 +60,22 @@ export function unwrapLazyToolChunk({ chunk, heldStarts }: {return { emit: [chunk] }}-function createSkillTools({ registry, surface, guides, onSkillLoaded, canAffordPaidTool, wasRerouted }: {+function createSkillTools({ registry, surface, guides, loadedSkills, onSkillLoaded, canAffordPaidTool, wasRerouted }: {registry: ToolSetsurface: SkillSurfaceguides: Record<string, string>+ loadedSkills: Set<string>onSkillLoaded: (skill: AgentSkill) => voidcanAffordPaidTool: () => booleanwasRerouted: (toolCallId: string) => boolean}): ToolSet {- const loadedSkills = new Set<string>()const core = new Set(agentToolSkills.coreToolNames({ surface }))const loadableSkills = AGENT_SKILLS.filter((skill) => skill.toolNames.some((name) => name in registry) || (skill.guideTopic !== undefined && skill.guideTopic in guides))const [firstSkill, ...otherSkills] = loadableSkills.map((skill) => skill.name)const loadSkillTool: ToolSet = firstSkill === undefined ? {} : {[LOAD_SKILL_NAME]: tool({- description: 'Load skills before that kind of work (silent, internal). A loaded playbook stays in the conversation and is re-read on every later step, so load only the skills the work in front of you needs right now, together in one call, and load another when the work reaches it. Returns each playbook and the input schema of every tool in it, which you then run with ap_lazy_tool.',+ description: 'Load skills before that kind of work (silent, internal). A loaded playbook stays in the conversation and is re-read on every later step, so load only the skills the work in front of you needs right now, together in one call, and load another when the work reaches it. Returns each playbook and attaches its tools to you, so you call them by their own name from the next step on.',inputSchema: z.object({skills: z.array(z.enum([firstSkill, ...otherSkills])).min(1).describe('The skills the work in front of you needs now, loaded together'),}),@@ -123,21 +125,31 @@ function createSkillTools({ registry, surface, guides, onSkillLoaded, canAffordP}return target.execute(input, options)},- toModelOutput: ({ toolCallId, input, output }) => lazyToolModelOutput({ output, reroutedTool: wasRerouted(toolCallId) ? input.tool : undefined }),+ toModelOutput: async ({ toolCallId, input, output }) => lazyToolModelOutput({+ output: await registry[input.tool]?.toModelOutput?.({ toolCallId, input: input.input, output }) ?? asModelOutput(output),+ reroutedTool: wasRerouted(toolCallId) ? input.tool : undefined,+ }),}),}}-function lazyToolModelOutput({ output, reroutedTool }: { output: JSONValue | undefined, reroutedTool: string | undefined }): ToolResultPart['output'] {- const note = isNil(reroutedTool) ? undefined : `Note: "${reroutedTool}" is not attached to you, so calling it by its own name does not work. It ran this time; next time call ${LAZY_TOOL_NAME} with tool: "${reroutedTool}" and its arguments as input.`- if (typeof output === 'string') {- return { type: 'text', value: isNil(note) ? output : `${output}\n\n${note}` }+function asModelOutput(output: JSONValue | undefined): ToolResultPart['output'] {+ return typeof output === 'string' ? { type: 'text', value: output } : { type: 'json', value: output ?? null }+}++function lazyToolModelOutput({ output, reroutedTool }: { output: ToolResultPart['output'], reroutedTool: string | undefined }): ToolResultPart['output'] {+ if (isNil(reroutedTool)) {+ return output+ }+ const note = `Note: "${reroutedTool}" is not attached to you, so calling it by its own name does not work. It ran this time; next time call ${LAZY_TOOL_NAME} with tool: "${reroutedTool}" and its arguments as input.`+ if (output.type === 'text') {+ return { type: 'text', value: `${output.value}\n\n${note}` }}- const value = output ?? null- if (isNil(note)) {- return { type: 'json', value }+ if (output.type === 'json') {+ const value = output.value+ return { type: 'json', value: isObject(value) && !Array.isArray(value) ? { ...value, note } : { result: value, note } }}- return { type: 'json', value: isObject(value) && !Array.isArray(value) ? { ...value, note } : { result: value, note } }+ return output}function lazyToolInputSchema({ registry, canAffordPaidTool }: { registry: ToolSet, canAffordPaidTool: () => boolean }): Schema<LazyToolInput> {@@ -204,7 +216,8 @@ async function renderSkill({ skill, guide, registry, core, canAffordPaidTool }:core: Set<string>canAffordPaidTool: () => boolean}): Promise<string> {- const available = skill.toolNames.filter((name) => name in registry && !core.has(name))+ const attached = attachableToolNames({ skill, registry }).filter((name) => !core.has(name))+ const available = skill.toolNames.filter((name) => name in registry && !core.has(name) && chatBilling.isPaidTool(name))const unaffordable = canAffordPaidTool() ? [] : available.filter((name) => chatBilling.isPaidTool(name))const toolNames = available.filter((name) => !unaffordable.includes(name))const sections = await Promise.all(toolNames.map(async (name) => {@@ -214,11 +227,16 @@ async function renderSkill({ skill, guide, registry, core, canAffordPaidTool }:return [`# Skill: ${skill.name}`,...(guide === undefined ? [] : [guide]),+ ...(attached.length === 0 ? [] : [`## Tools now attached to you: call them by their own name, not through ${LAZY_TOOL_NAME}\n${attached.join(', ')}`]),...(sections.length === 0 ? [] : [`## Tools: call each one through ${LAZY_TOOL_NAME}, never by its own name`, ...sections]),...(unaffordable.length === 0 ? [] : [`Not available, the balance cannot cover these paid tools: ${unaffordable.join(', ')}. Tell the user if the task needs them.`]),].join('\n\n')}+function attachableToolNames({ skill, registry }: { skill: AgentSkill | undefined, registry: ToolSet }): string[] {+ return (skill?.toolNames ?? []).filter((name) => name in registry && !chatBilling.isPaidTool(name))+}+function descriptionOf(target: ToolSet[string] | undefined): string {return typeof target?.description === 'string' ? target.description : ''}@@ -278,5 +296,6 @@ type LazyToolInput = z.infer<typeof LAZY_TOOL_OUTER_SCHEMA>export type SkillSurfaceResult = {tools: ToolSetcoreToolNames: string[]+ attachedToolNames: () => string[]catalogNote: string}diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-context.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-context.tsnew file mode 100644index 00000000000..0a16892636e--- /dev/null+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-context.ts@@ -0,0 +1,16 @@+import { AsyncLocalStorage } from 'node:async_hooks'++function run<T>({ title, fn }: { title: string, fn: () => Promise<T> }): Promise<T> {+ return storage.run({ title }, fn)+}++function currentTitle(): string | undefined {+ return storage.getStore()?.title+}++const storage = new AsyncLocalStorage<{ title: string }>()++export const taskContext = {+ run,+ currentTitle,+}diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.tsnew file mode 100644index 00000000000..f96a55615ca--- /dev/null+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/task-subagent-tools.ts@@ -0,0 +1,365 @@+import { isNil, isObject, omit, tryCatch } from '@activepieces/core-utils'+import { AGENT_SURFACE_TOOLS, AgentPhase, BeginAgentTaskResponse, chatBilling, FinishAgentTaskRequest, PersistedAgentPart, PersistedAgentPartType, PersistedToolCallStatus, SkillSurface, SubagentActivity, SubagentTaskArtifact, TASK_COMPLETION_TOOL_NAME } from '@activepieces/shared'+import { hasToolCall, isLoopFinished, ModelMessage, tool, ToolSet } from 'ai'+import { z } from 'zod'+import { AgentTurnResult, runAgentTurn, RunAgentTurnParams } from '../run-agent-turn'+import { taskContext } from './task-context'+import { AgentEventEmitter } from './tool-primitives'++export function createTaskSubagentTools({ tools, taskPrompt, ...rest }: Omit<TaskDeps, 'workerTools' | 'taskPrompt'> & {+ tools: ToolSet+ taskPrompt: string | undefined+}): ToolSet {+ if (isNil(taskPrompt)) {+ return {}+ }+ const deps: TaskDeps = {+ ...rest,+ taskPrompt,+ workerTools: Object.fromEntries(Object.entries(tools).filter(([name]) => !NOT_FOR_TASKS.includes(name))),+ }+ return {+ [TASK_TOOL_NAME]: tool({+ description: 'Hand one self-contained goal to a focused sub-agent with its own fresh context and the same tools you have (read, search, build, update, execute; risky actions still ask the user for approval). Use it when it buys something: independent goals that can run in parallel (several calls in one step run at once), or noisy preparation with a short answer (going through many records or runs, investigating a failure). Build flows yourself, even several at once, and make small edits yourself. It cannot ask the user anything: when it needs something only the user can give it finishes as blocked and says what. Pass taskId to continue a task you started earlier in this conversation (after a block, or for a follow-up on what it built).',+ inputSchema: taskInput,+ toModelOutput: ({ output }) => ({ type: 'text', value: JSON.stringify(omit(output, ['activity', 'billedToolCalls'])) }),+ execute: async ({ title, brief, taskId }, { toolCallId }) => runTask({ deps, title, brief, taskId, progressId: toolCallId }),+ }),+ }+}++async function runTask({ deps, title, brief, taskId, progressId }: {+ deps: TaskDeps+ title: string+ brief: string+ taskId?: string+ progressId: string+}): Promise<TaskRunOutput> {+ const { workerTools, guides, models, tier, taskPrompt, creditsLeftFor, beginTask, finishTask, eventEmitter, abortSignal, log } = deps+ if (abortSignal.aborted) {+ return { status: 'failed', summary: 'Stopped before it started.' }+ }+ const { data: begun, error } = await tryCatch(() => beginTask({ title, ...(isNil(taskId) ? {} : { taskId }) }))+ if (error || isNil(begun)) {+ return { status: 'failed', summary: `Could not start this task: ${error instanceof Error ? error.message : 'unknown error'}` }+ }+ const startedAt = new Date()+ const report = (activity: SubagentActivity) => eventEmitter.emitSubagentProgress({ toolCallId: progressId, data: { ...activity, taskId: begun.taskId } })+ report({ title, status: 'running', stepCount: 0, startedAt: startedAt.toISOString() })+ const finish: { result?: TaskResult } = {}+ const priorMessages = begun.messages.filter(isModelMessage)+ const messages: ModelMessage[] = [...priorMessages, { role: 'user', content: brief }]+ const phaseState: { phase: AgentPhase } = { phase: 'build' }+ const taskTools = {+ ...workerTools,+ ...finishTool(finish),+ }+ const turnParams: RunAgentTurnParams = {+ models,+ systemPrompt: taskPrompt,+ messages,+ tools: taskTools,+ allToolNames: Object.keys(taskTools),+ tier,+ phaseState,+ abortSignal,+ log,+ creditsLeft: creditsLeftFor(progressId),+ stopWhen: [isLoopFinished(), hasToolCall(TASK_COMPLETION_TOOL_NAME)],+ skills: { surface: TASK_SKILL_SURFACE, guides },+ sinks: {+ drainStream: async (result) => {+ await result.consumeStream()+ return undefined+ },+ onProgress: ({ uiParts }) => report(runningActivity({ title, uiParts, startedAt })),+ },+ }+ const workTurn = await workUntilSettled({ title, turnParams, finished: () => !isNil(finish.result) })+ const turn = isNil(finish.result) && endedCleanly({ turn: workTurn, abortSignal })+ ? await continueTurn({ title, turnParams, previous: workTurn, request: REPORT_REQUEST, overrides: { stepCeiling: REPORT_STEPS } })+ : workTurn+ const reported = finish.result ?? fallbackResult(turn)+ const result = abortSignal.aborted ? stoppedResult(reported) : reported+ const activity = finalActivity({ title, turn, result, startedAt })+ await saveTaskResult({+ finishTask,+ log,+ request: {+ taskId: begun.taskId,+ claimId: begun.claimId,+ status: STATUS_BY_RESULT[result.status],+ messages: [...messages, ...turn.accumulatedResponseMessages],+ summary: result.summary,+ artifacts: result.artifacts,+ },+ })+ report(activity)+ return {+ taskId: begun.taskId,+ status: result.status,+ summary: result.summary,+ artifacts: result.artifacts,+ ...(isNil(result.needs) ? {} : { needs: result.needs }),+ activity,+ billedToolCalls: billedToolCalls(turn.uiParts),+ }+}++async function saveTaskResult({ finishTask, log, request }: {+ finishTask: TaskDeps['finishTask']+ log: TaskDeps['log']+ request: Omit<FinishAgentTaskRequest, 'platformId' | 'conversationId'>+}): Promise<void> {+ const { error } = await tryCatch(() => finishTask(request))+ if (isNil(error)) {+ return+ }+ const { error: retryError } = await tryCatch(() => finishTask(request))+ if (!isNil(retryError)) {+ log.error({ error: retryError, task: { id: request.taskId } }, '[taskSubagent] Could not save the task result, so it cannot be resumed')+ }+}++async function workUntilSettled({ title, turnParams, finished }: {+ title: string+ turnParams: RunAgentTurnParams+ finished: () => boolean+}): Promise<AgentTurnResult> {+ const first = await taskContext.run({ title, fn: () => runAgentTurn(turnParams) })+ return continueAfterInterruptions({ title, turnParams, finished, turn: first, continuationsLeft: MAX_CONTINUATIONS })+}++async function continueAfterInterruptions({ title, turnParams, finished, turn, continuationsLeft }: {+ title: string+ turnParams: RunAgentTurnParams+ finished: () => boolean+ turn: AgentTurnResult+ continuationsLeft: number+}): Promise<AgentTurnResult> {+ const shouldContinue = !finished() && continuationsLeft > 0 && interruptedTransiently({ turn, abortSignal: turnParams.abortSignal })+ if (!shouldContinue) {+ return turn+ }+ const continued = await continueTurn({ title, turnParams, previous: turn, request: CONTINUE_REQUEST, overrides: {} })+ return continueAfterInterruptions({ title, turnParams, finished, turn: continued, continuationsLeft: continuationsLeft - 1 })+}++async function continueTurn({ title, turnParams, previous, request, overrides }: {+ title: string+ turnParams: RunAgentTurnParams+ previous: AgentTurnResult+ request: string+ overrides: Partial<RunAgentTurnParams>+}): Promise<AgentTurnResult> {+ const requestMessage: ModelMessage = { role: 'user', content: request }+ const next = await taskContext.run({+ title,+ fn: () => runAgentTurn({+ ...turnParams,+ ...overrides,+ messages: [...turnParams.messages, ...previous.accumulatedResponseMessages, requestMessage],+ priorToolCalls: [...(turnParams.priorToolCalls ?? []), ...billedToolCalls(previous.uiParts)],+ sinks: withEarlierParts({ sinks: turnParams.sinks, earlierParts: previous.uiParts }),+ }),+ })+ return {+ ...next,+ uiParts: [...previous.uiParts, ...next.uiParts],+ accumulatedResponseMessages: [...previous.accumulatedResponseMessages, requestMessage, ...next.accumulatedResponseMessages],+ }+}++function withEarlierParts({ sinks, earlierParts }: { sinks: RunAgentTurnParams['sinks'], earlierParts: PersistedAgentPart[] }): RunAgentTurnParams['sinks'] {+ if (isNil(sinks)) {+ return sinks+ }+ const onProgress = sinks.onProgress+ return {+ ...sinks,+ ...(isNil(onProgress) ? {} : { onProgress: (progress: Parameters<typeof onProgress>[0]) => onProgress({ ...progress, uiParts: [...earlierParts, ...progress.uiParts] }) }),+ }+}++function interruptedTransiently({ turn, abortSignal }: { turn: AgentTurnResult, abortSignal: AbortSignal }): boolean {+ return !abortSignal.aborted && !outOfBudget(turn) && (turn.streamError !== null || turn.truncatedAfterRetries)+}++function endedCleanly({ turn, abortSignal }: { turn: AgentTurnResult, abortSignal: AbortSignal }): boolean {+ return !abortSignal.aborted && turn.streamError === null && !outOfBudget(turn)+}++function outOfBudget(turn: AgentTurnResult): boolean {+ return turn.creditsExhausted || turn.budgetExceeded+}++function finishTool(finish: { result?: TaskResult }): ToolSet {+ return {+ [TASK_COMPLETION_TOOL_NAME]: tool({+ description: 'Call this exactly once, as your last action, to hand your result back. status: done when the goal is achieved, blocked when only the user can unblock you (say what in needs), failed when you tried and could not. summary: a few plain sentences the main assistant can relay. artifacts: only what you created or changed (flows, tables, records, agents) with ids and names, empty when you only read.',+ inputSchema: taskResult,+ execute: async (result) => {+ finish.result = result+ return { content: [{ type: 'text', text: 'Result recorded.' }] }+ },+ }),+ }+}++function stoppedResult(reported: TaskResult): TaskResult {+ return { ...reported, status: 'failed', summary: `Stopped by the user before it finished. ${reported.summary}` }+}++function fallbackResult(turn: AgentTurnResult): TaskResult {+ const lastMessage = lastText(turn.uiParts)+ return {+ status: 'failed',+ summary: lastMessage.length > 0 ? lastMessage : 'The task stopped without reporting a result. Check its work before relying on it.',+ artifacts: [],+ }+}++function runningActivity({ title, uiParts, startedAt }: { title: string, uiParts: PersistedAgentPart[], startedAt: Date }): SubagentActivity {+ const statuses = statusLines(uiParts)+ return {+ title,+ status: 'running',+ statusLine: statuses[statuses.length - 1] ?? lastToolTitle(uiParts),+ stepCount: uiParts.filter((part) => part.type === PersistedAgentPartType.TOOL_CALL).length,+ pieces: piecesFrom(uiParts),+ startedAt: startedAt.toISOString(),+ }+}++function finalActivity({ title, turn, result, startedAt }: { title: string, turn: AgentTurnResult, result: TaskResult, startedAt: Date }): SubagentActivity {+ return {+ ...runningActivity({ title, uiParts: turn.uiParts, startedAt }),+ status: result.status,+ artifacts: result.artifacts,+ summary: result.summary,+ ...(isNil(result.needs) ? {} : { needs: result.needs }),+ durationMs: Date.now() - startedAt.getTime(),+ }+}++function lastToolTitle(parts: PersistedAgentPart[]): string | undefined {+ return parts.filter(isTitledToolCall).at(-1)?.title.trim()+}++function isTitledToolCall(part: PersistedAgentPart): part is Extract<PersistedAgentPart, { type: PersistedAgentPartType.TOOL_CALL }> & { title: string } {+ return part.type === PersistedAgentPartType.TOOL_CALL && !isNil(part.title) && part.title.trim().length > 0+}++function statusLines(parts: PersistedAgentPart[]): string[] {+ return parts.flatMap((part) => part.type === PersistedAgentPartType.THINKING_STATUS && part.text.trim().length > 0 ? [part.text.trim()] : [])+}++function billedToolCalls(parts: PersistedAgentPart[]): { toolName: string, output: unknown }[] {+ return parts.flatMap((part) => part.type === PersistedAgentPartType.TOOL_CALL && part.status === PersistedToolCallStatus.COMPLETED && chatBilling.isFlatBilledToolCall({ toolName: part.toolName, output: part.output })+ ? [{ toolName: part.toolName, output: billingOutput(part.output) }]+ : [])+}++function billingOutput(output: unknown): Record<string, unknown> {+ return isObject(output) && output['billedAtCost'] === true ? { billedAtCost: true } : {}+}++function piecesFrom(parts: PersistedAgentPart[]): string[] {+ const names = parts.flatMap((part) => part.type === PersistedAgentPartType.TOOL_CALL ? pieceNamesIn(part.input) : [])+ return [...new Set(names)]+}++function pieceNamesIn(input: unknown): string[] {+ if (!isObject(input)) {+ return []+ }+ const own = typeof input['pieceName'] === 'string' ? [input['pieceName']] : []+ const trigger = pieceNamesIn(input['trigger'])+ const steps = Array.isArray(input['steps']) ? input['steps'].flatMap(pieceNamesIn) : []+ return [...trigger, ...own, ...steps]+}++function lastText(parts: PersistedAgentPart[]): string {+ const texts = parts.flatMap((part) => part.type === PersistedAgentPartType.TEXT && part.text.trim().length > 0 ? [part.text.trim()] : [])+ return texts[texts.length - 1] ?? ''+}++function isModelMessage(value: unknown): value is ModelMessage {+ return isObject(value) && typeof value['role'] === 'string' && 'content' in value+}++const taskInput = z.object({+ title: z.string().min(1).describe('A short plain name for the task the user will see, e.g. "Build Save order" or "Research Twilio WhatsApp"'),+ brief: z.string().min(1).describe('Everything the sub-agent needs, self-contained: the goal and when it is done, what it owns (and must not change), ids and decisions already made, connections to use. For a resumed task, the new instruction or the user\'s answer.'),+ taskId: z.string().optional().describe('Continue a task from earlier in this conversation instead of starting a new one'),+})++const taskResult = z.object({+ status: z.enum(['done', 'blocked', 'failed']),+ summary: z.string().describe('A few plain sentences: what you did and what the main assistant should tell the user'),+ artifacts: z.array(SubagentTaskArtifact).describe('Only what you created or changed. Empty when you only read.'),+ needs: z.string().optional().describe('When blocked: exactly what you need from the user'),+})++const STATUS_BY_RESULT: Record<TaskResult['status'], FinishAgentTaskRequest['status']> = {+ done: 'DONE',+ blocked: 'BLOCKED',+ failed: 'FAILED',+}++const TASK_TOOL_NAME = 'ap_run_task'+const TASK_SKILL_SURFACE: SkillSurface = 'CHAT'+const REPORT_REQUEST = `You stopped without reporting. Call ${TASK_COMPLETION_TOOL_NAME} now with your result.`+const CONTINUE_REQUEST = 'You were cut off. Continue from where you stopped.'+const MAX_CONTINUATIONS = 2+const REPORT_STEPS = 2++const NOT_FOR_TASKS = [+ TASK_TOOL_NAME,+ 'ap_retry_run',+ ...AGENT_SURFACE_TOOLS,+ 'ap_update_thinking_status',+ 'ap_send_email',+ 'ap_show_questions',+ 'ap_show_quick_replies',+ 'ap_show_connection_picker',+ 'ap_show_connection_required',+ 'ap_show_project_picker',+ 'ap_show_mcp_reconnect',+ 'ap_show_showcase',+ 'ap_set_build_plan',+ 'ap_select_project',+ 'ap_deselect_project',+ 'ap_remember',+ 'ap_generate_image',+ 'ap_test_flow',+ 'ap_test_step',+ 'ap_lock_and_publish',+ 'ap_change_flow_status',+]++type TaskResult = z.infer<typeof taskResult>++type TaskDeps = {+ workerTools: ToolSet+ guides: Record<string, string>+ models: RunAgentTurnParams['models']+ tier: RunAgentTurnParams['tier']+ taskPrompt: string+ creditsLeftFor: (runKey: string) => RunAgentTurnParams['creditsLeft']+ beginTask: (input: { title: string, taskId?: string }) => Promise<BeginAgentTaskResponse>+ finishTask: (input: Omit<FinishAgentTaskRequest, 'platformId' | 'conversationId'>) => Promise<void>+ eventEmitter: AgentEventEmitter+ abortSignal: AbortSignal+ log: RunAgentTurnParams['log']+}++type TaskRunOutput = {+ taskId?: string+ status: TaskResult['status']+ summary: string+ artifacts?: TaskResult['artifacts']+ needs?: string+ activity?: SubagentActivity+ billedToolCalls?: { toolName: string, output: unknown }[]+}diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.tsindex 21fd74f46e8..bde3aca4bfc 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts@@ -1,6 +1,6 @@import { isNil, isObject, spreadIfDefined } from '@activepieces/core-utils'import { largeResultUtils, MAX_TOOL_RESULT_BYTES } from '@activepieces/server-utils'-import { ActionPreviewEvent, ActionReceiptEvent, agentToolClassification, agentToolPhases, BuildPlanEvent, FileProducedEvent, ImageGeneratedEvent, PersistedAgentMessageSchema, PersistedAgentRole, ToolProgressEvent } from '@activepieces/shared'+import { ActionPreviewEvent, ActionReceiptEvent, agentToolClassification, agentToolPhases, BuildPlanEvent, FileProducedEvent, ImageGeneratedEvent, PersistedAgentMessageSchema, PersistedAgentRole, SubagentProgressEvent, ToolProgressEvent } from '@activepieces/shared'import { JSONSchema7, ToolExecutionOptions, ToolSet } from 'ai'import { z } from 'zod'@@ -61,7 +61,7 @@ export function truncateLargeResult(result: unknown): unknown {maxBytes: MAX_TOOL_RESULT_BYTES,wrap: (json) => buildOversizeEnvelope({result,- text: `[LARGE RESPONSE — long values were truncated to fit, structure preserved]${sizeNote} Truncated values are marked with "…[truncated]".\n\n${json}`,+ text: `[LARGE RESPONSE — long values were truncated to fit, structure preserved]${sizeNote} Truncated values are marked with "…[truncated]". This is not the full data, so never answer as if you saw all of it: narrow the request (a filter, fewer items or fields), or hand the digging to a task when you can.\n\n${json}`,}),})return fitted ?? buildOversizeEnvelope({@@ -178,6 +178,7 @@ export type AgentEventEmitter = {emitImageGenerated(data: ImageGeneratedEvent): voidemitFileProduced(data: FileProducedEvent): voidemitBuildPlan(data: BuildPlanEvent): void+ emitSubagentProgress(data: SubagentProgressEvent): void}export type TaintState = { tainted: boolean }diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-title.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-title.test.tsnew file mode 100644index 00000000000..0468d2502c6--- /dev/null+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-title.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest'+import { agentTitle } from '../../../../../../src/lib/execute/jobs/ee/agent/agent-title'++describe('agentTitle.finalize', () => {+ it('strips markdown and quotes from a generated title', () => {+ expect(agentTitle.finalize('"**Failing Flow Audit**"')).toBe('Failing Flow Audit')+ })++ it('caps the title at 100 characters', () => {+ expect(agentTitle.finalize('x'.repeat(150))).toHaveLength(100)+ })+})diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/credit-ledger.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/credit-ledger.test.tsnew file mode 100644index 00000000000..9d8ec60af6a--- /dev/null+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/credit-ledger.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it, vi } from 'vitest'+import { creditLedger } from '../../../../../../src/lib/execute/jobs/ee/agent/credit-ledger'++describe('creditLedger', () => {+ it('adds up the tool calls of every run but charges the message once', async () => {+ const creditsLeft = vi.fn().mockResolvedValue(10)+ const creditsLeftFor = creditLedger.create({ creditsLeft, messageCredits: 1 })++ await creditsLeftFor('main')(3)+ await creditsLeftFor('task-a')(2)+ await creditsLeftFor('task-b')(4)++ expect(creditsLeft).toHaveBeenLastCalledWith(7)+ })++ it('replaces a run\'s earlier pending total instead of adding it again', async () => {+ const creditsLeft = vi.fn().mockResolvedValue(10)+ const creditsLeftFor = creditLedger.create({ creditsLeft, messageCredits: 0 })++ await creditsLeftFor('main')(1)+ await creditsLeftFor('main')(2)++ expect(creditsLeft).toHaveBeenLastCalledWith(2)+ })+})diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/declined-actions.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/declined-actions.test.tsnew file mode 100644index 00000000000..4e758a0fb86--- /dev/null+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/declined-actions.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it, vi } from 'vitest'+import { declinedActions } from '../../../../../../src/lib/execute/jobs/ee/agent/declined-actions'++describe('declinedActions', () => {+ it('declines a repeat of an action the user already said no to, without showing a new card', () => {+ const emitActionPreview = vi.fn()+ const declines = declinedActions.create({ eventEmitter: emitterWith(emitActionPreview) })++ declines.eventEmitter.emitActionPreview(preview('gate-1'))+ declines.recordDecision({ gateId: 'gate-1', approved: false })+ declines.eventEmitter.emitActionPreview(preview('gate-2'))++ expect(declines.isDeclined('gate-2')).toBe(true)+ expect(emitActionPreview).toHaveBeenCalledTimes(1)+ })++ it('keeps asking after an approval, and for other actions', () => {+ const emitActionPreview = vi.fn()+ const declines = declinedActions.create({ eventEmitter: emitterWith(emitActionPreview) })++ declines.eventEmitter.emitActionPreview(preview('gate-1'))+ declines.recordDecision({ gateId: 'gate-1', approved: true })+ declines.eventEmitter.emitActionPreview(preview('gate-2'))+ declines.eventEmitter.emitActionPreview({ ...preview('gate-3'), actionName: 'ap_delete_flow' })++ expect(declines.isDeclined('gate-2')).toBe(false)+ expect(declines.isDeclined('gate-3')).toBe(false)+ expect(emitActionPreview).toHaveBeenCalledTimes(3)+ })++ it('only keeps the refused operation declined, not the same action on something else', () => {+ const emitActionPreview = vi.fn()+ const declines = declinedActions.create({ eventEmitter: emitterWith(emitActionPreview) })+ const deleteFlow = (gateId: string, flowId: string, title: string) => ({ ...preview(gateId), actionName: 'ap_delete_flow', input: { flowId, title } })++ declines.eventEmitter.emitActionPreview(deleteFlow('gate-1', 'flow-a', 'Deleting flow A'))+ declines.recordDecision({ gateId: 'gate-1', approved: false })+ declines.eventEmitter.emitActionPreview(deleteFlow('gate-2', 'flow-a', 'Removing flow A'))+ declines.eventEmitter.emitActionPreview(deleteFlow('gate-3', 'flow-b', 'Deleting flow B'))++ expect(declines.isDeclined('gate-2')).toBe(true)+ expect(declines.isDeclined('gate-3')).toBe(false)+ })+})++function preview(toolCallId: string): { toolCallId: string, pieceName: string, actionName: string, actionDisplayName: string, input: Record<string, unknown>, isBatch: boolean } {+ return { toolCallId, pieceName: 'email', actionName: 'ap_send_email', actionDisplayName: 'Send email', input: {}, isBatch: false }+}++function emitterWith(emitActionPreview: () => void): Parameters<typeof declinedActions.create>[0]['eventEmitter'] {+ return { emitToolProgress: vi.fn(), emitActionPreview, emitActionReceipt: vi.fn(), emitImageGenerated: vi.fn(), emitFileProduced: vi.fn(), emitBuildPlan: vi.fn(), emitSubagentProgress: vi.fn() }+}diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.tsindex 3f898525f53..12bf3ed8f95 100644--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.ts+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/run-agent-turn-history.test.ts@@ -1,7 +1,7 @@import { AIProviderName } from '@activepieces/core-utils'import { ModelMessage, tool } from 'ai'import { convertArrayToReadableStream, MockLanguageModelV3 } from 'ai/test'-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import { z } from 'zod'import { runAgentTurn } from '../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn'@@ -32,6 +32,29 @@ describe('the history a turn leaves behind', () => {expect(rolesAndParts(progress[progress.length - 1])).toEqual(['assistant:tool-call', 'tool:tool-result', 'assistant:text'])})+ it('counts paid calls from before a cut-off when it checks credits', async () => {+ const creditsLeft = vi.fn().mockResolvedValue(100)++ await runAgentTurn({+ models: [{ model: updateThenConfirm(), provider: AIProviderName.ANTHROPIC, modelId: TIER.modelId, thinkingBudget: TIER.thinkingBudget }],+ systemPrompt: 'You are a test agent.',+ messages: [{ role: 'user', content: 'Change the instructions of New agent to: Reply in Arabic.' }],+ tools: {+ ap_update_agent: tool({ description: 'change an agent', inputSchema: z.object({ instructions: z.string() }), execute: async () => ({ saved: true }) }),+ },+ allToolNames: ['ap_update_agent'],+ tier: TIER,+ phaseState: { phase: 'build' },+ abortSignal: new AbortController().signal,+ log: SILENT_LOG,+ creditsLeft,+ priorToolCalls: [{ toolName: 'ap_web_search', output: {} }],+ sinks: { drainStream: (result) => result.consumeStream() },+ })++ expect(creditsLeft).toHaveBeenCalledWith(2)+ })+it('keeps every finished step when the turn is cancelled partway, not just the last one', async () => {const controller = new AbortController()let saves = 0diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/skill-tools.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/skill-tools.test.tsindex e15a75acb34..5c3ffc86ab4 100644--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/skill-tools.test.ts+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/skill-tools.test.ts@@ -60,6 +60,16 @@ describe('buildSkillSurface', () => {expect(surface.tools['ap_add_step']).toBeDefined()})+ it('attaches a skill\'s tools directly once it is loaded', async () => {+ const surface = chatSurface()+ expect(surface.attachedToolNames()).not.toContain('ap_build_flow')+ const playbook = String(await surface.tools['ap_load_skill']?.execute?.({ skills: ['flow_building'] }, CALL_OPTIONS))+ expect(surface.attachedToolNames()).toEqual(expect.arrayContaining(['ap_build_flow', 'ap_add_step', 'ap_test_flow', ...surface.coreToolNames]))+ expect(surface.attachedToolNames()).not.toContain('ap_list_tables')+ expect(playbook).toContain('Tools now attached to you')+ expect(playbook).not.toContain('Call: ap_lazy_tool with tool: "ap_build_flow"')+ })+it('lists tools no skill covers in the catalog note', () => {expect(chatSurface().catalogNote).toContain('mcp__gmail__send_email')})@@ -105,7 +115,7 @@ describe('paid tools', () => {const surfaceFor = (canAfford: boolean) => buildSkillSurface({ tools, surface: 'CHAT', guides: {}, onSkillLoaded: vi.fn(), canAffordPaidTool: () => canAfford })const lowPlaybook = String(await surfaceFor(false).tools['ap_load_skill']?.execute?.({ skills: ['web_and_media'] }, CALL_OPTIONS))- expect(lowPlaybook).toContain('### ap_fetch_url')+ expect(lowPlaybook).toMatch(/attached to you[^\n]*\nap_fetch_url/)expect(lowPlaybook).not.toContain('### ap_web_search')expect(lowPlaybook).not.toContain('### ap_scrape_url')expect(lowPlaybook).toContain('balance cannot cover these paid tools: ap_web_search, ap_scrape_url')@@ -232,6 +242,23 @@ describe('ap_lazy_tool', () => {expect(errorMessageOf(rejected)).toContain('Invalid input for "ap_rename_flow"')})+ it('shows the model what the target tool chooses to show, not its full output', async () => {+ const surface = buildSkillSurface({+ tools: {+ ...stubTools(CHAT_TOOL_NAMES),+ ap_rename_flow: tool({ description: 'Rename a flow.', inputSchema: z.object({ flowId: z.string() }), execute: async () => ({ renamed: true, internal: 'big' }), toModelOutput: () => ({ type: 'text', value: 'renamed' }) }),+ },+ surface: 'CHAT',+ guides: {},+ onSkillLoaded: vi.fn(),+ canAffordPaidTool: () => true,+ })++ const shown = await surface.tools[LAZY_TOOL_NAME]?.toModelOutput?.({ toolCallId: 'call-1', input: { tool: 'ap_rename_flow', input: { flowId: 'f1' } }, output: { renamed: true, internal: 'big' } })++ expect(shown).toEqual({ type: 'text', value: 'renamed' })+ })+it('hands a JSON-schema tool its input unchanged', async () => {const execute = vi.fn(async () => ({ renamed: true }))await executeWrapped({ surface: surfaceWithJsonSchemaTool(execute), toolName: 'ap_rename_flow', input: { flowId: 'f1' } })diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.tsnew file mode 100644index 00000000000..93d8735e54c--- /dev/null+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/task-subagent-tools.test.ts@@ -0,0 +1,308 @@+import { AIProviderName } from '@activepieces/core-utils'+import { PersistedAgentPartType, PersistedToolCallStatus, TASK_COMPLETION_TOOL_NAME } from '@activepieces/shared'+import { tool, ToolExecutionOptions, ToolSet } from 'ai'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { z } from 'zod'++const runAgentTurn = vi.fn()+vi.mock('../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn', () => ({+ runAgentTurn: (...args: unknown[]) => runAgentTurn(...args),+}))++import { RunAgentTurnParams } from '../../../../../../src/lib/execute/jobs/ee/agent/run-agent-turn'+import { createTaskSubagentTools } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/task-subagent-tools'+import { taskContext } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/task-context'++describe('createTaskSubagentTools', () => {+ beforeEach(() => {+ runAgentTurn.mockReset()+ emitSubagentProgress.mockReset()+ beginTask.mockReset()+ finishTask.mockReset()+ beginTask.mockResolvedValue({ taskId: 'task-1', claimId: 'claim-1', messages: [] })+ finishTask.mockResolvedValue(undefined)+ })++ it('runs the goal with every tool except the user-facing ones, inside the task context', async () => {+ let titleDuringRun: string | undefined+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ titleDuringRun = taskContext.currentTitle()+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Built it.', artifacts: [{ type: 'flow', id: 'f1', name: 'Save order' }] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow', 'ap_web_search', 'ap_execute_action', 'ap_show_questions', 'ap_show_quick_replies', 'ap_remember', 'ap_set_build_plan', 'ap_test_flow', 'ap_lock_and_publish']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Build Save order', brief: 'Build the Save order flow' }, EXECUTION_OPTIONS)++ const params = runAgentTurn.mock.calls[0][0]+ expect(Object.keys(params.tools).sort()).toEqual(['ap_build_flow', 'ap_execute_action', 'ap_web_search', TASK_COMPLETION_TOOL_NAME].sort())+ expect(params.allToolNames).toContain(TASK_COMPLETION_TOOL_NAME)+ expect(params.systemPrompt).toBe('TASK PROMPT')+ expect(params.phaseState).toEqual({ phase: 'build' })+ expect(params.messages).toEqual([{ role: 'user', content: 'Build the Save order flow' }])+ expect(titleDuringRun).toBe('Build Save order')+ expect(result).toMatchObject({ taskId: 'task-1', status: 'done', summary: 'Built it.', artifacts: [{ type: 'flow', id: 'f1', name: 'Save order' }], billedToolCalls: [{ toolName: 'ap_web_search', output: {} }] })+ expect(finishTask).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-1', claimId: 'claim-1', status: 'DONE', summary: 'Built it.', messages: [{ role: 'user', content: 'Build the Save order flow' }, { role: 'assistant', content: 'ok' }] }))+ })++ it('resumes an earlier task with its history, and shows its own status line live', async () => {+ beginTask.mockResolvedValue({ taskId: 'task-1', claimId: 'claim-1', messages: [{ role: 'user', content: 'first brief' }, { role: 'assistant', content: 'blocked' }] })+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet, sinks: { onProgress: (progress: { uiParts: unknown[] }) => void } }) => {+ params.sinks.onProgress({ uiParts: [{ type: PersistedAgentPartType.THINKING_STATUS, text: 'Checking the Gmail connection' }] })+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'blocked', summary: 'Gmail is not connected.', artifacts: [], needs: 'A Gmail connection' }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Build Save order', brief: 'Gmail is connected now', taskId: 'task-1' }, EXECUTION_OPTIONS)++ expect(beginTask).toHaveBeenCalledWith({ title: 'Build Save order', taskId: 'task-1' })+ expect(runAgentTurn.mock.calls[0][0].messages).toEqual([{ role: 'user', content: 'first brief' }, { role: 'assistant', content: 'blocked' }, { role: 'user', content: 'Gmail is connected now' }])+ expect(emitSubagentProgress.mock.calls.map(([event]) => event.data.statusLine)).toContain('Checking the Gmail connection')+ expect(result).toMatchObject({ status: 'blocked', needs: 'A Gmail connection' })+ expect(finishTask).toHaveBeenCalledWith(expect.objectContaining({ status: 'BLOCKED' }))+ })++ it('keeps the card details out of what the main model reads', async () => {+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })++ const view = await tasks['ap_run_task'].toModelOutput?.({ toolCallId: 'call-1', input: { title: 't', brief: 'b' }, output: { taskId: 'task-1', status: 'done', summary: 'ok', artifacts: [], activity: { steps: [] }, billedToolCalls: [] } })++ expect(view).toEqual({ type: 'text', value: JSON.stringify({ taskId: 'task-1', status: 'done', summary: 'ok', artifacts: [] }) })+ })++ it('asks a task that stopped without reporting for its result, keeping its tools so the cache holds', async () => {+ runAgentTurn+ .mockResolvedValueOnce(turnResult())+ .mockImplementationOnce(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Asana costs $13.49 a seat.', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research Asana', brief: 'Find pricing' }, EXECUTION_OPTIONS)++ const [workParams, reportParams] = runAgentTurn.mock.calls.map(([params]) => params)+ expect(Object.keys(reportParams.tools)).toEqual(Object.keys(workParams.tools))+ expect(reportParams.stepCeiling).toBe(2)+ expect(result).toMatchObject({ status: 'done', summary: 'Asana costs $13.49 a seat.' })+ })++ it('reports a task the user stopped as stopped, even after it filed a result', async () => {+ const controller = new AbortController()+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Built.', artifacts: [] }, EXECUTION_OPTIONS)+ controller.abort()+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, abortSignal: controller.signal, tools: toolSet(['ap_build_flow']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ status: 'failed', activity: { status: 'failed' } })+ expect(finishTask).toHaveBeenCalledWith(expect.objectContaining({ status: 'FAILED' }))+ })++ it('picks up where it was cut off and finishes in the same task', async () => {+ runAgentTurn+ .mockResolvedValueOnce({ ...turnResult(), streamError: new Error('stream dropped') })+ .mockImplementationOnce(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Done after the drop.', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(runAgentTurn).toHaveBeenCalledTimes(2)+ expect(runAgentTurn.mock.calls[1][0].messages.at(-1)).toMatchObject({ role: 'user' })+ expect(result).toMatchObject({ status: 'done', summary: 'Done after the drop.' })+ })++ it('carries the paid calls made before a cut-off into the continued turn', async () => {+ runAgentTurn+ .mockResolvedValueOnce({ ...turnResult(), streamError: new Error('stream dropped') })+ .mockImplementationOnce(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(runAgentTurn.mock.calls[1][0].priorToolCalls).toEqual([{ toolName: 'ap_web_search', output: {} }])+ })++ it('keeps the steps from before a cut-off in its live progress', async () => {+ runAgentTurn+ .mockResolvedValueOnce({ ...turnResult(), streamError: new Error('stream dropped') })+ .mockImplementationOnce(async (params: { tools: ToolSet, sinks: { onProgress: (progress: { uiParts: unknown[] }) => void } }) => {+ params.sinks.onProgress({ uiParts: [{ type: PersistedAgentPartType.THINKING_STATUS, text: 'Writing the summary' }] })+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ const lines = emitSubagentProgress.mock.calls.map(([event]) => event.data.statusLine)+ expect(lines).toContain('Writing the summary')+ const continued = emitSubagentProgress.mock.calls.find(([event]) => event.data.statusLine === 'Writing the summary')+ expect(continued?.[0].data.stepCount).toBe(1)+ })++ it('stops retrying an interrupted task after its budget of continuations', async () => {+ runAgentTurn.mockResolvedValue({ ...turnResult(), streamError: new Error('stream dropped') })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(runAgentTurn).toHaveBeenCalledTimes(3)+ expect(result).toMatchObject({ status: 'failed' })+ })++ it('marks a task that stopped without reporting as failed', async () => {+ runAgentTurn.mockResolvedValue(turnResult())+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ status: 'failed' })+ expect(finishTask).toHaveBeenCalledWith(expect.objectContaining({ status: 'FAILED' }))+ })++ it('reports a task that could not start, such as one still running', async () => {+ beginTask.mockRejectedValue(new Error('Task task-1 does not exist in this conversation or is still running'))+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Again', taskId: 'task-1' }, EXECUTION_OPTIONS)++ expect(result).toMatchObject({ status: 'failed', summary: expect.stringContaining('still running') })+ expect(runAgentTurn).not.toHaveBeenCalled()+ })++ it('starts nothing once the run is stopped', async () => {+ const controller = new AbortController()+ controller.abort()+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, abortSignal: controller.signal, tools: toolSet(['ap_build_flow']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)++ expect(beginTask).not.toHaveBeenCalled()+ expect(result).toMatchObject({ status: 'failed' })+ })++ it('keeps the result when saving it fails once', async () => {+ finishTask.mockRejectedValueOnce(new Error('api restarting'))+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'Saved on retry.', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_web_search']) })++ const result = await tasks['ap_run_task'].execute?.({ title: 'Research', brief: 'Find out' }, EXECUTION_OPTIONS)++ expect(finishTask).toHaveBeenCalledTimes(2)+ expect(result).toMatchObject({ status: 'done', summary: 'Saved on retry.' })+ })++ it('loads its guides as skills and keeps them for the report turn', async () => {+ runAgentTurn+ .mockResolvedValueOnce(turnResult())+ .mockImplementationOnce(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })++ await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)++ const [workTurn, reportTurn] = runAgentTurn.mock.calls.map(([params]) => params)+ expect(workTurn.skills).toEqual({ surface: 'CHAT', guides: BASE_PARAMS.guides })+ expect(reportTurn.skills).toEqual(workTurn.skills)+ })++ it('never gives a task the status tool or email to the user, which stay with the main chat', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow', 'ap_update_thinking_status', 'ap_send_email', 'ap_retry_run']) })++ await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)++ expect(Object.keys(runAgentTurn.mock.calls[0][0].tools)).not.toContain('ap_update_thinking_status')+ expect(Object.keys(runAgentTurn.mock.calls[0][0].tools)).not.toContain('ap_send_email')+ expect(Object.keys(runAgentTurn.mock.calls[0][0].tools)).not.toContain('ap_retry_run')+ })++ it('shows the latest step title on the card when the task sends no status', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet, sinks: { onProgress: (progress: { uiParts: unknown[] }) => void } }) => {+ params.sinks.onProgress({ uiParts: [{ type: PersistedAgentPartType.TOOL_CALL, toolCallId: 'b1', toolName: 'ap_build_flow', title: 'Building your intake flow', input: {}, status: PersistedToolCallStatus.COMPLETED }] })+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow']) })++ await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)++ const lines = emitSubagentProgress.mock.calls.map(([event]) => event.data.statusLine)+ expect(lines).toContain('Building your intake flow')+ })++ it('never gives a task the tools that create, change or publish saved agents', async () => {+ runAgentTurn.mockImplementation(async (params: { tools: ToolSet }) => {+ await params.tools[TASK_COMPLETION_TOOL_NAME].execute?.({ status: 'done', summary: 'ok', artifacts: [] }, EXECUTION_OPTIONS)+ return turnResult()+ })+ const tasks = createTaskSubagentTools({ ...BASE_PARAMS, tools: toolSet(['ap_build_flow', 'ap_create_agent', 'ap_update_agent', 'ap_add_agent_tool']) })++ await tasks['ap_run_task'].execute?.({ title: 'Build', brief: 'Build it' }, EXECUTION_OPTIONS)++ expect(Object.keys(runAgentTurn.mock.calls[0][0].tools)).not.toEqual(expect.arrayContaining(['ap_create_agent']))+ expect(Object.keys(runAgentTurn.mock.calls[0][0].tools).filter((name) => name.includes('agent'))).toEqual([])+ })++ it('offers no task tool without a task prompt', () => {+ expect(createTaskSubagentTools({ ...BASE_PARAMS, taskPrompt: undefined, tools: toolSet(['ap_build_flow']) })).toEqual({})+ })+})++function toolSet(names: string[]): ToolSet {+ return Object.fromEntries(names.map((name) => [name, tool({ description: name, inputSchema: z.object({}), execute: async () => 'ok' })]))+}++function turnResult(): Record<string, unknown> {+ return {+ uiParts: [+ { type: PersistedAgentPartType.TOOL_CALL, toolCallId: 't1', toolName: 'ap_web_search', input: {}, status: PersistedToolCallStatus.COMPLETED, output: { content: [{ type: 'text', text: 'results' }] } },+ ],+ accumulatedResponseMessages: [{ role: 'assistant', content: 'ok' }],+ toolCalls: [],+ streamError: null,+ creditsExhausted: false,+ budgetExceeded: false,+ truncatedAfterRetries: false,+ }+}++const emitSubagentProgress = vi.fn()+const beginTask = vi.fn()+const finishTask = vi.fn()++const MODELS: RunAgentTurnParams['models'] = [{ model: 'test-model', provider: AIProviderName.OPENAI, modelId: 'm', thinkingBudget: 0 }]++const BASE_PARAMS = {+ guides: { build_flow: 'BUILD FLOW GUIDE' },+ models: MODELS,+ tier: { id: 'smart', thinkingBudget: 0, modelId: 'm' },+ taskPrompt: 'TASK PROMPT',+ creditsLeftFor: () => undefined,+ beginTask,+ finishTask,+ eventEmitter: { emitToolProgress: vi.fn(), emitActionPreview: vi.fn(), emitActionReceipt: vi.fn(), emitImageGenerated: vi.fn(), emitFileProduced: vi.fn(), emitBuildPlan: vi.fn(), emitSubagentProgress },+ abortSignal: new AbortController().signal,+ log: { debug: () => undefined, info: () => undefined, warn: () => undefined, error: () => undefined },+}++const EXECUTION_OPTIONS: ToolExecutionOptions = { toolCallId: 'call-1', messages: [] }diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 5d678cc676c..3b6caf66255 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -3266,5 +3266,18 @@"1 min ago": "1 min ago","{count} mins ago": "{count} mins ago","1 hour ago": "1 hour ago",- "{count} hours ago": "{count} hours ago"+ "{count} hours ago": "{count} hours ago",+ "Could not delete this key": "Could not delete this key",+ "Invalid file type": "Invalid file type",+ "Best for everyday use": "Best for everyday use",+ "Highest quality, a bit slower": "Highest quality, a bit slower",+ "Quick replies for simple tasks": "Quick replies for simple tasks",+ "Couldn't load {key} models": "Couldn't load {key} models",+ "Stopped early": "Stopped early",+ "Getting started": "Getting started",+ "{count, plural, =1 {Working on a task} other {Working on # tasks at once}}": "{count, plural, =1 {Working on a task} other {Working on # tasks at once}}",+ "{count, plural, =1 {Task finished} other {# tasks finished}}": "{count, plural, =1 {Task finished} other {# tasks finished}}",+ "Needs your input": "Needs your input",+ "Task": "Task",+ "Asked by {taskTitle}": "Asked by {taskTitle}"}diff --git a/packages/web/src/app/routes/chat-with-ai/components/action-preview-card.tsx b/packages/web/src/app/routes/chat-with-ai/components/action-preview-card.tsxindex a61763b2ec2..75bc81f165a 100644--- a/packages/web/src/app/routes/chat-with-ai/components/action-preview-card.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/action-preview-card.tsx@@ -42,6 +42,11 @@ export function ActionPreviewCard({: preview.actionDisplayName}>+ {preview.taskTitle && (+ <p className="truncate pb-2 text-xs text-gray-11">+ {t('Asked by {taskTitle}', { taskTitle: preview.taskTitle })}+ </p>+ )}{preview.pieceName && (<div className="flex items-center gap-2 pb-3"><PieceIconWithPieceNamediff --git a/packages/web/src/app/routes/chat-with-ai/components/assistant-message.tsx b/packages/web/src/app/routes/chat-with-ai/components/assistant-message.tsxindex df37177773b..c7c57b8536e 100644--- a/packages/web/src/app/routes/chat-with-ai/components/assistant-message.tsx+++ b/packages/web/src/app/routes/chat-with-ai/components/assistant-message.tsx@@ -53,6 +53,7 @@ import { ProducedFileCard } from './produced-file-card';import { ProjectPickerCard } from './project-picker-card';import { ShowcaseCard } from './showcase-card/showcase-card';import { ShowcaseTileData } from './showcase-card/showcase-tile';+import { SubagentGroup } from './subagent-card';import { ToolShimmerPills } from './tool-shimmer-pills';const PROSE_CLASSES = 'max-w-none break-words';@@ -397,6 +398,15 @@ function MessageBlocks({}return null;}+ case 'tasks':+ return (+ <SubagentGroup+ key={`tasks-${block.tasks[0]?.toolCallId ?? i}`}+ tasks={block.tasks}+ toolCallMeta={toolCallMeta}+ isStreaming={isStreaming}+ />+ );case 'batch-progress':return (<div key={`batch-${i}`} className="py-2">diff --git a/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsx b/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsxnew file mode 100644index 00000000000..4755b620b62--- /dev/null+++ b/packages/web/src/app/routes/chat-with-ai/components/subagent-card.tsx@@ -0,0 +1,124 @@+import { isObject } from '@activepieces/core-utils';+import { SubagentActivity } from '@activepieces/shared';+import { t } from 'i18next';+import { motion } from 'motion/react';++import { TextWithTooltip } from '@/components/custom/text-with-tooltip';+import { ToolCallMeta } from '@/features/chat/lib/chat-store';+import { AnyToolPart, chatPartUtils } from '@/features/chat/lib/chat-types';++import {+ AppLogos,+ Duration,+ LiveLine,+ StatusMark,+} from './subagent-primitives';++export function SubagentGroup({+ tasks,+ toolCallMeta,+ isStreaming,+}: {+ tasks: { toolCallId: string; part: AnyToolPart }[];+ toolCallMeta: Record<string, ToolCallMeta>;+ isStreaming: boolean;+}) {+ const activities = tasks.map(({ toolCallId, part }) => ({+ toolCallId,+ activity: resolveActivity({+ live: toolCallMeta[toolCallId]?.subagent,+ part,+ isStreaming,+ }),+ }));+ const working = activities.some(+ ({ activity }) => activity.status === 'running',+ );++ return (+ <motion.div+ className="my-2 overflow-hidden rounded-xl border bg-panel"+ initial={{ opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ duration: 0.25 }}+ >+ <div className="px-4 pt-3 pb-1 text-xs text-gray-11">+ {working+ ? t(+ '{count, plural, =1 {Working on a task} other {Working on # tasks at once}}',+ { count: tasks.length },+ )+ : t('{count, plural, =1 {Task finished} other {# tasks finished}}', {+ count: tasks.length,+ })}+ </div>+ <div className="pb-1.5">+ {activities.map(({ toolCallId, activity }) => (+ <SubagentRow key={toolCallId} activity={activity} />+ ))}+ </div>+ </motion.div>+ );+}++function SubagentRow({ activity }: { activity: SubagentActivity }) {+ return (+ <div className="flex items-center gap-3 px-4 py-2">+ <StatusMark status={activity.status} />+ <div className="min-w-0 flex-1">+ <TextWithTooltip tooltipMessage={activity.title}>+ <p className="truncate text-sm font-medium text-gray-12">+ {activity.title}+ </p>+ </TextWithTooltip>+ <LiveLine activity={activity} />+ </div>+ <AppLogos pieces={activity.pieces ?? []} />+ <Duration activity={activity} />+ </div>+ );+}++function resolveActivity({+ live,+ part,+ isStreaming,+}: {+ live: SubagentActivity | undefined;+ part: AnyToolPart;+ isStreaming: boolean;+}): SubagentActivity {+ const saved = activityFromOutput(part);+ if (saved) return saved;+ if (live) {+ const stoppedMidRun = live.status === 'running' && !isStreaming;+ return stoppedMidRun ? { ...live, status: 'failed' } : live;+ }+ const input = isObject(part.input) ? part.input : {};+ return {+ title: typeof input['title'] === 'string' ? input['title'] : t('Task'),+ status: isStreaming ? 'running' : 'failed',+ stepCount: 0,+ startedAt: '',+ };+}++function activityFromOutput(part: AnyToolPart): SubagentActivity | null {+ const parsed = chatPartUtils.parseToolOutput(part);+ if (parsed.state !== 'success' || !isObject(parsed.data)) return null;+ const activity = parsed.data['activity'];+ return isSubagentActivity(activity) ? activity : null;+}++function isSubagentActivity(value: unknown): value is SubagentActivity {+ return (+ isObject(value) &&+ typeof value['title'] === 'string' &&+ typeof value['startedAt'] === 'string' &&+ typeof value['status'] === 'string' &&+ STATUSES.includes(value['status']) &&+ typeof value['stepCount'] === 'number'+ );+}++const STATUSES: string[] = ['running', 'done', 'blocked', 'failed'];diff --git a/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsx b/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsxnew file mode 100644index 00000000000..63abf96ad06--- /dev/null+++ b/packages/web/src/app/routes/chat-with-ai/components/subagent-primitives.tsx@@ -0,0 +1,148 @@+import { SubagentActivity } from '@activepieces/shared';+import { t } from 'i18next';+import { Check, Hand, Loader2, Minus } from 'lucide-react';+import { AnimatePresence, motion } from 'motion/react';+import { useEffect, useState } from 'react';++import { TextShimmer } from '@/components/ui/text-shimmer';+import { PieceIcon } from '@/features/pieces/components/piece-icon';+import { piecesHooks } from '@/features/pieces/hooks/pieces-hooks';++export function LiveLine({ activity }: { activity: SubagentActivity }) {+ if (activity.status === 'done') {+ return <p className="text-xs leading-4 text-gray-11">{t('Done')}</p>;+ }+ if (activity.status === 'blocked') {+ return (+ <p className="text-xs leading-4 text-accent-11">+ {t('Needs your input')}+ </p>+ );+ }+ if (activity.status === 'failed') {+ return (+ <p className="text-xs leading-4 text-gray-11">{t('Stopped early')}</p>+ );+ }+ const label = activity.statusLine ?? t('Getting started');+ return (+ <AnimatePresence mode="wait" initial={false}>+ <motion.div+ key={label}+ initial={{ opacity: 0, y: 3 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -3 }}+ transition={{ duration: 0.18 }}+ >+ <TextShimmer as="p" className="truncate text-xs font-normal leading-4">+ {label}+ </TextShimmer>+ </motion.div>+ </AnimatePresence>+ );+}++export function StatusMark({ status }: { status: SubagentActivity['status'] }) {+ if (status === 'done') {+ return (+ <motion.span+ initial={{ scale: 0.6, opacity: 0 }}+ animate={{ scale: 1, opacity: 1 }}+ className="flex size-5 shrink-0 items-center justify-center rounded-full bg-success-9"+ >+ <Check className="size-3 text-on-success" strokeWidth={3} />+ </motion.span>+ );+ }+ if (status === 'blocked') {+ return (+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-accent-3">+ <Hand className="size-3 text-accent-11" />+ </span>+ );+ }+ if (status === 'failed') {+ return (+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-gray-3">+ <Minus className="size-3 text-gray-11" />+ </span>+ );+ }+ return (+ <span className="flex size-5 shrink-0 items-center justify-center">+ <Loader2 className="size-4 animate-spin text-accent-10 motion-reduce:animate-none" />+ </span>+ );+}++export function AppLogos({ pieces }: { pieces: string[] }) {+ const apps = pieces.filter(+ (pieceName) => !PLUMBING_PIECES.includes(pieceName),+ );+ if (apps.length === 0) return null;+ const shown = apps.slice(0, MAX_LOGOS);+ const extra = apps.length - shown.length;+ return (+ <div className="flex shrink-0 items-center gap-1">+ {shown.map((pieceName) => (+ <AppLogo key={pieceName} pieceName={pieceName} />+ ))}+ {extra > 0 && (+ <span className="text-xs text-gray-11 tabular-nums">+{extra}</span>+ )}+ </div>+ );+}++export function Duration({ activity }: { activity: SubagentActivity }) {+ if (activity.status === 'running') {+ return activity.startedAt.length > 0 ? (+ <Elapsed startedAt={activity.startedAt} />+ ) : null;+ }+ if (activity.durationMs === undefined) return null;+ return (+ <span className="w-12 shrink-0 text-right text-xs text-gray-11 tabular-nums">+ {formatDuration(activity.durationMs)}+ </span>+ );+}++function Elapsed({ startedAt }: { startedAt: string }) {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const timer = setInterval(() => setNow(Date.now()), 1_000);+ return () => clearInterval(timer);+ }, []);+ return (+ <span className="w-12 shrink-0 text-right text-xs text-gray-11 tabular-nums">+ {formatDuration(now - Date.parse(startedAt))}+ </span>+ );+}++function formatDuration(ms: number): string {+ const totalSeconds = Math.max(0, Math.round(ms / 1000));+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return minutes === 0+ ? `${seconds}s`+ : `${minutes}m ${seconds.toString().padStart(2, '0')}s`;+}++function AppLogo({ pieceName }: { pieceName: string }) {+ const { summary } = piecesHooks.usePieceSummary({ name: pieceName });+ if (!summary?.logoUrl) return null;+ return (+ <PieceIcon+ size="xs"+ border={false}+ displayName={summary.displayName}+ logoUrl={summary.logoUrl}+ showTooltip={true}+ />+ );+}++const MAX_LOGOS = 3;+const PLUMBING_PIECES = ['@activepieces/piece-subflows'];diff --git a/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts b/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.tsindex fe7d6b951d8..8491d3924d6 100644--- a/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts+++ b/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts@@ -190,6 +190,17 @@ export function buildMessageBlocks({}continue;}+ if (toolName === 'ap_run_task') {+ endSegment();+ const task = { toolCallId: chatPartUtils.getToolCallId(p), part: p };+ const previous = result[result.length - 1];+ if (previous?.kind === 'tasks') {+ previous.tasks.push(task);+ } else {+ result.push({ kind: 'tasks', tasks: [task] });+ }+ continue;+ }if (toolName === 'ap_remember') {const memory = (p.input as { memory?: string } | undefined@@ -207,6 +218,7 @@ export function buildMessageBlocks({continue;}if (chatPartUtils.isDisplayTool(toolName)) {+ endSegment();result.push({ kind: 'display-tool', part: p });continue;}@@ -376,6 +388,10 @@ export type MessageBlock =| { kind: 'display-tool'; part: AnyToolPart }| { kind: 'memory-saved'; memory: string }| { kind: 'batch-progress'; data: BatchProgressData }+ | {+ kind: 'tasks';+ tasks: { toolCallId: string; part: AnyToolPart }[];+ }| OutcomeCardBlock| { kind: 'card-group'; cards: OutcomeCardBlock[] }| {diff --git a/packages/web/src/features/chat/lib/chat-api.ts b/packages/web/src/features/chat/lib/chat-api.tsindex bd77a750cb1..a78d4d1fe4b 100644--- a/packages/web/src/features/chat/lib/chat-api.ts+++ b/packages/web/src/features/chat/lib/chat-api.ts@@ -185,4 +185,5 @@ export type PendingGate = {toolName: string;displayName: string;toolInput: Record<string, unknown>;+ taskTitle?: string;};diff --git a/packages/web/src/features/chat/lib/chat-store.ts b/packages/web/src/features/chat/lib/chat-store.tsindex 31fce7106e8..f6b4fd0e7d5 100644--- a/packages/web/src/features/chat/lib/chat-store.ts+++ b/packages/web/src/features/chat/lib/chat-store.ts@@ -6,6 +6,7 @@ import {BuildPlanEvent,FileProducedEvent,ImageGeneratedEvent,+ SubagentActivity,} from '@activepieces/shared';import { StoreApi, create } from 'zustand';@@ -49,6 +50,7 @@ export type ToolCallMeta = {actionReceipt?: ActionReceiptEvent;image?: ImageGeneratedEvent;files?: FileProducedEvent[];+ subagent?: SubagentActivity;};export type BuildState = BuildPlanEvent;@@ -156,11 +158,24 @@ function selectPendingActionPreview({return !!id && !!state.toolCallMeta[id]?.actionPreview;},});- if (!isNotDismissed(part, state)) return null;+ if (!isNotDismissed(part, state)) return taskActionPreview(state);const toolCallId = chatPartUtils.getToolCallId(part);return state.toolCallMeta[toolCallId]?.actionPreview ?? null;}+function taskActionPreview(state: ChatStoreState): ActionPreviewEvent | null {+ const metas = Object.values(state.toolCallMeta);+ const taskRunning = metas.some((meta) => meta.subagent?.status === 'running');+ if (!taskRunning) return null;+ const waiting = metas.find(+ (meta) =>+ meta.actionPreview?.taskTitle !== undefined &&+ meta.actionReceipt === undefined &&+ !state.dismissedGateIds[meta.actionPreview.toolCallId],+ );+ return waiting?.actionPreview ?? null;+}+function selectActiveQuestions({state,lastAssistantMessage,@@ -223,7 +238,7 @@ function selectHasBlockingCard({return !!state.toolCallMeta[id]?.actionPreview;},});- return part !== null;+ return part !== null || taskActionPreview(state) !== null;}function selectBatchProgress({diff --git a/packages/web/src/features/chat/lib/chat-utils.ts b/packages/web/src/features/chat/lib/chat-utils.tsindex 8532d7ca086..bfa2f0bd975 100644--- a/packages/web/src/features/chat/lib/chat-utils.ts+++ b/packages/web/src/features/chat/lib/chat-utils.ts@@ -52,6 +52,7 @@ const TOOL_LABELS: Record<string, { active: string; done: string }> = {done: 'Searched integrations',},ap_build_flow: { active: 'Building automation', done: 'Built automation' },+ ap_run_task: { active: 'Working on a task', done: 'Finished a task' },ap_create_flow: { active: 'Creating automation', done: 'Created automation' },ap_validate_step_config: {active: 'Validating setup',diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.tsindex 9f3b5d86f24..4a7b7bd64e4 100644--- a/packages/web/src/features/chat/lib/use-chat.ts+++ b/packages/web/src/features/chat/lib/use-chat.ts@@ -12,6 +12,8 @@ import {PersistedAgentMessage,ToolProgressEvent,AgentMessageSource,+ SubagentActivity,+ SubagentProgressEvent,} from '@activepieces/shared';import { useQuery } from '@tanstack/react-query';import { t } from 'i18next';@@ -27,7 +29,7 @@ import {SetChatStore,ToolCallMeta,} from './chat-store';-import { useChatStoreApi } from './chat-store-context';+import { useChatStoreApi, useChatStoreContext } from './chat-store-context';import { ChatUIMessage, QuickRepliesData, chatPartUtils } from './chat-types';import { chatUtils } from './chat-utils';import { useStreamingReducer } from './use-streaming-reducer';@@ -89,6 +91,7 @@ function restoreReceiptsIntoStore({const MAX_FILE_SIZE = 10 * 1024 * 1024;const AGENT_POLL_INTERVAL_MS = 5_000;const TOOL_GATES_WITHOUT_A_PIECE = new Set([+ 'ap_send_email','ap_test_flow','ap_delete_records','ap_delete_table',@@ -147,7 +150,14 @@ function buildToolCallMetaFromGate(isBatch: false,};}- return actionPreview ? { [gate.gateId]: { actionPreview } } : {};+ if (!actionPreview) return {};+ return {+ [gate.gateId]: {+ actionPreview: gate.taskTitle+ ? { ...actionPreview, taskTitle: gate.taskTitle }+ : actionPreview,+ },+ };}// History only persists resolved tool calls, so a live pending gate loses its `input-available`@@ -163,41 +173,92 @@ function buildGatePart(gate: PendingGate) {};}+function buildRunningTaskPart({+ toolCallId,+ title,+}: {+ toolCallId: string;+ title: string;+}) {+ return {+ type: 'dynamic-tool' as const,+ toolCallId,+ toolName: 'ap_run_task',+ title,+ state: 'input-available' as const,+ input: { title },+ };+}+function appendGatePart({messages,gate,}: {messages: ChatUIMessage[];gate: PendingGate;+}): ChatUIMessage[] {+ return appendTrailingPart({ messages, part: buildGatePart(gate) });+}++function appendRunningTaskParts({+ messages,+ toolCallMeta,+}: {+ messages: ChatUIMessage[];+ toolCallMeta: Record<string, ToolCallMeta>;+}): ChatUIMessage[] {+ return Object.entries(toolCallMeta).reduce(+ (current, [toolCallId, meta]) =>+ meta.subagent?.status === 'running'+ ? appendTrailingPart({+ messages: current,+ part: buildRunningTaskPart({+ toolCallId,+ title: meta.subagent.title,+ }),+ })+ : current,+ messages,+ );+}++function appendTrailingPart({+ messages,+ part,+}: {+ messages: ChatUIMessage[];+ part: ReturnType<typeof buildGatePart>;}): ChatUIMessage[] {const alreadyAnchored = messages.some((m) =>m.parts.some(- (part) => 'toolCallId' in part && part.toolCallId === gate.gateId,+ (existing) =>+ 'toolCallId' in existing && existing.toolCallId === part.toolCallId,),);if (alreadyAnchored) return messages;- // Anchor on the current turn, always at the tail. When the tail is the user's just-sent- // message (the worker is blocked on the gate before persisting its assistant turn), open a- // fresh trailing assistant message rather than attaching to an earlier, already-finished turn.const last = messages[messages.length - 1];if (last?.role === 'assistant') {const next = [...messages];next[next.length - 1] = {...last,- parts: [...last.parts, buildGatePart(gate)],+ parts: [...last.parts, part],};return next;}return [...messages,{- id: `gate-${gate.gateId}`,+ id: `live-${part.toolCallId}`,role: 'assistant',- parts: [buildGatePart(gate)],+ parts: [part],},];}+function progressOf(activity: SubagentActivity): number {+ return activity.stepCount;+}+const ALLOWED_MIME_SET: ReadonlySet<string> = new Set(CHAT_ALLOWED_MIME_TYPES);function isAllowedMimeType(value: string): value is AgentAllowedMimeType {@@ -283,6 +344,7 @@ export function useAgentChat({onTurnEnd?: () => void;} = {}) {const store = useChatStoreApi();+ const toolCallMeta = useChatStoreContext((state) => state.toolCallMeta);const [conversationId, setConversationIdState] = useState<string | null>(null,@@ -347,6 +409,32 @@ export function useAgentChat({[store],);+ const handleSubagentProgress = useCallback(+ (event: SubagentProgressEvent) => {+ store.setState((prev) => {+ const existing = prev.toolCallMeta[event.toolCallId]?.subagent;+ const isStale =+ existing !== undefined &&+ (existing.status !== 'running' ||+ progressOf(existing) > progressOf(event.data)) &&+ event.data.status === 'running';+ if (isStale) {+ return prev;+ }+ return {+ toolCallMeta: {+ ...prev.toolCallMeta,+ [event.toolCallId]: {+ ...prev.toolCallMeta[event.toolCallId],+ subagent: event.data,+ },+ },+ };+ });+ },+ [store],+ );+const updateToolCallMeta = useCallback(<K extends keyof ToolCallMeta>(key: K,@@ -470,6 +558,7 @@ export function useAgentChat({onImageGenerated: handleImageGenerated,onFileProduced: handleFileProduced,onBuildPlan: handleBuildPlan,+ onSubagentProgress: handleSubagentProgress,onStreamFinished: (convId) => {chatDebug.info({ conversation: { id: convId } }, 'stream finished');settleStreamRef.current(convId);@@ -580,11 +669,19 @@ export function useAgentChat({const base = [...persistedMessages];if (optimisticUserMessage) base.push(optimisticUserMessage);if (streamingMessage) base.push(streamingMessage);- return injectFilePartsIntoLastUserMessage({- messages: base,- fileNames: lastSentFileNamesRef.current,+ return appendRunningTaskParts({+ messages: injectFilePartsIntoLastUserMessage({+ messages: base,+ fileNames: lastSentFileNamesRef.current,+ }),+ toolCallMeta,});- }, [persistedMessages, optimisticUserMessage, streamingMessage]);+ }, [+ persistedMessages,+ optimisticUserMessage,+ streamingMessage,+ toolCallMeta,+ ]);const error =sendStatus.type === 'error'diff --git a/packages/web/src/features/chat/lib/use-streaming-reducer.ts b/packages/web/src/features/chat/lib/use-streaming-reducer.tsindex bdf406f6396..10275ee99fd 100644--- a/packages/web/src/features/chat/lib/use-streaming-reducer.ts+++ b/packages/web/src/features/chat/lib/use-streaming-reducer.ts@@ -5,6 +5,7 @@ import {AgentEventType,FileProducedEvent,ImageGeneratedEvent,+ SubagentProgressEvent,ToolProgressEvent,WebsocketClientEvent,} from '@activepieces/shared';@@ -28,6 +29,7 @@ export function useStreamingReducer({onImageGenerated,onFileProduced,onBuildPlan,+ onSubagentProgress,onStreamFinished,onStreamError,onStaleCheck,@@ -39,6 +41,7 @@ export function useStreamingReducer({onImageGenerated: (event: ImageGeneratedEvent) => void;onFileProduced: (event: FileProducedEvent) => void;onBuildPlan: (event: BuildPlanEvent) => void;+ onSubagentProgress: (event: SubagentProgressEvent) => void;onStreamFinished: (conversationId: string) => void;onStreamError: (params: {conversationId: string;@@ -76,6 +79,8 @@ export function useStreamingReducer({onFileProducedRef.current = onFileProduced;const onBuildPlanRef = useRef(onBuildPlan);onBuildPlanRef.current = onBuildPlan;+ const onSubagentProgressRef = useRef(onSubagentProgress);+ onSubagentProgressRef.current = onSubagentProgress;const onStreamFinishedRef = useRef(onStreamFinished);onStreamFinishedRef.current = onStreamFinished;const onStreamErrorRef = useRef(onStreamError);@@ -289,6 +294,12 @@ export function useStreamingReducer({} else if (event.type === AgentEventType.BUILD_PLAN) {lastChunkTimeRef.current = Date.now();onBuildPlanRef.current(event.data as BuildPlanEvent);+ } else if (+ event.type === AgentEventType.SUBAGENT_PROGRESS &&+ isSubagentProgressEvent(event.data)+ ) {+ lastChunkTimeRef.current = Date.now();+ onSubagentProgressRef.current(event.data);}};@@ -366,3 +377,14 @@ type SocketEvent = {type StreamPhase = 'idle' | 'awaiting-stream' | 'streaming' | 'reconciling';export type { StreamPhase };++function isSubagentProgressEvent(data: unknown): data is SubagentProgressEvent {+ if (typeof data !== 'object' || data === null) return false;+ return (+ 'toolCallId' in data &&+ typeof data.toolCallId === 'string' &&+ 'data' in data &&+ typeof data.data === 'object' &&+ data.data !== null+ );+}