Files
Codeman/src/utils/cli-launcher.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

114 lines
5.4 KiB
TypeScript

/**
* @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;
}