mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 12:39:42 +02:00
Post-merge follow-ups for PR #329 (shared CLI executable resolution): - Negative-cache resolution misses with a doubling backoff (1min -> 5min cap, cliResolveRetryDelayMs, mirroring claudeVersionRetryDelayMs): the shared resolver cached success only, so a missing CLI re-ran the whole chain - ending in a synchronous interactive login-shell spawn bounded by the 5s EXEC_TIMEOUT_MS - on every /api/<cli>/status request and Run attempt, stalling the event loop each time, forever. Success still caches for the process lifetime, so an installed CLI is picked up within minutes without a restart. Tests drive the backoff via an injectable clock (createCliExecutableResolver `now` option, threaded through the createPiResolverForTest / createAntigravityResolverForTest wrappers). - Pass killSignal: 'SIGKILL' on the resolver's login-shell spawn and on the pi/claude --version probes: execFileSync's timeout only SENDS the kill signal and then keeps waiting for the child to exit, and interactive bash ignores SIGTERM, so a login shell stuck in a blocking .bash_profile survived the timeout and blocked the server permanently. - Restore test hermeticity (PR #329 deleted pi's VITEST guards, and one test pinned the deletion): under vitest the production resolver host now replaces un-injected IO primitives with inert stubs - no real PATH scanning, no login-shell spawns - and probePiVersion never executes a `pi` candidate again (`pi` is a generic binary name, so route tests hitting /api/pi/status executed whatever binary the machine carried). Tests opt in through the runCommand/isExecutableFile injection hooks or allowRealIoUnderVitest for real-filesystem fixtures. The deletion-pinning test is replaced by behavioral pins, including a real-executable fixture in the new test/pi-cli-resolver.test.ts that fails loudly if the pi gate is ever removed again. - Wire the six get*NotFoundMessage() exports (previously dead) into their intended call sites: the createSession throws in tmux-manager and the availability gates on POST /api/sessions and POST /api/quick-start in session-routes, replacing a third hardcoded copy of the text. A not-found error now names where resolution looked (server PATH, login shell, checked directories). npm run knip no longer reports any unused export from the resolver modules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
147 lines
5.8 KiB
TypeScript
147 lines
5.8 KiB
TypeScript
/**
|
|
* @fileoverview Resolve the Pi CLI (`pi`) binary across common install paths.
|
|
*
|
|
* Mirrors antigravity-cli-resolver.ts, with one addition the other external-CLI
|
|
* resolvers do not need: `pi` is a SHORT, GENERIC name (Raspberry Pi tooling,
|
|
* personal scripts, `$PATH` accidents), so a `which pi` hit is not by itself
|
|
* evidence that the coding agent is installed. Every candidate is therefore
|
|
* sanity-probed with `pi --version` and required to print a semver-shaped
|
|
* string; a binary that fails the probe is treated as absent and the rejected
|
|
* path is logged so a misresolution is diagnosable.
|
|
*
|
|
* Pi ships as the npm package `@earendil-works/pi-coding-agent`, so the search
|
|
* dirs are the usual global-bin locations (npm/bun/manual installs).
|
|
*
|
|
* @module utils/pi-cli-resolver
|
|
*/
|
|
|
|
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 {
|
|
createCliExecutableResolver,
|
|
formatCliNotFoundMessage,
|
|
type CliResolverHost,
|
|
} 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'),
|
|
];
|
|
|
|
/**
|
|
* A real `pi --version` prints a semver-shaped string (e.g. `0.84.1`).
|
|
*
|
|
* Exported and SHARED with the `pi` entry in `config/dependency-registry.ts`, so
|
|
* `codeman doctor` and the run mode cannot disagree about what counts as an installed
|
|
* pi: two copies of this rule would let the Dependencies panel report "Pi CLI ✓" on a
|
|
* box where `resolvePiDir()` rejects the same binary and Run Pi stays hidden.
|
|
*
|
|
* Shape is dictated by the doctor's `extractVersion()`, which returns the first CAPTURE
|
|
* GROUP and scans the whole output: hence a capturing group, and a leading boundary
|
|
* instead of `^` so `pi 0.84.1` matches while `v0.84.1` (some other program) does not.
|
|
* No `g` flag, so there is no shared `lastIndex` to reset.
|
|
*/
|
|
export const PI_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
|
|
|
|
const PI_NOT_FOUND = 'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent';
|
|
|
|
/**
|
|
* Run `pi --version` on a candidate path and return the trimmed version when it
|
|
* looks like the coding agent. Returns null for anything else — a missing
|
|
* binary, a non-zero exit, a hang (timeout), or output that is not semver-shaped
|
|
* (which is how an unrelated `pi` 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 pi installed — and since `pi` is a short
|
|
* GENERIC name, 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 `createPiResolverForTest`, whose
|
|
* injected probe bypasses it. Pinned by test/pi-cli-resolver.test.ts.
|
|
*/
|
|
function probePiVersion(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 `pi` that ignores SIGTERM would survive the timeout
|
|
// and block the server (execFileSync keeps waiting after the signal).
|
|
killSignal: 'SIGKILL',
|
|
}).trim();
|
|
// Upstream prints a bare version today; tolerate a `pi 0.84.1` style prefix too.
|
|
const candidate = PI_VERSION_REGEX.exec(out)?.[1];
|
|
if (candidate) return candidate;
|
|
console.warn(`[PiResolver] Ignoring ${binPath}: "pi --version" printed ${JSON.stringify(out.slice(0, 80))}`);
|
|
} catch (err) {
|
|
console.warn(`[PiResolver] Ignoring ${binPath}: "pi --version" failed (${(err as Error).message})`);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
type PiVersionProbe = (binPath: string) => string | null;
|
|
|
|
function createPiResolver(host?: CliResolverHost, versionProbe: PiVersionProbe = probePiVersion, now?: () => number) {
|
|
return createCliExecutableResolver<string>(
|
|
{
|
|
binary: 'pi',
|
|
searchDirs: PI_SEARCH_DIRS,
|
|
validateCandidate: (binPath) => {
|
|
const version = versionProbe(binPath);
|
|
return version ? { accepted: true, metadata: version } : { accepted: false };
|
|
},
|
|
now,
|
|
},
|
|
host
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Creates an isolated Pi 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 createPiResolverForTest(host: CliResolverHost, versionProbe?: PiVersionProbe, now?: () => number) {
|
|
return createPiResolver(host, versionProbe ?? probePiVersion, now);
|
|
}
|
|
|
|
const piResolver = createPiResolver();
|
|
|
|
/**
|
|
* Finds the directory containing a verified `pi` binary.
|
|
* Checks `which pi` first, then falls back to common install locations. Every
|
|
* candidate must pass the `pi --version` sanity probe (§2.6 of the integration
|
|
* plan) before it is accepted.
|
|
*
|
|
* @returns Directory path, or null if not found
|
|
*/
|
|
export function resolvePiDir(): string | null {
|
|
return piResolver.resolve()?.directory ?? null;
|
|
}
|
|
|
|
/**
|
|
* Check if the Pi CLI is available on the system.
|
|
*/
|
|
export function isPiAvailable(): boolean {
|
|
return resolvePiDir() !== null;
|
|
}
|
|
|
|
export function getPiNotFoundMessage(): string {
|
|
return formatCliNotFoundMessage(PI_NOT_FOUND, piResolver.diagnostics());
|
|
}
|
|
|
|
/**
|
|
* Version reported by the resolved `pi` binary, or null when pi is unavailable.
|
|
* Surfaced through `GET /api/pi/status` so a misresolution is diagnosable from the UI.
|
|
*/
|
|
export function getPiCliVersion(): string | null {
|
|
return piResolver.resolve()?.metadata ?? null;
|
|
}
|