Elffuss BraidHub

kikocis/continue public

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