mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
feat/https-compose-caddy
1
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
fbf7bc3278 |
feat(proxy): let turn hooks rewrite OpenAI Responses requests on HTTP and WebSocket (#4232)
## Description
Add an optional on_responses_create turn hook so extensions can replace
an OpenAI Responses request before model-dependent proxy processing. The
hook applies to HTTP requests and WebSocket response.create frames,
including subsequent frames, and respects the Headroom bypass header.
## Type of Change
- [x] New feature (optional turn-hook method)
## Changes Made
- Expose ResponsesCreate with request body, headers, transport, and
connection identity.
- Run ordered synchronous/asynchronous hooks and isolate hook
exceptions.
- Apply replacement bodies before compression, model-dependent
accounting, and HTTP dispatch.
- Apply the hook to initial and subsequent WebSocket create frames.
- Add handler-level regression coverage for replacement, no-op, bypass,
and streaming behavior.
## Testing
- [x] Maintainer focused hook and WebSocket lifecycle suites passed.
- [x] Touched-file Ruff and whitespace checks passed.
### Test Output
```text
python -m pytest tests/test_responses_create_hooks.py tests/test_turn_hooks.py tests/test_openai_codex_ws_lifecycle.py tests/test_original_snapshot_in_place_hook.py -q
76 passed, 1 warning in 13.93s
ruff check headroom/proxy/turn_hooks.py headroom/proxy/handlers/openai.py tests/test_responses_create_hooks.py
All checks passed!
```
The latest main sync incorporates the merged snapshot-preservation fix
from #4241. All 76 focused hook, WebSocket, and snapshot tests passed
after that clean sync. Hosted CI is qualifying the newly pushed head.
Maintainer tests used the available development native extension; no
newly built native binary or independent live-provider validation is
claimed.
## Real Behavior Proof
- Environment: isolated Windows/Python 3.12.13 maintainer worktree, real
HTTP/WebSocket handlers exercised through repository test fixtures.
- Exact command / steps: run the four pytest suites listed above;
inspect replacement, bypass, no-op, and WebSocket lifecycle cases.
- Observed result: all 76 focused tests passed, including routed
model/effort reaching the captured upstream request and preserving
no-op/bypass behavior.
- Not tested: independent live inference through an installed routing
extension. The original author-supplied live/replay evidence is
preserved below and remains attributed to the author.
## Runtime Rollout Safety
- Rollout-managed feature(s): no new global rollout switch; the optional
hook runs only when registered.
- Minimum rollout channel: existing extension deployment policy applies.
- Stable/default behavior changed: registered hooks may replace
Responses bodies before proxy processing; deployments without this hook
retain the existing path.
- Kill switch / disable path: disable or unregister the consuming
extension; the Headroom bypass header skips this hook.
- Unsafe override required: no.
- Qualification impact: routing/model/stream changes require
extension-specific runtime qualification in addition to the core tests.
- Rollback path: disable the extension or retain the prior qualified
release.
## Review Readiness
- [ ] I have performed a self-review
- [ ] This PR is ready for human review
Maintainer qualification is recorded above; author attestations have not
been filled on the author's behalf.
## Additional Notes
The original author description and supplied evidence follow, with
headings demoted for the required template structure. The read-only body
view is shallow: hooks must construct replacements rather than mutate
nested request values.
#### Summary
Proxy extensions can now route Codex's `/v1/responses` traffic on the
WebSocket transport as well as over HTTP. This adds one optional
turn-hook method, `on_responses_create(ResponsesCreate) -> dict | None`.
It runs on every HTTP `/v1/responses` body and on every WebSocket
`response.create` frame, at the same point in the pipeline on both. A
hook reads `request.body`, which is a read-only view. To change the
request it returns a replacement body (for example with a new `model` or
`reasoning`); returning `None` leaves the request alone. This mirrors
how `on_response` already works. Chained hooks each see the previous
hook's replacement. `ResponsesCreate` carries `body`, `headers`,
`transport` (`"http"` or `"websocket"`) and `connection_id`.
`connection_id` is the WS session id and is `None` over HTTP. A
`previous_response_id` chain lives within one connection, so a hook that
holds state across a chain's frames should key it on `connection_id`.
#### The test we ran
- **Setup:** a Daytona sandbox running Headroom Enterprise 0.4.3 (core
0.39.1), Codex CLI 0.162.1 with the real GitHub MCP server, and
RouteMeGood in apply mode.
- **HTTP Codex:** 0 RouteMeGood decisions before routemegood#33 and 3
after it, on a probe.
- **Wrapped Codex:** still 0 decisions. `headroom wrap codex` writes
`supports_websockets = true`, so wrapped Codex sends `/v1/responses`
over a WebSocket. That traffic never passes through
`@app.middleware("http")`, so routing silently did nothing.
#### Why a new hook rather than a writable `TurnContext.model`
Turn hooks already run on the WS path. They run inside
`_compress_openai_responses_payload`, and that call site is the wrong
place for a router to change the model:
- It runs only when `config.optimize` is on, and on the executor under
the compression timeout. A timeout or a compression failure would drop
the routing decision.
- Built-in tool-search deferral
(`inject_tool_search_deferral_openai(model)`) has already run against
the *old* model. Routing to a model without tool search would forward a
`tool_search` tool the new model rejects.
- The handler's `model` (tokenizer, pricing, metrics, outcome) is
captured before compression, so a changed `ctx.model` would be priced as
the old model.
`on_responses_create` runs before all of that:
- **HTTP:** right after the inbound debug capture and before `model =
body["model"]`.
- **First WS frame:** before the ChatGPT `store=false` force, memory and
compression.
- **Later WS frames:** before memory and compression.
So everything downstream sees the routed model: compression, deferral,
`store=false`, token counting, pricing, and the WS memory-continuation
template, which is rebuilt from the outbound frame. It is skipped under
`x-headroom-bypass`, and it is inert when no hook defines it.
- **`previous_response_id`:** passed through untouched. OpenAI allows a
model switch mid-chain, and the continuation template already drops
`previous_response_id`.
- **Byte-faithful forwarding (#1542):** the HTTP body is marked mutated
only when a hook returns a replacement. An unchanged request still
forwards the client's original bytes, and nothing has to serialize the
body to find out.
- **A failing hook leaves no trace:** a hook never edits the body in
place, so a hook that raises cannot leave a half-made edit behind.
Without that, pricing would see the edit while the forwarded bytes did
not.
- **`stream` is read after the hook:** a replacement that turns
streaming on takes the streaming dispatch path.
- **Headers:** WS handshake headers are handed over read-only
(`MappingProxyType`).
#### Before / after
| | before | after |
|---|---|---|
| Unit: WS `response.create` frames, hook sets `gpt-5.4-mini` +
`reasoning.effort=low` | upstream frames carry the client's `gpt-5.5` |
both frames carry `gpt-5.4-mini` / `low` (compression off: routing
doesn't depend on it) |
| Unit: HTTP `/v1/responses`, same hook | upstream body +
`RequestOutcome.model` = `gpt-5.5` | upstream body and outcome =
`gpt-5.4-mini` |
| Live, local proxy (steps below) | 0 decisions (2 WS create frames, 0
HTTP POSTs); RouteMeGood logs `this Headroom has no Responses create
hook: Codex over WebSocket passes through unrouted` | 2 decisions, one
per WS create frame |
##### Live check: steps
- **Machine:** macOS (Darwin 25.6), Python 3.12.13.
- **Codex:** codex-cli 0.153.2 with ChatGPT auth.
- **Extension:** RouteMeGood from the stacked PR branch, in shadow mode.
- **Proxy:** the extension's `.venv`, started from this branch:
```sh
HEADROOM_BEACON=off ROUTEMEGOOD_BEACON=off HEADROOM_ROUTEMEGOOD_LICENSE_DEV=1 ROUTEMEGOOD_MODE=shadow ROUTEMEGOOD_HARNESS=codex ROUTEMEGOOD_PERSIST=0 ROUTEMEGOOD_REQUIRE_CREDS=0 PYTHONPATH=<this branch>:<routemegood feat/responses-ws> python -m headroom.cli proxy --port 8799 --proxy-extension routemegood
codex exec --skip-git-repo-check -c model_provider=headroom -c 'model_providers.headroom={name="OpenAI via Headroom proxy",base_url="http://127.0.0.1:8799/v1",supports_websockets=true,requires_openai_auth=true,wire_api="responses"}' "Reply with the single word: pong"
curl -s localhost:8799/routemegood/stats
```
**Observed:**
- The proxy log showed `WS /v1/responses accepted
(route=chatgpt_subscription ...)`, then `completed (... client_frames=2
...)`.
- There were no HTTP `POST /v1/responses`.
- Codex printed `pong`.
- **After:** `/routemegood/stats` returned
`{"decisions":2,"harness":"codex","picked":{"gpt-5.6-terra":2},...}`.
- **Before:** I ran the same steps with `PYTHONPATH` set to a `main`
checkout (
|