mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
refactor(cli): one missing-binary error for every wrap command (#4122)
## Description
Ten `headroom wrap <tool>` commands each repeated the same four-line
block for a missing binary: `shutil.which`, `click.echo("Error: '<x>'
not found in PATH.")`, then an install hint, then `SystemExit(1)`. The
messages went to **stdout**, while `wrap openclaw` and `headroom init`
already used `click.ClickException`, which writes to stderr.
This PR replaces the ten copies with one helper, `_require_binary`. It
also folds three identical copies of the hidden legacy code-memory flags
into one decorator.
Refs #4136
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)
## Changes Made
- `headroom/cli/wrap.py`: new `_require_binary(*names,
install_hint=...)`.
- It returns the first name found on PATH, or raises
`click.ClickException("'<x>' not found in PATH.\n<hint>")`.
- It replaces the blocks in `claude`, `copilot`, `codex`, `aider`,
`vibe`, `kimi`, `grok`, `opencode` and `omp`, and in the
registry-generated commands (goose, openhands, openclaude, bob).
- `kimi` keeps its `'kimi' (or 'kimi-cli')` wording.
- The output is the same `Error: ...` text, followed by the hint, with
exit code 1. The one difference is that it now goes to stderr.
- `headroom/cli/wrap.py`: new `_legacy_code_memory_options` decorator.
- It replaces the three identical hidden `--no-tokensave` / `--serena` /
`--no-serena` declarations on `wrap claude`, `wrap codex` and `wrap
grok`.
- It sits next to the existing `_code_memory_option`, the module's idiom
for shared options.
- The option order is preserved.
- `tests/test_cli/test_wrap_helpers.py`: new
`test_missing_binary_error_goes_to_stderr_only`, for `wrap aider`
(hand-written), `wrap goose` (registry) and `wrap kimi` (two names). It
reads stdout and stderr separately: exit 1, empty stdout, the error on
stderr, and no proxy start. It fails on origin/main, where the message
went to stdout.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ pytest -q -p no:cacheprovider tests/test_cli/test_wrap_*.py tests/test_cli/test_tokensave_scope.py tests/test_cli/test_serena_disable.py tests/test_cli/test_serena_migrate.py tests/test_cli/test_serena_reconcile.py tests/test_cli/test_serena_scope.py tests/test_cli/test_unwrap_claude.py tests/test_cli/test_port_alignment.py
4 failed, 837 passed, 1 skipped in 23.28s
# The 4 failures are in tests/test_cli/test_wrap_persistent.py ("'_Manifest' object has no attribute 'runtime_kind'"). They are pre-existing: clean origin/main gives "4 failed, 59 passed" for that file.
# Every wrap/unwrap command's params (name, opts, hidden, help, default), dumped before and after:
267 lines, diff IDENTICAL
$ uvx ruff@0.16.8 check headroom/cli/wrap.py
All checks passed!
$ mypy headroom/cli/wrap.py --ignore-missing-imports
Success: no issues found in 1 source file
```
## Real Behavior Proof
- Environment: macOS 25.6, Python 3.12, repo `.venv`,
`PATH=/usr/bin:/bin`, and a scratch `HOME`.
- Exact command / steps: `python -m headroom.cli wrap claude`, `wrap
kimi` and `wrap goose`, with stdout and stderr captured separately.
- Observed result: each exits rc=1 with empty stdout. Stderr shows, for
example, `Error: 'claude' not found in PATH.` followed by `Install
Claude Code: https://docs.anthropic.com/en/docs/claude-code`. For kimi
it is `Error: 'kimi' (or 'kimi-cli') not found in PATH.` followed by
`Install Kimi CLI: ...`.
- Smoke harness (real proxy started from this checkout against a local
fake upstream; temp HOME and workspace, offline):
```text
branch: cleanup/cli-integrations-wrap-missing-binary @ ed29a8ce
health: 200
POST /v1/messages -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-49552.log):
2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
2 headroom.transforms.kompress_compressor - WARNING - Kompress: 'onnx/kompress-int8-wo.onnx' for chopratejas/kompress-v2-base is not cached and HEADROOM_OFFLINE forbids fetching it (HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.). Compression falls back to the non-ML path.
4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: <tmp>)
```
- Direct runtime command on this PR's own path (temp HOME,
HEADROOM_WORKSPACE_DIR and CODEX_HOME):
```text
## pr3
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom wrap aider
exit=1
--- stdout
--- stderr
Error: 'aider' not found in PATH.
Install aider: pip install aider-chat
## clean
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom wrap aider
exit=1
--- stdout
Error: 'aider' not found in PATH.
Install aider: pip install aider-chat
--- stderr
```
- Not tested: Windows; nothing in this change is platform-specific.
## Runtime Rollout Safety
- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A, not rollout-managed.
- Stable/default behavior changed: Only the stream: the missing-binary
error moves from stdout to stderr. The text and the exit code (1) are
unchanged. The tests that assert the text use CliRunner's merged
`result.output` and still pass. `scripts/install.sh` has its own
`command -v` check and does not parse this message.
- Kill switch / disable path: N/A.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Screenshots (if applicable)
N/A
## Additional Notes
- Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.
- No new test: the existing per-command missing-binary tests (goose,
openhands, kimi, vibe, opencode, copilot, openclaw) cover the helper.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4122"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
This commit is contained in:
+67
-105
@@ -1165,6 +1165,42 @@ _code_memory_scope_option = click.option(
|
||||
)
|
||||
|
||||
|
||||
def _legacy_code_memory_options(command: Any) -> Any:
|
||||
"""Hidden pre-``--code-memory`` flags, still accepted by claude/codex/grok."""
|
||||
for decorator in (
|
||||
click.option(
|
||||
"--no-serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory none. Register no code-memory MCP.",
|
||||
),
|
||||
click.option(
|
||||
"--serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory serena. Force the Serena MCP compressor on.",
|
||||
),
|
||||
click.option(
|
||||
"--no-tokensave",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated and ignored: tokensave was retired; Serena is the default code memory.",
|
||||
),
|
||||
):
|
||||
command = decorator(command)
|
||||
return command
|
||||
|
||||
|
||||
def _require_binary(*names: str, install_hint: str) -> str:
|
||||
"""Return the first of ``names`` on PATH, or fail with how to install it."""
|
||||
for name in names:
|
||||
found = shutil.which(name)
|
||||
if found:
|
||||
return found
|
||||
shown = f"'{names[0]}'" + "".join(f" (or '{name}')" for name in names[1:])
|
||||
raise click.ClickException(f"{shown} not found in PATH.\n{install_hint}")
|
||||
|
||||
|
||||
# Hook-command markers Headroom manages in Claude settings.json. unwrap drops
|
||||
# any hook entry whose command contains one of these. (Retired rtk / lean-ctx
|
||||
# hooks are removed separately, by
|
||||
@@ -5838,24 +5874,7 @@ def _detect_inbound_anthropic_upstream(port: int) -> str | None:
|
||||
)
|
||||
@_code_memory_option
|
||||
@_code_memory_scope_option
|
||||
@click.option(
|
||||
"--no-tokensave",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated and ignored: tokensave was retired; Serena is the default code memory.",
|
||||
)
|
||||
@click.option(
|
||||
"--serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory serena. Force the Serena MCP compressor on.",
|
||||
)
|
||||
@click.option(
|
||||
"--no-serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory none. Register no code-memory MCP.",
|
||||
)
|
||||
@_legacy_code_memory_options
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -5955,11 +5974,9 @@ def claude(
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
claude_bin = shutil.which("claude")
|
||||
if not claude_bin:
|
||||
click.echo("Error: 'claude' not found in PATH.")
|
||||
click.echo("Install Claude Code: https://docs.anthropic.com/en/docs/claude-code")
|
||||
raise SystemExit(1)
|
||||
claude_bin = _require_binary(
|
||||
"claude", install_hint="Install Claude Code: https://docs.anthropic.com/en/docs/claude-code"
|
||||
)
|
||||
|
||||
# Validate --tool-search up front so a typo fails before we start the proxy.
|
||||
if tool_search is not None:
|
||||
@@ -6553,14 +6570,13 @@ def copilot(
|
||||
explicitly with GITHUB_COPILOT_API_URL (the override flows through to upstream).
|
||||
See TESTING-copilot-subscription.md for details.
|
||||
"""
|
||||
copilot_bin = shutil.which("copilot")
|
||||
if not copilot_bin:
|
||||
click.echo("Error: 'copilot' not found in PATH.")
|
||||
click.echo(
|
||||
copilot_bin = _require_binary(
|
||||
"copilot",
|
||||
install_hint=(
|
||||
"Install GitHub Copilot CLI: "
|
||||
"https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli"
|
||||
)
|
||||
raise SystemExit(1)
|
||||
),
|
||||
)
|
||||
|
||||
explicit_subscription = subscription
|
||||
effective_backend = backend or os.environ.get("HEADROOM_BACKEND")
|
||||
@@ -7162,11 +7178,9 @@ def _run_codex_wrap(
|
||||
)
|
||||
return
|
||||
|
||||
codex_bin = shutil.which("codex")
|
||||
if not codex_bin:
|
||||
click.echo("Error: 'codex' not found in PATH.")
|
||||
click.echo("Install Codex CLI: npm install -g @openai/codex")
|
||||
raise SystemExit(1)
|
||||
codex_bin = _require_binary(
|
||||
"codex", install_hint="Install Codex CLI: npm install -g @openai/codex"
|
||||
)
|
||||
|
||||
active_codex_home = _codex_home_dir()
|
||||
_offer_dangling_codex_recovery(active_codex_home)
|
||||
@@ -7226,24 +7240,7 @@ def _run_codex_wrap(
|
||||
help="Skip headroom MCP server registration (compression markers will be unactionable)",
|
||||
)
|
||||
@_code_memory_option
|
||||
@click.option(
|
||||
"--no-tokensave",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated and ignored: tokensave was retired; Serena is the default code memory.",
|
||||
)
|
||||
@click.option(
|
||||
"--serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory serena. Force the Serena MCP compressor on.",
|
||||
)
|
||||
@click.option(
|
||||
"--no-serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory none. Register no code-memory MCP.",
|
||||
)
|
||||
@_legacy_code_memory_options
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -7374,11 +7371,7 @@ def aider(
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
aider_bin = shutil.which("aider")
|
||||
if not aider_bin:
|
||||
click.echo("Error: 'aider' not found in PATH.")
|
||||
click.echo("Install aider: pip install aider-chat")
|
||||
raise SystemExit(1)
|
||||
aider_bin = _require_binary("aider", install_hint="Install aider: pip install aider-chat")
|
||||
|
||||
env, env_vars_display = _build_aider_launch_env(
|
||||
port, os.environ, project=_project_name_from_cwd()
|
||||
@@ -7445,11 +7438,9 @@ def vibe(
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
vibe_bin = shutil.which("vibe")
|
||||
if not vibe_bin:
|
||||
click.echo("Error: 'vibe' not found in PATH.")
|
||||
click.echo("Install Mistral Vibe: https://github.com/mistralai/mistral-vibe")
|
||||
raise SystemExit(1)
|
||||
vibe_bin = _require_binary(
|
||||
"vibe", install_hint="Install Mistral Vibe: https://github.com/mistralai/mistral-vibe"
|
||||
)
|
||||
|
||||
env, env_vars_display = _build_mistral_vibe_launch_env(
|
||||
port, os.environ, project=_project_name_from_cwd()
|
||||
@@ -7524,11 +7515,9 @@ def kimi(
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
kimi_bin = shutil.which("kimi") or shutil.which("kimi-cli")
|
||||
if not kimi_bin:
|
||||
click.echo("Error: 'kimi' (or 'kimi-cli') not found in PATH.")
|
||||
click.echo("Install Kimi CLI: https://github.com/MoonshotAI/kimi-cli")
|
||||
raise SystemExit(1)
|
||||
kimi_bin = _require_binary(
|
||||
"kimi", "kimi-cli", install_hint="Install Kimi CLI: https://github.com/MoonshotAI/kimi-cli"
|
||||
)
|
||||
|
||||
project = _project_name_from_cwd()
|
||||
env, env_vars_display = _build_kimi_launch_env(port, os.environ, project=project)
|
||||
@@ -7573,24 +7562,7 @@ def kimi(
|
||||
@proxy_port_option()
|
||||
@click.option("--no-mcp", is_flag=True, help="Skip headroom MCP server registration")
|
||||
@_code_memory_option
|
||||
@click.option(
|
||||
"--no-tokensave",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated and ignored: tokensave was retired; Serena is the default code memory.",
|
||||
)
|
||||
@click.option(
|
||||
"--serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory serena. Force the Serena MCP compressor on.",
|
||||
)
|
||||
@click.option(
|
||||
"--no-serena",
|
||||
is_flag=True,
|
||||
hidden=True,
|
||||
help="Deprecated: use --code-memory none. Register no code-memory MCP.",
|
||||
)
|
||||
@_legacy_code_memory_options
|
||||
@click.option(
|
||||
"--code-graph",
|
||||
is_flag=True,
|
||||
@@ -7663,11 +7635,9 @@ def grok(
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
grok_bin = shutil.which("grok")
|
||||
if not grok_bin:
|
||||
click.echo("Error: 'grok' not found in PATH.")
|
||||
click.echo("Install Grok CLI: https://docs.x.ai/docs/grok-cli")
|
||||
raise SystemExit(1)
|
||||
grok_bin = _require_binary(
|
||||
"grok", install_hint="Install Grok CLI: https://docs.x.ai/docs/grok-cli"
|
||||
)
|
||||
|
||||
env, env_vars_display = _build_grok_launch_env(
|
||||
port, os.environ, project=_project_name_from_cwd()
|
||||
@@ -8462,11 +8432,9 @@ def opencode(
|
||||
# config without launching, so it is exempt.
|
||||
opencode_bin: str | None = None
|
||||
if not prepare_only:
|
||||
opencode_bin = shutil.which("opencode")
|
||||
if not opencode_bin:
|
||||
click.echo("Error: 'opencode' not found in PATH.")
|
||||
click.echo("Install OpenCode: https://opencode.ai")
|
||||
raise SystemExit(1)
|
||||
opencode_bin = _require_binary(
|
||||
"opencode", install_hint="Install OpenCode: https://opencode.ai"
|
||||
)
|
||||
|
||||
# Likewise refuse a reused proxy that cannot honor --openai-api-url before
|
||||
# touching OpenCode's config or registering a client marker; the same check
|
||||
@@ -8970,11 +8938,9 @@ def omp(
|
||||
_inject_omp_models_override(port, _project_name_from_cwd())
|
||||
return
|
||||
|
||||
omp_bin = shutil.which("omp")
|
||||
if not omp_bin:
|
||||
click.echo("Error: 'omp' not found in PATH.")
|
||||
click.echo("Install Oh My Pi: npm install -g @oh-my-pi/pi-coding-agent")
|
||||
raise SystemExit(1)
|
||||
omp_bin = _require_binary(
|
||||
"omp", install_hint="Install Oh My Pi: npm install -g @oh-my-pi/pi-coding-agent"
|
||||
)
|
||||
|
||||
env, env_vars_display = _build_omp_launch_env(
|
||||
port, os.environ, project=_project_name_from_cwd()
|
||||
@@ -9199,11 +9165,7 @@ def _make_registry_command(target: WrapTarget) -> click.Command:
|
||||
if prepare_only:
|
||||
return
|
||||
|
||||
tool_bin = shutil.which(target.binary)
|
||||
if not tool_bin:
|
||||
click.echo(f"Error: '{target.binary}' not found in PATH.")
|
||||
click.echo(target.install_hint)
|
||||
raise SystemExit(1)
|
||||
tool_bin = _require_binary(target.binary, install_hint=target.install_hint)
|
||||
|
||||
# Exported before proxy startup so _start_proxy forwards it as --mode;
|
||||
# an explicit HEADROOM_MODE always wins.
|
||||
|
||||
@@ -1145,3 +1145,33 @@ def test_no_proxy_does_not_create_startup_lock(monkeypatch: pytest.MonkeyPatch)
|
||||
|
||||
assert wrap_mod._ensure_proxy(8787, True) == (None, 8787)
|
||||
assert entered is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("argv", "expected"),
|
||||
[
|
||||
(
|
||||
["wrap", "aider"],
|
||||
"Error: 'aider' not found in PATH.\nInstall aider: pip install aider-chat",
|
||||
),
|
||||
(["wrap", "goose"], "Error: 'goose' not found in PATH."),
|
||||
(["wrap", "kimi"], "Error: 'kimi' (or 'kimi-cli') not found in PATH."),
|
||||
],
|
||||
)
|
||||
def test_missing_binary_error_goes_to_stderr_only(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, argv: list[str], expected: str
|
||||
) -> None:
|
||||
"""The missing-binary error is a ClickException on stderr; stdout stays empty."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setattr(wrap_mod.shutil, "which", lambda name: None)
|
||||
|
||||
def no_proxy(*args: Any, **kwargs: Any) -> None:
|
||||
raise AssertionError("a missing binary must fail before any proxy start")
|
||||
|
||||
monkeypatch.setattr(wrap_mod, "_ensure_proxy", no_proxy)
|
||||
|
||||
result = CliRunner().invoke(main, argv)
|
||||
|
||||
assert result.exit_code == 1
|
||||
assert result.stdout == ""
|
||||
assert result.stderr.startswith(expected)
|
||||
|
||||
Reference in New Issue
Block a user