| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | // MUST be the first import - intercepts console/stdout/stderr before any dependencies load |
| 4 | import "./init.js"; |
| 5 | |
| 6 | import { Command } from "commander"; |
| 7 | |
| 8 | import { chat } from "./commands/chat.js"; |
| 9 | import { login } from "./commands/login.js"; |
| 10 | import { logout } from "./commands/logout.js"; |
| 11 | import { listSessionsCommand } from "./commands/ls.js"; |
| 12 | import { remoteTest } from "./commands/remote-test.js"; |
| 13 | import { remote } from "./commands/remote.js"; |
| 14 | import { serve } from "./commands/serve.js"; |
| 15 | import { |
| 16 | handleValidationErrors, |
| 17 | validateFlags, |
| 18 | } from "./flags/flagValidator.js"; |
| 19 | import { configureConsoleForHeadless, safeStderr } from "./init.js"; |
| 20 | import { sentryService } from "./sentry.js"; |
| 21 | import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; |
| 22 | import { posthogService } from "./telemetry/posthogService.js"; |
| 23 | import { gracefulExit } from "./util/exit.js"; |
| 24 | import { logger } from "./util/logger.js"; |
| 25 | import { readStdinSync } from "./util/stdin.js"; |
| 26 | import { getVersion } from "./version.js"; |
| 27 | |
| 28 | // TUI lifecycle and two-stage exit state management |
| 29 | let tuiUnmount: (() => void) | null; |
| 30 | let showExitMessage: boolean; |
| 31 | let exitMessageCallback: (() => void) | null; |
| 32 | let 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 |
| 43 | export function setTUIUnmount(unmount: () => void) { |
| 44 | tuiUnmount = unmount; |
| 45 | } |
| 46 | |
| 47 | // Register callback to trigger UI updates when exit message state changes |
| 48 | export function setExitMessageCallback(callback: () => void) { |
| 49 | exitMessageCallback = callback; |
| 50 | } |
| 51 | |
| 52 | // Sets up SIGINT handler that requires double Ctrl+C within 1 second to exit |
| 53 | export 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 |
| 88 | export function shouldShowExitMessage(): boolean { |
| 89 | return showExitMessage; |
| 90 | } |
| 91 | |
| 92 | // Add global error handlers to prevent uncaught errors from crashing the process |
| 93 | process.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 | |
| 104 | process.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 | |
| 110 | // keyboard interruption handler for non-TUI flows |
| 111 | process.on("SIGINT", async () => { |
| 112 | await gracefulExit(130); |
| 113 | }); |
| 114 | |
| 115 | const program = new Command(); |
| 116 | |
| 117 | program |
| 118 | .name("cn") |
| 119 | .description( |
| 120 | "Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.", |
| 121 | ) |
| 122 | .version(getVersion(), "-v, --version", "Display version number"); |
| 123 | |
| 124 | // Root command - chat functionality (default) |
| 125 | // Add common options to the root command |
| 126 | addCommonOptions(program) |
| 127 | .argument("[prompt]", "Optional prompt to send to the assistant") |
| 128 | .option("-p, --print", "Print response and exit (useful for pipes)") |
| 129 | .option( |
| 130 | "--format <format>", |
| 131 | "Output format for headless mode (json). Only works with -p/--print flag.", |
| 132 | ) |
| 133 | .option( |
| 134 | "--silent", |
| 135 | "Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.", |
| 136 | ) |
| 137 | .option("--resume", "Resume from last session") |
| 138 | .option("--fork <sessionId>", "Fork from an existing session ID") |
| 139 | .action(async (prompt, options) => { |
| 140 | // Telemetry: record command invocation |
| 141 | await posthogService.capture("cliCommand", { command: "cn" }); |
| 142 | // Handle piped input - detect it early and decide on mode |
| 143 | let stdinInput = null; |
| 144 | |
| 145 | if (!options.print) { |
| 146 | // Check if there's piped input available |
| 147 | stdinInput = readStdinSync(); |
| 148 | if (stdinInput) { |
| 149 | // Use piped input as the initial prompt |
| 150 | if (prompt) { |
| 151 | // Combine stdin and prompt argument |
| 152 | prompt = `${stdinInput}\n\n${prompt}`; |
| 153 | } else { |
| 154 | // Only stdin input, use as initial prompt |
| 155 | prompt = stdinInput; |
| 156 | } |
| 157 | |
| 158 | // We have piped input but want to use TUI mode |
| 159 | // Store a flag to pass custom stdin to TUI |
| 160 | (options as any).hasPipedInput = true; |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // Configure console overrides FIRST, before any other logging |
| 165 | const isHeadless = options.print; |
| 166 | configureConsoleForHeadless(isHeadless); |
| 167 | logger.configureHeadlessMode(isHeadless); |
| 168 | |
| 169 | // Validate all command line flags |
| 170 | const validation = validateFlags({ |
| 171 | print: options.print, |
| 172 | format: options.format, |
| 173 | silent: options.silent, |
| 174 | readonly: options.readonly, |
| 175 | auto: options.auto, |
| 176 | config: options.config, |
| 177 | resume: options.resume, |
| 178 | fork: options.fork, |
| 179 | allow: options.allow, |
| 180 | ask: options.ask, |
| 181 | exclude: options.exclude, |
| 182 | isRootCommand: true, |
| 183 | commandName: "cn", |
| 184 | }); |
| 185 | |
| 186 | if (!validation.isValid) { |
| 187 | handleValidationErrors(validation.errors); |
| 188 | } |
| 189 | |
| 190 | if (options.verbose) { |
| 191 | logger.setLevel("debug"); |
| 192 | const logPath = logger.getLogPath(); |
| 193 | const sessionId = logger.getSessionId(); |
| 194 | // In headless mode, suppress these verbose logs |
| 195 | if (!isHeadless) { |
| 196 | console.log(`Verbose logging enabled (session: ${sessionId})`); |
| 197 | console.log(`Logs: ${logPath}`); |
| 198 | console.log( |
| 199 | `Filter this session: grep '\\[${sessionId}\\]' ${logPath}`, |
| 200 | ); |
| 201 | } |
| 202 | logger.debug("Verbose logging enabled"); |
| 203 | } |
| 204 | |
| 205 | // Handle piped input for headless mode (only if we haven't already read it) |
| 206 | if (options.print && !stdinInput) { |
| 207 | const headlessStdinInput = readStdinSync(); |
| 208 | if (headlessStdinInput) { |
| 209 | if (prompt) { |
| 210 | // Combine stdin and prompt argument - stdin comes first in XML block |
| 211 | prompt = `<stdin>\n${headlessStdinInput}\n</stdin>\n\n${prompt}`; |
| 212 | } else { |
| 213 | // Only stdin input, use as-is |
| 214 | prompt = headlessStdinInput; |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | // In headless mode, ensure we have a prompt |
| 220 | if (options.print && !prompt) { |
| 221 | safeStderr( |
| 222 | "Error: A prompt is required when using the -p/--print flag.\n\n", |
| 223 | ); |
| 224 | safeStderr("Usage examples:\n"); |
| 225 | safeStderr(' cn -p "please review my current git diff"\n'); |
| 226 | safeStderr(' echo "hello" | cn -p\n'); |
| 227 | safeStderr(' cn -p "analyze the code in src/"\n'); |
| 228 | await gracefulExit(1); |
| 229 | } |
| 230 | |
| 231 | // Map --print to headless mode |
| 232 | options.headless = options.print; |
| 233 | options.print = undefined; |
| 234 | await chat(prompt, options); |
| 235 | }); |
| 236 | |
| 237 | // Login subcommand |
| 238 | program |
| 239 | .command("login") |
| 240 | .description("Authenticate with Continue") |
| 241 | .action(async () => { |
| 242 | // Telemetry: record command invocation |
| 243 | await posthogService.capture("cliCommand", { command: "login" }); |
| 244 | await login(); |
| 245 | }); |
| 246 | |
| 247 | // Logout subcommand |
| 248 | program |
| 249 | .command("logout") |
| 250 | .description("Log out from Continue") |
| 251 | .action(async () => { |
| 252 | // Telemetry: record command invocation |
| 253 | await posthogService.capture("cliCommand", { command: "logout" }); |
| 254 | await logout(); |
| 255 | }); |
| 256 | |
| 257 | // List sessions subcommand |
| 258 | program |
| 259 | .command("ls") |
| 260 | .description("List recent chat sessions and select one to resume") |
| 261 | .option("--json", "Output in JSON format") |
| 262 | .action(async (options) => { |
| 263 | // Telemetry: record command invocation |
| 264 | await posthogService.capture("cliCommand", { command: "ls" }); |
| 265 | await listSessionsCommand({ |
| 266 | format: options.json ? "json" : undefined, |
| 267 | }); |
| 268 | }); |
| 269 | |
| 270 | // Remote subcommand |
| 271 | addCommonOptions( |
| 272 | program |
| 273 | .command("remote [prompt]", { hidden: true }) |
| 274 | .description("Launch a remote instance of the cn agent"), |
| 275 | ) |
| 276 | .option( |
| 277 | "--url <url>", |
| 278 | "Connect directly to the specified URL instead of creating a new remote environment", |
| 279 | ) |
| 280 | .option( |
| 281 | "--id <id>", |
| 282 | "Connect to an existing remote agent by id and establish a tunnel", |
| 283 | ) |
| 284 | .option( |
| 285 | "--idempotency-key <key>", |
| 286 | "Idempotency key for session management - allows resuming existing sessions", |
| 287 | ) |
| 288 | .option( |
| 289 | "-s, --start", |
| 290 | "Create remote environment and print connection details without starting TUI", |
| 291 | ) |
| 292 | .option( |
| 293 | "--branch <branch>", |
| 294 | "Specify the git branch name to use in the remote environment", |
| 295 | ) |
| 296 | .option( |
| 297 | "--repo <url>", |
| 298 | "Specify the repository URL to use in the remote environment", |
| 299 | ) |
| 300 | .action(async (prompt: string | undefined, options) => { |
| 301 | // Telemetry: record command invocation |
| 302 | await posthogService.capture("cliCommand", { |
| 303 | command: "remote", |
| 304 | flagS: options.start, |
| 305 | }); |
| 306 | await remote(prompt, options); |
| 307 | }); |
| 308 | |
| 309 | // Serve subcommand |
| 310 | program |
| 311 | .command("serve [prompt]", { hidden: true }) |
| 312 | .description("Start an HTTP server with /state and /message endpoints") |
| 313 | .option( |
| 314 | "--timeout <seconds>", |
| 315 | "Inactivity timeout in seconds (default: 300)", |
| 316 | "300", |
| 317 | ) |
| 318 | .option("--port <port>", "Port to run the server on (default: 8000)", "8000") |
| 319 | .option( |
| 320 | "--id <storageId>", |
| 321 | "Upload session snapshots to Continue-managed storage using the provided identifier", |
| 322 | ) |
| 323 | .action(async (prompt, options) => { |
| 324 | // Telemetry: record command invocation |
| 325 | await posthogService.capture("cliCommand", { command: "serve" }); |
| 326 | // Merge parent options with subcommand options |
| 327 | const mergedOptions = mergeParentOptions(program, options); |
| 328 | |
| 329 | if (mergedOptions.verbose) { |
| 330 | logger.setLevel("debug"); |
| 331 | logger.debug("Verbose logging enabled"); |
| 332 | } |
| 333 | |
| 334 | await serve(prompt, mergedOptions); |
| 335 | }); |
| 336 | |
| 337 | // Remote test subcommand (for development) |
| 338 | program |
| 339 | .command("remote-test [prompt]") |
| 340 | .description("Test remote TUI mode with a local server") |
| 341 | .option("--url <url>", "Server URL (default: http://localhost:8000)") |
| 342 | .action(async (prompt: string | undefined, options) => { |
| 343 | // Telemetry: record command invocation |
| 344 | await posthogService.capture("cliCommand", { command: "remote-test" }); |
| 345 | await remoteTest(prompt, options.url); |
| 346 | }); |
| 347 | |
| 348 | // Handle unknown commands |
| 349 | program.on("command:*", () => { |
| 350 | console.error(`Error: Unknown command '${program.args.join(" ")}'\n`); |
| 351 | program.outputHelp(); |
| 352 | void gracefulExit(1); |
| 353 | }); |
| 354 | |
| 355 | export async function runCli(): Promise<void> { |
| 356 | // Parse arguments and handle errors |
| 357 | try { |
| 358 | program.parse(); |
| 359 | } catch (error) { |
| 360 | console.error(error); |
| 361 | sentryService.captureException( |
| 362 | error instanceof Error ? error : new Error(String(error)), |
| 363 | ); |
| 364 | process.exit(1); |
| 365 | } |
| 366 | |
| 367 | process.on("SIGTERM", async () => { |
| 368 | await gracefulExit(0); |
| 369 | }); |
| 370 | } |