Elffuss BraidHub

kikocis/continue public

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