Elffuss BraidHub

kikocis/continue public

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