From 23cc853785e229ef68058dce5268b500237c6ebd Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 13 Nov 2025 18:48:48 -0800 Subject: [PATCH] feat: report failure tool (#8694) * chore: add FAILED to status list * feat: report failure tool * add failure reporting for failed chat completions * Create status.ts * Update status.ts * sentry logigng * Update reportFailure.ts * Update posthogService.ts --- extensions/cli/src/commands/serve.ts | 14 +++ extensions/cli/src/sentry.ts | 9 +- .../cli/src/telemetry/posthogService.ts | 8 +- extensions/cli/src/tools/allBuiltIns.ts | 4 +- extensions/cli/src/tools/index.tsx | 8 +- extensions/cli/src/tools/reportFailure.ts | 101 ++++++++++++++++++ 6 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 extensions/cli/src/tools/reportFailure.ts diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 5f78155b2..2b3718462 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -26,6 +26,7 @@ import { createSession, getCompleteStateSnapshot } from "../session.js"; import { messageQueue } from "../stream/messageQueue.js"; import { constructSystemMessage } from "../systemMessage.js"; import { telemetryService } from "../telemetry/telemetryService.js"; +import { reportFailureTool } from "../tools/reportFailure.js"; import { gracefulExit } from "../util/exit.js"; import { formatError } from "../util/formatError.js"; import { getGitDiffSnapshot } from "../util/git.js"; @@ -472,6 +473,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { removePartialAssistantMessage(state); } else { logger.error(`Error: ${formatError(e)}`); + // Add error message via ChatHistoryService const errorMessage = `Error: ${formatError(e)}`; try { @@ -482,6 +484,18 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { contextItems: [], }); } + + // Report failure to control plane (retries exhausted or non-retryable error) + try { + await reportFailureTool.run({ + errorMessage: formatError(e), + }); + } catch (reportError) { + logger.error( + `Failed to report agent failure: ${formatError(reportError)}`, + ); + // Don't block on reporting failure + } } } finally { state.currentAbortController = null; diff --git a/extensions/cli/src/sentry.ts b/extensions/cli/src/sentry.ts index 838d6c27d..585c453a9 100644 --- a/extensions/cli/src/sentry.ts +++ b/extensions/cli/src/sentry.ts @@ -95,10 +95,17 @@ class SentryService { return this.config.enabled && this.initialized; } - public captureException(error: Error, context?: Record) { + public captureException( + error: Error, + context?: Record, + level?: "info" | "warning" | "error" | "debug" | "fatal", + ) { if (!this.isEnabled()) return; Sentry.withScope((scope) => { + if (level) { + scope.setLevel(level); + } if (context) { Object.entries(context).forEach(([key, value]) => { scope.setContext(key, value); diff --git a/extensions/cli/src/telemetry/posthogService.ts b/extensions/cli/src/telemetry/posthogService.ts index 025181f8b..1c2c66304 100644 --- a/extensions/cli/src/telemetry/posthogService.ts +++ b/extensions/cli/src/telemetry/posthogService.ts @@ -79,10 +79,16 @@ export class PosthogService { } /** - * - Continue user id if signed in + * - Continue user id from environment (when running as agent) + * - Continue user id if signed in locally * - Unique machine id if not signed in */ private getEventUserId(): string { + // When running as an agent, use the user ID from the environment + if (process.env.CONTINUE_USER_ID) { + return process.env.CONTINUE_USER_ID; + } + const authConfig = loadAuthConfig(); if (isAuthenticatedConfig(authConfig)) { diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index c239c37fc..09ba9dbba 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -4,9 +4,9 @@ import { fetchTool } from "./fetch.js"; import { listFilesTool } from "./listFiles.js"; import { multiEditTool } from "./multiEdit.js"; import { readFileTool } from "./readFile.js"; +import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; -import { statusTool } from "./status.js"; import { writeChecklistTool } from "./writeChecklist.js"; import { writeFileTool } from "./writeFile.js"; @@ -22,5 +22,5 @@ export const ALL_BUILT_IN_TOOLS = [ fetchTool, writeChecklistTool, exitTool, - statusTool, + reportFailureTool, ]; diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 4dee13f53..80a977c80 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -25,9 +25,9 @@ import { fetchTool } from "./fetch.js"; import { listFilesTool } from "./listFiles.js"; import { multiEditTool } from "./multiEdit.js"; import { readFileTool } from "./readFile.js"; +import { reportFailureTool } from "./reportFailure.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; -import { statusTool } from "./status.js"; import { type Tool, type ToolCall, @@ -49,6 +49,7 @@ const BASE_BUILTIN_TOOLS: Tool[] = [ runTerminalCommandTool, fetchTool, writeChecklistTool, + reportFailureTool, ]; // Get all builtin tools including dynamic ones, with capability-based filtering @@ -87,11 +88,6 @@ export async function getAllAvailableTools( tools.push(exitTool); } - // Add beta status tool if --beta-status-tool flag is present - if (process.argv.includes("--beta-status-tool")) { - tools.push(statusTool); - } - const mcpState = await serviceContainer.get( SERVICE_NAMES.MCP, ); diff --git a/extensions/cli/src/tools/reportFailure.ts b/extensions/cli/src/tools/reportFailure.ts new file mode 100644 index 000000000..1e0fede2e --- /dev/null +++ b/extensions/cli/src/tools/reportFailure.ts @@ -0,0 +1,101 @@ +import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; + +import { sentryService } from "../sentry.js"; +import { + ApiRequestError, + AuthenticationRequiredError, + post, +} from "../util/apiClient.js"; +import { logger } from "../util/logger.js"; + +import { Tool } from "./types.js"; + +/** + * Extract the agent ID from the --id command line flag + */ +function getAgentIdFromArgs(): string | undefined { + const args = process.argv; + const idIndex = args.indexOf("--id"); + if (idIndex !== -1 && idIndex + 1 < args.length) { + return args[idIndex + 1]; + } + return undefined; +} + +export const reportFailureTool: Tool = { + name: "ReportFailure", + displayName: "Report Failure", + description: + "Report that the task has failed due to an unrecoverable error. Include a succinct explanation for the user.", + parameters: { + type: "object", + required: ["errorMessage"], + properties: { + errorMessage: { + type: "string", + description: "Explain what went wrong and why you cannot continue.", + }, + }, + }, + readonly: true, + isBuiltIn: true, + run: async (args: { errorMessage: string }): Promise => { + try { + const trimmedMessage = args.errorMessage.trim(); + if (!trimmedMessage) { + throw new ContinueError( + ContinueErrorReason.Unspecified, + "errorMessage is required to report a failure.", + ); + } + + const agentId = getAgentIdFromArgs(); + if (!agentId) { + const errorMessage = + "Agent ID is required. Please use the --id flag with cn serve."; + logger.error(errorMessage); + throw new ContinueError(ContinueErrorReason.Unspecified, errorMessage); + } + + // Capture failure in Sentry with context + sentryService.captureException( + new Error(trimmedMessage), + { + agent_failure: { + agentId, + errorMessage: trimmedMessage, + }, + }, + "fatal", + ); + + await post(`agents/${agentId}/status`, { + status: "FAILED", + errorMessage: trimmedMessage, + }); + + logger.info(`Failure reported: ${trimmedMessage}`); + return "Failure reported to user."; + } catch (error) { + if (error instanceof ContinueError) { + throw error; + } + + if (error instanceof AuthenticationRequiredError) { + logger.error(error.message); + throw new Error("Error: Authentication required"); + } + + if (error instanceof ApiRequestError) { + throw new Error( + `Error reporting failure: ${error.status} ${error.response || error.statusText}`, + ); + } + + const errorMessage = + error instanceof Error ? error.message : String(error); + logger.error(`Error reporting failure: ${errorMessage}`); + throw new Error(`Error reporting failure: ${errorMessage}`); + } + }, +};