Elffuss BraidHub

kikocis/continue public

88b8936f200c · 8.0 KiBRawPermalink
1#!/usr/bin/env node
2
3import { Command } from "commander";
4
5import { chat } from "./commands/chat.js";
6import { login } from "./commands/login.js";
7import { logout } from "./commands/logout.js";
8import { listSessionsCommand } from "./commands/ls.js";
9import { remoteTest } from "./commands/remote-test.js";
10import { remote } from "./commands/remote.js";
11import { serve } from "./commands/serve.js";
12import {
13 validateFlags,
14 handleValidationErrors,
15} from "./flags/flagValidator.js";
16import { sentryService } from "./sentry.js";
17import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
18import { configureConsoleForHeadless } from "./util/consoleOverride.js";
19import { logger } from "./util/logger.js";
20import { readStdinSync } from "./util/stdin.js";
21import { getVersion } from "./version.js";
22
23// Add global error handlers to prevent uncaught errors from crashing the process
24process.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
35process.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
41const program = new Command();
42
43program
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
52addCommonOptions(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
159program
160 .command("login")
161 .description("Authenticate with Continue")
162 .action(async () => {
163 await login();
164 });
165
166// Logout subcommand
167program
168 .command("logout")
169 .description("Log out from Continue")
170 .action(async () => {
171 await logout();
172 });
173
174// List sessions subcommand
175program
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
186program
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 .option(
206 "--repo <url>",
207 "Specify the repository URL to use in the remote environment",
208 )
209 .action(async (prompt: string | undefined, options) => {
210 await remote(prompt, options);
211 });
212
213// Serve subcommand
214program
215 .command("serve [prompt]")
216 .description("Start an HTTP server with /state and /message endpoints")
217 .option(
218 "--timeout <seconds>",
219 "Inactivity timeout in seconds (default: 300)",
220 "300",
221 )
222 .option("--port <port>", "Port to run the server on (default: 8000)", "8000")
223 .action(async (prompt, options) => {
224 // Merge parent options with subcommand options
225 const mergedOptions = mergeParentOptions(program, options);
226
227 if (mergedOptions.verbose) {
228 logger.setLevel("debug");
229 logger.debug("Verbose logging enabled");
230 }
231
232 await serve(prompt, mergedOptions);
233 });
234
235// Remote test subcommand (for development)
236program
237 .command("remote-test [prompt]")
238 .description("Test remote TUI mode with a local server")
239 .option("--url <url>", "Server URL (default: http://localhost:8000)")
240 .action(async (prompt: string | undefined, options) => {
241 await remoteTest(prompt, options.url);
242 });
243
244// Handle unknown commands
245program.on("command:*", () => {
246 console.error(`Error: Unknown command '${program.args.join(" ")}'\n`);
247 program.outputHelp();
248 process.exit(1);
249});
250
251// Parse arguments and handle errors
252try {
253 program.parse();
254} catch (error) {
255 console.error(error);
256 sentryService.captureException(
257 error instanceof Error ? error : new Error(String(error)),
258 );
259 process.exit(1);
260}
261
262// Graceful shutdown - flush Sentry data
263process.on("SIGINT", async () => {
264 await sentryService.flush();
265 process.exit(0);
266});
267
268process.on("SIGTERM", async () => {
269 await sentryService.flush();
270 process.exit(0);
271});