Elffuss BraidHub

kikocis/continue public

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