Elffuss BraidHub

kikocis/continue public

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