The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(setup): Image Generation 'OpenAI (Codex auth)' row starts Codex sign-in and names the real auth command
teknium100e1a55519b7
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex 61a6c29630d..b1ca04c2acb 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -150,12 +150,15 @@ def _sync_codex_pool_entries(_clear_pool_entry_status(entry)-def _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None, label: str = None) -> None:+def _save_codex_tokens(+ tokens: Dict[str, str], last_refresh: str = None, label: str = None, *, set_active: bool = True,+) -> None:"""Save Codex OAuth tokens (singleton AND ``credential_pool`` aliases) to the active auth store.Codex refresh tokens are single-use with rotation-family reuse detection, so the pool rows thatalias the singleton must rotate with it or the next process replays the consumed token and- OpenAI revokes the whole family (#87503).+ OpenAI revokes the whole family (#87503). ``set_active=False`` stores credentials for a side+ tool (image gen) without making Codex the active inference provider."""from hermes_cli.auth import _provider_state_transaction, _save_auth_store, _store_provider_state, _utc_now_zif last_refresh is None:@@ -169,7 +172,7 @@ def _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None, label:state.update(tokens=tokens, last_refresh=last_refresh, auth_mode="chatgpt")if label and str(label).strip():state["label"] = str(label).strip()- _store_provider_state(auth_store, "openai-codex", state, set_active=True)+ _store_provider_state(auth_store, "openai-codex", state, set_active=set_active)_sync_codex_pool_entries(auth_store, tokens, last_refresh, previous_singleton_tokens=previous_singleton_tokens)_save_auth_store(auth_store)diff --git a/hermes_cli/tools_config_post_setup.py b/hermes_cli/tools_config_post_setup.pyindex 5fdfcfee952..5304257adb4 100644--- a/hermes_cli/tools_config_post_setup.py+++ b/hermes_cli/tools_config_post_setup.py@@ -339,6 +339,62 @@ def _post_setup_xai_grok() -> None:_print_info(" xAI will remain inactive until credentials are configured.")+def _codex_credentials_present() -> bool:+ """Cheap offline check for Codex/ChatGPT OAuth credentials (auth store + pool only)."""+ try:+ from hermes_cli.auth import get_codex_auth_status+ return bool(get_codex_auth_status().get("logged_in"))+ except Exception:+ return False+++def _post_setup_openai_codex() -> None:+ """Shared Codex/ChatGPT OAuth bootstrap for any picker row that talks to Codex without an API key+ (image gen today). The rows declare empty env_vars so the sign-in UX lives here. Saves tokens only —+ never rewrites ``model.provider``: the user picked an image backend, not a chat model (#102144)."""+ if _codex_credentials_present():+ _print_success(" Image generation will use your existing Codex/ChatGPT OAuth credentials")+ return++ relogin = "hermes auth add openai-codex"+ _print_info(" OpenAI (Codex auth) needs credentials.")+ try:+ from hermes_cli.auth import _codex_device_code_login, _save_codex_tokens+ from hermes_cli.setup import prompt_choice+ except Exception as exc:+ _print_warning(f" Could not load setup helpers: {exc}")+ _info_lines(f"Run later: {relogin}")+ return++ idx = prompt_choice(+ " How do you want to sign in?", default=0,+ choices=["Sign in with ChatGPT/Codex OAuth — browser login",+ f"Skip — configure later via `{relogin}`"])+ if idx != 0:+ _print_info(" Codex image generation will remain inactive until you sign in.")+ return+ try:+ creds = _codex_device_code_login()+ _save_codex_tokens(creds["tokens"], creds.get("last_refresh"), set_active=False)+ except (Exception, KeyboardInterrupt) as exc:+ _print_warning(f" Codex sign-in did not complete: {exc}. Run later: {relogin}")+ return+ _print_success(" Logged in — image generation will use these Codex OAuth credentials")+++def _xai_credentials_ready() -> bool:+ from hermes_cli.tools_config import _xai_credentials_present # facade binding: tests patch it there+ return _xai_credentials_present()+++# Credential-bootstrap post_setup keys -> "credentials present" predicate. These rows have no install+# side-effect; ``provider_readiness_status`` reports them ready/needs_auth from the auth store.+_POST_SETUP_AUTH_READY: dict = {+ "xai_grok": _xai_credentials_ready,+ "openai_codex": _codex_credentials_present,+}++# post_setup key -> hook. Unknown keys are a silent no-op (callers validate against valid_post_setup_keys())._POST_SETUP_HOOKS: dict = {"lightpanda": _post_setup_lightpanda,@@ -350,6 +406,7 @@ _POST_SETUP_HOOKS: dict = {"spotify": _post_setup_spotify,"langfuse": _post_setup_langfuse,"xai_grok": _post_setup_xai_grok,+ "openai_codex": _post_setup_openai_codex,**{key: (lambda spec=spec: _post_setup_pip(spec)) for key, spec in _PIP_POST_SETUP_HOOKS.items()},}@@ -483,8 +540,8 @@ def _cloud_agent_browser_installed() -> bool:# post_setup_key -> predicate(): True when the install side-effect is satisfied. Used by# ``provider_readiness_status`` to mark a keyless post_setup row "ready" vs "needs_setup"; mirrors the-# installed-checks the hooks perform. ``xai_grok`` is absent — a credential bootstrap handled as an-# auth check. Late-bound lambdas so tests can monkeypatch the underlying predicates.+# installed-checks the hooks perform. Credential bootstraps (``xai_grok``, ``openai_codex``) are absent —+# they live in ``_POST_SETUP_AUTH_READY`` as auth checks. Late-bound lambdas so tests can monkeypatch the underlying predicates._POST_SETUP_READY: dict = {**{key: (lambda m=module: _module_installed(m)) for key, (module, _args) in _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.items()},"agent_browser": lambda: _agent_browser_installed(),diff --git a/hermes_cli/tools_config_providers.py b/hermes_cli/tools_config_providers.pyindex c1854f2325f..e9abd1e9001 100644--- a/hermes_cli/tools_config_providers.py+++ b/hermes_cli/tools_config_providers.py@@ -164,9 +164,8 @@ def provider_readiness_status(provider: dict, config: dict, *, features=None, is"""Honest readiness state for a provider picker row.``features`` avoids re-fetching portal state per row. ``is_active`` is the completed-setup fallbackfor post_setup hooks with no registered installed-check (selecting a row runs its hook)."""- from hermes_cli.tools_config import (- _POST_SETUP_READY, _provider_env_ready, _xai_credentials_present, get_nous_subscription_features,- )+ from hermes_cli.tools_config import _POST_SETUP_READY, _provider_env_ready, get_nous_subscription_features+ from hermes_cli.tools_config_post_setup import _POST_SETUP_AUTH_READYif provider.get("env_vars", []):return "ready" if _provider_env_ready(provider) else "needs_keys"@@ -189,8 +188,9 @@ def provider_readiness_status(provider: dict, config: dict, *, features=None, ispost_setup = provider.get("post_setup")if post_setup:- if post_setup == "xai_grok":- return "ready" if _xai_credentials_present() else "needs_auth"+ auth_predicate = _POST_SETUP_AUTH_READY.get(post_setup)+ if auth_predicate is not None:+ return "ready" if auth_predicate() else "needs_auth"predicate = _POST_SETUP_READY.get(post_setup)if predicate is not None:try:diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.pyindex 6063fef8c46..a6a9181e4d6 100644--- a/plugins/image_gen/openai-codex/__init__.py+++ b/plugins/image_gen/openai-codex/__init__.py@@ -43,7 +43,7 @@ _ACCEPTED_INPUT_MIME = frozenset({"image/png", "image/jpeg", "image/gif", "image_NO_AUTH = ("No Codex/ChatGPT OAuth credentials available. Run "- "`hermes auth codex` (or `hermes setup` → Codex) to sign in.")+ "`hermes auth add openai-codex` (or `hermes setup` → Codex) to sign in.")def _summarize_error_body(body: str) -> str:@@ -242,8 +242,11 @@ class OpenAICodexImageGenProvider(StaticImageGenProvider):"badge": "free","tag": "gpt-image-2 via ChatGPT/Codex OAuth — no API key required; supports text and image inputs","env_vars": [],+ # Empty env_vars means the picker writes the selection without a credential prompt; the shared+ # Codex OAuth bootstrap hook (hermes_cli/tools_config_post_setup.py) starts the sign-in (#102144).+ "post_setup": "openai_codex","post_setup_hint": (- "Sign in with `hermes auth codex` (or `hermes setup` → Codex) "+ "Sign in with `hermes auth add openai-codex` (or `hermes setup` → Codex) ""if you haven't already. No API key needed."),}diff --git a/tests/hermes_cli/test_image_gen_picker.py b/tests/hermes_cli/test_image_gen_picker.pyindex 3b4a1584422..67b9019563b 100644--- a/tests/hermes_cli/test_image_gen_picker.py+++ b/tests/hermes_cli/test_image_gen_picker.py@@ -170,3 +170,37 @@ class TestConfigWriting:assert tools_config._is_provider_active(openai_row, config) is Trueassert tools_config._is_provider_active(nous_row, config) is False+++class TestCodexOAuthBootstrapHook:+ """#102144: the Image Generation 'OpenAI (Codex auth)' row is keyless, so its ``post_setup``+ hook is the only thing that can sign the user in. Selecting it with no Codex credentials must+ start the device-code flow and save tokens without hijacking ``model.provider``; with existing+ credentials it must not re-prompt."""++ @pytest.mark.parametrize("logged_in", [False, True])+ def test_hook_starts_codex_oauth_only_when_credentials_missing(self, monkeypatch, logged_in):+ from hermes_cli import auth, tools_config_post_setup++ monkeypatch.setattr(auth, "get_codex_auth_status", lambda: {"logged_in": logged_in})+ monkeypatch.setattr("hermes_cli.setup.prompt_choice", lambda *a, **kw: 0)+ started, saved = [], []+ monkeypatch.setattr(auth, "_codex_device_code_login",+ lambda: started.append(1) or {"tokens": {"access_token": "t"}, "last_refresh": "x"})+ monkeypatch.setattr(auth, "_save_codex_tokens", lambda tokens, last_refresh=None, **kw: saved.append(kw))++ tools_config_post_setup._POST_SETUP_HOOKS["openai_codex"]()++ assert len(started) == (0 if logged_in else 1)+ # Side-tool sign-in must not make Codex the active inference provider.+ assert saved == ([] if logged_in else [{"set_active": False}])++ def test_readiness_reports_codex_row_from_auth_store(self, monkeypatch):+ from hermes_cli import auth, tools_config++ row = {"name": "OpenAI (Codex auth)", "env_vars": [], "image_gen_plugin_name": "openai-codex",+ "post_setup": "openai_codex"}+ monkeypatch.setattr(auth, "get_codex_auth_status", lambda: {"logged_in": False})+ assert tools_config.provider_readiness_status(row, {}) == "needs_auth"+ monkeypatch.setattr(auth, "get_codex_auth_status", lambda: {"logged_in": True})+ assert tools_config.provider_readiness_status(row, {}) == "ready"diff --git a/tests/plugins/image_gen/test_openai_codex_provider.py b/tests/plugins/image_gen/test_openai_codex_provider.pyindex b20e86f8d8b..962165c1a78 100644--- a/tests/plugins/image_gen/test_openai_codex_provider.py+++ b/tests/plugins/image_gen/test_openai_codex_provider.py@@ -96,9 +96,13 @@ class TestMetadata:assert ids == ["gpt-image-2-low", "gpt-image-2-medium", "gpt-image-2-high"]def test_setup_schema_has_no_required_env_vars(self, provider):+ """#102144: the keyless row must declare the shared Codex OAuth bootstrap hook (otherwise setup+ saves the backend without ever signing in) and its hint must name a command that exists."""schema = provider.get_setup_schema()assert schema["env_vars"] == []- assert "hermes auth codex" in schema["post_setup_hint"]+ assert schema["post_setup"] == "openai_codex"+ assert "hermes auth add openai-codex" in schema["post_setup_hint"]+ assert "hermes auth codex`" not in schema["post_setup_hint"]# ── Availability ────────────────────────────────────────────────────────────