Files

322 lines
9.4 KiB
JavaScript
Raw Permalink Normal View History

2025-06-10 12:55:25 +08:00
#!/usr/bin/env node
import { run } from "./index";
import { showStatus } from "./utils/status";
import { executeCodeCommand } from "./utils/codeCommand";
2025-08-15 23:50:57 +08:00
import { parseStatusLineData, type StatusLineInput } from "./utils/statusline";
2025-08-04 09:48:15 +08:00
import {
cleanupPidFile,
isServiceRunning,
getServiceInfo,
} from "./utils/processCheck";
2025-06-10 12:55:25 +08:00
import { version } from "../package.json";
2025-07-30 11:15:05 +08:00
import { spawn, exec } from "child_process";
2025-06-17 06:12:59 +08:00
import { PID_FILE, REFERENCE_COUNT_FILE } from "./constants";
2025-07-21 15:34:39 +08:00
import fs, { existsSync, readFileSync } from "fs";
2025-08-04 09:48:15 +08:00
import { join } from "path";
2025-06-10 12:55:25 +08:00
const command = process.argv[2];
const HELP_TEXT = `
2025-06-17 06:12:59 +08:00
Usage: ccr [command]
2025-06-10 12:55:25 +08:00
Commands:
2025-07-21 15:34:39 +08:00
start Start server
stop Stop server
restart Restart server
status Show server status
2025-08-15 23:54:41 +08:00
statusline Integrated statusline
2025-07-21 15:34:39 +08:00
code Execute claude command
2025-07-30 11:15:05 +08:00
ui Open the web UI in browser
2025-06-10 12:55:25 +08:00
-v, version Show version information
-h, help Show help information
Example:
2025-06-17 06:12:59 +08:00
ccr start
ccr code "Write a Hello World"
2025-07-30 11:15:05 +08:00
ccr ui
2025-06-10 12:55:25 +08:00
`;
async function waitForService(
timeout = 10000,
initialDelay = 1000
): Promise<boolean> {
// Wait for an initial period to let the service initialize
await new Promise((resolve) => setTimeout(resolve, initialDelay));
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
if (isServiceRunning()) {
// Wait for an additional short period to ensure service is fully ready
await new Promise((resolve) => setTimeout(resolve, 500));
return true;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
return false;
}
async function main() {
switch (command) {
case "start":
run();
2025-06-10 12:55:25 +08:00
break;
case "stop":
try {
const pid = parseInt(readFileSync(PID_FILE, "utf-8"));
process.kill(pid);
cleanupPidFile();
if (existsSync(REFERENCE_COUNT_FILE)) {
try {
2025-07-21 15:34:39 +08:00
fs.unlinkSync(REFERENCE_COUNT_FILE);
} catch (e) {
// Ignore cleanup errors
}
}
console.log(
"claude code router service has been successfully stopped."
);
} catch (e) {
console.log(
"Failed to stop the service. It may have already been stopped."
);
cleanupPidFile();
}
2025-06-10 12:55:25 +08:00
break;
case "status":
2025-07-20 01:00:33 +08:00
await showStatus();
2025-06-10 12:55:25 +08:00
break;
2025-08-15 23:50:57 +08:00
case "statusline":
// 从stdin读取JSON输入
let inputData = "";
process.stdin.setEncoding("utf-8");
process.stdin.on("readable", () => {
let chunk;
while ((chunk = process.stdin.read()) !== null) {
inputData += chunk;
}
});
process.stdin.on("end", async () => {
try {
const input: StatusLineInput = JSON.parse(inputData);
const statusLine = await parseStatusLineData(input);
console.log(statusLine);
} catch (error) {
console.error("Error parsing status line data:", error);
process.exit(1);
}
});
break;
2025-06-10 12:55:25 +08:00
case "code":
if (!isServiceRunning()) {
console.log("Service not running, starting service...");
const cliPath = join(__dirname, "cli.js");
const startProcess = spawn("node", [cliPath, "start"], {
detached: true,
2025-07-27 16:10:48 +08:00
stdio: "ignore",
});
2025-07-27 16:10:48 +08:00
// let errorMessage = "";
// startProcess.stderr?.on("data", (data) => {
// errorMessage += data.toString();
// });
2025-06-17 06:12:59 +08:00
startProcess.on("error", (error) => {
console.error("Failed to start service:", error.message);
2025-06-17 06:12:59 +08:00
process.exit(1);
});
2025-07-27 16:10:48 +08:00
// startProcess.on("close", (code) => {
// if (code !== 0 && errorMessage) {
// console.error("Failed to start service:", errorMessage.trim());
// process.exit(1);
// }
// });
2025-06-17 06:12:59 +08:00
startProcess.unref();
2025-06-10 12:55:25 +08:00
if (await waitForService()) {
2025-08-04 09:48:15 +08:00
// Join all code arguments into a single string to preserve spaces within quotes
const codeArgs = process.argv.slice(3);
executeCodeCommand(codeArgs);
2025-06-10 12:55:25 +08:00
} else {
console.error(
2025-06-17 06:12:59 +08:00
"Service startup timeout, please manually run `ccr start` to start the service"
2025-06-10 12:55:25 +08:00
);
process.exit(1);
}
} else {
2025-08-04 09:48:15 +08:00
// Join all code arguments into a single string to preserve spaces within quotes
const codeArgs = process.argv.slice(3);
executeCodeCommand(codeArgs);
2025-06-10 12:55:25 +08:00
}
break;
2025-07-30 11:15:05 +08:00
case "ui":
// Check if service is running
if (!isServiceRunning()) {
console.log("Service not running, starting service...");
const cliPath = join(__dirname, "cli.js");
const startProcess = spawn("node", [cliPath, "start"], {
detached: true,
stdio: "ignore",
});
startProcess.on("error", (error) => {
console.error("Failed to start service:", error.message);
process.exit(1);
});
startProcess.unref();
if (!(await waitForService())) {
// If service startup fails, try to start with default config
2025-08-04 09:48:15 +08:00
console.log(
"Service startup timeout, trying to start with default configuration..."
);
const {
initDir,
writeConfigFile,
backupConfigFile,
} = require("./utils");
try {
// Initialize directories
await initDir();
2025-08-04 09:48:15 +08:00
// Backup existing config file if it exists
const backupPath = await backupConfigFile();
if (backupPath) {
2025-08-04 09:48:15 +08:00
console.log(
`Backed up existing configuration file to ${backupPath}`
);
}
2025-08-04 09:48:15 +08:00
// Create a minimal default config file
await writeConfigFile({
2025-08-04 09:48:15 +08:00
PORT: 3456,
Providers: [],
Router: {},
});
2025-08-04 09:48:15 +08:00
console.log(
"Created minimal default configuration file at ~/.claude-code-router/config.json"
);
console.log(
"Please edit this file with your actual configuration."
);
// Try starting the service again
const restartProcess = spawn("node", [cliPath, "start"], {
detached: true,
stdio: "ignore",
});
2025-08-04 09:48:15 +08:00
restartProcess.on("error", (error) => {
2025-08-04 09:48:15 +08:00
console.error(
"Failed to start service with default config:",
error.message
);
process.exit(1);
});
2025-08-04 09:48:15 +08:00
restartProcess.unref();
2025-08-04 09:48:15 +08:00
if (!(await waitForService(15000))) {
// Wait a bit longer for the first start
console.error(
"Service startup still failing. Please manually run `ccr start` to start the service and check the logs."
);
process.exit(1);
}
} catch (error: any) {
2025-08-04 09:48:15 +08:00
console.error(
"Failed to create default configuration:",
error.message
);
process.exit(1);
}
2025-07-30 11:15:05 +08:00
}
}
// Get service info and open UI
const serviceInfo = await getServiceInfo();
2025-08-12 21:41:42 +08:00
// Add temporary API key as URL parameter if successfully generated
2025-08-12 21:41:42 +08:00
const uiUrl = `${serviceInfo.endpoint}/ui/`;
2025-07-30 11:15:05 +08:00
console.log(`Opening UI at ${uiUrl}`);
2025-08-04 09:48:15 +08:00
2025-07-30 11:15:05 +08:00
// Open URL in browser based on platform
const platform = process.platform;
let openCommand = "";
2025-08-04 09:48:15 +08:00
2025-07-30 11:15:05 +08:00
if (platform === "win32") {
// Windows
openCommand = `start ${uiUrl}`;
} else if (platform === "darwin") {
// macOS
openCommand = `open ${uiUrl}`;
} else if (platform === "linux") {
// Linux
openCommand = `xdg-open ${uiUrl}`;
} else {
console.error("Unsupported platform for opening browser");
process.exit(1);
}
2025-08-04 09:48:15 +08:00
2025-07-30 11:15:05 +08:00
exec(openCommand, (error) => {
if (error) {
console.error("Failed to open browser:", error.message);
process.exit(1);
}
});
break;
2025-06-10 12:55:25 +08:00
case "-v":
case "version":
2025-06-17 06:12:59 +08:00
console.log(`claude-code-router version: ${version}`);
2025-06-10 12:55:25 +08:00
break;
2025-07-25 14:27:34 +08:00
case "restart":
// Stop the service if it's running
try {
const pid = parseInt(readFileSync(PID_FILE, "utf-8"));
process.kill(pid);
cleanupPidFile();
if (existsSync(REFERENCE_COUNT_FILE)) {
try {
fs.unlinkSync(REFERENCE_COUNT_FILE);
} catch (e) {
// Ignore cleanup errors
}
}
console.log("claude code router service has been stopped.");
} catch (e) {
console.log("Service was not running or failed to stop.");
cleanupPidFile();
}
// Start the service again in the background
console.log("Starting claude code router service...");
const cliPath = join(__dirname, "cli.js");
const startProcess = spawn("node", [cliPath, "start"], {
detached: true,
stdio: "ignore",
});
startProcess.on("error", (error) => {
console.error("Failed to start service:", error);
process.exit(1);
});
startProcess.unref();
console.log("✅ Service started successfully in the background.");
break;
2025-06-10 12:55:25 +08:00
case "-h":
case "help":
console.log(HELP_TEXT);
break;
default:
console.log(HELP_TEXT);
process.exit(1);
}
}
main().catch(console.error);