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
feat(cli): add one-command OpenClaw wrap bootstrap
JerrettDavisc5e3686c8922
diff --git a/README.md b/README.mdindex d90d2bd0e..79a9688c1 100644--- a/README.md+++ b/README.md@@ -125,6 +125,7 @@ headroom wrap claude # Starts proxy + launches Claude Codeheadroom wrap codex # Starts proxy + launches OpenAI Codex CLIheadroom wrap aider # Starts proxy + launches Aiderheadroom wrap cursor # Starts proxy + prints Cursor config+headroom wrap openclaw # Installs + configures OpenClaw plugin```Headroom starts a proxy, points your tool at it, and compresses everything automatically.@@ -164,7 +165,7 @@ Gives your AI tool three MCP tools: `headroom_compress`, `headroom_retrieve`, `h| **Any Python proxy** | ASGI Middleware | `app.add_middleware(CompressionMiddleware)` || **Agno agents** | Wrap model | `HeadroomAgnoModel(your_model)` || **LangChain** | Wrap model | `HeadroomChatModel(your_llm)` |-| **OpenClaw** | ContextEngine plugin | [See OpenClaw plugin](#openclaw-plugin) |+| **OpenClaw** | One-command wrap | `headroom wrap openclaw` || **Claude Code** | Wrap | `headroom wrap claude` || **Codex / Aider** | Wrap | `headroom wrap codex` or `headroom wrap aider` |diff --git a/docs/index.md b/docs/index.mdindex d81193ab7..a0567bdd6 100644--- a/docs/index.md+++ b/docs/index.md@@ -98,6 +98,7 @@ Headroom works as a **transparent proxy** (zero code changes), a **Python functiheadroom wrap codex # OpenAI Codex CLIheadroom wrap aider # Aiderheadroom wrap cursor # Cursor+ headroom wrap openclaw # OpenClaw plugin bootstrap```Starts the proxy, points your tool at it, compresses everything automatically.@@ -215,7 +216,7 @@ npm install headroom-aiContextEngine plugin for OpenClaw agents. Auto-compresses context in `assemble()`.```bash-openclaw plugins install headroom-openclaw+headroom wrap openclaw```[OpenClaw Plugin →](https://github.com/chopratejas/headroom/tree/main/plugins/openclaw)diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex d6e2ffd7e..f02c5df59 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -5,6 +5,7 @@ Usage:headroom wrap codex # Start proxy + OpenAI Codex CLIheadroom wrap aider # Start proxy + aiderheadroom wrap cursor # Start proxy + print Cursor config instructions+ headroom wrap openclaw # Install + configure OpenClaw pluginheadroom wrap claude --no-rtk # Without rtk hooksheadroom wrap claude --port 9999 # Custom proxy portheadroom wrap claude -- --model opus # Pass args to claude@@ -13,6 +14,7 @@ Usage:from __future__ import annotationsimport io+import jsonimport osimport shutilimport signal@@ -384,6 +386,75 @@ def _launch_tool(cleanup()+def _run_checked(+ cmd: list[str],+ *,+ cwd: Path | None = None,+ action: str,+) -> subprocess.CompletedProcess[str]:+ """Run subprocess and raise a ClickException with actionable context on failure."""+ try:+ return subprocess.run(+ cmd,+ cwd=str(cwd) if cwd else None,+ check=True,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ except FileNotFoundError as e:+ raise click.ClickException(f"{action} failed: command not found: {cmd[0]}") from e+ except subprocess.CalledProcessError as e:+ stderr = (e.stderr or "").strip()+ stdout = (e.stdout or "").strip()+ details = stderr or stdout or f"exit code {e.returncode}"+ raise click.ClickException(f"{action} failed: {details}") from e+++def _default_openclaw_plugin_dir() -> Path:+ """Return repo-relative plugins/openclaw path for editable/dev installs."""+ return Path(__file__).resolve().parents[2] / "plugins" / "openclaw"+++def _resolve_openclaw_extensions_dir(openclaw_bin: str) -> Path:+ """Resolve OpenClaw extension root from active config file path."""+ result = _run_checked([openclaw_bin, "config", "file"], action="openclaw config file")+ config_path_str = result.stdout.strip().splitlines()[-1].strip()+ if not config_path_str:+ raise click.ClickException("Unable to resolve OpenClaw config path from `openclaw config file`.")+ config_path = Path(config_path_str).expanduser()+ return config_path.parent / "extensions"+++def _copy_openclaw_plugin_into_extensions(+ *,+ plugin_dir: Path,+ openclaw_bin: str,+) -> Path:+ """Fallback install path when `openclaw plugins install` is blocked on linked source."""+ dist_dir = plugin_dir / "dist"+ if not dist_dir.exists():+ raise click.ClickException(+ f"Plugin dist folder missing at {dist_dir}. Build the plugin first."+ )++ extensions_dir = _resolve_openclaw_extensions_dir(openclaw_bin)+ target_dir = extensions_dir / "headroom"+ target_dist = target_dir / "dist"+ target_dir.mkdir(parents=True, exist_ok=True)+ if target_dist.exists():+ shutil.rmtree(target_dist)+ shutil.copytree(dist_dir, target_dist)++ for filename in ("openclaw.plugin.json", "package.json", "README.md"):+ source = plugin_dir / filename+ if source.exists():+ shutil.copy2(source, target_dir / filename)++ return target_dir++@main.group()def wrap() -> None:"""Wrap CLI tools to run through Headroom.@@ -398,6 +469,7 @@ def wrap() -> None:headroom wrap codex # OpenAI Codex CLIheadroom wrap aider # Aiderheadroom wrap cursor # Cursor (prints config instructions)+ headroom wrap openclaw # OpenClaw plugin bootstrap"""@@ -744,3 +816,213 @@ def cursor(port: int, no_rtk: bool, no_proxy: bool, learn: bool, verbose: bool)raise SystemExit(1) from efinally:cleanup()+++# =============================================================================+# OpenClaw+# =============================================================================++[email protected]("openclaw")+ "--plugin-path",+ type=click.Path(path_type=Path, file_okay=False, dir_okay=True),+ default=None,+ help="Path to the OpenClaw plugin source directory (default: repo plugins/openclaw)",+)+ "--skip-build",+ is_flag=True,+ help="Skip npm install/build before plugin install",+)+ "--copy",+ is_flag=True,+ help="Install by copying plugin path instead of using --link",+)[email protected]("--proxy-port", default=8787, type=int, help="Headroom proxy port")[email protected]("--startup-timeout-ms", default=20000, type=int, help="Proxy startup timeout")+ "--python-path",+ default=None,+ help="Optional Python executable for proxy launcher fallback",+)+ "--no-auto-start",+ is_flag=True,+ help="Disable plugin auto-start of local headroom proxy",+)+ "--no-restart",+ is_flag=True,+ help="Do not restart OpenClaw gateway at the end",+)[email protected]("--verbose", "-v", is_flag=True, help="Verbose output")+def openclaw(+ plugin_path: Path | None,+ skip_build: bool,+ copy: bool,+ proxy_port: int,+ startup_timeout_ms: int,+ python_path: str | None,+ no_auto_start: bool,+ no_restart: bool,+ verbose: bool,+) -> None:+ """Install and configure Headroom OpenClaw plugin in one command.++ \b+ What this command does:+ 1. Builds plugin source (npm install + npm run build)+ 2. Installs plugin with unsafe-install flag required by OpenClaw+ 3. Writes minimal plugin config and sets contextEngine slot+ 4. Validates config+ 5. Restarts OpenClaw gateway (unless --no-restart)++ \b+ Example:+ headroom wrap openclaw+ headroom wrap openclaw --plugin-path C:\\git\\headroom\\plugins\\openclaw+ """+ openclaw_bin = shutil.which("openclaw")+ if not openclaw_bin:+ raise click.ClickException(+ "'openclaw' not found in PATH. Install OpenClaw CLI first."+ )++ plugin_dir = (plugin_path or _default_openclaw_plugin_dir()).resolve()+ if not plugin_dir.exists():+ raise click.ClickException(+ f"Plugin path not found: {plugin_dir}. Pass --plugin-path explicitly."+ )+ if not (plugin_dir / "package.json").exists():+ raise click.ClickException(f"Invalid plugin path (missing package.json): {plugin_dir}")+ if not (plugin_dir / "openclaw.plugin.json").exists():+ raise click.ClickException(+ f"Invalid plugin path (missing openclaw.plugin.json): {plugin_dir}"+ )++ npm_bin = shutil.which("npm")+ if not skip_build and not npm_bin:+ raise click.ClickException(+ "'npm' not found in PATH. Install Node/npm or rerun with --skip-build."+ )++ click.echo()+ click.echo(" ╔═══════════════════════════════════════════════╗")+ click.echo(" ║ HEADROOM WRAP: OPENCLAW ║")+ click.echo(" ╚═══════════════════════════════════════════════╝")+ click.echo()+ click.echo(f" Plugin source: {plugin_dir}")++ if not skip_build:+ click.echo(" Building OpenClaw plugin (npm install + npm run build)...")+ _run_checked([npm_bin or "npm", "install"], cwd=plugin_dir, action="npm install")+ _run_checked([npm_bin or "npm", "run", "build"], cwd=plugin_dir, action="npm run build")++ install_cmd = [+ openclaw_bin,+ "plugins",+ "install",+ "--dangerously-force-unsafe-install",+ ]+ if copy:+ install_cmd.append(str(plugin_dir))+ install_cwd = None+ else:+ install_cmd.extend(["--link", "."])+ install_cwd = plugin_dir++ click.echo(" Installing OpenClaw plugin with required unsafe-install flag...")+ install_result = subprocess.run(+ install_cmd,+ cwd=str(install_cwd) if install_cwd else None,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ if install_result.returncode != 0:+ combined_error = "\n".join(+ x for x in [install_result.stderr.strip(), install_result.stdout.strip()] if x+ )+ linked_install_bug = (+ "also not a valid hook pack" in combined_error.lower()+ and "--dangerously-force-unsafe-install" in " ".join(install_cmd)+ )+ if linked_install_bug:+ click.echo(+ " OpenClaw linked-path install bug detected; applying extension-path fallback..."+ )+ target_dir = _copy_openclaw_plugin_into_extensions(+ plugin_dir=plugin_dir,+ openclaw_bin=openclaw_bin,+ )+ click.echo(f" Fallback plugin copy completed: {target_dir}")+ else:+ details = combined_error or f"exit code {install_result.returncode}"+ raise click.ClickException(f"openclaw plugins install failed: {details}")+ elif verbose and install_result.stdout.strip():+ click.echo(install_result.stdout.strip())++ plugin_config: dict[str, object] = {+ "proxyPort": proxy_port,+ "autoStart": not no_auto_start,+ "startupTimeoutMs": startup_timeout_ms,+ }+ if python_path:+ plugin_config["pythonPath"] = python_path+ entry = {"enabled": True, "config": plugin_config}++ click.echo(" Writing plugin configuration...")+ _run_checked(+ [+ openclaw_bin,+ "config",+ "set",+ "plugins.entries.headroom",+ json.dumps(entry, separators=(",", ":")),+ "--strict-json",+ ],+ action="openclaw config set plugins.entries.headroom",+ )+ _run_checked(+ [+ openclaw_bin,+ "config",+ "set",+ "plugins.slots.contextEngine",+ json.dumps("headroom"),+ "--strict-json",+ ],+ action="openclaw config set plugins.slots.contextEngine",+ )+ _run_checked(+ [openclaw_bin, "config", "validate"],+ action="openclaw config validate",+ )++ if no_restart:+ click.echo(" Skipping gateway restart (--no-restart).")+ click.echo(" Run `openclaw gateway restart` to apply plugin changes.")+ else:+ click.echo(" Warning: restarting OpenClaw gateway to apply plugin changes.")+ restart_result = _run_checked(+ [openclaw_bin, "gateway", "restart"],+ action="openclaw gateway restart",+ )+ if verbose and restart_result.stdout.strip():+ click.echo(restart_result.stdout.strip())++ inspect_result = _run_checked(+ [openclaw_bin, "plugins", "inspect", "headroom"],+ action="openclaw plugins inspect headroom",+ )+ if verbose and inspect_result.stdout.strip():+ click.echo(inspect_result.stdout.strip())++ click.echo()+ click.echo("✓ OpenClaw is configured to use Headroom context compression.")+ click.echo(" Plugin: headroom")+ click.echo(" Slot: plugins.slots.contextEngine = headroom")+ click.echo()diff --git a/plugins/openclaw/README.md b/plugins/openclaw/README.mdindex 86dc1cace..e28f281a9 100644--- a/plugins/openclaw/README.md+++ b/plugins/openclaw/README.md@@ -4,6 +4,14 @@ Context compression plugin for [OpenClaw](https://github.com/openclaw/openclaw).## Install+Recommended one-command setup:++```bash+headroom wrap openclaw+```++Manual install:+```bashpip install "headroom-ai[proxy]"openclaw plugins install --dangerously-force-unsafe-install headroom-ai/openclawdiff --git a/tests/test_cli/test_wrap_openclaw.py b/tests/test_cli/test_wrap_openclaw.pynew file mode 100644index 000000000..c5a2f8b52--- /dev/null+++ b/tests/test_cli/test_wrap_openclaw.py@@ -0,0 +1,173 @@+"""Tests for `headroom wrap openclaw` command."""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from click.testing import CliRunner++from headroom.cli.main import main+++def runner() -> CliRunner:+ return CliRunner()+++def plugin_dir(tmp_path: Path) -> Path:+ """Create a minimal OpenClaw plugin directory fixture."""+ plugin = tmp_path / "plugins" / "openclaw"+ plugin.mkdir(parents=True)+ (plugin / "package.json").write_text('{"name":"headroom-openclaw"}\n')+ (plugin / "openclaw.plugin.json").write_text('{"id":"headroom"}\n')+ return plugin+++def _make_successful_run(calls: list[dict]) -> object:+ def run(cmd, **kwargs): # noqa: ANN001+ calls.append({"cmd": list(cmd), **kwargs})+ return MagicMock(returncode=0, stdout="", stderr="")++ return run+++def test_wrap_openclaw_happy_path_installs_builds_configures_and_restarts(+ runner: CliRunner, plugin_dir: Path+) -> None:+ calls: list[dict] = []++ def which(name: str) -> str | None:+ mapping = {+ "openclaw": "openclaw",+ "npm": "npm",+ }+ return mapping.get(name)++ with patch("headroom.cli.wrap.shutil.which", side_effect=which):+ with patch("headroom.cli.wrap._default_openclaw_plugin_dir", return_value=plugin_dir):+ with patch("headroom.cli.wrap.subprocess.run", side_effect=_make_successful_run(calls)):+ result = runner.invoke(main, ["wrap", "openclaw"])++ assert result.exit_code == 0, result.output++ cmds = [c["cmd"] for c in calls]+ assert ["npm", "install"] in cmds+ assert ["npm", "run", "build"] in cmds+ assert [+ "openclaw",+ "plugins",+ "install",+ "--dangerously-force-unsafe-install",+ "--link",+ ".",+ ] in cmds+ assert ["openclaw", "config", "validate"] in cmds+ assert ["openclaw", "gateway", "restart"] in cmds+ assert ["openclaw", "plugins", "inspect", "headroom"] in cmds++ # Verify plugin install uses plugin cwd when linking+ install_call = next(+ c+ for c in calls+ if c["cmd"][:4]+ == ["openclaw", "plugins", "install", "--dangerously-force-unsafe-install"]+ )+ assert install_call["cwd"] == str(plugin_dir)++ # Verify config payload includes enabled + expected defaults+ set_entry = next(c for c in calls if c["cmd"][:4] == ["openclaw", "config", "set", "plugins.entries.headroom"])+ payload = json.loads(set_entry["cmd"][4])+ assert payload["enabled"] is True+ assert payload["config"]["proxyPort"] == 8787+ assert payload["config"]["autoStart"] is True+ assert payload["config"]["startupTimeoutMs"] == 20000+++def test_wrap_openclaw_skip_build_and_no_restart(runner: CliRunner, plugin_dir: Path) -> None:+ calls: list[dict] = []++ def which(name: str) -> str | None:+ mapping = {+ "openclaw": "openclaw",+ "npm": "npm",+ }+ return mapping.get(name)++ with patch("headroom.cli.wrap.shutil.which", side_effect=which):+ with patch("headroom.cli.wrap.subprocess.run", side_effect=_make_successful_run(calls)):+ result = runner.invoke(+ main,+ [+ "wrap",+ "openclaw",+ "--plugin-path",+ str(plugin_dir),+ "--skip-build",+ "--no-restart",+ ],+ )++ assert result.exit_code == 0, result.output+ cmds = [c["cmd"] for c in calls]+ assert ["npm", "install"] not in cmds+ assert ["npm", "run", "build"] not in cmds+ assert ["openclaw", "gateway", "restart"] not in cmds+++def test_wrap_openclaw_fails_when_openclaw_missing(runner: CliRunner, plugin_dir: Path) -> None:+ def which(name: str) -> str | None:+ return None if name == "openclaw" else "npm"++ with patch("headroom.cli.wrap.shutil.which", side_effect=which):+ result = runner.invoke(main, ["wrap", "openclaw", "--plugin-path", str(plugin_dir)])++ assert result.exit_code != 0+ assert "'openclaw' not found in PATH" in result.output+++def test_wrap_openclaw_fails_when_plugin_path_invalid(runner: CliRunner, tmp_path: Path) -> None:+ invalid = tmp_path / "missing-plugin"++ with patch("headroom.cli.wrap.shutil.which", return_value="openclaw"):+ result = runner.invoke(main, ["wrap", "openclaw", "--plugin-path", str(invalid)])++ assert result.exit_code != 0+ assert "Plugin path not found" in result.output+++def test_wrap_openclaw_uses_extension_fallback_on_linked_install_bug(+ runner: CliRunner, plugin_dir: Path+) -> None:+ calls: list[dict] = []++ def which(name: str) -> str | None:+ mapping = {+ "openclaw": "openclaw",+ "npm": "npm",+ }+ return mapping.get(name)++ def run(cmd, **kwargs): # noqa: ANN001+ calls.append({"cmd": list(cmd), **kwargs})+ if cmd[:3] == ["openclaw", "plugins", "install"]:+ return MagicMock(+ returncode=1,+ stdout="Also not a valid hook pack",+ stderr='Plugin installation blocked despite "--dangerously-force-unsafe-install"',+ )+ return MagicMock(returncode=0, stdout="", stderr="")++ with patch("headroom.cli.wrap.shutil.which", side_effect=which):+ with patch("headroom.cli.wrap.subprocess.run", side_effect=run):+ with patch(+ "headroom.cli.wrap._copy_openclaw_plugin_into_extensions",+ return_value=Path("C:/Users/test/.openclaw/extensions/headroom"),+ ) as copy_fallback:+ result = runner.invoke(main, ["wrap", "openclaw", "--plugin-path", str(plugin_dir)])++ assert result.exit_code == 0, result.output+ copy_fallback.assert_called_once()