Elffuss BraidHub

kikocis/continue public

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