Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
refactor(wrap): generate goose/openhands/openclaude from a WrapTarget registry (#3800)
trs-80de4cf7e7a1ec
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex b670d81ab..5860a4c84 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -186,6 +186,8 @@ from headroom.providers.opencode.config import (snapshot_opencode_config_if_unwrapped,strip_opencode_headroom_blocks,)+from headroom.providers.wrap_registry import WRAP_TARGETS, WrapTarget+from headroom.providers.wrap_registry import build_launch_env as _build_registry_launch_envfrom headroom.providers.zcode import (detect_upstream as _detect_zcode_upstream,)@@ -6627,86 +6629,6 @@ def aider()-# =============================================================================-# OpenClaude-# =============================================================================--[email protected](context_settings={"ignore_unknown_options": True})-@_retired_context_tool_option[email protected]("--port", "-p", default=8787, type=int, help="Proxy port (default: 8787)")- "--code-graph",- is_flag=True,- help="Enable code graph indexing via codebase-memory-mcp (optional)",-)[email protected]("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")[email protected]("--learn", is_flag=True, help="Enable live traffic learning")[email protected]("--memory", is_flag=True, help="Enable persistent cross-session memory")- "--backend", default=None, help="API backend: 'anthropic', 'anyllm', 'litellm-vertex', etc."-)[email protected]("--anyllm-provider", default=None, help="Provider for any-llm backend")[email protected]("--region", default=None, help="Cloud region for Bedrock/Vertex")[email protected]("--verbose", "-v", is_flag=True, help="Verbose output")[email protected]("--prepare-only", is_flag=True, hidden=True)[email protected]("openclaude_args", nargs=-1, type=click.UNPROCESSED)-def openclaude(- port: int,- code_graph: bool,- no_proxy: bool,- learn: bool,- memory: bool,- backend: str | None,- anyllm_provider: str | None,- region: str | None,- verbose: bool,- prepare_only: bool,- openclaude_args: tuple,-) -> None:- """Launch OpenClaude through Headroom proxy.-- \b- OpenClaude is a prose-format coding CLI (like Aider / Cline); it speaks- OpenAI- and Anthropic-compatible HTTP, so wrap routes both base URLs- through the local proxy — same env shape as `wrap aider`.-- \b- Examples:- headroom wrap openclaude # Start proxy + openclaude- headroom wrap openclaude -- --model gpt-4o # Pass args to openclaude- """- if prepare_only:- return-- openclaude_bin = shutil.which("openclaude")- if not openclaude_bin:- click.echo("Error: 'openclaude' not found in PATH.")- click.echo("Install OpenClaude before running `headroom wrap openclaude`.")- raise SystemExit(1)-- env, env_vars_display = _build_aider_launch_env(- port, os.environ, project=_project_name_from_cwd()- )-- _launch_tool(- binary=openclaude_bin,- args=openclaude_args,- env=env,- port=port,- no_proxy=no_proxy,- tool_label="OPENCLAUDE",- env_vars_display=env_vars_display,- learn=learn,- memory=memory,- agent_type="openclaude",- code_graph=code_graph,- backend=backend,- anyllm_provider=anyllm_provider,- region=region,- )--# =============================================================================# Mistral Vibe# =============================================================================@@ -7341,190 +7263,6 @@ def continue_dev()-# =============================================================================-# Goose (Block)-# =============================================================================--[email protected](context_settings={"ignore_unknown_options": True})-@_retired_context_tool_option- "--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"-)- "--code-graph",- is_flag=True,- help="Enable code graph indexing via codebase-memory-mcp (optional)",-)[email protected]("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")[email protected]("--learn", is_flag=True, help="Enable live traffic learning")[email protected]("--memory", is_flag=True, help="Enable persistent cross-session memory")- "--backend", default=None, help="API backend: 'anthropic', 'anyllm', 'litellm-vertex', etc."-)[email protected]("--anyllm-provider", default=None, help="Provider for any-llm backend")[email protected]("--region", default=None, help="Cloud region for Bedrock/Vertex")[email protected]("--verbose", "-v", is_flag=True, help="Verbose output")[email protected]("--prepare-only", is_flag=True, hidden=True)[email protected]("goose_args", nargs=-1, type=click.UNPROCESSED)-def goose(- port: int,- code_graph: bool,- no_proxy: bool,- learn: bool,- memory: bool,- backend: str | None,- anyllm_provider: str | None,- region: str | None,- verbose: bool,- prepare_only: bool,- goose_args: tuple,-) -> None:- """Launch Goose (Block) CLI through Headroom proxy.-- \b- Sets OPENAI_BASE_URL and ANTHROPIC_BASE_URL to route Goose's API calls- through Headroom.-- \b- Uninstall: there is no ``headroom unwrap goose`` subcommand — nothing is- written to the project.-- \b- Examples:- headroom wrap goose # Start proxy + goose- headroom wrap goose -- session # Start a Goose session- headroom wrap goose -- --provider anthropic # Pass args to goose- """- if prepare_only:- return-- goose_bin = shutil.which("goose")- if not goose_bin:- click.echo("Error: 'goose' not found in PATH.")- click.echo("Install Goose: https://block.github.io/goose/")- raise SystemExit(1)-- # Goose accepts OpenAI- and Anthropic-compatible providers; route both.- env = os.environ.copy()- openai_base = f"http://127.0.0.1:{port}/v1"- anthropic_base = _claude_proxy_base_url(port)- env["OPENAI_BASE_URL"] = openai_base- env["OPENAI_API_BASE"] = openai_base- env["ANTHROPIC_BASE_URL"] = anthropic_base- env_vars_display = [- f"OPENAI_BASE_URL={openai_base}",- f"ANTHROPIC_BASE_URL={anthropic_base}",- ]-- _launch_tool(- binary=goose_bin,- args=goose_args,- env=env,- port=port,- no_proxy=no_proxy,- tool_label="GOOSE",- env_vars_display=env_vars_display,- learn=learn,- memory=memory,- agent_type="goose",- code_graph=code_graph,- backend=backend,- anyllm_provider=anyllm_provider,- region=region,- )---# =============================================================================-# OpenHands-# =============================================================================--[email protected](context_settings={"ignore_unknown_options": True})-@_retired_context_tool_option- "--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"-)- "--code-graph",- is_flag=True,- help="Enable code graph indexing via codebase-memory-mcp (optional)",-)[email protected]("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")[email protected]("--learn", is_flag=True, help="Enable live traffic learning")[email protected]("--memory", is_flag=True, help="Enable persistent cross-session memory")- "--backend", default=None, help="API backend: 'anthropic', 'anyllm', 'litellm-vertex', etc."-)[email protected]("--anyllm-provider", default=None, help="Provider for any-llm backend")[email protected]("--region", default=None, help="Cloud region for Bedrock/Vertex")[email protected]("--verbose", "-v", is_flag=True, help="Verbose output")[email protected]("--prepare-only", is_flag=True, hidden=True)[email protected]("openhands_args", nargs=-1, type=click.UNPROCESSED)-def openhands(- port: int,- code_graph: bool,- no_proxy: bool,- learn: bool,- memory: bool,- backend: str | None,- anyllm_provider: str | None,- region: str | None,- verbose: bool,- prepare_only: bool,- openhands_args: tuple,-) -> None:- """Launch OpenHands CLI through Headroom proxy.-- \b- Sets OPENAI_BASE_URL / ANTHROPIC_BASE_URL to route OpenHands' API calls- through Headroom. Nothing is written to disk, so there is nothing to undo.-- \b- Examples:- headroom wrap openhands # Start proxy + openhands- headroom wrap openhands -- --task ... # Pass args to openhands- """- if prepare_only:- return-- openhands_bin = shutil.which("openhands")- if not openhands_bin:- click.echo("Error: 'openhands' not found in PATH.")- click.echo("Install OpenHands: https://docs.all-hands.dev/")- raise SystemExit(1)-- env = os.environ.copy()- openai_base = f"http://127.0.0.1:{port}/v1"- anthropic_base = _claude_proxy_base_url(port)- env["OPENAI_BASE_URL"] = openai_base- env["OPENAI_API_BASE"] = openai_base- env["ANTHROPIC_BASE_URL"] = anthropic_base- # Also set LLM_BASE_URL for OpenHands' generic LLM provider config.- env["LLM_BASE_URL"] = openai_base- env_vars_display = [- f"OPENAI_BASE_URL={openai_base}",- f"ANTHROPIC_BASE_URL={anthropic_base}",- f"LLM_BASE_URL={openai_base}",- ]- _launch_tool(- binary=openhands_bin,- args=openhands_args,- env=env,- port=port,- no_proxy=no_proxy,- tool_label="OPENHANDS",- env_vars_display=env_vars_display,- learn=learn,- memory=memory,- agent_type="openhands",- code_graph=code_graph,- backend=backend,- anyllm_provider=anyllm_provider,- region=region,- )--# =============================================================================# OpenClaw# =============================================================================@@ -8509,3 +8247,101 @@ def unwrap_zcode(port: int, no_stop_proxy: bool) -> None:if not no_stop_proxy:_echo_unwrap_proxy_stop_status(_stop_local_proxy_for_unwrap(port), port)click.echo()+++# =============================================================================+# Registry-generated wrap commands+# =============================================================================+# Env-var tools are described declaratively in headroom.providers.wrap_registry;+# one click command per WrapTarget is generated here.+++def _make_registry_command(target: WrapTarget) -> click.Command:+ def _run(+ port: int,+ code_graph: bool,+ no_proxy: bool,+ learn: bool,+ memory: bool,+ backend: str | None,+ anyllm_provider: str | None,+ region: str | None,+ verbose: bool,+ prepare_only: bool,+ tool_args: tuple,+ ) -> None:+ 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)++ env, env_vars_display = _build_registry_launch_env(+ target,+ port,+ os.environ,+ project=_project_name_from_cwd() if target.project_prefix else None,+ )++ _launch_tool(+ binary=tool_bin,+ args=tool_args,+ env=env,+ port=port,+ no_proxy=no_proxy,+ tool_label=target.name.upper(),+ env_vars_display=env_vars_display,+ learn=learn,+ memory=memory,+ agent_type=target.name,+ code_graph=code_graph,+ backend=backend,+ anyllm_provider=anyllm_provider,+ region=region,+ )++ _run.__doc__ = target.help_text+ command: Any = _run+ # Same option surface as the hand-written commands these replaced.+ for decorator in (+ click.argument(+ "tool_args",+ nargs=-1,+ type=click.UNPROCESSED,+ metavar=f"[{target.name.upper()}_ARGS]...",+ ),+ click.option("--prepare-only", is_flag=True, hidden=True),+ click.option("--verbose", "-v", is_flag=True, help="Verbose output"),+ click.option("--region", default=None, help="Cloud region for Bedrock/Vertex"),+ click.option("--anyllm-provider", default=None, help="Provider for any-llm backend"),+ click.option(+ "--backend",+ default=None,+ help="API backend: 'anthropic', 'anyllm', 'litellm-vertex', etc.",+ ),+ click.option("--memory", is_flag=True, help="Enable persistent cross-session memory"),+ click.option("--learn", is_flag=True, help="Enable live traffic learning"),+ click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)"),+ click.option(+ "--code-graph",+ is_flag=True,+ help="Enable code graph indexing via codebase-memory-mcp (optional)",+ ),+ click.option(+ "--port",+ "-p",+ default=8787,+ type=click.IntRange(1, 65535),+ help="Proxy port (default: 8787)",+ ),+ _retired_context_tool_option,+ ):+ command = decorator(command)+ return click.command(target.name, context_settings={"ignore_unknown_options": True})(command)+++for _target in WRAP_TARGETS.values():+ wrap.add_command(_make_registry_command(_target))diff --git a/headroom/providers/wrap_registry.py b/headroom/providers/wrap_registry.pynew file mode 100644index 000000000..8efc6e6f3--- /dev/null+++ b/headroom/providers/wrap_registry.py@@ -0,0 +1,164 @@+"""Declarative registry of env-var wrap targets.++A tool whose integration is fully described by data — the binary to launch+and which environment variables point at the local proxy — is registered here+as a :class:`WrapTarget` instead of a hand-written command in ``cli/wrap.py``.+``cli/wrap.py`` generates one ``headroom wrap <name>`` command per entry, so+adding such a tool is a registry entry, not a new command body. Mirrors the+declarative-route seam (:mod:`headroom.providers.route_specs`).++Tools that need imperative setup (settings files, token exchange, MCP+registrars, config rendering) or whose launch env is shared with+``headroom install`` (aider) keep their own commands.+"""++from __future__ import annotations++import os+from collections.abc import Mapping+from dataclasses import dataclass+from typing import Literal++from headroom.providers.claude import proxy_base_url as claude_proxy_base_url+from headroom.providers.codex import proxy_base_url as codex_proxy_base_url+from headroom.proxy.project_context import with_project_prefix++# How an EnvVar's URL is shaped: ``openai_v1`` ends in ``/v1`` (OpenAI-style+# clients append ``/chat/completions``); ``anthropic`` is a bare origin+# (Anthropic clients append ``/v1/messages``).+UrlStyle = Literal["openai_v1", "anthropic"]++_STYLE_BUILDERS = {+ "openai_v1": codex_proxy_base_url,+ "anthropic": claude_proxy_base_url,+}+++@dataclass(frozen=True, slots=True)+class EnvVar:+ """One environment variable a wrap target needs pointed at the proxy.++ ``display`` controls whether the assignment is echoed in the wrap banner;+ hidden aliases (e.g. ``OPENAI_API_BASE`` next to ``OPENAI_BASE_URL``) are+ set but not shown.+ """++ key: str+ style: UrlStyle+ display: bool = True+++@dataclass(frozen=True, slots=True)+class WrapTarget:+ """Everything needed to generate a ``headroom wrap <name>`` command."""++ name: str+ binary: str+ install_hint: str+ env_vars: tuple[EnvVar, ...]+ help_text: str+ # Encode the launch directory as a /p/<name> base-URL prefix so the proxy+ # can attribute savings per project (for tools that can't send headers).+ project_prefix: bool = True+++def build_launch_env(+ target: WrapTarget,+ port: int,+ environ: Mapping[str, str] | None = None,+ project: str | None = None,+) -> tuple[dict[str, str], list[str]]:+ """Build the launch environment for ``target`` routed through the proxy."""+ env = dict(environ if environ is not None else os.environ)+ display: list[str] = []+ for var in target.env_vars:+ url = _STYLE_BUILDERS[var.style](port)+ if target.project_prefix:+ url = with_project_prefix(url, project)+ env[var.key] = url+ if var.display:+ display.append(f"{var.key}={url}")+ return env, display+++WRAP_TARGETS: dict[str, WrapTarget] = {+ target.name: target+ for target in (+ WrapTarget(+ name="goose",+ binary="goose",+ install_hint="Install Goose: https://block.github.io/goose/",+ env_vars=(+ EnvVar("OPENAI_BASE_URL", "openai_v1"),+ EnvVar("OPENAI_API_BASE", "openai_v1", display=False),+ EnvVar("ANTHROPIC_BASE_URL", "anthropic"),+ ),+ project_prefix=False,+ help_text=(+ "Launch Goose (Block) CLI through Headroom proxy.\n"+ "\n"+ "\b\n"+ "Sets OPENAI_BASE_URL and ANTHROPIC_BASE_URL to route Goose's API calls\n"+ "through Headroom.\n"+ "\n"+ "\b\n"+ "Uninstall: there is no ``headroom unwrap goose`` subcommand — nothing is\n"+ "written to the project.\n"+ "\n"+ "\b\n"+ "Examples:\n"+ " headroom wrap goose # Start proxy + goose\n"+ " headroom wrap goose -- session # Start a Goose session\n"+ " headroom wrap goose -- --provider anthropic # Pass args to goose"+ ),+ ),+ WrapTarget(+ name="openhands",+ binary="openhands",+ install_hint="Install OpenHands: https://docs.all-hands.dev/",+ env_vars=(+ EnvVar("OPENAI_BASE_URL", "openai_v1"),+ EnvVar("OPENAI_API_BASE", "openai_v1", display=False),+ EnvVar("ANTHROPIC_BASE_URL", "anthropic"),+ # OpenHands' generic LLM provider config reads LLM_BASE_URL.+ EnvVar("LLM_BASE_URL", "openai_v1"),+ ),+ project_prefix=False,+ help_text=(+ "Launch OpenHands CLI through Headroom proxy.\n"+ "\n"+ "\b\n"+ "Sets OPENAI_BASE_URL / ANTHROPIC_BASE_URL to route OpenHands' API calls\n"+ "through Headroom. Nothing is written to disk, so there is nothing to undo.\n"+ "\n"+ "\b\n"+ "Examples:\n"+ " headroom wrap openhands # Start proxy + openhands\n"+ " headroom wrap openhands -- --task ... # Pass args to openhands"+ ),+ ),+ WrapTarget(+ name="openclaude",+ binary="openclaude",+ install_hint="Install OpenClaude before running `headroom wrap openclaude`.",+ # Same env shape as `wrap aider`.+ env_vars=(+ EnvVar("OPENAI_API_BASE", "openai_v1"),+ EnvVar("ANTHROPIC_BASE_URL", "anthropic"),+ ),+ help_text=(+ "Launch OpenClaude through Headroom proxy.\n"+ "\n"+ "\b\n"+ "OpenClaude is a prose-format coding CLI (like Aider / Cline); it speaks\n"+ "OpenAI- and Anthropic-compatible HTTP, so wrap routes both base URLs\n"+ "through the local proxy — same env shape as `wrap aider`.\n"+ "\n"+ "\b\n"+ "Examples:\n"+ " headroom wrap openclaude # Start proxy + openclaude\n"+ " headroom wrap openclaude -- --model gpt-4o # Pass args to openclaude"+ ),+ ),+ )+}diff --git a/tests/test_cli/test_wrap_registry.py b/tests/test_cli/test_wrap_registry.pynew file mode 100644index 000000000..105406b46--- /dev/null+++ b/tests/test_cli/test_wrap_registry.py@@ -0,0 +1,78 @@+"""Tests for the declarative WrapTarget registry.++The per-tool suites (test_wrap_goose / _openhands / _openclaude) still cover+env routing, missing binaries, and --prepare-only end to end against the+generated commands. These tests pin what they don't: the banner, parity with+the aider builder openclaude used to call, and the option surface.+"""++from __future__ import annotations++from click.testing import CliRunner++import headroom.cli.wrap as wrap_mod+from headroom.cli.wrap import wrap+from headroom.providers.wrap_registry import WRAP_TARGETS, build_launch_env+++def test_goose_banner_hides_openai_api_base_alias():+ _, display = build_launch_env(WRAP_TARGETS["goose"], 8787, environ={}, project="p")+ # Legacy goose never encoded the project prefix and showed two vars only.+ assert display == [+ "OPENAI_BASE_URL=http://127.0.0.1:8787/v1",+ "ANTHROPIC_BASE_URL=http://127.0.0.1:8787",+ ]+++def test_openhands_banner_matches_legacy_body():+ _, display = build_launch_env(WRAP_TARGETS["openhands"], 9000, environ={})+ assert display == [+ "OPENAI_BASE_URL=http://127.0.0.1:9000/v1",+ "ANTHROPIC_BASE_URL=http://127.0.0.1:9000",+ "LLM_BASE_URL=http://127.0.0.1:9000/v1",+ ]+++def test_openclaude_matches_legacy_aider_builder():+ from headroom.providers.aider import build_launch_env as aider_build_launch_env++ environ = {"PATH": "/bin"} # non-empty: the aider builder treats {} as os.environ+ got = build_launch_env(WRAP_TARGETS["openclaude"], 8787, environ, project="myproj")+ assert got == aider_build_launch_env(8787, environ, project="myproj")+++def test_option_surface_is_preserved():+ for name in WRAP_TARGETS:+ params = {p.name for p in wrap.commands[name].params}+ assert {+ "port",+ "code_graph",+ "no_proxy",+ "learn",+ "memory",+ "backend",+ "anyllm_provider",+ "region",+ "verbose",+ "prepare_only",+ "tool_args",+ } <= params, name+++def test_launch_passes_flags_through(monkeypatch):+ monkeypatch.setattr(wrap_mod.shutil, "which", lambda name: f"/usr/bin/{name}")+ captured: dict = {}+ monkeypatch.setattr(wrap_mod, "_launch_tool", lambda **kw: captured.update(kw))++ result = CliRunner().invoke(+ wrap,+ ["goose", "--port", "9001", "--learn", "--backend", "anyllm", "--", "session"],+ )++ assert result.exit_code == 0, result.output+ assert captured["args"] == ("session",)+ assert captured["port"] == 9001+ assert captured["learn"] is True+ assert captured["backend"] == "anyllm"+ assert captured["tool_label"] == "GOOSE"+ assert captured["agent_type"] == "goose"