From fa00a2f0eae87e678b231b0754f378dd404aff02 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 19:02:22 -0700 Subject: [PATCH] make it a commander CLI --- package-lock.json | 14 +++- package.json | 1 + src/commands/chat.ts | 146 +++++++++++++++++++++++++++++++++++ src/commands/login.ts | 14 ++++ src/commands/logout.ts | 5 ++ src/index.ts | 170 +++++++++-------------------------------- src/version.ts | 16 ++++ 7 files changed, 228 insertions(+), 138 deletions(-) create mode 100644 src/commands/chat.ts create mode 100644 src/commands/login.ts create mode 100644 src/commands/logout.ts create mode 100644 src/version.ts diff --git a/package-lock.json b/package-lock.json index 8ba587817..94c93ead0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/cli", - "version": "1.3.0", + "version": "1.3.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/cli", - "version": "1.3.0", + "version": "1.3.1", "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "^1.0.96", @@ -18,6 +18,7 @@ "@workos-inc/node": "^7.45.0", "axios": "^1.8.4", "chalk": "^5.4.1", + "commander": "^14.0.0", "diff": "^7.0.0", "dotenv": "^16.5.0", "glob": "^11.0.3", @@ -5420,6 +5421,15 @@ "node": ">= 0.8" } }, + "node_modules/commander": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.0.tgz", + "integrity": "sha512-2uM9rYjPvyq39NwLRqaiLtWHyDC1FvryJDa2ATTVims5YAS4PupsEQsDvP14FqhFr0P49CYDugi59xaxJlTXRA==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, "node_modules/compare-func": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/compare-func/-/compare-func-2.0.0.tgz", diff --git a/package.json b/package.json index 1742aa09e..9a70565a8 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "@workos-inc/node": "^7.45.0", "axios": "^1.8.4", "chalk": "^5.4.1", + "commander": "^14.0.0", "diff": "^7.0.0", "dotenv": "^16.5.0", "glob": "^11.0.3", diff --git a/src/commands/chat.ts b/src/commands/chat.ts new file mode 100644 index 000000000..8dc6b7171 --- /dev/null +++ b/src/commands/chat.ts @@ -0,0 +1,146 @@ +import chalk from "chalk"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import * as readlineSync from "readline-sync"; +import { initializeAssistant } from "../assistant.js"; +import { ensureAuthenticated } from "../auth/ensureAuth.js"; +import { ensureOrganization, loadAuthConfig } from "../auth/workos.js"; +import { introMessage } from "../intro.js"; +import { configureLogger } from "../logger.js"; +import { loadSession, saveSession } from "../session.js"; +import { streamChatResponse } from "../streamChatResponse.js"; +import { constructSystemMessage } from "../systemMessage.js"; +import { startTUIChat } from "../ui/index.js"; + +export interface ChatOptions { + headless?: boolean; + config?: string; + resume?: boolean; +} + +async function initializeChat(options: ChatOptions) { + const isAuthenticated = await ensureAuthenticated(true); + + if (!isAuthenticated) { + console.error(chalk.red("Authentication failed. Exiting...")); + process.exit(1); + } + + const authConfig = loadAuthConfig(); + + // Ensure organization is selected + const authConfigWithOrg = await ensureOrganization( + authConfig, + options.headless ?? false + ); + + // Initialize ContinueSDK and MCPService once + const { config, llmApi, model, mcpService } = await initializeAssistant( + authConfigWithOrg, + options.config + ); + + return { config, llmApi, model, mcpService }; +} + +export async function chat(prompt?: string, options: ChatOptions = {}) { + // Configure logger based on headless mode + configureLogger(options.headless ?? false); + + try { + let { config, llmApi, model, mcpService } = await initializeChat(options); + + // If not in headless mode, start the TUI chat (default) + if (!options.headless) { + await startTUIChat( + config, + llmApi, + model, + mcpService, + prompt, + options.resume, + options.config + ); + return; + } + + // Show intro message for headless mode + introMessage(config, model, mcpService); + + // Rules + let chatHistory: ChatCompletionMessageParam[] = []; + + // Load previous session if --resume flag is used + if (options.resume) { + const savedHistory = loadSession(); + if (savedHistory) { + chatHistory = savedHistory; + console.log(chalk.yellow("Resuming previous session...")); + } else { + console.log( + chalk.yellow("No previous session found, starting fresh...") + ); + } + } + + // If no session loaded or not resuming, initialize with system message + if (chatHistory.length === 0) { + const rulesSystemMessage = ""; // TODO //assistant.systemMessage; + const systemMessage = constructSystemMessage(rulesSystemMessage); + if (systemMessage) { + chatHistory.push({ role: "system", content: systemMessage }); + } + } + + let isFirstMessage = true; + while (true) { + // When in headless mode, don't ask for user input + if (!isFirstMessage && prompt && options.headless) { + break; + } + + // Get user input + let userInput = + isFirstMessage && prompt + ? prompt + : readlineSync.question(`\n${chalk.bold.green("You:")} `); + + isFirstMessage = false; + + // Add user message to history + chatHistory.push({ role: "user", content: userInput }); + + // Get AI response with potential tool usage + if (!options.headless) { + console.info(`\n${chalk.bold.blue("Assistant:")}`); + } + + try { + const abortController = new AbortController(); + const finalResponse = await streamChatResponse( + chatHistory, + model, + llmApi, + abortController + ); + + // In headless mode, only print the final response + if (options.headless && finalResponse.trim()) { + console.log(finalResponse); + } + + // Save session after each successful response + saveSession(chatHistory); + } catch (e: any) { + console.error(`\n${chalk.red(`Error: ${e.message}`)}`); + if (!options.headless) { + console.info( + chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`) + ); + } + } + } + } catch (error: any) { + console.error(chalk.red(`Fatal error: ${error.message}`)); + process.exit(1); + } +} diff --git a/src/commands/login.ts b/src/commands/login.ts new file mode 100644 index 000000000..d7d96a827 --- /dev/null +++ b/src/commands/login.ts @@ -0,0 +1,14 @@ +import chalk from "chalk"; +import { login as workosLogin } from "../auth/workos.js"; + +export async function login() { + console.info(chalk.yellow("Logging in to Continue...")); + + try { + await workosLogin(); + console.info(chalk.green("Successfully logged in!")); + } catch (error: any) { + console.error(chalk.red(`Login failed: ${error.message}`)); + process.exit(1); + } +} diff --git a/src/commands/logout.ts b/src/commands/logout.ts new file mode 100644 index 000000000..bd520191a --- /dev/null +++ b/src/commands/logout.ts @@ -0,0 +1,5 @@ +import { logout as workosLogout } from "../auth/workos.js"; + +export async function logout() { + workosLogout(); +} diff --git a/src/index.ts b/src/index.ts index b6c3c4060..85a7fc66a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,144 +1,42 @@ #!/usr/bin/env node -import chalk from "chalk"; -import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import * as readlineSync from "readline-sync"; -import { parseArgs } from "./args.js"; -import { initializeAssistant } from "./assistant.js"; -import { ensureAuthenticated } from "./auth/ensureAuth.js"; -import { ensureOrganization, loadAuthConfig } from "./auth/workos.js"; -import { introMessage } from "./intro.js"; -import { configureLogger } from "./logger.js"; -import { loadSession, saveSession } from "./session.js"; -import { streamChatResponse } from "./streamChatResponse.js"; -import { constructSystemMessage } from "./systemMessage.js"; -import { startTUIChat } from "./ui/index.js"; +import { Command } from "commander"; +import { chat } from "./commands/chat.js"; +import { login } from "./commands/login.js"; +import { logout } from "./commands/logout.js"; +import { getVersion } from "./version.js"; -// Parse command line arguments -const args = parseArgs(); +const program = new Command(); -// Configure logger based on headless mode -configureLogger(args.isHeadless); +program + .name("cn") + .description("Continue CLI - AI-powered development assistant") + .version(getVersion()); -async function initializeChat() { - const isAuthenticated = await ensureAuthenticated(true); +// Root command - chat functionality (default) +program + .argument("[prompt]", "Optional prompt to send to the assistant") + .option("--headless", "Run in headless mode (non-interactive)") + .option("--config ", "Path to configuration file") + .option("--resume", "Resume from last session") + .action(async (prompt, options) => { + await chat(prompt, options); + }); - if (!isAuthenticated) { - console.error(chalk.red("Authentication failed. Exiting...")); - process.exit(1); - } +// Login subcommand +program + .command("login") + .description("Authenticate with Continue") + .action(async () => { + await login(); + }); - const authConfig = loadAuthConfig(); +// Logout subcommand +program + .command("logout") + .description("Log out from Continue") + .action(async () => { + await logout(); + }); - // Ensure organization is selected - const authConfigWithOrg = await ensureOrganization( - authConfig, - args.isHeadless - ); - - // Initialize ContinueSDK and MCPService once - const { config, llmApi, model, mcpService } = await initializeAssistant( - authConfigWithOrg, - args.configPath - ); - - return { config, llmApi, model, mcpService }; -} - -async function chat() { - let { config, llmApi, model, mcpService } = await initializeChat(); - - // If not in headless mode, start the TUI chat (default) - if (!args.isHeadless) { - await startTUIChat( - config, - llmApi, - model, - mcpService, - args.prompt, - args.resume, - args.configPath - ); - return; - } - - // Show intro message for headless mode - introMessage(config, model, mcpService); - - // Rules - let chatHistory: ChatCompletionMessageParam[] = []; - - // Load previous session if --resume flag is used - if (args.resume) { - const savedHistory = loadSession(); - if (savedHistory) { - chatHistory = savedHistory; - console.log(chalk.yellow("Resuming previous session...")); - } else { - console.log(chalk.yellow("No previous session found, starting fresh...")); - } - } - - // If no session loaded or not resuming, initialize with system message - if (chatHistory.length === 0) { - const rulesSystemMessage = ""; // TODO //assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage); - if (systemMessage) { - chatHistory.push({ role: "system", content: systemMessage }); - } - } - - let isFirstMessage = true; - while (true) { - // When in headless mode, don't ask for user input - if (!isFirstMessage && args.prompt && args.isHeadless) { - break; - } - - // Get user input - let userInput = - isFirstMessage && args.prompt - ? args.prompt - : readlineSync.question(`\n${chalk.bold.green("You:")} `); - - isFirstMessage = false; - - - // Add user message to history - chatHistory.push({ role: "user", content: userInput }); - - // Get AI response with potential tool usage - if (!args.isHeadless) { - console.info(`\n${chalk.bold.blue("Assistant:")}`); - } - - try { - const abortController = new AbortController(); - const finalResponse = await streamChatResponse( - chatHistory, - model, - llmApi, - abortController - ); - - // In headless mode, only print the final response - if (args.isHeadless && finalResponse.trim()) { - console.log(finalResponse); - } - - // Save session after each successful response - saveSession(chatHistory); - } catch (e: any) { - console.error(`\n${chalk.red(`Error: ${e.message}`)}`); - if (!args.isHeadless) { - console.info( - chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`) - ); - } - } - } -} - -chat().catch((error) => - console.error(chalk.red(`Fatal error: ${error.message}`)) -); +program.parse(); diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 000000000..8d2b4b98b --- /dev/null +++ b/src/version.ts @@ -0,0 +1,16 @@ +import { readFileSync } from "fs"; +import { dirname, join } from "path"; +import { fileURLToPath } from "url"; + +export function getVersion(): string { + try { + const __filename = fileURLToPath(import.meta.url); + const __dirname = dirname(__filename); + const packageJsonPath = join(__dirname, "../package.json"); + const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")); + return packageJson.version; + } catch (error) { + console.warn("Warning: Could not read version from package.json"); + return "unknown"; + } +}