| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | import { Command } from "commander"; |
| 4 | |
| 5 | import { chat } from "./commands/chat.js"; |
| 6 | import { login } from "./commands/login.js"; |
| 7 | import { logout } from "./commands/logout.js"; |
| 8 | import { listSessionsCommand } from "./commands/ls.js"; |
| 9 | import { remoteTest } from "./commands/remote-test.js"; |
| 10 | import { remote } from "./commands/remote.js"; |
| 11 | import { serve } from "./commands/serve.js"; |
| 12 | import { |
| 13 | validateFlags, |
| 14 | handleValidationErrors, |
| 15 | } from "./flags/flagValidator.js"; |
| 16 | import { sentryService } from "./sentry.js"; |
| 17 | import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; |
| 18 | import { configureConsoleForHeadless } from "./util/consoleOverride.js"; |
| 19 | import { logger } from "./util/logger.js"; |
| 20 | import { readStdinSync } from "./util/stdin.js"; |
| 21 | import { getVersion } from "./version.js"; |
| 22 | |
| 23 | // Add global error handlers to prevent uncaught errors from crashing the process |
| 24 | process.on("unhandledRejection", (reason, promise) => { |
| 25 | logger.error("Unhandled Rejection at:", { promise, reason }); |
| 26 | sentryService.captureException( |
| 27 | reason instanceof Error ? reason : new Error(String(reason)), |
| 28 | { |
| 29 | promise: String(promise), |
| 30 | }, |
| 31 | ); |
| 32 | // Don't exit the process, just log the error |
| 33 | }); |
| 34 | |
| 35 | process.on("uncaughtException", (error) => { |
| 36 | logger.error("Uncaught Exception:", error); |
| 37 | sentryService.captureException(error); |
| 38 | // Don't exit the process, just log the error |
| 39 | }); |
| 40 | |
| 41 | const program = new Command(); |
| 42 | |
| 43 | program |
| 44 | .name("cn") |
| 45 | .description( |
| 46 | "Continue CLI - AI-powered development assistant. Starts an interactive session by default, use -p/--print for non-interactive output.", |
| 47 | ) |
| 48 | .version(getVersion()); |
| 49 | |
| 50 | // Root command - chat functionality (default) |
| 51 | // Add common options to the root command |
| 52 | addCommonOptions(program) |
| 53 | .argument("[prompt]", "Optional prompt to send to the assistant") |
| 54 | .option("-p, --print", "Print response and exit (useful for pipes)") |
| 55 | .option( |
| 56 | "--format <format>", |
| 57 | "Output format for headless mode (json). Only works with -p/--print flag.", |
| 58 | ) |
| 59 | .option( |
| 60 | "--silent", |
| 61 | "Strip <think></think> tags and excess whitespace from output. Only works with -p/--print flag.", |
| 62 | ) |
| 63 | .option("--resume", "Resume from last session") |
| 64 | .action(async (prompt, options) => { |
| 65 | // Handle piped input - detect it early and decide on mode |
| 66 | let stdinInput = null; |
| 67 | |
| 68 | if (!options.print) { |
| 69 | // Check if there's piped input available |
| 70 | stdinInput = readStdinSync(); |
| 71 | if (stdinInput) { |
| 72 | // Use piped input as the initial prompt |
| 73 | if (prompt) { |
| 74 | // Combine stdin and prompt argument |
| 75 | prompt = `${stdinInput}\n\n${prompt}`; |
| 76 | } else { |
| 77 | // Only stdin input, use as initial prompt |
| 78 | prompt = stdinInput; |
| 79 | } |
| 80 | |
| 81 | // We have piped input but want to use TUI mode |
| 82 | // Store a flag to pass custom stdin to TUI |
| 83 | (options as any).hasPipedInput = true; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // Configure console overrides FIRST, before any other logging |
| 88 | const isHeadless = options.print; |
| 89 | configureConsoleForHeadless(isHeadless); |
| 90 | logger.configureHeadlessMode(isHeadless); |
| 91 | |
| 92 | // Validate all command line flags |
| 93 | const validation = validateFlags({ |
| 94 | print: options.print, |
| 95 | format: options.format, |
| 96 | silent: options.silent, |
| 97 | readonly: options.readonly, |
| 98 | auto: options.auto, |
| 99 | config: options.config, |
| 100 | allow: options.allow, |
| 101 | ask: options.ask, |
| 102 | exclude: options.exclude, |
| 103 | isRootCommand: true, |
| 104 | commandName: "cn", |
| 105 | }); |
| 106 | |
| 107 | if (!validation.isValid) { |
| 108 | handleValidationErrors(validation.errors); |
| 109 | } |
| 110 | |
| 111 | if (options.verbose) { |
| 112 | logger.setLevel("debug"); |
| 113 | const logPath = logger.getLogPath(); |
| 114 | const sessionId = logger.getSessionId(); |
| 115 | // In headless mode, suppress these verbose logs |
| 116 | if (!isHeadless) { |
| 117 | console.log(`Verbose logging enabled (session: ${sessionId})`); |
| 118 | console.log(`Logs: ${logPath}`); |
| 119 | console.log( |
| 120 | `Filter this session: grep '\\[${sessionId}\\]' ${logPath}`, |
| 121 | ); |
| 122 | } |
| 123 | logger.debug("Verbose logging enabled"); |
| 124 | } |
| 125 | |
| 126 | // Handle piped input for headless mode (only if we haven't already read it) |
| 127 | if (options.print && !stdinInput) { |
| 128 | const headlessStdinInput = readStdinSync(); |
| 129 | if (headlessStdinInput) { |
| 130 | if (prompt) { |
| 131 | // Combine stdin and prompt argument - stdin comes first in XML block |
| 132 | prompt = `<stdin>\n${headlessStdinInput}\n</stdin>\n\n${prompt}`; |
| 133 | } else { |
| 134 | // Only stdin input, use as-is |
| 135 | prompt = headlessStdinInput; |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // In headless mode, ensure we have a prompt |
| 141 | if (options.print && !prompt) { |
| 142 | console.error( |
| 143 | "Error: A prompt is required when using the -p/--print flag.\n", |
| 144 | ); |
| 145 | console.error("Usage examples:"); |
| 146 | console.error(' cn -p "please review my current git diff"'); |
| 147 | console.error(' echo "hello" | cn -p'); |
| 148 | console.error(' cn -p "analyze the code in src/"'); |
| 149 | process.exit(1); |
| 150 | } |
| 151 | |
| 152 | // Map --print to headless mode |
| 153 | options.headless = options.print; |
| 154 | options.print = undefined; |
| 155 | await chat(prompt, options); |
| 156 | }); |
| 157 | |
| 158 | // Login subcommand |
| 159 | program |
| 160 | .command("login") |
| 161 | .description("Authenticate with Continue") |
| 162 | .action(async () => { |
| 163 | await login(); |
| 164 | }); |
| 165 | |
| 166 | // Logout subcommand |
| 167 | program |
| 168 | .command("logout") |
| 169 | .description("Log out from Continue") |
| 170 | .action(async () => { |
| 171 | await logout(); |
| 172 | }); |
| 173 | |
| 174 | // List sessions subcommand |
| 175 | program |
| 176 | .command("ls") |
| 177 | .description("List recent chat sessions and select one to resume") |
| 178 | .option("--json", "Output in JSON format") |
| 179 | .action(async (options) => { |
| 180 | await listSessionsCommand({ |
| 181 | format: options.json ? "json" : undefined, |
| 182 | }); |
| 183 | }); |
| 184 | |
| 185 | // Remote subcommand |
| 186 | program |
| 187 | .command("remote [prompt]") |
| 188 | .description("Launch a remote instance of the cn agent") |
| 189 | .option( |
| 190 | "--url <url>", |
| 191 | "Connect directly to the specified URL instead of creating a new remote environment", |
| 192 | ) |
| 193 | .option( |
| 194 | "--idempotency-key <key>", |
| 195 | "Idempotency key for session management - allows resuming existing sessions", |
| 196 | ) |
| 197 | .option( |
| 198 | "-s, --start", |
| 199 | "Create remote environment and print connection details without starting TUI", |
| 200 | ) |
| 201 | .option( |
| 202 | "--branch <branch>", |
| 203 | "Specify the git branch name to use in the remote environment", |
| 204 | ) |
| 205 | .action(async (prompt: string | undefined, options) => { |
| 206 | await remote(prompt, options); |
| 207 | }); |
| 208 | |
| 209 | // Serve subcommand |
| 210 | program |
| 211 | .command("serve [prompt]") |
| 212 | .description("Start an HTTP server with /state and /message endpoints") |
| 213 | .option( |
| 214 | "--timeout <seconds>", |
| 215 | "Inactivity timeout in seconds (default: 300)", |
| 216 | "300", |
| 217 | ) |
| 218 | .option("--port <port>", "Port to run the server on (default: 8000)", "8000") |
| 219 | .action(async (prompt, options) => { |
| 220 | // Merge parent options with subcommand options |
| 221 | const mergedOptions = mergeParentOptions(program, options); |
| 222 | |
| 223 | if (mergedOptions.verbose) { |
| 224 | logger.setLevel("debug"); |
| 225 | logger.debug("Verbose logging enabled"); |
| 226 | } |
| 227 | |
| 228 | await serve(prompt, mergedOptions); |
| 229 | }); |
| 230 | |
| 231 | // Remote test subcommand (for development) |
| 232 | program |
| 233 | .command("remote-test [prompt]") |
| 234 | .description("Test remote TUI mode with a local server") |
| 235 | .option("--url <url>", "Server URL (default: http://localhost:8000)") |
| 236 | .action(async (prompt: string | undefined, options) => { |
| 237 | await remoteTest(prompt, options.url); |
| 238 | }); |
| 239 | |
| 240 | // Handle unknown commands |
| 241 | program.on("command:*", () => { |
| 242 | console.error(`Error: Unknown command '${program.args.join(" ")}'\n`); |
| 243 | program.outputHelp(); |
| 244 | process.exit(1); |
| 245 | }); |
| 246 | |
| 247 | // Parse arguments and handle errors |
| 248 | try { |
| 249 | program.parse(); |
| 250 | } catch (error) { |
| 251 | console.error(error); |
| 252 | sentryService.captureException( |
| 253 | error instanceof Error ? error : new Error(String(error)), |
| 254 | ); |
| 255 | process.exit(1); |
| 256 | } |
| 257 | |
| 258 | // Graceful shutdown - flush Sentry data |
| 259 | process.on("SIGINT", async () => { |
| 260 | await sentryService.flush(); |
| 261 | process.exit(0); |
| 262 | }); |
| 263 | |
| 264 | process.on("SIGTERM", async () => { |
| 265 | await sentryService.flush(); |
| 266 | process.exit(0); |
| 267 | }); |