make it a commander CLI
This commit is contained in:
parent
c7b02b22a8
commit
fa00a2f0ea
7 changed files with 228 additions and 138 deletions
14
package-lock.json
generated
14
package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
146
src/commands/chat.ts
Normal file
146
src/commands/chat.ts
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
14
src/commands/login.ts
Normal file
14
src/commands/login.ts
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
5
src/commands/logout.ts
Normal file
5
src/commands/logout.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { logout as workosLogout } from "../auth/workos.js";
|
||||
|
||||
export async function logout() {
|
||||
workosLogout();
|
||||
}
|
||||
170
src/index.ts
170
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>", "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();
|
||||
|
|
|
|||
16
src/version.ts
Normal file
16
src/version.ts
Normal file
|
|
@ -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";
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue