Elffuss BraidHub

kikocis/continue public

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