diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index cdef19fb0..a954e8b34 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -1,11 +1,12 @@ import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; import chalk from "chalk"; import { ChatHistoryItem, Session } from "core"; import { ChatDescriber } from "core/util/chatDescriber.js"; import { compactChatHistory, findCompactionIndex } from "../compaction.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; -import { safeStdout } from "../init.js"; +import { safeStderr, safeStdout } from "../init.js"; import { configureLogger } from "../logger.js"; import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; @@ -119,7 +120,7 @@ export async function initializeChatHistory( async function handleManualCompaction( chatHistory: ChatHistoryItem[], model: ModelConfig, - llmApi: any, + llmApi: BaseLlmApi, isHeadless: boolean, ): Promise<{ compactionIndex?: number | null } | void> { if (!isHeadless) { @@ -160,11 +161,66 @@ async function handleManualCompaction( } } +// Helper function to get streaming response based on compaction state +async function getStreamingResponse( + compactionIndex: number | null | undefined, + model: ModelConfig, + llmApi: BaseLlmApi, +): Promise { + const abortController = new AbortController(); + + if (compactionIndex !== null && compactionIndex !== undefined) { + // Use service to compute history for LLM + const historyForLLM = + services.chatHistory.getHistoryForLLM(compactionIndex); + + return await streamChatResponse( + historyForLLM, + model, + llmApi, + abortController, + ); + } else { + // No compaction - get full history from service + return await streamChatResponse( + services.chatHistory.getHistory(), + model, + llmApi, + abortController, + ); + } +} + +// Helper function to process and output response in headless mode +function processAndOutputResponse( + finalResponse: string, + isHeadless: boolean, + silent?: boolean, + format?: "json", +): void { + if (isHeadless && finalResponse && finalResponse.trim()) { + let processedResponse = finalResponse; + + // Strip think tags if --silent flag is enabled + if (silent) { + processedResponse = stripThinkTags(processedResponse); + } + + // Process output based on format + const outputResponse = + format === "json" + ? processJsonOutput(processedResponse) + : processedResponse; + + safeStdout(outputResponse + "\n"); + } +} + // Helper function to handle auto-compaction for headless mode async function handleAutoCompaction( chatHistory: ChatHistoryItem[], model: ModelConfig, - llmApi: any, + llmApi: BaseLlmApi, isHeadless: boolean, format?: "json", ): Promise { @@ -244,7 +300,7 @@ async function handleAutoCompaction( */ async function handleTitleGeneration( assistantResponse: string, - llmApi: any, + llmApi: BaseLlmApi, model: ModelConfig, ): Promise { try { @@ -270,7 +326,7 @@ interface ProcessMessageOptions { userInput: string; chatHistory: ChatHistoryItem[]; model: ModelConfig; - llmApi: any; + llmApi: BaseLlmApi; isHeadless: boolean; format?: "json"; silent?: boolean; @@ -325,71 +381,35 @@ async function processMessage( } try { - const abortController = new AbortController(); - - // Service-driven streaming; history updates occur via ChatHistoryService - let finalResponse; - if (compactionIndex !== null && compactionIndex !== undefined) { - // Use service to compute history for LLM - const historyForLLM = - services.chatHistory.getHistoryForLLM(compactionIndex); - - finalResponse = await streamChatResponse( - historyForLLM, - model, - llmApi, - abortController, - ); - } else { - // No compaction - get full history from service - finalResponse = await streamChatResponse( - services.chatHistory.getHistory(), - model, - llmApi, - abortController, - ); - } + // Get AI response with potential tool usage + const finalResponse = await getStreamingResponse( + compactionIndex, + model, + llmApi, + ); // Generate session title after first assistant response if (firstAssistantResponse && finalResponse && finalResponse.trim()) { await handleTitleGeneration(finalResponse, llmApi, model); } - // In headless mode, only print the final response using safe stdout - if (isHeadless && finalResponse && finalResponse.trim()) { - let processedResponse = finalResponse; - - // Strip think tags if --silent flag is enabled - if (silent) { - processedResponse = stripThinkTags(processedResponse); - } - - // Process output based on format - const outputResponse = - format === "json" - ? processJsonOutput(processedResponse) - : processedResponse; - - safeStdout(outputResponse + "\n"); - } + // Process and output response in headless mode + processAndOutputResponse(finalResponse, isHeadless, silent, format); // Save session after each successful response updateSessionHistory(services.chatHistory.getHistory()); } catch (e: any) { const error = e instanceof Error ? e : new Error(String(e)); - if (model.provider === "anthropic") { - logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); - } else { - logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); - } - - sentryService.captureException(error, { - context: "chat_response", - isHeadless, - chatHistoryLength: services.chatHistory.getHistory().length, - }); + // In headless mode, don't output JSON here - let error bubble up to main handler if (!isHeadless) { + // Non-headless mode: use colored console output + if (model.provider === "anthropic") { + logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); + } else { + logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); + } + logger.info( chalk.dim( `Chat history:\n${JSON.stringify( @@ -400,6 +420,18 @@ async function processMessage( ), ); } + + sentryService.captureException(error, { + context: "chat_response", + isHeadless, + chatHistoryLength: services.chatHistory.getHistory().length, + }); + + // In headless mode, re-throw the error to bubble up to main error handler + // This preserves downstream logic like telemetry cleanup + if (isHeadless) { + throw error; + } } } @@ -426,6 +458,10 @@ async function runHeadlessMode( throw new Error("No models were found."); } + if (!llmApi) { + throw new Error("No LLM API instance found."); + } + // Initialize service-driven history (resume if requested) const chatHistory = await initializeChatHistory(options); let compactionIndex: number | null = null; @@ -535,15 +571,30 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { await runHeadlessMode(prompt, options); } catch (error: any) { const err = error instanceof Error ? error : new Error(String(error)); - // Use headless-aware error logging to ensure fatal errors are shown in headless mode - logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); + + // In headless mode, output error as JSON to stdout + if (options.headless) { + const errorOutput = { + status: "error", + message: err.message || String(err), + }; + safeStderr(JSON.stringify(errorOutput) + "\n"); + } else { + // Use headless-aware error logging for non-headless mode + logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); + } + sentryService.captureException(err, { context: "chat_command_fatal", headless: options.headless, }); + + // Stop active time tracking BEFORE graceful exit + telemetryService.stopActiveTime(); + await gracefulExit(1); } finally { - // Stop active time tracking + // Stop active time tracking for normal completion telemetryService.stopActiveTime(); } } diff --git a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts index a13823c69..a5ccf0970 100644 --- a/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +++ b/extensions/cli/src/e2e/headless-anthropic-api-key.test.ts @@ -8,8 +8,8 @@ import { } from "../test-helpers/cli-helpers.js"; import { cleanupMockLLMServer, - type MockLLMServer, createMockLLMServer, + type MockLLMServer, } from "../test-helpers/mock-llm-server.js"; describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => { @@ -80,9 +80,9 @@ models: expect(userMessage.content).toBe("Hi there"); }, 20000); - it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => { + it("should create config but fail with invalid API key when no config exists", async () => { // This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY - // when no config file exists in headless mode + // when no config file exists, but fails when the API key is invalid const result = await runCLI(context, { args: ["-p", "test prompt"], @@ -90,13 +90,17 @@ models: ANTHROPIC_API_KEY: "TEST-test-invalid-key-format", CONTINUE_GLOBAL_DIR: context.testDir + "/.continue", }, - expectError: false, // Config creation succeeds even with invalid key + expectError: true, // API call should fail with invalid key timeout: 15000, }); - // The CLI should create config and exit successfully in headless mode - // (it doesn't actually make API calls unless there's a valid provider setup) - expect(result.exitCode).toBe(0); + // The CLI should create config but fail due to invalid API key + // This is expected behavior - invalid API keys should cause authentication errors + expect(result.exitCode).toBe(1); + + // Should contain authentication error (not service initialization error) + expect(result.stderr).toContain("authentication_error"); + expect(result.stderr).toContain("invalid x-api-key"); // Should NOT contain the old error about service initialization expect(result.stderr).not.toContain("Failed to initialize ConfigService");