mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-06 07:29:42 +02:00
* feat(cli-registry): add cliManagementEnabled flag and GET /api/clis
Phases 1-2 of docs/cli-enable-disable-plan.md ("PR C" from the #343
review): a synced, default-OFF master flag gating the upcoming CLI
management surface, plus a read-only GET /api/clis endpoint listing
every registry entry (stock + custom, enabled or not) for the
Settings UI. Non-admins in multi-user mode see an empty list rather
than a 403. Write endpoints, auto-install, custom entry CRUD and the
Settings UI list itself land in later phases.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* feat(cli-registry): Phases 3-6 - write API + custom entries + Settings UI
Completes docs/cli-enable-disable-plan.md ("PR C" from the #343 review).
Phase 3: PUT /api/clis/:id toggles enabled for any EXISTING entry (stock or
custom) via a shallow merge onto its clis.json override; shell/claude are
structurally un-disableable (Decision 4), an unknown id 404s rather than
becoming a creation backdoor.
Phase 4: POST /api/clis/:id/install runs a STOCK entry's already-vetted
install command (shell:true, bounded by timeout, process-group killed on
expiry, output captured, audit-logged). A custom entry's id is refused
outright, independent of anything Phase 5 does (Decision 3: a custom
entry's install text is display-only, never executed).
Phase 5: POST /api/clis (create) / PUT /api/clis/custom/:id (update) /
DELETE /api/clis/:id (custom only) — a deliberately minimal request shape
(id/label/shortBadge/binaries/a simple launch variant), assembled into a
full CliEntry with conservative capability defaults and re-validated
through CliEntrySchema before writing, never a relaxed path for
UI-originated entries. Stock-id collisions, duplicate custom ids, and
edits/deletes against a stock id are all rejected explicitly.
Phase 6: the Settings UI section (App Settings -> Agents & CLIs), gated
independently on cliManagementEnabled AND admin-in-multi-user-mode
(Decision 5), fetching/rendering GET /api/clis and wiring every write
endpoint above.
Every write endpoint answers the same way when the feature is off: 403
FORBIDDEN via one shared requireCliManagementGate() (Phase 1's own
checklist item). registry-writer.ts is a new, deliberately separate write
module so registry.ts itself stays import-side-effect-free, same tmp+
rename+0600 shape as custom-model-hosts.ts.
27 new/updated route tests covering every gate, collision, and cleanup
path; full CI gate green (415/416 files, 7854 tests).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* fix(cli-registry): toggling a CLI off in Settings never hid it anywhere else
window.__codemanCliAvailable — the flag isCliAvailable() reads client-side
to gate the welcome-screen buttons, the Run-menu dropdown and the mobile
overview — was built purely from each CLI's own installed-on-PATH resolver
(isClaudeAvailable() etc.), with no reference to the registry's `enabled`
flag at all. So disabling a CLI via the new Settings UI (or a hand-edited
clis.json) updated the settings row and nothing else: every launch surface
kept offering it, both live and after a full page reload, since even a
fresh render never consulted the registry.
Fixed in two places:
- server.ts: after building `available`, intersect the nine real
SessionMode ids against `enabledClis()`. git/cloudflared (utility
binaries, not CLI registry entries) and deepseekBinary (a secondary
installed-only flag for the "add a profile" affordance) are deliberately
left alone.
- settings-ui.js: `toggleCliEnabled()` now patches
`window.__codemanCliAvailable` in place and refreshes the welcome screen,
the mobile overview and an already-open Run menu, mirroring the existing
`installDeepSeekProfile()` pattern for the same "injected once, needs an
explicit patch" reason — without this half, the server-side fix alone
still left every surface stale until the next reload.
New test in test/render-index-html.test.ts: an installed-but-disabled CLI
(codex, forced via clis.json + reloadCliRegistry()) reads as unavailable,
while an installed-and-enabled one (claude) is unaffected by the override.
Verified on the Debian devbox (codeman-devbox, real tmux — this sandbox has
none and WebServer's constructor hard-requires it): typecheck clean, the
new test passes (17/17 in render-index-html.test.ts), the CLI-registry
suites pass (86/86), and the full CI gate is green (415 test files, 7855
tests, 0 failures).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N6eadpRyqpA9PD3i139cSD
* docs(cli-registry): update the CLI-management plan with status, gotchas, and the Run-menu gap
Phases 1-6 were implemented across two commits (da07b38c, db4557d9) with no
corresponding update to the plan doc itself — every checklist still read
Status: TODO and every box unchecked. Brings the doc in line with the tree:
- A new "Status as of 2026-09-22" section up top: what's actually
implemented (verified by grepping the routes/schema/UI, not just trusting
the commit messages), the availability-flag staleness bug found and fixed
in this session (commit 0c77dd0a) with its devbox verification record, and
one real outstanding gap.
- The outstanding gap: a custom CLI created via Phase 5's write API has no
way to actually be launched. The Run menu is static per-mode markup with
no consumer of window.__codemanCliCatalog, so Phase 6's own "create a
custom entry, confirm it can be launched" verify step was never actually
exercised against this. Documented with two candidate fixes, neither
started.
- Each phase's checklist flipped to [x] where confirmed present in the tree,
Status lines updated from TODO to DONE, and the two originally-open
questions (Phase 2's installed source, Phase 5's PUT endpoint shape)
marked resolved against what actually shipped.
No code changes in this commit — documentation only, so a future session
(or the one already mid-flight on a separate checkout of this same branch)
picks up accurate status instead of a stale plan.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N6eadpRyqpA9PD3i139cSD
* docs: add the CLI-registry deployment plan and the parked Copilot plan
Both were sitting as untracked scratch files in the master checkout,
never committed to any branch. Moving them here rather than leaving them
loose:
- DEPLOYMENT_PLAN.md is the live tracker for the CLI-registry follow-up
series (PR A #347 merged, PR B #380 merged, PR B2 merged as #458) and
is where PR C (this branch's own CLI-management work) belongs.
- docs/copilot-integration-plan.md is explicitly PARKED, referenced by
name in docs/cli-enable-disable-plan.md's own header as a sibling plan
tracked separately — kept for continuity, not active on this branch.
The other scratch files found alongside these (PRA.md, PRB.md, PR-B2.md
and their review-response counterparts) described PR A/B/B2, all now
merged — deleted from the master checkout as stale rather than committed
anywhere, since their content is superseded by the real merged PRs.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N6eadpRyqpA9PD3i139cSD
* fix(cli-registry): render enabled CLIs in launch surfaces
* test(cli-registry): update frontend branch guard
* fix(test): isolate suite from deployment environment
* fix(cli-registry): revise Decision 4 - claude is toggleable, shell stays permanent
shell/claude were both structurally un-disableable in the original plan
(Decision 4). Revised: shell keeps the hard backend guarantee (it is the
one non-agent mode several code paths assume always exists as a raw-
terminal fallback), but claude is now a normal toggleable entry like any
other CLI.
Safe to do because internal session creation (tmux-manager.ts, session.ts,
Ralph, plan-orchestrator) resolves a CLI via getCli(), which does not
check `enabled` at all - only the Run menu and the HTTP-facing
sessionModeSchema() (new session requests through the normal API) key off
it. Disabling claude therefore behaves identically in kind to disabling
any other CLI: no internal fallback path breaks, it just stops being
offered for new sessions until re-enabled.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* fix(cli-registry): hide shell's toggle entirely instead of greying it out
A permanently-disabled switch next to every other row's working toggle
read as broken rather than intentional. shell now renders no switch at
all - a plain "Always available" label - so there is nothing to click
that could look like it should work but doesn't. Backend guard is
unchanged (UNDISABLEABLE_IDS still refuses shell unconditionally); this
is UI-only.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* fix(cli-registry): sort the Installed CLIs list, installed-first then alphabetical
renderCliList() previously rendered in registry order (each entry's fixed
order field). Now sorts installed CLIs first, then not-installed, each
group alphabetical by label - matches how a user actually scans the list
(what's ready to use, then what needs installing).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* style: prettier fixes from the master merge
* fix(cli-registry): install/edit take effect immediately, confirm before install, phone labels
Four gaps found verifying #476 against the #343 review trail:
- Installed or edited CLIs kept reading as missing/stale. Every binary lookup
(the nine per-CLI resolvers and the generic registry one) caches in its own
closure, with a negative-cache backoff of up to 5 minutes, and nothing
cleared them. invalidateCliExecutableResolvers(binaries) now drops those
caches per binary; install (success or failure), create, edit and delete
call it plus invalidateCliResolverCache(id). Before this, a CLI installed
from Settings could fail to launch for minutes, and an edited custom entry
kept launching its old binary until a restart.
- The Settings "installed" badge for a custom entry used a private `which`,
ignoring the entry's searchDirs and the login-shell lookup that spawn and
the Run menu use; it now asks the same generic resolver they do.
- Install ran on a single click. The #343 review asked for auto-install to
sit behind an explicit confirm; the confirm now names the exact command,
which GET /api/clis returns for stock entries only (installCommand).
- The phone Run button showed the two-letter tab badge ("CC", "CX") instead
of the word ("Claude", "Codex"). It uses the registry label again, which is
identical to the old static table for every stock CLI (now pinned).
14 new tests; 9 of them fail against the previous head and pass here.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* fix(cli-registry): address #476 review — safe serialized writes, no id branches, docs
Must-fix:
- registry-writer: start fresh only on ENOENT; refuse (409) a clis.json that
does not parse or has group/world permission bits instead of overwriting it
(isUnsafePermissions now exported from registry.ts)
- mutateRegistryFile(): one promise chain for every mutation, with the
existence/duplicate checks inside the serialized step, plus a unique tmp
name per write
- docs: CLAUDE.md, architecture-invariants, cli-registry (new Settings
section) and api-reference (the six /api/clis routes)
- drop DEPLOYMENT_PLAN.md and docs/copilot-integration-plan.md
Smaller:
- PUT /api/clis/custom/:id keeps the entry's current enabled state when the
body omits it
- runMode setter falls back to the first enabled catalogue entry, not 'claude'
- shell guard keyed on kind === 'shell' (routes + Settings list); stock probe
map shared with server.ts via utils/cli-installed-probes.ts
- stock claude label is now 'Claude Code', so the Run menu / phone overview
label rewrites are gone (doctor row keeps "Claude CLI" via its override)
- welcome buttons are translatable again and read "Run Claude Code" /
"Run Shell"; zh-CN gains "Run Codex" / "Run OMP"
- install: per-id in-flight guard (409) and CODEMAN_* stripped from its env
- fileoverview / CliEnableSchema comments no longer say stock-only
- test-env isolation changes moved to their own PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
* test(cli-registry): pin the #343/#347 findings #476 makes reachable
A CLI toggled or created through the routes is accepted or rejected by
CreateSessionSchema with no restart (#343 finding 2), and a custom CLI created
through the API renders a real local, remote and docker launch command
(#347 finding 5: no more `cd <path> && undefined`).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
249 lines
10 KiB
TypeScript
249 lines
10 KiB
TypeScript
/**
|
|
* @fileoverview Loads, merges and re-validates the CLI registry.
|
|
*
|
|
* `~/.codeman/clis.json` holds OVERRIDES and CUSTOM entries only — never a full copy of the
|
|
* stock catalog — so a shipped fix to a stock definition actually reaches an existing
|
|
* install, and the file stays small enough to hand-edit.
|
|
*
|
|
* Resolution: start from `STOCK_CLIS` → deep-merge each override by id (objects merge
|
|
* key-wise, arrays replace wholesale) → validate every resulting entry. A stock entry that
|
|
* fails validation after merge falls back to its pristine stock definition (a fat-fingered
|
|
* override cannot brick a shipped CLI); a custom entry that fails is dropped with a warning
|
|
* rather than failing the whole load. Stock entries are always emitted, so `shell` and
|
|
* `claude` can be disabled but can never go missing — large parts of the app assume at
|
|
* minimum that a shell fallback exists.
|
|
*
|
|
* ⚠️ READ-ONLY. Nothing in this module writes, creates or migrates the file. That is a
|
|
* deliberate property, not a missing feature: there is no settings UI and no write API yet,
|
|
* so there is nothing to persist, and it means importing the registry — which
|
|
* `src/web/schemas.ts` does, transitively, just to validate a request — performs no
|
|
* filesystem writes. A `seededStockIds` ratchet belongs with the write API that needs it.
|
|
* The one exception is the quarantine RENAME of a file that fails to parse (see
|
|
* `readRegistryFile`), which happens on first use rather than at import.
|
|
*
|
|
* ⚠️ The file must be mode 0600. `isUnsafePermissions` refuses ANY group/world bit, read
|
|
* bits included, so a file created with a normal umask (0644) is ignored. Every reason the
|
|
* file was ignored, or an entry in it dropped, is logged ONCE on first load: the warnings
|
|
* used to be returned to a caller that nobody wired up, so a normally-created file was
|
|
* ignored with no feedback anywhere (found reviewing #347).
|
|
*
|
|
* @module config/cli-registry/registry
|
|
*/
|
|
|
|
import { existsSync, readFileSync, renameSync, statSync } from 'node:fs';
|
|
import { dataPath } from '../instance.js';
|
|
import type { CliEntry, CliId, CliRegistryFile } from './types.js';
|
|
import { CliEntrySchema } from './schema.js';
|
|
import { STOCK_CLIS } from './stock.js';
|
|
|
|
/** Construct a validated CliId. Throws if `raw` is not a well-formed id — call at API boundaries. */
|
|
export function asCliId(raw: string): CliId {
|
|
if (!/^[a-z][a-z0-9-]{0,23}$/.test(raw)) {
|
|
throw new Error(`invalid CLI id: ${JSON.stringify(raw)}`);
|
|
}
|
|
return raw as CliId;
|
|
}
|
|
|
|
function filePath(): string {
|
|
return dataPath('clis.json');
|
|
}
|
|
|
|
/**
|
|
* The resolved path of `~/.codeman/clis.json`, exported for the write API
|
|
* (`cli-registry-writer.ts`, docs/cli-enable-disable-plan.md Phases 3/5) so both the read and
|
|
* write sides resolve the SAME path through the SAME instance-scoped helper — never a second
|
|
* `dataPath('clis.json')` call that could drift from this one under a future `dataPath()` change.
|
|
*/
|
|
export function registryFilePath(): string {
|
|
return filePath();
|
|
}
|
|
|
|
/**
|
|
* Keys that must never be merged out of a hand-editable JSON file.
|
|
*
|
|
* `JSON.parse` produces `__proto__` as an ORDINARY own property, but `result[key] = …` on a
|
|
* plain object walks the setter chain and would set the merged object's PROTOTYPE instead.
|
|
* Not exploitable today — every merged entry is spread into `{ ...merged, id, stock }` and
|
|
* then Zod-parsed before anything reads it, which drops the effect — but "not exploitable
|
|
* because of what a caller happens to do afterwards" is a property that quietly stops
|
|
* holding. A `continue` in the loop that reads the file is the cheap end of that trade.
|
|
*/
|
|
const UNMERGEABLE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
|
|
/** Plain-object deep merge: nested objects merge key-wise, arrays and primitives replace. */
|
|
function deepMerge<T>(base: T, override: unknown): T {
|
|
if (override === null || typeof override !== 'object' || Array.isArray(override)) {
|
|
return (override === undefined ? base : (override as T)) ?? base;
|
|
}
|
|
if (base === null || typeof base !== 'object' || Array.isArray(base)) {
|
|
return override as T;
|
|
}
|
|
const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };
|
|
for (const [key, value] of Object.entries(override as Record<string, unknown>)) {
|
|
if (UNMERGEABLE_KEYS.has(key)) continue;
|
|
result[key] = deepMerge((base as Record<string, unknown>)[key], value);
|
|
}
|
|
return result as T;
|
|
}
|
|
|
|
export interface LoadResult {
|
|
entries: CliEntry[];
|
|
warnings: string[];
|
|
}
|
|
|
|
/**
|
|
* Refuse a registry file with any group/world permission bit — same posture as the ssh-key
|
|
* discipline, so 0600 is the only accepted mode. This file selects the binaries Codeman
|
|
* spawns, so a writable one is a way to redirect every session.
|
|
*
|
|
* POSIX only: Windows has no meaningful group/world bits on NTFS (Node reports every file
|
|
* as mode 0o666 there regardless of its actual ACL), so this check would flag every file on
|
|
* Windows and silently ignore all user config. `win32` relies on NTFS ACLs instead, which
|
|
* this check cannot see and does not attempt to.
|
|
*
|
|
* Exported for `registry-writer.ts`, which must refuse the same files: rewriting a refused
|
|
* file as 0600 would silently turn it into trusted config.
|
|
*/
|
|
export function isUnsafePermissions(path: string): boolean {
|
|
if (process.platform === 'win32') return false;
|
|
try {
|
|
const mode = statSync(path).mode & 0o777;
|
|
return (mode & 0o077) !== 0;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function readRegistryFile(path: string, warnings: string[]): CliRegistryFile | null {
|
|
if (!existsSync(path)) return null;
|
|
if (isUnsafePermissions(path)) {
|
|
warnings.push(
|
|
`${path} must be mode 0600 (no group/world permission bits; run \`chmod 600 ${path}\`); ignoring it and falling back to stock CLIs.`
|
|
);
|
|
return null;
|
|
}
|
|
let raw: string;
|
|
try {
|
|
raw = readFileSync(path, 'utf-8');
|
|
} catch (err) {
|
|
warnings.push(`Failed to read ${path}: ${(err as Error).message}. Falling back to stock CLIs.`);
|
|
return null;
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(raw) as CliRegistryFile;
|
|
if (typeof parsed !== 'object' || parsed === null || typeof parsed.clis !== 'object') {
|
|
throw new Error('missing "clis" object');
|
|
}
|
|
return parsed;
|
|
} catch (err) {
|
|
// QUARANTINE, never overwrite: the file is hand-editable, so a syntax error is far more
|
|
// likely to be a half-finished edit than junk. Renaming keeps the user's work.
|
|
const quarantined = `${path}.invalid-${Date.now()}`;
|
|
try {
|
|
renameSync(path, quarantined);
|
|
warnings.push(`${path} was not valid JSON (${(err as Error).message}); moved to ${quarantined}.`);
|
|
} catch {
|
|
warnings.push(
|
|
`${path} was not valid JSON (${(err as Error).message}); left in place, falling back to stock CLIs.`
|
|
);
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Merge the stock catalog with a (possibly absent) registry file. PURE — no IO, which is
|
|
* what lets the load tests drive every merge case directly.
|
|
*/
|
|
export function resolveRegistry(stock: CliEntry[], file: CliRegistryFile | null, warnings: string[]): LoadResult {
|
|
const stockById = new Map(stock.map((e) => [e.id as string, e]));
|
|
const overrides = file?.clis ?? {};
|
|
const entries: CliEntry[] = [];
|
|
|
|
for (const stockEntry of stock) {
|
|
const id = stockEntry.id as string;
|
|
const override = overrides[id];
|
|
const merged = override ? deepMerge(stockEntry, override) : stockEntry;
|
|
// `stock: true` is forced here rather than read from the merged object, so an override
|
|
// can never flip a custom entry's provenance or vice versa.
|
|
const parsed = CliEntrySchema.safeParse({ ...merged, id, stock: true });
|
|
if (parsed.success) {
|
|
entries.push(parsed.data as CliEntry);
|
|
} else {
|
|
warnings.push(
|
|
`Override for stock CLI "${id}" failed validation; using the shipped definition. ${parsed.error.message}`
|
|
);
|
|
entries.push(stockEntry);
|
|
}
|
|
}
|
|
|
|
for (const [id, raw] of Object.entries(overrides)) {
|
|
if (stockById.has(id)) continue; // already merged above
|
|
// Same forcing in the other direction: a custom entry claiming `stock: true` cannot
|
|
// shadow or impersonate a shipped one.
|
|
const parsed = CliEntrySchema.safeParse({ ...(raw as object), id, stock: false });
|
|
if (parsed.success) {
|
|
entries.push(parsed.data as CliEntry);
|
|
} else {
|
|
warnings.push(`Custom CLI "${id}" failed validation and was dropped. ${parsed.error.message}`);
|
|
}
|
|
}
|
|
|
|
entries.sort((a, b) => a.order - b.order);
|
|
return { entries, warnings };
|
|
}
|
|
|
|
let cache: LoadResult | null = null;
|
|
|
|
/**
|
|
* Load the effective registry (stock + user overrides). Memoized for the process lifetime;
|
|
* `reloadCliRegistry()` invalidates.
|
|
*/
|
|
export function loadCliRegistry(): LoadResult {
|
|
if (cache) return cache;
|
|
const warnings: string[] = [];
|
|
const existing = readRegistryFile(filePath(), warnings);
|
|
cache = resolveRegistry(STOCK_CLIS, existing, warnings);
|
|
// Once per process (the result is memoized): silence here is what made a 0644 file look
|
|
// like "the override feature does nothing".
|
|
for (const warning of warnings) console.warn(`[cli-registry] ${warning}`);
|
|
return cache;
|
|
}
|
|
|
|
/** Drop the memoized registry so the next `loadCliRegistry()` re-reads the file. */
|
|
export function reloadCliRegistry(): void {
|
|
cache = null;
|
|
}
|
|
|
|
export function listClis(): CliEntry[] {
|
|
return loadCliRegistry().entries;
|
|
}
|
|
|
|
export function enabledClis(): CliEntry[] {
|
|
return listClis().filter((e) => e.enabled);
|
|
}
|
|
|
|
export function getCli(id: string): CliEntry | undefined {
|
|
return listClis().find((e) => (e.id as string) === id);
|
|
}
|
|
|
|
export function cliIds(): string[] {
|
|
return listClis().map((e) => e.id as string);
|
|
}
|
|
|
|
/** Every enabled entry's id, in registry order. */
|
|
export function enabledCliIds(): string[] {
|
|
return enabledClis().map((e) => e.id as string);
|
|
}
|
|
|
|
/**
|
|
* Resolve the install command for the current platform, falling back to the linux one (the
|
|
* common case for a `curl | bash` or `npm install -g` line) and then to whatever is
|
|
* declared. Display text only — never executed. See CliDiscovery.install.command.
|
|
*/
|
|
export function resolveInstallCommandForPlatform(entry: CliEntry): string | undefined {
|
|
const { command } = entry.discovery.install;
|
|
const platform = process.platform as 'linux' | 'darwin' | 'win32';
|
|
return command[platform] ?? command.linux ?? Object.values(command)[0];
|
|
}
|