Elffuss BraidHub

kikocis/continue public

4131ae02de3e · 16.1 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import chalk from "chalk";
3import type { ChatHistoryItem, Session } from "core/index.js";
4import { ChatDescriber } from "core/util/chatDescriber.js";
5import * as readlineSync from "readline-sync";
6
7import { compactChatHistory, findCompactionIndex } from "../compaction.js";
8import { processCommandFlags } from "../flags/flagProcessor.js";
9import { 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 {
29 calculateContextUsagePercentage,
30 countChatHistoryTokens,
31 shouldAutoCompact,
32} from "../util/tokenizer.js";
33
34import { 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 */
41function 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 */
64function 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
77export 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
85export 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
119async 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
164async 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 */
245async 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
269interface 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
281async 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
406async 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
480export 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 await initializeServices({
502 options,
503 headless: false,
504 toolPermissionOverrides: permissionOverrides,
505 });
506
507 // Start TUI with skipOnboarding since we already handled it
508 const tuiOptions: any = {
509 initialPrompt: prompt,
510 resume: options.resume,
511 fork: options.fork,
512 config: options.config,
513 org: options.org,
514 rule: options.rule,
515 prompt: options.prompt,
516 toolPermissionOverrides: permissionOverrides,
517 skipOnboarding: true,
518 };
519
520 // If we detected piped input, create a custom stdin for TUI
521 if ((options as any).hasPipedInput) {
522 const fs = await import("fs");
523 const { ReadStream } = await import("tty");
524 const ttyFd = fs.openSync("/dev/tty", "r");
525 const customStdin = new ReadStream(ttyFd);
526 tuiOptions.customStdin = customStdin;
527 logger.debug("Created custom TTY stdin for TUI mode");
528 }
529
530 await startTUIChat(tuiOptions);
531 return;
532 }
533
534 // Run headless mode
535 await runHeadlessMode(prompt, options);
536 } catch (error: any) {
537 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)}`));
540 sentryService.captureException(err, {
541 context: "chat_command_fatal",
542 headless: options.headless,
543 });
544 await gracefulExit(1);
545 } finally {
546 // Stop active time tracking
547 telemetryService.stopActiveTime();
548 }
549}