Elffuss BraidHub

kikocis/continue public

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