Elffuss BraidHub

kikocis/continue public

feat: headless mode surface errors and exit code 1 (#7864)

* feat: cn headless bubble up errors and exit code

* refactor to reduce eslint complexity error

* fix test
Changesetc9a6efde71c8ea603447d7e4af2f6817f7156263dbef8b21715c302e8bcf343a
AuthorTing-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-22 14:49 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-22 14:49 -07:00
Parents89cedaf513f2

Browse the files at this changeset

2 files changed

modified extensions/cli/src/commands/chat.ts +111 −60
@@ -1,11 +1,12 @@
11 import { ModelConfig } from "@continuedev/config-yaml";
2+import { BaseLlmApi } from "@continuedev/openai-adapters";
23 import chalk from "chalk";
34 import { ChatHistoryItem, Session } from "core";
45 import { ChatDescriber } from "core/util/chatDescriber.js";
56
67 import { compactChatHistory, findCompactionIndex } from "../compaction.js";
78 import { processCommandFlags } from "../flags/flagProcessor.js";
8-import { safeStdout } from "../init.js";
9+import { safeStderr, safeStdout } from "../init.js";
910 import { configureLogger } from "../logger.js";
1011 import * as logging from "../logging.js";
1112 import { sentryService } from "../sentry.js";
@@ -119,7 +120,7 @@
119120 async function handleManualCompaction(
120121 chatHistory: ChatHistoryItem[],
121122 model: ModelConfig,
122- llmApi: any,
123+ llmApi: BaseLlmApi,
123124 isHeadless: boolean,
124125 ): Promise<{ compactionIndex?: number | null } | void> {
125126 if (!isHeadless) {
@@ -160,11 +161,66 @@
160161 }
161162 }
162163
164+// Helper function to get streaming response based on compaction state
165+async function getStreamingResponse(
166+ compactionIndex: number | null | undefined,
167+ model: ModelConfig,
168+ llmApi: BaseLlmApi,
169+): Promise<string> {
170+ const abortController = new AbortController();
171+
172+ if (compactionIndex !== null && compactionIndex !== undefined) {
173+ // Use service to compute history for LLM
174+ const historyForLLM =
175+ services.chatHistory.getHistoryForLLM(compactionIndex);
176+
177+ return await streamChatResponse(
178+ historyForLLM,
179+ model,
180+ llmApi,
181+ abortController,
182+ );
183+ } else {
184+ // No compaction - get full history from service
185+ return await streamChatResponse(
186+ services.chatHistory.getHistory(),
187+ model,
188+ llmApi,
189+ abortController,
190+ );
191+ }
192+}
193+
194+// Helper function to process and output response in headless mode
195+function processAndOutputResponse(
196+ finalResponse: string,
197+ isHeadless: boolean,
198+ silent?: boolean,
199+ format?: "json",
200+): void {
201+ if (isHeadless && finalResponse && finalResponse.trim()) {
202+ let processedResponse = finalResponse;
203+
204+ // Strip think tags if --silent flag is enabled
205+ if (silent) {
206+ processedResponse = stripThinkTags(processedResponse);
207+ }
208+
209+ // Process output based on format
210+ const outputResponse =
211+ format === "json"
212+ ? processJsonOutput(processedResponse)
213+ : processedResponse;
214+
215+ safeStdout(outputResponse + "\n");
216+ }
217+}
218+
163219 // Helper function to handle auto-compaction for headless mode
164220 async function handleAutoCompaction(
165221 chatHistory: ChatHistoryItem[],
166222 model: ModelConfig,
167- llmApi: any,
223+ llmApi: BaseLlmApi,
168224 isHeadless: boolean,
169225 format?: "json",
170226 ): Promise<number | null> {
@@ -244,7 +300,7 @@
244300 */
245301 async function handleTitleGeneration(
246302 assistantResponse: string,
247- llmApi: any,
303+ llmApi: BaseLlmApi,
248304 model: ModelConfig,
249305 ): Promise<void> {
250306 try {
@@ -270,7 +326,7 @@
270326 userInput: string;
271327 chatHistory: ChatHistoryItem[];
272328 model: ModelConfig;
273- llmApi: any;
329+ llmApi: BaseLlmApi;
274330 isHeadless: boolean;
275331 format?: "json";
276332 silent?: boolean;
@@ -325,71 +381,35 @@
325381 }
326382
327383 try {
328- const abortController = new AbortController();
329-
330- // Service-driven streaming; history updates occur via ChatHistoryService
331- let finalResponse;
332- if (compactionIndex !== null && compactionIndex !== undefined) {
333- // Use service to compute history for LLM
334- const historyForLLM =
335- services.chatHistory.getHistoryForLLM(compactionIndex);
336-
337- finalResponse = await streamChatResponse(
338- historyForLLM,
339- model,
340- llmApi,
341- abortController,
342- );
343- } else {
344- // No compaction - get full history from service
345- finalResponse = await streamChatResponse(
346- services.chatHistory.getHistory(),
347- model,
348- llmApi,
349- abortController,
350- );
351- }
384+ // Get AI response with potential tool usage
385+ const finalResponse = await getStreamingResponse(
386+ compactionIndex,
387+ model,
388+ llmApi,
389+ );
352390
353391 // Generate session title after first assistant response
354392 if (firstAssistantResponse && finalResponse && finalResponse.trim()) {
355393 await handleTitleGeneration(finalResponse, llmApi, model);
356394 }
357395
358- // In headless mode, only print the final response using safe stdout
359- if (isHeadless && finalResponse && finalResponse.trim()) {
360- let processedResponse = finalResponse;
361-
362- // Strip think tags if --silent flag is enabled
363- if (silent) {
364- processedResponse = stripThinkTags(processedResponse);
365- }
366-
367- // Process output based on format
368- const outputResponse =
369- format === "json"
370- ? processJsonOutput(processedResponse)
371- : processedResponse;
372-
373- safeStdout(outputResponse + "\n");
374- }
396+ // Process and output response in headless mode
397+ processAndOutputResponse(finalResponse, isHeadless, silent, format);
375398
376399 // Save session after each successful response
377400 updateSessionHistory(services.chatHistory.getHistory());
378401 } catch (e: any) {
379402 const error = e instanceof Error ? e : new Error(String(e));
380403
381- if (model.provider === "anthropic") {
382- logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
383- } else {
384- logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
385- }
386-
387- sentryService.captureException(error, {
388- context: "chat_response",
389- isHeadless,
390- chatHistoryLength: services.chatHistory.getHistory().length,
391- });
404+ // In headless mode, don't output JSON here - let error bubble up to main handler
392405 if (!isHeadless) {
406+ // Non-headless mode: use colored console output
407+ if (model.provider === "anthropic") {
408+ logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
409+ } else {
410+ logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
411+ }
412+
393413 logger.info(
394414 chalk.dim(
395415 `Chat history:\n${JSON.stringify(
@@ -400,6 +420,18 @@
400420 ),
401421 );
402422 }
423+
424+ sentryService.captureException(error, {
425+ context: "chat_response",
426+ isHeadless,
427+ chatHistoryLength: services.chatHistory.getHistory().length,
428+ });
429+
430+ // In headless mode, re-throw the error to bubble up to main error handler
431+ // This preserves downstream logic like telemetry cleanup
432+ if (isHeadless) {
433+ throw error;
434+ }
403435 }
404436 }
405437
@@ -426,6 +458,10 @@
426458 throw new Error("No models were found.");
427459 }
428460
461+ if (!llmApi) {
462+ throw new Error("No LLM API instance found.");
463+ }
464+
429465 // Initialize service-driven history (resume if requested)
430466 const chatHistory = await initializeChatHistory(options);
431467 let compactionIndex: number | null = null;
@@ -535,15 +571,30 @@
535571 await runHeadlessMode(prompt, options);
536572 } catch (error: any) {
537573 const err = error instanceof Error ? error : new Error(String(error));
538- // Use headless-aware error logging to ensure fatal errors are shown in headless mode
539- logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
574+
575+ // In headless mode, output error as JSON to stdout
576+ if (options.headless) {
577+ const errorOutput = {
578+ status: "error",
579+ message: err.message || String(err),
580+ };
581+ safeStderr(JSON.stringify(errorOutput) + "\n");
582+ } else {
583+ // Use headless-aware error logging for non-headless mode
584+ logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
585+ }
586+
540587 sentryService.captureException(err, {
541588 context: "chat_command_fatal",
542589 headless: options.headless,
543590 });
591+
592+ // Stop active time tracking BEFORE graceful exit
593+ telemetryService.stopActiveTime();
594+
544595 await gracefulExit(1);
545596 } finally {
546- // Stop active time tracking
597+ // Stop active time tracking for normal completion
547598 telemetryService.stopActiveTime();
548599 }
549600 }
modified extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +11 −7
@@ -8,8 +8,8 @@
88 } from "../test-helpers/cli-helpers.js";
99 import {
1010 cleanupMockLLMServer,
11- type MockLLMServer,
1211 createMockLLMServer,
12+ type MockLLMServer,
1313 } from "../test-helpers/mock-llm-server.js";
1414
1515 describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => {
@@ -80,9 +80,9 @@
8080 expect(userMessage.content).toBe("Hi there");
8181 }, 20000);
8282
83- it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => {
83+ it("should create config but fail with invalid API key when no config exists", async () => {
8484 // This test verifies that CLI automatically creates config from ANTHROPIC_API_KEY
85- // when no config file exists in headless mode
85+ // when no config file exists, but fails when the API key is invalid
8686
8787 const result = await runCLI(context, {
8888 args: ["-p", "test prompt"],
@@ -90,13 +90,17 @@
9090 ANTHROPIC_API_KEY: "TEST-test-invalid-key-format",
9191 CONTINUE_GLOBAL_DIR: context.testDir + "/.continue",
9292 },
93- expectError: false, // Config creation succeeds even with invalid key
93+ expectError: true, // API call should fail with invalid key
9494 timeout: 15000,
9595 });
9696
97- // The CLI should create config and exit successfully in headless mode
98- // (it doesn't actually make API calls unless there's a valid provider setup)
99- expect(result.exitCode).toBe(0);
97+ // The CLI should create config but fail due to invalid API key
98+ // This is expected behavior - invalid API keys should cause authentication errors
99+ expect(result.exitCode).toBe(1);
100+
101+ // Should contain authentication error (not service initialization error)
102+ expect(result.stderr).toContain("authentication_error");
103+ expect(result.stderr).toContain("invalid x-api-key");
100104
101105 // Should NOT contain the old error about service initialization
102106 expect(result.stderr).not.toContain("Failed to initialize ConfigService");