fix(proxy): classify Pi Codex Responses alias (#2583)

## Description

Pi-compatible clients such as Gajae-Code open the Codex Responses
WebSocket at `/v1/codex/responses`, an alias added in #196. The
unidentified-client stamp added in #1036 only recognizes
`/v1/responses`, while Gajae-Code currently identifies itself as
`pi/<version>`. The alias therefore remains unclassified and takes the
generic proxy compression-timeout path instead of the Codex fail-open
path.

This change applies the existing narrow `X-Client: codex` stamp to the
Pi-compatible alias and its subpaths. Explicit `X-Client` values and
already-recognized user agents remain untouched.

Refs #196 and #1036.

## 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 causes existing functionality
to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Treat `/v1/codex/responses` and its subpaths as Codex Responses paths
for unidentified-client stamping.
- Add regression coverage for the exact Pi-compatible alias and its
compact subpath.
- Add a WebSocket lifecycle test proving the alias forwards `X-Client:
codex` upstream.

## Testing

- [ ] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run pytest tests/test_codex_client_stamp.py tests/test_auth_policy.py tests/test_auth_mode.py tests/test_proxy_codex_route_aliases.py tests/test_openai_codex_ws_lifecycle.py -q
81 passed, 1 pre-existing Starlette deprecation warning in 35.79s

$ uv run ruff check .
All checks passed!

$ uv run ruff format --check headroom/proxy/auth_policy.py tests/test_codex_client_stamp.py tests/test_openai_codex_ws_lifecycle.py
3 files already formatted

$ uv run mypy headroom
Success: no issues found in 509 source files

$ uv run pre-commit run --files headroom/proxy/auth_policy.py tests/test_codex_client_stamp.py tests/test_openai_codex_ws_lifecycle.py
All configured hooks passed
```

The full suite completed with `9696 passed, 568 skipped, 15 failed`. The
15 failures are outside this diff: existing `unwrap claude` signature
mismatches, environment-dependent Kompress health expectations, an
overlong AF_UNIX test path, and a missing local Rust toolchain. The
focused Codex routing suite above is green.

## Real Behavior Proof

- Environment: macOS Darwin 25.5 arm64, Python 3.13.13, Gajae-Code
0.11.11, `openai-codex/gpt-5.6-sol`; patched Headroom source proxy on
`127.0.0.1:8788` in cache mode with OpenAI Kompress disabled. The
isolated GJC model config contained the proxy base URL and deliberately
had no `X-Client` header override.
- Exact command / steps: Exercised the patched source proxy through the
live Pi-compatible alias as follows:
1. Start the patched source proxy with `uv run headroom proxy --host
127.0.0.1 --port 8788 --mode cache --disable-kompress-openai
--stateless`.
2. Point an isolated GJC agent config at `http://127.0.0.1:8788/v1`
without custom headers.
3. Run `gjc -p --no-session --no-tools --system-prompt "Reply exactly as
requested." --model openai-codex/gpt-5.6-sol "Reply with exactly
ALIAS_OK."`.
- Observed result: GJC returned `ALIAS_OK`. The live proxy recorded
`path=/v1/codex/responses` and the request outcome ended with
`client=codex` (`tok_before=3120`, `tok_after=3081`, `tok_saved=39`).
Before the patch, the same installed classifier returned `False` for
this alias and live GJC outcomes had an empty client classification
(reported as `proxy` by the savings ledger).
- Not tested: Windows/Linux live providers, token mode, or the broader
compression scheduler changes proposed in #963. The full repository
suite is not locally green for the unrelated failures listed above.

## Runtime Rollout Safety

- Rollout-managed feature(s): none — this is a fix to an existing
unidentified-client stamping path, not behind a rollout channel.
- Minimum rollout channel: n/a (ships to stable with the fix).
- Stable/default behavior changed: yes. Unidentified clients calling
`/v1/codex/responses` or its subpaths (e.g. the Pi-compatible
`pi/<version>` user agent) are now stamped `X-Client: codex` and take
the Codex fail-open path instead of the generic proxy
compression-timeout path. Requests with an explicit `X-Client` header or
an already-recognized user agent are unchanged.
- Kill switch / disable path: no new switch; the existing explicit
`X-Client` header and recognized-user-agent paths still bypass the stamp
exactly as before.
- Unsafe override required: no.
- Qualification impact: none — no qualification-gated surface is
touched.
- Rollback path: revert the implementation commit.

## 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] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that the
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

Not applicable.

## Additional Notes

- Documentation is unchanged because this restores the
already-documented Pi compatibility route's existing Codex
classification behavior.
- PR #963 addresses broader Responses compression scheduling/timeouts
but does not add `/v1/codex/responses` to the path-based client stamp.
- `make ci-precheck` was not available because this workstation has no
Rust toolchain; the push used `--no-verify` after the Python, lint,
formatting, typing, focused routing, and live proxy checks above.

Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
This commit is contained in:
Hyunsik Kang
2026-10-05 20:49:30 -05:00
committed by GitHub
co-authored by Jerrett Davis
parent 62cde35b93
commit a493f559a1
3 changed files with 50 additions and 5 deletions
+6 -2
View File
@@ -46,6 +46,10 @@ CLIENT_UA_MAP: tuple[tuple[str, str], ...] = (
CODEX_RESPONSES_PATH = "/v1/responses"
CODEX_RESPONSES_PATHS: tuple[str, ...] = (
CODEX_RESPONSES_PATH,
"/v1/codex/responses",
)
@dataclass(frozen=True)
@@ -111,8 +115,8 @@ def classify_client_signals(signals: AuthSignals, *, default: str | None = None)
def is_codex_responses_path(path: str) -> bool:
"""Return True for the OpenAI Responses endpoint and its subpaths."""
return path == CODEX_RESPONSES_PATH or path.startswith(CODEX_RESPONSES_PATH + "/")
"""Return True for OpenAI Responses endpoints and their subpaths."""
return any(root == path or path.startswith(root + "/") for root in CODEX_RESPONSES_PATHS)
def should_stamp_codex_client_signals(path: str, signals: AuthSignals) -> bool:
+15 -3
View File
@@ -1,9 +1,9 @@
"""Tests for ``should_stamp_codex_client`` — the path-based ``X-Client: codex``
stamp on the Responses endpoint.
The stamp fires only for an unidentified caller on the Responses endpoint, so
Codex Desktop (whose User-Agent isn't a known codex UA) takes the codex
fail-open path instead of being refused with a 413 on a compression timeout.
The stamp fires only for an unidentified caller on a Responses endpoint, so
Codex Desktop and Pi-compatible Codex callers take the codex fail-open path
instead of being refused with a 413 on a compression timeout.
"""
from __future__ import annotations
@@ -13,12 +13,17 @@ from headroom.proxy.auth_mode import classify_client, should_stamp_codex_client
CODEX_DESKTOP_UA = (
"Codex Desktop/0.140.0-alpha.2 (Mac OS 15.7.7; arm64) unknown (Codex Desktop; 26.609.71450)"
)
PI_UA = "pi/0.11.11 (darwin 25.5.0; arm64)"
def test_unidentified_codex_desktop_on_responses_is_stamped() -> None:
assert should_stamp_codex_client("/v1/responses", {"user-agent": CODEX_DESKTOP_UA})
def test_unidentified_pi_on_codex_responses_alias_is_stamped() -> None:
assert should_stamp_codex_client("/v1/codex/responses", {"user-agent": PI_UA})
def test_stamp_then_classify_yields_codex() -> None:
# End-to-end of what the HTTP middleware and the WS handler both do:
# stamp the header, after which classify_client must read "codex".
@@ -36,6 +41,13 @@ def test_responses_subpath_is_stamped() -> None:
assert should_stamp_codex_client("/v1/responses/foo", {"user-agent": CODEX_DESKTOP_UA})
def test_codex_responses_alias_subpath_is_stamped() -> None:
assert should_stamp_codex_client(
"/v1/codex/responses/compact",
{"user-agent": PI_UA},
)
def test_other_path_is_not_stamped() -> None:
# Scoped to the Responses endpoint; unknown callers elsewhere are untouched.
assert not should_stamp_codex_client("/v1/chat/completions", {"user-agent": CODEX_DESKTOP_UA})
+29
View File
@@ -1792,6 +1792,35 @@ async def test_ws_recognized_client_with_real_path_is_not_restamped():
assert handler.ws_sessions.active_count() == 0
@pytest.mark.asyncio
async def test_ws_pi_codex_responses_alias_is_stamped():
"""The Pi-compatible Codex alias gets the same client stamp as /v1/responses."""
upstream_events = [
json.dumps({"type": "response.created", "response": {"id": "r_1"}}),
json.dumps({"type": "response.completed", "response": {"id": "r_1"}}),
]
connect_calls: list[tuple[tuple, dict]] = []
upstream = _FakeUpstream(upstream_events)
fake_ws_mod = _make_fake_websockets_module(upstream, connect_calls=connect_calls)
client_ws = _FakeWebSocket(
frames=[_first_frame()],
headers={
"authorization": "Bearer test",
"user-agent": "pi/0.11.11 (darwin 25.5.0; arm64)",
},
)
client_ws.url = SimpleNamespace(path="/v1/codex/responses")
handler = _DummyOpenAIHandler()
with patch.dict(sys.modules, {"websockets": fake_ws_mod}):
await handler.handle_openai_responses_ws(client_ws)
assert len(connect_calls) == 1
forwarded_headers = connect_calls[0][1]["additional_headers"]
assert forwarded_headers["x-client"] == "codex"
assert handler.ws_sessions.active_count() == 0
@pytest.mark.asyncio
@pytest.mark.parametrize("store", [True, False])
@pytest.mark.parametrize(