Files
Codeman/src/utils/grok-cli-resolver.ts
T
DevvynandClaude Opus 5 4830e662f9 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
2026-09-02 08:26:45 +08:00

152 lines
6.1 KiB
TypeScript

/**
* @fileoverview Resolve the Grok Build CLI (`grok`, xAI) binary across common install paths.
*
* Mirrors pi-cli-resolver.ts, version probe included: `grok` is another short
* name with known squatters (the unrelated `@vibe-kit/grok-cli` npm package also
* installs a `grok` bin), so a `which grok` hit is not by itself evidence that
* xAI's coding agent is installed. Every candidate is sanity-probed with
* `grok --version` and required to print a version-shaped string (the real CLI
* prints `grok 1.0.5 (5115b46bc9)`); a binary that fails the probe is treated
* as absent and the rejected path is logged. The probe cannot tell two
* version-printing `grok`s apart, which is why `GET /api/grok/status` surfaces
* path AND version: a misresolution is diagnosable rather than presenting as
* "the mode just doesn't work".
*
* The official installer (`curl -fsSL https://x.ai/cli/install.sh | bash`)
* places the binary in `~/.grok/bin` and symlinks it into `~/.local/bin`, so
* those two head the search list.
*
* @module utils/grok-cli-resolver
*/
import { execFileSync } from 'node:child_process';
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,
type CliResolverHost,
} from './cli-executable-resolver.js';
/** Common directories where the Grok CLI binary may be installed */
/**
* 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).
*
* Exported and SHARED with the `grok` entry in `config/dependency-registry.ts`,
* so `codeman doctor` and the run mode cannot disagree about what counts as an
* installed grok (the same single-source rule as PI_VERSION_REGEX). Shape is
* dictated by the doctor's `extractVersion()` (first capture group, whole-output
* scan): hence a capturing group and a leading boundary instead of `^`. No `g`
* flag, so there is no shared `lastIndex` to reset.
*/
export const GROK_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
const GROK_NOT_FOUND = 'Grok CLI not found. Install with: curl -fsSL https://x.ai/cli/install.sh | bash';
/**
* Run `grok --version` on a candidate path and return the version token when it
* looks like the coding agent. Returns null for anything else: a missing
* binary, a non-zero exit, a hang (timeout), or output with no version-shaped
* token (which is how an unrelated `grok` on PATH gets rejected).
*
* Never runs under vitest: the suites must stay hermetic and must not depend on
* whether the dev box happens to have grok installed, and since `grok` is a
* name with known squatters, this probe would EXECUTE whatever binary of that
* name the machine carries. The shared resolver host is already inert under
* vitest, so this gate is defense in depth for any opted-in host that still
* carries the default probe; tests drive resolution via
* `createGrokResolverForTest`, whose injected probe bypasses it. Pinned by
* test/grok-cli-resolver.test.ts.
*/
function probeGrokVersion(binPath: string): string | null {
if (process.env.VITEST) return null;
try {
const out = execFileSync(binPath, ['--version'], {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
// A stuck or hostile `grok` that ignores SIGTERM would survive the timeout
// and block the server (execFileSync keeps waiting after the signal).
killSignal: 'SIGKILL',
}).trim();
const candidate = GROK_VERSION_REGEX.exec(out)?.[1];
if (candidate) return candidate;
console.warn(`[GrokResolver] Ignoring ${binPath}: "grok --version" printed ${JSON.stringify(out.slice(0, 80))}`);
} catch (err) {
console.warn(`[GrokResolver] Ignoring ${binPath}: "grok --version" failed (${(err as Error).message})`);
}
return null;
}
type GrokVersionProbe = (binPath: string) => string | null;
function createGrokResolver(
host?: CliResolverHost,
versionProbe: GrokVersionProbe = probeGrokVersion,
now?: () => number
) {
return createCliExecutableResolver<string>(
{
binary: 'grok',
searchDirs: GROK_SEARCH_DIRS,
validateCandidate: (binPath) => {
const version = versionProbe(binPath);
return version ? { accepted: true, metadata: version } : { accepted: false };
},
now,
},
host
);
}
/**
* Creates an isolated Grok wrapper around an injected host, version probe and
* clock. Omitting `versionProbe` keeps the ambient (VITEST-gated) probe, which
* is exactly what the hermeticity test exercises.
*/
export function createGrokResolverForTest(host: CliResolverHost, versionProbe?: GrokVersionProbe, now?: () => number) {
return createGrokResolver(host, versionProbe ?? probeGrokVersion, now);
}
const grokResolver = createGrokResolver();
/**
* Finds the directory containing a verified `grok` binary.
* Checks the server PATH first, then the common install locations
* (`~/.grok/bin` leading, the official installer's target). Every candidate
* must pass the `grok --version` sanity probe before it is accepted.
*
* @returns Directory path, or null if not found
*/
export function resolveGrokDir(): string | null {
return grokResolver.resolve()?.directory ?? null;
}
/**
* Check if the Grok CLI is available on the system.
*/
export function isGrokAvailable(): boolean {
return resolveGrokDir() !== null;
}
export function getGrokNotFoundMessage(): string {
return formatCliNotFoundMessage(GROK_NOT_FOUND, grokResolver.diagnostics());
}
/**
* Version reported by the resolved `grok` binary, or null when grok is
* unavailable. Surfaced through `GET /api/grok/status` so a misresolution is
* diagnosable from the UI.
*/
export function getGrokCliVersion(): string | null {
return grokResolver.resolve()?.metadata ?? null;
}