mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-02 21:49:42 +02:00
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
130 lines
4.5 KiB
TypeScript
130 lines
4.5 KiB
TypeScript
/**
|
|
* @fileoverview Resolve the Codex (OpenAI) CLI binary across common install paths.
|
|
*
|
|
* Mirrors opencode-cli-resolver.ts pattern. Finds the `codex` binary
|
|
* and provides an augmented PATH string for tmux sessions.
|
|
*
|
|
* @module utils/codex-cli-resolver
|
|
*/
|
|
|
|
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';
|
|
|
|
/**
|
|
* 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 });
|
|
const CODEX_NOT_FOUND = 'Codex CLI not found. Install with: npm install -g @openai/codex';
|
|
|
|
/**
|
|
* Finds the directory containing the `codex` binary.
|
|
* Checks `which codex` first, then falls back to common install locations.
|
|
* Result is cached for subsequent calls.
|
|
*
|
|
* @returns Directory path, or null if not found
|
|
*/
|
|
export function resolveCodexDir(): string | null {
|
|
return codexResolver.resolve()?.directory ?? null;
|
|
}
|
|
|
|
/** Absolute Codex executable path, for direct app-server requests. */
|
|
export function resolveCodexBinaryPath(): string | null {
|
|
return codexResolver.resolve()?.binaryPath ?? null;
|
|
}
|
|
|
|
/**
|
|
* Check if Codex CLI is available on the system.
|
|
*/
|
|
export function isCodexAvailable(): boolean {
|
|
return resolveCodexDir() !== null;
|
|
}
|
|
|
|
export function getCodexNotFoundMessage(): string {
|
|
return formatCliNotFoundMessage(CODEX_NOT_FOUND, codexResolver.diagnostics());
|
|
}
|
|
|
|
type CodexRateLimitsRequest = (binaryPath: string, clientVersion: string) => Promise<unknown>;
|
|
|
|
const APP_SERVER_TIMEOUT_MS = 10_000;
|
|
const APP_SERVER_MAX_OUTPUT_BYTES = 256 * 1024;
|
|
|
|
function requestCodexRateLimits(binaryPath: string, clientVersion: string): Promise<unknown> {
|
|
return new Promise((resolve) => {
|
|
let settled = false;
|
|
let initialized = false;
|
|
let buffer = '';
|
|
const child = spawn(binaryPath, ['app-server', '--stdio'], {
|
|
stdio: ['pipe', 'pipe', 'ignore'],
|
|
windowsHide: true,
|
|
});
|
|
const timeout = setTimeout(() => finish(null), APP_SERVER_TIMEOUT_MS);
|
|
|
|
const finish = (value: unknown): void => {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(timeout);
|
|
child.stdin.end();
|
|
child.kill();
|
|
resolve(value);
|
|
};
|
|
const send = (message: unknown): void => {
|
|
if (!settled && child.stdin.writable) child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
};
|
|
const handleLine = (line: string): void => {
|
|
if (!line.trim()) return;
|
|
let message: { id?: number; result?: unknown; error?: unknown };
|
|
try {
|
|
message = JSON.parse(line) as { id?: number; result?: unknown; error?: unknown };
|
|
} catch {
|
|
return;
|
|
}
|
|
if (message.id === 1) {
|
|
if (message.error) return finish(null);
|
|
if (!initialized) {
|
|
initialized = true;
|
|
send({ method: 'account/rateLimits/read', id: 2 });
|
|
}
|
|
} else if (message.id === 2) {
|
|
finish(message.error ? null : message.result);
|
|
}
|
|
};
|
|
|
|
child.on('error', () => finish(null));
|
|
child.on('close', () => finish(null));
|
|
child.stdin.on('error', () => finish(null));
|
|
child.stdout.on('data', (chunk: Buffer) => {
|
|
buffer += chunk.toString('utf8');
|
|
if (Buffer.byteLength(buffer) > APP_SERVER_MAX_OUTPUT_BYTES) return finish(null);
|
|
const lines = buffer.split(/\r?\n/);
|
|
buffer = lines.pop() ?? '';
|
|
for (const line of lines) handleLine(line);
|
|
});
|
|
|
|
send({
|
|
method: 'initialize',
|
|
id: 1,
|
|
params: {
|
|
clientInfo: { name: 'codeman', title: 'Codeman', version: clientVersion },
|
|
capabilities: null,
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/** Read the signed-in host account's main Codex limits without exposing credentials. */
|
|
export async function readCodexPlanUsage(
|
|
binaryPath: string,
|
|
clientVersion: string,
|
|
request: CodexRateLimitsRequest = requestCodexRateLimits
|
|
): Promise<StatusTelemetry | null> {
|
|
return parseCodexRateLimitsResponse(await request(binaryPath, clientVersion));
|
|
}
|