Skip to content

The agent that grows with you

fix(codex): identify Hermes requests

Vignesh Ramesha0795acc8312
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 9b77d5227f5..0e2dd48a9a2 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1318,7 +1318,9 @@ def init_agent(
client_kwargs["default_headers"] = _ra()._qwen_portal_headers()
elif base_url_host_matches(effective_base, "chatgpt.com"):
from agent.auxiliary_client import _codex_cloudflare_headers
- client_kwargs["default_headers"] = _codex_cloudflare_headers(api_key)
+ client_kwargs["default_headers"] = _codex_cloudflare_headers(
+ api_key, base_url=effective_base,
+ )
elif base_url_host_matches(effective_base, "x.ai"):
from tools.xai_http import hermes_xai_default_headers
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index cc3e9637fc2..9ef90d4bcfe 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2664,7 +2664,6 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
client_kwargs["default_headers"] = existing
except Exception:
_ra().logger.debug("Copilot default-header guard skipped", exc_info=True)
-
# OpenCode Free: the tier is served ANONYMOUSLY — any bearer the relay
# doesn't recognize (including placeholders) is a 401. Route every
# opencode-free client through the shared keyless header policy: an
@@ -2676,6 +2675,16 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
_existing = dict(client_kwargs.get("default_headers") or {})
_existing.update(opencode_zen_free_headers())
client_kwargs["default_headers"] = _existing
+
+ # All primary construction and recovery paths must identify Hermes to the
+ # official Codex endpoint, including snapshots with custom header overrides.
+ from agent.auxiliary_client import _apply_required_codex_headers
+
+ _apply_required_codex_headers(
+ client_kwargs,
+ access_token=client_kwargs.get("api_key", ""),
+ base_url=str(client_kwargs.get("base_url", "")),
+ )
# Uses the module-level `OpenAI` name, resolved lazily on first
# access via __getattr__ below. Tests patch via `run_agent.OpenAI`.
client = _ra().OpenAI(**client_kwargs)
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 251a5e27d21..dba8f840ed6 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -281,6 +281,7 @@ def _create_openai_client(*, api_key: str, base_url: str, **kwargs: Any) -> Any:
kwargs["default_headers"] = merged
except Exception:
pass
+ _apply_required_codex_headers(kwargs, access_token=api_key, base_url=base_url)
# Hermes owns auxiliary retry + provider/model fallback policy (the
# same-provider transient retry in call_llm plus the except-chain
# fallback). The OpenAI SDK's own default (max_retries=2 → up to 3
@@ -1222,19 +1223,31 @@ _AUTH_JSON_PATH = get_hermes_home() / "auth.json"
_CODEX_AUX_BASE_URL = "https://chatgpt.com/backend-api/codex"
-def _codex_cloudflare_headers(access_token: str) -> Dict[str, str]:
- """Headers required to avoid Cloudflare 403s on chatgpt.com/backend-api/codex.
+def _is_official_codex_base_url(base_url: str) -> bool:
+ """Identify OpenAI's Codex endpoint without matching custom proxies."""
+ try:
+ parsed = urlparse(base_url)
+ path = parsed.path.rstrip("/")
+ return (
+ parsed.scheme == "https"
+ and parsed.hostname == "chatgpt.com"
+ and parsed.port in (None, 443)
+ and (path == "/backend-api/codex" or path.startswith("/backend-api/codex/"))
+ )
+ except (TypeError, ValueError):
+ return False
+
- The Cloudflare layer in front of the Codex endpoint whitelists a small set of
- first-party originators (``codex_cli_rs``, ``codex_vscode``, ``codex_sdk_ts``,
- anything starting with ``Codex``). Requests from non-residential IPs (VPS,
- server-hosted agents) that don't advertise an allowed originator are served
- a 403 with ``cf-mitigated: challenge`` regardless of auth correctness.
+def _codex_cloudflare_headers(
+ access_token: str, *, base_url: str = _CODEX_AUX_BASE_URL,
+) -> Dict[str, str]:
+ """Identity and account headers for chatgpt.com/backend-api/codex.
- We pin ``originator: codex_cli_rs`` to match the upstream codex-rs CLI, set
- ``User-Agent`` to a codex_cli_rs-shaped string (beats SDK fingerprinting),
- and extract ``ChatGPT-Account-ID`` (canonical casing, from codex-rs
- ``auth.rs``) out of the OAuth JWT's ``chatgpt_account_id`` claim.
+ OpenAI requires third-party harnesses to identify themselves. Requests to
+ the official endpoint always send Hermes' originator and version. Custom
+ endpoints retain the existing compatibility identity. In either case,
+ preserve ``ChatGPT-Account-ID`` from the OAuth JWT's
+ ``chatgpt_account_id`` claim.
Malformed tokens are tolerated — we drop the account-ID header rather than
raise, so a bad token still surfaces as an auth error (401) instead of a
@@ -1244,6 +1257,13 @@ def _codex_cloudflare_headers(access_token: str) -> Dict[str, str]:
"User-Agent": "codex_cli_rs/0.0.0 (Hermes Agent)",
"originator": "codex_cli_rs",
}
+ if _is_official_codex_base_url(base_url):
+ from hermes_cli import __version__
+
+ headers.update({
+ "User-Agent": f"HermesAgent/{__version__}",
+ "originator": "hermes-agent",
+ })
if not isinstance(access_token, str) or not access_token.strip():
return headers
try:
@@ -1261,6 +1281,22 @@ def _codex_cloudflare_headers(access_token: str) -> Dict[str, str]:
return headers
+def _apply_required_codex_headers(
+ client_kwargs: Dict[str, Any], *, access_token: str, base_url: str,
+) -> None:
+ """Keep required Codex identity after user/provider header overrides."""
+ if not _is_official_codex_base_url(base_url):
+ return
+ required = _codex_cloudflare_headers(access_token, base_url=base_url)
+ required_names = {name.lower() for name in required}
+ existing = client_kwargs.get("default_headers") or {}
+ client_kwargs["default_headers"] = {
+ **{name: value for name, value in existing.items()
+ if str(name).lower() not in required_names},
+ **required,
+ }
+
+
# Hosts that expose BOTH an Anthropic-style ``…/anthropic`` path and a sibling
# OpenAI-compatible ``…/v1`` (or vendor-specific OpenAI path). Unconditional
# ``/anthropic`` → ``/v1`` rewrites break Anthropic-only gateways such as
@@ -3804,7 +3840,7 @@ def _build_codex_client(model: str) -> Tuple[Optional[Any], Optional[str]]:
real_client = _create_openai_client(
api_key=codex_token,
base_url=base_url,
- default_headers=_codex_cloudflare_headers(codex_token),
+ default_headers=_codex_cloudflare_headers(codex_token, base_url=base_url),
)
return CodexAuxiliaryClient(real_client, model), model
@@ -6201,6 +6237,10 @@ def _to_async_client(sync_client, model: str, is_vision: bool = False):
async_kwargs["default_headers"] = {"User-Agent": "claude-code/0.1.0"}
elif base_url_host_matches(sync_base_url, "integrate.api.nvidia.com"):
async_kwargs["default_headers"] = build_nvidia_nim_headers(sync_base_url)
+ elif _is_official_codex_base_url(sync_base_url):
+ async_kwargs["default_headers"] = _codex_cloudflare_headers(
+ sync_client.api_key, base_url=sync_base_url,
+ )
elif base_url_host_matches(sync_base_url, "x.ai"):
from tools.xai_http import hermes_xai_default_headers
@@ -6222,6 +6262,9 @@ def _to_async_client(sync_client, model: str, is_vision: bool = False):
_merged_async = _apply_user_default_headers(async_kwargs.get("default_headers"))
if _merged_async:
async_kwargs["default_headers"] = _merged_async
+ _apply_required_codex_headers(
+ async_kwargs, access_token=sync_client.api_key, base_url=sync_base_url,
+ )
async_kwargs = {
**_openai_http_client_kwargs(sync_base_url, async_mode=True),
**async_kwargs,
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..8c8b0809349
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1 @@
+vignesh-oai
diff --git a/run_agent.py b/run_agent.py
index 17276245212..3436bcf992f 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -6412,7 +6412,7 @@ class AIAgent:
elif base_url_host_matches(base_url, "chatgpt.com"):
from agent.auxiliary_client import _codex_cloudflare_headers
self._client_kwargs["default_headers"] = _codex_cloudflare_headers(
- self._client_kwargs.get("api_key", "")
+ self._client_kwargs.get("api_key", ""), base_url=base_url,
)
elif base_url_host_matches(base_url, "x.ai"):
# Cover both provider=xai and provider=xai-oauth (api.x.ai).
diff --git a/tests/agent/test_codex_cloudflare_headers.py b/tests/agent/test_codex_cloudflare_headers.py
index cb80c9efe64..5e315788e79 100644
--- a/tests/agent/test_codex_cloudflare_headers.py
+++ b/tests/agent/test_codex_cloudflare_headers.py
@@ -1,11 +1,8 @@
-"""Regression guard: Codex Cloudflare 403 mitigation headers.
+"""Regression coverage for required Codex identity and account headers.
-The ``chatgpt.com/backend-api/codex`` endpoint sits behind a Cloudflare layer
-that whitelists a small set of first-party originators (``codex_cli_rs``,
-``codex_vscode``, ``codex_sdk_ts``, ``Codex*``). Requests from non-residential
-IPs (VPS, always-on servers, some corporate egress) that don't advertise an
-allowed originator are served 403 with ``cf-mitigated: challenge`` regardless
-of auth correctness.
+The official Codex endpoint must receive Hermes' own harness identity, rather
+than the historical first-party compatibility identity. Live endpoint
+acceptance is a separate smoke test; these tests verify request construction.
``_codex_cloudflare_headers`` in ``agent.auxiliary_client`` centralizes the
header set so the primary chat client (``run_agent.AIAgent.__init__`` +
@@ -14,8 +11,8 @@ header set so the primary chat client (``run_agent.AIAgent.__init__`` +
all emit the same headers.
These tests pin:
-- the originator value (must be ``codex_cli_rs`` — the whitelisted one)
-- the User-Agent shape (codex_cli_rs-prefixed)
+- the required Hermes originator
+- the versioned Hermes User-Agent
- ``ChatGPT-Account-ID`` extraction from the OAuth JWT (canonical casing,
from codex-rs ``auth.rs``)
- graceful handling of malformed tokens (drop the account-ID header, don't
@@ -29,6 +26,7 @@ import base64
import json
from unittest.mock import MagicMock, patch
+from hermes_cli import __version__
# ---------------------------------------------------------------------------
@@ -59,10 +57,11 @@ def _make_codex_jwt(account_id: str = "acct-test-123") -> str:
class TestCodexCloudflareHeaders:
- def test_user_agent_advertises_codex_cli_rs(self):
+ def test_user_agent_advertises_hermes_version(self):
from agent.auxiliary_client import _codex_cloudflare_headers
headers = _codex_cloudflare_headers(_make_codex_jwt())
- assert headers["User-Agent"].startswith("codex_cli_rs/")
+ assert headers["User-Agent"] == f"HermesAgent/{__version__}"
+ assert headers["originator"] == "hermes-agent"
def test_canonical_header_casing(self):
@@ -86,7 +85,7 @@ class TestCodexCloudflareHeaders:
payload = b64url(_json.dumps({"sub": "user-xyz", "exp": 9999999999}).encode())
token = f"{b64url(b'{}')}.{payload}.{b64url(b'sig')}"
headers = _codex_cloudflare_headers(token)
- assert headers["originator"] == "codex_cli_rs"
+ assert headers["originator"] == "hermes-agent"
assert "ChatGPT-Account-ID" not in headers
@@ -117,9 +116,9 @@ class TestPrimaryClientWiring:
"https://chatgpt.com/backend-api/codex"
)
headers = agent._client_kwargs.get("default_headers") or {}
- assert headers.get("originator") == "codex_cli_rs"
+ assert headers.get("originator") == "hermes-agent"
assert headers.get("ChatGPT-Account-ID") == "acct-rotation"
- assert headers.get("User-Agent", "").startswith("codex_cli_rs/")
+ assert headers.get("User-Agent") == f"HermesAgent/{__version__}"
def test_apply_client_headers_clears_codex_headers_off_chatgpt(self):
"""Switching AWAY from chatgpt.com must drop the codex headers."""
@@ -173,9 +172,9 @@ class TestAuxiliaryClientWiring:
client, model = auxiliary_client._build_codex_client("gpt-5.4")
assert client is not None
headers = mock_openai.call_args.kwargs.get("default_headers") or {}
- assert headers.get("originator") == "codex_cli_rs"
+ assert headers.get("originator") == "hermes-agent"
assert headers.get("ChatGPT-Account-ID") == "acct-aux-try-codex"
- assert headers.get("User-Agent", "").startswith("codex_cli_rs/")
+ assert headers.get("User-Agent") == f"HermesAgent/{__version__}"
def test_resolve_provider_client_raw_codex_passes_codex_headers(self, monkeypatch):
"""The ``raw_codex=True`` branch (used by the main agent loop for direct
@@ -193,6 +192,6 @@ class TestAuxiliaryClientWiring:
)
assert client is not None
headers = mock_openai.call_args.kwargs.get("default_headers") or {}
- assert headers.get("originator") == "codex_cli_rs"
+ assert headers.get("originator") == "hermes-agent"
assert headers.get("ChatGPT-Account-ID") == "acct-aux-raw-codex"
- assert headers.get("User-Agent", "").startswith("codex_cli_rs/")
+ assert headers.get("User-Agent") == f"HermesAgent/{__version__}"
diff --git a/tests/agent/test_codex_usage_attribution.py b/tests/agent/test_codex_usage_attribution.py
new file mode 100644
index 00000000000..08d9e02aca3
--- /dev/null
+++ b/tests/agent/test_codex_usage_attribution.py
@@ -0,0 +1,360 @@
+"""Exercise required Codex attribution through real SDK request construction."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import httpx
+import pytest
+import yaml
+
+from hermes_cli import __version__
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+
+CODEX_URL = "https://chatgpt.com/backend-api/codex"
+MODEL = "gpt-5.4"
+
+
+def _jwt(account_id="acct-attribution-test"):
+ payload = json.dumps({
+ "https://api.openai.com/auth": {"chatgpt_account_id": account_id},
+ }).encode()
+ encoded = base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
+ return f"e30.{encoded}.test-signature"
+
+
+def profile(tmp_path, monkeypatch):
+ home = tmp_path / "profile"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ token = set_hermes_home_override(home)
+ try:
+ yield home
+ finally:
+ reset_hermes_home_override(token)
+
+
+def _set_legacy_attribution(profile, enabled):
+ """Old draft settings must not disable required harness identification."""
+ if enabled is not None:
+ (profile / "config.yaml").write_text(
+ yaml.safe_dump({
+ "telemetry": {"usage_attribution": {"enabled": enabled}},
+ }),
+ encoding="utf-8",
+ )
+
+
+def wire(profile, monkeypatch):
+ """Replace only HTTP transports; use Hermes routing and the real SDK."""
+ from agent import auxiliary_client
+ from run_agent import AIAgent
+
+ requests = []
+ response = {
+ "id": "resp_attribution_test",
+ "object": "response",
+ "created_at": 0,
+ "status": "completed",
+ "model": MODEL,
+ "output": [{
+ "type": "message",
+ "id": "msg_test",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": "ok", "annotations": []}],
+ }],
+ }
+
+ def respond(request):
+ requests.append(request)
+ if json.loads(request.content).get("stream"):
+ events = [
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": response["output"][0],
+ },
+ {"type": "response.completed", "response": response},
+ ]
+ content = "".join(f"data: {json.dumps(event)}\n\n" for event in events)
+ return httpx.Response(
+ 200,
+ headers={"Content-Type": "text/event-stream"},
+ content=content + "data: [DONE]\n\n",
+ )
+ return httpx.Response(200, json=response)
+
+ def http_client(*_args, async_mode=False, **_kwargs):
+ cls = httpx.AsyncClient if async_mode else httpx.Client
+ return cls(transport=httpx.MockTransport(respond))
+
+ monkeypatch.setattr(
+ auxiliary_client, "_openai_http_client_kwargs",
+ lambda _url, *, async_mode=False: {
+ "http_client": http_client(async_mode=async_mode),
+ },
+ )
+ monkeypatch.setattr(AIAgent, "_build_keepalive_http_client", staticmethod(http_client))
+ return requests
+
+
+def _assert_identity(request, account_id="acct-attribution-test"):
+ assert request.headers["originator"] == "hermes-agent"
+ assert request.headers["user-agent"] == f"HermesAgent/{__version__}"
+ assert request.headers["chatgpt-account-id"] == account_id
+ assert "extra_headers" not in json.loads(request.content)
+
+
[email protected]("legacy_enabled", [None, False, True])
+def test_required_identity_preserves_account_id(profile, legacy_enabled):
+ from agent.auxiliary_client import _codex_cloudflare_headers
+
+ _set_legacy_attribution(profile, legacy_enabled)
+ headers = _codex_cloudflare_headers(_jwt())
+
+ assert headers["originator"] == "hermes-agent"
+ assert headers["User-Agent"] == f"HermesAgent/{__version__}"
+ assert headers["ChatGPT-Account-ID"] == "acct-attribution-test"
+ assert "ChatGPT-Account-ID" not in _codex_cloudflare_headers("not-a-jwt")
+
+
+ ("base_url", "attributed"),
+ [
+ (CODEX_URL, True),
+ (CODEX_URL + "/", True),
+ (CODEX_URL + "/responses", True),
+ ("https://CHATGPT.COM:443/backend-api/codex", True),
+ ("http://chatgpt.com/backend-api/codex", False),
+ ("https://chatgpt.com:8443/backend-api/codex", False),
+ ("https://api.openai.com/v1", False),
+ ("https://proxy.example/backend-api/codex", False),
+ ("https://chatgpt.com.example/backend-api/codex", False),
+ ("https://subdomain.chatgpt.com/backend-api/codex", False),
+ ("https://chatgpt.com/backend-api/codex-other", False),
+ ("https://chatgpt.com/backend-api/other", False),
+ ("https://chatgpt.com:invalid/backend-api/codex", False),
+ ],
+)
+def test_new_identity_is_limited_to_the_official_endpoint(base_url, attributed):
+ from agent.auxiliary_client import _codex_cloudflare_headers
+
+ headers = _codex_cloudflare_headers(_jwt(), base_url=base_url)
+
+ assert headers["originator"] == ("hermes-agent" if attributed else "codex_cli_rs")
+ assert headers["User-Agent"] == (
+ f"HermesAgent/{__version__}"
+ if attributed else "codex_cli_rs/0.0.0 (Hermes Agent)"
+ )
+
+
[email protected]("legacy_enabled", [None, False, True])
+def test_primary_client_and_credential_rebuild_send_expected_headers(
+ profile, wire, legacy_enabled,
+):
+ from run_agent import AIAgent
+
+ _set_legacy_attribution(profile, legacy_enabled)
+ agent = AIAgent(
+ api_key=_jwt(),
+ base_url=CODEX_URL,
+ provider="openai-codex",
+ model=MODEL,
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ clients = [agent.client]
+ try:
+ agent.client.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1])
+
+ agent._client_kwargs["api_key"] = _jwt("acct-rotated")
+ agent._apply_client_headers_for_base_url(CODEX_URL)
+ assert agent._replace_primary_openai_client(reason="attribution-test")
+ clients.append(agent.client)
+ agent.client.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1], "acct-rotated")
+
+ direct_url = "https://api.openai.com/v1"
+ agent._client_kwargs.update(api_key="test-direct-key", base_url=direct_url)
+ agent._apply_client_headers_for_base_url(direct_url)
+ assert agent._replace_primary_openai_client(reason="attribution-route-change")
+ clients.append(agent.client)
+ agent.client.responses.create(model=MODEL, input="test")
+ assert "originator" not in wire[-1].headers
+ assert "chatgpt-account-id" not in wire[-1].headers
+ assert not wire[-1].headers["user-agent"].startswith("HermesAgent/")
+ finally:
+ for client in clients:
+ client.close()
+
+
[email protected]("legacy_enabled", [None, False, True])
+def test_auxiliary_raw_and_async_clients_send_expected_headers(
+ profile, wire, monkeypatch, legacy_enabled,
+):
+ from agent import auxiliary_client
+
+ _set_legacy_attribution(profile, legacy_enabled)
+ monkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda _p: (False, None))
+ monkeypatch.setattr(auxiliary_client, "_read_codex_access_token", _jwt)
+
+ wrapped, model = auxiliary_client._build_codex_client(MODEL)
+ raw, raw_model = auxiliary_client.resolve_provider_client(
+ "openai-codex", model=MODEL, raw_codex=True,
+ )
+ try:
+ result = wrapped.chat.completions.create(
+ model=model, messages=[{"role": "user", "content": "test"}],
+ )
+ assert result.choices[0].message.content == "ok"
+ _assert_identity(wire[-1])
+
+ raw.responses.create(model=raw_model, input="test")
+ _assert_identity(wire[-1])
+
+ async def send_async():
+ async_wrapped, _ = auxiliary_client._to_async_client(wrapped, model)
+ result = await async_wrapped.chat.completions.create(
+ model=model, messages=[{"role": "user", "content": "test"}],
+ )
+ assert result.choices[0].message.content == "ok"
+ _assert_identity(wire[-1])
+
+ async_raw, _ = auxiliary_client._to_async_client(raw, raw_model)
+ try:
+ await async_raw.responses.create(model=raw_model, input="test")
+ _assert_identity(wire[-1])
+ finally:
+ await async_raw.close()
+
+ asyncio.run(send_async())
+ finally:
+ wrapped.close()
+ raw.close()
+
+
+def test_credential_pool_custom_endpoint_keeps_existing_identity(
+ wire, monkeypatch,
+):
+ from agent import auxiliary_client
+
+ entry = SimpleNamespace(
+ runtime_api_key=_jwt(),
+ runtime_base_url="https://proxy.example/backend-api/codex",
+ )
+ monkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda _p: (True, entry))
+
+ client, model = auxiliary_client._build_codex_client(MODEL)
+ try:
+ client.chat.completions.create(
+ model=model, messages=[{"role": "user", "content": "test"}],
+ )
+ assert wire[-1].url.host == "proxy.example"
+ assert wire[-1].headers["originator"] == "codex_cli_rs"
+ assert wire[-1].headers["user-agent"] == "codex_cli_rs/0.0.0 (Hermes Agent)"
+ assert wire[-1].headers["chatgpt-account-id"] == "acct-attribution-test"
+ finally:
+ client.close()
+
+
+def test_legacy_disabled_setting_cannot_disable_attribution_for_new_clients(
+ profile, wire, monkeypatch,
+):
+ from agent import auxiliary_client
+
+ monkeypatch.setattr(auxiliary_client, "_read_codex_access_token", _jwt)
+ _set_legacy_attribution(profile, True)
+ old, _ = auxiliary_client.resolve_provider_client(
+ "openai-codex", model=MODEL, raw_codex=True,
+ )
+ _set_legacy_attribution(profile, False)
+ new, _ = auxiliary_client.resolve_provider_client(
+ "openai-codex", model=MODEL, raw_codex=True,
+ )
+ try:
+ old.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1])
+ new.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1])
+ finally:
+ old.close()
+ new.close()
+
+
+def test_required_identity_wins_over_configured_header_defaults(
+ profile, wire,
+):
+ from agent import auxiliary_client
+ from run_agent import AIAgent
+
+ overrides = {
+ "Originator": "codex_cli_rs",
+ "user-agent": "custom-client",
+ "X-Test-Header": "preserved",
+ }
+ (profile / "config.yaml").write_text(
+ yaml.safe_dump({"model": {"default_headers": overrides}}),
+ encoding="utf-8",
+ )
+ agent = AIAgent(
+ api_key=_jwt(),
+ base_url=CODEX_URL,
+ provider="openai-codex",
+ model=MODEL,
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ raw = auxiliary_client._create_openai_client(
+ api_key=_jwt(), base_url=CODEX_URL, default_headers=overrides,
+ )
+ proxy = auxiliary_client._create_openai_client(
+ api_key="test-proxy-key",
+ base_url="https://proxy.example/v1",
+ default_headers=overrides,
+ )
+ clients = [agent.client, raw, proxy]
+ try:
+ for client in (agent.client, raw):
+ client.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1])
+ assert wire[-1].headers["x-test-header"] == "preserved"
+
+ agent._apply_client_headers_for_base_url(CODEX_URL)
+ assert agent._replace_primary_openai_client(reason="required-identity-test")
+ clients.append(agent.client)
+ agent.client.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1])
+ assert wire[-1].headers["x-test-header"] == "preserved"
+
+ async def send_async():
+ async_raw, _ = auxiliary_client._to_async_client(raw, MODEL)
+ try:
+ await async_raw.responses.create(model=MODEL, input="test")
+ _assert_identity(wire[-1])
+ assert wire[-1].headers["x-test-header"] == "preserved"
+ finally:
+ await async_raw.close()
+
+ asyncio.run(send_async())
+
+ proxy.responses.create(model=MODEL, input="test")
+ assert wire[-1].headers["originator"] == "codex_cli_rs"
+ assert "custom-client" in wire[-1].headers.get_list("user-agent")
+ assert "HermesAgent/" not in wire[-1].headers["user-agent"]
+ assert wire[-1].headers["x-test-header"] == "preserved"
+ assert "chatgpt-account-id" not in wire[-1].headers
+ finally:
+ for client in clients:
+ client.close()
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 3cfa3765643..b01117b7db7 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -2005,6 +2005,15 @@ When `redact_pii` is `true`, the gateway redacts personally identifiable informa
Hashes are deterministic — the same user always maps to the same hash, so the model can still distinguish between users in group chats. Routing and delivery use the original values internally.
+### OpenAI Codex request identity
+
+OpenAI requires third-party Codex harnesses to identify themselves.
+ChatGPT-authenticated requests to the official Codex endpoint automatically
+send `originator: hermes-agent` and `User-Agent: HermesAgent/<version>`.
+The existing ChatGPT account header is preserved. No additional prompt content
+or telemetry request is sent.
+Direct OpenAI API requests and custom proxy endpoints are unchanged.
+
## Speech-to-Text (STT)
```yaml