Elffuss BraidHub

kikocis/continue public

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