Elffuss BraidHub

kikocis/continue public

a17b76b80f64 · 9.9 KiBRawPermalink
1#!/usr/bin/env node
2
3// MUST be the first import - intercepts console/stdout/stderr before any dependencies load
4import "./init.js";
5
6import { Command } from "commander";
7
8import { chat } from "./commands/chat.js";
9import { login } from "./commands/login.js";
10import { logout } from "./commands/logout.js";
11import { listSessionsCommand } from "./commands/ls.js";
12import { remoteTest } from "./commands/remote-test.js";
13import { remote } from "./commands/remote.js";
14import { serve } from "./commands/serve.js";
15import {
16 handleValidationErrors,
17 validateFlags,
18} from "./flags/flagValidator.js";
19import { configureConsoleForHeadless, safeStderr } from "./init.js";
20import { sentryService } from "./sentry.js";
21import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
22import { logger } from "./util/logger.js";
23import { readStdinSync } from "./util/stdin.js";
24import { getVersion } from "./version.js";
25
26// TUI lifecycle and two-stage exit state management
27let tuiUnmount: (() => void) | null;
28let showExitMessage: boolean;
29let exitMessageCallback: (() => void) | null;
30let lastCtrlCTime: number;
31
32// Initialize state immediately to avoid temporal dead zone issues with exported functions
33(function initializeTUIState() {
34 tuiUnmount = null;
35 showExitMessage = false;
36 exitMessageCallback = null;
37 lastCtrlCTime = 0;
38})();
39
40// Register TUI cleanup function for graceful shutdown
41export function setTUIUnmount(unmount: () => void) {
42 tuiUnmount = unmount;
43}
44
45// Register callback to trigger UI updates when exit message state changes
46export function setExitMessageCallback(callback: () => void) {
47 exitMessageCallback = callback;
48}
49
50// Sets up SIGINT handler that requires double Ctrl+C within 1 second to exit
51export function enableSigintHandler() {
52 // Remove all existing SIGINT listeners first
53 process.removeAllListeners("SIGINT");
54
55 process.on("SIGINT", async () => {
56 const now = Date.now();
57 const timeSinceLastCtrlC = now - lastCtrlCTime;
58
59 if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) {
60 // Second Ctrl+C within 1 second - exit
61 showExitMessage = false;
62 if (tuiUnmount) {
63 tuiUnmount();
64 }
65 await sentryService.flush();
66 process.exit(0);
67 } else {
68 // First Ctrl+C or too much time elapsed - show exit message
69 lastCtrlCTime = now;
70 showExitMessage = true;
71 if (exitMessageCallback) {
72 exitMessageCallback();
73 }
74
75 // Hide message after 1 second
76 setTimeout(() => {
77 showExitMessage = false;
78 if (exitMessageCallback) {
79 exitMessageCallback();
80 }
81 }, 1000);
82 }
83 });
84}
85
86// Check if "ctrl+c to exit" message should be displayed
87export function shouldShowExitMessage(): boolean {
88 return showExitMessage;
89}
90
91// Add global error handlers to prevent uncaught errors from crashing the process
92process.on("unhandledRejection", (reason, promise) => {
93 logger.error("Unhandled Rejection at:", { promise, reason });
94 sentryService.captureException(
95 reason instanceof Error ? reason : new Error(String(reason)),
96 {
97 promise: String(promise),
98 },
99 );
100 // Don't exit the process, just log the error
101});
102
103process.on("uncaughtException", (error) => {
104 logger.error("Uncaught Exception:", error);
105 sentryService.captureException(error);
106 // Don't exit the process, just log the error
107});
108
109const program = new Command();
110
111program
112 .name("cn")
113 .description(
114 "Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.",
115 )
116 .version(getVersion());
117
118// Root command - chat functionality (default)
119// Add common options to the root command
120addCommonOptions(program)
121 .argument("[prompt]", "Optional prompt to send to the assistant")
122 .option("-p, --print", "Print response and exit (useful for pipes)")
123 .option(
124 "--format <format>",
125 "Output format for headless mode (json). Only works with -p/--print flag.",
126 )
127 .option(
128 "--silent",
129 "Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.",
130 )
131 .option("--resume", "Resume from last session")
132 .option("--fork <sessionId>", "Fork from an existing session ID")
133 .action(async (prompt, options) => {
134 // Handle piped input - detect it early and decide on mode
135 let stdinInput = null;
136
137 if (!options.print) {
138 // Check if there's piped input available
139 stdinInput = readStdinSync();
140 if (stdinInput) {
141 // Use piped input as the initial prompt
142 if (prompt) {
143 // Combine stdin and prompt argument
144 prompt = `${stdinInput}\n\n${prompt}`;
145 } else {
146 // Only stdin input, use as initial prompt
147 prompt = stdinInput;
148 }
149
150 // We have piped input but want to use TUI mode
151 // Store a flag to pass custom stdin to TUI
152 (options as any).hasPipedInput = true;
153 }
154 }
155
156 // Configure console overrides FIRST, before any other logging
157 const isHeadless = options.print;
158 configureConsoleForHeadless(isHeadless);
159 logger.configureHeadlessMode(isHeadless);
160
161 // Validate all command line flags
162 const validation = validateFlags({
163 print: options.print,
164 format: options.format,
165 silent: options.silent,
166 readonly: options.readonly,
167 auto: options.auto,
168 config: options.config,
169 resume: options.resume,
170 fork: options.fork,
171 allow: options.allow,
172 ask: options.ask,
173 exclude: options.exclude,
174 isRootCommand: true,
175 commandName: "cn",
176 });
177
178 if (!validation.isValid) {
179 handleValidationErrors(validation.errors);
180 }
181
182 if (options.verbose) {
183 logger.setLevel("debug");
184 const logPath = logger.getLogPath();
185 const sessionId = logger.getSessionId();
186 // In headless mode, suppress these verbose logs
187 if (!isHeadless) {
188 console.log(`Verbose logging enabled (session: ${sessionId})`);
189 console.log(`Logs: ${logPath}`);
190 console.log(
191 `Filter this session: grep '\\[${sessionId}\\]' ${logPath}`,
192 );
193 }
194 logger.debug("Verbose logging enabled");
195 }
196
197 // Handle piped input for headless mode (only if we haven't already read it)
198 if (options.print && !stdinInput) {
199 const headlessStdinInput = readStdinSync();
200 if (headlessStdinInput) {
201 if (prompt) {
202 // Combine stdin and prompt argument - stdin comes first in XML block
203 prompt = `<stdin>\n${headlessStdinInput}\n</stdin>\n\n${prompt}`;
204 } else {
205 // Only stdin input, use as-is
206 prompt = headlessStdinInput;
207 }
208 }
209 }
210
211 // In headless mode, ensure we have a prompt
212 if (options.print && !prompt) {
213 safeStderr(
214 "Error: A prompt is required when using the -p/--print flag.\n\n",
215 );
216 safeStderr("Usage examples:\n");
217 safeStderr(' cn -p "please review my current git diff"\n');
218 safeStderr(' echo "hello" | cn -p\n');
219 safeStderr(' cn -p "analyze the code in src/"\n');
220 process.exit(1);
221 }
222
223 // Map --print to headless mode
224 options.headless = options.print;
225 options.print = undefined;
226 await chat(prompt, options);
227 });
228
229// Login subcommand
230program
231 .command("login")
232 .description("Authenticate with Continue")
233 .action(async () => {
234 await login();
235 });
236
237// Logout subcommand
238program
239 .command("logout")
240 .description("Log out from Continue")
241 .action(async () => {
242 await logout();
243 });
244
245// List sessions subcommand
246program
247 .command("ls")
248 .description("List recent chat sessions and select one to resume")
249 .option("--json", "Output in JSON format")
250 .action(async (options) => {
251 await listSessionsCommand({
252 format: options.json ? "json" : undefined,
253 });
254 });
255
256// Remote subcommand
257program
258 .command("remote [prompt]", { hidden: true })
259 .description("Launch a remote instance of the cn agent")
260 .option(
261 "--url <url>",
262 "Connect directly to the specified URL instead of creating a new remote environment",
263 )
264 .option(
265 "--idempotency-key <key>",
266 "Idempotency key for session management - allows resuming existing sessions",
267 )
268 .option(
269 "-s, --start",
270 "Create remote environment and print connection details without starting TUI",
271 )
272 .option(
273 "--branch <branch>",
274 "Specify the git branch name to use in the remote environment",
275 )
276 .option(
277 "--repo <url>",
278 "Specify the repository URL to use in the remote environment",
279 )
280 .action(async (prompt: string | undefined, options) => {
281 await remote(prompt, options);
282 });
283
284// Serve subcommand
285program
286 .command("serve [prompt]", { hidden: true })
287 .description("Start an HTTP server with /state and /message endpoints")
288 .option(
289 "--timeout <seconds>",
290 "Inactivity timeout in seconds (default: 300)",
291 "300",
292 )
293 .option("--port <port>", "Port to run the server on (default: 8000)", "8000")
294 .action(async (prompt, options) => {
295 // Merge parent options with subcommand options
296 const mergedOptions = mergeParentOptions(program, options);
297
298 if (mergedOptions.verbose) {
299 logger.setLevel("debug");
300 logger.debug("Verbose logging enabled");
301 }
302
303 await serve(prompt, mergedOptions);
304 });
305
306// Remote test subcommand (for development)
307program
308 .command("remote-test [prompt]")
309 .description("Test remote TUI mode with a local server")
310 .option("--url <url>", "Server URL (default: http://localhost:8000)")
311 .action(async (prompt: string | undefined, options) => {
312 await remoteTest(prompt, options.url);
313 });
314
315// Handle unknown commands
316program.on("command:*", () => {
317 console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
318 program.outputHelp();
319 process.exit(1);
320});
321
322// Parse arguments and handle errors
323try {
324 program.parse();
325} catch (error) {
326 console.error(error);
327 sentryService.captureException(
328 error instanceof Error ? error : new Error(String(error)),
329 );
330 process.exit(1);
331}
332
333process.on("SIGTERM", async () => {
334 await sentryService.flush();
335 process.exit(0);
336});