Elffuss BraidHub

kikocis/continue public

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