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
This commit is contained in:
Patrick Erichsen 2025-11-13 18:48:48 -08:00 • committed by GitHub
parent cffc9fb615
commit 23cc853785
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 134 additions and 10 deletions

View file

@ -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;

View file

@ -95,10 +95,17 @@ class SentryService {
return this.config.enabled && this.initialized;
}
public captureException(error: Error, context?: Record<string, any>) {
public captureException(
error: Error,
context?: Record<string, any>,
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);

View file

@ -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)) {

View file

@ -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,
];

View file

@ -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<MCPServiceState>(
SERVICE_NAMES.MCP,
);

View file

@ -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<string> => {
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}`);
}
},
};