Elffuss BraidHub

kikocis/continue public

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