mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-03 22:19:42 +02:00
refactor(cli-registry): make CLI backends data instead of per-mode branching
Every run mode is now a `CliEntry` in `src/config/cli-registry/` — discovery (search dirs, version + identity probes), the launch argv template, env handling, the `capabilities` flags that replace per-CLI branching, and the `overlays` that back the remote/docker pane commands. Code that used to ask "which CLI is this?" reads the entry instead. Behaviour is unchanged. `test/cli-registry-spawn-golden.test.ts` pins every spawn command as a literal string, captured from the hand-written builders before they were deleted, and `test/location-overlay-commands.test.ts` does the same for all 20 remote and in-container pane commands. Config can never contain shell text: an entry declares typed argv tokens, literals are validated against a safe-word pattern at LOAD time (a bad literal rejects the whole entry — a silently dropped `--no-approve` is not cosmetic), and values resolve through patterns NAMED in code, so a user `clis.json` cannot widen its own validation. `~/.codeman/clis.json` overrides any entry, read-only in this release. OMP is included as a registry entry rather than a tenth hand-written builder, so `buildOmpCommand()`, the omp availability pre-flight, the omp arm of `buildPathExport()` and the omp entries in the truecolor/NO_COLOR, alt-screen and doctor ladders all drop out. Guard rails: - `test/cli-registry-no-id-branching.test.ts` fails the build if per-CLI-id branching reappears outside `stock.ts`, in any of its four shapes (`===`, `!==`, `switch`/`case`, `includes`) — an `===`-only version would miss the negated forms, which is how 36 of them survived an earlier pass. Every allowlisted branch carries its reason. - `external`, `hooks` and `altScreen` stay three INDEPENDENT capabilities; deriving one from another shipped the `until=stop`-hangs-on-shell bug. - `param` is two namespaces. `launch.params` keys, `configSetenv.fromParam` and `privilegedParams[].param` all name a LAUNCH param; the legacy `<Mode>Config` wire field is separate, bridged only by `legacyConfigAliases`. Getting `privilegedParams[].param` wrong is SILENT — it is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a wrong name clamps nothing with no error and no failing test — so `schema.ts` rejects an entry naming a param it never declared. - Registry data resolves AT CALL TIME (`sessionModeSchema()`, `allowedEnvPrefixes()`, `dependencyRegistry()`, the resolvers' `searchDirs` thunks). A module-level const freezes at first import, so a CLI enabled while the server ran moved the run menu but not that surface. - Six fields are annotated DECLARED-FOR-LATER and read by nothing (`shortBadge`, `accent`, `capabilities.echo`/`wheelForward`/ `keyboardAccessory`/`maxFrameBytes`): all frontend behaviour, transcribed rather than measured. A test pins the list so it cannot quietly grow. Three user-visible changes, all deliberate and named: - `probeDockerCliVersion()` derives the in-container binary from the registry rather than assuming it equals the mode name (`antigravity` runs `agy`). - The remote CLI version probe now covers grok and deepseek, which the hardcoded map it replaces omitted while its own comment said the rule was "every mode except shell". - `codeman doctor`'s CLI rows are generated from the entries, so Claude's install hint is the install command rather than a docs URL, five CLIs gain hints they never had, and the row order follows the catalog. Also hardened along the way: `sessionModeSchema()` is bounded at 24 chars (matching the `cliId` pattern) before its failure message quotes the value back, and `deepMerge` skips `__proto__`/`constructor`/`prototype` when reading the hand-editable `clis.json`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WQkoi1cNegqVwZHgzx5SbJ
This commit is contained in:
@@ -7,8 +7,8 @@
|
||||
* @module utils/antigravity-cli-resolver
|
||||
*/
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
@@ -16,14 +16,12 @@ import {
|
||||
} from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Antigravity CLI binary may be installed */
|
||||
const ANTIGRAVITY_SEARCH_DIRS = [
|
||||
join(homedir(), '.local', 'bin'),
|
||||
join(homedir(), '.antigravity', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), '.bun', 'bin'),
|
||||
join(homedir(), '.npm-global', 'bin'),
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const ANTIGRAVITY_SEARCH_DIRS = (): string[] => (getCli('antigravity')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const ANTIGRAVITY_NOT_FOUND =
|
||||
'Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash';
|
||||
|
||||
@@ -207,13 +207,23 @@ export function createProductionCliResolverHost(options: ProductionCliResolverHo
|
||||
export function createCliExecutableResolver<T = undefined>(
|
||||
options: {
|
||||
binary: string;
|
||||
searchDirs: string[];
|
||||
/**
|
||||
* Where to look after the process PATH. A THUNK is accepted alongside an array so a
|
||||
* caller sourcing its dirs from the CLI registry can defer the lookup: passing
|
||||
* `searchDirs: FOO_SEARCH_DIRS()` evaluates at module import, which froze the dirs
|
||||
* before a user `clis.json` or a `reloadCliRegistry()` could be seen. Resolved on each
|
||||
* probe and each `diagnostics()` call — a handful of string ops, and only when a probe
|
||||
* actually runs.
|
||||
*/
|
||||
searchDirs: string[] | (() => string[]);
|
||||
validateCandidate?: (path: string) => CandidateValidation<T>;
|
||||
/** Clock injection for tests driving the failure backoff. Defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
},
|
||||
host: CliResolverHost = createProductionCliResolverHost()
|
||||
): CliExecutableResolver<T> {
|
||||
const resolveSearchDirs = (): string[] =>
|
||||
typeof options.searchDirs === 'function' ? options.searchDirs() : options.searchDirs;
|
||||
if (!SAFE_BINARY_NAME.test(options.binary)) {
|
||||
throw new Error(`Unsafe CLI binary name: ${options.binary}`);
|
||||
}
|
||||
@@ -248,7 +258,7 @@ export function createCliExecutableResolver<T = undefined>(
|
||||
|
||||
cached = accept(host.findOnProcessPath(options.binary), 'process-path');
|
||||
if (!cached) {
|
||||
for (const dir of options.searchDirs) {
|
||||
for (const dir of resolveSearchDirs()) {
|
||||
cached = accept(join(dir, options.binary), 'common-directory');
|
||||
if (cached) break;
|
||||
}
|
||||
@@ -271,7 +281,7 @@ export function createCliExecutableResolver<T = undefined>(
|
||||
processPath: host.processPath,
|
||||
shellPath: host.shellPath,
|
||||
shellArgs: [...host.shellArgs],
|
||||
searchDirs: [...options.searchDirs],
|
||||
searchDirs: [...resolveSearchDirs()],
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* @fileoverview Implementations of the LAUNCHER profiles named by `discovery.launcherProfile`.
|
||||
*
|
||||
* A launcher CLI's binary is not the agent — it boots some further target — so two questions
|
||||
* the registry normally answers from the binary alone have to be asked of that target:
|
||||
*
|
||||
* - `isCliRunnable(id)` — stricter than "is the binary on disk?"
|
||||
* - `launcherDefaultTarget(entry)` — what to launch when the caller names no target
|
||||
*
|
||||
* The profile NAMES and their validation live in `config/cli-registry/profiles.ts`, which is
|
||||
* kept free of imports so `schema.ts` can validate a name at load time. The implementations
|
||||
* live here because they reach into resolvers that reach back into the registry, and holding
|
||||
* them next to the names would close an import cycle.
|
||||
*
|
||||
* ⚠️ Everything in this file is keyed by PROFILE NAME, never by CLI id. A new launcher CLI
|
||||
* adds a profile here and names it from its entry; it does not add a branch anywhere else.
|
||||
*
|
||||
* @module utils/cli-launcher
|
||||
*/
|
||||
|
||||
import { isDeepSeekRunnable, resolveDefaultDeepSeekProfile } from './deepseek-cli-resolver.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import type { CliEntry } from '../config/cli-registry/types.js';
|
||||
import { missingCliMessage, resolveCliBinDir } from './cli-resolver.js';
|
||||
|
||||
interface LauncherProfile {
|
||||
/** Is the launcher usable, given that its binary resolved? */
|
||||
isRunnable(): boolean;
|
||||
/** The target to launch when the caller named none, or null when there is none. */
|
||||
defaultTarget(): string | null;
|
||||
/**
|
||||
* Why a session cannot start, or null when it can — including why a SPECIFICALLY
|
||||
* requested target will not work, which "is it runnable" alone cannot say.
|
||||
*/
|
||||
launchError(requestedTarget?: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
const LAUNCHER_PROFILES: Record<string, LauncherProfile> = {
|
||||
// `dsh` launches a profile from $DSH_HOME/profiles/<name>. DeepSeek ships only
|
||||
// `web`/`headless`/`base`, none of which can drive a terminal pane, so the terminal front
|
||||
// door is always third-party: a perfectly-installed dsh with no TUI profile is installed
|
||||
// but NOT runnable, and the two questions have genuinely different answers.
|
||||
'deepseek-profile': {
|
||||
isRunnable: isDeepSeekRunnable,
|
||||
defaultTarget: resolveDefaultDeepSeekProfile,
|
||||
// Three distinct, actionable messages (binary missing / no pane-capable profile /
|
||||
// the named profile is not pane-capable). Worth keeping distinct: a pane that dies
|
||||
// instantly is the most confusing failure this mode can produce, and "not installed"
|
||||
// would send the user to fix the wrong thing.
|
||||
launchError: async (requestedTarget) => {
|
||||
const { resolveDeepSeekLaunchError } = await import('./deepseek-cli-resolver.js');
|
||||
return resolveDeepSeekLaunchError(requestedTarget);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Why a session in this mode cannot start, or null when it can.
|
||||
*
|
||||
* For an ordinary CLI this is just "is the binary there?", answered with the not-found
|
||||
* message that names where resolution looked. For a launcher CLI it defers to that CLI's own
|
||||
* profile, which can be far more specific.
|
||||
*
|
||||
* `rawConfig` is the caller's per-CLI config object, read for the target the caller named
|
||||
* (declared as `discovery.launcherTargetParam`) so the error can be about THAT target.
|
||||
*/
|
||||
export async function resolveCliLaunchError(mode: string, rawConfig?: Record<string, unknown>): Promise<string | null> {
|
||||
const entry = getCli(mode);
|
||||
if (!entry) return null;
|
||||
|
||||
const profileName = entry.discovery.launcherProfile;
|
||||
if (profileName !== undefined) {
|
||||
const profile = LAUNCHER_PROFILES[profileName];
|
||||
if (!profile) return `${entry.label} is not runnable: its launcher profile is unavailable in this build.`;
|
||||
const targetParam = entry.discovery.launcherTargetParam;
|
||||
const requested = targetParam ? rawConfig?.[targetParam] : undefined;
|
||||
return profile.launchError(typeof requested === 'string' ? requested : undefined);
|
||||
}
|
||||
|
||||
// No binary to find (`shell`) is never an error.
|
||||
if (entry.discovery.binaries.length === 0) return null;
|
||||
return resolveCliBinDir(mode) === null ? missingCliMessage(mode) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this CLI actually usable? For an ordinary CLI that is exactly "its binary resolved".
|
||||
* For a launcher it is that AND whatever its profile demands.
|
||||
*
|
||||
* ⚠️ A named-but-unimplemented profile fails CLOSED. In practice `schema.ts` rejects such an
|
||||
* entry at load time, so this is the second line of defence rather than the first — but the
|
||||
* direction matters: offering a Run that always fails is worse than reporting unavailable.
|
||||
*/
|
||||
export function isCliRunnable(id: string): boolean {
|
||||
const entry = getCli(id);
|
||||
if (!entry) return false;
|
||||
// No binary to find (`shell`): tmux-manager resolves the login shell in code.
|
||||
const resolved = entry.discovery.binaries.length === 0 ? true : resolveCliBinDir(id) !== null;
|
||||
const profileName = entry.discovery.launcherProfile;
|
||||
if (profileName === undefined) return resolved;
|
||||
const profile = LAUNCHER_PROFILES[profileName];
|
||||
if (!profile) return false;
|
||||
return resolved && profile.isRunnable();
|
||||
}
|
||||
|
||||
/**
|
||||
* The launcher's default target, for the `launcherDefaultTarget` engine value. Null for
|
||||
* every non-launcher CLI, which is what makes the corresponding launch arg drop out.
|
||||
*/
|
||||
export function launcherDefaultTarget(entry: CliEntry): string | null {
|
||||
const profileName = entry.discovery.launcherProfile;
|
||||
if (profileName === undefined) return null;
|
||||
return LAUNCHER_PROFILES[profileName]?.defaultTarget() ?? null;
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* @fileoverview Registry-driven CLI binary resolution: look up ANY registered CLI's binary
|
||||
* directory, version and not-found message from its `CliEntry`, with no per-CLI branch.
|
||||
*
|
||||
* This is a LAYER over `cli-executable-resolver.ts`, not a replacement for it. That module
|
||||
* still owns the lookup chain (process PATH → the entry's search dirs → an interactive
|
||||
* login shell), the negative cache and its doubling backoff, the marker-fenced login-shell
|
||||
* parse, the `SIGKILL` timeouts and the vitest hermeticity gate — all of it deliberately
|
||||
* untouched here, because those guards are load-bearing and separately tested. What this
|
||||
* module adds is: where the parameters come from (the registry, rather than seven
|
||||
* hand-written constant blocks) and what makes a candidate acceptable.
|
||||
*
|
||||
* CANDIDATE VALIDATION runs in a fixed order, and the order is the point:
|
||||
*
|
||||
* 1. IDENTITY (`discovery.identity`) — does the binary say it is the program we meant?
|
||||
* Checked FIRST, because a version probe cannot tell an impostor from the real thing:
|
||||
* Debian's `dsh` (dancer's shell) answers `--version` perfectly happily, and npm
|
||||
* carries squatters for both `pi` and `grok`.
|
||||
* 2. VERSION (`discovery.version`) — does its version output have the right shape? With
|
||||
* `requireVersionMatch`, a mismatch means ABSENT rather than present-with-unknown-
|
||||
* version, which is what a short, generic binary name needs.
|
||||
*
|
||||
* Both probes EXECUTE the candidate, which is exactly why both are gated off under vitest:
|
||||
* a suite must never depend on — let alone run — whatever binary of that name the machine
|
||||
* running it happens to carry. Tests inject probes instead.
|
||||
*
|
||||
* @module utils/cli-resolver
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { compileVersionRegex, MAX_VERSION_OUTPUT } from '../config/cli-registry/patterns.js';
|
||||
import { getCli, resolveInstallCommandForPlatform } from '../config/cli-registry/registry.js';
|
||||
import { getClaudeCliVersion } from './claude-cli-resolver.js';
|
||||
import type { CliEntry } from '../config/cli-registry/types.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
type CliExecutableResolver,
|
||||
type CliResolverHost,
|
||||
} from './cli-executable-resolver.js';
|
||||
|
||||
/** Expand a leading `~` to the home directory. Nothing else is interpreted. */
|
||||
export function expandHome(dir: string): string {
|
||||
if (dir === '~') return homedir();
|
||||
if (dir.startsWith('~/')) return join(homedir(), dir.slice(2));
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `<binPath> <arg>` and return its trimmed output, truncated to the cap a
|
||||
* config-supplied regex is allowed to see.
|
||||
*
|
||||
* Returns null under vitest — see this file's header. This is defense in depth rather than
|
||||
* the only gate (the shared resolver host is already inert under vitest), and it is what
|
||||
* makes the "resolve nothing even against a real on-disk fixture" behaviour hold for a
|
||||
* test that opts back into real filesystem IO.
|
||||
*/
|
||||
function probeCommandOutput(binPath: string, arg: string, logPrefix: string): string | null {
|
||||
if (process.env.VITEST) return null;
|
||||
try {
|
||||
return execFileSync(binPath, [arg], {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
// execFileSync's `timeout` only SENDS the signal and then keeps waiting. A stuck or
|
||||
// hostile binary that ignores SIGTERM would survive it and block the server.
|
||||
killSignal: 'SIGKILL',
|
||||
})
|
||||
.trim()
|
||||
.slice(0, MAX_VERSION_OUTPUT);
|
||||
} catch (err) {
|
||||
console.warn(`[${logPrefix}] Ignoring ${binPath}: "${arg}" failed (${(err as Error).message})`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** What a candidate probe reports back. `version` is undefined when none was declared. */
|
||||
export interface CliCandidateProbeResult {
|
||||
accepted: boolean;
|
||||
version?: string;
|
||||
}
|
||||
|
||||
/** A probe hook, so tests can drive resolution without executing anything. */
|
||||
export type CliCandidateProbe = (binPath: string, entry: CliEntry) => CliCandidateProbeResult;
|
||||
|
||||
/**
|
||||
* The production probe: identity first, then version. A CLI declaring neither is accepted
|
||||
* on existence alone, which is the common case (opencode, codex, gemini, antigravity).
|
||||
*/
|
||||
export function probeCliCandidate(binPath: string, entry: CliEntry): CliCandidateProbeResult {
|
||||
const logPrefix = `CliResolver:${entry.id as string}`;
|
||||
const { identity, version } = entry.discovery;
|
||||
|
||||
if (identity) {
|
||||
const pattern = compileVersionRegex(identity.regex);
|
||||
if (!pattern) {
|
||||
console.warn(`[${logPrefix}] identity.regex was rejected as unsafe; refusing every candidate.`);
|
||||
return { accepted: false };
|
||||
}
|
||||
const out = probeCommandOutput(binPath, identity.arg, logPrefix);
|
||||
if (out === null || !pattern.test(out)) {
|
||||
console.warn(`[${logPrefix}] Ignoring ${binPath}: "${identity.arg}" did not identify it as ${entry.label}.`);
|
||||
return { accepted: false };
|
||||
}
|
||||
}
|
||||
|
||||
if (!version) return { accepted: true };
|
||||
|
||||
const out = probeCommandOutput(binPath, version.arg, logPrefix);
|
||||
const pattern = version.regex ? compileVersionRegex(version.regex) : null;
|
||||
const found = out !== null && pattern ? (pattern.exec(out)?.[1] ?? undefined) : undefined;
|
||||
|
||||
if (found === undefined && version.requireVersionMatch) {
|
||||
// A `which` hit is not evidence for a short, generic or squatted binary name.
|
||||
console.warn(`[${logPrefix}] Ignoring ${binPath}: "${version.arg}" printed ${JSON.stringify(out?.slice(0, 80))}`);
|
||||
return { accepted: false };
|
||||
}
|
||||
return { accepted: true, version: found };
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolver for one registry entry. An entry may declare several binary names (first hit
|
||||
* wins), so this holds one underlying resolver per name and returns the first that
|
||||
* resolves — which is also what keeps each name's own negative cache and backoff intact.
|
||||
*/
|
||||
interface RegistryResolver {
|
||||
resolveDir(): string | null;
|
||||
getVersion(): string | null;
|
||||
notFoundMessage(base: string): string;
|
||||
}
|
||||
|
||||
function createRegistryResolver(
|
||||
entry: CliEntry,
|
||||
probe: CliCandidateProbe = probeCliCandidate,
|
||||
host?: CliResolverHost,
|
||||
now?: () => number
|
||||
): RegistryResolver {
|
||||
const searchDirs = entry.discovery.searchDirs.map(expandHome);
|
||||
const perBinary: CliExecutableResolver<string>[] = entry.discovery.binaries.map((binary) =>
|
||||
createCliExecutableResolver<string>(
|
||||
{
|
||||
binary,
|
||||
searchDirs,
|
||||
validateCandidate: (binPath) => {
|
||||
const result = probe(binPath, entry);
|
||||
return result.accepted ? { accepted: true, metadata: result.version } : { accepted: false };
|
||||
},
|
||||
now,
|
||||
},
|
||||
host
|
||||
)
|
||||
);
|
||||
|
||||
const first = () => {
|
||||
for (const resolver of perBinary) {
|
||||
const resolution = resolver.resolve();
|
||||
if (resolution) return resolution;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return {
|
||||
resolveDir: () => first()?.directory ?? null,
|
||||
getVersion: () => first()?.metadata ?? null,
|
||||
notFoundMessage: (base) =>
|
||||
// Diagnostics come from the FIRST declared binary: every name shares the same search
|
||||
// dirs, PATH and login shell, so the extra copies would say the same thing twice.
|
||||
perBinary.length > 0 ? formatCliNotFoundMessage(base, perBinary[0].diagnostics()) : base,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an isolated resolver for `entry` around an injected probe, host and clock — the
|
||||
* test seam. Omitting `probe` keeps the ambient, VITEST-gated one, which is exactly what
|
||||
* the hermeticity tests exercise.
|
||||
*/
|
||||
export function createCliResolverForTest(
|
||||
entry: CliEntry,
|
||||
probe?: CliCandidateProbe,
|
||||
host?: CliResolverHost,
|
||||
now?: () => number
|
||||
): RegistryResolver {
|
||||
return createRegistryResolver(entry, probe ?? probeCliCandidate, host, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* One memoized resolver per id, for the process lifetime — the same caching the per-CLI
|
||||
* modules already do for themselves, just keyed by id so generic code holding only a
|
||||
* `CliId` string can resolve a CLI it knows nothing else about, custom entries included.
|
||||
*/
|
||||
const resolvers = new Map<string, RegistryResolver>();
|
||||
|
||||
function resolverFor(id: string): RegistryResolver | null {
|
||||
const cached = resolvers.get(id);
|
||||
if (cached) return cached;
|
||||
const entry = getCli(id);
|
||||
// `shell` declares no binary: tmux-manager resolves the real login shell in code.
|
||||
if (!entry || entry.discovery.binaries.length === 0) return null;
|
||||
const resolver = createRegistryResolver(entry);
|
||||
resolvers.set(id, resolver);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the memoized resolver for `id` so the next lookup re-probes from scratch instead of
|
||||
* replaying a cached negative result and waiting out a backoff window already in progress.
|
||||
*/
|
||||
export function invalidateCliResolverCache(id?: string): void {
|
||||
if (id === undefined) resolvers.clear();
|
||||
else resolvers.delete(id);
|
||||
}
|
||||
|
||||
/** The directory containing this CLI's binary, or null when it cannot be found. */
|
||||
export function resolveCliBinDir(id: string): string | null {
|
||||
return resolverFor(id)?.resolveDir() ?? null;
|
||||
}
|
||||
|
||||
/** Is this CLI's binary present? Note: for a launcher CLI this is NOT the same as runnable. */
|
||||
export function isCliAvailable(id: string): boolean {
|
||||
return resolveCliBinDir(id) !== null;
|
||||
}
|
||||
|
||||
/** The version the resolved binary reported, or null when unresolved or none was declared. */
|
||||
export function resolveCliVersion(id: string): string | null {
|
||||
return resolverFor(id)?.getVersion() ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* "CLI not found" message for `id`, with bounded PATH/login-shell/search-dir diagnostics
|
||||
* appended so the error names where resolution actually looked. Returns null for an id with
|
||||
* no binary to find (`shell`) or one that is not registered at all.
|
||||
*/
|
||||
export function missingCliMessage(id: string): string | null {
|
||||
const entry = getCli(id);
|
||||
if (!entry || entry.discovery.binaries.length === 0) return null;
|
||||
const install = resolveInstallCommandForPlatform(entry);
|
||||
const base = install
|
||||
? `${entry.label} CLI not found. Install with: ${install}`
|
||||
: `${entry.label} CLI not found (looked for ${entry.discovery.binaries.join(', ')}).`;
|
||||
return resolverFor(id)?.notFoundMessage(base) ?? base;
|
||||
}
|
||||
|
||||
/**
|
||||
* The version to stamp on a SESSION in this mode.
|
||||
*
|
||||
* ⚠️ Dispatched on DATA, not on an id, and the field it dispatches on is the one that
|
||||
* describes the difference: `discovery.version.retryOnTransientFailure`.
|
||||
*
|
||||
* Claude needs a probe policy no other CLI does. A single failed `claude --version` — a 5s
|
||||
* timeout, a PATH-starved systemd unit, a transient fs hiccup — used to be cached forever,
|
||||
* which silently disabled wheel-forwarding to Claude's own transcript for every session
|
||||
* until the server restarted (the only route to history in repaint mode: a dead wheel on
|
||||
* every device at once). `getClaudeCliVersion()` caches success forever and retries failure
|
||||
* with backoff, and that policy has to be preserved exactly, so this routes to it rather
|
||||
* than reimplementing it generically.
|
||||
*
|
||||
* Everything else goes through the ordinary registry resolver, which is the point: the
|
||||
* caller asks `cliNeedsVersionProbe()` whether this CLI gates anything on its version and
|
||||
* then asks HERE for that CLI's version. Before this, all three call sites asked
|
||||
* `cliNeedsVersionProbe()` a generic question and then called `getClaudeCliVersion()`
|
||||
* unconditionally — so the first non-claude entry to declare a `capabilities.gates` would
|
||||
* have had CLAUDE's version stamped on its sessions and its gate evaluated against it.
|
||||
*/
|
||||
export function resolveSessionCliVersion(mode: string): string | null {
|
||||
return getCli(mode)?.discovery.version?.retryOnTransientFailure ? getClaudeCliVersion() : resolveCliVersion(mode);
|
||||
}
|
||||
@@ -7,21 +7,18 @@
|
||||
* @module utils/codex-cli-resolver
|
||||
*/
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
import { parseCodexRateLimitsResponse, type StatusTelemetry } from '../usage-telemetry.js';
|
||||
|
||||
/** Common directories where the Codex CLI binary may be installed */
|
||||
const CODEX_SEARCH_DIRS = [
|
||||
join(homedir(), '.codex', 'bin'), // Default install location
|
||||
join(homedir(), '.local', 'bin'), // Alternative install location
|
||||
'/usr/local/bin', // Homebrew / system
|
||||
join(homedir(), '.bun', 'bin'), // Bun global
|
||||
join(homedir(), '.npm-global', 'bin'), // npm global
|
||||
join(homedir(), 'bin'), // User bin
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const CODEX_SEARCH_DIRS = (): string[] => (getCli('codex')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const CODEX_BINARY = process.platform === 'win32' ? 'codex.exe' : 'codex';
|
||||
const codexResolver = createCliExecutableResolver({ binary: CODEX_BINARY, searchDirs: CODEX_SEARCH_DIRS });
|
||||
|
||||
@@ -35,6 +35,8 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
@@ -49,12 +51,12 @@ import {
|
||||
* user's prefix points. `~/.local/bin` heads the list because it is the default
|
||||
* for a prefix-relocated npm (and is where this box's install landed).
|
||||
*/
|
||||
const DEEPSEEK_SEARCH_DIRS = [
|
||||
join(homedir(), '.local', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), '.npm-global', 'bin'),
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const DEEPSEEK_SEARCH_DIRS = (): string[] => (getCli('deepseek')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
/**
|
||||
* A real `dsh --version` prints a bare `0.1.1-rc.2` (measured, 0.1.1-rc.2), so
|
||||
|
||||
@@ -7,19 +7,17 @@
|
||||
* @module utils/gemini-cli-resolver
|
||||
*/
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Gemini CLI binary may be installed */
|
||||
const GEMINI_SEARCH_DIRS = [
|
||||
join(homedir(), '.gemini', 'bin'),
|
||||
join(homedir(), '.local', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), '.bun', 'bin'),
|
||||
join(homedir(), '.npm-global', 'bin'),
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const GEMINI_SEARCH_DIRS = (): string[] => (getCli('gemini')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const geminiResolver = createCliExecutableResolver({ binary: 'gemini', searchDirs: GEMINI_SEARCH_DIRS });
|
||||
const GEMINI_NOT_FOUND = 'Gemini CLI not found. Install with: npm install -g @google/gemini-cli';
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
@@ -30,12 +30,12 @@ import {
|
||||
} from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Grok CLI binary may be installed */
|
||||
const GROK_SEARCH_DIRS = [
|
||||
join(homedir(), '.grok', 'bin'),
|
||||
join(homedir(), '.local', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const GROK_SEARCH_DIRS = (): string[] => (getCli('grok')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
/**
|
||||
* A real `grok --version` prints `grok 1.0.5 (5115b46bc9)` (measured, 1.0.5).
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
@@ -24,20 +24,15 @@ import {
|
||||
} from './cli-executable-resolver.js';
|
||||
|
||||
/**
|
||||
* Common directories where the OMP CLI binary may be installed. `~/.local/bin`
|
||||
* leads: omp.sh's installer targets `$HOME/.local/bin` with no `--dir`
|
||||
* override (verified against a real `--no-cache` Docker build — see
|
||||
* docker/agent.Dockerfile); `~/.omp/bin` was an unverified guess that turned
|
||||
* out wrong, kept after `~/.local/bin` only as a defensive fallback.
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*
|
||||
* `~/.local/bin` still leads, for the reason it always did: omp.sh's installer targets it
|
||||
* with no `--dir` override (verified against a real `--no-cache` docker build), while
|
||||
* `~/.omp/bin` was an unverified guess that turned out wrong and is kept as a fallback.
|
||||
*/
|
||||
const OMP_SEARCH_DIRS = [
|
||||
join(homedir(), '.local', 'bin'),
|
||||
join(homedir(), '.omp', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), '.bun', 'bin'),
|
||||
join(homedir(), '.npm-global', 'bin'),
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
const OMP_SEARCH_DIRS = (): string[] => (getCli('omp')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
/**
|
||||
* A real `omp --version` prints `omp/<semver>` (e.g. `omp/17.4.0`).
|
||||
|
||||
@@ -7,20 +7,17 @@
|
||||
* @module utils/opencode-cli-resolver
|
||||
*/
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the OpenCode CLI binary may be installed */
|
||||
const OPENCODE_SEARCH_DIRS = [
|
||||
join(homedir(), '.opencode', 'bin'), // Default install location
|
||||
join(homedir(), '.local', 'bin'), // Alternative install location
|
||||
'/usr/local/bin', // Homebrew / system
|
||||
join(homedir(), 'go', 'bin'), // Go install
|
||||
join(homedir(), '.bun', 'bin'), // Bun global
|
||||
join(homedir(), '.npm-global', 'bin'), // npm global
|
||||
join(homedir(), 'bin'), // User bin
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const OPENCODE_SEARCH_DIRS = (): string[] => (getCli('opencode')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
const openCodeResolver = createCliExecutableResolver({ binary: 'opencode', searchDirs: OPENCODE_SEARCH_DIRS });
|
||||
const OPENCODE_NOT_FOUND = 'OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash';
|
||||
|
||||
@@ -16,9 +16,9 @@
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
import { getCli } from '../config/cli-registry/registry.js';
|
||||
import { expandHome } from './cli-resolver.js';
|
||||
import {
|
||||
createCliExecutableResolver,
|
||||
formatCliNotFoundMessage,
|
||||
@@ -26,13 +26,12 @@ import {
|
||||
} from './cli-executable-resolver.js';
|
||||
|
||||
/** Common directories where the Pi CLI binary may be installed */
|
||||
const PI_SEARCH_DIRS = [
|
||||
join(homedir(), '.local', 'bin'),
|
||||
'/usr/local/bin',
|
||||
join(homedir(), '.bun', 'bin'),
|
||||
join(homedir(), '.npm-global', 'bin'),
|
||||
join(homedir(), 'bin'),
|
||||
];
|
||||
/**
|
||||
* Directories probed after `which`, read from this CLI's registry entry so the spawn
|
||||
* path, `codeman doctor` and this resolver cannot disagree about where to look.
|
||||
* `~` is expanded by `expandHome`; nothing else is interpreted.
|
||||
*/
|
||||
const PI_SEARCH_DIRS = (): string[] => (getCli('pi')?.discovery.searchDirs ?? []).map(expandHome);
|
||||
|
||||
/**
|
||||
* A real `pi --version` prints a semver-shaped string (e.g. `0.84.1`).
|
||||
|
||||
Reference in New Issue
Block a user