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
fix(codex): keep init model_provider at config root (#260)
Matt849b46de5934
diff --git a/headroom/cli/init.py b/headroom/cli/init.pyindex a01dc293c..4d7ab1c14 100644--- a/headroom/cli/init.py+++ b/headroom/cli/init.py@@ -199,12 +199,27 @@ def _ensure_copilot_hooks(path: Path, profile: str) -> None:_write_json(path, payload)-def _replace_marker_block(content: str, marker_start: str, marker_end: str, block: str) -> str:+def _replace_marker_block(+ content: str, marker_start: str, marker_end: str, block: str, *, at_root: bool = False+) -> str:if marker_start in content and marker_end in content:start = content.index(marker_start)end = content.index(marker_end) + len(marker_end)content = content[:start].rstrip() + "\n\n" + content[end:].lstrip()- return (content.rstrip() + "\n\n" + block.strip() + "\n").lstrip()+ block = block.strip()+ if at_root:+ # The block carries top-level keys, so it must sit above the first table+ # header; appended after a table (e.g. [features]) TOML scopes those keys+ # into that table and Codex rejects the config (#260).+ lines = content.splitlines()+ for index, line in enumerate(lines):+ stripped = line.strip()+ if stripped.startswith("[") and stripped.endswith("]"):+ head = "\n".join(lines[:index]).rstrip()+ tail = "\n".join(lines[index:]).lstrip("\n")+ prefix = f"{head}\n\n" if head else ""+ return (f"{prefix}{block}\n\n{tail}").rstrip() + "\n"+ return (content.rstrip() + "\n\n" + block + "\n").lstrip()def _strip_codex_init_block(content: str) -> str:@@ -245,6 +260,8 @@ def _strip_codex_init_block(content: str) -> str:def _ensure_codex_provider(path: Path, port: int) -> None:+ import re+logger.debug("ensure codex provider block: %s (port=%s)", path, port)block = (f"{_CODEX_PROVIDER_MARKER_START}\n"@@ -257,8 +274,15 @@ def _ensure_codex_provider(path: Path, port: int) -> None:f"{_CODEX_PROVIDER_MARKER_END}")content = path.read_text(encoding="utf-8") if path.exists() else ""+ # init owns model_provider/openai_base_url: drop any prior assignment (any+ # value, including one an older version mis-scoped under a table) so we+ # replace it instead of emitting a duplicate top-level key (#260).+ content = re.sub(r"(?m)^[ \t]*model_provider[ \t]*=.*\r?\n", "", content)+ content = re.sub(r"(?m)^[ \t]*openai_base_url[ \t]*=.*\r?\n", "", content)+ # The provider block carries top-level keys (model_provider, openai_base_url),+ # so it must land at the document root rather than after a trailing table (#260).content = _replace_marker_block(- content, _CODEX_PROVIDER_MARKER_START, _CODEX_PROVIDER_MARKER_END, block+ content, _CODEX_PROVIDER_MARKER_START, _CODEX_PROVIDER_MARKER_END, block, at_root=True)path.parent.mkdir(parents=True, exist_ok=True)path.write_text(content, encoding="utf-8")diff --git a/tests/test_cli/test_init_cli.py b/tests/test_cli/test_init_cli.pyindex b5feaa94b..a545217df 100644--- a/tests/test_cli/test_init_cli.py+++ b/tests/test_cli/test_init_cli.py@@ -7,6 +7,11 @@ import typesfrom pathlib import Pathfrom types import SimpleNamespace+try:+ import tomllib+except ModuleNotFoundError: # Python < 3.11+ import tomli as tomllib # type: ignore[no-redef]+import clickimport pytestfrom click.testing import CliRunner@@ -440,6 +445,49 @@ def test_ensure_codex_provider_replaces_existing_marker(monkeypatch, tmp_path: Passert 'env_key = "OPENAI_API_KEY"' not in content+def test_ensure_codex_provider_keeps_root_keys_above_existing_table(+ monkeypatch, tmp_path: Path+) -> None:+ """#260: a config ending in a table must not capture the provider root keys.++ Appending the block after a trailing [features] table scoped model_provider+ under it, so Codex refused to start with+ 'invalid type: string "headroom", expected a boolean in features'.+ """+ init_cli, _ = _load_init_module(monkeypatch)+ path = tmp_path / "config.toml"+ path.write_text("[features]\ncodex_hooks = true\n", encoding="utf-8")++ init_cli._ensure_codex_provider(path, 8787)++ parsed = tomllib.loads(path.read_text(encoding="utf-8"))+ # model_provider belongs at the document root, not under [features].+ assert parsed["model_provider"] == "headroom"+ assert "model_provider" not in parsed["features"]+ assert "openai_base_url" not in parsed["features"]+ # The user's existing table is preserved.+ assert parsed["features"]["codex_hooks"] is True+ assert parsed["model_providers"]["headroom"]["base_url"] == "http://127.0.0.1:8787/v1"+++def test_ensure_codex_provider_replaces_existing_model_provider(+ monkeypatch, tmp_path: Path+) -> None:+ """A pre-existing root model_provider is replaced, never duplicated (#260).++ A second top-level model_provider key would be invalid TOML; init owns it.+ """+ init_cli, _ = _load_init_module(monkeypatch)+ path = tmp_path / "config.toml"+ path.write_text('model_provider = "openai"\n[features]\ncodex_hooks = true\n', encoding="utf-8")++ init_cli._ensure_codex_provider(path, 8787)++ parsed = tomllib.loads(path.read_text(encoding="utf-8")) # raises on a duplicate key+ assert parsed["model_provider"] == "headroom"+ assert parsed["features"]["codex_hooks"] is True++def test_ensure_codex_feature_flag_replaces_existing_marker(monkeypatch, tmp_path: Path) -> None:init_cli, _ = _load_init_module(monkeypatch)path = tmp_path / "config.toml"