fix: inject openai_base_url so Codex subscription (ChatGPT plan) routes through proxy

Codex subscription mode uses the built-in openai provider with
chatgpt.com/backend-api/codex as the default base URL, bypassing
OPENAI_BASE_URL and the custom model_provider setting entirely.

Setting openai_base_url in config.toml overrides that default for all
auth modes (API key and ChatGPT subscription), so both traffic paths
now flow through the Headroom proxy.

Also adds orphan-cleanup regex for openai_base_url in
_strip_codex_headroom_blocks and 5 new tests covering subscription
routing behaviour.
This commit is contained in:
chopratejas
2026-05-05 14:33:41 -07:00
parent 19a43f0d52
commit 5c7a5b4857
2 changed files with 91 additions and 9 deletions
+29 -8
View File
@@ -457,9 +457,14 @@ def _strip_codex_headroom_blocks(content: str) -> str:
content = content.replace(_CODEX_TOP_LEVEL_MARKER + "\n", "")
content = content.replace(_CODEX_END_MARKER + "\n", "")
# Strip any leftover top-level `model_provider = "headroom"` line, which
# older versions of `wrap codex` wrote outside the marker block.
# 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,
)
# Strip any orphaned `[model_providers.headroom]` table with the fields we
# write. We only remove it if the table is recognisably ours (base_url
@@ -537,10 +542,20 @@ def _prepare_wrap_rtk(verbose: bool = False, *, label: str | None = None) -> Pat
def _inject_codex_provider_config(port: int) -> None:
"""Inject a Headroom model provider into Codex's config.toml.
Codex ignores OPENAI_BASE_URL for WebSocket transport unless a custom
provider declares ``supports_websockets = true``. This writes a
``[model_providers.headroom]`` section that routes both HTTP and WS
through the proxy, and sets ``model_provider = "headroom"``.
Two keys are written in the top-level block:
* ``model_provider = "headroom"`` — selects the custom provider for
API-key mode traffic.
* ``openai_base_url = "http://127.0.0.1:{port}/v1"`` — overrides the
built-in ``openai`` provider's base URL. This is the critical key for
**subscription (ChatGPT plan) users**: Codex detects subscription auth
and routes through the built-in ``openai`` provider regardless of
``model_provider``, so without this override it bypasses the proxy and
hits ``https://chatgpt.com/backend-api/codex`` directly.
A ``[model_providers.headroom]`` section is also written with
``supports_websockets = true`` so that WebSocket transport (used by
default) also flows through the proxy for API-key users.
Safe to call multiple times — the injected block is fully replaced on
each call, so re-running with a different ``port`` updates the config.
@@ -558,7 +573,10 @@ def _inject_codex_provider_config(port: int) -> None:
# stripping them is unambiguous and never consumes user content that
# happens to sit between the two.
top_level_block = (
f'{_CODEX_TOP_LEVEL_MARKER}\nmodel_provider = "headroom"\n{_CODEX_END_MARKER}\n'
f"{_CODEX_TOP_LEVEL_MARKER}\n"
f'model_provider = "headroom"\n'
f'openai_base_url = "http://127.0.0.1:{port}/v1"\n'
f"{_CODEX_END_MARKER}\n"
)
provider_section = (
f"{_CODEX_TOP_LEVEL_MARKER}\n"
@@ -596,7 +614,10 @@ def _inject_codex_provider_config(port: int) -> None:
content = top_level_block + "\n" + provider_section
config_file.write_text(content)
click.echo(f" Codex config: injected Headroom provider (WS + HTTP) into {config_file}")
click.echo(
f" Codex config: injected Headroom provider (WS + HTTP, API-key + subscription)"
f" into {config_file}"
)
except Exception as e:
click.echo(f" Warning: could not update Codex config: {e}")
+62 -1
View File
@@ -195,9 +195,11 @@ class TestInjectAndRestoreRoundTrip:
# provider-table block. Re-wrapping must not duplicate them.
assert content.count(wrap_mod._CODEX_TOP_LEVEL_MARKER) == 2
assert content.count(wrap_mod._CODEX_END_MARKER) == 2
# Latest port is honoured.
# Latest port is honoured in both keys.
assert 'base_url = "http://127.0.0.1:9999/v1"' in content
assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in content
assert 'base_url = "http://127.0.0.1:8787/v1"' not in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' not in content
# User's original content is preserved.
assert 'model = "gpt-4o"' in content
@@ -256,6 +258,65 @@ class TestInjectAndRestoreRoundTrip:
assert config_file.read_text() == malformed
# ---------------------------------------------------------------------------
# Subscription routing: openai_base_url intercepts ChatGPT plan traffic
# ---------------------------------------------------------------------------
class TestSubscriptionRouting:
"""Codex subscription (ChatGPT plan) bypasses OPENAI_BASE_URL and the
custom model_provider; it uses the built-in ``openai`` provider whose
base_url defaults to ``https://chatgpt.com/backend-api/codex``.
Setting ``openai_base_url`` overrides that default for all auth modes."""
def test_inject_writes_openai_base_url(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
content = (tmp_path / ".codex" / "config.toml").read_text()
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in content
def test_openai_base_url_port_updates_on_rewrap(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
wrap_mod._inject_codex_provider_config(8787)
wrap_mod._inject_codex_provider_config(9999)
content = (tmp_path / ".codex" / "config.toml").read_text()
assert 'openai_base_url = "http://127.0.0.1:9999/v1"' in content
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' not in content
def test_openai_base_url_removed_on_unwrap(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
config_dir = tmp_path / ".codex"
config_dir.mkdir()
config_file = config_dir / "config.toml"
original = '[profiles.default]\nmodel = "gpt-4o"\n'
config_file.write_text(original)
wrap_mod._inject_codex_provider_config(8787)
assert 'openai_base_url = "http://127.0.0.1:8787/v1"' in config_file.read_text()
wrap_mod._restore_codex_provider_config()
assert config_file.read_text() == original
def test_strip_cleans_orphaned_openai_base_url(self) -> None:
"""Safety net: orphaned openai_base_url lines are cleaned up."""
content = (
'[profiles.default]\nmodel = "gpt-4o"\nopenai_base_url = "http://127.0.0.1:8787/v1"\n'
)
cleaned = wrap_mod._strip_codex_headroom_blocks(content)
assert "openai_base_url" not in cleaned
assert 'model = "gpt-4o"' in cleaned
# ---------------------------------------------------------------------------
# Integration tests: full `headroom wrap codex` / `headroom unwrap codex`
# ---------------------------------------------------------------------------