mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(wrap): route OMP OpenAI providers through Headroom (#2755)
## Description `headroom wrap omp` advertised OMP support but only redirected OMP's `anthropic` provider. OMP models under `openai` and `openai-codex`—including the current `openai-codex/gpt-5.6-sol` model—kept their native endpoints and bypassed Headroom. This change adds reversible `models.yml` base URL overrides for both OpenAI provider IDs while preserving the existing Anthropic route, provider credentials/headers, custom models, byte-for-byte backup, and `headroom unwrap omp` behavior. Follow-up to #1811. ## 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 - Route `providers.openai.baseUrl` through the project-prefixed Headroom `/v1` endpoint. - Route `providers.openai-codex.baseUrl` through the same endpoint; OMP appends `/codex/responses`, which Headroom already supports for HTTP and WebSocket traffic. - Preserve all existing provider fields and the established backup/reinject/unwrap contract. - Show all three managed provider routes at launch and document the expanded OMP support. - Extend the existing OMP wrap tests for fresh injection, user-config preservation, reinjection, and CLI display. ## Testing - [x] 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 --extra dev pytest -q tests/test_cli/test_wrap_omp.py 15 passed in 0.31s $ uv run --extra dev ruff check . All checks passed! $ uv run --extra dev ruff format --check . 1343 files already formatted $ uv run --extra dev mypy headroom Success: no issues found in 511 source files ``` The full pytest suite was started but not completed: after roughly 17 minutes it was still running unrelated Codex unwrap tests that repeatedly install/index Serena. No failure was observed before cancellation; the affected OMP suite is green. ## Real Behavior Proof - Environment: macOS Darwin 25.4 arm64 (Apple M5 Pro), Python 3.13.13, CLI code from this branch, published Headroom 0.33.0 proxy on port 8787, OMP 17.2.7, `openai-codex/gpt-5.6-sol` with stored ChatGPT/Codex OAuth. - Exact command / steps: Run the command below against the existing proxy, then inspect `/stats` and the managed `models.yml`. 1. Start or reuse the local proxy on `127.0.0.1:8787`. 2. Run: ```bash headroom wrap omp --no-proxy -- -p "Reply with exactly: HEADROOM_OMP_CODEX_OK" \ --model openai-codex/gpt-5.6-sol --no-session --no-tools \ --no-extensions --no-skills --no-rules --thinking off --max-time 30s ``` 3. Inspect `/stats` and the managed `~/.omp/agent/models.yml`. - Observed result: OMP returned the expected sentinel, Headroom recorded one new project request, and all three provider overrides were present. - Wrap printed all three routes: ```text providers.anthropic.baseUrl=http://127.0.0.1:8787/p/headroom providers.openai.baseUrl=http://127.0.0.1:8787/p/headroom/v1 providers.openai-codex.baseUrl=http://127.0.0.1:8787/p/headroom/v1 ``` - OMP returned exactly `HEADROOM_OMP_CODEX_OK`. - Headroom `/stats` recorded the new request under project `headroom` (`requests` increased from 2 to 3; `last_activity_at=2026-08-04T02:14:07Z`). - The managed `models.yml` contained all three overrides; the pristine backup remained the restore source. - The running 0.33.0 proxy does not contain the project-prefixed WebSocket fix from #2379, so this proves fallback-capable request completion rather than a clean WebSocket upgrade. - Not tested: a clean project-prefixed WebSocket upgrade against a release containing #2379; live `openai` API-key request; Windows/Linux; a long interactive or explicitly isolated WebSocket session; completion of the full unrelated pytest suite. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review An independent review pass found no correctness or security findings (confidence 0.96). ## 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 - [x] 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 my feature works - [ ] New and existing unit tests pass locally with my changes — affected tests pass; full suite did not finish as documented above - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title ## Screenshots (if applicable) N/A — terminal evidence is included above. ## Additional Notes Release prerequisite: Headroom 0.33.0 has a `/p/<project>` WebSocket upgrade bug that returns 403 before routing. It was independently fixed and merged in #2379 (`789a4f3060aa33a5bae82680968c3e367fa2db83`). This PR builds on `main`, which already contains that fix; stable interactive OMP WebSocket routing requires a release/backport containing #2379. The OpenAI API-key provider and ChatGPT/Codex OAuth provider intentionally share the local `/v1` base URL. Headroom distinguishes PAYG API keys from Codex OAuth JWT/account headers and forwards each request to the correct upstream. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2755" 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: Jerrett Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Jerrett Davis
parent
62cc38a6b0
commit
fae1e849cb
@@ -255,7 +255,7 @@ Saved** card then reads `measured` rather than `estimated`, with the band.
|
||||
| Goose | ✅ | starts proxy + launches |
|
||||
| OpenHands | ✅ | starts proxy + launches |
|
||||
| Mistral Vibe | ✅ | starts proxy + launches |
|
||||
| Oh My Pi | ✅ | injects config · starts proxy + launches |
|
||||
| Oh My Pi | ✅ | Anthropic + OpenAI/Codex · injects config · starts proxy + launches |
|
||||
| Cortex Code | Library only | 60–65% savings in library mode; no `wrap` |
|
||||
| Kimi CLI | ✅ | OAuth bearer forwarded — log in once |
|
||||
| ZCode | ✅ | starts the proxy and prints base URLs for ZCode settings |
|
||||
|
||||
@@ -9100,14 +9100,14 @@ def omp(
|
||||
"""Launch Oh My Pi (omp) through Headroom proxy.
|
||||
|
||||
\b
|
||||
Points omp's built-in `anthropic` provider at Headroom by injecting a
|
||||
marker-fenced `providers.anthropic.baseUrl` override into
|
||||
~/.omp/agent/models.yml (pre-wrap file backed up byte-for-byte; undo with
|
||||
`headroom unwrap omp`). omp resolves its Anthropic chat endpoint from
|
||||
models.yml — ANTHROPIC_BASE_URL only affects its web-search helper — and a
|
||||
same-ID override keeps omp's bundled model catalog and stored credentials.
|
||||
omp's other providers (OpenAI-direct, Gemini, ...) keep their normal
|
||||
endpoints; route those via your own custom provider in models.yml.
|
||||
Points omp's built-in `anthropic`, `openai` (API-key), and `openai-codex`
|
||||
(OAuth) providers at Headroom by injecting marker-fenced base-URL overrides
|
||||
into ~/.omp/agent/models.yml (pre-wrap file backed up byte-for-byte; undo
|
||||
with `headroom unwrap omp`). omp resolves these endpoints from models.yml —
|
||||
ANTHROPIC_BASE_URL only affects its web-search helper — and same-ID
|
||||
overrides keep omp's bundled model catalog and stored credentials. OMP
|
||||
Codex appends `/codex/responses`, which Headroom already aliases. Gemini
|
||||
and other providers keep their normal endpoints.
|
||||
|
||||
\b
|
||||
Examples:
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
"""Runtime helpers for Oh My Pi (omp) integrations.
|
||||
|
||||
omp resolves its Anthropic chat endpoint from the model registry
|
||||
(``providers.anthropic.baseUrl`` in ``~/.omp/agent/models.yml``), not from
|
||||
omp resolves its Anthropic and OpenAI provider endpoints from the model registry
|
||||
(``providers.<id>.baseUrl`` in ``~/.omp/agent/models.yml``), not from
|
||||
``ANTHROPIC_BASE_URL`` — that env var only feeds omp's web-search helper.
|
||||
Verified empirically: with ``ANTHROPIC_BASE_URL`` pointed at a local probe
|
||||
server, omp's chat traffic still went to the real Anthropic endpoint; with a
|
||||
``models.yml`` same-ID override, every ``/v1/messages`` request arrived at the
|
||||
probe. A same-ID override keeps omp's bundled Anthropic model catalog and
|
||||
stored credentials (both keyed by provider id ``anthropic``), so only the
|
||||
endpoint moves.
|
||||
probe. Same-ID overrides keep omp's bundled model catalog and stored
|
||||
credentials, so only the endpoints move.
|
||||
|
||||
The wrap therefore injects a marker-fenced ``providers.anthropic.baseUrl``
|
||||
override into ``models.yml``, snapshotting the pre-wrap file byte-for-byte
|
||||
first — the same durable-wrap + backup + ``headroom unwrap`` contract the
|
||||
Codex wrap uses for ``config.toml``.
|
||||
The wrap injects marker-fenced ``providers.anthropic.baseUrl``,
|
||||
``providers.openai.baseUrl``, and ``providers.openai-codex.baseUrl`` overrides
|
||||
into ``models.yml``, snapshotting the pre-wrap file byte-for-byte first. OMP's
|
||||
Codex provider appends ``/codex/responses``; Headroom already aliases that
|
||||
path. Gemini and other providers remain untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,6 +23,7 @@ from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
from headroom.providers.claude import proxy_base_url as claude_proxy_base_url
|
||||
from headroom.providers.codex import proxy_base_url as codex_proxy_base_url
|
||||
from headroom.proxy.project_context import with_project_prefix
|
||||
|
||||
MANAGED_MARKER = "# managed by `headroom wrap omp`"
|
||||
@@ -62,6 +63,11 @@ def proxy_anthropic_base_url(port: int, project: str | None = None) -> str:
|
||||
return with_project_prefix(claude_proxy_base_url(port), project)
|
||||
|
||||
|
||||
def proxy_openai_base_url(port: int, project: str | None = None) -> str:
|
||||
"""Proxy base URL omp's OpenAI and Codex providers are pointed at."""
|
||||
return with_project_prefix(codex_proxy_base_url(port), project)
|
||||
|
||||
|
||||
def is_managed(models_file: Path) -> bool:
|
||||
"""Whether ``models_file`` is currently a wrap-managed override."""
|
||||
if not models_file.exists():
|
||||
@@ -74,25 +80,26 @@ def is_managed(models_file: Path) -> bool:
|
||||
|
||||
|
||||
def inject_models_override(port: int, project: str | None = None) -> tuple[Path, str]:
|
||||
"""Point ``providers.anthropic.baseUrl`` at the local proxy.
|
||||
"""Point omp's Anthropic, OpenAI, and Codex provider endpoints at Headroom.
|
||||
|
||||
Returns ``(models_file, base_url)``.
|
||||
Returns ``(models_file, anthropic_base_url)`` for backward compatibility.
|
||||
|
||||
* First injection snapshots the user's pre-wrap file byte-for-byte to
|
||||
``models.yml.headroom-backup`` so unwrap can restore it exactly. A file
|
||||
``models.yml.headroom-backup`` so unwrap can restore it exactly. A file
|
||||
that is already wrap-managed is never re-snapshotted (that would clobber
|
||||
the pristine backup — same guard as the Codex config snapshot).
|
||||
* The managed file is regenerated from the backup (or from scratch when
|
||||
the user had no ``models.yml``) on every call, so re-running with a
|
||||
different ``--port`` updates the override idempotently.
|
||||
different ``--port`` updates the overrides idempotently.
|
||||
* Any user-defined providers/models from the pre-wrap file are preserved:
|
||||
the override only deep-sets ``providers.anthropic.baseUrl``.
|
||||
the override only deep-sets each supported provider's ``baseUrl``.
|
||||
"""
|
||||
import yaml # type: ignore[import-untyped] # PyYAML ships no stubs; lint env installs no deps
|
||||
|
||||
models_file = models_yml_path()
|
||||
backup = backup_path(models_file)
|
||||
base_url = proxy_anthropic_base_url(port, project)
|
||||
openai_base_url = proxy_openai_base_url(port, project)
|
||||
|
||||
original_bytes: bytes | None = None
|
||||
if backup.exists():
|
||||
@@ -119,11 +126,16 @@ def inject_models_override(port: int, project: str | None = None) -> tuple[Path,
|
||||
if not isinstance(providers, dict): # malformed user value: keep it in backup only
|
||||
providers = {}
|
||||
data["providers"] = providers
|
||||
anthropic = providers.setdefault("anthropic", {})
|
||||
if not isinstance(anthropic, dict):
|
||||
anthropic = {}
|
||||
providers["anthropic"] = anthropic
|
||||
anthropic["baseUrl"] = base_url
|
||||
for provider_name, provider_base_url in (
|
||||
("anthropic", base_url),
|
||||
("openai", openai_base_url),
|
||||
("openai-codex", openai_base_url),
|
||||
):
|
||||
provider = providers.setdefault(provider_name, {})
|
||||
if not isinstance(provider, dict):
|
||||
provider = {}
|
||||
providers[provider_name] = provider
|
||||
provider["baseUrl"] = provider_base_url
|
||||
|
||||
models_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
rendered = yaml.safe_dump(data, sort_keys=False, default_flow_style=False)
|
||||
@@ -157,10 +169,15 @@ def build_launch_env(
|
||||
) -> tuple[dict[str, str], list[str]]:
|
||||
"""Build the launch environment and display lines for the omp wrap.
|
||||
|
||||
The endpoint redirect itself lives in ``models.yml`` (see module
|
||||
The endpoint redirects themselves live in ``models.yml`` (see module
|
||||
docstring), so the environment passes through unchanged; the display
|
||||
lines surface where the override went.
|
||||
lines surface where the overrides went.
|
||||
"""
|
||||
env = dict(environ or os.environ)
|
||||
base_url = proxy_anthropic_base_url(port, project)
|
||||
return env, [f"models.yml: providers.anthropic.baseUrl={base_url}"]
|
||||
openai_base_url = proxy_openai_base_url(port, project)
|
||||
return env, [
|
||||
f"models.yml: providers.anthropic.baseUrl={base_url}",
|
||||
f"models.yml: providers.openai.baseUrl={openai_base_url}",
|
||||
f"models.yml: providers.openai-codex.baseUrl={openai_base_url}",
|
||||
]
|
||||
|
||||
@@ -71,9 +71,12 @@ def test_inject_fresh_create_writes_managed_marker_and_no_backup(omp_home: Path)
|
||||
assert base_url == "http://127.0.0.1:8787/p/proj"
|
||||
|
||||
text = models_file.read_text(encoding="utf-8")
|
||||
providers = yaml.safe_load(text)["providers"]
|
||||
openai_base_url = "http://127.0.0.1:8787/p/proj/v1"
|
||||
assert MANAGED_MARKER in text
|
||||
assert yaml.safe_load(text)["providers"]["anthropic"]["baseUrl"] == base_url
|
||||
|
||||
assert providers["anthropic"]["baseUrl"] == base_url
|
||||
assert providers["openai"]["baseUrl"] == openai_base_url
|
||||
assert providers["openai-codex"]["baseUrl"] == openai_base_url
|
||||
# Nothing pre-existed, so there is nothing to snapshot.
|
||||
assert not backup_path(models_file).exists()
|
||||
|
||||
@@ -85,6 +88,10 @@ def test_inject_over_existing_backs_up_pristine_and_merges(omp_home: Path) -> No
|
||||
" apiKey: sk-user-secret\n"
|
||||
" openai:\n"
|
||||
" baseUrl: https://api.openai.com/v1\n"
|
||||
" apiKey: sk-user-openai\n"
|
||||
" openai-codex:\n"
|
||||
" baseUrl: https://chatgpt.com/backend-api/codex\n"
|
||||
" oauth: true\n"
|
||||
"models:\n"
|
||||
" - id: my-custom-model\n"
|
||||
)
|
||||
@@ -97,9 +104,13 @@ def test_inject_over_existing_backs_up_pristine_and_merges(omp_home: Path) -> No
|
||||
|
||||
merged = yaml.safe_load(omp_home.read_text(encoding="utf-8"))
|
||||
assert merged["providers"]["anthropic"]["baseUrl"] == base_url
|
||||
# Only anthropic.baseUrl is set; every other user key survives the merge.
|
||||
openai_base_url = "http://127.0.0.1:8787/p/proj/v1"
|
||||
assert merged["providers"]["openai"]["baseUrl"] == openai_base_url
|
||||
assert merged["providers"]["openai"]["apiKey"] == "sk-user-openai"
|
||||
assert merged["providers"]["openai-codex"]["baseUrl"] == openai_base_url
|
||||
assert merged["providers"]["openai-codex"]["oauth"] is True
|
||||
# Only supported provider base URLs are set; every other user key survives.
|
||||
assert merged["providers"]["anthropic"]["apiKey"] == "sk-user-secret"
|
||||
assert merged["providers"]["openai"]["baseUrl"] == "https://api.openai.com/v1"
|
||||
assert merged["models"] == [{"id": "my-custom-model"}]
|
||||
assert MANAGED_MARKER in omp_home.read_text(encoding="utf-8")
|
||||
|
||||
@@ -120,6 +131,8 @@ def test_reinject_new_port_regenerates_from_pristine_backup(omp_home: Path) -> N
|
||||
merged = yaml.safe_load(omp_home.read_text(encoding="utf-8"))
|
||||
assert base_url_9999 == "http://127.0.0.1:9999/p/proj"
|
||||
assert merged["providers"]["anthropic"]["baseUrl"] == base_url_9999
|
||||
assert merged["providers"]["openai"]["baseUrl"] == "http://127.0.0.1:9999/p/proj/v1"
|
||||
assert merged["providers"]["openai-codex"]["baseUrl"] == "http://127.0.0.1:9999/p/proj/v1"
|
||||
# Regenerated from the backup, so user creds still survive the new port.
|
||||
assert merged["providers"]["anthropic"]["apiKey"] == "sk-user-secret"
|
||||
|
||||
@@ -171,11 +184,15 @@ def test_build_launch_env_passes_env_through_and_emits_display(omp_home: Path) -
|
||||
source = {"PATH": "/usr/bin", "ANTHROPIC_BASE_URL": "https://api.anthropic.com"}
|
||||
env, display = build_launch_env(8787, source, project="proj")
|
||||
|
||||
# The redirect lives in models.yml, so env is a verbatim copy — notably
|
||||
# The redirects live in models.yml, so env is a verbatim copy — notably
|
||||
# ANTHROPIC_BASE_URL is NOT rewritten to the proxy.
|
||||
assert env == source
|
||||
assert env is not source # a copy, so caller's environ can't be mutated
|
||||
assert display == ["models.yml: providers.anthropic.baseUrl=http://127.0.0.1:8787/p/proj"]
|
||||
assert display == [
|
||||
"models.yml: providers.anthropic.baseUrl=http://127.0.0.1:8787/p/proj",
|
||||
"models.yml: providers.openai.baseUrl=http://127.0.0.1:8787/p/proj/v1",
|
||||
"models.yml: providers.openai-codex.baseUrl=http://127.0.0.1:8787/p/proj/v1",
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -217,12 +234,18 @@ def test_wrap_omp_happy_path_injects_before_launch(runner: CliRunner, omp_home:
|
||||
text_at_launch = captured["models_text_at_launch"]
|
||||
assert isinstance(text_at_launch, str)
|
||||
assert MANAGED_MARKER in text_at_launch
|
||||
base_url = yaml.safe_load(text_at_launch)["providers"]["anthropic"]["baseUrl"]
|
||||
providers = yaml.safe_load(text_at_launch)["providers"]
|
||||
base_url = providers["anthropic"]["baseUrl"]
|
||||
openai_base_url = providers["openai"]["baseUrl"]
|
||||
assert base_url.startswith("http://127.0.0.1:8787/p/")
|
||||
assert openai_base_url == f"{base_url}/v1"
|
||||
assert providers["openai-codex"]["baseUrl"] == openai_base_url
|
||||
|
||||
display = captured["env_vars_display"]
|
||||
assert isinstance(display, list)
|
||||
assert f"models.yml: providers.anthropic.baseUrl={base_url}" in display
|
||||
assert f"models.yml: providers.openai.baseUrl={openai_base_url}" in display
|
||||
assert f"models.yml: providers.openai-codex.baseUrl={openai_base_url}" in display
|
||||
|
||||
|
||||
def test_wrap_omp_does_not_write_agents_md(
|
||||
|
||||
Reference in New Issue
Block a user