Changesets · Branches · Tags · Compare
| Changeset | c9a6efde71c8ea603447d7e4af2f6817f7156263dbef8b21715c302e8bcf343a |
|---|---|
| Author | Ting-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-22 14:49 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-22 14:49 -07:00 |
| Parents | 89cedaf513f2 |
2 files changed
modified extensions/cli/src/commands/chat.ts +111 −60
| @@ -1,11 +1,12 @@ | ||
| 1 | 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 2 | 3 | import chalk from "chalk"; |
| 3 | 4 | import { ChatHistoryItem, Session } from "core"; |
| 4 | 5 | import { ChatDescriber } from "core/util/chatDescriber.js"; |
| 5 | 6 | |
| 6 | 7 | import { compactChatHistory, findCompactionIndex } from "../compaction.js"; |
| 7 | 8 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 8 | -import { safeStdout } from "../init.js"; | |
| 9 | +import { safeStderr, safeStdout } from "../init.js"; | |
| 9 | 10 | import { configureLogger } from "../logger.js"; |
| 10 | 11 | import * as logging from "../logging.js"; |
| 11 | 12 | import { sentryService } from "../sentry.js"; |
| @@ -119,7 +120,7 @@ | ||
| 119 | 120 | async function handleManualCompaction( |
| 120 | 121 | chatHistory: ChatHistoryItem[], |
| 121 | 122 | model: ModelConfig, |
| 122 | - llmApi: any, | |
| 123 | + llmApi: BaseLlmApi, | |
| 123 | 124 | isHeadless: boolean, |
| 124 | 125 | ): Promise<{ compactionIndex?: number | null } | void> { |
| 125 | 126 | if (!isHeadless) { |
| @@ -160,11 +161,66 @@ | ||
| 160 | 161 | } |
| 161 | 162 | } |
| 162 | 163 | |
| 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 | + | |
| 163 | 219 | // Helper function to handle auto-compaction for headless mode |
| 164 | 220 | async function handleAutoCompaction( |
| 165 | 221 | chatHistory: ChatHistoryItem[], |
| 166 | 222 | model: ModelConfig, |
| 167 | - llmApi: any, | |
| 223 | + llmApi: BaseLlmApi, | |
| 168 | 224 | isHeadless: boolean, |
| 169 | 225 | format?: "json", |
| 170 | 226 | ): Promise<number | null> { |
| @@ -244,7 +300,7 @@ | ||
| 244 | 300 | */ |
| 245 | 301 | async function handleTitleGeneration( |
| 246 | 302 | assistantResponse: string, |
| 247 | - llmApi: any, | |
| 303 | + llmApi: BaseLlmApi, | |
| 248 | 304 | model: ModelConfig, |
| 249 | 305 | ): Promise<void> { |
| 250 | 306 | try { |
| @@ -270,7 +326,7 @@ | ||
| 270 | 326 | userInput: string; |
| 271 | 327 | chatHistory: ChatHistoryItem[]; |
| 272 | 328 | model: ModelConfig; |
| 273 | - llmApi: any; | |
| 329 | + llmApi: BaseLlmApi; | |
| 274 | 330 | isHeadless: boolean; |
| 275 | 331 | format?: "json"; |
| 276 | 332 | silent?: boolean; |
| @@ -325,71 +381,35 @@ | ||
| 325 | 381 | } |
| 326 | 382 | |
| 327 | 383 | 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 | + ); | |
| 352 | 390 | |
| 353 | 391 | // Generate session title after first assistant response |
| 354 | 392 | if (firstAssistantResponse && finalResponse && finalResponse.trim()) { |
| 355 | 393 | await handleTitleGeneration(finalResponse, llmApi, model); |
| 356 | 394 | } |
| 357 | 395 | |
| 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); | |
| 375 | 398 | |
| 376 | 399 | // Save session after each successful response |
| 377 | 400 | updateSessionHistory(services.chatHistory.getHistory()); |
| 378 | 401 | } catch (e: any) { |
| 379 | 402 | const error = e instanceof Error ? e : new Error(String(e)); |
| 380 | 403 | |
| 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 | |
| 392 | 405 | 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 | + | |
| 393 | 413 | logger.info( |
| 394 | 414 | chalk.dim( |
| 395 | 415 | `Chat history:\n${JSON.stringify( |
| @@ -400,6 +420,18 @@ | ||
| 400 | 420 | ), |
| 401 | 421 | ); |
| 402 | 422 | } |
| 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 | + } | |
| 403 | 435 | } |
| 404 | 436 | } |
| 405 | 437 | |
| @@ -426,6 +458,10 @@ | ||
| 426 | 458 | throw new Error("No models were found."); |
| 427 | 459 | } |
| 428 | 460 | |
| 461 | + if (!llmApi) { | |
| 462 | + throw new Error("No LLM API instance found."); | |
| 463 | + } | |
| 464 | + | |
| 429 | 465 | // Initialize service-driven history (resume if requested) |
| 430 | 466 | const chatHistory = await initializeChatHistory(options); |
| 431 | 467 | let compactionIndex: number | null = null; |
| @@ -535,15 +571,30 @@ | ||
| 535 | 571 | await runHeadlessMode(prompt, options); |
| 536 | 572 | } catch (error: any) { |
| 537 | 573 | 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 | + | |
| 540 | 587 | sentryService.captureException(err, { |
| 541 | 588 | context: "chat_command_fatal", |
| 542 | 589 | headless: options.headless, |
| 543 | 590 | }); |
| 591 | + | |
| 592 | + // Stop active time tracking BEFORE graceful exit | |
| 593 | + telemetryService.stopActiveTime(); | |
| 594 | + | |
| 544 | 595 | await gracefulExit(1); |
| 545 | 596 | } finally { |
| 546 | - // Stop active time tracking | |
| 597 | + // Stop active time tracking for normal completion | |
| 547 | 598 | telemetryService.stopActiveTime(); |
| 548 | 599 | } |
| 549 | 600 | } |
modified extensions/cli/src/e2e/headless-anthropic-api-key.test.ts +11 −7
| @@ -8,8 +8,8 @@ | ||
| 8 | 8 | } from "../test-helpers/cli-helpers.js"; |
| 9 | 9 | import { |
| 10 | 10 | cleanupMockLLMServer, |
| 11 | - type MockLLMServer, | |
| 12 | 11 | createMockLLMServer, |
| 12 | + type MockLLMServer, | |
| 13 | 13 | } from "../test-helpers/mock-llm-server.js"; |
| 14 | 14 | |
| 15 | 15 | describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => { |
| @@ -80,9 +80,9 @@ | ||
| 80 | 80 | expect(userMessage.content).toBe("Hi there"); |
| 81 | 81 | }, 20000); |
| 82 | 82 | |
| 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 () => { | |
| 84 | 84 | // 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 | |
| 86 | 86 | |
| 87 | 87 | const result = await runCLI(context, { |
| 88 | 88 | args: ["-p", "test prompt"], |
| @@ -90,13 +90,17 @@ | ||
| 90 | 90 | ANTHROPIC_API_KEY: "TEST-test-invalid-key-format", |
| 91 | 91 | CONTINUE_GLOBAL_DIR: context.testDir + "/.continue", |
| 92 | 92 | }, |
| 93 | - expectError: false, // Config creation succeeds even with invalid key | |
| 93 | + expectError: true, // API call should fail with invalid key | |
| 94 | 94 | timeout: 15000, |
| 95 | 95 | }); |
| 96 | 96 | |
| 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"); | |
| 100 | 104 | |
| 101 | 105 | // Should NOT contain the old error about service initialization |
| 102 | 106 | expect(result.stderr).not.toContain("Failed to initialize ConfigService"); |