The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): auth_xai — shared JWT-exp/token-pair helpers, packed layout, tighter docs
Teknium423c14c65ae9
diff --git a/hermes_cli/auth_xai.py b/hermes_cli/auth_xai.pyindex fdd334ac1a8..565aeb1e8e4 100644--- a/hermes_cli/auth_xai.py+++ b/hermes_cli/auth_xai.py@@ -14,86 +14,70 @@ import jsonimport osimport timefrom pathlib import Path-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, TYPE_CHECKINGfrom urllib.parse import urlparsefrom hermes_cli.auth_codex import _load_auth_store_maybe_locked, _refresh_payload_access_tokenfrom hermes_cli.auth_constants import (- AUTH_LOCK_TIMEOUT_SECONDS,- AuthError,- DEFAULT_XAI_OAUTH_BASE_URL,- DEVICE_CODE_GRANT_TYPE,- XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,- XAI_OAUTH_CLIENT_ID,- XAI_OAUTH_DEVICE_CODE_URL,- XAI_OAUTH_DISCOVERY_URL,- XAI_OAUTH_SCOPE,- _FORM_JSON_HEADERS,- _xai_err,- httpx,+ AUTH_LOCK_TIMEOUT_SECONDS, AuthError, DEFAULT_XAI_OAUTH_BASE_URL, DEVICE_CODE_GRANT_TYPE,+ XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, XAI_OAUTH_CLIENT_ID, XAI_OAUTH_DEVICE_CODE_URL,+ XAI_OAUTH_DISCOVERY_URL, XAI_OAUTH_SCOPE, _FORM_JSON_HEADERS, _xai_err, httpx,)from utils import env_float-from typing import TYPE_CHECKING-if TYPE_CHECKING: # annotation-only; the runtime import would be a cyclefrom hermes_cli.auth import ProviderConfig# Log-record parity with the origin module (caplog tests pin "hermes_cli.auth").logger = logging.getLogger("hermes_cli.auth")+_RELOGIN = "Re-authenticate with `hermes model`."+++def _clean(value: Any) -> str:+ return str(value or "").strip()+++def _token_pair(tokens: Any) -> tuple[str, str]:+ """``(access_token, refresh_token)`` stripped; empty strings when *tokens* is not a dict."""+ if not isinstance(tokens, dict):+ return "", ""+ return _clean(tokens.get("access_token")), _clean(tokens.get("refresh_token"))+def _xai_oauth_state_from_store(auth_store: Dict[str, Any]) -> Optional[Dict[str, Any]]:"""Return usable xAI OAuth state from provider state or credential pool."""from hermes_cli.auth import _load_provider_statestate = _load_provider_state(auth_store, "xai-oauth")- tokens = state.get("tokens") if isinstance(state, dict) else None- if isinstance(tokens, dict):- access_token = str(tokens.get("access_token", "") or "").strip()- refresh_token = str(tokens.get("refresh_token", "") or "").strip()- if access_token and refresh_token:- return state+ if isinstance(state, dict) and all(_token_pair(state.get("tokens"))):+ return statecredential_pool = auth_store.get("credential_pool")- entries = (- credential_pool.get("xai-oauth")- if isinstance(credential_pool, dict)- else None- )- if isinstance(entries, list):- for entry in entries:- if not isinstance(entry, dict):- continue- access_token = str(entry.get("access_token", "") or "").strip()- refresh_token = str(entry.get("refresh_token", "") or "").strip()- if not access_token or not refresh_token:- continue- merged = dict(state or {})- merged["tokens"] = {- "access_token": access_token,- "refresh_token": refresh_token,- "token_type": str(entry.get("token_type") or "Bearer"),- }- if entry.get("last_refresh"):- merged["last_refresh"] = entry.get("last_refresh")- merged.setdefault("auth_mode", "oauth_pkce")- return merged+ entries = credential_pool.get("xai-oauth") if isinstance(credential_pool, dict) else None+ for entry in entries if isinstance(entries, list) else ():+ access_token, refresh_token = _token_pair(entry)+ if not access_token or not refresh_token:+ continue+ merged = dict(state or {})+ merged["tokens"] = {+ "access_token": access_token,+ "refresh_token": refresh_token,+ "token_type": str(entry.get("token_type") or "Bearer"),+ }+ if entry.get("last_refresh"):+ merged["last_refresh"] = entry.get("last_refresh")+ merged.setdefault("auth_mode", "oauth_pkce")+ return mergedreturn state if isinstance(state, dict) else Nonedef _xai_oauth_state_has_usable_tokens(state: Optional[Dict[str, Any]]) -> bool:- tokens = state.get("tokens") if isinstance(state, dict) else None- return (- isinstance(tokens, dict)- and bool(str(tokens.get("access_token", "") or "").strip())- and bool(str(tokens.get("refresh_token", "") or "").strip())- )+ return isinstance(state, dict) and all(_token_pair(state.get("tokens")))def _read_xai_oauth_tokens(*, _lock: bool = True) -> Dict[str, Any]:from hermes_cli.auth import _load_global_auth_store- auth_store = _load_auth_store_maybe_locked(_lock)- state = _xai_oauth_state_from_store(auth_store)+ state = _xai_oauth_state_from_store(_load_auth_store_maybe_locked(_lock))if not _xai_oauth_state_has_usable_tokens(state):global_state = _xai_oauth_state_from_store(_load_global_auth_store())if _xai_oauth_state_has_usable_tokens(global_state):@@ -105,22 +89,13 @@ def _read_xai_oauth_tokens(*, _lock: bool = True) -> Dict[str, Any]:)tokens = state.get("tokens")if not isinstance(tokens, dict):- raise _xai_err(- "xAI OAuth state is missing tokens. Re-authenticate with `hermes model`.",- "xai_auth_invalid_shape", relogin=True,- )- access_token = str(tokens.get("access_token", "") or "").strip()- refresh_token = str(tokens.get("refresh_token", "") or "").strip()- if not access_token:- raise _xai_err(- "xAI OAuth state is missing access_token. Re-authenticate with `hermes model`.",- "xai_auth_missing_access_token", relogin=True,- )- if not refresh_token:- raise _xai_err(- "xAI OAuth state is missing refresh_token. Re-authenticate with `hermes model`.",- "xai_auth_missing_refresh_token", relogin=True,- )+ raise _xai_err(f"xAI OAuth state is missing tokens. {_RELOGIN}", "xai_auth_invalid_shape", relogin=True)+ access_token, refresh_token = _token_pair(tokens)+ for value, field in ((access_token, "access_token"), (refresh_token, "refresh_token")):+ if not value:+ raise _xai_err(+ f"xAI OAuth state is missing {field}. {_RELOGIN}", f"xai_auth_missing_{field}", relogin=True,+ )return {"tokens": tokens,"last_refresh": state.get("last_refresh"),@@ -130,41 +105,30 @@ def _read_xai_oauth_tokens(*, _lock: bool = True) -> Dict[str, Any]:def _write_through_xai_oauth_to_global_root(state: Dict[str, Any]) -> None:- """Persist a rotated xAI OAuth ``state`` into the global-root auth.json.+ """Persist a rotated xAI OAuth ``state`` into the global-root auth.json (best effort).- Best-effort write-through for the multi-profile rotation hazard (#43589): xAI rotates the- refresh_token on every refresh, so when a profile session refreshes a grant it resolved from the- root fallback, the rotated chain must land back in root.-- Only updates ``providers.xai-oauth`` in the root store; never touches the profile store (the- caller already saved that). Swallows all errors — a failed write-through degrades to the pre-- existing behavior (root stale), it must never break the profile's own successful save.+ xAI rotates the refresh_token on every refresh, so when a profile session refreshes a grant it+ resolved from the root fallback, the rotated chain must land back in root. Only updates+ ``providers.xai-oauth`` in root; never touches the profile store (the caller saved that).+ Swallows all errors — a failed write-through degrades to root-stale, never breaks the profile save."""from hermes_cli.auth import _global_auth_file_path, _persist_provider_state_to_storeglobal_path = _global_auth_file_path()- if global_path is None:- # Classic mode (profile == root); the profile save already hit root.+ if global_path is None: # classic mode (profile == root); the profile save already hit rootreturn- # Seat belt: under pytest, refuse to write the real user's- # ~/.hermes/auth.json even when HERMES_HOME points at a profile path- # (mirrors the read-side guard in _load_global_auth_store). Uses the- # unmodified HOME env, not Path.home() which fixtures may monkeypatch.- if os.environ.get("PYTEST_CURRENT_TEST"):- real_home_env = os.environ.get("HOME", "")- if real_home_env:- real_root = Path(real_home_env) / ".hermes" / "auth.json"- try:- if global_path.resolve(strict=False) == real_root.resolve(strict=False):- return- except Exception:+ # Seat belt: under pytest, refuse to write the real user's ~/.hermes/auth.json even when+ # HERMES_HOME points at a profile path (mirrors the read-side guard in _load_global_auth_store).+ # Uses the unmodified HOME env, not Path.home() which fixtures may monkeypatch.+ real_home_env = os.environ.get("HOME", "") if os.environ.get("PYTEST_CURRENT_TEST") else ""+ if real_home_env:+ real_root = Path(real_home_env) / ".hermes" / "auth.json"+ try:+ if global_path.resolve(strict=False) == real_root.resolve(strict=False):return+ except Exception:+ returntry:- _persist_provider_state_to_store(- "xai-oauth",- state,- global_path,- set_active=False,- )+ _persist_provider_state_to_store("xai-oauth", state, global_path, set_active=False)except Exception as exc: # pragma: no cover - best effortlogger.debug("xAI OAuth: write-through to global root failed: %s", exc)@@ -180,105 +144,70 @@ def _save_xai_oauth_tokens() -> None:"""Persist xAI OAuth tokens into the auth store.- When *set_active* is True (default), also promote ``xai-oauth`` to ``active_provider`` —- appropriate for intentional model/auth login. Pass ``set_active=False`` for side-tool credential- bootstrap (TTS/setup, tools config, dashboard token save, token refresh) so inference routing is- unchanged.+ *set_active* (default True) also promotes ``xai-oauth`` to ``active_provider`` — right for an+ intentional login. Pass False for side-tool credential bootstrap (TTS/setup, tools config,+ dashboard token save, token refresh) so inference routing is unchanged."""from hermes_cli.auth import _auth_store_lock, _global_auth_file_path, _load_auth_store, _load_provider_state_with_source, _same_path, _save_auth_store, _store_provider_state, _utc_now_z, _write_through_xai_oauth_to_global_rootif last_refresh is None:last_refresh = _utc_now_z()with _auth_store_lock():auth_store = _load_auth_store()- # A profile that lacks its own xai-oauth block is reading the root- # grant through _load_provider_state's fallback. When such a profile- # refreshes the (rotating) grant, we must write the rotated chain back- # to root too, or root is left holding a revoked refresh token (#43589).- # #74339: the old key-presence check (_profile_has_own_xai_oauth_state)- # decided write-through based on whether the profile had a- # providers.xai-oauth key BEFORE the save — but _store_provider_state- # unconditionally creates that key below. Use- # _load_provider_state_with_source to learn where the grant was- # resolved from and write back only to that source.- state, source_path = _load_provider_state_with_source(- auth_store, "xai-oauth"- )- if state is None:- state = {}- state["tokens"] = tokens- state["last_refresh"] = last_refresh- state["auth_mode"] = auth_mode+ # A profile without its own xai-oauth block reads the root grant through+ # _load_provider_state's fallback. Refreshing that (rotating) grant must write the rotated+ # chain back to root, or root keeps a revoked refresh token. Decide by where the grant was+ # resolved FROM, not by key presence: _store_provider_state below would create the key.+ state, source_path = _load_provider_state_with_source(auth_store, "xai-oauth")+ state = state if state is not None else {}+ state.update(tokens=tokens, last_refresh=last_refresh, auth_mode=auth_mode)if discovery:state["discovery"] = discoveryif redirect_uri:state["redirect_uri"] = redirect_uriglobal_root = _global_auth_file_path()- is_from_root = bool(- source_path is not None- and global_root is not None- and _same_path(source_path, global_root)- )- if is_from_root:- # Grant was resolved from root — write back to root only.- # Do NOT call _store_provider_state on the profile auth_store- # (it would create a shadowing providers.xai-oauth key that- # disables write-through on the next refresh — #74339).+ if source_path is not None and global_root is not None and _same_path(source_path, global_root):+ # Resolved from root — write back to root only. Storing on the profile auth_store would+ # create a shadowing providers.xai-oauth key that disables write-through next refresh._write_through_xai_oauth_to_global_root(state)else:- # Profile genuinely owns this — write to profile store.- _store_provider_state(- auth_store, "xai-oauth", state, set_active=set_active- )+ _store_provider_state(auth_store, "xai-oauth", state, set_active=set_active)_save_auth_store(auth_store)-def _xai_access_token_is_expiring(access_token: str, skew_seconds: int = 0) -> bool:+def _xai_jwt_exp(access_token: Any) -> Optional[float]:+ """``exp`` claim of a JWT-shaped access token, or None when absent/undecodable."""if not isinstance(access_token, str) or "." not in access_token:- return False+ return Nonetry:parts = access_token.split(".")if len(parts) < 2:- return False- payload_b64 = parts[1]- payload_b64 += "=" * (-len(payload_b64) % 4)- payload = json.loads(base64.urlsafe_b64decode(payload_b64.encode("ascii")).decode("utf-8"))- exp = payload.get("exp")- if not isinstance(exp, (int, float)):- return False- return float(exp) <= (time.time() + max(0, int(skew_seconds)))+ return None+ payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)+ exp = json.loads(base64.urlsafe_b64decode(payload_b64.encode("ascii")).decode("utf-8")).get("exp")+ return float(exp) if isinstance(exp, (int, float)) else Noneexcept Exception:- return False+ return None+++def _xai_access_token_is_expiring(access_token: str, skew_seconds: int = 0) -> bool:+ exp = _xai_jwt_exp(access_token)+ return exp is not None and exp <= time.time() + max(0, int(skew_seconds))def _xai_proactive_refresh_skew_seconds(access_token: str) -> int:"""How far before JWT ``exp`` to proactively refresh xAI OAuth tokens.- SuperGrok sessions ship multi-hour tokens where the gateway-oriented hour-long skew makes sense,- but device-code logins often return ~15-minute JWTs; the full skew would force a refresh on- every credential resolution, burning single-use refresh tokens and racing concurrent callers- into ``invalid_grant`` quarantine.+ SuperGrok sessions ship multi-hour tokens where the hour-long skew makes sense, but device-code+ logins often return ~15-minute JWTs; the full skew would force a refresh on every credential+ resolution, burning single-use refresh tokens and racing concurrent callers into+ ``invalid_grant`` quarantine."""max_skew = XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS- if not isinstance(access_token, str) or "." not in access_token:- return max_skew- try:- parts = access_token.split(".")- if len(parts) < 2:- return max_skew- payload_b64 = parts[1]- payload_b64 += "=" * (-len(payload_b64) % 4)- payload = json.loads(base64.urlsafe_b64decode(payload_b64.encode("ascii")).decode("utf-8"))- exp = payload.get("exp")- if not isinstance(exp, (int, float)):- return max_skew- remaining = float(exp) - time.time()- if remaining <= 0:- return max_skew- if remaining <= 45 * 60:- return min(120, max_skew)- return max_skew- except Exception:+ exp = _xai_jwt_exp(access_token)+ if exp is None:return max_skew+ remaining = exp - time.time()+ return min(120, max_skew) if 0 < remaining <= 45 * 60 else max_skewdef _is_xai_origin_host(host: str) -> bool:@@ -290,22 +219,15 @@ def _xai_validate_oauth_endpoint(url: str, *, field: str) -> str:"""Refuse any OIDC discovery endpoint that isn't HTTPS on the xAI origin.The discovery result is cached in auth.json, so a single MITM at login could plant a malicious- ``token_endpoint`` that receives the refresh_token forever. Pinning scheme + host (RFC 8414 §2:- HTTPS issuer, same-origin token_endpoint) removes that persistence; ``x.ai`` is the bare apex,- so an exact match or any ``.x.ai`` suffix is accepted.+ ``token_endpoint`` that receives the refresh_token forever. Pinning scheme + host (RFC 8414 §2)+ removes that persistence."""parsed = urlparse(url)if parsed.scheme != "https":- raise _xai_err(- f"xAI OIDC discovery returned a non-HTTPS {field}: {url!r}.",- "xai_discovery_invalid",- )+ raise _xai_err(f"xAI OIDC discovery returned a non-HTTPS {field}: {url!r}.", "xai_discovery_invalid")host = (parsed.hostname or "").lower()if not host:- raise _xai_err(- f"xAI OIDC discovery {field} is missing a hostname: {url!r}.",- "xai_discovery_invalid",- )+ raise _xai_err(f"xAI OIDC discovery {field} is missing a hostname: {url!r}.", "xai_discovery_invalid")if not _is_xai_origin_host(host):raise _xai_err(f"xAI OIDC discovery {field} host {host!r} is not on the xAI origin "@@ -320,12 +242,9 @@ def _xai_validate_oauth_endpoint(url: str, *, field: str) -> str:def _xai_validate_inference_base_url(value: str, *, fallback: str) -> str:"""Refuse a non-xAI base_url for the OAuth-authenticated inference path.- Pin the inference origin to ``api.x.ai`` (or any ``*.x.ai`` subdomain xAI may add). On- rejection, fall back to the default and log a warning rather than raise — a bad env var should- not deadlock authentication, but it should also never leak the bearer.-- ``value`` is the already-stripped, trailing-slash-trimmed candidate from env. Empty input- returns ``fallback`` unchanged.+ Pins the inference origin to ``api.x.ai`` (or any ``*.x.ai`` subdomain). On rejection, fall+ back to the default and log a warning rather than raise — a bad env var should not deadlock+ authentication, but it must never leak the bearer. Empty input returns ``fallback``."""candidate = (value or "").strip().rstrip("/")if not candidate:@@ -333,10 +252,7 @@ def _xai_validate_inference_base_url(value: str, *, fallback: str) -> str:try:parsed = urlparse(candidate)except Exception:- logger.warning(- "Ignoring malformed xAI base_url override %r; using %s instead.",- candidate, fallback,- )+ logger.warning("Ignoring malformed xAI base_url override %r; using %s instead.", candidate, fallback)return fallbackif parsed.scheme != "https":logger.warning(@@ -347,10 +263,7 @@ def _xai_validate_inference_base_url(value: str, *, fallback: str) -> str:return fallbackhost = (parsed.hostname or "").lower()if not host:- logger.warning(- "Ignoring xAI base_url override %r with no hostname; using %s instead.",- candidate, fallback,- )+ logger.warning("Ignoring xAI base_url override %r with no hostname; using %s instead.", candidate, fallback)return fallbackif not _is_xai_origin_host(host):logger.warning(@@ -366,43 +279,23 @@ def _xai_validate_inference_base_url(value: str, *, fallback: str) -> str:def _xai_oauth_discovery(timeout_seconds: float = 15.0) -> Dict[str, str]:try:- response = httpx.get(- XAI_OAUTH_DISCOVERY_URL,- headers={"Accept": "application/json"},- timeout=timeout_seconds,- )+ response = httpx.get(XAI_OAUTH_DISCOVERY_URL, headers={"Accept": "application/json"}, timeout=timeout_seconds)except Exception as exc:raise _xai_err(f"xAI OIDC discovery failed: {exc}", "xai_discovery_failed") from excif response.status_code != 200:- raise _xai_err(- f"xAI OIDC discovery returned status {response.status_code}.",- "xai_discovery_failed",- )+ raise _xai_err(f"xAI OIDC discovery returned status {response.status_code}.", "xai_discovery_failed")try:payload = response.json()except Exception as exc:- raise _xai_err(- f"xAI OIDC discovery returned invalid JSON: {exc}",- "xai_discovery_invalid_json",- ) from exc+ raise _xai_err(f"xAI OIDC discovery returned invalid JSON: {exc}", "xai_discovery_invalid_json") from excif not isinstance(payload, dict):- raise _xai_err(- "xAI OIDC discovery response was not a JSON object.",- "xai_discovery_incomplete",- )- authorization_endpoint = str(payload.get("authorization_endpoint", "") or "").strip()- token_endpoint = str(payload.get("token_endpoint", "") or "").strip()- if not authorization_endpoint or not token_endpoint:- raise _xai_err(- "xAI OIDC discovery response was missing required endpoints.",- "xai_discovery_incomplete",- )- _xai_validate_oauth_endpoint(authorization_endpoint, field="authorization_endpoint")- _xai_validate_oauth_endpoint(token_endpoint, field="token_endpoint")- return {- "authorization_endpoint": authorization_endpoint,- "token_endpoint": token_endpoint,- }+ raise _xai_err("xAI OIDC discovery response was not a JSON object.", "xai_discovery_incomplete")+ endpoints = {k: _clean(payload.get(k)) for k in ("authorization_endpoint", "token_endpoint")}+ if not all(endpoints.values()):+ raise _xai_err("xAI OIDC discovery response was missing required endpoints.", "xai_discovery_incomplete")+ for field, url in endpoints.items():+ _xai_validate_oauth_endpoint(url, field=field)+ return endpointsdef _xai_tokens_from_payload(payload: Dict[str, Any], access_token: str, fallback_refresh: str) -> Dict[str, Any]:@@ -410,9 +303,9 @@ def _xai_tokens_from_payload(payload: Dict[str, Any], access_token: str, fallbacreturn {"access_token": access_token,"refresh_token": str(payload.get("refresh_token") or fallback_refresh).strip(),- "id_token": str(payload.get("id_token") or "").strip(),+ "id_token": _clean(payload.get("id_token")),"expires_in": payload.get("expires_in"),- "token_type": str(payload.get("token_type") or "Bearer").strip() or "Bearer",+ "token_type": _clean(payload.get("token_type") or "Bearer") or "Bearer",}@@ -427,40 +320,29 @@ def refresh_xai_oauth_pure(del access_tokenif not _nonempty_str(refresh_token):raise _xai_err(- "xAI OAuth is missing refresh_token. Re-authenticate with `hermes model`.",- "xai_auth_missing_refresh_token", relogin=True,+ f"xAI OAuth is missing refresh_token. {_RELOGIN}", "xai_auth_missing_refresh_token", relogin=True,)endpoint = token_endpoint.strip() or _xai_oauth_discovery(timeout_seconds)["token_endpoint"]- # Re-validate cached endpoints on the refresh hot path: an auth.json- # written by an older Hermes (or hand-edited) may carry a non-xAI- # token_endpoint that would receive every future refresh_token in- # plaintext if we trusted it blindly. Cheap suffix check; fast-fail- # with a clear error so the user can re-run `hermes model` to refetch.+ # Re-validate cached endpoints on the refresh hot path: an auth.json written by an older Hermes+ # (or hand-edited) may carry a non-xAI token_endpoint that would receive every future+ # refresh_token in plaintext if trusted blindly._xai_validate_oauth_endpoint(endpoint, field="token_endpoint")timeout = httpx.Timeout(max(5.0, float(timeout_seconds)))with httpx.Client(timeout=timeout, headers={"Accept": "application/json"}) as client:response = client.post(endpoint,headers={"Content-Type": "application/x-www-form-urlencoded"},- data={- "grant_type": "refresh_token",- "client_id": XAI_OAUTH_CLIENT_ID,- "refresh_token": refresh_token,- },+ data={"grant_type": "refresh_token", "client_id": XAI_OAUTH_CLIENT_ID, "refresh_token": refresh_token},)if response.status_code != 200:detail = response.text.strip()- # ``403`` from xAI's token endpoint is almost always a tier /- # entitlement gate (the OAuth grant exists but the account isn't- # on the allowlist for API access). Re-running ``hermes model``- # won't fix that — surface a separate error code so- # ``format_auth_error`` doesn't append a misleading- # re-authenticate hint, and point users at the ``XAI_API_KEY``- # fallback. See #26847.+ suffix = f" Response: {detail}" if detail else ""+ # 403 from xAI's token endpoint is almost always a tier / entitlement gate (the grant exists+ # but the account isn't allowlisted for API access). Re-running `hermes model` won't fix+ # that — use a separate code so format_auth_error skips the re-authenticate hint.if response.status_code == 403:raise _xai_err(- "xAI token refresh failed with HTTP 403."- + (f" Response: {detail}" if detail else "")+ "xAI token refresh failed with HTTP 403." + suffix+ " This OAuth account is not authorized for xAI API"" access — xAI may be restricting API/OAuth use to"" specific SuperGrok tiers despite the in-app"@@ -471,9 +353,7 @@ def refresh_xai_oauth_pure("xai_oauth_tier_denied", relogin=False,)raise _xai_err(- "xAI token refresh failed."- + (f" Response: {detail}" if detail else ""),- "xai_refresh_failed", relogin=response.status_code in {400, 401},+ "xAI token refresh failed." + suffix, "xai_refresh_failed", relogin=response.status_code in {400, 401},)payload, refreshed_access = _refresh_payload_access_token(response,@@ -481,19 +361,10 @@ def refresh_xai_oauth_pure(invalid_json=("xAI token refresh returned invalid JSON: {exc}", "xai_refresh_invalid_json"),invalid_json_relogin=False,strict_str=False,- invalid_response=(- "xAI token refresh response was not a JSON object.",- "xai_refresh_invalid_response",- ),- missing_access=(- "xAI token refresh response was missing access_token.",- "xai_refresh_missing_access_token",- ),+ invalid_response=("xAI token refresh response was not a JSON object.", "xai_refresh_invalid_response"),+ missing_access=("xAI token refresh response was missing access_token.", "xai_refresh_missing_access_token"),)- return {- **_xai_tokens_from_payload(payload, refreshed_access, refresh_token),- "last_refresh": _utc_now_z(),- }+ return {**_xai_tokens_from_payload(payload, refreshed_access, refresh_token), "last_refresh": _utc_now_z()}def _refresh_xai_oauth_tokens(@@ -503,9 +374,8 @@ def _refresh_xai_oauth_tokens(redirect_uri: str = "",timeout_seconds: float,) -> Dict[str, Any]:- # Re-persist whatever auth_mode is already stored (legacy pre-device-code- # logins may still carry ``oauth_pkce``): the refresh hot path must not- # relabel how the grant was originally obtained.+ # Re-persist whatever auth_mode is already stored (legacy pre-device-code logins may still+ # carry ``oauth_pkce``): the refresh hot path must not relabel how the grant was obtained.from hermes_cli.auth import _load_auth_store, _load_provider_state, refresh_xai_oauth_puretry:state = _load_provider_state(_load_auth_store(), "xai-oauth") or {}@@ -513,10 +383,8 @@ def _refresh_xai_oauth_tokens(except Exception:auth_mode = "oauth_device_code"refreshed = refresh_xai_oauth_pure(- str(tokens.get("access_token", "") or ""),- str(tokens.get("refresh_token", "") or ""),- token_endpoint=token_endpoint,- timeout_seconds=timeout_seconds,+ _clean(tokens.get("access_token")), _clean(tokens.get("refresh_token")),+ token_endpoint=token_endpoint, timeout_seconds=timeout_seconds,)updated_tokens = dict(tokens)updated_tokens["access_token"] = refreshed["access_token"]@@ -527,15 +395,11 @@ def _refresh_xai_oauth_tokens(updated_tokens["expires_in"] = refreshed["expires_in"]if refreshed.get("token_type"):updated_tokens["token_type"] = refreshed["token_type"]+ # set_active=False: refresh must not flip active_provider — TTS/side tools can refresh xAI+ # tokens while chat still routes through another provider._save_xai_oauth_tokens(- updated_tokens,- discovery={"token_endpoint": token_endpoint},- redirect_uri=redirect_uri,- last_refresh=refreshed["last_refresh"],- auth_mode=auth_mode,- # Refresh must not flip active_provider — TTS/side tools can refresh- # xAI tokens while chat still routes through another provider.- set_active=False,+ updated_tokens, discovery={"token_endpoint": token_endpoint}, redirect_uri=redirect_uri,+ last_refresh=refreshed["last_refresh"], auth_mode=auth_mode, set_active=False,)return updated_tokens@@ -544,33 +408,29 @@ def _quarantine_xai_oauth_tokens(exc: AuthError) -> None:"""Clear dead xAI tokens from auth.json after a terminal refresh failure.Terminal = HTTP 400/401/403 (invalid_grant, token revoked). Subsequent sessions then fail fast- without a network retry. Mirrors credential_pool.py quarantine. Best-effort: persistence- failures are logged and swallowed (caller re-raises the original error regardless).+ without a network retry. Best-effort: persistence failures are logged and swallowed (caller+ re-raises the original error regardless)."""from hermes_cli.auth import _last_auth_error_marker, _load_auth_store, _load_provider_state, _save_auth_store, _store_provider_statetry:- _q_store = _load_auth_store()- _q_state = _load_provider_state(_q_store, "xai-oauth") or {}- _q_tokens = dict(_q_state.get("tokens") or {})- _q_tokens.pop("access_token", None)- _q_tokens.pop("refresh_token", None)- _q_state["tokens"] = _q_tokens- _q_state["last_auth_error"] = _last_auth_error_marker(- "xai-oauth", exc,- reason="runtime_refresh_failure", default_code="xai_refresh_failed",- )- _store_provider_state(_q_store, "xai-oauth", _q_state, set_active=False)- _save_auth_store(_q_store)- except Exception as _save_exc:- logger.debug(- "xAI OAuth: failed to persist quarantined state: %s", _save_exc,+ store = _load_auth_store()+ state = _load_provider_state(store, "xai-oauth") or {}+ tokens = dict(state.get("tokens") or {})+ tokens.pop("access_token", None)+ tokens.pop("refresh_token", None)+ state["tokens"] = tokens+ state["last_auth_error"] = _last_auth_error_marker(+ "xai-oauth", exc, reason="runtime_refresh_failure", default_code="xai_refresh_failed",)+ _store_provider_state(store, "xai-oauth", state, set_active=False)+ _save_auth_store(store)+ except Exception as save_exc:+ logger.debug("xAI OAuth: failed to persist quarantined state: %s", save_exc)def _xai_oauth_inference_base_url() -> str:return _xai_validate_inference_base_url(- os.getenv("HERMES_XAI_BASE_URL", "").strip().rstrip("/")- or os.getenv("XAI_BASE_URL", "").strip().rstrip("/"),+ os.getenv("HERMES_XAI_BASE_URL", "").strip().rstrip("/") or os.getenv("XAI_BASE_URL", "").strip().rstrip("/"),fallback=DEFAULT_XAI_OAUTH_BASE_URL,)@@ -582,20 +442,19 @@ def resolve_xai_oauth_runtime_credentials(refresh_skew_seconds: Optional[int] = None,) -> Dict[str, Any]:from hermes_cli.auth import _auth_store_lock, _is_terminal_xai_oauth_refresh_error, _refresh_xai_oauth_tokens, _xai_oauth_discovery+def _view(data: Dict[str, Any]) -> tuple[Dict[str, Any], str, str, str, bool]:tokens = dict(data["tokens"])- access_token = str(tokens.get("access_token", "") or "").strip()- discovery = dict(data.get("discovery") or {})- token_endpoint = str(discovery.get("token_endpoint", "") or "").strip()- redirect_uri = str(data.get("redirect_uri", "") or "").strip()+ access_token = _clean(tokens.get("access_token"))+ token_endpoint = _clean(dict(data.get("discovery") or {}).get("token_endpoint"))+ redirect_uri = _clean(data.get("redirect_uri"))effective_skew = (- int(refresh_skew_seconds)- if refresh_skew_seconds is not None+ int(refresh_skew_seconds) if refresh_skew_seconds is not Noneelse _xai_proactive_refresh_skew_seconds(access_token))- should_refresh = bool(force_refresh)- if (not should_refresh) and refresh_if_expiring:- should_refresh = _xai_access_token_is_expiring(access_token, effective_skew)+ should_refresh = bool(force_refresh) or bool(+ refresh_if_expiring and _xai_access_token_is_expiring(access_token, effective_skew)+ )return tokens, access_token, token_endpoint, redirect_uri, should_refreshdata = _read_xai_oauth_tokens()@@ -610,37 +469,28 @@ def resolve_xai_oauth_runtime_credentials(token_endpoint = _xai_oauth_discovery(refresh_timeout_seconds)["token_endpoint"]try:tokens = _refresh_xai_oauth_tokens(- tokens,- token_endpoint=token_endpoint,- redirect_uri=redirect_uri,+ tokens, token_endpoint=token_endpoint, redirect_uri=redirect_uri,timeout_seconds=refresh_timeout_seconds,)- access_token = str(tokens.get("access_token", "") or "").strip()+ access_token = _clean(tokens.get("access_token"))except AuthError as exc:if _is_terminal_xai_oauth_refresh_error(exc):_quarantine_xai_oauth_tokens(exc)raise- base_url = _xai_oauth_inference_base_url()return {"provider": "xai-oauth",- "base_url": base_url,+ "base_url": _xai_oauth_inference_base_url(),"api_key": access_token,"source": "hermes-auth-store","last_refresh": data.get("last_refresh"),- # Display/telemetry only. Device-code is the only supported xAI OAuth- # flow, so report it unconditionally — auth.json may still carry a- # legacy ``oauth_pkce`` label, which the refresh path preserves as-is.+ # Display/telemetry only. Device-code is the only supported xAI OAuth flow, so report it+ # unconditionally — auth.json may still carry a legacy ``oauth_pkce`` label."auth_mode": "oauth_device_code",}-def _login_xai_oauth(- args,- pconfig: ProviderConfig,- *,- force_new_login: bool = False,-) -> None:+def _login_xai_oauth(args, pconfig: ProviderConfig, *, force_new_login: bool = False) -> None:from hermes_cli.auth import _is_remote_session, _offer_existing_oauth_credentials, _print_login_success, _update_config_for_provider, _xai_oauth_device_code_login, resolve_xai_oauth_runtime_credentials, unsuppress_credential_sourcedel pconfig@@ -663,10 +513,7 @@ def _login_xai_oauth(if _is_remote_session():open_browser = False- creds = _xai_oauth_device_code_login(- timeout_seconds=timeout_seconds,- open_browser=open_browser,- )+ creds = _xai_oauth_device_code_login(timeout_seconds=timeout_seconds, open_browser=open_browser)_save_xai_oauth_tokens(creds["tokens"],discovery=creds.get("discovery"),@@ -674,31 +521,19 @@ def _login_xai_oauth(last_refresh=creds.get("last_refresh"),auth_mode="oauth_device_code",)- # An explicit interactive re-login is a strong signal the user wants the- # xAI credential re-enabled. ``hermes auth remove xai-oauth`` leaves a- # ``device_code`` suppression marker that otherwise stops the singleton- # seed from re-creating the pool entry, so ``hermes auth list`` would show- # nothing even though the agent still works via the singleton fallback.- # Clear it here (same helper ``auth_add_command`` uses). This is kept OUT- # of ``_save_xai_oauth_tokens`` on purpose — that helper is shared with the- # refresh hot path, which must never mutate suppression state.+ # An explicit interactive re-login means the user wants the xAI credential re-enabled.+ # ``hermes auth remove xai-oauth`` leaves a ``device_code`` suppression marker that otherwise+ # stops the singleton seed from re-creating the pool entry. Kept OUT of _save_xai_oauth_tokens+ # on purpose — that helper is shared with the refresh hot path, which must never mutate+ # suppression state.unsuppress_credential_source("xai-oauth", "device_code")config_path = _update_config_for_provider("xai-oauth", creds.get("base_url", DEFAULT_XAI_OAUTH_BASE_URL))_print_login_success("xai-oauth", config_path, show_auth_state=True)-def _xai_oauth_request_device_code(- client: httpx.Client,- *,- scope: str = XAI_OAUTH_SCOPE,-) -> Dict[str, Any]:+def _xai_oauth_request_device_code(client: httpx.Client, *, scope: str = XAI_OAUTH_SCOPE) -> Dict[str, Any]:response = client.post(- XAI_OAUTH_DEVICE_CODE_URL,- headers=_FORM_JSON_HEADERS,- data={- "client_id": XAI_OAUTH_CLIENT_ID,- "scope": scope,- },+ XAI_OAUTH_DEVICE_CODE_URL, headers=_FORM_JSON_HEADERS, data={"client_id": XAI_OAUTH_CLIENT_ID, "scope": scope},)if response.status_code != 200:raise _xai_err(@@ -707,20 +542,10 @@ def _xai_oauth_request_device_code("device_code_request_failed",)payload = response.json()- required = (- "device_code",- "user_code",- "verification_uri",- "verification_uri_complete",- "expires_in",- "interval",- )+ required = ("device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in", "interval")missing = [key for key in required if key not in payload]if missing:- raise _xai_err(- f"xAI device-code response missing fields: {', '.join(missing)}",- "device_code_invalid",- )+ raise _xai_err(f"xAI device-code response missing fields: {', '.join(missing)}", "device_code_invalid")return payload@@ -733,6 +558,7 @@ def _xai_oauth_poll_device_token(poll_interval: int,) -> Dict[str, Any]:from hermes_cli.auth import _poll_device_token_generic+def _validate(payload: Dict[str, Any]) -> None:for field_name, article in (("access_token", "an"), ("refresh_token", "a")):if not payload.get(field_name):@@ -742,89 +568,56 @@ def _xai_oauth_poll_device_token()def _error(response, error_payload) -> Exception:- description = (- error_payload.get("error_description")- or error_payload.get("error")- or response.text- )- return _xai_err(- f"xAI device-code token polling failed: {description}",- "xai_device_token_failed",- )+ description = error_payload.get("error_description") or error_payload.get("error") or response.text+ return _xai_err(f"xAI device-code token polling failed: {description}", "xai_device_token_failed")return _poll_device_token_generic(lambda: client.post(token_endpoint,headers=_FORM_JSON_HEADERS,- data={- "grant_type": DEVICE_CODE_GRANT_TYPE,- "client_id": XAI_OAUTH_CLIENT_ID,- "device_code": device_code,- },+ data={"grant_type": DEVICE_CODE_GRANT_TYPE, "client_id": XAI_OAUTH_CLIENT_ID, "device_code": device_code},),expires_in=int(expires_in),poll_interval=max(1, int(poll_interval)),validate_success=_validate,on_non_json_error=lambda _r: _xai_err(- "xAI device-code token polling returned a non-JSON error response.",- "xai_device_token_failed",+ "xAI device-code token polling returned a non-JSON error response.", "xai_device_token_failed",),on_error=_error,- on_timeout=lambda: _xai_err(- "Timed out waiting for xAI device authorization.",- "device_code_timeout",- ),+ on_timeout=lambda: _xai_err("Timed out waiting for xAI device authorization.", "device_code_timeout"),)-def _xai_oauth_device_code_login(- *,- timeout_seconds: float = 20.0,- open_browser: bool = True,-) -> Dict[str, Any]:+def _xai_oauth_device_code_login(*, timeout_seconds: float = 20.0, open_browser: bool = True) -> Dict[str, Any]:from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session, _print_device_code_instructions, _utc_now_z, _xai_oauth_discovery, _xai_oauth_poll_device_tokendiscovery = _xai_oauth_discovery(timeout_seconds)- token_endpoint = discovery["token_endpoint"]timeout = httpx.Timeout(max(20.0, timeout_seconds))with httpx.Client(timeout=timeout, headers={"Accept": "application/json"}) as client:device_data = _xai_oauth_request_device_code(client)- verification_url = str(- device_data.get("verification_uri_complete")- or device_data["verification_uri"]- )- user_code = str(device_data["user_code"])- expires_in = int(device_data["expires_in"])interval = int(device_data["interval"])-_print_device_code_instructions(- verification_url,- user_code,+ str(device_data.get("verification_uri_complete") or device_data["verification_uri"]),+ str(device_data["user_code"]),open_browser=open_browser and not _is_remote_session() and _can_open_graphical_browser(),swallow_open_errors=True,)print(f"Waiting for approval (polling every {max(1, interval)}s)...")-payload = _xai_oauth_poll_device_token(client,- token_endpoint=token_endpoint,+ token_endpoint=discovery["token_endpoint"],device_code=str(device_data["device_code"]),- expires_in=expires_in,+ expires_in=int(device_data["expires_in"]),poll_interval=interval,)- access_token = str(payload.get("access_token", "") or "").strip()- refresh_token = str(payload.get("refresh_token", "") or "").strip()+ access_token, refresh_token = _token_pair(payload)if not access_token or not refresh_token:- raise _xai_err(- "xAI device-code token response was missing required tokens.",- "xai_device_token_invalid",- )- base_url = _xai_oauth_inference_base_url()+ raise _xai_err("xAI device-code token response was missing required tokens.", "xai_device_token_invalid")return {"tokens": _xai_tokens_from_payload(payload, access_token, refresh_token),"discovery": discovery,"redirect_uri": "",- "base_url": base_url,+ "base_url": _xai_oauth_inference_base_url(),"last_refresh": _utc_now_z(),"source": "oauth-device-code",}