mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-19 05:32:19 +03:00
feat(cli): relay-like CLI closure — target manifest, Codex TOML, Gemini launcher, guards
- canonical executable manifest (bin/cli/cli-manifest.mjs): run/configure/completion derive targets, aliases and --model wiring from one table; drift test cross-checks manifest x cliRuntime x UI catalog (tests/unit/cli/cli-manifest-drift.test.ts) - dashboard Codex generator converged to ~/.codex/config.toml (modern Codex v0.137+, verified against codex-cli 0.147.0): conservative merge, env_key auth (key never written), refuses invalid TOML, reports legacy config.yaml as migration note - omniroute run gemini: launcher over OmniRoute's /v1beta surface via GOOGLE_GEMINI_BASE_URL + isolated GEMINI_CLI_HOME forcing gemini-api-key auth (contract proven against @google/gemini-cli 0.50.0); ACP registration kept distinct - opt-in real smoke harness for upstream CLIs (RUN_CLI_SMOKE=1, credential by env NAME, redacted output): tests/integration/upstream-cli-smoke.int.test.ts - container-guard homologation for POST /api/cli-tools/apply (422 in container, dry-run preview allowed, host write passes) + docs; guard untouched - typecheck: omniglyphAdapter union narrowing, usageTracking typed signatures (UsageLike, no any), models.ts isValidModel params — typecheck:core and typecheck:noimplicit:core now clean - relay core (prior session of this effort): omniroute run for 6 CLIs, configure picker with per-context favorites/recents, contexts with optional keychain + 0600 fallback, provider CRUD with recursive redaction, completion updates, docs
This commit is contained in:
@@ -3,9 +3,9 @@ import { z } from "zod";
|
||||
import { requireCliToolsAuth } from "@/lib/api/requireCliToolsAuth";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { generateConfig } from "@/lib/cli-helper/config-generator";
|
||||
import { guardCliConfigWrite } from "@/lib/api/cliConfigWriteGuard";
|
||||
import { getCliPrimaryConfigPath, normalizeCliToolId } from "@/shared/services/cliRuntime";
|
||||
|
||||
const applySchema = z.object({
|
||||
toolId: z.string().min(1),
|
||||
@@ -15,21 +15,13 @@ const applySchema = z.object({
|
||||
dryRun: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const TOOL_CONFIG_PATHS: Record<string, string> = {
|
||||
claude: path.join(os.homedir(), ".claude", "settings.json"),
|
||||
codex: path.join(os.homedir(), ".codex", "config.yaml"),
|
||||
cline: path.join(os.homedir(), ".cline", "data", "globalState.json"),
|
||||
kilocode: path.join(os.homedir(), ".config", "kilocode", "settings.json"),
|
||||
continue: path.join(os.homedir(), ".continue", "config.yaml"),
|
||||
};
|
||||
|
||||
/** The host-side command that does the same job when OmniRoute is containerised. */
|
||||
const HOST_SETUP_COMMANDS: Record<string, string> = {
|
||||
claude: "omniroute setup-claude",
|
||||
codex: "omniroute setup-codex",
|
||||
opencode: "omniroute setup-opencode",
|
||||
cline: "omniroute setup-cline",
|
||||
kilocode: "omniroute setup-kilo",
|
||||
kilo: "omniroute setup-kilo",
|
||||
continue: "omniroute setup-continue",
|
||||
};
|
||||
|
||||
@@ -56,8 +48,9 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
const { toolId, baseUrl, apiKey, model, dryRun } = parsed.data;
|
||||
const canonicalToolId = normalizeCliToolId(toolId);
|
||||
|
||||
const result = await generateConfig(toolId, {
|
||||
const result = await generateConfig(canonicalToolId, {
|
||||
baseUrl: baseUrl || "http://localhost:20128/v1",
|
||||
apiKey,
|
||||
model,
|
||||
@@ -72,10 +65,11 @@ export async function POST(request: Request) {
|
||||
dryRun: true,
|
||||
configPath: result.configPath,
|
||||
content: result.content,
|
||||
...(result.migration ? { migration: result.migration } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const configPath = toolId === "opencode" ? result.configPath : TOOL_CONFIG_PATHS[toolId];
|
||||
const configPath = result.configPath || getCliPrimaryConfigPath(canonicalToolId);
|
||||
if (!configPath) {
|
||||
return NextResponse.json({ error: `Unknown tool: ${toolId}` }, { status: 400 });
|
||||
}
|
||||
@@ -83,8 +77,8 @@ export async function POST(request: Request) {
|
||||
// A container write into an unmounted path looks successful and then
|
||||
// disappears with the container — refuse it and point at the host CLI.
|
||||
const refusal = guardCliConfigWrite(configPath, {
|
||||
toolLabel: toolId,
|
||||
hostCommand: HOST_SETUP_COMMANDS[toolId],
|
||||
toolLabel: canonicalToolId,
|
||||
hostCommand: HOST_SETUP_COMMANDS[canonicalToolId],
|
||||
});
|
||||
if (refusal) return refusal;
|
||||
|
||||
@@ -100,6 +94,7 @@ export async function POST(request: Request) {
|
||||
configPath,
|
||||
backupPath,
|
||||
content: result.content,
|
||||
...(result.migration ? { migration: result.migration } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
console.log("Error applying config:", error);
|
||||
|
||||
@@ -4,7 +4,12 @@
|
||||
* Re-exports the registry and manager for convenient imports.
|
||||
*/
|
||||
|
||||
export { detectInstalledAgents, getAgentById, getAvailableAgents } from "./registry";
|
||||
export {
|
||||
detectInstalledAgents,
|
||||
getAgentById,
|
||||
getAvailableAgents,
|
||||
hasRegisteredAgent,
|
||||
} from "./registry";
|
||||
export type { CliAgentInfo } from "./registry";
|
||||
|
||||
export { AcpManager, acpManager } from "./manager";
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
import { spawn, ChildProcess } from "child_process";
|
||||
import { EventEmitter } from "events";
|
||||
import { hasRegisteredAgent } from "./registry";
|
||||
|
||||
export interface AcpSession {
|
||||
/** Unique session ID */
|
||||
@@ -47,11 +48,18 @@ export class AcpManager extends EventEmitter {
|
||||
args: string[] = [],
|
||||
env: Record<string, string> = {}
|
||||
): AcpSession {
|
||||
const ALLOWED_AGENTS = ["claude", "codex", "gemini", "qwen"];
|
||||
if (!ALLOWED_AGENTS.includes(agentId)) {
|
||||
const normalizedAgentId = String(agentId || "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!hasRegisteredAgent(normalizedAgentId)) {
|
||||
throw new Error(`Unknown agent: ${agentId}`);
|
||||
}
|
||||
|
||||
// Keep session ids and telemetry stable when a caller uses a registry
|
||||
// alias/custom spelling. The registry remains the source of truth for
|
||||
// which ACP-capable IDs may be spawned.
|
||||
agentId = normalizedAgentId;
|
||||
|
||||
const sessionId = `acp-${agentId}-${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
|
||||
|
||||
const child = spawn(binary, args, {
|
||||
|
||||
@@ -69,6 +69,15 @@ const AGENT_DEFINITIONS: Omit<CliAgentInfo, "version" | "installed">[] = [
|
||||
spawnArgs: ["--print", "--output-format", "json"],
|
||||
protocol: "stdio",
|
||||
},
|
||||
{
|
||||
id: "gemini",
|
||||
name: "Google Gemini CLI",
|
||||
binary: "gemini",
|
||||
versionCommand: "gemini --version",
|
||||
providerAlias: "gemini",
|
||||
spawnArgs: [],
|
||||
protocol: "stdio",
|
||||
},
|
||||
{
|
||||
id: "goose",
|
||||
name: "Goose CLI",
|
||||
@@ -385,6 +394,24 @@ export function getAgentById(id: string): CliAgentInfo | undefined {
|
||||
return agents.find((a) => a.id === id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check registration without probing every executable on PATH.
|
||||
*
|
||||
* Process lifecycle callers need an allowlist decision, not a fresh health
|
||||
* scan. Keeping this lookup pure avoids making `spawn()` wait on one timeout
|
||||
* per uninstalled agent while preserving detectInstalledAgents() for UI/status
|
||||
* consumers.
|
||||
*/
|
||||
export function hasRegisteredAgent(id: string): boolean {
|
||||
const normalized = String(id || "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return (
|
||||
AGENT_DEFINITIONS.some((agent) => agent.id === normalized) ||
|
||||
_customAgentDefs.some((agent) => agent.id === normalized)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agents that are installed and available for ACP.
|
||||
*/
|
||||
|
||||
@@ -1,34 +1,93 @@
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import { parse, stringify } from "smol-toml";
|
||||
|
||||
let yaml: typeof import("js-yaml") | null = null;
|
||||
async function loadYaml() {
|
||||
if (!yaml) {
|
||||
yaml = await import("js-yaml");
|
||||
}
|
||||
return yaml;
|
||||
/**
|
||||
* Codex CLI config generator — TOML.
|
||||
*
|
||||
* Modern Codex (Rust CLI, v0.137+) reads `~/.codex/config.toml` exclusively;
|
||||
* the YAML `~/.codex/config.yaml` this generator used to emit belongs to the
|
||||
* legacy npm codex-cli and is silently ignored by current binaries. The shape
|
||||
* below matches the documented OmniRoute block
|
||||
* (docs/guides/CODEX-CLI-CONFIGURATION.md → "Ready-to-paste config.toml").
|
||||
*
|
||||
* Two deliberate safety properties:
|
||||
* - The API key is NEVER written into the file. Codex reads it from the env
|
||||
* var named by `env_key` (`OMNIROUTE_API_KEY`), so the generated content is
|
||||
* credential-free and safe to show in dry-run.
|
||||
* - An existing `config.toml` is merged conservatively: every unrelated key
|
||||
* the operator already has is preserved; only `model`, `model_provider` and
|
||||
* `[model_providers.omniroute]` are set. An existing file that fails TOML
|
||||
* parsing aborts generation instead of clobbering the operator's config.
|
||||
*/
|
||||
|
||||
export const CODEX_MODEL_PROVIDER_ID = "omniroute";
|
||||
|
||||
export function getCodexHome(): string {
|
||||
return path.join(os.homedir(), ".codex");
|
||||
}
|
||||
|
||||
const CONFIG_PATH = path.join(os.homedir(), ".codex", "config.yaml");
|
||||
/** Path of the legacy YAML config, when one is left over from old generators. */
|
||||
export function findLegacyCodexYaml(codexHome: string = getCodexHome()): string | null {
|
||||
const legacyPath = path.join(codexHome, "config.yaml");
|
||||
try {
|
||||
return fs.existsSync(legacyPath) ? legacyPath : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateCodexConfig(options: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
/** Override for tests; production callers use ~/.codex/config.toml. */
|
||||
configPath?: string;
|
||||
}): Promise<string> {
|
||||
const y = await loadYaml();
|
||||
let base = options.baseUrl;
|
||||
let end = base.length;
|
||||
while (end > 0 && base[end - 1] === "/") end--;
|
||||
base = end < base.length ? base.slice(0, end) : base;
|
||||
if (base.endsWith("/v1")) base = base.slice(0, -3);
|
||||
|
||||
const config = {
|
||||
openai: {
|
||||
api_key: options.apiKey,
|
||||
base_url: `${base}/v1`,
|
||||
const configPath = options.configPath ?? path.join(getCodexHome(), "config.toml");
|
||||
|
||||
let existing: Record<string, unknown> = {};
|
||||
if (fs.existsSync(configPath)) {
|
||||
const raw = fs.readFileSync(configPath, "utf-8");
|
||||
try {
|
||||
existing = parse(raw) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Existing ${configPath} is not valid TOML; refusing to overwrite it. ` +
|
||||
"Fix or move the file, then retry."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const existingProviders =
|
||||
existing.model_providers && typeof existing.model_providers === "object"
|
||||
? (existing.model_providers as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
const merged: Record<string, unknown> = {
|
||||
...existing,
|
||||
...(options.model ? { model: options.model } : {}),
|
||||
model_provider: CODEX_MODEL_PROVIDER_ID,
|
||||
model_providers: {
|
||||
...existingProviders,
|
||||
[CODEX_MODEL_PROVIDER_ID]: {
|
||||
name: "OmniRoute",
|
||||
base_url: `${base}/v1`,
|
||||
env_key: "OMNIROUTE_API_KEY",
|
||||
requires_openai_auth: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return y.dump(config, { lineWidth: -1 });
|
||||
const header =
|
||||
"# Generated by OmniRoute. The API key is read from the OMNIROUTE_API_KEY\n" +
|
||||
"# environment variable (env_key) and is never stored in this file.\n";
|
||||
return header + stringify(merged) + "\n";
|
||||
}
|
||||
|
||||
@@ -4,13 +4,14 @@ import os from "node:os";
|
||||
import { getHermesConfigPath } from "./hermesHome.ts";
|
||||
import { generateClaudeConfig } from "./claude";
|
||||
import { generateClineConfig } from "./cline";
|
||||
import { generateCodexConfig } from "./codex";
|
||||
import { generateCodexConfig, findLegacyCodexYaml } from "./codex";
|
||||
import { generateContinueConfig } from "./continue";
|
||||
import { generateHermesConfig } from "./hermes";
|
||||
import { generateHermesAgentConfig, type HermesAgentConfigPayload } from "./hermes-agent";
|
||||
import { generateKilocodeConfig } from "./kilocode";
|
||||
import { generateOpencodeConfig } from "./opencode";
|
||||
import { resolveOpencodeConfigPath } from "../../../shared/services/opencodeConfigPath";
|
||||
import { normalizeCliToolId } from "../../../shared/services/cliRuntime";
|
||||
|
||||
export interface GenerateOptions {
|
||||
baseUrl: string;
|
||||
@@ -23,6 +24,8 @@ export interface GenerateResult {
|
||||
configPath: string;
|
||||
content?: string;
|
||||
error?: string;
|
||||
/** Human-readable migration note (e.g. a legacy config file that is now ignored). */
|
||||
migration?: string;
|
||||
}
|
||||
|
||||
export function validateBaseUrl(url: string): boolean {
|
||||
@@ -42,9 +45,12 @@ function expandHome(p: string): string {
|
||||
// Static paths that do not depend on runtime env vars can stay eagerly computed.
|
||||
const STATIC_TOOL_CONFIG_PATHS: Record<string, string> = {
|
||||
claude: path.join(os.homedir(), ".claude", "settings.json"),
|
||||
codex: path.join(os.homedir(), ".codex", "config.yaml"),
|
||||
// Modern Codex (v0.137+) reads TOML only; config.yaml is the legacy npm CLI.
|
||||
codex: path.join(os.homedir(), ".codex", "config.toml"),
|
||||
cline: path.join(os.homedir(), ".cline", "data", "globalState.json"),
|
||||
kilocode: path.join(os.homedir(), ".config", "kilocode", "settings.json"),
|
||||
// `kilo` is the canonical id; the file name remains `kilocode` because the
|
||||
// VS Code extension owns that settings namespace.
|
||||
kilo: path.join(os.homedir(), ".config", "kilocode", "settings.json"),
|
||||
continue: path.join(os.homedir(), ".continue", "config.yaml"),
|
||||
};
|
||||
|
||||
@@ -55,6 +61,7 @@ const STATIC_TOOL_CONFIG_PATHS: Record<string, string> = {
|
||||
* honoured (#3628). All other tools use the eagerly-computed static map.
|
||||
*/
|
||||
function getToolConfigPath(toolId: string): string {
|
||||
toolId = normalizeCliToolId(toolId);
|
||||
if (toolId === "hermes" || toolId === "hermes-agent") {
|
||||
return getHermesConfigPath();
|
||||
}
|
||||
@@ -71,7 +78,7 @@ const GENERATORS: Record<string, ConfigGenerator> = {
|
||||
codex: generateCodexConfig,
|
||||
opencode: generateOpencodeConfig,
|
||||
cline: generateClineConfig,
|
||||
kilocode: generateKilocodeConfig,
|
||||
kilo: generateKilocodeConfig,
|
||||
continue: generateContinueConfig,
|
||||
hermes: generateHermesConfig,
|
||||
"hermes-agent": generateHermesAgentConfig as any, // rich multi-role version
|
||||
@@ -94,16 +101,31 @@ export async function generateConfig(
|
||||
}
|
||||
|
||||
try {
|
||||
const generate = GENERATORS[toolId];
|
||||
const canonicalToolId = normalizeCliToolId(toolId);
|
||||
const generate = GENERATORS[canonicalToolId];
|
||||
if (!generate) {
|
||||
return { success: false, configPath: "", error: `Unknown tool: ${toolId}` };
|
||||
}
|
||||
const configPath = getToolConfigPath(toolId);
|
||||
const configPath = getToolConfigPath(canonicalToolId);
|
||||
const content =
|
||||
toolId === "opencode"
|
||||
canonicalToolId === "opencode"
|
||||
? await generateOpencodeConfig({ ...options, configPath })
|
||||
: await generate(options);
|
||||
return { success: true, configPath, content };
|
||||
: canonicalToolId === "codex"
|
||||
? await generateCodexConfig({ ...options, configPath })
|
||||
: await generate(options);
|
||||
|
||||
let migration: string | undefined;
|
||||
if (canonicalToolId === "codex") {
|
||||
const legacyYaml = findLegacyCodexYaml();
|
||||
if (legacyYaml) {
|
||||
migration =
|
||||
`Legacy ${legacyYaml} found — modern Codex (v0.137+) ignores YAML and reads ` +
|
||||
`only config.toml. The YAML file was left untouched; remove it manually once ` +
|
||||
`you confirm nothing else uses it.`;
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, configPath, content, ...(migration ? { migration } : {}) };
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return { success: false, configPath: "", error: `Generation failed: ${msg}` };
|
||||
@@ -111,15 +133,10 @@ export async function generateConfig(
|
||||
}
|
||||
|
||||
export async function generateAllConfigs(options: GenerateOptions): Promise<GenerateResult[]> {
|
||||
const toolIds = [
|
||||
"claude",
|
||||
"codex",
|
||||
"opencode",
|
||||
"cline",
|
||||
"kilocode",
|
||||
"continue",
|
||||
"hermes",
|
||||
] as const;
|
||||
// Keep the batch view derived from the actual generator registry. Hermes
|
||||
// Agent has a richer payload and is intentionally exposed by its dedicated
|
||||
// endpoint, not by this simple `{baseUrl, apiKey, model}` batch API.
|
||||
const toolIds = Object.keys(GENERATORS).filter((id) => id !== "hermes-agent");
|
||||
const results = await Promise.allSettled(toolIds.map((id) => generateConfig(id, options)));
|
||||
|
||||
return results.map((r) =>
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { getCurrentHermesAgentRoles } from "./config-generator/hermes-agent";
|
||||
import { getHermesConfigPath } from "./config-generator/hermesHome";
|
||||
import { getCliTool, listCliTools } from "../../shared/constants/cliTools";
|
||||
import {
|
||||
CLI_TOOL_IDS,
|
||||
getLookupEnv,
|
||||
getCliPrimaryConfigPath,
|
||||
getCliToolCommandCandidates,
|
||||
locateCommand,
|
||||
normalizeCliToolId,
|
||||
shouldUseShellForCommand,
|
||||
} from "../../shared/services/cliRuntime";
|
||||
import { resolveOpencodeConfigPath } from "../../shared/services/opencodeConfigPath";
|
||||
@@ -42,30 +47,29 @@ export interface DetectedTool {
|
||||
>;
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{ id: "claude", name: "Claude Code", configPath: "~/.claude/settings.json" },
|
||||
{ id: "codex", name: "Codex CLI", configPath: "~/.codex/config.yaml" },
|
||||
{ id: "opencode", name: "OpenCode", configPath: resolveOpencodeConfigPath },
|
||||
{ id: "cline", name: "Cline", configPath: "~/.cline/data/globalState.json" },
|
||||
{ id: "kilocode", name: "Kilo Code", configPath: "~/.config/kilocode/settings.json" },
|
||||
{ id: "continue", name: "Continue", configPath: "~/.continue/config.yaml" },
|
||||
{ id: "hermes", name: "Hermes", configPath: "~/.hermes/config.yaml" },
|
||||
{ id: "hermes-agent", name: "Hermes Agent", configPath: "~/.hermes/config.yaml" },
|
||||
{ id: "openclaw", name: "OpenClaw", configPath: "~/.openclaw/openclaw.json" },
|
||||
] as const;
|
||||
type ToolDescriptor = { id: string; name: string; configPath: string };
|
||||
|
||||
const BINARY_NAMES: Record<string, string> = {
|
||||
claude: "claude",
|
||||
codex: "codex",
|
||||
opencode: "opencode",
|
||||
cline: "cline",
|
||||
kilocode: "kilocode",
|
||||
continue: "continue",
|
||||
hermes: "hermes",
|
||||
"hermes-agent": "hermes",
|
||||
openclaw: "openclaw",
|
||||
// Keep the long-standing CLI status labels stable while the UI catalog uses
|
||||
// marketing names (for example, "Open Claw").
|
||||
const DETECTOR_NAME_OVERRIDES: Readonly<Record<string, string>> = {
|
||||
claude: "Claude Code",
|
||||
codex: "Codex CLI",
|
||||
openclaw: "OpenClaw",
|
||||
};
|
||||
|
||||
/**
|
||||
* The detector is a read-only view over the shared runtime/UI catalogs.
|
||||
* Runtime-only entries (for example qoder) are retained, while guide-only UI
|
||||
* entries still appear with an empty config path and `installed: false`.
|
||||
*/
|
||||
const TOOLS: ToolDescriptor[] = Array.from(
|
||||
new Set([...listCliTools().map((tool) => tool.id), ...CLI_TOOL_IDS])
|
||||
).map((id) => ({
|
||||
id,
|
||||
name: DETECTOR_NAME_OVERRIDES[id] || getCliTool(id)?.name || id,
|
||||
configPath: "",
|
||||
}));
|
||||
|
||||
function expandHome(p: string): string {
|
||||
const home = os.homedir();
|
||||
return p.replace(/^~\//, home + "/");
|
||||
@@ -111,27 +115,35 @@ async function detectBinaryWindows(
|
||||
}
|
||||
|
||||
async function detectBinary(name: string): Promise<{ installed: boolean; version?: string }> {
|
||||
const binary = BINARY_NAMES[name] || name;
|
||||
const binaries = getCliToolCommandCandidates(name);
|
||||
if (binaries.length === 0) return { installed: false };
|
||||
const env = getLookupEnv();
|
||||
|
||||
if (process.platform === "win32") {
|
||||
return detectBinaryWindows(binary, env);
|
||||
for (const binary of binaries) {
|
||||
if (process.platform === "win32") {
|
||||
const result = await detectBinaryWindows(binary, env);
|
||||
if (result.installed) return result;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileImpl(binary, ["--version"], { timeout: 5000, env });
|
||||
const version = stdout.trim().replace(/^v/, "");
|
||||
return { installed: true, version };
|
||||
} catch {
|
||||
try {
|
||||
// Try `which` as fallback (routed through execFileImpl so it stays mockable)
|
||||
const { stdout } = await execFileImpl("which", [binary], { timeout: 5000, env });
|
||||
if (stdout.trim()) {
|
||||
return { installed: true };
|
||||
}
|
||||
} catch {
|
||||
// Try the next declared command candidate.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileImpl(binary, ["--version"], { timeout: 5000, env });
|
||||
const version = stdout.trim().replace(/^v/, "");
|
||||
return { installed: true, version };
|
||||
} catch {
|
||||
try {
|
||||
// Try `which` as fallback (routed through execFileImpl so it stays mockable)
|
||||
const { stdout } = await execFileImpl("which", [binary], { timeout: 5000, env });
|
||||
if (stdout.trim()) {
|
||||
return { installed: true };
|
||||
}
|
||||
} catch {}
|
||||
return { installed: false };
|
||||
}
|
||||
return { installed: false };
|
||||
}
|
||||
|
||||
async function readConfigFile(configPath: string): Promise<string | null> {
|
||||
@@ -146,17 +158,21 @@ async function readConfigFile(configPath: string): Promise<string | null> {
|
||||
}
|
||||
|
||||
export async function detectTool(id: string): Promise<DetectedTool | null> {
|
||||
const tool = TOOLS.find((t) => t.id === id);
|
||||
const canonicalId = normalizeCliToolId(id);
|
||||
const tool = TOOLS.find((t) => t.id === canonicalId);
|
||||
if (!tool) return null;
|
||||
|
||||
const { installed, version } = await detectBinary(tool.id);
|
||||
const configPath =
|
||||
typeof tool.configPath === "function" ? tool.configPath() : expandHome(tool.configPath);
|
||||
tool.id === "hermes" || tool.id === "hermes-agent"
|
||||
? getHermesConfigPath()
|
||||
: getCliPrimaryConfigPath(tool.id) ||
|
||||
(tool.id === "opencode" ? resolveOpencodeConfigPath() : "");
|
||||
const configContents = await readConfigFile(configPath);
|
||||
const configured = !!configContents && isConfigured(configContents, "http://localhost:20128");
|
||||
|
||||
const result: DetectedTool = {
|
||||
id: tool.id,
|
||||
id: canonicalId,
|
||||
name: tool.name,
|
||||
installed,
|
||||
version,
|
||||
|
||||
@@ -28,7 +28,7 @@ const PASSTHROUGH_PROVIDERS = new Set(
|
||||
);
|
||||
|
||||
// Wrap isValidModel with passthrough providers
|
||||
export function isValidModel(aliasOrId, modelId) {
|
||||
export function isValidModel(aliasOrId: string, modelId: string) {
|
||||
if (isOpenAICompatibleProvider(aliasOrId)) return true;
|
||||
if (isAnthropicCompatibleProvider(aliasOrId)) return true;
|
||||
if (PASSTHROUGH_PROVIDERS.has(aliasOrId)) return true;
|
||||
|
||||
@@ -198,6 +198,34 @@ const CLI_TOOLS: Record<string, any> = {
|
||||
env: ".qwen/.env",
|
||||
},
|
||||
},
|
||||
aider: {
|
||||
defaultCommand: "aider",
|
||||
envBinKey: "CLI_AIDER_BIN",
|
||||
requiresBinary: true,
|
||||
healthcheckTimeoutMs: 12000,
|
||||
paths: {
|
||||
config: ".aider.conf.yml",
|
||||
},
|
||||
},
|
||||
goose: {
|
||||
defaultCommand: "goose",
|
||||
envBinKey: "CLI_GOOSE_BIN",
|
||||
requiresBinary: true,
|
||||
healthcheckTimeoutMs: 12000,
|
||||
paths: {
|
||||
config: ".config/goose/config.yaml",
|
||||
},
|
||||
},
|
||||
gemini: {
|
||||
defaultCommand: "gemini",
|
||||
envBinKey: "CLI_GEMINI_BIN",
|
||||
requiresBinary: true,
|
||||
// gemini-cli cold start (bundle + extension discovery) can exceed 4s.
|
||||
healthcheckTimeoutMs: 15000,
|
||||
paths: {
|
||||
settings: ".gemini/settings.json",
|
||||
},
|
||||
},
|
||||
// ── Plan 14 — new "custom" configType tools ───────────────────────────────
|
||||
forge: {
|
||||
defaultCommand: "forge",
|
||||
@@ -286,6 +314,33 @@ const CLI_TOOLS: Record<string, any> = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Compatibility aliases accepted by CLI/API callers.
|
||||
*
|
||||
* The runtime catalog keeps one canonical id per executable. Older surfaces
|
||||
* exposed a binary name (notably `kilocode`) or launcher aliases instead of
|
||||
* that id, so normalize them at the boundary rather than duplicating entries.
|
||||
*/
|
||||
export const CLI_TOOL_ALIASES: Readonly<Record<string, string>> = {
|
||||
kilocode: "kilo",
|
||||
"kilo-code": "kilo",
|
||||
kilo_cli: "kilo",
|
||||
cc: "claude",
|
||||
"claude-code": "claude",
|
||||
"openai-codex": "codex",
|
||||
openai: "codex",
|
||||
cn: "continue",
|
||||
qodercli: "qoder",
|
||||
};
|
||||
|
||||
/** Resolve a user-facing or legacy id to the canonical runtime id. */
|
||||
export const normalizeCliToolId = (toolId: string): string => {
|
||||
const normalized = String(toolId || "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return CLI_TOOL_ALIASES[normalized] || normalized;
|
||||
};
|
||||
|
||||
const isWindows = () => process.platform === "win32";
|
||||
|
||||
/**
|
||||
@@ -568,6 +623,7 @@ const getExtraPaths = () =>
|
||||
* Works on all platforms — Windows checks .cmd wrappers, Linux/macOS checks bare names.
|
||||
*/
|
||||
export const getKnownToolPaths = (toolId: string): string[] => {
|
||||
toolId = normalizeCliToolId(toolId);
|
||||
const home = os.homedir();
|
||||
const paths: string[] = [];
|
||||
|
||||
@@ -730,7 +786,7 @@ export const getLookupEnv = () => {
|
||||
};
|
||||
|
||||
const resolveToolCommands = (toolId: string): string[] => {
|
||||
const tool = CLI_TOOLS[toolId];
|
||||
const tool = CLI_TOOLS[normalizeCliToolId(toolId)];
|
||||
if (!tool) return [];
|
||||
const envCommand = String(process.env[tool.envBinKey] || "").trim();
|
||||
if (envCommand) return [envCommand];
|
||||
@@ -740,6 +796,16 @@ const resolveToolCommands = (toolId: string): string[] => {
|
||||
return tool.defaultCommand ? [tool.defaultCommand] : [];
|
||||
};
|
||||
|
||||
/**
|
||||
* Return command candidates without probing the filesystem.
|
||||
*
|
||||
* Lightweight consumers (config status and CLI inventory) use this to build
|
||||
* a version probe while getCliRuntimeStatus() remains the authoritative
|
||||
* health/runnability check.
|
||||
*/
|
||||
export const getCliToolCommandCandidates = (toolId: string): string[] =>
|
||||
resolveToolCommands(toolId);
|
||||
|
||||
const checkExplicitPath = async (commandPath: string) => {
|
||||
// Reject paths that look like injection attempts
|
||||
if (!isSafePath(commandPath)) {
|
||||
@@ -781,13 +847,13 @@ export const locateCommand = async (command: string, env: Record<string, string
|
||||
// and a .cmd wrapper. We must prefer the Windows executable extension.
|
||||
const lines = located.stdout
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.map((l: string) => l.trim())
|
||||
.filter(Boolean);
|
||||
if (lines.length === 0) {
|
||||
return { installed: false, commandPath: null, reason: "not_found" };
|
||||
}
|
||||
const winExt = /\.(cmd|exe|bat|com)$/i;
|
||||
const preferred = lines.find((l) => winExt.test(l)) || lines[0];
|
||||
const preferred = lines.find((l: string) => winExt.test(l)) || lines[0];
|
||||
return { installed: true, commandPath: normalizeMsys2Path(preferred), reason: null };
|
||||
}
|
||||
return { installed: false, commandPath: null, reason: "not_found" };
|
||||
@@ -1025,6 +1091,7 @@ export const resolveOpencodeConfigPath = (
|
||||
export const getOpenCodeConfigPath = () => resolveOpencodeConfigPath();
|
||||
|
||||
export const getCliConfigPaths = (toolId: string) => {
|
||||
toolId = normalizeCliToolId(toolId);
|
||||
const tool = CLI_TOOLS[toolId];
|
||||
if (!tool) return null;
|
||||
|
||||
@@ -1071,6 +1138,7 @@ export const getCliPrimaryConfigPath = (toolId: string) => {
|
||||
};
|
||||
|
||||
export const getCliRuntimeStatus = async (toolId: string) => {
|
||||
toolId = normalizeCliToolId(toolId);
|
||||
const tool = CLI_TOOLS[toolId];
|
||||
const runtimeMode = getRuntimeMode();
|
||||
if (!tool) {
|
||||
|
||||
Reference in New Issue
Block a user