| 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import chalk from "chalk"; |
| 3 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 4 | import { ChatDescriber } from "core/util/chatDescriber.js"; |
| 5 | import * as readlineSync from "readline-sync"; |
| 6 | |
| 7 | import { compactChatHistory, findCompactionIndex } from "../compaction.js"; |
| 8 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 9 | import { safeStdout } from "../init.js"; |
| 10 | import { configureLogger } from "../logger.js"; |
| 11 | import * as logging from "../logging.js"; |
| 12 | import { sentryService } from "../sentry.js"; |
| 13 | import { initializeServices, services } from "../services/index.js"; |
| 14 | import { serviceContainer } from "../services/ServiceContainer.js"; |
| 15 | import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; |
| 16 | import { |
| 17 | loadSession, |
| 18 | updateSessionHistory, |
| 19 | updateSessionTitle, |
| 20 | } from "../session.js"; |
| 21 | import { streamChatResponse } from "../stream/streamChatResponse.js"; |
| 22 | import { posthogService } from "../telemetry/posthogService.js"; |
| 23 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 24 | import { startTUIChat } from "../ui/index.js"; |
| 25 | import { gracefulExit } from "../util/exit.js"; |
| 26 | import { formatAnthropicError, formatError } from "../util/formatError.js"; |
| 27 | import { logger } from "../util/logger.js"; |
| 28 | import { |
| 29 | calculateContextUsagePercentage, |
| 30 | countChatHistoryTokens, |
| 31 | shouldAutoCompact, |
| 32 | } from "../util/tokenizer.js"; |
| 33 | |
| 34 | import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; |
| 35 | |
| 36 | /** |
| 37 | * Processes and validates JSON output for headless mode |
| 38 | * @param response - The raw response from the LLM |
| 39 | * @returns Valid JSON string |
| 40 | */ |
| 41 | function processJsonOutput(response: string): string { |
| 42 | const trimmedResponse = response.trim(); |
| 43 | |
| 44 | try { |
| 45 | // Try to parse the response as JSON to validate it |
| 46 | JSON.parse(trimmedResponse); |
| 47 | // If it parses successfully, return as-is |
| 48 | return trimmedResponse; |
| 49 | } catch { |
| 50 | // If it's not valid JSON, wrap it in a JSON object |
| 51 | return JSON.stringify({ |
| 52 | response: trimmedResponse, |
| 53 | status: "success", |
| 54 | note: "Response was not valid JSON, so it was wrapped in a JSON object", |
| 55 | }); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Strips <think></think> tags and excess whitespace from response |
| 61 | * @param response - The raw response from the LLM |
| 62 | * @returns Cleaned response |
| 63 | */ |
| 64 | function stripThinkTags(response: string): string { |
| 65 | // Remove <think></think> tags and their content |
| 66 | let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, ""); |
| 67 | |
| 68 | // Remove excess whitespace: multiple consecutive newlines become single newlines |
| 69 | cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n"); |
| 70 | |
| 71 | // Trim leading and trailing whitespace |
| 72 | cleaned = cleaned.trim(); |
| 73 | |
| 74 | return cleaned; |
| 75 | } |
| 76 | |
| 77 | export interface ChatOptions extends ExtendedCommandOptions { |
| 78 | headless?: boolean; |
| 79 | resume?: boolean; |
| 80 | fork?: string; // Fork from an existing session ID |
| 81 | format?: "json"; // Output format for headless mode |
| 82 | silent?: boolean; // Strip <think></think> tags and excess whitespace |
| 83 | } |
| 84 | |
| 85 | export async function initializeChatHistory( |
| 86 | options: ChatOptions, |
| 87 | ): Promise<ChatHistoryItem[]> { |
| 88 | let session: Session | null = null; |
| 89 | |
| 90 | // Fork from an existing session if --fork flag is used |
| 91 | if (options.fork) { |
| 92 | const { loadSessionById, startNewSession } = await import("../session.js"); |
| 93 | const sessionToFork = loadSessionById(options.fork); |
| 94 | if (sessionToFork) { |
| 95 | logger.info(chalk.yellow("Forking from existing session...")); |
| 96 | const newSession = startNewSession(sessionToFork.history); |
| 97 | return newSession.history; |
| 98 | } else { |
| 99 | logger.error(chalk.red(`Session with ID "${options.fork}" not found.`)); |
| 100 | await gracefulExit(1); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | // Load previous session if --resume flag is used |
| 105 | if (options.resume) { |
| 106 | session = loadSession(); |
| 107 | if (session) { |
| 108 | logger.info(chalk.yellow("Resuming previous session...")); |
| 109 | return session.history; |
| 110 | } else { |
| 111 | logger.info(chalk.yellow("No previous session found, starting fresh...")); |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | return []; |
| 116 | } |
| 117 | |
| 118 | // Helper function to handle manual compaction |
| 119 | async function handleManualCompaction( |
| 120 | chatHistory: ChatHistoryItem[], |
| 121 | model: ModelConfig, |
| 122 | llmApi: any, |
| 123 | isHeadless: boolean, |
| 124 | ): Promise<{ compactionIndex?: number | null } | void> { |
| 125 | if (!isHeadless) { |
| 126 | console.info(chalk.yellow("Compacting chat history...")); |
| 127 | } |
| 128 | |
| 129 | try { |
| 130 | const current = services.chatHistory.getHistory(); |
| 131 | const result = await compactChatHistory(current, model, llmApi); |
| 132 | |
| 133 | // Update service-driven history (persistence handled by service) |
| 134 | services.chatHistory.compact( |
| 135 | result.compactedHistory, |
| 136 | result.compactionIndex, |
| 137 | ); |
| 138 | |
| 139 | if (isHeadless) { |
| 140 | safeStdout( |
| 141 | JSON.stringify({ |
| 142 | status: "success", |
| 143 | message: "Chat history compacted", |
| 144 | historyLength: services.chatHistory.getHistory().length, |
| 145 | }) + "\n", |
| 146 | ); |
| 147 | } else { |
| 148 | console.info(chalk.green("Chat history compacted successfully.")); |
| 149 | } |
| 150 | |
| 151 | return { compactionIndex: result.compactionIndex }; |
| 152 | } catch (error) { |
| 153 | const errorMsg = `Compaction error: ${formatError(error)}`; |
| 154 | if (isHeadless) { |
| 155 | safeStdout(JSON.stringify({ status: "error", message: errorMsg }) + "\n"); |
| 156 | } else { |
| 157 | console.error(chalk.red(errorMsg)); |
| 158 | } |
| 159 | return; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // Helper function to handle auto-compaction for headless mode |
| 164 | async function handleAutoCompaction( |
| 165 | chatHistory: ChatHistoryItem[], |
| 166 | model: ModelConfig, |
| 167 | llmApi: any, |
| 168 | isHeadless: boolean, |
| 169 | format?: "json", |
| 170 | ): Promise<number | null> { |
| 171 | const { handleAutoCompaction: coreAutoCompaction } = await import( |
| 172 | "../stream/streamChatResponse.autoCompaction.js" |
| 173 | ); |
| 174 | |
| 175 | // Custom callbacks for headless mode console output |
| 176 | const callbacks = { |
| 177 | onSystemMessage: (message: string) => { |
| 178 | if ( |
| 179 | message.includes("Auto-compacting") || |
| 180 | message.includes("Approaching") |
| 181 | ) { |
| 182 | if (!isHeadless) { |
| 183 | console.info(chalk.yellow(`\n${message}`)); |
| 184 | } else if (format === "json") { |
| 185 | safeStdout( |
| 186 | JSON.stringify({ |
| 187 | status: "info", |
| 188 | message: "Auto-compacting triggered", |
| 189 | contextUsage: |
| 190 | calculateContextUsagePercentage( |
| 191 | countChatHistoryTokens(services.chatHistory.getHistory()), |
| 192 | model, |
| 193 | ) + "%", |
| 194 | }) + "\n", |
| 195 | ); |
| 196 | } |
| 197 | } else if (message.includes("✓")) { |
| 198 | if (!isHeadless) { |
| 199 | console.info(chalk.green(message)); |
| 200 | } else if (format === "json") { |
| 201 | // Omit history length here; service updates occur after compaction completes |
| 202 | safeStdout( |
| 203 | JSON.stringify({ |
| 204 | status: "success", |
| 205 | message: "Auto-compacted successfully", |
| 206 | }) + "\n", |
| 207 | ); |
| 208 | } |
| 209 | } else if (message.includes("Warning:")) { |
| 210 | if (!isHeadless) { |
| 211 | console.error(chalk.red(message)); |
| 212 | console.info(chalk.yellow("Continuing without compaction...")); |
| 213 | } else if (format === "json") { |
| 214 | safeStdout( |
| 215 | JSON.stringify({ |
| 216 | status: "warning", |
| 217 | message: "Auto-compaction failed, continuing without compaction", |
| 218 | }) + "\n", |
| 219 | ); |
| 220 | } |
| 221 | } |
| 222 | }, |
| 223 | }; |
| 224 | |
| 225 | const result = await coreAutoCompaction( |
| 226 | services.chatHistory.getHistory(), |
| 227 | model, |
| 228 | llmApi, |
| 229 | { |
| 230 | isHeadless, |
| 231 | format, |
| 232 | callbacks, |
| 233 | }, |
| 234 | ); |
| 235 | |
| 236 | // Update service-driven history |
| 237 | services.chatHistory.setHistory(result.chatHistory); |
| 238 | |
| 239 | return result.compactionIndex; |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Helper to generate and update session title after first assistant response |
| 244 | */ |
| 245 | async function handleTitleGeneration( |
| 246 | assistantResponse: string, |
| 247 | llmApi: any, |
| 248 | model: ModelConfig, |
| 249 | ): Promise<void> { |
| 250 | try { |
| 251 | if (!assistantResponse) return; |
| 252 | |
| 253 | const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( |
| 254 | llmApi, |
| 255 | model, |
| 256 | assistantResponse, |
| 257 | ); |
| 258 | |
| 259 | if (generatedTitle) { |
| 260 | updateSessionTitle(generatedTitle); |
| 261 | logger.debug("Generated session title:", generatedTitle); |
| 262 | } |
| 263 | } catch (error) { |
| 264 | // Don't fail the response if title generation fails |
| 265 | logger.debug("Session title generation failed:", error); |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | interface ProcessMessageOptions { |
| 270 | userInput: string; |
| 271 | chatHistory: ChatHistoryItem[]; |
| 272 | model: ModelConfig; |
| 273 | llmApi: any; |
| 274 | isHeadless: boolean; |
| 275 | format?: "json"; |
| 276 | silent?: boolean; |
| 277 | compactionIndex?: number | null; |
| 278 | firstAssistantResponse?: boolean; |
| 279 | } |
| 280 | |
| 281 | async function processMessage( |
| 282 | options: ProcessMessageOptions, |
| 283 | ): Promise<{ compactionIndex?: number | null } | void> { |
| 284 | const { |
| 285 | userInput, |
| 286 | chatHistory, |
| 287 | model, |
| 288 | llmApi, |
| 289 | isHeadless, |
| 290 | format, |
| 291 | silent, |
| 292 | compactionIndex: initialCompactionIndex, |
| 293 | firstAssistantResponse = false, |
| 294 | } = options; |
| 295 | let compactionIndex = initialCompactionIndex; |
| 296 | // Check for slash commands in headless mode |
| 297 | if (userInput.trim() === "/compact") { |
| 298 | return handleManualCompaction(chatHistory, model, llmApi, isHeadless); |
| 299 | } |
| 300 | |
| 301 | // Track user prompt |
| 302 | telemetryService.logUserPrompt(userInput.length, userInput); |
| 303 | |
| 304 | // Check if auto-compacting is needed BEFORE adding user message |
| 305 | if (shouldAutoCompact(services.chatHistory.getHistory(), model)) { |
| 306 | const newIndex = await handleAutoCompaction( |
| 307 | chatHistory, |
| 308 | model, |
| 309 | llmApi, |
| 310 | isHeadless, |
| 311 | format, |
| 312 | ); |
| 313 | if (newIndex !== null) { |
| 314 | compactionIndex = newIndex; |
| 315 | // Service already updated in handleAutoCompaction via setHistory |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // Add user message to history AFTER potential compaction |
| 320 | services.chatHistory.addUserMessage(userInput); |
| 321 | |
| 322 | // Get AI response with potential tool usage |
| 323 | if (!isHeadless) { |
| 324 | console.info(`\n${chalk.bold.blue("Assistant:")}`); |
| 325 | } |
| 326 | |
| 327 | 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 | } |
| 352 | |
| 353 | // Generate session title after first assistant response |
| 354 | if (firstAssistantResponse && finalResponse && finalResponse.trim()) { |
| 355 | await handleTitleGeneration(finalResponse, llmApi, model); |
| 356 | } |
| 357 | |
| 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 | } |
| 375 | |
| 376 | // Save session after each successful response |
| 377 | updateSessionHistory(services.chatHistory.getHistory()); |
| 378 | } catch (e: any) { |
| 379 | const error = e instanceof Error ? e : new Error(String(e)); |
| 380 | |
| 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 | }); |
| 392 | if (!isHeadless) { |
| 393 | logger.info( |
| 394 | chalk.dim( |
| 395 | `Chat history:\n${JSON.stringify( |
| 396 | services.chatHistory.getHistory(), |
| 397 | null, |
| 398 | 2, |
| 399 | )}`, |
| 400 | ), |
| 401 | ); |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | async function runHeadlessMode( |
| 407 | prompt: string | undefined, |
| 408 | options: ChatOptions, |
| 409 | ): Promise<void> { |
| 410 | // Initialize services for headless mode |
| 411 | const { permissionOverrides } = processCommandFlags(options); |
| 412 | |
| 413 | await initializeServices({ |
| 414 | options, |
| 415 | headless: true, |
| 416 | toolPermissionOverrides: permissionOverrides, |
| 417 | }); |
| 418 | |
| 419 | // Get required services from the service container |
| 420 | const modelState = await serviceContainer.get<ModelServiceState>( |
| 421 | SERVICE_NAMES.MODEL, |
| 422 | ); |
| 423 | const { llmApi, model } = modelState; |
| 424 | |
| 425 | if (!model) { |
| 426 | throw new Error("No models were found."); |
| 427 | } |
| 428 | |
| 429 | // Initialize service-driven history (resume if requested) |
| 430 | const chatHistory = await initializeChatHistory(options); |
| 431 | let compactionIndex: number | null = null; |
| 432 | if (options.resume || options.fork) { |
| 433 | services.chatHistory.setHistory(chatHistory); |
| 434 | compactionIndex = findCompactionIndex(chatHistory); |
| 435 | } |
| 436 | |
| 437 | // Handle additional prompts from --prompt flags |
| 438 | const { processAndCombinePrompts } = await import( |
| 439 | "../util/promptProcessor.js" |
| 440 | ); |
| 441 | const initialUserInput = await processAndCombinePrompts( |
| 442 | options.prompt, |
| 443 | prompt, |
| 444 | ); |
| 445 | |
| 446 | let isFirstMessage = true; |
| 447 | while (true) { |
| 448 | // When in headless mode, don't ask for user input |
| 449 | if (!isFirstMessage && initialUserInput && options.headless) { |
| 450 | break; |
| 451 | } |
| 452 | |
| 453 | // Get user input |
| 454 | const userInput = |
| 455 | isFirstMessage && initialUserInput |
| 456 | ? initialUserInput |
| 457 | : readlineSync.question(`\n${chalk.bold.green("You:")} `); |
| 458 | |
| 459 | isFirstMessage = false; |
| 460 | |
| 461 | const result = await processMessage({ |
| 462 | userInput, |
| 463 | chatHistory, |
| 464 | model, |
| 465 | llmApi, |
| 466 | isHeadless: true, |
| 467 | format: options.format, |
| 468 | silent: options.silent, |
| 469 | compactionIndex, |
| 470 | firstAssistantResponse: isFirstMessage && !options.resume, // Only generate title for new conversations |
| 471 | }); |
| 472 | |
| 473 | // Update compaction index if compaction occurred |
| 474 | if (result && result.compactionIndex !== undefined) { |
| 475 | compactionIndex = result.compactionIndex; |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | export async function chat(prompt?: string, options: ChatOptions = {}) { |
| 481 | // Configure logger based on headless mode |
| 482 | configureLogger(options.headless ?? false); |
| 483 | |
| 484 | // Configure headless-aware logging system |
| 485 | logging.configureLogger({ headless: options.headless ?? false }); |
| 486 | |
| 487 | try { |
| 488 | // Record session start |
| 489 | telemetryService.recordSessionStart(); |
| 490 | await posthogService.capture("sessionStart", {}); |
| 491 | |
| 492 | // Start active time tracking |
| 493 | telemetryService.startActiveTime(); |
| 494 | |
| 495 | // If not in headless mode, use unified initialization with TUI |
| 496 | if (!options.headless) { |
| 497 | // Process flags for TUI mode |
| 498 | const { permissionOverrides } = processCommandFlags(options); |
| 499 | |
| 500 | // Initialize services with onboarding handled internally |
| 501 | const initResult = await initializeServices({ |
| 502 | options, |
| 503 | headless: false, |
| 504 | toolPermissionOverrides: permissionOverrides, |
| 505 | }); |
| 506 | |
| 507 | // If onboarding was completed, show success message |
| 508 | if (initResult.wasOnboarded) { |
| 509 | console.log(chalk.green("✓ Setup complete! Starting chat...")); |
| 510 | } |
| 511 | |
| 512 | // Start TUI with skipOnboarding since we already handled it |
| 513 | const tuiOptions: any = { |
| 514 | initialPrompt: prompt, |
| 515 | resume: options.resume, |
| 516 | fork: options.fork, |
| 517 | config: options.config, |
| 518 | org: options.org, |
| 519 | rule: options.rule, |
| 520 | prompt: options.prompt, |
| 521 | toolPermissionOverrides: permissionOverrides, |
| 522 | skipOnboarding: true, |
| 523 | }; |
| 524 | |
| 525 | // If we detected piped input, create a custom stdin for TUI |
| 526 | if ((options as any).hasPipedInput) { |
| 527 | const fs = await import("fs"); |
| 528 | const { ReadStream } = await import("tty"); |
| 529 | const ttyFd = fs.openSync("/dev/tty", "r"); |
| 530 | const customStdin = new ReadStream(ttyFd); |
| 531 | tuiOptions.customStdin = customStdin; |
| 532 | logger.debug("Created custom TTY stdin for TUI mode"); |
| 533 | } |
| 534 | |
| 535 | await startTUIChat(tuiOptions); |
| 536 | return; |
| 537 | } |
| 538 | |
| 539 | // Run headless mode |
| 540 | await runHeadlessMode(prompt, options); |
| 541 | } catch (error: any) { |
| 542 | const err = error instanceof Error ? error : new Error(String(error)); |
| 543 | // Use headless-aware error logging to ensure fatal errors are shown in headless mode |
| 544 | logging.error(chalk.red(`Fatal error: ${formatError(err)}`)); |
| 545 | sentryService.captureException(err, { |
| 546 | context: "chat_command_fatal", |
| 547 | headless: options.headless, |
| 548 | }); |
| 549 | await gracefulExit(1); |
| 550 | } finally { |
| 551 | // Stop active time tracking |
| 552 | telemetryService.stopActiveTime(); |
| 553 | } |
| 554 | } |