Elffuss BraidHub

kikocis/continue public

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