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
fix(chat): changing a saved agent after the chat read your data now asks for your approval (#15927)
Hazem Adel7e7e38097eb9
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.mdindex 42d3a5b101b..4c1bb026ee1 100644--- a/brain/knowledge/flows-execution/chat.md+++ b/brain/knowledge/flows-execution/chat.md@@ -36,7 +36,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **A failed turn used to leave status ERROR with an empty reply.** The error text only travelled as a websocket `ERROR` event, so a reload, another tab, or a user who was away saw a dead conversation (and often no user message either when the job died inside `getAgentConfig`, before it persists the turn). The `execute-agent-run.ts` catch now sends `failure: { message, userMessage? }` on the empty `saveAgentMessages` call and `conversation-rpc.ts` appends it to `uiMessages` as an assistant text reply; `use-chat.ts` shows the Retry banner when a loaded conversation is ERROR. Stale STREAMING to IDLE recovery, a worker that never picks the job up, and `assertAgentMessageRateLimitNotExceeded` still leave no reply of their own.- **A built flow ends with a "Turn it on?" card, never an auto-publish**: an audit found 40% of built-but-unpublished flows ended on "open it to review", some claiming LIVE. Chat never publishes on its own; only a yes to the card calls `ap_lock_and_publish` (`build_flow.md` "Turn it on?"). Pinned by the `build-then-ask-turn-it-on` fixture (`askedToTurnItOn`, `noLiveClaimWithoutPublish`). The live-claim check is a regex plus "was `ap_lock_and_publish` called", so it cannot see whether publish succeeded.- **Server-managed connections**: the LLM never sees connection externalIds; `ap_execute_action` auto-fills them from a Redis store.-- **Prompt-injection taint**: a per-turn `taintState` flips to `tainted` once the turn reads outside or user data (MCP tools, web/search/scrape, `ap_explore_data`, `ap_execute_action`, `ap_run_code`, `ap_list_across_projects`, configured tools). It forces the action-preview gate on non-read-only actions, blocks saved-agent edits, and makes `ap_remember` ask before saving (memory reaches every future conversation). It carries one message: each saved reply stores `tainted` (this reply's own reads, via `createTaintState`), and the next message starts from it. Deletes are confirmed always, not by taint.+- **Prompt-injection taint**: a per-turn `taintState` flips to `tainted` once the turn reads outside or user data (MCP tools, web/search/scrape, `ap_explore_data`, `ap_execute_action`, `ap_run_code`, `ap_list_across_projects`, configured tools). It forces the action-preview gate on non-read-only actions, makes saved-agent edits (`ap_update_agent`, `ap_add_agent_tool`, `ap_remove_agent_tool`, `ap_create_agent`) ask for approval on the action card instead of refusing, and makes `ap_remember` ask before saving (memory reaches every future conversation). It carries one message: each saved reply stores `tainted` (this reply's own reads, via `createTaintState`), and the next message starts from it. Deletes are confirmed always, not by taint.- **Write-check gate**: before a live `ap_test_flow`, `__flow_write_check` RPC flags write/destructive PIECE steps; read-only flows run ungated; gate fails open on RPC error.- **Cloud rollout cap**: opens to non-embed users without `chatEnabled` until 200 distinct users have sent a message (`CLOUD_CHAT_ROLLOUT_CAP`); grandfathered after close. Embedded sessions never see chat.- **Flow correctness is 100% prompt/guide-driven — nothing in code enforces it.** The "#1 silent bug" ("Class A"): the agent frames a *recurring* automation as a *one-time task* and omits any anti-reprocessing step, so run N+1 redoes run N's work (re-pays, re-sends). It's a design-time reasoning gap, not a testing gap — `ap_test_flow` runs ONCE, so a single test looks perfect; the bug only shows on the 2nd run. Fix lives in the prompt (`chat-system-prompt.md` `<decision_framework>` + `build_flow.md` "Recurring flows must not reprocess") + capability eval fixtures with a `recurring_avoids_reprocessing` judge dimension. The platform already has every primitive (Tables New-Record webhook, polling `DedupeStrategy`, `_dedupe_key`, Store, update/delete-record); the agent just wasn't reaching for them. Watch the `build_flow.md` "don't over-build" bias — it once actively discouraged the fix.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 31652d2a213..d8ff53db8a4 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@@ -6,7 +6,7 @@ const GATE_TTL_SECONDS = 15 * 60const CANCEL_TTL_SECONDS = 2 * 60 * 60const CONNECTION_STORE_TTL_SECONDS = 24 * 60 * 60-const KEY_PREFIX = 'tool-approval-decision:'+const KEY_PREFIX = 'tool-approval-decision:v2:'const CHANNEL_PREFIX = 'tool-approval:'const CANCEL_KEY_PREFIX = 'chat-cancel:'const AVAILABLE_CONNECTIONS_PREFIX = 'chat-conn-avail:'@@ -27,7 +27,8 @@ async function resolveGate({ gateId, approved, payload, log }: { gateId: string,const conversationId = await distributedStore.get<string>(`${PENDING_GATE_PREFIX}gate:${gateId}`)const pendingGate = conversationId ? (await readPendingGates({ conversationId }))[gateId] : undefinedconst approvedInput = pendingGate?.toolInput- const wasSet = await distributedStore.putIfAbsent(decisionKey(gateId), { approved, payload, approvedInput }, GATE_TTL_SECONDS)+ const decision: GateDecision = { approved, payload, approvedInput, approvedToolName: pendingGate?.toolName, approvedConversationId: conversationId ?? undefined, approvedRunId: pendingGate?.runId }+ const wasSet = await distributedStore.putIfAbsent(decisionKey(gateId), decision, GATE_TTL_SECONDS)if (wasSet) {await pubsub.publish(channelName(gateId), JSON.stringify({ approved, payload }))if (conversationId) {@@ -44,7 +45,11 @@ async function resolveGate({ gateId, approved, payload, log }: { gateId: string,async function checkDecision({ gateId }: { gateId: string }): Promise<GateDecision | 'pending'> {const raw = await distributedStore.get<GateDecision>(decisionKey(gateId))if (!raw) return 'pending'- return { approved: raw.approved === true, payload: raw.payload, approvedInput: raw.approvedInput }+ return { approved: raw.approved === true, payload: raw.payload, approvedInput: raw.approvedInput, approvedToolName: raw.approvedToolName, approvedConversationId: raw.approvedConversationId, approvedRunId: raw.approvedRunId }+}++async function consumeApproval({ gateId }: { gateId: string }): Promise<boolean> {+ return distributedStore.putIfAbsent(`${decisionKey(gateId)}:consumed`, true, GATE_TTL_SECONDS)}async function waitForDecision({ gateId, timeoutMs }: { gateId: string, timeoutMs: number }): Promise<GateDecision | 'pending'> {@@ -162,6 +167,7 @@ async function clearPendingGate({ conversationId }: { conversationId: string }):export const agentApprovalGate = {resolveGate,checkDecision,+ consumeApproval,waitForDecision,requestCancel,isCancelled,@@ -180,6 +186,9 @@ type GateDecision = {approved: booleanpayload?: Record<string, unknown>approvedInput?: Record<string, unknown>+ approvedToolName?: string+ approvedConversationId?: string+ approvedRunId?: string}type StoredConnection = {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 9b4e3eb5831..4bd6a9514df 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@@ -1,3 +1,4 @@+import { isDeepStrictEqual } from 'node:util'import { ActivepiecesAiConsumerSource, ActivepiecesError, ErrorCode, isNil, spreadIfDefined, tryCatch } from '@activepieces/core-utils'import { aiUtils } from '@activepieces/server-utils'import { AGENT_SELF_EDIT_TOOLS, AGENT_SURFACE_TOOLS, AgentActionOutcome, AgentRunSource, agentToolClassification, ExecuteAgentToolRequest, ExecuteAgentToolResponse, ExecuteFlowToolRequest, ExecuteFlowToolResponse, ExecuteKnowledgeBaseToolRequest, ExecuteKnowledgeBaseToolResponse, ExecutePieceToolRequest, ExecutePieceToolResponse, FlowActionType, flowStructureUtil } from '@activepieces/shared'@@ -154,7 +155,8 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({}if (AGENT_SELF_EDIT_TOOLS.includes(input.toolName) || input.toolName === 'ap_create_agent') {const readAlready = await turnHasRead({ conversationId: input.conversationId ?? '', ...spreadIfDefined('runId', input.runId) })- if (readAlready) {+ const approvedByUser = readAlready && await approvedByHuman({ toolName: input.toolName, toolInput: input.toolInput, conversationId: input.conversationId, runId: input.runId })+ if (readAlready && !approvedByUser) {log.warn({ tool: { name: input.toolName }, source: input.source, conversation: { id: input.conversationId } }, '[agentRpc#executeAgentTool] Refused a saved-agent change for a turn that already read something')throw new ActivepiecesError({code: ErrorCode.AUTHORIZATION,@@ -281,6 +283,26 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({const MAX_APPROVAL_BLOCK_MS = 50_000const CHAT_ONLY_TOOL_PREFIX = '__'const OWNER_SCOPED_TOOLS = ['ap_remember']+async function approvedByHuman({ toolName, toolInput, conversationId, runId }: { toolName: string, toolInput: Record<string, unknown>, conversationId?: string, runId?: string }): Promise<boolean> {+ const { [APPROVED_GATE_KEY]: gateId, ...requested } = toolInput+ if (typeof gateId !== 'string') {+ return false+ }+ const decision = await agentApprovalGate.checkDecision({ gateId })+ const approvedThisCall = decision !== 'pending'+ && decision.approved+ && decision.approvedToolName === toolName+ && decision.approvedConversationId === conversationId+ && decision.approvedRunId === runId+ && !isNil(decision.approvedInput)+ && isDeepStrictEqual(decision.approvedInput, requested)+ if (!approvedThisCall) {+ return false+ }+ return agentApprovalGate.consumeApproval({ gateId })+}++const APPROVED_GATE_KEY = 'approvedGateId'const ATTENDED_STATE_TOOLS = ['__cancel_check', '__approval_wait', '__store_pending_gate', '__store_selected_connection', '__get_selected_connection']const SOURCE_EXTRA_TOOLS: Partial<Record<AgentRunSource, readonly string[]>> = {[AgentRunSource.AGENT_BUILDER]: AGENT_SURFACE_TOOLS,diff --git a/packages/server/api/test/integration/ee/agent/agent-self-edit.test.ts b/packages/server/api/test/integration/ee/agent/agent-self-edit.test.tsindex 4da4b40abbc..532228f8118 100644--- a/packages/server/api/test/integration/ee/agent/agent-self-edit.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-self-edit.test.ts@@ -2,6 +2,7 @@ import { AgentIcon, AgentRunSource, AIProviderName, apId, ApplicationEvent, Applimport { FastifyInstance } from 'fastify'import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { agentRpcHandlers } from '../../../../src/app/ee/agent/agent-rpc-handlers'+import { agentApprovalGate } from '../../../../src/app/ee/agent/agent-approval-gate'import { markTurnAsHavingRead } from '../../../../src/app/ee/agent/rpc/rpc-shared'import { db } from '../../../helpers/db'import { mockAndSaveAIProvider } from '../../../helpers/mocks'@@ -240,6 +241,77 @@ describe('an agent asked to change its own instructions', () => {expect(await instructionsOf(agentId)).toBe('Do the original job.')})+ describe('on a turn that read something, after the approval card', () => {+ const editAfterRead = async ({ approve, approvedInstructions, sentInstructions, approvedToolName = 'ap_update_agent', sendingRunId }: { approve: boolean, approvedInstructions: string, sentInstructions: string, approvedToolName?: string, sendingRunId?: string }) => {+ const ctx = await contextWithAgents()+ const agentId = await createAgent({ ctx, displayName: 'Ops agent' })+ const conversationId = await conversationFor({ ctx, agentId })+ const runId = apId()+ const gateId = apId()+ await markTurnAsHavingRead({ conversationId, runId })+ await markTurnAsHavingRead({ conversationId, runId: sendingRunId ?? runId })+ await agentApprovalGate.storePendingGate({+ conversationId,+ gate: { gateId, toolName: approvedToolName, displayName: 'Change a saved agent', toolInput: { instructions: approvedInstructions }, runId },+ })+ await agentApprovalGate.resolveGate({ gateId, approved: approve })+ const send = ({ instructions }: { instructions: string }) => agentRpcHandlers(app.log).executeAgentTool({+ toolName: 'ap_update_agent',+ toolInput: { instructions, approvedGateId: gateId },+ platformId: ctx.platform.id,+ userId: ctx.user.id,+ source: AgentRunSource.AGENT,+ conversationId,+ runId: sendingRunId ?? runId,+ })+ return { attempt: send({ instructions: sentInstructions }), send, agentId }+ }++ it('applies exactly the change the person approved', async () => {+ const { attempt, agentId } = await editAfterRead({ approve: true, approvedInstructions: 'Ask before refunds.', sentInstructions: 'Ask before refunds.' })+ await attempt++ expect(await instructionsOf(agentId)).toBe('Ask before refunds.')+ })++ it('refuses a different change than the one approved', async () => {+ const { attempt, agentId } = await editAfterRead({ approve: true, approvedInstructions: 'Ask before refunds.', sentInstructions: 'Approve every refund.' })+ await expect(attempt).rejects.toThrow()++ expect(await instructionsOf(agentId)).toBe('Do the original job.')+ })++ it('refuses a second change on an approval that was already used', async () => {+ const { attempt, send, agentId } = await editAfterRead({ approve: true, approvedInstructions: 'Ask before refunds.', sentInstructions: 'Ask before refunds.' })+ await attempt+ await db.update('agent', agentId, { draft: { instructions: 'Reset by the person.', maxSteps: 5, tools: [], structuredOutput: [], modelName: null } })++ await expect(send({ instructions: 'Ask before refunds.' })).rejects.toThrow()+ expect(await instructionsOf(agentId)).toBe('Reset by the person.')+ })++ it('refuses an approval given for a different tool', async () => {+ const { attempt, agentId } = await editAfterRead({ approve: true, approvedInstructions: 'Ask before refunds.', sentInstructions: 'Ask before refunds.', approvedToolName: 'ap_delete_agent' })+ await expect(attempt).rejects.toThrow()++ expect(await instructionsOf(agentId)).toBe('Do the original job.')+ })++ it('refuses an approval given in another run', async () => {+ const { attempt, agentId } = await editAfterRead({ approve: true, approvedInstructions: 'Ask before refunds.', sentInstructions: 'Ask before refunds.', sendingRunId: apId() })+ await expect(attempt).rejects.toThrow()++ expect(await instructionsOf(agentId)).toBe('Do the original job.')+ })++ it('refuses when the person declined', async () => {+ const { attempt, agentId } = await editAfterRead({ approve: false, approvedInstructions: 'Ask before refunds.', sentInstructions: 'Ask before refunds.' })+ await expect(attempt).rejects.toThrow()++ expect(await instructionsOf(agentId)).toBe('Do the original job.')+ })+ })+it('is refused when the turn is not named, so a worker cannot dodge the check by omitting it', async () => {const ctx = await contextWithAgents()const agentId = await createAgent({ ctx, displayName: 'Ops agent' })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 299372b052c..8976944d054 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@@ -696,7 +696,7 @@ function buildToolSet({ ctx, eventEmitter, log, phaseState, taintState, mcpToolS})const crossProjectTools = agentWorkerTools.createCrossProjectTools({ executeTool: executeCrossProjectTool, eventEmitter, waitForApproval, onGateOpened: storePendingGate, guides, taintState })const agentSurfaceTools = agentsAvailable && !dryRun && !discoveryOnly- ? agentWorkerTools.createAgentSurfaceTools({ executeTool: executeCrossProjectTool, taintState })+ ? agentWorkerTools.createAgentSurfaceTools({ executeTool: executeCrossProjectTool, taintState, eventEmitter, waitForApproval, onGateOpened: storePendingGate }): {}const thinkingTools = agentWorkerTools.createThinkingTools()const phaseTools = agentWorkerTools.createPhaseTools({ onPhaseChange: (phase) => {diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.tsindex 7c5741aacbe..b9581b1a552 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.ts@@ -1,8 +1,8 @@-import { spreadIfDefined } from '@activepieces/core-utils'+import { spreadIfDefined, tryCatch } from '@activepieces/core-utils'import { AgentOutputField, AgentOutputFieldType, AgentPhase, apId, BuildPlanEvent, TASK_COMPLETION_TOOL_NAME } from '@activepieces/shared'-import { tool, ToolSet } from 'ai'+import { tool, ToolExecutionOptions, ToolSet } from 'ai'import { z } from 'zod'-import { AgentEventEmitter, QUESTION_ICON_NAMES, TaintState } from './tool-primitives'+import { AgentEventEmitter, GateDecision, gateNoResponseMessage, QUESTION_ICON_NAMES, TaintState } from './tool-primitives'export function createLocalTools({ onSetProjectContext, projects }: {onSetProjectContext: (projectId: string | null) => Promise<{ success: boolean, error?: string }>@@ -43,15 +43,25 @@ export function createLocalTools({ onSetProjectContext, projects }: {}}-export function createAgentSurfaceTools({ executeTool, taintState }: {+export function createAgentSurfaceTools({ executeTool, taintState, eventEmitter, waitForApproval, onGateOpened }: {executeTool: (toolName: string, toolInput: Record<string, unknown>) => Promise<unknown>taintState: TaintState+ eventEmitter: AgentEventEmitter+ waitForApproval: (params: { gateId: string, timeoutMs?: number }) => Promise<GateDecision>+ onGateOpened?: (params: { gateId: string, toolName: string, displayName: string, toolInput: Record<string, unknown> }) => Promise<void>}): ToolSet {- const runUnlessTainted = async (toolName: string, toolInput: Record<string, unknown>): Promise<unknown> => {+ const runAfterApprovalIfTainted = async ({ toolName, toolInput, toolCallId }: { toolName: string, toolInput: Record<string, unknown>, toolCallId: string }): Promise<unknown> => {if (taintState.tainted) {- return { error: 'You read the user\'s data in this reply or the one before it, so you cannot change a saved agent now. Say what you would have changed, and offer to do it if they send that request as its own message after a reply that reads no data. The Configure panel is the other way.' }+ const label = AGENT_CHANGE_LABELS[toolName] ?? toolName+ eventEmitter.emitActionPreview({ toolCallId, pieceName: '', actionName: toolName, actionDisplayName: label, input: toolInput, isBatch: false })+ await tryCatch(async () => onGateOpened?.({ gateId: toolCallId, toolName, displayName: label, toolInput }))+ const decision = await waitForApproval({ gateId: toolCallId })+ if (decision.outcome !== 'approved') {+ const text = decision.outcome === 'timeout' ? gateNoResponseMessage('agent change approval') : 'The user declined this change to the agent. Do not retry it; ask what they want instead.'+ return { error: text }+ }}- return executeTool(toolName, toolInput)+ return executeTool(toolName, taintState.tainted ? { ...toolInput, approvedGateId: toolCallId } : toolInput)}return {ap_list_agents: tool({@@ -71,8 +81,8 @@ export function createAgentSurfaceTools({ executeTool, taintState }: {connectionExternalId: z.string().optional().describe('externalId from ap_list_connections, for a piece that needs an account'),publish: z.boolean().optional().describe('Make the agent live with these tools in the same step'),}),- execute: async (toolInput) => {- return runUnlessTainted('ap_add_agent_tool', toolInput)+ execute: async (toolInput, { toolCallId }: ToolExecutionOptions<undefined>) => {+ return runAfterApprovalIfTainted({ toolName: 'ap_add_agent_tool', toolInput, toolCallId })},}),@@ -84,8 +94,8 @@ export function createAgentSurfaceTools({ executeTool, taintState }: {pieceName: z.string().optional().describe('Full piece name, only needed when the same action name is on two of the agent\'s pieces'),publish: z.boolean().optional().describe('Make the agent live without these tools in the same step'),}),- execute: async (toolInput) => {- return runUnlessTainted('ap_remove_agent_tool', toolInput)+ execute: async (toolInput, { toolCallId }: ToolExecutionOptions<undefined>) => {+ return runAfterApprovalIfTainted({ toolName: 'ap_remove_agent_tool', toolInput, toolCallId })},}),@@ -98,20 +108,20 @@ export function createAgentSurfaceTools({ executeTool, taintState }: {instructions: z.string().optional().describe('The agent\'s full new standing brief, in second person'),publish: z.boolean().optional().describe('Make the change live for flows and chats in the same step'),}),- execute: async (toolInput) => {- return runUnlessTainted('ap_update_agent', toolInput)+ execute: async (toolInput, { toolCallId }: ToolExecutionOptions<undefined>) => {+ return runAfterApprovalIfTainted({ toolName: 'ap_update_agent', toolInput, toolCallId })},}),ap_create_agent: tool({- description: 'Create a saved agent in the active project from a name and instructions. Write the instructions as the agent\'s own standing brief, in second person, covering what it does and what it must not do. Call it before you read any of the user\'s data in this reply: afterwards it is refused until their next message, so stand the agent up first and refine it with ap_update_agent once you have looked at their data.',+ description: 'Create a saved agent in the active project from a name and instructions. Write the instructions as the agent\'s own standing brief, in second person, covering what it does and what it must not do. If you have read the user\'s data in this reply, they are asked to approve it first.',inputSchema: z.object({displayName: z.string().describe('Short name the user will recognise, e.g. "Inbox triage"'),instructions: z.string().describe('The agent\'s standing brief, in second person'),description: z.string().optional().describe('One line on what it is for'),}),- execute: async (toolInput) => {- return runUnlessTainted('ap_create_agent', toolInput)+ execute: async (toolInput, { toolCallId }: ToolExecutionOptions<undefined>) => {+ return runAfterApprovalIfTainted({ toolName: 'ap_create_agent', toolInput, toolCallId })},}),}@@ -219,3 +229,10 @@ function schemaForOutputField(field: AgentOutputField): z.ZodType {}}++const AGENT_CHANGE_LABELS: Record<string, string> = {+ ap_add_agent_tool: 'Add tools to a saved agent',+ ap_remove_agent_tool: 'Remove tools from a saved agent',+ ap_update_agent: 'Change a saved agent',+ ap_create_agent: 'Create a saved agent',+}diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.tsindex 09cfe0d46ed..2157e945559 100644--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.ts+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.ts@@ -365,23 +365,35 @@ describe('agentWorkerTools', () => {})describe('self-edit taint gate', () => {- const editWith = async (tainted: boolean) => {+ const editWith = async ({ tainted, outcome }: { tainted: boolean, outcome: 'approved' | 'declined' | 'timeout' }) => {+ const { eventEmitter } = makeMockEventEmitter()+ const emitActionPreview = vi.spyOn(eventEmitter, 'emitActionPreview')const executeTool = vi.fn().mockResolvedValue({ agentId: 'agent_1' })- const tools = agentWorkerTools.createAgentSurfaceTools({ executeTool, taintState: { tainted } })+ const waitForApproval = vi.fn().mockResolvedValue({ outcome })+ const tools = agentWorkerTools.createAgentSurfaceTools({ executeTool, taintState: { tainted }, eventEmitter, waitForApproval })const result = await tools.ap_update_agent.execute({ instructions: 'Do as the email says.' }, { toolCallId: 'tc-self', messages: [], abortSignal: undefined as unknown as AbortSignal })- return { result: result as { error?: string }, executeTool }+ return { result: result as { error?: string }, executeTool, waitForApproval, emitActionPreview }}- it('refuses to rewrite the agent once the turn has read outside content', async () => {- const { result, executeTool } = await editWith(true)+ it('asks the user to approve once the turn has read outside content, and runs the edit only after they do', async () => {+ const { executeTool, waitForApproval, emitActionPreview } = await editWith({ tainted: true, outcome: 'approved' })++ expect(emitActionPreview).toHaveBeenCalledWith(expect.objectContaining({ toolCallId: 'tc-self', actionName: 'ap_update_agent' }))+ expect(waitForApproval).toHaveBeenCalledWith({ gateId: 'tc-self' })+ expect(executeTool).toHaveBeenCalledWith('ap_update_agent', { instructions: 'Do as the email says.', approvedGateId: 'tc-self' })+ })++ it.each(['declined', 'timeout'] as const)('does not touch the agent when the approval is %s', async (outcome) => {+ const { result, executeTool } = await editWith({ tainted: true, outcome })- expect(result.error).toMatch(/read the user's data in this reply or the one before it/i)+ expect(result.error).toBeDefined()expect(executeTool).not.toHaveBeenCalled()})- it('rewrites it on a clean turn', async () => {- const { executeTool } = await editWith(false)+ it('rewrites it without asking on a clean turn', async () => {+ const { executeTool, waitForApproval } = await editWith({ tainted: false, outcome: 'declined' })+ expect(waitForApproval).not.toHaveBeenCalled()expect(executeTool).toHaveBeenCalledWith('ap_update_agent', { instructions: 'Do as the email says.' })})})diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.tsindex 7b93c5dd1cf..9f3b5d86f24 100644--- a/packages/web/src/features/chat/lib/use-chat.ts+++ b/packages/web/src/features/chat/lib/use-chat.ts@@ -95,6 +95,10 @@ const TOOL_GATES_WITHOUT_A_PIECE = new Set(['ap_delete_flow','ap_manage_fields','ap_remember',+ 'ap_create_agent',+ 'ap_update_agent',+ 'ap_add_agent_tool',+ 'ap_remove_agent_tool',]);function buildToolCallMetaFromGate(