Elffuss BraidHub

kikocis/continue public

5716809d136b · 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
221program
222 .command("remote [prompt]", { hidden: true })
223 .description("Launch a remote instance of the cn agent")
224 .option(
225 "--url <url>",
226 "Connect directly to the specified URL instead of creating a new remote environment",
227 )
228 .option(
229 "--idempotency-key <key>",
230 "Idempotency key for session management - allows resuming existing sessions",
231 )
232 .option(
233 "-s, --start",
234 "Create remote environment and print connection details without starting TUI",
235 )
236 .option(
237 "--branch <branch>",
238 "Specify the git branch name to use in the remote environment",
239 )
240 .option(
241 "--repo <url>",
242 "Specify the repository URL to use in the remote environment",
243 )
244 .action(async (prompt: string | undefined, options) => {
245 await remote(prompt, options);
246 });
247
248// Serve subcommand
249program
250 .command("serve [prompt]", { hidden: true })
251 .description("Start an HTTP server with /state and /message endpoints")
252 .option(
253 "--timeout <seconds>",
254 "Inactivity timeout in seconds (default: 300)",
255 "300",
256 )
257 .option("--port <port>", "Port to run the server on (default: 8000)", "8000")
258 .action(async (prompt, options) => {
259 // Merge parent options with subcommand options
260 const mergedOptions = mergeParentOptions(program, options);
261
262 if (mergedOptions.verbose) {
263 logger.setLevel("debug");
264 logger.debug("Verbose logging enabled");
265 }
266
267 await serve(prompt, mergedOptions);
268 });
269
270// Remote test subcommand (for development)
271program
272 .command("remote-test [prompt]")
273 .description("Test remote TUI mode with a local server")
274 .option("--url <url>", "Server URL (default: http://localhost:8000)")
275 .action(async (prompt: string | undefined, options) => {
276 await remoteTest(prompt, options.url);
277 });
278
279// Handle unknown commands
280program.on("command:*", () => {
281 console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
282 program.outputHelp();
283 process.exit(1);
284});
285
286// Parse arguments and handle errors
287try {
288 program.parse();
289} catch (error) {
290 console.error(error);
291 sentryService.captureException(
292 error instanceof Error ? error : new Error(String(error)),
293 );
294 process.exit(1);
295}
296
297// Graceful shutdown with two-stage Ctrl+C exit
298
299// Remove all existing SIGINT listeners first
300process.removeAllListeners("SIGINT");
301
302process.on("SIGINT", async () => {
303 const now = Date.now();
304 const timeSinceLastCtrlC = now - lastCtrlCTime;
305
306 if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) {
307 // Second Ctrl+C within 1 second - exit
308 showExitMessage = false;
309 if (tuiUnmount) {
310 tuiUnmount();
311 }
312 await sentryService.flush();
313 process.exit(0);
314 } else {
315 // First Ctrl+C or too much time elapsed - show exit message
316 lastCtrlCTime = now;
317 showExitMessage = true;
318 if (exitMessageCallback) {
319 exitMessageCallback();
320 }
321
322 // Hide message after 1 second
323 setTimeout(() => {
324 showExitMessage = false;
325 if (exitMessageCallback) {
326 exitMessageCallback();
327 }
328 }, 1000);
329 }
330});
331
332process.on("SIGTERM", async () => {
333 await sentryService.flush();
334 process.exit(0);
335});