The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): a sign-in outage stays a failure; xAI and Codex keep their class
Teknium1d99394fbc63
diff --git a/hermes_cli/auth_device_flow.py b/hermes_cli/auth_device_flow.pyindex 5f5a7fec1f3..5feb61ba46e 100644--- a/hermes_cli/auth_device_flow.py+++ b/hermes_cli/auth_device_flow.py@@ -331,6 +331,7 @@ def _poll_device_token_generic(deadline = time.monotonic() + max(1, expires_in)current_interval = poll_intervaledge_backoff = 0.0 # kept apart from current_interval so slow_down/pending pacing is untouched+ unavailable = 0 # HTTP status of the latest edge/service failure; 0 once the endpoint answers againwhile time.monotonic() < deadline:response = post()if response.status_code == 200:@@ -345,6 +346,7 @@ def _poll_device_token_generic(if status in {408, 429} or status >= 500 or (status == 403 and response.headers.get("x-vercel-mitigated")):from agent.retry_utils import parse_retry_after_seconds+ unavailable = statusretry_after = parse_retry_after_seconds(response.headers)if retry_after is not None:edge_backoff = min(max(current_interval, retry_after), 60)@@ -354,7 +356,7 @@ def _poll_device_token_generic(continueresponse.raise_for_status()raise on_non_json_error(response)- edge_backoff = 0.0+ edge_backoff, unavailable = 0.0, 0error_code = str(error_payload.get("error") or "")if error_code == "authorization_pending":time.sleep(current_interval)@@ -364,7 +366,8 @@ def _poll_device_token_generic(time.sleep(current_interval)continueraise on_error(response, error_payload)- raise on_timeout()+ # Still failing when the code ran out: a service outage (``__cause__``), not a sign-in left unapproved.+ raise on_timeout() from (ConnectionError(f"token endpoint answered HTTP {unavailable}") if unavailable else None)def _poll_for_token(diff --git a/hermes_cli/auth_xai.py b/hermes_cli/auth_xai.pyindex 34bb7cb1771..f94011710bf 100644--- a/hermes_cli/auth_xai.py+++ b/hermes_cli/auth_xai.py@@ -534,7 +534,9 @@ 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")+ err = _xai_err(f"xAI device-code token polling failed: {description}", "xai_device_token_failed")+ err.oauth_error_code = str(error_payload.get("error") or "") # a declined or expired code is a walk-away+ return errreturn _poll_device_token_generic(lambda: client.post(diff --git a/hermes_cli/observability/shared_metrics_setup.py b/hermes_cli/observability/shared_metrics_setup.pyindex 002656103e7..d4be0d2dda8 100644--- a/hermes_cli/observability/shared_metrics_setup.py+++ b/hermes_cli/observability/shared_metrics_setup.py@@ -114,13 +114,16 @@ def setup_failure_class(exc: BaseException) -> str:from hermes_cli.auth_error_copy import is_cancelled, is_device_code_expired, is_network_errornames = {cls.__name__ for cls in type(exc).__mro__}+ if isinstance(getattr(exc, "setup_failure_class", None), str): # classified where it was raised+ return exc.setup_failure_class# Esc in the setup menus, or consent declined on the provider's page.if is_cancelled(exc) or "_SetupCancelled" in names or getattr(exc, "oauth_error_code", "") == "access_denied":return "cancelled"- if is_device_code_expired(exc):- return "expired"+ # Before the expiry check: a code that ran out while the service kept failing is an outage.if is_network_error(exc) or (exc.__cause__ is not None and is_network_error(exc.__cause__)):return "network"+ if is_device_code_expired(exc):+ return "expired"if names & _AUTH_ERROR_TYPES:return "auth"return "other"diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 904cf73fefa..3c33de38e5d 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -17,6 +17,7 @@ from typing import Any, Callable, Dict, Optionalfrom fastapi import APIRouter, HTTPException, Request+from hermes_cli.auth_constants import _codex_errfrom hermes_cli.web_deps import LateState, latefrom hermes_cli.web_server_oauth import (_external_process_cli_command, _oauth_profile_name, _oauth_sessions, _oauth_sessions_lock, _truncate_token,@@ -215,8 +216,8 @@ def _codex_request_user_code(httpx) -> Dict[str, Any]:httpx, f"{_CODEX_ISSUER}/api/accounts/deviceauth/usercode", json={"client_id": CODEX_OAUTH_CLIENT_ID},headers=_JSON_HEADERS,)- if resp.status_code != 200:- raise RuntimeError(_codex_device_code_start_error(resp))+ if resp.status_code != 200: # a 401/403 is OpenAI refusing this account/client+ raise (_codex_err if resp.status_code in {401, 403} else RuntimeError)(_codex_device_code_start_error(resp))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"):@@ -279,7 +280,8 @@ def _codex_exchange_tokens(httpx, code_resp: Dict[str, Any]) -> Dict[str, str]:headers={"Content-Type": "application/x-www-form-urlencoded"},)if token_resp.status_code != 200:- raise RuntimeError(f"token exchange returned {token_resp.status_code}")+ raise (_codex_err if token_resp.status_code in {401, 403} else RuntimeError)(+ f"token exchange returned {token_resp.status_code}")tokens = token_resp.json()if not tokens.get("access_token"):raise RuntimeError("token exchange did not return access_token")@@ -517,7 +519,10 @@ async def _start_codex_device_code(profile: Optional[str]) -> Dict[str, Any]:with _oauth_sessions_lock:s = _oauth_sessions.get(sid, {})if s.get("status") == "error":- raise HTTPException(status_code=500, detail=s.get("error_message") or "device-auth failed")+ from hermes_cli.observability.shared_metrics_setup import _OAUTH_FAILURE_KEY+ err = HTTPException(status_code=500, detail=s.get("error_message") or "device-auth failed")+ err.setup_failure_class = s.get(_OAUTH_FAILURE_KEY) or "other" # the worker's class, not "500"+ raise errif not s.get("user_code"):raise HTTPException(status_code=504, detail="device-auth timed out before returning a user code")return {diff --git a/tests/hermes_cli/test_shared_metrics_signals.py b/tests/hermes_cli/test_shared_metrics_signals.pyindex ed29f0e5b1b..3ee799eb81c 100644--- a/tests/hermes_cli/test_shared_metrics_signals.py+++ b/tests/hermes_cli/test_shared_metrics_signals.py@@ -345,6 +345,70 @@ def test_cancel_or_lapsed_code_is_never_a_failure_and_poller_errors_keep_their_c]+def _wire(status, body):+ """A real httpx client whose every POST gets one canned response (JSON dict, else raw text)."""+ import httpx++ def reply(request):+ if isinstance(body, Exception):+ raise body+ return httpx.Response(status, request=request, **({"json": body} if isinstance(body, dict) else {"text": body}))++ return httpx.Client(transport=httpx.MockTransport(reply))+++def _poll(provider, status, body):+ """The real device-code poll loop on a fake clock (each sleep advances it)."""+ def run(monkeypatch):+ from hermes_cli import auth_device_flow+ from hermes_cli.auth_xai import _xai_oauth_poll_device_token++ clock = [0.0]+ fake_time = SimpleNamespace(monotonic=lambda: clock[0], sleep=lambda s: clock.__setitem__(0, clock[0] + max(s, 1)))+ monkeypatch.setattr(auth_device_flow, "time", fake_time)+ if provider == "nous":+ return auth_device_flow._poll_for_token(_wire(status, body), "https://p", "c", "d", 30, 1)+ return _xai_oauth_poll_device_token(+ _wire(status, body), token_endpoint="https://x/token", device_code="d", expires_in=30, poll_interval=1)+ return run+++def _codex_start(status, body):+ """The dashboard start route: the worker thread's failure crosses into an HTTPException."""+ def run(monkeypatch):+ import asyncio++ import hermes_cli.web_routers.oauth as routes++ client = _wire(status, body)+ monkeypatch.setattr(routes, "_codex_post", lambda _httpx, url, **kw: client.post(url, **kw))+ asyncio.run(routes._start_codex_device_code(None))+ return run++[email protected]("producer, ending", [+ (_poll("nous", 400, {"error": "authorization_pending"}), ("abandoned", "none")), # code left unapproved+ (_poll("nous", 503, "<html>503 unavailable</html>"), ("failed", "network")), # outage until it ran out+ (_poll("xai", 400, {"error": "access_denied"}), ("abandoned", "none")), # consent declined+ (_poll("xai", 400, {"error": "expired_token"}), ("abandoned", "none")), # the server let the code lapse+ (_poll("xai", 400, {"error": "invalid_client"}), ("failed", "auth")),+ (_codex_start(401, {"error": "invalid_client"}), ("failed", "auth")),+ (_codex_start(0, ConnectionRefusedError("down")), ("failed", "network")),+], ids=["nous-pending", "nous-503", "xai-denied", "xai-expired", "xai-refused", "codex-401", "codex-down"])+def test_wire_failures_keep_the_producers_class_to_the_recorded_end(marks, monkeypatch, producer, ending):+ """Real poll loops / start route against wire responses: a lapse or a decline is a walk-away, an+ outage or a refusal stays a failure, across the worker -> HTTPException boundary too."""+ import asyncio++ import hermes_cli.web_routers.oauth as routes++ monkeypatch.setattr(setup_metrics, "web_setup_surface", lambda: "desktop")+ flow = setup_metrics.begin_oauth_setup("nous", None)+ with pytest.raises(Exception) as ended:+ producer(monkeypatch)+ asyncio.run(routes._end_oauth_setup_metric(flow, ended.value))+ assert [r[2:] for r in _setup_rows(marks.rows)] == [("started", "none"), ending]+def test_pending_oauth_session_does_not_settle(marks, monkeypatch):monkeypatch.setattr(setup_metrics, "web_setup_surface", lambda: "dashboard")sess = {"status": "pending"}