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.

fix(codex): make unwrap codex remove headroom init routing (#3920)

Parideboy326079517b40
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdx
index d2459e271..7d49ed051 100644
--- a/docs/content/docs/proxy.mdx
+++ b/docs/content/docs/proxy.mdx
@@ -912,7 +912,13 @@ headroom init -g codex # ~/.codex/config.toml, for every project
```
That routing is persistent: it applies to every Codex session in that scope
-until you remove it.
+until you remove it. `headroom unwrap codex` removes the `-g` routing; for a
+project, delete the `# --- Headroom init provider ---` block from
+`.codex/config.toml`. Unwrap removes only the routing: the Headroom
+`SessionStart` hook that `init` adds to Codex's `hooks.json` stays, and still
+starts a proxy when a Codex session begins until you delete it. On Windows,
+nothing starts the proxy for this routing, so Codex cannot connect while the
+proxy is down; use `headroom install apply` if you need a supervised proxy.
Cursor reads model endpoints from its settings UI, so `headroom wrap cursor`
does not rewrite Cursor configuration or launch the app. After it starts the
diff --git a/headroom/cli/init.py b/headroom/cli/init.py
index 26178d951..3d3b9d72f 100644
--- a/headroom/cli/init.py
+++ b/headroom/cli/init.py
@@ -319,6 +319,27 @@ def _remove_marker_block(content: str, marker_start: str, marker_end: str) -> st
return content[:start].rstrip() + "\n\n" + content[end:].lstrip()
+def _strip_codex_root_routing_orphans(content: str) -> str:
+ """Drop Headroom loopback routing keys left at the document root.
+
+ Only the root (everything before the first table header) is Headroom's to
+ clean: the same keys inside ``[profiles.*]`` tables are user-owned
+ per-profile overrides, even when they point at Headroom.
+ """
+ import re
+
+ first_table = re.search(r"(?m)^[ \t]*\[", content)
+ split = first_table.start() if first_table else len(content)
+ root, rest = content[:split], content[split:]
+ root = re.sub(r'(?m)^[ \t]*model_provider[ \t]*=[ \t]*"headroom"[ \t]*\r?\n', "", root)
+ root = re.sub(
+ r'(?m)^[ \t]*openai_base_url[ \t]*=[ \t]*"http://127\.0\.0\.1:\d+/v1"[ \t]*\r?\n',
+ "",
+ root,
+ )
+ return root + rest
+
+
def _strip_codex_init_block(content: str) -> str:
"""Remove all Headroom init-managed blocks and orphan keys from a Codex config.toml string."""
import re
@@ -338,12 +359,7 @@ def _strip_codex_init_block(content: str) -> str:
# Strip any orphan top-level keys that a crashed or partial write may have
# left outside the marker block.
- content = re.sub(r'(?m)^[ \t]*model_provider[ \t]*=[ \t]*"headroom"[ \t]*\r?\n', "", content)
- content = re.sub(
- r'(?m)^[ \t]*openai_base_url[ \t]*=[ \t]*"http://127\.0\.0\.1:\d+/v1"[ \t]*\r?\n',
- "",
- content,
- )
+ content = _strip_codex_root_routing_orphans(content)
# Strip any orphaned [model_providers.headroom] table that is recognisably ours.
orphan_headroom_table = re.compile(
@@ -921,6 +937,12 @@ def _init_codex(*, global_scope: bool, profile: str, port: int) -> None:
click.echo(
"Codex hooks are currently disabled upstream on Windows; provider routing was still installed."
)
+ click.echo(
+ "Nothing starts the Headroom proxy for Codex on Windows, so Codex cannot connect "
+ "while it is down. Use `headroom install apply` for a supervised proxy. To remove "
+ "this routing, run `headroom unwrap codex` (user scope) or delete the Headroom init "
+ "provider block from the project's .codex/config.toml."
+ )
click.echo("Restart Codex to activate Headroom configuration.")
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index a8036e1c6..39e248b98 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -3109,13 +3109,11 @@ def _strip_codex_headroom_blocks(
content = _remove_marker_span(content, _MEMORY_MCP_MARKER, _MEMORY_MCP_END)
# Strip any leftover top-level keys that older (or crashed) versions of
- # `wrap codex` may have written outside the marker block.
- content = re.sub(r'(?m)^[ \t]*model_provider[ \t]*=[ \t]*"headroom"[ \t]*\r?\n', "", content)
- content = re.sub(
- r'(?m)^[ \t]*openai_base_url[ \t]*=[ \t]*"http://127\.0\.0\.1:\d+/v1"[ \t]*\r?\n',
- "",
- content,
- )
+ # `wrap codex` may have written outside the marker block. Root only:
+ # [profiles.*] overrides are the user's.
+ from headroom.cli.init import _strip_codex_root_routing_orphans
+
+ content = _strip_codex_root_routing_orphans(content)
# Remove an orphaned local-proxy provider structurally. Text-level table
# matching cannot safely distinguish comments, multiline strings, and
@@ -3634,7 +3632,8 @@ def _inject_codex_provider_config(port: int) -> str | None:
def _restore_codex_provider_config() -> tuple[str, Path]:
- """Undo ``_inject_codex_provider_config`` for the active Codex config file.
+ """Undo ``_inject_codex_provider_config`` (and ``headroom init codex``
+ routing) for the active Codex config file.
Returns a tuple of ``(status, config_file)`` where status is one of:
@@ -3643,21 +3642,37 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
* ``"cleaned"`` — no backup existed, but the Headroom-managed block was
found and stripped out (preserving surrounding user content).
* ``"removed"`` — the config file only contained Headroom-managed
- content (created by wrap) and has been deleted.
+ content (created by wrap or init) and has been deleted.
* ``"noop"`` — nothing to undo; no Headroom marker and no backup.
"""
+ from headroom.cli.init import _CODEX_PROVIDER_MARKER_START, _strip_codex_init_block
+
config_file, backup_file = _codex_config_paths()
# Case 1: pre-wrap snapshot exists — restore it exactly.
if backup_file.exists():
- shutil.copy2(backup_file, config_file)
+ # A snapshot taken after `headroom init codex` still carries init's
+ # routing block; restoring it verbatim would leave Codex pinned to the
+ # proxy while unwrap reports success (#3749). The snapshot is deleted
+ # only once the config is written, so a failed write can be retried.
+ snapshot = _read_text(backup_file)
+ if _CODEX_PROVIDER_MARKER_START in snapshot:
+ cleaned = _strip_codex_init_block(snapshot)
+ if not cleaned.strip():
+ config_file.unlink(missing_ok=True)
+ backup_file.unlink()
+ return "removed", config_file
+ _write_text(config_file, cleaned)
+ else:
+ shutil.copy2(backup_file, config_file)
backup_file.unlink()
return "restored", config_file
# Case 2: no backup, but config file exists and has markers — strip them.
if config_file.exists():
original = _read_text(config_file)
- if _codex_config_has_headroom_markers(original):
+ has_init_block = _CODEX_PROVIDER_MARKER_START in original
+ if has_init_block or _codex_config_has_headroom_markers(original):
# Without a backup, only remove named MCP blocks when this file
# also carries wrap-owned provider markers from a full wrap.
remove_named_mcp = any(
@@ -3669,8 +3684,11 @@ def _restore_codex_provider_config() -> tuple[str, Path]:
_CODEX_MCP_END,
)
)
+ # `headroom init codex` writes its own routing block, and nothing else
+ # removes it (#3749). Strip it first so its markers go with its keys.
+ content = _strip_codex_init_block(original) if has_init_block else original
cleaned = _strip_codex_headroom_blocks(
- original,
+ content,
remove_mcp=True,
remove_named_mcp=remove_named_mcp,
)
@@ -8785,7 +8803,7 @@ def unwrap_grok_build(port: int, no_stop_proxy: bool) -> None:
)
@click.option("--no-stop-proxy", is_flag=True, help="Do not stop the local Headroom proxy")
def unwrap_codex(port: int, no_stop_proxy: bool) -> None:
- """Undo ``headroom wrap codex`` edits to the active Codex config file.
+ """Undo ``headroom wrap codex`` and ``headroom init codex`` routing in the Codex config.
Behaviour:
diff --git a/tests/test_cli/test_init_cli.py b/tests/test_cli/test_init_cli.py
index 352d6341c..6f953383c 100644
--- a/tests/test_cli/test_init_cli.py
+++ b/tests/test_cli/test_init_cli.py
@@ -1368,6 +1368,8 @@ def test_init_codex_windows_warns_about_upstream_hook_limitation(monkeypatch) ->
init_cli._init_codex(global_scope=True, profile="init-user", port=9000)
assert any("disabled upstream on Windows" in message for message in messages)
+ # Routing to a proxy nothing restarts must come with a way out (#3749).
+ assert any("headroom unwrap codex" in message for message in messages)
def test_init_openclaw_propagates_nonzero_exit(monkeypatch) -> None:
diff --git a/tests/test_cli/test_wrap_codex.py b/tests/test_cli/test_wrap_codex.py
index 95ccffe0d..685faa6b9 100644
--- a/tests/test_cli/test_wrap_codex.py
+++ b/tests/test_cli/test_wrap_codex.py
@@ -802,12 +802,18 @@ class TestSubscriptionRouting:
assert config_file.read_text(encoding="utf-8") == original
def test_strip_cleans_orphaned_openai_base_url(self) -> None:
- """Safety net: orphaned openai_base_url lines are cleaned up."""
+ """Safety net: orphaned root openai_base_url lines are cleaned up.
+
+ Wrap only ever writes these keys at the document root; the same key
+ inside a [profiles.*] table is a user override and stays.
+ """
content = (
- '[profiles.default]\nmodel = "gpt-4o"\nopenai_base_url = "http://127.0.0.1:8787/v1"\n'
+ 'openai_base_url = "http://127.0.0.1:8787/v1"\n\n'
+ '[profiles.default]\nmodel = "gpt-4o"\nopenai_base_url = "http://127.0.0.1:9999/v1"\n'
)
cleaned = wrap_mod._strip_codex_headroom_blocks(content)
- assert "openai_base_url" not in cleaned
+ assert "127.0.0.1:8787" not in cleaned
+ assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in cleaned
assert 'model = "gpt-4o"' in cleaned
def test_no_env_key_in_injected_provider(
@@ -2137,6 +2143,138 @@ def test_unwrap_codex_preserves_unrelated_sections(
assert restored == original
+def test_unwrap_codex_removes_init_provider_routing(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """`headroom init -g codex` routing must be removable with `unwrap codex` (#3749).
+
+ Without this, unwrap reported "no longer routed" while Codex stayed pinned
+ to a local proxy that nothing restarts on Windows.
+ """
+ from headroom.cli import init as init_cli
+
+ _set_test_home(monkeypatch, tmp_path)
+ config_file = tmp_path / ".codex" / "config.toml"
+ config_file.parent.mkdir(parents=True)
+ original = 'model = "gpt-5"\n\n[mcp_servers.local_thing]\ncommand = "thing"\n'
+ config_file.write_text(original, encoding="utf-8")
+ init_cli._ensure_codex_provider(config_file, 8787)
+ assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in config_file.read_text(encoding="utf-8")
+
+ result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
+
+ assert result.exit_code == 0, result.output
+ assert "Nothing to undo" not in result.output
+ cleaned = config_file.read_text(encoding="utf-8")
+ assert "Headroom init provider" not in cleaned
+ assert "openai_base_url" not in cleaned
+ assert "model_providers.headroom" not in cleaned
+ assert tomllib.loads(cleaned) == tomllib.loads(original)
+
+
+def test_unwrap_codex_removes_init_only_config_file(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ from headroom.cli import init as init_cli
+
+ _set_test_home(monkeypatch, tmp_path)
+ config_file = tmp_path / ".codex" / "config.toml"
+ init_cli._ensure_codex_provider(config_file, 8787)
+
+ result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
+
+ assert result.exit_code == 0, result.output
+ assert not config_file.exists()
+
+
+def test_unwrap_codex_after_init_then_wrap_removes_init_routing(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """init -> persistent wrap -> unwrap: the pre-wrap snapshot holds init's
+ routing, so restoring it verbatim left Codex pinned to the proxy."""
+ from headroom.cli import init as init_cli
+
+ _set_test_home(monkeypatch, tmp_path)
+ config_file = tmp_path / ".codex" / "config.toml"
+ config_file.parent.mkdir(parents=True)
+ original = 'model = "gpt-5"\n\n[mcp_servers.local_thing]\ncommand = "thing"\n'
+ config_file.write_text(original, encoding="utf-8")
+ init_cli._ensure_codex_provider(config_file, 8787)
+ runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
+ assert wrap_mod._codex_config_paths()[1].exists()
+
+ result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
+
+ assert result.exit_code == 0, result.output
+ assert "Restored prior" in result.output
+ restored = config_file.read_text(encoding="utf-8")
+ assert "Headroom init provider" not in restored
+ assert "127.0.0.1:8787" not in restored
+ assert tomllib.loads(restored) == tomllib.loads(original)
+
+
+def test_unwrap_codex_keeps_snapshot_when_init_cleanup_write_fails(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A failed write of the init-cleaned snapshot must not consume the
+ snapshot, or a retry has nothing left to restore."""
+ from headroom.cli import init as init_cli
+
+ _set_test_home(monkeypatch, tmp_path)
+ config_file = tmp_path / ".codex" / "config.toml"
+ config_file.parent.mkdir(parents=True)
+ original = 'model = "gpt-5"\n\n[mcp_servers.local_thing]\ncommand = "thing"\n'
+ config_file.write_text(original, encoding="utf-8")
+ init_cli._ensure_codex_provider(config_file, 8787)
+ runner.invoke(main, ["wrap", "codex", "--prepare-only", "--port", "8787"])
+ backup_file = wrap_mod._codex_config_paths()[1]
+ assert backup_file.exists()
+
+ def failing_write(path: Path, content: str) -> None:
+ raise OSError("disk full")
+
+ with monkeypatch.context() as m:
+ m.setattr(wrap_mod, "_write_text", failing_write)
+ failed = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
+
+ assert failed.exit_code != 0
+ assert backup_file.exists()
+
+ result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
+
+ assert result.exit_code == 0, result.output
+ assert "Restored prior" in result.output
+ restored = config_file.read_text(encoding="utf-8")
+ assert "127.0.0.1:8787" not in restored
+ assert tomllib.loads(restored) == tomllib.loads(original)
+
+
+def test_unwrap_codex_init_cleanup_keeps_profile_overrides(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Orphan cleanup is root-only: [profiles.*] routing keys are user-owned,
+ even when they point at a Headroom proxy."""
+ from headroom.cli import init as init_cli
+
+ _set_test_home(monkeypatch, tmp_path)
+ config_file = tmp_path / ".codex" / "config.toml"
+ config_file.parent.mkdir(parents=True)
+ original = (
+ 'model = "gpt-5"\n\n'
+ "[profiles.work]\n"
+ 'model_provider = "headroom"\n'
+ 'openai_base_url = "http://127.0.0.1:9999/v1"\n'
+ )
+ config_file.write_text(original, encoding="utf-8")
+ init_cli._ensure_codex_provider(config_file, 8787)
+
+ result = runner.invoke(main, ["unwrap", "codex", "--no-stop-proxy"])
+
+ assert result.exit_code == 0, result.output
+ assert tomllib.loads(config_file.read_text(encoding="utf-8")) == tomllib.loads(original)
+ assert tomllib.loads(wrap_mod._strip_codex_headroom_blocks(original)) == tomllib.loads(original)
+
+
# ---------------------------------------------------------------------------
# Per-project savings: env_http_headers in the injected provider block
# ---------------------------------------------------------------------------