diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.py index 7bf6e7b913..34a20ec0de 100644 --- a/hermes_cli/auth_codex.py +++ b/hermes_cli/auth_codex.py @@ -16,6 +16,7 @@ import json import os import threading import time +from contextlib import suppress from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple from hermes_cli.auth_constants import ( @@ -56,11 +57,8 @@ def _clear_pool_entry_status(entry: Dict[str, Any]) -> None: def _codex_access_token_is_expiring(access_token: Any, skew_seconds: int) -> bool: - claims = _decode_jwt_claims(access_token) - exp = claims.get("exp") - if not isinstance(exp, (int, float)): - return False - return float(exp) <= (time.time() + max(0, int(skew_seconds))) + exp = _decode_jwt_claims(access_token).get("exp") + return isinstance(exp, (int, float)) and float(exp) <= (time.time() + max(0, int(skew_seconds))) def _codex_base_url() -> str: @@ -122,12 +120,8 @@ def _sync_codex_pool_entries( if entries is None: return # None/empty prev_at → no manual entry can be an alias (right default for a first-ever save). - prev_at = None - if isinstance(previous_singleton_tokens, dict): - prev_at = previous_singleton_tokens.get("access_token") or None - for entry in entries: - if not isinstance(entry, dict): - continue + prev_at = (previous_singleton_tokens or {}).get("access_token") or None + for entry in _codex_pool_dicts(entries): source = entry.get("source") is_alias = source == "manual:device_code" and bool( prev_at and entry.get("access_token") == prev_at) @@ -155,9 +149,7 @@ def _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None, label: # tell legacy singleton-aliases (refresh) from independent ``auth add`` accounts (keep). previous_singleton_tokens = ( state.get("tokens") if isinstance(state.get("tokens"), dict) else None) - state["tokens"] = tokens - state["last_refresh"] = last_refresh - state["auth_mode"] = "chatgpt" + state.update(tokens=tokens, last_refresh=last_refresh, auth_mode="chatgpt") if label and str(label).strip(): state["label"] = str(label).strip() _save_provider_state(auth_store, "openai-codex", state) @@ -172,9 +164,8 @@ def _recover_codex_tokens_from_cli(reason: str) -> Optional[Dict[str, str]]: imported = _import_codex_cli_tokens() # Require BOTH tokens before adopting: persisting a payload without a usable refresh_token # would only break the next refresh cycle. - if not ( - imported and _stripped(imported.get("access_token")) - and _stripped(imported.get("refresh_token"))): + if not (imported and _stripped(imported.get("access_token")) + and _stripped(imported.get("refresh_token"))): return None logger.info("Codex auth recovered from Codex CLI auth.json (%s).", reason) _save_codex_tokens(imported) @@ -231,11 +222,9 @@ def _codex_http_client(**kwargs: Any) -> "httpx.Client": racing backend can't be installed (mocked client in tests), serial connect behavior remains. """ client = httpx.Client(**kwargs) - try: + with suppress(Exception): from agent.process_bootstrap import enable_happy_eyeballs_on_client enable_happy_eyeballs_on_client(client) - except Exception: - pass return client @@ -296,14 +285,11 @@ def refresh_codex_oauth_pure( if not _nonempty_str(refresh_token): raise _codex_err( _MISSING_REFRESH_TOKEN_MSG, "codex_auth_missing_refresh_token", relogin=True) - timeout = httpx.Timeout(max(5.0, float(timeout_seconds))) with _codex_http_client( - timeout=timeout, - headers={"Accept": "application/json", "User-Agent": CODEX_OAUTH_USER_AGENT}, - ) as client: + timeout=httpx.Timeout(max(5.0, float(timeout_seconds))), + headers={"Accept": "application/json", "User-Agent": CODEX_OAUTH_USER_AGENT}) as client: response = client.post( - CODEX_OAUTH_TOKEN_URL, - headers={"Content-Type": "application/x-www-form-urlencoded"}, + CODEX_OAUTH_TOKEN_URL, headers={"Content-Type": "application/x-www-form-urlencoded"}, data={ "grant_type": "refresh_token", "refresh_token": refresh_token, "client_id": CODEX_OAUTH_CLIENT_ID}) @@ -315,9 +301,8 @@ def refresh_codex_oauth_pure( if response.status_code != 200: raise _codex_refresh_failure_error(response) refresh_payload, refreshed_access = _refresh_payload_access_token( - response, provider="openai-codex", + response, provider="openai-codex", invalid_response=None, invalid_json=("Codex token refresh returned invalid JSON.", "codex_refresh_invalid_json"), - invalid_response=None, missing_access=( "Codex token refresh response was missing access_token.", "codex_refresh_missing_access_token")) @@ -358,10 +343,7 @@ def _refresh_codex_auth_tokens(tokens: Dict[str, str], timeout_seconds: float) - def _import_codex_cli_tokens() -> Optional[Dict[str, str]]: - """Read tokens from ~/.codex/auth.json (Codex CLI shared file) if valid and not expired. - - Does NOT write to the shared file. - """ + """Read ~/.codex/auth.json (Codex CLI file) tokens if valid and not expired; never writes.""" from hermes_cli.auth import _codex_access_token_is_expiring codex_home = os.getenv("CODEX_HOME", "").strip() or str(Path.home() / ".codex") auth_path = Path(codex_home).expanduser() / "auth.json" @@ -369,9 +351,8 @@ def _import_codex_cli_tokens() -> Optional[Dict[str, str]]: return None try: tokens = json.loads(auth_path.read_text(encoding="utf-8-sig")).get("tokens") - if not isinstance(tokens, dict): - return None - if not (tokens.get("access_token") and tokens.get("refresh_token")): + if not (isinstance(tokens, dict) and tokens.get("access_token") + and tokens.get("refresh_token")): return None # Importing stale tokens that can't be refreshed would leave the user with # "Login successful!" but no working credentials. @@ -400,11 +381,10 @@ def resolve_codex_runtime_credentials( data = _read_codex_tokens() except AuthError as exc: read_error = exc - if getattr(exc, "relogin_required", False) and getattr(exc, "code", None) in { + if exc.relogin_required and exc.code in { "codex_auth_missing_access_token", "codex_auth_missing_refresh_token", "codex_auth_invalid_shape"}: - imported = _recover_codex_tokens_from_cli( - str(getattr(exc, "code", None) or "auth_error")) + imported = _recover_codex_tokens_from_cli(str(exc.code or "auth_error")) if imported: data = {"tokens": imported, "last_refresh": imported.get("last_refresh")} if data is None: @@ -426,10 +406,8 @@ def resolve_codex_runtime_credentials( return _codex_runtime_result( pool_token, source="credential_pool", last_refresh=None) reset_at = pool_rate_limit.get("reset_at") - remaining = ( - int(reset_at - time.time()) - if isinstance(reset_at, (int, float)) and reset_at > time.time() else None) - raise _codex_quota_exhausted_error(remaining) + in_future = isinstance(reset_at, (int, float)) and reset_at > time.time() + raise _codex_quota_exhausted_error(int(reset_at - time.time()) if in_future else None) if read_error is not None: raise read_error raise _codex_err(_NO_CREDENTIALS_MSG, "codex_auth_missing", relogin=True) @@ -447,19 +425,16 @@ def resolve_codex_runtime_credentials( with _auth_store_lock(timeout_seconds=lock_timeout): data = _read_codex_tokens(_lock=False) tokens = dict(data["tokens"]) - access_token = _stripped(tokens.get("access_token")) - if _should_refresh(access_token): + if _should_refresh(_stripped(tokens.get("access_token"))): tokens = _refresh_codex_auth_tokens(tokens, refresh_timeout_seconds) - access_token = _stripped(tokens.get("access_token")) - + access_token = _stripped(tokens.get("access_token")) return _codex_runtime_result( access_token, source="hermes-auth-store", last_refresh=data.get("last_refresh")) def _is_codex_rate_limit_shaped(code: Any, reason: Any, message: Any) -> bool: """True when persisted pool-entry error metadata describes a 429/quota stop.""" - reason_l = str(reason or "").lower() - message_l = str(message or "").lower() + reason_l, message_l = str(reason or "").lower(), str(message or "").lower() return ( code == 429 or any(k in reason_l for k in ("rate_limit", "usage_limit", "quota")) @@ -568,10 +543,9 @@ def clear_codex_pool_quota_cooldowns(access_token: Optional[str] = None) -> int: for entry in _codex_pool_dicts(entries): if access_token and str(entry.get("access_token") or "") != access_token: continue - if not _entry_is_rate_limit_exhausted(entry): - continue - _clear_pool_entry_status(entry) - cleared += 1 + if _entry_is_rate_limit_exhausted(entry): + _clear_pool_entry_status(entry) + cleared += 1 if cleared: _save_auth_store(auth_store) except Exception: @@ -604,13 +578,12 @@ def _codex_pool_rate_limit_status() -> Optional[Dict[str, Any]]: if not _nonempty_str(token) or not _entry_is_rate_limit_exhausted(entry): continue reset_at = _parse_absolute_timestamp(entry.get("last_error_reset_at")) - if reset_at is not None and reset_at <= now: - continue - return { - "label": entry.get("label"), "last_refresh": entry.get("last_refresh"), - "reset_at": reset_at, "reason": entry.get("last_error_reason"), - "message": entry.get("last_error_message"), "access_token": token.strip(), - "base_url": entry.get("base_url")} + if reset_at is None or reset_at > now: + return { + "label": entry.get("label"), "last_refresh": entry.get("last_refresh"), + "reset_at": reset_at, "reason": entry.get("last_error_reason"), + "message": entry.get("last_error_message"), "access_token": token.strip(), + "base_url": entry.get("base_url")} except Exception: logger.debug("Codex pool rate-limit lookup failed", exc_info=True) return None @@ -631,11 +604,10 @@ def _pool_codex_access_token() -> str: from hermes_cli.auth import _nonempty_str try: for entry in _codex_pool_dicts(_read_codex_pool_entries()): - token = entry.get("access_token") - reset_at = entry.get("last_error_reset_at") + token, reset_at = entry.get("access_token"), entry.get("last_error_reset_at") in_cooldown = isinstance(reset_at, (int, float)) and reset_at > time.time() if _nonempty_str(token) and not in_cooldown: - return str(entry.get("access_token", "")).strip() + return token.strip() except Exception: logger.debug("Codex pool fallback lookup failed", exc_info=True) return "" @@ -682,8 +654,7 @@ def _login_openai_codex(args, pconfig: ProviderConfig, *, force_new_login: bool def _codex_login_rate_limited_error(response: "httpx.Response", *, during: str = "") -> AuthError: - """AuthError for a 429 from OpenAI's device-auth endpoints (a throttle, not a credential fault). - """ + """AuthError for a 429 from OpenAI's device-auth endpoints (throttle, not credential fault).""" retry_after = _parse_retry_after_seconds(getattr(response, "headers", None)) wait_hint = ( f" Try again in about {retry_after}s." if retry_after is not None @@ -700,7 +671,6 @@ def _codex_request_device_code(issuer: str, client_id: str) -> Dict[str, Any]: OpenAI rate-limits this request when login is attempted too often from one IP/account — retry with capped backoff (honoring ``Retry-After``) before surfacing an actionable message. """ - resp = None max_attempts = 4 for attempt in range(1, max_attempts + 1): resp = _codex_login_post( @@ -715,12 +685,11 @@ def _codex_request_device_code(issuer: str, client_id: str) -> Dict[str, Any]: delay = max(1, min(int(retry_after if retry_after is not None else 2 ** attempt), 60)) print(f"OpenAI is rate-limiting login requests (429); retrying in {delay}s...") time.sleep(delay) - if resp is not None and resp.status_code == 429: + if resp.status_code == 429: raise _codex_login_rate_limited_error(resp) - if resp is None or resp.status_code != 200: - status = resp.status_code if resp is not None else "unknown" + if resp.status_code != 200: raise _codex_err( - f"Device code request returned status {status}.", "device_code_request_error") + f"Device code request returned status {resp.status_code}.", "device_code_request_error") device_data = resp.json() device_data["interval"] = max(3, int(device_data.get("interval", "5"))) if not device_data.get("user_code", "") or not device_data.get("device_auth_id", ""): @@ -789,8 +758,7 @@ def _codex_exchange_authorization_code( def _codex_device_code_login() -> Dict[str, Any]: """Run the OpenAI device code login flow and return credentials dict.""" from hermes_cli.auth import _utc_now_z - issuer = "https://auth.openai.com" - client_id = CODEX_OAUTH_CLIENT_ID + issuer, client_id = "https://auth.openai.com", CODEX_OAUTH_CLIENT_ID device_data = _codex_request_device_code(issuer, client_id) user_code = device_data["user_code"] diff --git a/hermes_cli/auth_device_flow.py b/hermes_cli/auth_device_flow.py index f41b23448e..56cf7b6058 100644 --- a/hermes_cli/auth_device_flow.py +++ b/hermes_cli/auth_device_flow.py @@ -101,8 +101,7 @@ def _print_loopback_ssh_hint(redirect_uri: str, *, docs_url: str | None = None) parsed = urlparse(redirect_uri) except Exception: return - host = parsed.hostname or "" - port = parsed.port + host, port = parsed.hostname or "", parsed.port if host not in {"127.0.0.1", "::1", "localhost"} or not port: return divider = "-" * 60 @@ -168,8 +167,8 @@ def _request_device_code( response.raise_for_status() data = response.json() required_fields = [ - "device_code", "user_code", "verification_uri", - "verification_uri_complete", "expires_in", "interval"] + "device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in", + "interval"] missing = [f for f in required_fields if f not in data] if missing: raise ValueError(f"Device code response missing fields: {', '.join(missing)}") @@ -202,13 +201,12 @@ def _print_device_code_instructions( print(f" 2. If prompted, enter code: {user_code}") if not open_browser: return - if swallow_open_errors: - try: - opened = webbrowser.open(verification_url) - except Exception: - opened = False - else: + try: opened = webbrowser.open(verification_url) + except Exception: + if not swallow_open_errors: + raise + opened = False if opened: print(" (Opened browser for verification)") else: @@ -273,10 +271,9 @@ def _poll_for_token( "device_code": device_code}), expires_in=expires_in, poll_interval=max(1, min(poll_interval, DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS)), - validate_success=_validate, + validate_success=_validate, on_error=_error, on_non_json_error=lambda _r: RuntimeError( "Token endpoint returned a non-JSON error response"), - on_error=_error, # Enriched at the SOURCE so the CLI login and the dashboard/desktop poller # (web_server._nous_poller surfaces str(e) to the UI) both inherit the guidance. on_timeout=lambda: TimeoutError(_nous_device_auth_timeout_message(portal_base_url))) diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py index 653870e0aa..9339043578 100644 --- a/hermes_cli/auth_nous.py +++ b/hermes_cli/auth_nous.py @@ -13,7 +13,7 @@ import os import threading import time import uuid -from contextlib import contextmanager +from contextlib import contextmanager, suppress from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Optional @@ -50,12 +50,8 @@ def _token_fingerprint(token: Any) -> Optional[str]: return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()[:12] if cleaned else None -def _oauth_trace_enabled() -> bool: - return os.getenv("HERMES_OAUTH_TRACE", "").strip().lower() in {"1", "true", "yes", "on"} - - def _oauth_trace(event: str, *, sequence_id: Optional[str] = None, **fields: Any) -> None: - if not _oauth_trace_enabled(): + if os.getenv("HERMES_OAUTH_TRACE", "").strip().lower() not in {"1", "true", "yes", "on"}: return payload: Dict[str, Any] = {"event": event} if sequence_id: @@ -86,12 +82,9 @@ def _portal_entitlement_message(capability: str) -> str: def _format_nous_entitlement_auth_error(error: AuthError) -> str: - try: - message = _portal_entitlement_message("Nous model access") - if message: + with suppress(Exception): + if message := _portal_entitlement_message("Nous model access"): return message - except Exception: - pass return f"{error} Check credits or billing in Nous Portal, then retry." @@ -168,9 +161,7 @@ def _scope_values(raw_scope: Any) -> set[str]: if isinstance(raw_scope, str): scopes.update(part for part in raw_scope.replace(",", " ").split() if part.strip()) elif isinstance(raw_scope, (list, tuple, set, frozenset)): - for item in raw_scope: - if isinstance(item, str): - scopes.update(_scope_values(item)) + scopes.update(*(_scope_values(item) for item in raw_scope if isinstance(item, str))) return scopes @@ -228,10 +219,8 @@ def _nous_jwt_expires_at(token: Any, fallback_expires_at: Any = None) -> Optiona claims = _decode_jwt_claims(token) exp = claims.get("exp") if isinstance(exp, (int, float)): - try: + with suppress(Exception): return datetime.fromtimestamp(float(exp), tz=timezone.utc).isoformat() - except Exception: - pass return fallback_expires_at if isinstance(fallback_expires_at, str) else None @@ -242,23 +231,17 @@ def _set_nous_agent_key_from_invoke_jwt( if not _nonempty_str(access_token): return existing_obtained_at = state.get("agent_key_obtained_at") - if obtained_at: - effective_obtained_at = obtained_at - elif state.get("agent_key") == access_token and _nonempty_str(existing_obtained_at): - effective_obtained_at = existing_obtained_at - else: - effective_obtained_at = datetime.now(timezone.utc).isoformat() + if not obtained_at: + reuse = state.get("agent_key") == access_token and _nonempty_str(existing_obtained_at) + obtained_at = existing_obtained_at if reuse else datetime.now(timezone.utc).isoformat() expires_at = _nous_jwt_expires_at(access_token, state.get("expires_at")) expires_in = _remaining_ttl(expires_at, state.get("expires_in")) if expires_at: state["expires_at"] = expires_at state["expires_in"] = expires_in - state["agent_key"] = access_token - state["agent_key_id"] = None - state["agent_key_expires_at"] = expires_at - state["agent_key_expires_in"] = expires_in - state["agent_key_reused"] = False - state["agent_key_obtained_at"] = effective_obtained_at + state.update( + agent_key=access_token, agent_key_id=None, agent_key_expires_at=expires_at, + agent_key_expires_in=expires_in, agent_key_reused=False, agent_key_obtained_at=obtained_at) def _select_nous_invoke_jwt( @@ -352,9 +335,7 @@ _NOUS_SHARED_STATE_KEYS = ( def _merge_shared_nous_oauth_state(state: Dict[str, Any]) -> bool: """Copy fresher shared OAuth tokens into a profile-local Nous state.""" from hermes_cli.auth import _nonempty_str, _parse_iso_timestamp, _read_shared_nous_state - shared = _read_shared_nous_state() - if not shared: - return False + shared = _read_shared_nous_state() or {} shared_refresh = shared.get("refresh_token") if not _nonempty_str(shared_refresh): return False @@ -827,11 +808,9 @@ def _nous_effective_routing(state: Dict[str, Any]) -> tuple[str, str, str, str]: class _NousRuntimeResolve: """Working set for one ``resolve_nous_runtime_credentials`` call. - Holds the token pair and routing tuple that shared-store merges / refreshes replace mid-flight, - and persists state to its source store skipping no-op writes: writes where only derived TTL - countdowns changed are skipped (keeps the mtime-keyed auth-status cache warm), and every real - write is mirrored to the shared store so sibling profiles don't hold stale refresh_tokens after - rotation (best-effort inside ``_write_shared_nous_state``). + Holds the token pair + routing tuple that shared-store merges / refreshes replace mid-flight. + ``persist`` skips writes where only derived TTL countdowns changed (keeps the mtime-keyed + auth-status cache warm) and mirrors every real write to the shared store (best-effort). """ def __init__( @@ -963,13 +942,11 @@ def resolve_nous_runtime_credentials( *, timeout_seconds: float = 15.0, insecure: Optional[bool] = None, ca_bundle: Optional[str] = None, force_refresh: bool = False, stale_access_token: Optional[str] = None) -> Dict[str, Any]: - """Resolve Nous inference credentials for runtime use. + """Resolve Nous inference credentials for runtime use (refreshing under the auth-store lock). - Ensures access_token is a valid inference-scoped JWT, refreshing when needed; concurrent - processes coordinate through the auth store file lock. ``stale_access_token`` is the bearer - that just failed upstream (401): with ``force_refresh``, the refresh POST is skipped if the - store (re-read under the lock) already holds a *different* usable token — a peer won the - rotation, so adopt it rather than issue N refreshes that each invalidate a sibling's token. + ``stale_access_token`` is the bearer that just failed upstream (401): with ``force_refresh``, + the refresh POST is skipped if the store (re-read under the lock) already holds a *different* + usable token — a peer won the rotation; adopt it rather than invalidate a sibling's token. """ from hermes_cli.auth import ( _assert_nous_inference_jwt_usable, _auth_file_path, _provider_state_transaction, @@ -993,10 +970,10 @@ def resolve_nous_runtime_credentials( # Persist routing and TLS metadata for non-interactive refresh — the validated, # network-provenance URL, NEVER the env override (a runtime-only overlay; persisting # it would leak a dev/staging host into auth.json and survive unsetting it). - state["portal_base_url"] = run.portal_base_url - state["inference_base_url"] = run.stored_inference_base_url - state["client_id"] = run.client_id - state["tls"] = _tls_state_from_verify(verify) + state.update( + portal_base_url=run.portal_base_url, client_id=run.client_id, + inference_base_url=run.stored_inference_base_url, + tls=_tls_state_from_verify(verify)) run.persist("resolve_nous_runtime_credentials_final") if run.persisted_any: _sync_nous_pool_from_auth_store() @@ -1035,13 +1012,10 @@ def _snapshot_nous_pool_status() -> Dict[str, Any]: entries = list(pool.entries()) if pool and pool.has_credentials() else [] if not entries: return _empty_nous_auth_status() - - def _entry_sort_key(entry: Any) -> tuple[float, float, int]: - agent_exp = _parse_iso_timestamp(getattr(entry, "agent_key_expires_at", None)) or 0.0 - access_exp = _parse_iso_timestamp(getattr(entry, "expires_at", None)) or 0.0 - return (agent_exp, access_exp, -int(getattr(entry, "priority", 0) or 0)) - - entry = max(entries, key=_entry_sort_key) + entry = max(entries, key=lambda e: ( + _parse_iso_timestamp(getattr(e, "agent_key_expires_at", None)) or 0.0, + _parse_iso_timestamp(getattr(e, "expires_at", None)) or 0.0, + -int(getattr(e, "priority", 0) or 0))) attr = lambda name, default=None: getattr(entry, name, default) # noqa: E731 if not attr("runtime_api_key"): return _empty_nous_auth_status() @@ -1129,10 +1103,9 @@ def _terminal_quarantine_marker(state: Dict[str, Any]) -> Optional[Dict[str, Any def get_nous_auth_status_local() -> Dict[str, Any]: """Refresh-free Nous auth snapshot for read-only display surfaces. - NEVER calls ``resolve_nous_runtime_credentials()`` (no refresh POST, no single-use token - consumed); classifies the persisted access token with a local invoke-JWT decode only. - ``logged_in`` = "a persisted login the runtime can use or refresh" (usable invoke JWT, or a - refresh token not terminally quarantined) — not proof the server still accepts it. + NEVER calls ``resolve_nous_runtime_credentials()`` (no refresh POST / single-use token spent); + ``logged_in`` = usable invoke JWT, or a refresh token not terminally quarantined — not proof + the server still accepts it. """ from hermes_cli.auth import get_provider_auth_state try: @@ -1146,9 +1119,9 @@ def get_nous_auth_status_local() -> Dict[str, Any]: logged_in = (jwt_reason is None) or (bool(state.get("refresh_token")) and last_err is None) status = _nous_status_from_state(state, logged_in=logged_in, source="auth_store_local") if last_err is not None: - status["relogin_required"] = True - status["error_code"] = last_err.get("code") - status["error"] = last_err.get("message") or "re-login required" + status.update( + relogin_required=True, error_code=last_err.get("code"), + error=last_err.get("message") or "re-login required") return status @@ -1163,10 +1136,9 @@ NOUS_SESSION_UNKNOWN = "unknown" def get_nous_session_validity() -> str: """Classify the Nous bootstrap session for the dashboard /api/status probe. - Reads local auth-store state only (what a dead hosted box still has); polled frequently, so it - must never resolve credentials or refresh. ANTI-FLAP CONTRACT: only a *terminal* failure maps - to "terminal" — a rotation blip, network error, or merely-expiring token must NOT (that would - trigger a spurious NAS re-mint on a healthy box). + Local auth-store state only; polled frequently, so it never resolves or refreshes. ANTI-FLAP: + only a *terminal* failure maps to "terminal" — a rotation blip, network error, or expiring + token must NOT (that would trigger a spurious NAS re-mint on a healthy box). """ from hermes_cli.auth import get_provider_auth_state try: @@ -1211,10 +1183,8 @@ def _pool_first_oauth_status( "last_refresh": getattr(entry, "last_refresh", None), "auth_mode": auth_mode, "source": f"pool:{getattr(entry, 'label', 'unknown')}", "api_key": api_key} - if on_pool_miss is not None: - degraded = on_pool_miss() - if degraded: - return degraded + if on_pool_miss is not None and (degraded := on_pool_miss()): + return degraded except Exception: pass try: @@ -1268,10 +1238,8 @@ def _nous_device_code_login( # Out-of-band consumer (e.g. the TUI gateway, whose stdout is a JSON-RPC pipe): fired AFTER # the print/browser block and BEFORE polling so it can render the link while we wait. if on_verification is not None: - try: + with suppress(Exception): on_verification(verification_url, user_code) - except Exception: - pass effective_interval = max(1, min(interval, DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS)) print(f"Waiting for approval (polling every {effective_interval}s)...") token_data = _poll_for_token( @@ -1311,25 +1279,20 @@ def _nous_device_code_login( def _mirror_nous_state_best_effort(auth_state: Dict[str, Any]) -> None: """Mirror to the shared store + reseed the pool, swallowing all errors (same as _login_nous).""" from hermes_cli.auth import _sync_nous_pool_from_auth_store, _write_shared_nous_state - try: + with suppress(Exception): _write_shared_nous_state(auth_state) - except Exception: - pass - try: + with suppress(Exception): _sync_nous_pool_from_auth_store() - except Exception: - pass def step_up_nous_billing_scope( *, open_browser: bool = True, timeout_seconds: float = 15.0, on_verification: Optional[Callable[[str, str], None]] = None) -> bool: - """Re-run the device flow requesting ``billing:manage`` and persist the result. + """Re-run the device flow requesting ``billing:manage`` (step-up on 403 insufficient_scope). - Lazy step-up on ``403 insufficient_scope``. The user must be ADMIN/OWNER and select "Allow - Remote Spending" in the portal, else the server silently downscopes and this returns False. - Reuses the held credential's URLs + client_id (same deployment); persists like ``_login_nous`` - but WITHOUT the model picker. + The user must be ADMIN/OWNER and select "Allow Remote Spending" in the portal, else the + server silently downscopes and this returns False. Persists like ``_login_nous`` minus the + model picker. """ from hermes_cli.auth import ( PROVIDER_REGISTRY, _nous_device_code_login, _save_active_provider_state, @@ -1381,10 +1344,8 @@ def _pick_nous_model_after_login( # Narrow before the tier split, so a rescued id still has to pass the free/paid predicate. _policy_allowed = nous_policy_allowed_ids() if free_tier: - try: + with suppress(Exception): unavailable_message = _portal_entitlement_message("paid Nous models") - except Exception: - unavailable_message = "" # The Portal's free/paidRecommendedModels endpoint is the source of truth for what's # available *right now*: newly-launched models show without a CLI release. union = ( diff --git a/hermes_cli/auth_oauth_grants.py b/hermes_cli/auth_oauth_grants.py index 685a338166..42c6843f87 100644 --- a/hermes_cli/auth_oauth_grants.py +++ b/hermes_cli/auth_oauth_grants.py @@ -60,8 +60,8 @@ def strip_cloned_single_use_oauth_grants(profile_dir: Path) -> Dict[str, Any]: stripped: Dict[str, Any] = {"pool": [], "providers": [], "files": []} profile_dir = Path(profile_dir) for name in SINGLE_USE_OAUTH_SINGLETON_FILES: + target = profile_dir / name try: - target = profile_dir / name if target.is_file() or target.is_symlink(): target.unlink() stripped["files"].append(name) @@ -73,17 +73,16 @@ def strip_cloned_single_use_oauth_grants(profile_dir: Path) -> Dict[str, Any]: try: store = json.loads(auth_path.read_text(encoding="utf-8-sig")) except (OSError, json.JSONDecodeError): - return stripped + store = None if not isinstance(store, dict): return stripped changed = False pool = store.get("credential_pool") if isinstance(pool, dict): for provider_id in list(pool): - if provider_id not in SINGLE_USE_REFRESH_POOL_PROVIDERS: - continue entries = pool.get(provider_id) - if not isinstance(entries, list): + if (provider_id not in SINGLE_USE_REFRESH_POOL_PROVIDERS + or not isinstance(entries, list)): continue kept = [e for e in entries if not _is_oauth_pool_payload(e)] if len(kept) != len(entries): @@ -163,16 +162,11 @@ def _oauth_freshness(entry: Dict[str, Any]) -> float: the live copy; ``last_refresh`` and the JWT ``exp`` claim are fallbacks. """ from agent.credential_pool import _parse_absolute_timestamp - best = 0.0 - for key in ("expires_at_ms", "expires_at", "last_refresh"): - ts = _parse_absolute_timestamp(entry.get(key)) - if ts and ts > best: - best = ts + stamps = [entry.get(k) for k in ("expires_at_ms", "expires_at", "last_refresh")] + best = max((ts for ts in map(_parse_absolute_timestamp, stamps) if ts), default=0.0) if best == 0.0: exp = _decode_jwt_claims(entry.get("access_token")).get("exp") - ts = _parse_absolute_timestamp(exp) - if ts: - best = ts + best = _parse_absolute_timestamp(exp) or 0.0 return best @@ -223,8 +217,7 @@ def _adopt_oauth_material(target: Dict[str, Any], winner: Dict[str, Any]) -> Dic merged[key] = winner[key] else: merged.pop(key, None) - for status_field in _POOL_STATUS_FIELDS: - merged[status_field] = None + merged.update(dict.fromkeys(_POOL_STATUS_FIELDS)) return merged @@ -272,12 +265,10 @@ def _heal_forked_provider_block( Returns None when nothing matched, False when the profile copy was dropped (root already newest), True when the profile copy was fresher and was adopted into root. """ - p_providers = profile_store.get("providers") - r_providers = root_store.get("providers") + p_providers, r_providers = profile_store.get("providers"), root_store.get("providers") if not (isinstance(p_providers, dict) and isinstance(r_providers, dict)): return None - p_block = p_providers.get(provider_id) - r_block = r_providers.get(provider_id) + p_block, r_block = p_providers.get(provider_id), r_providers.get(provider_id) if not (isinstance(p_block, dict) and p_block and isinstance(r_block, dict) and r_block): return None @@ -313,9 +304,8 @@ def _pool_rows(store: Dict[str, Any], provider_id: str) -> Tuple[Any, List[Any]] def _adopt_if_fresher( target: Dict[str, Any], candidate: Dict[str, Any]) -> Optional[Dict[str, Any]]: """*target* carrying *candidate*'s pair when the candidate rotated later, else None.""" - if _oauth_freshness(candidate) > _oauth_freshness(target): - return _adopt_oauth_material(target, candidate) - return None + fresher = _oauth_freshness(candidate) > _oauth_freshness(target) + return _adopt_oauth_material(target, candidate) if fresher else None class _HealPass: @@ -399,8 +389,7 @@ class _HealPass: # root pkce row, if any. idx = next( (i for i, r in enumerate(self.r_rows) - if _is_oauth_pool_payload(r) and _is_pkce_row(r)), - None) + if _is_oauth_pool_payload(r) and _is_pkce_row(r)), None) if idx is not None: self._adopt_root_row(idx, p_single) try: @@ -421,14 +410,15 @@ class _HealPass: return pkce_idx = next( (i for i, r in enumerate(self.r_rows) - if _is_oauth_pool_payload(r) and r.get("source") == "hermes_pkce"), - None) + if _is_oauth_pool_payload(r) and r.get("source") == "hermes_pkce"), None) if pkce_idx is None: return pkce_row = self.r_rows[pkce_idx] - if _oauth_freshness(pkce_row) > _oauth_freshness(self.root_singleton_row): + row_fresh = _oauth_freshness(pkce_row) + single_fresh = _oauth_freshness(self.root_singleton_row) + if row_fresh > single_fresh: self.root_singleton_row = _adopt_oauth_material(self.root_singleton_row, pkce_row) - elif _oauth_freshness(self.root_singleton_row) > _oauth_freshness(pkce_row): + elif single_fresh > row_fresh: self.r_rows[pkce_idx] = _adopt_oauth_material(pkce_row, self.root_singleton_row) self.root_changed = True @@ -438,13 +428,10 @@ class _HealPass: def notice(self, profile_name: str) -> str: summary = self.summary - log_bits: List[str] = [] - if summary["stripped_ids"]: - log_bits.append(f"pool rows {summary['stripped_ids']}") - if summary["providers_block"]: - log_bits.append(f"providers.{self.provider_id} block") - if summary["files"]: - log_bits.append(", ".join(summary["files"])) + log_bits = [bit for bit, present in ( + (f"pool rows {summary['stripped_ids']}", summary["stripped_ids"]), + (f"providers.{self.provider_id} block", summary["providers_block"]), + (", ".join(summary["files"]), summary["files"])) if present] verdict = ( "profile copy was the live pair; root updated" if summary["adopted"] else "root copy already newest; profile copy dropped")