mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 15:10:00 +08:00
feat/https-compose-caddy
3
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
4a851ed254 |
fix(codex): accept multi-line inline tables in Codex config.toml (#4436)
## Description
Codex accepts an inline table split across lines, with a trailing comma,
in `~/.codex/config.toml`:
```toml
env = {
DINGTALK_Client_ID = "**********",
}
```
That is TOML 1.1 syntax. Headroom reads the Codex config with the
standard library `tomllib`, which only implements TOML 1.0 before Python
3.15, so it rejects the file with `Invalid initial character for a key
part`. The result is what the issue shows: `headroom wrap codex` and
`headroom mcp install` refuse to register MCP servers ("is not valid
TOML ... refusing to overwrite") and session routing fails with "could
not read Codex config for session routing", even though Codex itself is
happy with the file.
`tomlkit` is already a runtime dependency (used for Codex config
recovery) and parses this syntax from 0.15.0. 0.13.3 and 0.14.0 both
fail on it (`Empty key at line 1 col 7`).
The fix adds one helper, `loads_codex_config()`, that parses with
`tomllib` first and only on `TOMLDecodeError` retries with `tomlkit`. If
`tomlkit` rejects the text too, it re-raises the original
`tomllib.TOMLDecodeError`, so every caller keeps its existing `except
tomllib.TOMLDecodeError` handling and its error messages unchanged. All
places that parse the user's Codex config now go through it.
The follow-up commit (`dc193870`) fixes a problem the first commit
exposed: once a multi-line inline table parses, a `profiles = {` table
can carry per-profile `model_provider` / `openai_base_url` keys on their
own indented lines, and the line-based "root key" edits in init, the
provider-scope install and persistent wrap mistook those nested lines
for root assignments. Init and install deleted the profile's provider,
and wrap rewrote it to `headroom` and then skipped adding a real root
`model_provider`. Those edits now only touch lines that are actual root
assignments.
Fixes #4378
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)
## Changes Made
- `headroom/providers/codex/config_toml.py` (new):
`loads_codex_config(content)`, `tomllib` first, `tomlkit` fallback,
original `tomllib` error if both fail.
- Routed the Codex config parse sites through it (15 call sites, 16
parse calls):
- `headroom/cli/wrap.py`: session routing read, the user-content check
and its fallback in `_inject_codex_provider_config`, and the two "never
write a malformed candidate" checks.
- `headroom/cli/init.py`: provider snapshot check, the candidate check
in `_ensure_codex_provider`, and `_codex_features`.
- `headroom/providers/codex/install.py`: `_codex_credential_store`,
`codex_auth_helper_is_referenced`, and the merged-config check before
writing.
- `headroom/providers/codex/project_context.py`: the `sqlite_home`
lookup.
- `headroom/mcp_registry/codex.py`: `_load_toml`, `_unmergeable_reason`,
and both sides of `_only_server_changed`. This registrar class is shared
with Grok, so a Grok `config.toml` with the same syntax is accepted too.
- Left on `tomllib` on purpose: `_table_path` (parses a single `[table]`
header line) and the auth snippet check in `build_codex_auth_config`
(validates text Headroom generates itself).
- `pyproject.toml` / `uv.lock`: raise the `tomlkit` minimum from
`>=0.13.0` to `>=0.15.0`, the first release that parses multi-line
inline tables. The lock already resolved 0.15.0, so `uv lock` only
changed the specifier line.
- Write paths: the user's text is never re-serialized by this change.
The registrar and the wrap/init injectors still append or splice marker
blocks as text, and the existing `tomlkit` round-trip in wrap keeps the
multi-line table byte for byte (checked below).
- Tests:
- `tests/test_provider_codex_config_toml.py`: the helper on the exact
shape from the issue (multi-line, trailing comma, whitespace-only line,
indented `}`), and that invalid TOML still raises
`tomllib.TOMLDecodeError`.
-
`tests/test_mcp_registry/test_codex_registrar.py::test_register_accepts_multiline_inline_table`:
registering into that config succeeds and the user's text is kept as a
byte-for-byte prefix.
-
`tests/test_cli/test_wrap_codex.py::test_codex_session_launch_settings_accept_multiline_inline_table`:
session routing reads that config and leaves the file untouched.
- Follow-up commit `dc193870` (multi-line inline profile overrides):
- `headroom/providers/codex/config_toml.py`:
`root_assignment_lines(content)` returns the indexes of lines that start
a key/value pair at the document root. It stops at the first table
header and skips lines inside a multi-line inline table, array or
string, with a small scanner that tracks quotes, comments and bracket
depth.
- `headroom/cli/init.py` (`_ensure_codex_provider`) and
`headroom/providers/codex/install.py`
(`_strip_root_provider_assignments`) only drop `model_provider` /
`openai_base_url` lines that are root assignments.
- `headroom/cli/wrap.py`: `_redirect_existing_top_level_keys` and
`_has_redirectable_top_level_key` only look at root assignments. Before,
they matched the key on any line, so a `[profiles.work]` section
override was also rewritten to `headroom` and counted as a root key;
that now stays the user's, matching how init, install and
`_strip_codex_headroom_blocks` already treat `[profiles.*]`.
- Tests:
`test_root_assignment_lines_skip_keys_nested_in_multiline_inline_table`,
`test_ensure_codex_provider_preserves_multiline_inline_profile_overrides`
(init),
`test_provider_scope_preserves_multiline_inline_profile_overrides`
(install) and `test_inject_preserves_multiline_inline_profile_overrides`
(wrap).
## Testing
- [x] Unit tests pass (`pytest`) - Codex, MCP registry, init and Grok
suites: 774 passed, 2 failed (the 2 failures are in
`tests/test_codex_responses_passthrough_bytes.py` and fail the same way
on `main` without this change)
- [x] Linting passes (`ruff check .`) - `ruff check` and `ruff format
--check` on the 9 changed Python files
- [x] Type checking passes (`mypy headroom`) - `mypy` on the 6 changed
source files, no issues
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
New end-to-end tests on `main` (fix stashed):
```text
$ pytest tests/test_mcp_registry/test_codex_registrar.py::test_register_accepts_multiline_inline_table tests/test_cli/test_wrap_codex.py::test_codex_session_launch_settings_accept_multiline_inline_table -q
E AssertionError: .../.codex/config.toml is not valid TOML (Invalid initial character for a key part (at line 3, column 8)); refusing to overwrite. Fix or remove the file, then re-run.
E click.exceptions.ClickException: could not read Codex config for session routing: Invalid initial character for a key part (at line 5, column 8)
============================== 2 failed in 0.38s ===============================
```
(`tests/test_provider_codex_config_toml.py` cannot import on `main`
because the helper does not exist yet.)
With the fix:
```text
$ pytest tests/test_provider_codex_config_toml.py tests/test_mcp_registry/test_codex_registrar.py::test_register_accepts_multiline_inline_table tests/test_cli/test_wrap_codex.py::test_codex_session_launch_settings_accept_multiline_inline_table -q
============================== 4 passed in 0.56s ===============================
$ pytest tests/test_provider_codex_config_toml.py tests/test_mcp_registry tests/test_cli/test_wrap_codex.py tests/test_cli/test_init_cli.py tests/test_install/test_codex_install.py tests/test_provider_codex*.py tests/test_provider_grok*.py tests/test_codex*.py -q
FAILED tests/test_codex_responses_passthrough_bytes.py::test_unmutated_zstd_post_forwards_decoded_bytes_and_strips_content_encoding - concurrent.futures._base.CancelledError
FAILED tests/test_codex_responses_passthrough_bytes.py::test_unmutated_plain_post_passes_original_bytes_through - concurrent.futures._base.CancelledError
================== 2 failed, 774 passed, 8 warnings in 50.43s ==================
$ pytest tests/test_codex_responses_passthrough_bytes.py -q # on main, without this change
========================= 2 failed, 1 warning in 4.09s =========================
$ mypy headroom/cli/init.py headroom/cli/wrap.py headroom/mcp_registry/codex.py headroom/providers/codex/install.py headroom/providers/codex/project_context.py headroom/providers/codex/config_toml.py
Success: no issues found in 6 source files
```
Follow-up commit, the three new write-path tests on the first commit
(`dfe93720`, source changes reverted):
```text
$ pytest tests/test_cli/test_init_cli.py tests/test_install/test_codex_install.py tests/test_cli/test_wrap_codex.py -k multiline_inline_profile -q
FAILED tests/test_cli/test_init_cli.py::test_ensure_codex_provider_preserves_multiline_inline_profile_overrides - AssertionError: assert {} == {'model_provi...y.example/v1'}
FAILED tests/test_install/test_codex_install.py::test_provider_scope_preserves_multiline_inline_profile_overrides - AssertionError: assert {} == {'model_provider': 'company'}
FAILED tests/test_cli/test_wrap_codex.py::TestSubscriptionRouting::test_inject_preserves_multiline_inline_profile_overrides - KeyError: 'model_provider'
====================== 3 failed, 220 deselected in 0.56s =======================
```
With `dc193870`:
```text
$ pytest tests/test_provider_codex_config_toml.py tests/test_cli/test_init_cli.py tests/test_install/test_codex_install.py tests/test_cli/test_wrap_codex.py -k "multiline_inline_profile or root_assignment" -q
======================= 4 passed, 222 deselected in 0.27s =======================
$ pytest tests/test_provider_codex_config_toml.py tests/test_cli/test_init_cli.py tests/test_install/ -q
================== 346 passed, 13 skipped, 1 warning in 3.94s ==================
$ pytest tests/test_cli/test_wrap_codex.py tests/test_cli/test_port_alignment.py -q
============================= 167 passed in 6.01s ==============================
$ pytest tests/test_mcp_registry/ tests/test_provider_codex_install.py tests/test_cli/test_install_cli.py tests/test_cli/test_recover_codex.py -q
============================= 364 passed in 4.71s ==============================
$ pytest tests/test_cli/test_wrap_persistent.py tests/test_codex_project_context.py tests/test_cli/test_wrap_stale_marker.py tests/test_cli/test_wrap_dead_marker_selfheal.py tests/test_provider_codex_runtime.py tests/test_install_tool_env_reconcile.py -q
======================== 4 failed, 261 passed in 9.01s =========================
```
The 4 failures are in `tests/test_cli/test_wrap_persistent.py`
(`AttributeError: '_Manifest' object has no attribute 'runtime_kind'`)
and fail the same way with this PR's changes stashed. `ruff check`,
`ruff format --check` (8 files) and `mypy` on the 4 changed source files
are clean.
tomlkit versions on the issue's snippet:
```text
0.13.3 FAIL Empty key at line 1 col 7
0.14.0 FAIL Empty key at line 1 col 7
0.15.0 {'env': {'A': 'x'}}
```
## Real Behavior Proof
- Environment: macOS 26.2 (Apple Silicon), Python 3.14.7, repo venv with
the `mcp` package installed, a throwaway `HOME`/`CODEX_HOME` whose
`config.toml` holds the issue's config:
```toml
[mcp_servers.dingtalk]
command = "npx"
env = {
DINGTALK_Client_ID = "**********",
}
```
- Exact command / steps: `HOME=<tmp>/home CODEX_HOME=<tmp>/home/.codex
python -m headroom.cli mcp install --agent codex`, then compare the
start of the resulting file with the original bytes and count
`[mcp_servers.headroom]` tables. Also called
`wrap._inject_codex_provider_config(8787)` and
`init._ensure_codex_provider(path, 8787)` on the same config to check
the write paths.
- Observed result: before (`main`):
```text
codex: install failed (failed): <tmp>/home/.codex/config.toml is not
valid TOML (Invalid initial character for a key part (at line 3, column
8)); refusing to overwrite. Fix or remove the file, then re-run.
```
After:
```text
codex: registered (restart the agent if it was already running)
```
The user's original bytes are an exact prefix of the new file and one
`[mcp_servers.headroom]` table was appended. The wrap injector printed
`Codex config: injected Headroom provider (WS + HTTP)`, and in both the
wrap and init outputs the user's multi-line table is still present
verbatim, the file parses, `env` is `{'DINGTALK_Client_ID':
'**********'}` and `model_provider` is `headroom`.
- Follow-up commit: with a throwaway `HOME`/`CODEX_HOME` holding
```toml
model_provider = "openai"
profiles = {
work = {
model_provider = "company",
},
}
```
I ran `init._ensure_codex_provider`, `install.apply_provider_scope`
(provider scope) and `wrap._inject_codex_provider_config` (same config
without the root key) and parsed the result:
```text
== before (
|
||
|
|
a6523b1967 |
fix(codex): preserve auth.json API keys through Headroom (#3355)
## Description Closes #3354. When Codex uses an OpenAI API key stored in auth.json, Headroom's generated provider block did not configure authentication. Codex therefore sent requests to the local Headroom proxy without an Authorization header and received 401 Missing bearer. This is separate from #3206: that issue covers ChatGPT OAuth authentication, while this change covers file-backed API-key authentication. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature - [ ] Breaking change - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring ## Changes Made - Resolve API-key and OAuth credentials from `codex_home_dir()` for both project and user configurations, honoring `CODEX_HOME`. - Generate a private, config-specific helper beside `auth.json`; API keys stay out of generated TOML and Headroom environment variables. - Configure Codex's supported `auth.command` field for persistent install, init, and wrap. - Serialize command and argument paths with literal Unicode and validate generated TOML before writing provider configurations. - Abort provider updates with an actionable error if a helper collides with another file/symlink or cannot be created. - Use exclusive creation, 0600 permissions on Unix, and content checks for helper ownership. - Give project and user configurations independent helper lifetimes. Retain legacy shared helpers and helpers referenced by restored/remaining providers or unparseable configurations. - Preserve unrelated files and the original provider config when authentication setup fails. - Remove an unused config-specific helper on uninstall/unwrap. ## Testing - [x] Focused unit and integration tests pass - [x] Linting and formatting pass - [ ] Type checking - [x] New regression tests added - [x] Manual runtime testing performed ### Test Output ```text $ .venv/bin/python -m pytest tests/test_provider_codex_install.py tests/test_install/test_codex_install.py tests/test_cli/test_init_cli.py tests/test_install/test_providers.py tests/test_cli/test_wrap_codex.py -q 284 passed $ .venv/bin/ruff check . All checks passed! $ .venv/bin/ruff format --check . 1744 files already formatted ``` Ruff 0.16.8 matches this branch's CI pin. A focused coverage run reports 93% line/branch coverage for `headroom/providers/codex/install.py` and covers 44/45 newly added executable lines across the three production files in this follow-up. This is local focused coverage, not a claim about the hosted Codecov aggregate. Before the follow-up implementation, the added local-init/Unicode/helper-isolation regressions produced 6 failures while 118 existing tests passed. ## Real Behavior Proof - Environment: macOS 26.6.2, Apple Silicon arm64, Python 3.12.11, Headroom source from this PR, Codex CLI 0.160.0, Sub2API OpenAI-compatible provider, model `gpt-6-luna`, existing API key in the user's Codex `auth.json`. - Setup: start an isolated Headroom proxy on an unused loopback port with `ProxyConfig(optimize=False, cache_enabled=False, rate_limit_enabled=False, openai_api_url=<existing upstream>)`. Generate a temporary provider config with `_ensure_codex_provider(config_path, port)` while credentials resolve from the user's Codex home. Add `model = "gpt-6-luna"` and `model_reasoning_effort = "low"` at the document root. Run the child with its own temporary `CODEX_HOME` and no `OPENAI_API_KEY` or `OPENAI_BASE_URL` environment variable; its home contains the generated config, not a copied credential file. - Exact child command: ```sh CODEX_HOME=<temporary-home> codex exec --ephemeral --skip-git-repo-check --sandbox read-only --json -C <temporary-workspace> 'Reply with exactly OK. Do not call tools.' ``` Captured after-fix output on 2026-10-07: ```text Headroom test proxy: ready (optimization disabled) Codex: 0.160.0; model: gpt-6-luna; auth: generated command, no API-key environment variable codex exec exit: 0 agent messages: ['OK'] Responses bearer matches auth.json: True ``` The last line comes from an ASGI wrapper that compares the HTTP/WebSocket Responses request bearer with the file-backed key without logging either value. The command completed against the real upstream; no mocked model response was used. The temporary provider config/helper and test proxy were removed after validation. - Observed limitation: this upstream rejects WebSocket negotiation with HTTP 426, so Headroom's existing HTTP streaming fallback completed the request. This run proves file-backed command authentication and successful proxy routing, not a successful upstream WebSocket session. - Not tested in this follow-up: a new Windows/Linux runtime run, full test suite, native-extension rebuild, or optimization behavior. The focused Python suite reused the existing local native extension; no Rust code changed. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A. - Stable/default behavior changed: Yes, only when Codex has a file-backed API key and Headroom writes a provider block. - Kill switch / disable path: Remove the Headroom-managed provider block or run the existing Codex unwrap command. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert the generated provider block; auth.json is unchanged. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of the code - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective - [x] New and existing unit tests pass locally with my changes - [x] I did not edit CHANGELOG.md ## Additional Notes Helpers contain no credential value and read the user's existing credential file at runtime, so key rotation does not require reinstalling. Helper names now include a hash of the owning config's canonical path. Legacy fixed-name helpers are retained conservatively because other project configurations may still use them. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3355" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
46293f4daf |
fix(codex): detect keyring-backed ChatGPT auth (#2478)
## Description Headroom currently treats missing `auth.json` as “not ChatGPT auth” for Codex, which breaks keyring-backed ChatGPT sessions on Codex CLI 0.144.6 because those sessions intentionally may not store credentials in the file. This updates the Codex auth detector to keep the existing file-backed fast path and fall back to Codex-owned auth metadata when the session is keyring-backed or auto-backed, so `requires_openai_auth = true` is emitted only for real ChatGPT logins. Closes #2474 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - extend Codex auth detection so keyring-backed and auto-backed sessions can be classified from Codex-owned auth metadata when `auth.json` is absent - preserve the current file-backed ChatGPT, API-key, malformed-file, and fail-closed behaviors - add focused install-layer regression coverage for the new keyring path and adjacent negative space ## Testing - [x] Unit tests pass (`uv run pytest tests/test_install/test_codex_install.py -q`) - [x] Linting passes (`uv run ruff check headroom/providers/codex/install.py tests/test_install/test_codex_install.py`) - [ ] Type checking passes (`uv run mypy headroom`) - [x] New tests added for new functionality when applicable - [x] Manual testing performed ### Test Output ```text uv run pytest tests/test_install/test_codex_install.py -q ============================= test session starts ============================= platform win32 -- Python 3.12.13, pytest-9.0.3, pluggy-1.6.0 collected 9 items tests\test_install\test_codex_install.py ......... [100%] ============================== 9 passed in 0.24s ============================== uv run ruff check headroom/providers/codex/install.py tests/test_install/test_codex_install.py All checks passed! ``` ## Real Behavior Proof - Environment: Windows, Codex CLI 0.144.6 available locally, Python 3.12.13 via `uv` - Exact command / steps: `codex login status`; `Measure-Command { codex login status > $null }`; focused pytest and Ruff commands above - Observed result: `codex login status` returns `stdout=''` and `stderr='Logged in using ChatGPT\n'`; the status probe measured `71.40` ms; pytest reports `9 passed in 0.24s`; keyring ChatGPT emits `requires_openai_auth = true`, non-ChatGPT and failed probes omit it, and file-backed ChatGPT/API-key cases remain true/false - Not tested: live local keyring-backed Codex login ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable ## Additional Notes `CHANGELOG.md` stays untouched because Headroom generates release notes from conventional commits. The PR should only claim the Codex-owned detection path and focused local regression coverage; the live keyring session proof remains a follow-up owner check. |