The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(codex): one credential/route authority for aux + image paths
kshitijk4poore326520d50cf
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex a2f44a7258e..c12e1468115 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -2113,17 +2113,6 @@ def _read_codex_access_token() -> Optional[str]:return _read_codex_singleton_token()-def _codex_pool_entry_base_url(entry: Any) -> str:- """Host the chat route sends this pooled Codex entry's key to (``model.base_url`` included)."""- row_base = _pool_runtime_base_url(entry, _CODEX_AUX_BASE_URL)- try:- from hermes_cli.auth_codex import _codex_pool_route_base_url- return _codex_pool_route_base_url(row_base) or row_base- except Exception as exc:- logger.debug("Codex pool route base resolution failed: %s", exc)- return row_base--def _resolve_codex_credential_and_base() -> Tuple[Optional[str], str]:"""``(token, base_url)`` taken from ONE authority, so a Codex key is only ever sent to the hostit belongs to (#121486): the profile-scoped ``HERMES_CODEX_BASE_URL`` wins; otherwise a pooled@@ -2134,11 +2123,13 @@ def _resolve_codex_credential_and_base() -> Tuple[Optional[str], str]:if pool_present:token = _pool_runtime_api_key(entry)if token:- return token, override or _codex_pool_entry_base_url(entry) or _CODEX_AUX_BASE_URL- # A present pool whose selection gave no token: read auth.json directly — re-selecting could- # rotate to another pool row and pair its key with the default host.- token = _read_codex_singleton_token() if pool_present else _read_codex_access_token()- return token, override or _CODEX_AUX_BASE_URL+ if override:+ return token, override+ # Same route rule as the chat path (row URL, else ``model.base_url``); never empty.+ from hermes_cli.auth_codex import _codex_pool_route_base_url+ return token, _codex_pool_route_base_url(_pool_runtime_base_url(entry))+ # No usable pool token: auth.json only (re-selecting could pair another row's key with the default).+ return _read_codex_singleton_token(), override or _CODEX_AUX_BASE_URLdef _read_codex_singleton_token() -> Optional[str]:diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 5134b3d12c0..c141dd8d057 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -85,7 +85,11 @@ def _codex_pool_route_base_url(entry_base_url: Optional[str] = "") -> str:"openai-codex", None, model_cfg if isinstance(model_cfg, dict) else {}, "", base)[1]except Exception:logger.debug("Codex pool route base resolution failed", exc_info=True)- return _stripped(os.getenv("HERMES_CODEX_BASE_URL")).rstrip("/") or base or DEFAULT_CODEX_BASE_URL+ # Profile-scoped override only (never the raw process env: a multiplexed sibling's gateway).+ with suppress(Exception):+ from agent.secret_scope import get_secret_str+ base = _stripped(get_secret_str("HERMES_CODEX_BASE_URL", "")).rstrip("/") or base+ return base or DEFAULT_CODEX_BASE_URLdef _codex_runtime_result(@@ -910,18 +914,13 @@ def _pool_entries(auth_store: Dict[str, Any], provider_id: str) -> Optional[Listreturn entries if isinstance(entries, list) else None-def _pool_codex_access_token() -> str:- """First non-empty pool access_token not in an exhaustion cooldown window, else "".+def _pool_codex_credential() -> Tuple[str, str]:+ """``(access_token, row base_url)`` of the first pool entry with a non-empty access_token that is+ not in an exhaustion cooldown window, so the caller routes the token to the host that row belongs+ to; ``("", "")`` when none is usable.Fallback for ``resolve_codex_runtime_credentials`` when the singleton has no creds; reads- through ``read_credential_pool`` so a profile inherits the global-root pool (#34143).- """- return _pool_codex_credential()[0]---def _pool_codex_credential() -> Tuple[str, str]:- """``(access_token, row base_url)`` of the entry ``_pool_codex_access_token`` picks, so the- caller routes the token to the host that row belongs to; ``("", "")`` when none is usable."""+ through ``read_credential_pool`` so a profile inherits the global-root pool (#34143)."""from agent.credential_pool import _parse_absolute_timestampfrom hermes_cli.auth import _nonempty_str, read_credential_pooltry:diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.pyindex 56ea3aaf2ee..996d448d77a 100644--- a/hermes_cli/cli_model_switch_mixin.py+++ b/hermes_cli/cli_model_switch_mixin.py@@ -379,7 +379,7 @@ class CLIModelSwitchMixin:try:# self.base_url is the route resolved with self.api_key (#121486).available = get_codex_model_ids(- access_token=self.api_key if self.api_key else None, base_url=getattr(self, "base_url", None) or None)+ access_token=self.api_key if self.api_key else None, base_url=self.base_url or None)if available:fallback_model = available[0]except Exception:diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 42a6b195b00..bd342dd5e44 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -390,7 +390,7 @@ def _model_flow_openai_codex(config, current_model=""):codex_models = get_codex_model_ids(access_token=_codex_token, base_url=_codex_base)selected = _prompt_model_selection(codex_models, current_model=current_model, confirm_provider="openai-codex",- confirm_base_url=DEFAULT_CODEX_BASE_URL, confirm_api_key=_codex_token or "")+ confirm_base_url=_codex_base or DEFAULT_CODEX_BASE_URL, confirm_api_key=_codex_token or "")_activate_provider_model(selected, "openai-codex", DEFAULT_CODEX_BASE_URL,f"Default model set to: {selected} (via OpenAI Codex)")diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.pyindex 0ae03107bcf..799f3889a9b 100644--- a/plugins/image_gen/openai-codex/__init__.py+++ b/plugins/image_gen/openai-codex/__init__.py@@ -33,7 +33,6 @@ from plugins.image_gen._common import (logger = logging.getLogger(__name__)-_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"_MAX_ERROR_BODY_CHARS = 500_MAX_REFERENCE_IMAGES = 16@@ -65,28 +64,18 @@ def _resolve_model() -> Tuple[str, Dict[str, Any]]:GPT_IMAGE_2_TIERS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai-codex")-def _read_codex_access_token() -> Optional[str]:- """Usable Codex OAuth token or None (``agent.auxiliary_client`` owns expiry/pool/JWT)."""- try:- from agent.auxiliary_client import _read_codex_access_token as _reader-- token = _reader()- return token.strip() if isinstance(token, str) and token.strip() else None- except Exception as exc:- logger.debug("Could not resolve Codex access token: %s", exc)- return None--def _read_codex_credential() -> Tuple[Optional[str], Optional[str]]:- """``(token, base_url)`` from one resolution: the image request goes to the host the token's- credential routes to (pool row / ``model.base_url`` / profile override), never a default the- credential does not belong to (#121486)."""+ """``(token, base_url)`` from one resolution (``agent.auxiliary_client`` owns expiry/pool/JWT):+ the image request goes to the host the token's credential routes to (pool row /+ ``model.base_url`` / profile override), never a default it does not belong to (#121486).+ ``(None, None)`` without a usable token."""try:from agent.auxiliary_client import _resolve_codex_credential_and_basetoken, base_url = _resolve_codex_credential_and_base()- token = token.strip() if isinstance(token, str) and token.strip() else None- return token, (base_url or None) if token else None+ if isinstance(token, str) and token.strip():+ return token.strip(), base_url+ return None, Noneexcept Exception as exc:logger.debug("Could not resolve Codex credential: %s", exc)return None, None@@ -202,19 +191,16 @@ def _build_image_request(def _post_image_request(token: str, *, prompt: str, size: str, quality: str, input_images: Optional[List[Dict[str, str]]] = None,- base_url: Optional[str] = None,+ base_url: str,) -> Dict[str, Any]:"""POST to the native Codex images endpoint; return the decoded JSON body plus``imagegen_request_id`` (backend correlation id, for support tickets).- ``base_url`` should come from the same resolution as ``token`` (``_read_codex_credential``)."""+ ``base_url`` must come from the same resolution as ``token`` (``_read_codex_credential``)."""import httpx- from agent.auxiliary_client import _codex_base_url_overridefrom agent.codex_headers import codex_cloudflare_headers- # Match the text auxiliary route, including profile-scoped overrides. Resolve- # per request: a multiplexed process can serve different Codex gateways.- base_url = (base_url or "").strip().rstrip("/") or _codex_base_url_override() or _CODEX_BASE_URL+ base_url = base_url.strip().rstrip("/")headers = codex_cloudflare_headers(token, base_url=base_url)headers.update({"Authorization": f"Bearer {token}",@@ -256,7 +242,7 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):price = "varies"def is_available(self) -> bool:- return bool(_read_codex_access_token()) and _httpx_available()+ return bool(_read_codex_credential()[0]) and _httpx_available()def get_setup_schema(self) -> Dict[str, Any]:return {diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex a203f2ac9e8..0435b043b62 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -728,7 +728,8 @@ class TestBuildCodexClient:def test_profile_codex_base_url_applies_to_raw_codex_client(self, monkeypatch):"""The main agent's raw Codex client honours the same endpoint override."""with (- patch("agent.auxiliary_client._read_codex_access_token", return_value="codex-auth-token"),+ patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)),+ patch("agent.auxiliary_client._read_codex_singleton_token", return_value="codex-auth-token"),patch("agent.auxiliary_client.OpenAI") as mock_openai,):monkeypatch.setenv("HERMES_CODEX_BASE_URL", "http://127.0.0.1:8787/v1")diff --git a/tests/agent/test_codex_cloudflare_headers.py b/tests/agent/test_codex_cloudflare_headers.pyindex c0827589442..89ab5823cf0 100644--- a/tests/agent/test_codex_cloudflare_headers.py+++ b/tests/agent/test_codex_cloudflare_headers.py@@ -211,13 +211,13 @@ class TestAuxiliaryClientWiring:token = _make_codex_jwt("acct-aux-try-codex")# Force _select_pool_entry to return "no pool" so we fall through to- # _read_codex_access_token.+ # the auth.json token.monkeypatch.setattr(auxiliary_client, "_select_pool_entry",lambda provider: (False, None),)monkeypatch.setattr(- auxiliary_client, "_read_codex_access_token",+ auxiliary_client, "_read_codex_singleton_token",lambda: token,)with patch("agent.auxiliary_client.OpenAI") as mock_openai:@@ -235,7 +235,11 @@ class TestAuxiliaryClientWiring:from agent import auxiliary_clienttoken = _make_codex_jwt("acct-aux-raw-codex")monkeypatch.setattr(- auxiliary_client, "_read_codex_access_token",+ auxiliary_client, "_select_pool_entry",+ lambda provider: (False, None),+ )+ monkeypatch.setattr(+ auxiliary_client, "_read_codex_singleton_token",lambda: token,)with patch("agent.auxiliary_client.OpenAI") as mock_openai:diff --git a/tests/agent/test_codex_usage_attribution.py b/tests/agent/test_codex_usage_attribution.pyindex 7e9715bca33..640e427ecee 100644--- a/tests/agent/test_codex_usage_attribution.py+++ b/tests/agent/test_codex_usage_attribution.py@@ -192,7 +192,7 @@ def test_auxiliary_raw_and_async_clients_send_expected_headers(from agent import auxiliary_clientmonkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda _p: (False, None))- monkeypatch.setattr(auxiliary_client, "_read_codex_access_token", _jwt)+ monkeypatch.setattr(auxiliary_client, "_read_codex_singleton_token", _jwt)wrapped, model = auxiliary_client._build_codex_client(MODEL)raw, raw_model = auxiliary_client.resolve_provider_client(@@ -258,7 +258,8 @@ def test_legacy_disabled_setting_cannot_disable_attribution_for_new_clients():from agent import auxiliary_client- monkeypatch.setattr(auxiliary_client, "_read_codex_access_token", _jwt)+ monkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda _p: (False, None))+ monkeypatch.setattr(auxiliary_client, "_read_codex_singleton_token", _jwt)_set_legacy_attribution(profile, True)old, _ = auxiliary_client.resolve_provider_client("openai-codex", model=MODEL, raw_codex=True,diff --git a/tests/hermes_cli/test_codex_credential_host_binding.py b/tests/hermes_cli/test_codex_credential_host_binding.pyindex 2e72ab8541b..458c4e82d9d 100644--- a/tests/hermes_cli/test_codex_credential_host_binding.py+++ b/tests/hermes_cli/test_codex_credential_host_binding.py@@ -163,12 +163,15 @@ def test_model_setup_flow_catalog_goes_to_the_pool_entry_gateway(monkeypatch, pi_write_config(home, base_url=GW)_write_pool(home, OPAQUE)monkeypatch.setattr("builtins.input", lambda prompt="": "1") # reuse existing credentials- monkeypatch.setattr("hermes_cli.auth._prompt_model_selection", lambda *a, **kw: None)+ confirm = {}+ monkeypatch.setattr("hermes_cli.auth._prompt_model_selection", lambda *a, **kw: confirm.update(kw))from hermes_cli.model_setup_flows import _model_flow_openai_codex_model_flow_openai_codex({}, current_model="gpt-5.5")assert _authorized_hosts(picker_http) == {"codex-gw.example"}+ # The confirm guards see the key together with its own route, not the chatgpt.com default.+ assert (confirm["confirm_api_key"], confirm["confirm_base_url"]) == (OPAQUE, GW)def test_cli_default_model_swap_asks_the_session_route(monkeypatch, picker_http):@@ -306,3 +309,25 @@ def test_image_request_goes_to_the_pool_entry_gateway(monkeypatch, key):assert result["success"] is True, resultassert _authorized_hosts(seen) == {"codex-gw.example"}assert seen[0][1] == f"Bearer {key}"+++def test_route_fallback_reads_the_profile_scoped_override_not_a_sibling_process_env(monkeypatch):+ """If route resolution itself fails, the fallback still honours only the routed profile's+ ``HERMES_CODEX_BASE_URL`` — never a multiplexed sibling's process env."""+ from agent import secret_scope+ from agent.secret_scope import reset_secret_scope, set_secret_scope+ from hermes_cli import runtime_provider+ from hermes_cli.auth_codex import _codex_pool_route_base_url++ def _boom(*_a, **_kw):+ raise RuntimeError("route resolution failed")++ monkeypatch.setattr(runtime_provider, "_pool_entry_mode_and_url", _boom)+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)+ monkeypatch.setenv("HERMES_CODEX_BASE_URL", OTHER_GW)+ for scope, expected in [({}, GW), ({"HERMES_CODEX_BASE_URL": OTHER_GW + "/"}, OTHER_GW)]:+ token = set_secret_scope(scope)+ try:+ assert _codex_pool_route_base_url(GW) == expected+ finally:+ reset_secret_scope(token)diff --git a/tests/plugins/image_gen/test_openai_codex_provider.py b/tests/plugins/image_gen/test_openai_codex_provider.pyindex 8c586af4fd9..00a2a5abf2a 100644--- a/tests/plugins/image_gen/test_openai_codex_provider.py+++ b/tests/plugins/image_gen/test_openai_codex_provider.py@@ -58,7 +58,6 @@ def codex_backend(monkeypatch):# Seed the auth.json token below the credential/base resolver so generate() exercises the real# (token, base_url) binding; no pool present.from agent import auxiliary_client- monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: "codex-token")monkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda provider: (False, None))monkeypatch.setattr(auxiliary_client, "_read_codex_singleton_token", lambda: "codex-token")state = {"requests": [], "respond": None}@@ -106,16 +105,16 @@ class TestMetadata:class TestAvailability:def test_unavailable_without_codex_token(self, monkeypatch):- monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: None)+ monkeypatch.setattr(codex_plugin, "_read_codex_credential", lambda: (None, None))assert codex_plugin.OpenAICodexImageGenProvider().is_available() is Falsedef test_available_with_codex_token(self, monkeypatch):- monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: "tok")+ monkeypatch.setattr(codex_plugin, "_read_codex_credential", lambda: ("tok", "https://chatgpt.com/backend-api/codex"))assert codex_plugin.OpenAICodexImageGenProvider().is_available() is Truedef test_openai_api_key_alone_is_not_enough(self, monkeypatch):monkeypatch.setenv("OPENAI_API_KEY", "sk-test")- monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: None)+ monkeypatch.setattr(codex_plugin, "_read_codex_credential", lambda: (None, None))assert codex_plugin.OpenAICodexImageGenProvider().is_available() is False@@ -187,7 +186,6 @@ class TestGenerate:def test_returns_auth_error_without_codex_token(self, provider, monkeypatch):from agent import auxiliary_client- monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: None)monkeypatch.setattr(auxiliary_client, "_select_pool_entry", lambda provider: (False, None))monkeypatch.setattr(auxiliary_client, "_read_codex_singleton_token", lambda: None)result = provider.generate("a cat")