Elffuss BraidHub

kikocis/continue public

c61dd95048cf · 16.3 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import chalk from "chalk";
3import type { ChatHistoryItem, Session } from "core/index.js";
4import { ChatDescriber } from "core/util/chatDescriber.js";
5import * as readlineSync from "readline-sync";
6
7import { compactChatHistory, findCompactionIndex } from "../compaction.js";
8import { processCommandFlags } from "../flags/flagProcessor.js";
9import { safeStdout } from "../init.js";
10import { configureLogger } from "../logger.js";
11import * as logging from "../logging.js";
12import { sentryService } from "../sentry.js";
13import { initializeServices, services } from "../services/index.js";
14import { serviceContainer } from "../services/ServiceContainer.js";
15import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
16import {
17 loadSession,
18 updateSessionHistory,
19 updateSessionTitle,
20} from "../session.js";
21import { streamChatResponse } from "../stream/streamChatResponse.js";
22import { posthogService } from "../telemetry/posthogService.js";
23import { telemetryService } from "../telemetry/telemetryService.js";
24import { startTUIChat } from "../ui/index.js";
25import { formatAnthropicError, formatError } from "../util/formatError.js";
26import { logger } from "../util/logger.js";
27import {
28 calculateContextUsagePercentage,
29 countChatHistoryTokens,
30 shouldAutoCompact,
31} from "../util/tokenizer.js";
32
33import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
34
35/**
36 * Processes and validates JSON output for headless mode
37 * @param response - The raw response from the LLM
38 * @returns Valid JSON string
39 */
40function processJsonOutput(response: string): string {
41 const trimmedResponse = response.trim();
42
43 try {
44 // Try to parse the response as JSON to validate it
45 JSON.parse(trimmedResponse);
46 // If it parses successfully, return as-is
47 return trimmedResponse;
48 } catch {
49 // If it's not valid JSON, wrap it in a JSON object
50 return JSON.stringify({
51 response: trimmedResponse,
52 status: "success",
53 note: "Response was not valid JSON, so it was wrapped in a JSON object",
54 });
55 }
56}
57
58/**
59 * Strips <think></think> tags and excess whitespace from response
60 * @param response - The raw response from the LLM
61 * @returns Cleaned response
62 */
63function stripThinkTags(response: string): string {
64 // Remove <think></think> tags and their content
65 let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, "");
66
67 // Remove excess whitespace: multiple consecutive newlines become single newlines
68 cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n");
69
70 // Trim leading and trailing whitespace
71 cleaned = cleaned.trim();
72
73 return cleaned;
74}
75
76export interface ChatOptions extends ExtendedCommandOptions {
77 headless?: boolean;
78 resume?: boolean;
79 fork?: string; // Fork from an existing session ID
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<ChatHistoryItem[]> {
87 let session: Session | null = null;
88
89 // Fork from an existing session if --fork flag is used
90 if (options.fork) {
91 const { loadSessionById, startNewSession } = await import("../session.js");
92 const sessionToFork = loadSessionById(options.fork);
93 if (sessionToFork) {
94 logger.info(chalk.yellow("Forking from existing session..."));
95 const newSession = startNewSession(sessionToFork.history);
96 return newSession.history;
97 } else {
98 logger.error(chalk.red(`Session with ID "${options.fork}" not found.`));
99 process.exit(1);
100 }
101 }
102
103 // Load previous session if --resume flag is used
104 if (options.resume) {
105 session = loadSession();
106 if (session) {
107 logger.info(chalk.yellow("Resuming previous session..."));
108 return session.history;
109 } else {
110 logger.info(chalk.yellow("No previous session found, starting fresh..."));
111 }
112 }
113
114 return [];
115}
116
117// Helper function to handle manual compaction
118async function handleManualCompaction(
119 chatHistory: ChatHistoryItem[],
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 current = services.chatHistory.getHistory();
130 const result = await compactChatHistory(current, model, llmApi);
131
132 // Update service-driven history (persistence handled by service)
133 services.chatHistory.compact(
134 result.compactedHistory,
135 result.compactionIndex,
136 );
137
138 if (isHeadless) {
139 safeStdout(
140 JSON.stringify({
141 status: "success",
142 message: "Chat history compacted",
143 historyLength: services.chatHistory.getHistory().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: ChatHistoryItem[],
165 model: ModelConfig,
166 llmApi: any,
167 isHeadless: boolean,
168 format?: "json",
169): Promise<number | null> {
170 const { handleAutoCompaction: coreAutoCompaction } = await import(
171 "../stream/streamChatResponse.autoCompaction.js"
172 );
173
174 // Custom callbacks for headless mode console output
175 const callbacks = {
176 onSystemMessage: (message: string) => {
177 if (
178 message.includes("Auto-compacting") ||
179 message.includes("Approaching")
180 ) {
181 if (!isHeadless) {
182 console.info(chalk.yellow(`\n${message}`));
183 } else if (format === "json") {
184 safeStdout(
185 JSON.stringify({
186 status: "info",
187 message: "Auto-compacting triggered",
188 contextUsage:
189 calculateContextUsagePercentage(
190 countChatHistoryTokens(services.chatHistory.getHistory()),
191 model,
192 ) + "%",
193 }) + "\n",
194 );
195 }
196 } else if (message.includes("✓")) {
197 if (!isHeadless) {
198 console.info(chalk.green(message));
199 } else if (format === "json") {
200 // Omit history length here; service updates occur after compaction completes
201 safeStdout(
202 JSON.stringify({
203 status: "success",
204 message: "Auto-compacted successfully",
205 }) + "\n",
206 );
207 }
208 } else if (message.includes("Warning:")) {
209 if (!isHeadless) {
210 console.error(chalk.red(message));
211 console.info(chalk.yellow("Continuing without compaction..."));
212 } else if (format === "json") {
213 safeStdout(
214 JSON.stringify({
215 status: "warning",
216 message: "Auto-compaction failed, continuing without compaction",
217 }) + "\n",
218 );
219 }
220 }
221 },
222 };
223
224 const result = await coreAutoCompaction(
225 services.chatHistory.getHistory(),
226 model,
227 llmApi,
228 {
229 isHeadless,
230 format,
231 callbacks,
232 },
233 );
234
235 // Update service-driven history
236 services.chatHistory.setHistory(result.chatHistory);
237
238 return result.compactionIndex;
239}
240
241/**
242 * Helper to generate and update session title after first assistant response
243 */
244async function handleTitleGeneration(
245 assistantResponse: string,
246 llmApi: any,
247 model: ModelConfig,
248): Promise<void> {
249 try {
250 if (!assistantResponse) return;
251
252 const generatedTitle = await ChatDescriber.describeWithBaseLlmApi(
253 llmApi,
254 model,
255 assistantResponse,
256 );
257
258 if (generatedTitle) {
259 updateSessionTitle(generatedTitle);
260 logger.debug("Generated session title:", generatedTitle);
261 }
262 } catch (error) {
263 // Don't fail the response if title generation fails
264 logger.debug("Session title generation failed:", error);
265 }
266}
267
268interface ProcessMessageOptions {
269 userInput: string;
270 chatHistory: ChatHistoryItem[];
271 model: ModelConfig;
272 llmApi: any;
273 isHeadless: boolean;
274 format?: "json";
275 silent?: boolean;
276 compactionIndex?: number | null;
277 firstAssistantResponse?: boolean;
278}
279
280async function processMessage(
281 options: ProcessMessageOptions,
282): Promise<{ compactionIndex?: number | null } | void> {
283 const {
284 userInput,
285 chatHistory,
286 model,
287 llmApi,
288 isHeadless,
289 format,
290 silent,
291 compactionIndex: initialCompactionIndex,
292 firstAssistantResponse = false,
293 } = options;
294 let compactionIndex = initialCompactionIndex;
295 // Check for slash commands in headless mode
296 if (userInput.trim() === "/compact") {
297 return handleManualCompaction(chatHistory, model, llmApi, isHeadless);
298 }
299
300 // Track user prompt
301 telemetryService.logUserPrompt(userInput.length, userInput);
302
303 // Check if auto-compacting is needed BEFORE adding user message
304 if (shouldAutoCompact(services.chatHistory.getHistory(), model)) {
305 const newIndex = await handleAutoCompaction(
306 chatHistory,
307 model,
308 llmApi,
309 isHeadless,
310 format,
311 );
312 if (newIndex !== null) {
313 compactionIndex = newIndex;
314 // Service already updated in handleAutoCompaction via setHistory
315 }
316 }
317
318 // Add user message to history AFTER potential compaction
319 services.chatHistory.addUserMessage(userInput);
320
321 // Get AI response with potential tool usage
322 if (!isHeadless) {
323 console.info(`\n${chalk.bold.blue("Assistant:")}`);
324 }
325
326 try {
327 const abortController = new AbortController();
328
329 // Service-driven streaming; history updates occur via ChatHistoryService
330 let finalResponse;
331 if (compactionIndex !== null && compactionIndex !== undefined) {
332 // Use service to compute history for LLM
333 const historyForLLM =
334 services.chatHistory.getHistoryForLLM(compactionIndex);
335
336 finalResponse = await streamChatResponse(
337 historyForLLM,
338 model,
339 llmApi,
340 abortController,
341 );
342 } else {
343 // No compaction - get full history from service
344 finalResponse = await streamChatResponse(
345 services.chatHistory.getHistory(),
346 model,
347 llmApi,
348 abortController,
349 );
350 }
351
352 // Generate session title after first assistant response
353 if (firstAssistantResponse && finalResponse && finalResponse.trim()) {
354 await handleTitleGeneration(finalResponse, llmApi, model);
355 }
356
357 // In headless mode, only print the final response using safe stdout
358 if (isHeadless && finalResponse && finalResponse.trim()) {
359 let processedResponse = finalResponse;
360
361 // Strip think tags if --silent flag is enabled
362 if (silent) {
363 processedResponse = stripThinkTags(processedResponse);
364 }
365
366 // Process output based on format
367 const outputResponse =
368 format === "json"
369 ? processJsonOutput(processedResponse)
370 : processedResponse;
371
372 safeStdout(outputResponse + "\n");
373 }
374
375 // Save session after each successful response
376 updateSessionHistory(services.chatHistory.getHistory());
377 } catch (e: any) {
378 const error = e instanceof Error ? e : new Error(String(e));
379
380 if (model.provider === "anthropic") {
381 logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`);
382 } else {
383 logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`);
384 }
385
386 sentryService.captureException(error, {
387 context: "chat_response",
388 isHeadless,
389 chatHistoryLength: services.chatHistory.getHistory().length,
390 });
391 if (!isHeadless) {
392 logger.info(
393 chalk.dim(
394 `Chat history:\n${JSON.stringify(
395 services.chatHistory.getHistory(),
396 null,
397 2,
398 )}`,
399 ),
400 );
401 }
402 }
403}
404
405async function runHeadlessMode(
406 prompt: string | undefined,
407 options: ChatOptions,
408): Promise<void> {
409 // Initialize services for headless mode
410 const { permissionOverrides } = processCommandFlags(options);
411
412 await initializeServices({
413 options,
414 headless: true,
415 toolPermissionOverrides: permissionOverrides,
416 });
417
418 // Get required services from the service container
419 const modelState = await serviceContainer.get<ModelServiceState>(
420 SERVICE_NAMES.MODEL,
421 );
422 const { llmApi, model } = modelState;
423
424 if (!model) {
425 throw new Error("No models were found.");
426 }
427
428 // Initialize service-driven history (resume if requested)
429 const chatHistory = await initializeChatHistory(options);
430 let compactionIndex: number | null = null;
431 if (options.resume || options.fork) {
432 services.chatHistory.setHistory(chatHistory);
433 compactionIndex = findCompactionIndex(chatHistory);
434 }
435
436 // Handle additional prompts from --prompt flags
437 const { processAndCombinePrompts } = await import(
438 "../util/promptProcessor.js"
439 );
440 const initialUserInput = await processAndCombinePrompts(
441 options.prompt,
442 prompt,
443 );
444
445 let isFirstMessage = true;
446 while (true) {
447 // When in headless mode, don't ask for user input
448 if (!isFirstMessage && initialUserInput && options.headless) {
449 break;
450 }
451
452 // Get user input
453 const userInput =
454 isFirstMessage && initialUserInput
455 ? initialUserInput
456 : readlineSync.question(`\n${chalk.bold.green("You:")} `);
457
458 isFirstMessage = false;
459
460 const result = await processMessage({
461 userInput,
462 chatHistory,
463 model,
464 llmApi,
465 isHeadless: true,
466 format: options.format,
467 silent: options.silent,
468 compactionIndex,
469 firstAssistantResponse: isFirstMessage && !options.resume, // Only generate title for new conversations
470 });
471
472 // Update compaction index if compaction occurred
473 if (result && result.compactionIndex !== undefined) {
474 compactionIndex = result.compactionIndex;
475 }
476 }
477}
478
479export async function chat(prompt?: string, options: ChatOptions = {}) {
480 // Configure logger based on headless mode
481 configureLogger(options.headless ?? false);
482
483 // Configure headless-aware logging system
484 logging.configureLogger({ headless: options.headless ?? false });
485
486 try {
487 // Record session start
488 telemetryService.recordSessionStart();
489 await posthogService.capture("sessionStart", {});
490
491 // Start active time tracking
492 telemetryService.startActiveTime();
493
494 // If not in headless mode, use unified initialization with TUI
495 if (!options.headless) {
496 // Process flags for TUI mode
497 const { permissionOverrides } = processCommandFlags(options);
498
499 // Initialize services with onboarding handled internally
500 const initResult = await initializeServices({
501 options,
502 headless: false,
503 toolPermissionOverrides: permissionOverrides,
504 });
505
506 // If onboarding was completed, show success message
507 if (initResult.wasOnboarded) {
508 console.log(chalk.green("✓ Setup complete! Starting chat..."));
509 }
510
511 // Start TUI with skipOnboarding since we already handled it
512 const tuiOptions: any = {
513 initialPrompt: prompt,
514 resume: options.resume,
515 fork: options.fork,
516 config: options.config,
517 org: options.org,
518 rule: options.rule,
519 prompt: options.prompt,
520 toolPermissionOverrides: permissionOverrides,
521 skipOnboarding: true,
522 };
523
524 // If we detected piped input, create a custom stdin for TUI
525 if ((options as any).hasPipedInput) {
526 const fs = await import("fs");
527 const { ReadStream } = await import("tty");
528 const ttyFd = fs.openSync("/dev/tty", "r");
529 const customStdin = new ReadStream(ttyFd);
530 tuiOptions.customStdin = customStdin;
531 logger.debug("Created custom TTY stdin for TUI mode");
532 }
533
534 await startTUIChat(tuiOptions);
535 return;
536 }
537
538 // Run headless mode
539 await runHeadlessMode(prompt, options);
540 } catch (error: any) {
541 const err = error instanceof Error ? error : new Error(String(error));
542 // Use headless-aware error logging to ensure fatal errors are shown in headless mode
543 logging.error(chalk.red(`Fatal error: ${formatError(err)}`));
544 sentryService.captureException(err, {
545 context: "chat_command_fatal",
546 headless: options.headless,
547 });
548 process.exit(1);
549 } finally {
550 // Stop active time tracking
551 telemetryService.stopActiveTime();
552 }
553}