🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(agent): Improve reaction to denied tool calls (#14967)
Ben Bachem31738d01b72b
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.tsindex 335eeb71e7..83d6904f71 100644--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -310,6 +310,37 @@ describe("in-app agent public API route auth", () => {});});+ it("does not create a mutating tool override for rejected approvals", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps(false);+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ const { response } = await callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ forwardedProps,+ });++ expect(response.status).toBe(200);+ expect(agentMocks.createAgUiStream).toHaveBeenCalledWith(+ expect.objectContaining({+ options: expect.objectContaining({+ langfuseMcp: expect.objectContaining({+ runOverride: undefined,+ }),+ }),+ }),+ );+ });+ });+it("rejects mutated resume forwarded props without consuming the pending approval", async () => {await withInAppAgentCloudEnv(async () => {const { project, userId } = await setupInAppAgentProjectSession();@@ -486,6 +517,40 @@ describe("in-app agent public API route auth", () => {});});+ it("does not restore a rejected approval when stream initialization fails", async () => {+ await withInAppAgentCloudEnv(async () => {+ const { project, userId } = await setupInAppAgentProjectSession();+ const conversationId = `conversation-${randomUUID()}`;+ const forwardedProps = createResumeForwardedProps(false);+ await seedPendingToolApproval({+ projectId: project.id,+ conversationId,+ userId,+ approvalRequest: forwardedProps.command.resume.approvalRequest,+ });++ agentMocks.createAgUiStream.mockRejectedValueOnce(+ new Error("stream init failed"),+ );++ await expect(+ callInAppAgentRoute({+ projectId: project.id,+ conversationId,+ runId: "client-run-rejected-failed",+ forwardedProps,+ }),+ ).rejects.toThrow("stream init failed");+ await expect(+ pendingToolApprovalExists({+ projectId: project.id,+ conversationId,+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,+ }),+ ).resolves.toBe(false);+ });+ });+it("keeps pending approval retryable when a resumed stream errors after creation", async () => {await withInAppAgentCloudEnv(async () => {const { project, userId } = await setupInAppAgentProjectSession();@@ -1004,11 +1069,11 @@ async function setupInAppAgentProjectSession() {return { org, project, userId };}-function createResumeForwardedProps() {+function createResumeForwardedProps(approved = true) {return {command: {resume: {- approved: true,+ approved,approvalRequest: {type: "tool_approval_request" as const,toolCallId: `tool-call-${randomUUID()}`,diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsindex e8ebdf5edb..ef13798697 100644--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -1306,7 +1306,7 @@ describe("createAgUiStream", () => {);});- it("aborts rejected tools after streaming the rejected tool result", async () => {+ it("continues after rejected tools and asks the user how to proceed", async () => {const { createAgUiStream } =await import("@/src/ee/features/in-app-agent/server/agent");const input = createToolApprovalResumeInput(false);@@ -1317,6 +1317,25 @@ describe("createAgUiStream", () => {threadId: input.threadId,runId: input.runId,},+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "assistant-message-1",+ role: "assistant",+ },+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "assistant-message-1",+ delta: "The action was not completed. How would you like to continue?",+ },+ {+ type: EventType.TEXT_MESSAGE_END,+ messageId: "assistant-message-1",+ },+ {+ type: EventType.RUN_FINISHED,+ threadId: input.threadId,+ runId: input.runId,+ },];const langfuseClient = {getPrompt: promptMocks.getPrompt,@@ -1339,7 +1358,6 @@ describe("createAgUiStream", () => {publicKey: "pk",secretKey: "sk",userAccess: defaultInAppAgentUserAccess,- runOverride: "run-override",},redirectAction: {projectId: "project-1",@@ -1354,9 +1372,39 @@ describe("createAgUiStream", () => {streamedEvents.push(event);});- expect(adapterEvents.inputs).toEqual([]);- expect(vi.mocked(MCPClient)).not.toHaveBeenCalled();- expect(vi.mocked(Agent)).not.toHaveBeenCalled();+ expect(adapterEvents.inputs).toEqual([+ expect.objectContaining({+ forwardedProps: {},+ messages: expect.arrayContaining([+ expect.objectContaining({+ id: "tool-call-1-approval-tool-call",+ role: "assistant",+ toolCalls: [+ expect.objectContaining({+ id: "tool-call-1",+ }),+ ],+ }),+ expect.objectContaining({+ id: "tool-call-1-approval-tool-result",+ role: "tool",+ toolCallId: "tool-call-1",+ content: "Tool call was not approved by the user.",+ error: "Tool call was not approved by the user.",+ }),+ expect.objectContaining({+ id: "tool-call-1-approval-rejection-guidance",+ role: "developer",+ content: expect.stringContaining(+ "ask the user how they would like to continue",+ ),+ }),+ ]),+ }),+ ]);+ expect(adapterEvents.createScoreConfigExecute).not.toHaveBeenCalled();+ expect(vi.mocked(MCPClient)).toHaveBeenCalledOnce();+ expect(vi.mocked(Agent)).toHaveBeenCalledOnce();expect(persistedEvents).toEqual([{type: EventType.RUN_STARTED,@@ -1391,6 +1439,25 @@ describe("createAgUiStream", () => {role: "tool",error: "Tool call was not approved by the user.",},+ {+ type: EventType.TEXT_MESSAGE_START,+ messageId: "assistant-message-1",+ role: "assistant",+ },+ {+ type: EventType.TEXT_MESSAGE_CONTENT,+ messageId: "assistant-message-1",+ delta: "The action was not completed. How would you like to continue?",+ },+ {+ type: EventType.TEXT_MESSAGE_END,+ messageId: "assistant-message-1",+ },+ {+ type: EventType.RUN_FINISHED,+ threadId: input.threadId,+ runId: input.runId,+ },]);expect(streamedEvents).toEqual(persistedEvents);expect(diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsxindex 20b0aeb1d5..67ca866bed 100644--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx@@ -454,6 +454,14 @@ function InAppAiAgentProviderInner({return nextApprovals;});},+ onToolCallResultEvent: ({ event }) => {+ updatePendingToolApprovals((currentApprovals) =>+ currentApprovals.filter(+ (approval) =>+ approval.approvalRequest.toolCallId !== event.toolCallId,+ ),+ );+ },onRunErrorEvent: ({ event }) => {if (intentionalAbortRef.current) {return;diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.tsindex 4bc6671c73..55d3f781b2 100644--- a/web/src/ee/features/in-app-agent/server/agent.ts+++ b/web/src/ee/features/in-app-agent/server/agent.ts@@ -15,10 +15,7 @@ import {type InAppAgentToolApprovalRequest,type ResumeForwardedProps,} from "@/src/ee/features/in-app-agent/schema";-import {- createManualToolApprovalRunInput,- type ManualToolApprovalRunInput,-} from "@/src/ee/features/in-app-agent/server/human-in-the-loop";+import { createManualToolApprovalRunInput } from "@/src/ee/features/in-app-agent/server/human-in-the-loop";import type {InAppAgentPromptMetadata,InAppAgentTracingConfig,@@ -337,27 +334,6 @@ export async function createAgUiStream(params: {return params.options.onError?.(new Error(streamedRunError));};- const completeManualToolApprovalRun = (- runInput: ManualToolApprovalRunInput,- ) => {- const terminalEvents = [- createRunStartedEvent(params.input),- ...runInput.syntheticEvents,- ];-- instrumentation?.recordToolCallApproval(runInput.toolCallApproval);- instrumentation?.recordEvents(terminalEvents);- for (const syntheticEvent of terminalEvents) {- enqueueEvent(syntheticEvent);- }-- closeController(() => {- instrumentation?.end({});- instrumentation?.flush();- return params.options.onComplete?.();- });- };-const closeController = (terminalCallback?: () => void | Promise<void>,) => {@@ -440,32 +416,6 @@ export async function createAgUiStream(params: {| ResumeForwardedProps| undefined;- if (forwardedProps?.command?.resume?.approved === false) {- createManualToolApprovalRunInput({- input: params.input,- executeToolCall: async () => {- throw new Error("Rejected tool approvals must not execute tools.");- },- })- .then((runInput) => {- if (ending || closed || params.signal.aborted) {- abortStream();- return;- }-- completeManualToolApprovalRun(runInput);- })- .catch((error) => {- if (ending || closed) {- return;- }-- failStream(error);- });-- return;- }-createMastraAdapter({input: params.input,signal: params.signal,@@ -502,11 +452,6 @@ export async function createAgUiStream(params: {});const pendingSyntheticEvents = [...runInput.syntheticEvents];- if (!runInput.shouldContinue) {- completeManualToolApprovalRun(runInput);- return;- }-if (forwardedProps?.command?.resume?.approved === true &¶ms.options.langfuseMcp.runOverride@@ -1202,15 +1147,6 @@ function normalizeAdapterEvent(return [event];}-function createRunStartedEvent(input: AgUiRunAgentInput): AgUiEvent {- return {- type: EventType.RUN_STARTED,- threadId: input.threadId,- runId: input.runId,- ...(input.parentRunId ? { parentRunId: input.parentRunId } : {}),- };-}-function createRunErrorEvent(input: AgUiRunAgentInput,error: unknown,diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex 7997891d71..61524f37e5 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -263,13 +263,19 @@ export default async function handler(request: Request) {? sanitizedInput.forwardedProps.command.resume.approvalRequest: undefined;+ const approvedResumeApprovalRequest =+ isResumeAgentInput(sanitizedInput) &&+ sanitizedInput.forwardedProps.command.resume.approved+ ? sanitizedInput.forwardedProps.command.resume.approvalRequest+ : undefined;+return await withInAppAgentMcpApiKeyCleanup({projectId,runId: sanitizedInput.runId,userId,toolName: getInAppAgentMcpRegistryToolName(- resumeApprovalRequest?.toolName,+ approvedResumeApprovalRequest?.toolName,),},async (mcpApiKey, runOverride, cleanupMcpApiKey) => {@@ -281,7 +287,7 @@ export default async function handler(request: Request) {const restorePendingToolApprovalIfRetryable = () => {if (!pendingToolApprovalConsumed ||- !resumeApprovalRequest ||+ !approvedResumeApprovalRequest ||approvedToolResultPersisted) {return;@@ -290,7 +296,7 @@ export default async function handler(request: Request) {return storePendingToolApproval({projectId,conversationId: conversation.id,- approvalRequest: resumeApprovalRequest,+ approvalRequest: approvedResumeApprovalRequest,});};diff --git a/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts b/web/src/ee/features/in-app-agent/server/human-in-the-loop.tsindex 093af24aa6..8203a9a392 100644--- a/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts+++ b/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts@@ -155,7 +155,6 @@ export function parseInAppAgentInterruptEvent(export type ManualToolApprovalRunInput = {input: AgUiRunAgentInput;syntheticEvents: AgUiEvent[];- shouldContinue: boolean;toolCallApproval?: {toolCallId: string;status: "approved" | "rejected";@@ -172,14 +171,30 @@ export async function createManualToolApprovalRunInput(params: {const forwardedProps = getResumeForwardedProps(params.input);if (!forwardedProps) {- return { input: params.input, syntheticEvents: [], shouldContinue: true };+ return { input: params.input, syntheticEvents: [] };}const { approved, approvalRequest } = forwardedProps.command.resume;if (!approved) {+ const assistantMessage =+ createManualToolCallAssistantMessage(approvalRequest);+ const toolMessage: AgUiMessage = {+ id: createManualToolResultMessageId(approvalRequest),+ role: "tool",+ content: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,+ toolCallId: approvalRequest.toolCallId,+ error: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,+ };+return {input: {...params.input,+ messages: [+ ...params.input.messages,+ assistantMessage,+ toolMessage,+ createToolRejectionGuidanceMessage(approvalRequest),+ ],forwardedProps: {},},syntheticEvents: createManualToolApprovalEvents({@@ -187,7 +202,6 @@ export async function createManualToolApprovalRunInput(params: {toolResultContent: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,toolError: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,}),- shouldContinue: false,toolCallApproval: {toolCallId: approvalRequest.toolCallId,status: "rejected",@@ -235,7 +249,6 @@ export async function createManualToolApprovalRunInput(params: {forwardedProps: {},},syntheticEvents,- shouldContinue: true,toolCallApproval: {toolCallId: approvalRequest.toolCallId,status: "approved",@@ -243,6 +256,21 @@ export async function createManualToolApprovalRunInput(params: {};}+function createToolRejectionGuidanceMessage(+ approvalRequest: InAppAgentToolApprovalRequest,+): AgUiMessage {+ return {+ id: `${approvalRequest.toolCallId}-approval-rejection-guidance`,+ role: "developer",+ content: [+ `The user declined the proposed tool call ${approvalRequest.toolName}.`,+ "The action was not completed.",+ "Do not retry this tool call or attempt an equivalent action unless the user explicitly requests it.",+ "Briefly acknowledge that the action was not completed and ask the user how they would like to continue.",+ ].join("\n"),+ };+}+async function executeApprovedToolCall(params: {approvalRequest: InAppAgentToolApprovalRequest;executeToolCall: (