Skip to content

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.

Add OpenClaw unwrap flow and non-blocking proxy startup

JerrettDavis0da1a7b4de9c
diff --git a/README.md b/README.md
index 06c645672..19807d4f8 100644
--- a/README.md
+++ b/README.md
@@ -135,6 +135,7 @@ headroom wrap codex # Starts proxy + launches OpenAI Codex CLI
headroom wrap aider # Starts proxy + launches Aider
headroom wrap cursor # Starts proxy + prints Cursor config
headroom wrap openclaw # Installs + configures OpenClaw plugin
+headroom unwrap openclaw # Disables plugin + restores legacy engine
```
Headroom starts a proxy, points your tool at it, and compresses everything automatically.
@@ -174,7 +175,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** | One-command wrap | `headroom wrap openclaw` |
+| **OpenClaw** | One-command wrap/unwrap | `headroom wrap openclaw` / `headroom unwrap openclaw` |
| **Claude Code** | Wrap | `headroom wrap claude` |
| **Codex / Aider** | Wrap | `headroom wrap codex` or `headroom wrap aider` |
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index d9a641d5b..d9210e052 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -478,6 +478,131 @@ def _resolve_openclaw_extensions_dir(openclaw_bin: str) -> Path:
return config_path.parent / "extensions"
+def _normalize_openclaw_gateway_provider_ids(provider_ids: tuple[str, ...] | None) -> list[str]:
+ """Normalize configured OpenClaw provider ids, defaulting to openai-codex."""
+ values = provider_ids or ()
+ seen: set[str] = set()
+ normalized: list[str] = []
+
+ for entry in values:
+ provider_id = entry.strip()
+ if not provider_id or provider_id in seen:
+ continue
+ seen.add(provider_id)
+ normalized.append(provider_id)
+
+ if normalized:
+ return normalized
+ return ["openai-codex"]
+
+
+def _read_openclaw_config_value(openclaw_bin: str, path: str) -> Any | None:
+ """Read an OpenClaw config value when present, returning None on missing paths."""
+ result = subprocess.run(
+ [openclaw_bin, "config", "get", path],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ if result.returncode != 0:
+ return None
+
+ output = result.stdout.strip()
+ if not output:
+ return None
+
+ try:
+ return json.loads(output)
+ except json.JSONDecodeError:
+ return output
+
+
+def _build_openclaw_plugin_entry(
+ *,
+ existing_entry: Any,
+ proxy_port: int,
+ startup_timeout_ms: int,
+ python_path: str | None,
+ no_auto_start: bool,
+ gateway_provider_ids: tuple[str, ...] | None,
+ enabled: bool,
+) -> dict[str, object]:
+ """Merge managed Headroom plugin settings with any existing entry payload."""
+ base_entry = existing_entry if isinstance(existing_entry, dict) else {}
+ existing_config = base_entry.get("config")
+ next_config = dict(existing_config) if isinstance(existing_config, dict) else {}
+
+ next_config["proxyPort"] = proxy_port
+ next_config["autoStart"] = not no_auto_start
+ next_config["startupTimeoutMs"] = startup_timeout_ms
+ next_config["gatewayProviderIds"] = _normalize_openclaw_gateway_provider_ids(
+ gateway_provider_ids
+ )
+
+ if python_path:
+ next_config["pythonPath"] = python_path
+ else:
+ next_config.pop("pythonPath", None)
+
+ return {
+ **base_entry,
+ "enabled": enabled,
+ "config": next_config,
+ }
+
+
+def _write_openclaw_plugin_entry(openclaw_bin: str, entry: dict[str, object]) -> None:
+ """Persist the Headroom plugin config entry."""
+ _run_checked(
+ [
+ openclaw_bin,
+ "config",
+ "set",
+ "plugins.entries.headroom",
+ json.dumps(entry, separators=(",", ":")),
+ "--strict-json",
+ ],
+ action="openclaw config set plugins.entries.headroom",
+ )
+
+
+def _set_openclaw_context_engine_slot(openclaw_bin: str, engine_id: str) -> None:
+ """Persist the selected OpenClaw context engine slot."""
+ _run_checked(
+ [
+ openclaw_bin,
+ "config",
+ "set",
+ "plugins.slots.contextEngine",
+ json.dumps(engine_id),
+ "--strict-json",
+ ],
+ action="openclaw config set plugins.slots.contextEngine",
+ )
+
+
+def _restart_or_start_openclaw_gateway(openclaw_bin: str) -> tuple[str, str]:
+ """Restart the gateway when running, otherwise start it."""
+ restart_result = subprocess.run(
+ [openclaw_bin, "gateway", "restart"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ )
+ if restart_result.returncode == 0:
+ output = restart_result.stdout.strip() or restart_result.stderr.strip()
+ return "restarted", output
+
+ start_result = _run_checked(
+ [openclaw_bin, "gateway", "start"],
+ action="openclaw gateway start",
+ )
+ output = start_result.stdout.strip() or start_result.stderr.strip()
+ return "started", output
+
+
def _copy_openclaw_plugin_into_extensions(
*,
plugin_dir: Path,
@@ -533,6 +658,11 @@ def wrap() -> None:
"""
+def unwrap() -> None:
+ """Undo durable Headroom wrapping for supported tools."""
+
+
# =============================================================================
# Claude Code
# =============================================================================
@@ -913,6 +1043,12 @@ def cursor(port: int, no_rtk: bool, no_proxy: bool, learn: bool, verbose: bool)
)
@click.option("--proxy-port", default=8787, type=int, help="Headroom proxy port")
@click.option("--startup-timeout-ms", default=20000, type=int, help="Proxy startup timeout")
+ "--gateway-provider-id",
+ "gateway_provider_ids",
+ multiple=True,
+ help="OpenClaw provider id to route through Headroom (repeatable; default: openai-codex)",
+)
@click.option(
"--python-path",
default=None,
@@ -936,6 +1072,7 @@ def openclaw(
copy: bool,
proxy_port: int,
startup_timeout_ms: int,
+ gateway_provider_ids: tuple[str, ...],
python_path: str | None,
no_auto_start: bool,
no_restart: bool,
@@ -1047,38 +1184,20 @@ def openclaw(
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}
+ existing_entry = _read_openclaw_config_value(openclaw_bin, "plugins.entries.headroom")
+ entry = _build_openclaw_plugin_entry(
+ existing_entry=existing_entry,
+ proxy_port=proxy_port,
+ startup_timeout_ms=startup_timeout_ms,
+ python_path=python_path,
+ no_auto_start=no_auto_start,
+ gateway_provider_ids=gateway_provider_ids,
+ enabled=True,
+ )
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",
- )
+ _write_openclaw_plugin_entry(openclaw_bin, entry)
+ _set_openclaw_context_engine_slot(openclaw_bin, "headroom")
_run_checked(
[openclaw_bin, "config", "validate"],
action="openclaw config validate",
@@ -1086,15 +1205,13 @@ def openclaw(
if no_restart:
click.echo(" Skipping gateway restart (--no-restart).")
- click.echo(" Run `openclaw gateway restart` to apply plugin changes.")
+ click.echo(" Run `openclaw gateway restart` (or `openclaw gateway start`) 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())
+ click.echo(" Applying plugin changes to OpenClaw gateway...")
+ gateway_action, gateway_output = _restart_or_start_openclaw_gateway(openclaw_bin)
+ click.echo(f" Gateway {gateway_action}.")
+ if verbose and gateway_output:
+ click.echo(gateway_output)
inspect_result = _run_checked(
[openclaw_bin, "plugins", "inspect", "headroom"],
@@ -1108,3 +1225,61 @@ def openclaw(
click.echo(" Plugin: headroom")
click.echo(" Slot: plugins.slots.contextEngine = headroom")
click.echo()
+
+
[email protected]("openclaw")
[email protected]("--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 unwrap_openclaw(no_restart: bool, verbose: bool) -> None:
+ """Disable the Headroom OpenClaw plugin and restore the legacy engine slot."""
+ openclaw_bin = shutil.which("openclaw")
+ if not openclaw_bin:
+ raise click.ClickException("'openclaw' not found in PATH. Install OpenClaw CLI first.")
+
+ click.echo()
+ click.echo(" ╔═══════════════════════════════════════════════╗")
+ click.echo(" ║ HEADROOM UNWRAP: OPENCLAW ║")
+ click.echo(" ╚═══════════════════════════════════════════════╝")
+ click.echo()
+ click.echo(" Disabling Headroom plugin and removing engine mapping...")
+
+ existing_entry = _read_openclaw_config_value(openclaw_bin, "plugins.entries.headroom")
+ existing_config = {}
+ if isinstance(existing_entry, dict) and isinstance(existing_entry.get("config"), dict):
+ existing_config = {
+ key: value
+ for key, value in existing_entry["config"].items()
+ if key not in {"gatewayProviderIds", "proxyUrl", "proxyPort", "autoStart", "startupTimeoutMs", "pythonPath"}
+ }
+
+ entry = {"enabled": False, "config": existing_config}
+ _write_openclaw_plugin_entry(openclaw_bin, entry)
+ _set_openclaw_context_engine_slot(openclaw_bin, "legacy")
+ _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` (or `openclaw gateway start`) to apply unwrap changes.")
+ else:
+ click.echo(" Applying unwrap changes to OpenClaw gateway...")
+ gateway_action, gateway_output = _restart_or_start_openclaw_gateway(openclaw_bin)
+ click.echo(f" Gateway {gateway_action}.")
+ if verbose and gateway_output:
+ click.echo(gateway_output)
+
+ if verbose:
+ inspect_result = _run_checked(
+ [openclaw_bin, "plugins", "inspect", "headroom"],
+ action="openclaw plugins inspect headroom",
+ )
+ if inspect_result.stdout.strip():
+ click.echo(inspect_result.stdout.strip())
+
+ click.echo()
+ click.echo("✓ OpenClaw Headroom wrap removed.")
+ click.echo(" Plugin: headroom (installed, disabled)")
+ click.echo(" Slot: plugins.slots.contextEngine = legacy")
+ click.echo()
diff --git a/plugins/openclaw/src/engine.ts b/plugins/openclaw/src/engine.ts
index 0d6439bbc..bea49ed9b 100644
--- a/plugins/openclaw/src/engine.ts
+++ b/plugins/openclaw/src/engine.ts
@@ -28,6 +28,7 @@ export class HeadroomContextEngine {
private config: HeadroomEngineConfig;
private logger: ProxyManagerLogger;
private proxyReadyListeners = new Set<(proxyUrl: string) => void | Promise<void>>();
+ private proxyStartupPromise: Promise<string> | null = null;
private stats = {
totalCompressions: 0,
totalTokensSaved: 0,
@@ -52,15 +53,8 @@ export class HeadroomContextEngine {
return { bootstrapped: false, reason: "disabled" };
}
- try {
- this.proxyUrl = await this.proxyManager.start();
- await this.notifyProxyReady(this.proxyUrl);
- this.logger.info(`Engine bootstrapped (proxy: ${this.proxyUrl})`);
- return { bootstrapped: true };
- } catch (error) {
- this.logger.error(`Bootstrap failed: ${error}`);
- return { bootstrapped: false, reason: String(error) };
- }
+ this.ensureProxyStarted();
+ return { bootstrapped: true, reason: "proxy startup scheduled" };
}
async ingest(params: {
@@ -97,6 +91,7 @@ export class HeadroomContextEngine {
systemPromptAddition?: string;
}> {
if (!this.proxyUrl || this.config.enabled === false) {
+ this.ensureProxyStarted();
// Fallback: return messages unchanged
return { messages: normalizeAgentMessages(params.messages), estimatedTokens: 0 };
}
@@ -240,6 +235,28 @@ export class HeadroomContextEngine {
return this.proxyUrl;
}
+ ensureProxyStarted(): void {
+ if (this.config.enabled === false || this.proxyUrl || this.proxyStartupPromise) {
+ return;
+ }
+
+ this.proxyStartupPromise = this.proxyManager
+ .start()
+ .then(async (proxyUrl) => {
+ this.proxyUrl = proxyUrl;
+ await this.notifyProxyReady(proxyUrl);
+ this.logger.info(`Headroom proxy ready at ${proxyUrl}`);
+ return proxyUrl;
+ })
+ .catch((error) => {
+ this.logger.warn(`Headroom proxy unavailable: ${error}`);
+ throw error;
+ })
+ .finally(() => {
+ this.proxyStartupPromise = null;
+ });
+ }
+
onProxyReady(listener: (proxyUrl: string) => void | Promise<void>): () => void {
this.proxyReadyListeners.add(listener);
return () => {
@@ -252,9 +269,11 @@ export class HeadroomContextEngine {
return this.proxyUrl;
}
- this.proxyUrl = await this.proxyManager.start();
- await this.notifyProxyReady(this.proxyUrl);
- return this.proxyUrl;
+ this.ensureProxyStarted();
+ if (!this.proxyStartupPromise) {
+ throw new Error("Headroom proxy startup is disabled");
+ }
+ return this.proxyStartupPromise;
}
private async notifyProxyReady(proxyUrl: string): Promise<void> {
diff --git a/plugins/openclaw/src/plugin/index.ts b/plugins/openclaw/src/plugin/index.ts
index 61c1639a1..c71819048 100644
--- a/plugins/openclaw/src/plugin/index.ts
+++ b/plugins/openclaw/src/plugin/index.ts
@@ -66,6 +66,7 @@ export default function headroomPlugin(api: any) {
const activeProxyUrl = engine.getProxyUrl();
if (!activeProxyUrl) {
logger.debug?.("[headroom] Deferring upstream gateway routing until proxy is available");
+ engine.ensureProxyStarted();
return;
}
await applyGatewayRouting(activeProxyUrl);
diff --git a/plugins/openclaw/test/engine.test.ts b/plugins/openclaw/test/engine.test.ts
index 0d93d0900..8dc3acba4 100644
--- a/plugins/openclaw/test/engine.test.ts
+++ b/plugins/openclaw/test/engine.test.ts
@@ -145,6 +145,44 @@ describe("AgentMessage conversion", () => {
});
});
+describe("HeadroomContextEngine startup behavior", () => {
+ it("bootstrap schedules proxy startup without blocking on it", async () => {
+ const start = vi.fn(
+ () => new Promise<string>((resolve) => setTimeout(() => resolve("http://127.0.0.1:8787"), 50)),
+ );
+ vi.spyOn(ProxyManager.prototype, "start").mockImplementation(start);
+
+ const engine = new HeadroomContextEngine();
+ const result = await engine.bootstrap({
+ sessionId: "test-session",
+ sessionFile: "/tmp/test-session.jsonl",
+ });
+
+ expect(result).toEqual({ bootstrapped: true, reason: "proxy startup scheduled" });
+ expect(start).toHaveBeenCalledTimes(1);
+ expect(engine.getProxyUrl()).toBeNull();
+ });
+
+ it("assemble returns original messages while proxy startup is still pending", async () => {
+ const start = vi.fn(
+ () => new Promise<string>((resolve) => setTimeout(() => resolve("http://127.0.0.1:8787"), 50)),
+ );
+ vi.spyOn(ProxyManager.prototype, "start").mockImplementation(start);
+
+ const engine = new HeadroomContextEngine();
+ const messages = [{ role: "user", content: "hello", timestamp: Date.now() }];
+
+ const result = await engine.assemble({
+ sessionId: "test-session",
+ messages,
+ model: "claude-sonnet-4-5",
+ });
+
+ expect(result).toEqual({ messages, estimatedTokens: 0 });
+ expect(start).toHaveBeenCalledTimes(1);
+ });
+});
+
if (RUN) {
describe("ProxyManager", () => {
it("connects to configured proxy URL", { timeout: 30000 }, async () => {
diff --git a/plugins/openclaw/test/plugin-runtime-routing.test.ts b/plugins/openclaw/test/plugin-runtime-routing.test.ts
index 8d297b9cc..ea7ef1f4c 100644
--- a/plugins/openclaw/test/plugin-runtime-routing.test.ts
+++ b/plugins/openclaw/test/plugin-runtime-routing.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const mocked = vi.hoisted(() => ({
ensureProxyUrl: vi.fn(async () => "http://127.0.0.1:8787"),
+ ensureProxyStarted: vi.fn(),
getProxyUrl: vi.fn(() => null as string | null),
createHeadroomRetrieveTool: vi.fn(({ proxyUrl }: { proxyUrl: string }) => ({ proxyUrl })),
}));
@@ -11,6 +12,7 @@ const proxyReadyListeners: Array<(proxyUrl: string) => void | Promise<void>> = [
vi.mock("../src/engine.js", () => ({
HeadroomContextEngine: class {
ensureProxyUrl = mocked.ensureProxyUrl;
+ ensureProxyStarted = mocked.ensureProxyStarted;
getProxyUrl = mocked.getProxyUrl;
onProxyReady(listener: (proxyUrl: string) => void | Promise<void>) {
proxyReadyListeners.push(listener);
@@ -27,6 +29,7 @@ import headroomPlugin from "../src/plugin/index.js";
afterEach(() => {
mocked.ensureProxyUrl.mockClear();
+ mocked.ensureProxyStarted.mockClear();
mocked.getProxyUrl.mockClear();
mocked.createHeadroomRetrieveTool.mockClear();
proxyReadyListeners.length = 0;
@@ -88,6 +91,7 @@ describe("headroomPlugin runtime routing", () => {
await Promise.resolve();
expect(mocked.ensureProxyUrl).not.toHaveBeenCalled();
+ expect(mocked.ensureProxyStarted).toHaveBeenCalledTimes(1);
expect(writeConfigFile).not.toHaveBeenCalled();
expect(loadConfig).not.toHaveBeenCalled();
expect(api.config.models.providers["openai-codex"]).toBeUndefined();
@@ -111,6 +115,7 @@ describe("headroomPlugin runtime routing", () => {
const gatewayStart = gatewayHandlers.get("gateway_start");
expect(gatewayStart).toBeTypeOf("function");
await gatewayStart?.();
+ expect(mocked.ensureProxyStarted).toHaveBeenCalledTimes(2);
expect(writeConfigFile).not.toHaveBeenCalled();
expect(loadConfig).not.toHaveBeenCalled();
expect(mocked.ensureProxyUrl).not.toHaveBeenCalled();
diff --git a/tests/test_cli/test_wrap_openclaw.py b/tests/test_cli/test_wrap_openclaw.py
index 3072e9074..6b0444787 100644
--- a/tests/test_cli/test_wrap_openclaw.py
+++ b/tests/test_cli/test_wrap_openclaw.py
@@ -90,6 +90,7 @@ def test_wrap_openclaw_default_installs_from_npm_and_restarts(runner: CliRunner)
assert payload["config"]["proxyPort"] == 8787
assert payload["config"]["autoStart"] is True
assert payload["config"]["startupTimeoutMs"] == 20000
+ assert payload["config"]["gatewayProviderIds"] == ["openai-codex"]
def test_wrap_openclaw_skip_build_and_no_restart(runner: CliRunner, plugin_dir: Path) -> None:
@@ -272,6 +273,63 @@ def test_wrap_openclaw_verbose_prints_install_restart_and_inspect_output(
assert "inspect-ok" in result.output
+def test_wrap_openclaw_starts_gateway_when_restart_fails(runner: CliRunner) -> None:
+ calls: list[dict] = []
+
+ def which(name: str) -> str | None:
+ return {"openclaw": "openclaw", "npm": "npm"}.get(name)
+
+ def run(cmd, **kwargs): # noqa: ANN001
+ calls.append({"cmd": list(cmd), **kwargs})
+ if cmd[:3] == ["openclaw", "gateway", "restart"]:
+ return MagicMock(returncode=1, stdout="", stderr="gateway not running")
+ if cmd[:3] == ["openclaw", "gateway", "start"]:
+ return MagicMock(returncode=0, stdout="started-ok", stderr="")
+ 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):
+ result = runner.invoke(main, ["wrap", "openclaw", "--verbose"])
+
+ assert result.exit_code == 0, result.output
+ cmds = [c["cmd"] for c in calls]
+ assert ["openclaw", "gateway", "restart"] in cmds
+ assert ["openclaw", "gateway", "start"] in cmds
+ assert "Gateway started." in result.output
+ assert "started-ok" in result.output
+
+
+def test_wrap_openclaw_accepts_repeatable_gateway_provider_ids(runner: CliRunner) -> None:
+ calls: list[dict] = []
+
+ def which(name: str) -> str | None:
+ return {"openclaw": "openclaw", "npm": "npm"}.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",
+ "--gateway-provider-id",
+ "openai-codex",
+ "--gateway-provider-id",
+ "anthropic",
+ "--no-restart",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ 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["config"]["gatewayProviderIds"] == ["openai-codex", "anthropic"]
+
+
def test_wrap_openclaw_fails_for_npm_mode_hook_pack_bug_without_local_fallback(
runner: CliRunner,
) -> None:
@@ -448,3 +506,68 @@ def test_copy_openclaw_plugin_into_extensions_handles_missing_and_existing_dist(
assert not (target_dist / "old.js").exists()
assert (target_hook_shim / "index.js").exists()
assert not (target_hook_shim / "old.js").exists()
+
+
+def test_unwrap_openclaw_disables_plugin_and_restores_legacy_slot(runner: CliRunner) -> None:
+ calls: list[dict] = []
+
+ def which(name: str) -> str | None:
+ return {"openclaw": "openclaw"}.get(name)
+
+ def run(cmd, **kwargs): # noqa: ANN001
+ calls.append({"cmd": list(cmd), **kwargs})
+ if cmd[:4] == ["openclaw", "config", "get", "plugins.entries.headroom"]:
+ return MagicMock(
+ returncode=0,
+ stdout=json.dumps(
+ {
+ "enabled": True,
+ "config": {
+ "proxyPort": 8787,
+ "gatewayProviderIds": ["openai-codex"],
+ "customFlag": True,
+ },
+ }
+ ),
+ stderr="",
+ )
+ 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):
+ result = runner.invoke(main, ["unwrap", "openclaw"])
+
+ assert result.exit_code == 0, result.output
+ 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": False, "config": {"customFlag": True}}
+
+ set_slot = next(
+ c
+ for c in calls
+ if c["cmd"][:4] == ["openclaw", "config", "set", "plugins.slots.contextEngine"]
+ )
+ assert json.loads(set_slot["cmd"][4]) == "legacy"
+ assert ["openclaw", "gateway", "restart"] in [c["cmd"] for c in calls]
+
+
+def test_unwrap_openclaw_no_restart_skips_gateway_restart(runner: CliRunner) -> None:
+ calls: list[dict] = []
+
+ def which(name: str) -> str | None:
+ return {"openclaw": "openclaw"}.get(name)
+
+ def run(cmd, **kwargs): # noqa: ANN001
+ calls.append({"cmd": list(cmd), **kwargs})
+ 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):
+ result = runner.invoke(main, ["unwrap", "openclaw", "--no-restart"])
+
+ assert result.exit_code == 0, result.output
+ assert ["openclaw", "gateway", "restart"] not in [c["cmd"] for c in calls]