The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(auth): every Nous sign-in is the plain device login (#143235)
Siddharth Balyan67cfede5a93e
diff --git a/gateway/slash_commands_login.py b/gateway/slash_commands_login.pyindex 2b0e85d29f8..52252a0609b 100644--- a/gateway/slash_commands_login.py+++ b/gateway/slash_commands_login.py@@ -29,10 +29,11 @@ class _SignInAttempt:key: tuplesource: Anycancelled: bool = False+ saving: bool = False # past the final cancel check: the save is committed, a replacement waits-# These adapters use "dm" for a broadcast topic, a channel, or an agent peer. Sending a consent-# link and sign-in code there would publish them rather than deliver them to one person.+# These adapters use "dm" for a broadcast topic, a channel, or an agent peer. Sending a sign-in+# link and code there would publish them rather than deliver them to one person._LOGIN_BLOCKED_PLATFORMS = frozenset({"ntfy", "raft", "a2a"})@@ -102,7 +103,7 @@ class GatewayLoginCommandsMixin:# replacement command would wait behind the very attempt it needs to stop.with lock:live = attempts.get(_LOGIN_SINGLE)- if live is not None and live.key != key:+ if live is not None and (live.key != key or live.saving):return anon_auth.LOGIN_BUSY_ELSEWHEREif live is not None:live.cancelled = True@@ -113,7 +114,7 @@ class GatewayLoginCommandsMixin:with lock:live = attempts.get(_LOGIN_SINGLE)- if live is not None and live.key != key:+ if live is not None and (live.key != key or live.saving):return anon_auth.LOGIN_BUSY_ELSEWHEREif live is not None:live.cancelled = True@@ -131,11 +132,18 @@ class GatewayLoginCommandsMixin:with lock:return attempt.cancelled- gen = anon_auth.run_sign_in(- timeout_seconds=15.0,- cancelled=_cancelled,- cancel_wins_after_promotion=False,- )+ @contextlib.contextmanager+ def _persist_guard():+ # The final cancel check claims the save under the registry lock, so a replacing /login+ # either cancels first or is told a sign-in is finishing. The save itself runs outside+ # the lock: the event loop takes that lock, and a save can wait on the auth store.+ with lock:+ if not attempt.cancelled:+ attempt.saving = True+ may_persist = attempt.saving+ yield may_persist++ gen = anon_auth.run_sign_in(timeout_seconds=15.0, cancelled=_cancelled, persist_guard=_persist_guard)pushed_terminal = Falsetry:while True:diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.pyindex b2d8a9f863d..7f1568d308f 100644--- a/hermes_cli/anon_auth.py+++ b/hermes_cli/anon_auth.py@@ -1013,103 +1013,15 @@ def _save_guest_state(auth_store: dict[str, Any], state: dict[str, Any], source__save_auth_store(source_store, target_path=source_path)-# --- ``hermes auth upgrade``: sign the guest into a real Nous account, keeping its connectors ---------+# --- Sign-in completion: the account state from a token grant, and the config settle -------------#-# Wire: the normal device-code flow, with a promotion intent registered on NAS BETWEEN the code-# request and the token poll (``POST /api/anonymous/promotion-intent {token, user_code, device_code}``).-# NAS then transfers the guest's connectors into whichever account approves that device code. We-# watch ``POST /api/anonymous/promotion-status {claim_code}`` until it leaves ``pending``; only a-# ``completed`` promotion is followed by the token grant, which ``persist_nous_credentials`` writes-# over the guest singleton and the shared store. The server never reports expiry: our own-# ``expires_in`` clock ends the wait. User-facing copy never says guest / anonymous / claim.+# Every Nous sign-in is the plain device-code login (``anon_sign_in.run_sign_in``). The free tier it+# replaces hands its apps over in ``guest_handoff`` after the save. User-facing copy never says+# guest / anonymous / claim.UPGRADED_AUTH_METHOD = "oauth_device_code"-def register_promotion_intent(- client: httpx.Client, portal_base_url: str, anon_token: str, *, user_code: str, device_code: str,-) -> dict[str, Any]:- """``POST /api/anonymous/promotion-intent`` -> ``{claim_code, claim_url, expires_in, interval}``."""- response = client.post(- f"{portal_base_url.rstrip('/')}/api/anonymous/promotion-intent", headers=_anon_headers(),- json={"token": anon_token, "user_code": user_code, "device_code": device_code})- payload = _raise_for_anon_status(response, action="sign-in")- if not isinstance(payload.get("claim_code"), str) or not payload["claim_code"]:- logger.info("Nous free tier sign-in returned no transfer code")- raise _anon_err(ANON_FAILURE_COPY[ANON_SERVER_ERROR], ANON_SERVER_ERROR)- return payload---def _retry_after_seconds(response: httpx.Response, default: float) -> float:- seconds = parse_retry_after_seconds(response.headers)- return default if seconds is None else seconds---def _sleep_until(wake: float, cancelled: Optional[Callable[[], bool]]) -> bool:- """Sleep until the monotonic time *wake*. Returns True when *cancelled* fired first.-- Without a hook this is one plain :func:`time.sleep`. With one the sleep is cut into <= 1 s- ticks so an attempt stopped from outside ends in about a second instead of blocking to the- sign-in code's own expiry.- """- if cancelled is None:- remaining = wake - time.monotonic()- if remaining > 0:- time.sleep(remaining)- return False- while True:- if cancelled():- return True- remaining = wake - time.monotonic()- if remaining <= 0:- return False- time.sleep(min(1.0, remaining))---def wait_for_promotion(- client: httpx.Client, portal_base_url: str, claim_code: str, *, expires_in: int, interval: int,- cancelled: Optional[Callable[[], bool]] = None,-) -> dict[str, Any]:- """Poll ``POST /api/anonymous/promotion-status`` until it leaves ``pending`` or our clock runs out.-- Returns the final status payload; ``{"status": "timeout"}`` when ``expires_in`` elapsed. 429 honours- ``Retry-After``; other non-2xx statuses raise through :func:`_raise_for_anon_status`.-- *cancelled* is an optional hook a surface passes to stop an attempt it no longer wants (a newer- sign-in replaced it, the user cancelled, the process is shutting down). It is polled at the top- of every iteration and on a <= 1 s tick while sleeping; once it has fired this call returns- ``{"status": "cancelled"}`` for every outcome except a ``completed`` transfer already in hand,- which is reported so the caller's ``cancel_wins_after_promotion`` ruling can decide it.- Passing nothing is today's behaviour.- """- deadline = time.monotonic() + max(1, int(expires_in))- wait = max(0, int(interval))- while time.monotonic() < deadline:- if cancelled is not None and cancelled():- return {"status": "cancelled"}- response = client.post(- f"{portal_base_url.rstrip('/')}/api/anonymous/promotion-status", headers=_anon_headers(),- json={"claim_code": claim_code})- if response.status_code == 429:- retry = min(_retry_after_seconds(response, default=max(1, wait)),- max(0.0, deadline - time.monotonic()))- if _sleep_until(time.monotonic() + retry, cancelled):- return {"status": "cancelled"}- continue- payload = _raise_for_anon_status(response, action="sign-in")- status = str(payload.get("status") or "unknown")- if status != "pending":- # A completed transfer is already committed on the account service; report it even when- # the hook fired during this request. run_sign_in's cancel_wins_after_promotion- # rules what each surface does with it. Every other terminal outcome loses to a cancel.- if status != "completed" and cancelled is not None and cancelled():- return {"status": "cancelled"}- return payload- if _sleep_until(time.monotonic() + wait, cancelled):- return {"status": "cancelled"}- return {"status": "timeout"}--def _account_state_from_token(token_data: dict[str, Any], *, portal_base_url: str, client_id: str, scope: Optional[str], verify: Any,timeout_seconds: float,@@ -1203,9 +1115,9 @@ def persist_nous_credentials(*args, **kwargs):# The flow imports this module only inside calls, so either module can be imported first.from hermes_cli.anon_sign_in import (AlreadySignedIn,+ Cancelled,Code,Completed,- Declined,FREE_TIER_RATE_LIMIT_CARD,FREE_TIER_RATE_LIMIT_CHAT,Failed,@@ -1214,9 +1126,7 @@ from hermes_cli.anon_sign_in import (LOGIN_DM_ONLY,LOGIN_NOT_ALLOWED,LOGIN_STARTING,- Retired,SignInState,- Superseded,TimedOut,UPGRADE_ALREADY_SIGNED_IN,UPGRADE_CANCELLED,@@ -1224,18 +1134,12 @@ from hermes_cli.anon_sign_in import (UPGRADE_NOT_COMPLETED,UPGRADE_NO_DEFAULT_CHAT,UPGRADE_NO_DEFAULT_TERMINAL,- UPGRADE_REASON_COPY,UPGRADE_START,UPGRADE_TIMED_OUT,- UPGRADE_UNAVAILABLE,- UPGRADE_UNAVAILABLE_CHAT,UPGRADE_WAITING,UPGRADE_WAITING_UP_TO,- Unavailable,Waiting,- _RETIRED_REASONS,_default_persist_guard,- _outcome_state,format_wait_line,run_sign_in,)diff --git a/hermes_cli/anon_sign_in.py b/hermes_cli/anon_sign_in.pyindex 2b2ea1d7abf..0cd7f6ab43d 100644--- a/hermes_cli/anon_sign_in.py+++ b/hermes_cli/anon_sign_in.py@@ -1,4 +1,4 @@-"""Shared sign-in states, copy, and connector-preserving account promotion flow."""+"""The one Nous sign-in: the plain device-code login every surface renders, plus its states and copy."""from __future__ import annotations@@ -6,7 +6,7 @@ import contextlibimport mathimport timefrom dataclasses import dataclass-from typing import Any, Callable, ClassVar, ContextManager, Dict, Iterator, Optional+from typing import Any, Callable, ClassVar, ContextManager, Iterator, Optionalfrom hermes_cli.auth_constants import httpx@@ -16,21 +16,8 @@ UPGRADE_ALREADY_SIGNED_IN = "Already signed in."UPGRADE_DO_NOT_SHARE = "Do not share this code."UPGRADE_TIMED_OUT = "That sign-in link has expired. Start again whenever you're ready."UPGRADE_NOT_COMPLETED = "Sign-in didn't finish. Try again whenever you're ready."-UPGRADE_UNAVAILABLE = "The free tier is not available right now; run `hermes auth add nous` to sign in."-UPGRADE_REASON_COPY = {- "user_declined": "No problem, you're still on the free Nous service. Sign in whenever you're ready.",- "superseded": "A newer sign-in code replaced this one. Use the newest one, or start again.",- "account_retired": "Your session ended before the sign-in finished. A new one starts on its own; "- "sign in again whenever you're ready.",- "account_not_anonymous": "Your session ended before the sign-in finished. A new one starts on its own; "- "sign in again whenever you're ready.",- "account_busy": "Something's still finishing up on your account. Give it a few seconds, then try signing in again.",-}-_RETIRED_REASONS = frozenset({"account_retired", "account_not_anonymous"})-# Reasons a later attempt can succeed at: the desktop offers "try again" after the named wait.-RETRYABLE_SIGN_IN_REASONS = frozenset({"account_busy"})# The account service was busy or unreachable mid sign-in (an ``anon_*`` code from-# ``anon_auth``): the identity is untouched, so the copy reassures before the way forward.+# ``anon_auth.classify_mint_exception``): nothing was saved, so the copy reassures before the way forward.UPGRADE_SERVICE_BUSY = ("Signing in couldn't finish because the Nous service is busy. ""Try again in {wait}. Your session is still here in the meantime.")UPGRADE_SERVICE_UNREACHABLE = ("The Nous service couldn't be reached to finish signing you in. "@@ -41,7 +28,6 @@ UPGRADE_NO_DEFAULT_CHAT = "No default model is set yet; run /model to pick one."UPGRADE_WAITING = "Waiting for sign-in..."UPGRADE_WAITING_UP_TO = "Waiting for sign-in, up to {minutes}."UPGRADE_CANCELLED = "\nSign-in cancelled."-UPGRADE_UNAVAILABLE_CHAT = "The free tier is not available right now. Try /login again in a moment."LOGIN_COMMAND = "/login"LOGIN_STARTING = "Starting sign-in..."LOGIN_DM_ONLY = "Sign in from a direct message with Hermes."@@ -75,7 +61,7 @@ class SignInState:kind: ClassVar[str] = ""terminal: ClassVar[bool] = True # False only for Code and Waitingok: ClassVar[bool] = False # exit-code 0 / "this ended well"- precondition: ClassVar[bool] = False # True only for AlreadySignedIn and Unavailable+ precondition: ClassVar[bool] = False # True only for AlreadySignedIn@propertydef copy(self) -> str:@@ -84,13 +70,13 @@ class SignInState:@propertydef copy_terminal(self) -> str:- """The terminal form; differs for Completed, Failed and Unavailable."""+ """The terminal form; differs for Completed and Failed."""return self.copy@dataclass(frozen=True)class Code(SignInState):- """The consent link and the sign-in code, plus the clock the caller may show."""+ """The device page link and the sign-in code, plus the clock the caller may show."""link: strcode: str@@ -121,14 +107,18 @@ class Waiting(SignInState):@dataclass(frozen=True)class Completed(SignInState):+ """``handoff`` holds the guest handoff's result lines (what moved, what to reconnect), empty+ when the sign-in replaced no free tier."""+email: str = ""model: str = ""model_changed: bool = False+ handoff: tuple[str, ...] = ()kind: ClassVar[str] = "completed"ok: ClassVar[bool] = Truedef _lines(self, no_default: str) -> str:- lines = [f"Signed in as {self.email}." if self.email else "Signed in."]+ lines = [f"Signed in as {self.email}." if self.email else "Signed in.", *self.handoff]if self.model_changed:lines.append(f"Default model is now {self.model}." if self.model else no_default)return "\n".join(lines)@@ -143,23 +133,14 @@ class Completed(SignInState):@dataclass(frozen=True)-class Declined(SignInState):- kind: ClassVar[str] = "declined"-- @property- def copy(self) -> str:- return UPGRADE_REASON_COPY["user_declined"]-+class Cancelled(SignInState):+ """Stopped from outside before anything was saved: the user's cancel, a newer /login, a shutdown."""-@dataclass(frozen=True)-class Superseded(SignInState):- """Stopped from outside before it could persist: a newer code, a cancel, or a shutdown."""-- kind: ClassVar[str] = "superseded"+ kind: ClassVar[str] = "cancelled"@propertydef copy(self) -> str:- return UPGRADE_REASON_COPY["superseded"]+ return UPGRADE_CANCELLED.strip()@dataclass(frozen=True)@@ -173,23 +154,12 @@ class TimedOut(SignInState):return UPGRADE_TIMED_OUT-@dataclass(frozen=True)-class Retired(SignInState):- """The identity this sign-in started from is gone; run_sign_in already cleared it."""-- kind: ClassVar[str] = "retired"-- @property- def copy(self) -> str:- return UPGRADE_REASON_COPY["account_retired"]--@dataclass(frozen=True)class Failed(SignInState):- """``reason``: a promotion outcome reason (``account_busy``...), an ``anon_*`` code from the- account service (busy, paused, unreachable...), or "" for anything unnamed. ``retry_after``:- the wait the service asked for, in seconds (0 when it named none). ``retryable``: whether a- later attempt can succeed, so a renderer knows to offer "try again" and when."""+ """``reason``: an ``anon_*`` code naming the service's verdict (busy, unreachable...), or "" for+ anything unnamed. ``retry_after``: the wait the service asked for, in seconds (0 when it named+ none). ``retryable``: whether a later attempt can succeed, so a renderer knows to offer "try+ again" and when."""reason: str = ""detail: str = ""@@ -199,16 +169,11 @@ class Failed(SignInState):@propertydef retryable(self) -> bool:from hermes_cli import anon_auth as _core- if self.reason in RETRYABLE_SIGN_IN_REASONS:- return Truereturn bool(self.reason.startswith("anon_") and self.reason not in _core.ANON_TERMINAL_CODES)@propertydef copy(self) -> str:from hermes_cli import anon_auth as _core- ruled = UPGRADE_REASON_COPY.get(self.reason)- if ruled:- return ruledif self.reason in _core.ANON_UNREACHABLE_CODES:return UPGRADE_SERVICE_UNREACHABLEif self.reason in (_core.ANON_RATE_LIMITED, _core.ANON_GATE_PAUSED):@@ -235,57 +200,20 @@ class AlreadySignedIn(SignInState):return UPGRADE_ALREADY_SIGNED_IN-@dataclass(frozen=True)-class Unavailable(SignInState):- detail: str = ""- kind: ClassVar[str] = "unavailable"- precondition: ClassVar[bool] = True-- @property- def copy(self) -> str:- return UPGRADE_UNAVAILABLE_CHAT-- @property- def copy_terminal(self) -> str:- return f"{UPGRADE_UNAVAILABLE} ({self.detail})" if self.detail else UPGRADE_UNAVAILABLE--def _failed_from_exception(exc: BaseException) -> Failed:- """A ``Failed`` that keeps the account service's own verdict: the ``anon_*`` code and wait hint- an ``AuthError`` carries, or the wire's shape for a transport error. The raw detail never- reaches a chat; ``copy_terminal`` may show it when nothing better is known."""+ """A ``Failed`` that keeps the service's own verdict: the ``anon_*`` code and wait hint an+ ``AuthError`` carries, or the wire's shape for a transport error. The raw detail never reaches a+ chat; ``copy_terminal`` may show it when nothing better is known."""from hermes_cli import anon_auth as _coreerr = _core.classify_mint_exception(exc)reason = str(err.code or "")if reason == _core.ANON_SERVER_ERROR and not isinstance(exc, _core.AuthError):- # An unnamed local failure (a bad CA bundle, a lock timeout): keep today's generic copy- # and its terminal detail rather than blaming the service.+ # An unnamed local failure (a bad CA bundle, a lock timeout): keep the generic copy and its+ # terminal detail rather than blaming the service.return Failed(reason="", detail=str(exc))return Failed(reason=reason, detail=str(exc), retry_after=float(err.retry_after or 0.0))-def _outcome_state(outcome: dict[str, Any], anon_token: str) -> SignInState:- """The one reason -> state mapping in the tree, for a promotion that did not complete.-- A retiring outcome clears the dead identity here, pinned to the token this attempt started- from, so a losing attempt can never remove a newer one.- """- from hermes_cli import anon_auth as _core-- status = str(outcome.get("status") or "unknown")- reason = str(outcome.get("reason") or "")- if status == "timeout":- return TimedOut()- if reason in _RETIRED_REASONS:- _core.clear_dead_guest("retired", dead_token=anon_token or None)- return Retired()- if reason == "user_declined":- return Declined()- if reason == "superseded":- return Superseded()- return Failed(reason=reason)--def _default_persist_guard(is_cancelled: Callable[[], bool]) -> Callable[[], ContextManager[bool]]:"""The persist guard used when a surface brings none: proceed unless the attempt was stopped."""@contextlib.contextmanager@@ -294,74 +222,72 @@ def _default_persist_guard(is_cancelled: Callable[[], bool]) -> Callable[[], Conreturn _guard+def _account_email(account_state: dict[str, Any], fallback: Optional[str]) -> str:+ """The signed-in account's email, read from its own access token."""+ from hermes_cli.auth_constants import _decode_jwt_claims+ email = _decode_jwt_claims(account_state.get("access_token")).get("email")+ return str(email or fallback or "").strip()+++def _handoff_lines(results: list[dict[str, Any]]) -> tuple[str, ...]:+ from hermes_cli.guest_handoff import result_lines+ return tuple(line for view in results for line in result_lines(view))++def run_sign_in(*,timeout_seconds: float = 15.0,cancelled: Optional[Callable[[], bool]] = None,- cancel_wins_after_promotion: bool = True,+ replace_account: bool = False,persist_guard: Optional[Callable[[], ContextManager[bool]]] = None,scope: Optional[Callable[[], ContextManager[Any]]] = None,client_factory: Optional[Callable[[float, Any], ContextManager[httpx.Client]]] = None,) -> Iterator[SignInState]:- """Sign the free tier into a Nous account, keeping its connectors. Yields :class:`SignInState`s.-- One composition behind every surface: it reads the current identity itself, mints one when there- is none, registers the connector transfer, holds ONE absolute deadline across both waits,- persists only after a completed transfer AND a token grant, and runs- :func:`settle_after_upgrade` exactly once per completion. It always ends by yielding exactly one- state whose ``terminal`` is True -- a persist or settle failure becomes ``Failed``, never an- exception out of ``next()``.-- *cancelled* is polled between round trips and inside :func:`wait_for_promotion`.- *cancel_wins_after_promotion* rules what a cancel means once the account service has already- transferred the connectors: True (the desktop) aborts and persists nothing -- the install- re-mints a free tier on next use; False (a chat that was superseded) finishes, because a- transfer the user approved in the browser is irreversible and discarding it would leave the- connectors moved with no account to reach them.+ """Sign in with a Nous account: the plain device-code login. Yields :class:`SignInState`s.++ One composition behind every surface: device code, then a cancel-aware token poll on one+ deadline, then the save. The save is where the guest handoff hooks in (``guest_handoff``): a free+ tier the account replaces has its apps moved once the surface's lock is released, and the result+ rides :class:`Completed`. :func:`settle_after_upgrade` runs exactly once per completion. Works+ with or without a free tier on disk. It always ends by yielding exactly one state whose+ ``terminal`` is True: a persist or settle failure becomes ``Failed``, never an exception out of+ ``next()``.++ *cancelled* is polled before the wait, on a <= 1 s tick inside the token poll, and once more+ under *persist_guard* before the save; a cancel always wins and nothing is saved.+ *replace_account* lets a signed-in install sign in again (the desktop's "connect another+ account"); without it a signed-in install yields ``AlreadySignedIn`` before any network.*persist_guard* lets a surface make its own cancel check and the save atomic under its own lock.- *scope* is entered only around the two non-network blocks (preconditions/mint, persist/settle),- never across a ``yield``: ``run_in_executor`` does not carry contextvars, so the scope has to be+ *scope* is entered only around the two non-network blocks (precondition, persist/settle), never+ across a ``yield``: ``run_in_executor`` does not carry contextvars, so the scope has to beentered inside the generator, on whichever thread is advancing it.*client_factory* is the HTTP client seam, ``client_factory(timeout_seconds, verify)``."""from hermes_cli import anon_auth as _corefrom hermes_cli.auth import PROVIDER_REGISTRY, _resolve_verify- from hermes_cli.auth_device_flow import _request_device_code- from hermes_cli.auth_nous import _nous_http_client+ from hermes_cli.auth_device_flow import DeviceFlowCancelled, _request_device_code+ from hermes_cli.auth_error_copy import is_device_code_expired+ from hermes_cli.auth_nous import _nous_http_client, _nous_portal_base_url+ from hermes_cli.guest_handoff import deferredis_cancelled = cancelled or (lambda: False)- # Once the server says "completed" the transfer has happened; a cancel only undoes it where the- # surface says it does.- post_promotion_cancelled = is_cancelled if cancel_wins_after_promotion else (lambda: False)open_scope = scope or contextlib.nullcontext- # Preconditions run inside the scope; the state they produce is yielded outside it, because a- # scope must never be held across a ``yield``. A sign-in never creates the identity it signs in- # from: with none on disk there is nothing to promote and the answer is ``Unavailable`` (the- # trial claim and connector use are the only creators, NS-845 Q1.2).- precondition_state: Optional[SignInState] = None+ # Yielded outside the scope, because a scope must never be held across a ``yield``.state: Optional[dict[str, Any]] = Nonetry:with open_scope():state = _core.current_nous_state()- if state and not _core.is_guest_state(state):- precondition_state = AlreadySignedIn()- elif not state or not _core.guest_allowed():- precondition_state = Unavailable()- except Exception as exc:- # An unreadable auth store means the same thing here: there is no free tier to sign in from.- # It becomes the one precondition state, so nothing escapes ``next()``. KeyboardInterrupt- # and GeneratorExit are not Exceptions: they still propagate.- precondition_state = Unavailable(detail=str(exc))- if precondition_state is not None:- yield precondition_state+ # Inside the scope: the operator's Portal override is a profile setting, and it wins over+ # a saved URL the same way it does for every other Nous call.+ portal = _nous_portal_base_url(state or {})+ except Exception as exc: # health: allow BLE001 -- the generator's contract is one terminal state, never a raise+ yield Failed(reason="", detail=str(exc))+ return+ if state and not _core.is_guest_state(state) and not replace_account:+ yield AlreadySignedIn()return- anon_token = str(state.get("anon_token") or "")- portal = (state.get("portal_base_url") or _core._portal_base_url()).rstrip("/")-- outcome: dict[str, Any] = {}- account_state: Optional[dict[str, Any]] = Nonetry:pconfig = PROVIDER_REGISTRY["nous"]client_id, scope_str = pconfig.client_id, pconfig.scope@@ -370,60 +296,24 @@ def run_sign_in(open_client = client_factory or _nous_http_clientwith open_client(timeout_seconds, verify) as client:device = _request_device_code(client, portal, client_id, scope_str)- intent = _core.register_promotion_intent(- client, portal, anon_token, user_code=str(device["user_code"]),- device_code=str(device["device_code"]))- # The browser leg is the consent page for THIS sign-in (claim_url), not the generic- # device page: it shows both identities and the button. Relative paths are- # portal-relative.- link = str(intent.get("claim_url") or "")- if link.startswith("/"):- link = f"{portal}{link}"- link = link or str(device["verification_uri_complete"])- expires_in = min(int(device["expires_in"]), int(intent.get("expires_in") or device["expires_in"]))- interval = int(intent.get("interval") or device.get("interval") or 5)+ expires_in = int(device["expires_in"])+ interval = int(device.get("interval") or 5)deadline = time.monotonic() + max(1, expires_in)- yield Code(link=link, code=str(intent["claim_code"]), expires_in=expires_in, interval=interval)- if is_cancelled(): # nothing is approved anywhere yet: a cancel always wins here- yield Superseded()+ yield Code(link=str(device["verification_uri_complete"]), code=str(device["user_code"]),+ expires_in=expires_in, interval=interval)+ if is_cancelled():+ yield Cancelled()returnyield Waiting()-- remaining = max(1, int(deadline - time.monotonic()))- outcome = _core.wait_for_promotion(- client, portal, str(intent["claim_code"]),- expires_in=remaining, interval=interval, cancelled=is_cancelled)- status = str(outcome.get("status") or "unknown")- if status != "completed":- # A cancel is authoritative for every non-completed outcome, including the- # {"status": "cancelled"} the hook returns.- if is_cancelled():- yield Superseded()- return- # Scoped: a retiring outcome clears the identity out of this profile's auth store.- with open_scope():- ended = _outcome_state(outcome, anon_token)- yield ended- return- if post_promotion_cancelled():- yield Superseded()- return-- remaining = max(1, int(deadline - time.monotonic()))token_data = _core._poll_for_token(client=client, portal_base_url=portal, client_id=client_id,- device_code=str(device["device_code"]), expires_in=remaining, poll_interval=interval)+ device_code=str(device["device_code"]), expires_in=max(1, int(deadline - time.monotonic())),+ poll_interval=interval, cancelled=is_cancelled)account_state = _core._account_state_from_token(token_data, portal_base_url=portal, client_id=client_id, scope=scope_str,verify=verify, timeout_seconds=timeout_seconds)- except _core.AnonCredentialDead:- # Best effort: the credential is provably dead at the account service, so the outcome is- # Retired whatever the local write does. A clear that fails (locked or read-only store)- # self-heals on the next rejection, and must not cost this run its terminal state.- with contextlib.suppress(Exception):- with open_scope():- _core.clear_dead_guest("retired", dead_token=anon_token or None)- yield Retired()+ except DeviceFlowCancelled:+ yield Cancelled()returnexcept TimeoutError as exc:# The code ran out while the token endpoint kept failing (``_poll_device_token_generic`` sets@@ -432,22 +322,17 @@ def run_sign_in(yield _failed_from_exception(outage) if outage else TimedOut(detail=str(exc))returnexcept Exception as exc:- yield _failed_from_exception(exc)+ # The token endpoint's own ``expired_token`` answer is the same timeout as running out the clock.+ yield TimedOut(detail=str(exc)) if is_device_code_expired(exc) else _failed_from_exception(exc)return+ guard = persist_guard or _default_persist_guard(is_cancelled)try:- if post_promotion_cancelled():- yield Superseded()- return- guard = persist_guard or _default_persist_guard(post_promotion_cancelled)- from hermes_cli.guest_handoff import deferred, note_promotedwith open_scope():# The handoff runs once the surface's lock is released, never inside it.- with deferred():+ with deferred() as handoff:with guard() as may_persist:if may_persist:- # The completed promotion already moved the apps: nothing left to claim.- note_promoted(anon_token, account_email=str(outcome.get("account_email") or "") or None)_core.persist_nous_credentials(account_state)if may_persist:settled = _core.settle_after_upgrade(account_state)@@ -458,10 +343,11 @@ def run_sign_in(yield Failed(reason="", detail=str(exc))returnif not may_persist: # yielded outside the scope, never across it- yield Superseded()+ yield Cancelled()returnyield Completed(- email=str(outcome.get("account_email") or "").strip(),+ email=_account_email(account_state, handoff.account_email),model=str(settled.get("model") or ""),- model_changed=bool(settled.get("changed")))+ model_changed=bool(settled.get("changed")),+ handoff=_handoff_lines(handoff.results))diff --git a/hermes_cli/anon_sign_in_cli.py b/hermes_cli/anon_sign_in_cli.pyindex 86c64ebfb28..2278a428c6f 100644--- a/hermes_cli/anon_sign_in_cli.py+++ b/hermes_cli/anon_sign_in_cli.py@@ -69,10 +69,10 @@ def render_sign_in_cli(def upgrade_guest(args) -> int:- """``hermes auth upgrade``: sign in with a Nous account, transferring the free tier's connectors.+ """``hermes auth upgrade``: sign in with a Nous account; a free tier it replaces hands its apps over.- Returns 0 on success (or when already signed in), 1 otherwise, 130 on Ctrl-C. Never persists- anything unless the transfer completed AND the token grant succeeded.+ Returns 0 on success (or when already signed in), 1 otherwise, 130 on Ctrl-C. Nothing is saved+ before the token grant."""from hermes_cli import anon_auth as _corefrom hermes_cli.auth_device_flow import _is_remote_sessiondiff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.pyindex 75430053dd3..592c6dfdb0b 100644--- a/hermes_cli/auth_commands.py+++ b/hermes_cli/auth_commands.py@@ -312,10 +312,16 @@ def _add_nous_oauth_credential(args, provider: str) -> PooledCredential:def _persist(creds: dict, what: str) -> PooledCredential:# `--label` is embedded into providers.nous so label_from_token doesn't overwrite it on every# subsequent load_pool("nous").- entry = auth_mod.persist_nous_credentials(creds, label=custom_label)+ from hermes_cli.anon_auth import settle_after_upgrade+ from hermes_cli.guest_handoff import deferred, result_lines+ with deferred() as handoff: # a replaced free tier hands its apps over once the save lands+ entry = auth_mod.persist_nous_credentials(creds, label=custom_label)+ settle_after_upgrade(creds) # a config left on the free tier's route moves to the accountshown_label = entry.label if entry is not None else label_from_token(creds.get("access_token", ""), f"{provider}-oauth-1")print(f'{what} {provider} OAuth {"device-code " if what == "Saved" else ""}credentials: "{shown_label}"')+ for line in (line for view in handoff.results for line in result_lines(view)):+ print(f" {line}")return entry# Codex-style auto-import: a shared Nous credential at <hermes-root>/shared/nous_auth.jsondiff --git a/hermes_cli/auth_device_flow.py b/hermes_cli/auth_device_flow.pyindex 6664c5dac6e..54737c5e1ea 100644--- a/hermes_cli/auth_device_flow.py+++ b/hermes_cli/auth_device_flow.py@@ -318,12 +318,30 @@ def _print_device_code_instructions(print(f" Could not open browser automatically {failure_dash} use the URL above.")+class DeviceFlowCancelled(Exception):+ """The caller's ``cancelled`` hook fired while the token poll was waiting."""+++def _cancellable_sleep(seconds: float, cancelled: Optional[Callable[[], bool]]) -> None:+ """Sleep *seconds*; with a hook, in <= 1 s ticks so a cancel ends the poll within a second."""+ if cancelled is None:+ time.sleep(seconds)+ return+ wake = time.monotonic() + seconds+ while not cancelled():+ remaining = wake - time.monotonic()+ if remaining <= 0:+ return+ time.sleep(min(1.0, remaining))+ raise DeviceFlowCancelled()++def _poll_device_token_generic(post: Callable[[], httpx.Response], *, expires_in: int, poll_interval: int,validate_success: Callable[[dict[str, Any]], None],on_non_json_error: Callable[[httpx.Response], Exception],on_error: Callable[[httpx.Response, dict[str, Any]], Exception],- on_timeout: Callable[[], Exception]) -> dict[str, Any]:+ on_timeout: Callable[[], Exception], cancelled: Optional[Callable[[], bool]] = None) -> dict[str, Any]:"""RFC 8628 device-code polling loop shared by the Nous and xAI flows.``authorization_pending`` sleeps and retries; ``slow_down`` grows the interval by 1s (cap 30s).@@ -331,13 +349,16 @@ def _poll_device_token_generic(real OAuth error), backs off — honoring ``Retry-After``, capped at 60s and at the device-codedeadline — instead of aborting a login the user may still be approving. Every other error, anon-JSON error body, and the deadline become provider-specific exceptions via the supplied- factories so each caller keeps its exact error contract.+ factories so each caller keeps its exact error contract. *cancelled* is checked before every+ request and during every wait; once it fires the poll raises :class:`DeviceFlowCancelled`."""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 untouchedunavailable = 0 # HTTP status of the latest edge/service failure; 0 once the endpoint answers againwhile time.monotonic() < deadline:+ if cancelled is not None and cancelled():+ raise DeviceFlowCancelled()response = post()if response.status_code == 200:payload = response.json()@@ -357,18 +378,18 @@ def _poll_device_token_generic(edge_backoff = min(max(current_interval, retry_after), 60)else:edge_backoff = min(max(edge_backoff * 2, current_interval * 2, 5), 60)- time.sleep(max(0.0, min(edge_backoff, deadline - time.monotonic())))+ _cancellable_sleep(max(0.0, min(edge_backoff, deadline - time.monotonic())), cancelled)continueresponse.raise_for_status()raise on_non_json_error(response)edge_backoff, unavailable = 0.0, 0error_code = str(error_payload.get("error") or "")if error_code == "authorization_pending":- time.sleep(current_interval)+ _cancellable_sleep(min(current_interval, max(0.0, deadline - time.monotonic())), cancelled)continueif error_code == "slow_down":current_interval = min(current_interval + 1, 30)- time.sleep(current_interval)+ _cancellable_sleep(current_interval, cancelled)continueraise on_error(response, error_payload)# Still failing when the code ran out: a service outage (``__cause__``), not a sign-in left unapproved.@@ -377,7 +398,7 @@ def _poll_device_token_generic(def _poll_for_token(client: httpx.Client, portal_base_url: str, client_id: str, device_code: str,- expires_in: int, poll_interval: int) -> dict[str, Any]:+ expires_in: int, poll_interval: int, cancelled: Optional[Callable[[], bool]] = None) -> dict[str, Any]:"""Poll the Nous token endpoint until the user approves or the code expires."""def _validate(payload: dict[str, Any]) -> None:if "access_token" not in payload:@@ -402,8 +423,9 @@ def _poll_for_token(on_non_json_error=lambda _r: RuntimeError("Token endpoint returned a non-JSON error response"),# Enriched at the SOURCE so the CLI login and the dashboard/desktop poller- # (web_server_oauth._nous_promotion_poller surfaces it to the UI) both inherit the guidance.- on_timeout=lambda: DeviceCodeExpired(_nous_device_auth_timeout_message(portal_base_url)))+ # (web_server_oauth._nous_sign_in_poller surfaces it to the UI) both inherit the guidance.+ on_timeout=lambda: DeviceCodeExpired(_nous_device_auth_timeout_message(portal_base_url)),+ cancelled=cancelled)def _prompt_yes_no(prompt: str, *, default: str) -> bool:diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.pyindex fe698a5bbcd..0493c516bd0 100644--- a/hermes_cli/auth_nous.py+++ b/hermes_cli/auth_nous.py@@ -25,7 +25,7 @@ from hermes_cli.auth_constants import (DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS, NOUS_AUTH_PATH_INVOKE_JWT, NOUS_BILLING_MANAGE_SCOPE,NOUS_DEVICE_CODE_SOURCE, NOUS_INFERENCE_INVOKE_SCOPE, NOUS_INVOKE_JWT_MIN_TTL_SECONDS,WELCOME_CLAIM_FLAG, _nous_err, httpx)-from hermes_cli.guest_handoff import drain, note_replacement+from hermes_cli.guest_handoff import deferred, drain, note_replacement, result_linesif TYPE_CHECKING: # annotation-only; the runtime import would be a cyclefrom hermes_cli.auth import ProviderConfig@@ -1501,6 +1501,8 @@ def step_up_nous_billing_scope(invalidate_cached_token()except Exception:logger.debug("Billing token cache invalidation failed", exc_info=True)+ from hermes_cli.anon_auth import settle_after_upgrade+ settle_after_upgrade(auth_state) # a step-up that replaced the free tier moves its config toogranted = auth_state.get("scope")return isinstance(granted, str) and NOUS_BILLING_MANAGE_SCOPE in granted.split()@@ -1653,13 +1655,18 @@ def _login_nous(args, pconfig: ProviderConfig) -> None:# model-picker "Skip (keep current)" can restore the user's previous provider.with _auth_store_lock():prior_active_provider = _load_auth_store().get("active_provider")- saved_to = _save_active_provider_state("nous", auth_state)- # Mirror to the shared store so other profiles can one-tap import (best-effort inside).- _write_shared_nous_state(auth_state)+ with deferred() as handoff: # a replaced free tier hands its apps over once both saves land+ saved_to = _save_active_provider_state("nous", auth_state)+ # Mirror to the shared store so other profiles can one-tap import (best-effort inside).+ _write_shared_nous_state(auth_state)_sync_nous_pool_from_auth_store()+ from hermes_cli.anon_auth import settle_after_upgrade+ settle_after_upgrade(auth_state) # a config left on the free tier's route moves to the accountprint()print("Login successful!")print(f" Auth state: {saved_to}")+ for line in (line for view in handoff.results for line in result_lines(view)):+ print(f" {line}")# Pick the model BEFORE writing the provider to config.yaml so config is never half-updated.selected_model = Nonetry:diff --git a/hermes_cli/guest_handoff.py b/hermes_cli/guest_handoff.pyindex 4f3ec2738f9..b8ff11fb02e 100644--- a/hermes_cli/guest_handoff.py+++ b/hermes_cli/guest_handoff.py@@ -198,27 +198,6 @@ def note_replacement(previous: Any, new: Any) -> None:_token_key(anon_token)[:8])-def note_promoted(anon_token: str, *, account_email: Optional[str]) -> None:- """The promotion sign-in (``anon_sign_in.run_sign_in``) already moved this identity's apps on the- service: record the handoff as done so the save that follows sends no claim."""- if not anon_token:- return- home = _home_key()-- def change(record: Optional[dict[str, Any]]) -> dict[str, Any]:- record = record or {"attempts": 0, "profiles": [], "created_at": _iso(_now())}- record.pop("anon_token", None)- record.update(state=CLAIMED, error=None, result={- # The promotion reports no list of what moved: neutral copy, not "nothing moved".- "account_email": account_email, "connectors_kind": "unknown", "moved_toolkits": [],- "dropped_toolkits": []})- if home not in record["profiles"]:- record["profiles"].append(home)- return record-- _update(_records_path(), _token_key(anon_token), change)--# --- The runner: outside every lock ---------------------------------------------------------------def _holds_auth_locks() -> bool:@@ -592,6 +571,17 @@ def handoff_status() -> dict[str, Any]:def status_lines(status: dict[str, Any]) -> list[str]:"""User copy for a non-idle handoff (``hermes auth status nous``)."""+ lines = result_lines(status)+ kind = status.get("connectors_kind")+ moved_some = kind in ("moved", "swapped") and status.get("moved_toolkits")+ if status.get("state") == CLAIMED and not moved_some and kind != "conflict":+ lines[0] = f"Signed in as {status.get('account_email') or 'your account'}. {lines[0]}"+ return lines+++def result_lines(status: dict[str, Any]) -> list[str]:+ """What a handoff did, for the line after "Signed in as ..." (every sign-in surface) and for+ :func:`status_lines`."""state = status.get("state")where = status.get("account_email") or "your account"moved, dropped = status.get("moved_toolkits") or [], status.get("dropped_toolkits") or []@@ -616,9 +606,9 @@ def status_lines(status: dict[str, Any]) -> list[str]:elif kind == "conflict":lines = [f"{where} already had its own apps, so the free-tier apps stayed behind."]elif kind in ("none", "moved", "swapped"):- lines = [f"Signed in as {where}. There were no free-tier apps to move."]+ lines = ["There were no free-tier apps to move."]else:- lines = [f"Signed in as {where}. Any free-tier apps are in this account now."]+ lines = ["Any free-tier apps are in this account now."]if dropped:lines.append(f"Reconnect in {where}: {', '.join(dropped)}.")return linesdiff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 8ed772442e7..abbe84699d4 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -285,11 +285,8 @@ def _model_flow_nous(config, current_model="", args=None):from hermes_cli.nous_subscription import prompt_enable_tool_gatewaystate = get_provider_auth_state("nous")from hermes_cli import anon_auth- if anon_auth.guest_without_free_tier(state):- # A guest that carries no inference here: signing in promotes it and keeps its connectors.- print(anon_auth.UPGRADE_HINT)- return- if not state or not state.get("access_token"):+ # A free tier with no inference here signs in like no account; its apps move to the account after.+ if not state or not state.get("access_token") or anon_auth.guest_without_free_tier(state):_say("Not logged into Nous Portal. Starting login...", "")def _login_then_offer_gateway(login_args, pconfig):diff --git a/hermes_cli/nous_subscription.py b/hermes_cli/nous_subscription.pyindex cab1231648d..9196d78f926 100644--- a/hermes_cli/nous_subscription.py+++ b/hermes_cli/nous_subscription.py@@ -708,17 +708,23 @@ def _run_nous_portal_login_only(*, capability: str) -> bool:auth_state = auth._try_import_shared_nous_state(timeout_seconds=15.0)if auth_state is None:auth_state = auth._nous_device_code_login()- with auth._auth_store_lock():- auth_store = auth._load_auth_store()- auth._save_provider_state(auth_store, "nous", auth_state)- if prior_active_provider:- auth_store["active_provider"] = prior_active_provider- else:- auth_store.pop("active_provider", None)- auth._save_auth_store(auth_store)- auth._write_shared_nous_state(auth_state)+ from hermes_cli.anon_auth import settle_after_upgrade+ from hermes_cli.guest_handoff import deferred, result_lines+ with deferred() as handoff: # a replaced free tier hands its apps over once both saves land+ with auth._auth_store_lock():+ auth_store = auth._load_auth_store()+ auth._save_provider_state(auth_store, "nous", auth_state)+ if prior_active_provider:+ auth_store["active_provider"] = prior_active_provider+ else:+ auth_store.pop("active_provider", None)+ auth._save_auth_store(auth_store)+ auth._write_shared_nous_state(auth_state)auth._sync_nous_pool_from_auth_store()+ settle_after_upgrade(auth_state) # a config left on the free tier's route moves to the accountprint(" Nous Portal login successful.")+ for line in (line for view in handoff.results for line in result_lines(view)):+ print(f" {line}")return Trueexcept KeyboardInterrupt:print("\n Login cancelled.")diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 5e9f22471d6..02ab67e9385 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -38,8 +38,7 @@ _OAUTH_PROVIDER_CATALOG = LateState("_OAUTH_PROVIDER_CATALOG", "hermes_cli.web_s# test's monkeypatch on web_server_oauth must win at spawn time, not router-import time.# A direct import here made those mocks no-ops — the real poller then hit the network# from the leaked thread and segfaulted a later test's collection (CI flake, 2026-09-09).-_nous_plain_poller = late("_nous_plain_poller", "hermes_cli.web_server_oauth")-_nous_promotion_poller = late("_nous_promotion_poller", "hermes_cli.web_server_oauth")+_nous_sign_in_poller = late("_nous_sign_in_poller", "hermes_cli.web_server_oauth")_minimax_poller = late("_minimax_poller", "hermes_cli.web_server_oauth")_xai_device_poller = late("_xai_device_poller", "hermes_cli.web_server_oauth")@@ -433,32 +432,17 @@ def _resolve_provider_status(provider_id: str, status_fn) -> dict[str, Any]:async def _start_nous_device_code(profile: Optional[str]) -> dict[str, Any]:- """Start a Nous sign-in. Over a free-tier identity (``nous.guest`` on) the whole sign-in is the- shared ``anon_auth.run_sign_in`` flow: this route creates the generator, pulls its first state- (the transfer's consent link and code) and hands that to the UI, then the poller drains the rest.- Without a free-tier identity it is the plain device-code flow."""+ """Start a Nous sign-in: the shared ``anon_auth.run_sign_in`` flow, the plain device-code login.+ This route creates the generator, pulls its first state (the device page link and code) and+ hands that to the UI, then the poller drains the rest. A free tier the account replaces hands+ its apps over after the save, inside the flow."""from hermes_cli import anon_auth- from hermes_cli.auth import PROVIDER_REGISTRY, _request_device_code- from hermes_cli.web_server_profiles import _config_profile_scope, _profile_scope+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.web_server_profiles import _config_profile_scopepconfig = PROVIDER_REGISTRY["nous"]portal_base_url = (os.getenv("HERMES_PORTAL_BASE_URL") or os.getenv("NOUS_PORTAL_BASE_URL") or pconfig.portal_base_url).rstrip("/")- with _profile_scope(_oauth_profile_name(profile)):- guest = anon_auth.current_nous_state() if anon_auth.guest_allowed() else None-- if not anon_auth.is_guest_state(guest):- device_data = await _httpx_call(lambda client: _request_device_code(- client=client, portal_base_url=portal_base_url, client_id=pconfig.client_id,- scope=pconfig.scope))- expires_in, interval = int(device_data["expires_in"]), int(device_data["interval"])- fields = dict(- device_code=str(device_data["device_code"]), portal_base_url=portal_base_url,- client_id=pconfig.client_id, scope=pconfig.scope,- interval=interval, expires_at=time.time() + expires_in)- return _device_session_started(- "nous", profile, _nous_plain_poller, fields, str(device_data["user_code"]),- str(device_data["verification_uri_complete"]), expires_in, interval)# The session is registered BEFORE the generator exists, so a cancel landing in the start# window is already visible to the flow's own cancel check and persist guard.@@ -481,9 +465,8 @@ async def _start_nous_device_code(profile: Optional[str]) -> dict[str, Any]:gen = anon_auth.run_sign_in(timeout_seconds=15.0,cancelled=_cancelled,- # A DELETE from this machine means "not here": nothing is persisted and the install- # re-mints a free tier on next use.- cancel_wins_after_promotion=True,+ # The desktop also connects another account over a signed-in one.+ replace_account=True,persist_guard=_persist_guard,# Config + auth store only, so the light contextvar scope -- never the skills-module one,# whose process-global lock would be held across the whole wait.@@ -496,7 +479,7 @@ async def _start_nous_device_code(profile: Optional[str]) -> dict[str, Any]:gen.close()_drop_oauth_session(sid)raise- if getattr(first, "kind", "") != "code": # already signed in, or the free tier is unavailable+ if getattr(first, "kind", "") != "code": # the store was unreadable or the code request failedwith contextlib.suppress(Exception):gen.close()_drop_oauth_session(sid)@@ -505,9 +488,9 @@ async def _start_nous_device_code(profile: Optional[str]) -> dict[str, Any]:# ``device_code`` stays present because other routes read it; the generator owns the real one.sess.update(dict(portal_base_url=portal_base_url, client_id=pconfig.client_id, scope=pconfig.scope,- device_code="", claim_code=first.code, interval=first.interval,+ device_code="", interval=first.interval,expires_at=time.time() + first.expires_in, _sign_in=gen))- _start_poller(_nous_promotion_poller, sid) # last: nothing observes `sess` before it is complete+ _start_poller(_nous_sign_in_poller, sid) # last: nothing observes `sess` before it is completereturn {"session_id": sid, "flow": "device_code", "user_code": first.code,"verification_url": first.link, "expires_in": first.expires_in,@@ -886,10 +869,12 @@ async def poll_oauth_session(provider_id: str, session_id: str, profile: Optionareturn {"session_id": session_id, "status": sess["status"],"error_message": sess.get("error_message"), "expires_at": sess.get("expires_at"),- # Nous over a free-tier identity: why a transfer ended, who signed in, and the default model- # the completion settled on (None when the config was on the user's own model).+ # Nous: why a sign-in ended, who signed in, and the default model the completion settled on+ # (None when the config was on the user's own model)."reason": sess.get("reason"), "account_email": sess.get("account_email"), "model": sess.get("model"),- # Failed sign-ins over a free-tier identity: can a later attempt succeed, and after how long.+ # What the replaced free tier's handoff did: one user-facing line each (moved, reconnect).+ "handoff": sess.get("handoff"),+ # Failed Nous sign-ins: can a later attempt succeed, and after how long."retryable": sess.get("retryable"), "retry_after": sess.get("retry_after"),}diff --git a/hermes_cli/web_server_oauth.py b/hermes_cli/web_server_oauth.pyindex 783eaaf9f51..8454417a705 100644--- a/hermes_cli/web_server_oauth.py+++ b/hermes_cli/web_server_oauth.py@@ -233,51 +233,31 @@ def _record_sign_in_state(sess: dict[str, Any], state: Any) -> None:sess["account_email"] = state.email or None# None when the config was left on the user's own model, as the poll route documents.sess["model"] = state.model if state.model_changed else None+ # What the free tier's handoff did (moved apps, apps to reconnect); empty without one.+ sess["handoff"] = list(state.handoff)return- if kind == "declined":- sess["status"], sess["reason"] = "denied", "user_declined"- sess["error_message"] = state.copy+ if kind == "cancelled":+ sess["status"] = "cancelled"returnif kind == "timed_out":sess["status"], sess["reason"] = "error", "timeout"# The enriched device-auth guidance, which the dashboard has room for.sess["error_message"] = state.detail or state.copyreturn- if kind == "retired":- sess["status"], sess["reason"] = "error", "account_retired"- sess["error_message"] = state.copy- return- if kind == "superseded":- # Two producers, two screens: the user's own DELETE is a cancellation, while a sign-in- # started somewhere else (a chat, the terminal) voided this code and is an error the- # renderer has a dedicated screen for.- if sess.get("cancelled"):- sess["status"] = "cancelled"- else:- sess["status"], sess["reason"] = "error", "superseded"- sess["error_message"] = state.copy- return- if kind == "failed":- sess["status"] = "error"- sess["reason"] = state.reason or "error"- sess["error_message"] = state.copy # the chat form: no raw exception reaches the UI- # Whether a later attempt can succeed, and the wait the service named (seconds).- sess["retryable"] = bool(getattr(state, "retryable", False))- sess["retry_after"] = int(getattr(state, "retry_after", 0) or 0)- return- # already_signed_in / unavailable: the start route refuses these, so this is unreachable- # through the dashboard; record rather than crash.sess["status"] = "error"- sess["reason"] = kind or "error"- sess["error_message"] = state.copy+ sess["reason"] = getattr(state, "reason", "") or kind or "error"+ sess["error_message"] = state.copy # the chat form: no raw exception reaches the UI+ # Whether a later attempt can succeed, and the wait the service named (seconds).+ sess["retryable"] = bool(getattr(state, "retryable", False))+ sess["retry_after"] = int(getattr(state, "retry_after", 0) or 0)@_oauth_poller("nous")-def _nous_promotion_poller(session_id: str, sess: dict[str, Any]) -> None:- """Drain the sign-in the start route began: one shared flow, rendered onto the session.+def _nous_sign_in_poller(session_id: str, sess: dict[str, Any]) -> None:+ """Drain the sign-in the start route began: the one shared flow, rendered onto the session.The generator was created and advanced to its ``Code`` state by ``_start_nous_device_code``, so- it is already holding the transfer's codes and its HTTP client. Nothing here is wrapped in+ it is already holding the device code and its HTTP client. Nothing here is wrapped in``_profile_scope``: that context manager holds a process-global lock and swaps moduleattributes across its ``yield``, and this loop can last the sign-in code's whole expiry. Thegenerator scopes its own short config/auth-store sections instead.@@ -293,73 +273,6 @@ def _nous_promotion_poller(session_id: str, sess: dict[str, Any]) -> None:gen.close() # unwinds the suspended HTTP client if we leave early-@_oauth_poller("nous")-def _nous_plain_poller(session_id: str, sess: dict[str, Any]) -> None:- """Background poller for a plain Nous device-code login (no free-tier identity to transfer).-- A sign-in that carries the free tier's connectors runs through ``anon_auth.run_sign_in`` and- ``_nous_promotion_poller`` instead; this is the "connect another Nous account" path.- """- from hermes_cli.web_server_profiles import _profile_scope- from hermes_cli.auth import _poll_for_token, persist_nous_credentials, refresh_nous_oauth_from_state- from hermes_cli import anon_auth, guest_handoff- import httpx- portal_base_url, client_id = sess["portal_base_url"], sess["client_id"]-- def _cancelled() -> bool:- # The user abandoned this sign-in (DELETE /sessions/{id}) while this thread was blocked- # on the portal: nothing it learns afterwards may reach the auth store.- with _oauth_sessions_lock:- if sess.get("cancelled"):- sess["status"] = "cancelled"- return True- return False-- with httpx.Client(timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}) as client:- token_data = _poll_for_token(- client=client, portal_base_url=portal_base_url, client_id=client_id,- device_code=sess["device_code"], expires_in=max(60, int(sess["expires_at"] - time.time())),- poll_interval=sess["interval"],- )- if _cancelled():- return- # Same post-processing as _nous_device_code_login (validate/refresh JWT)- now = datetime.now(UTC)- token_ttl = int(token_data.get("expires_in") or 0)- auth_state = {- "portal_base_url": portal_base_url,- "inference_base_url": token_data.get("inference_base_url"),- "client_id": client_id,- "scope": token_data.get("scope") or sess.get("scope"),- "token_type": token_data.get("token_type", "Bearer"),- "access_token": token_data["access_token"],- "refresh_token": token_data.get("refresh_token"),- "obtained_at": now.isoformat(),- "expires_at": (- datetime.fromtimestamp(now.timestamp() + token_ttl, tz=UTC).isoformat()- if token_ttl else None- ),- "expires_in": token_ttl,- }- # The profile comes from the poller's own session dict: a cancel or the 15-minute sweep drops- # the registry entry, and a lookup by id would then save into the dashboard's launch profile.- with _profile_scope(sess.get("profile")):- full_state = refresh_nous_oauth_from_state(auth_state, timeout_seconds=15.0, force_refresh=False)- # The final cancellation check and the save share the session lock, so a cancel cannot- # land between them. The guest handoff runs after that lock is released.- with guest_handoff.deferred() as handoff:- with _oauth_sessions_lock:- if sess.get("cancelled"):- sess["status"] = "cancelled"- return- persist_nous_credentials(full_state)- # A config left on the free tier's route by a retired identity still has to move.- settled = anon_auth.settle_after_upgrade(full_state)- with _oauth_sessions_lock:- sess["account_email"] = handoff.account_email- sess["model"] = settled.get("model") or None--@_oauth_poller("minimax")def _minimax_poller(session_id: str, sess: dict[str, Any]) -> None:"""MiniMax poller: PKCE-style ``code_verifier`` + ``user_code`` instead of Nous'sdiff --git a/tests/agent/test_retry_delay_parsers_shared.py b/tests/agent/test_retry_delay_parsers_shared.pyindex d3ea34d3691..e5bf3321813 100644--- a/tests/agent/test_retry_delay_parsers_shared.py+++ b/tests/agent/test_retry_delay_parsers_shared.py@@ -19,20 +19,16 @@ def _http_date(seconds_ahead: int) -> str:class TestRetryAfterHeaderOneParser:def test_http_date_header_parsed_identically_at_formerly_divergent_sites(self):- """anon_auth, the error-context extractor and nous_rate_guard used to float() the header- and silently drop the RFC 7231 date form; all three must now agree with the canonical."""+ """The error-context extractor and nous_rate_guard used to float() the header and silently+ drop the RFC 7231 date form; both must now agree with the canonical."""from agent.agent_runtime_helpers import extract_api_error_contextfrom agent.nous_rate_guard import _parse_reset_seconds- from hermes_cli.anon_auth import _retry_after_seconds as anon_retry_afterimport timeheader = _http_date(90)canonical = parse_retry_after_seconds(header)assert 85 <= canonical <= 90- anon = anon_retry_after(SimpleNamespace(headers={"Retry-After": header}), default=1.0)- assert abs(anon - canonical) < 2-guard = _parse_reset_seconds({"Retry-After": header})assert guard is not None and abs(guard - canonical) < 2diff --git a/tests/gateway/test_login_command.py b/tests/gateway/test_login_command.pyindex 52343e07411..063386de46b 100644--- a/tests/gateway/test_login_command.py+++ b/tests/gateway/test_login_command.py@@ -87,7 +87,7 @@ async def test_broadcast_shaped_platforms_are_refused(monkeypatch, platform):@pytest.mark.asyncioasync def test_a_private_chat_type_is_accepted(monkeypatch):runner = _runner(monkeypatch)- monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter([anon_auth.Declined()]))+ monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter([anon_auth.TimedOut()]))assert await runner._handle_login_command(_event(chat_type="private")) == anon_auth.UPGRADE_STARTassert "login" in runner._login_attempts@@ -100,7 +100,7 @@ async def test_a_dm_posts_the_code_as_three_messages_then_the_terminal_copy(monkstates = [anon_auth.Code("https://example.test/sign-in", "CODE-1", 900, 5),anon_auth.Waiting(),- anon_auth.Declined(),+ anon_auth.TimedOut(),]monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter(states))@@ -111,7 +111,7 @@ async def test_a_dm_posts_the_code_as_three_messages_then_the_terminal_copy(monk# URL and code arrive as their own messages (copyable), then one waiting notice, then the outcome.assert len(notices) == 4assert notices[:2] == ["https://example.test/sign-in", "CODE-1"]- assert notices[-1] == anon_auth.Declined().copy+ assert notices[-1] == anon_auth.TimedOut().copy@pytest.mark.asyncio@@ -122,7 +122,7 @@ async def test_the_start_ack_arrives_before_the_flow_is_advanced(monkeypatch):def flow(**_kwargs):nonlocal advancedadvanced = True- yield anon_auth.Declined()+ yield anon_auth.TimedOut()monkeypatch.setattr(anon_auth, "run_sign_in", flow)@@ -133,12 +133,10 @@ async def test_the_start_ack_arrives_before_the_flow_is_advanced(monkeypatch):@pytest.mark.asyncio@pytest.mark.parametrize("state", [- anon_auth.Declined(),- anon_auth.Superseded(),+ anon_auth.Cancelled(),anon_auth.TimedOut(),- anon_auth.Retired(),- anon_auth.Failed("account_busy"),- anon_auth.Unavailable(),+ anon_auth.Failed(anon_auth.ANON_UNREACHABLE),+ anon_auth.Failed(),])async def test_each_terminal_outcome_is_pushed_to_the_same_dm(monkeypatch, state):runner = _runner(monkeypatch)@@ -179,15 +177,15 @@ async def test_a_failed_code_push_does_not_abort_the_drain(monkeypatch):runner._deliver_platform_notice = delivermonkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter([anon_auth.Code("https://example.test/sign-in", "CODE-1", 45, 5),- anon_auth.Completed(email="[email protected]", model="model-1", model_changed=True),+ anon_auth.Completed(email="[email protected]", model="model-1", model_changed=True,+ handoff=("Your apps moved to [email protected]: gmail.",)),]))await runner._handle_login_command(_event())await _finish_tasks(runner)assert len(delivered) == 4- assert delivered[-1] == anon_auth.Completed(- email="[email protected]", model="model-1", model_changed=True).copy+ assert "Your apps moved to [email protected]: gmail." in delivered[-1]@pytest.mark.asyncio@@ -234,7 +232,7 @@ async def test_a_second_login_from_the_same_identity_supersedes_the_first(monkeydef flow(**kwargs):seen.append(kwargs)yield anon_auth.Code("https://example.test/sign-in", "CODE", 60, 1)- yield anon_auth.Superseded() if kwargs["cancelled"]() else anon_auth.Declined()+ yield anon_auth.Cancelled() if kwargs["cancelled"]() else anon_auth.TimedOut()monkeypatch.setattr(anon_auth, "run_sign_in", flow)await runner._handle_login_command(_event())@@ -244,10 +242,9 @@ async def test_a_second_login_from_the_same_identity_supersedes_the_first(monkeyassert first.cancelled is Trueassert runner._login_attempts["login"] is not firstawait _finish_tasks(runner)- assert seen[0]["cancel_wins_after_promotion"] is False- # The replaced attempt tells its own DM why its code stopped working.+ # The replaced attempt tells its own DM that its code stopped working.assert any(- pushed.args[0] is first.source and pushed.args[1] == anon_auth.Superseded().copy+ pushed.args[0] is first.source and pushed.args[1] == anon_auth.Cancelled().copyfor pushed in runner._deliver_platform_notice.await_args_list)@@ -261,9 +258,8 @@ async def test_a_superseded_attempt_that_already_completed_still_pushes_its_compdef flow(**kwargs):seen.append(kwargs)yield anon_auth.Code("https://example.test/sign-in", "CODE", 60, 1)- # The user approved this attempt in the browser before it lost the race, so the grant is- # already spent and the flow completes anyway (S-2b, S-10).- yield completed if kwargs["cancelled"]() else anon_auth.Declined()+ # This attempt saved the account before the replacement's cancel reached it.+ yield completed if kwargs["cancelled"]() else anon_auth.TimedOut()monkeypatch.setattr(anon_auth, "run_sign_in", flow)await runner._handle_login_command(_event())@@ -272,7 +268,6 @@ async def test_a_superseded_attempt_that_already_completed_still_pushes_its_compassert runner._login_attempts["login"] is not firstawait _finish_tasks(runner)- assert seen[0]["cancel_wins_after_promotion"] is Falseassert any(pushed.args[0] is first.source and pushed.args[1] == completed.copyfor pushed in runner._deliver_platform_notice.await_args_list)@@ -292,7 +287,7 @@ async def test_a_replacement_reaches_a_poll_running_on_the_private_executor(monkpolling.set()while not kwargs["cancelled"]():time.sleep(0.01)- yield anon_auth.Superseded()+ yield anon_auth.Cancelled()monkeypatch.setattr(anon_auth, "run_sign_in", flow)await runner._handle_login_command(_event())@@ -500,7 +495,7 @@ async def test_shutdown_cancellation_marks_the_attempt_cancelled(monkeypatch):async def test_the_drain_never_touches_the_shared_executor(monkeypatch):runner = _runner(monkeypatch)runner._get_executor = MagicMock(side_effect=AssertionError("shared executor used"))- monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter([anon_auth.Declined()]))+ monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter([anon_auth.TimedOut()]))del runner.__dict__["_run_login_blocking"]await runner._run_login(SimpleNamespace(@@ -537,7 +532,7 @@ async def test_a_local_session_gets_the_sign_in_code_on_its_event_stream(monkeyppublish=lambda sid, payload, event_type: published.append((sid, event_type, payload["text"]))))authority = SimpleNamespace(sessions={"local-1": live})monkeypatch.setattr(session_authorities, "active_authority", lambda _runner: authority)- states = [anon_auth.Code("https://example.test/sign-in", "CODE-1", 900, 5), anon_auth.Declined()]+ states = [anon_auth.Code("https://example.test/sign-in", "CODE-1", 900, 5), anon_auth.TimedOut()]monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: iter(states))event = SimpleNamespace(source=_source(platform=Platform.LOCAL, chat_id="local-1"))@@ -546,5 +541,48 @@ async def test_a_local_session_gets_the_sign_in_code_on_its_event_stream(monkeypassert [(sid, kind) for sid, kind, _ in published] == [("local-1", "notification.show")] * 4assert [text for *_, text in published][:2] == ["https://example.test/sign-in", "CODE-1"]- assert published[-1][2] == anon_auth.Declined().copy+ assert published[-1][2] == anon_auth.TimedOut().copyrunner._deliver_platform_notice.assert_not_awaited()+++async def test_a_replacing_login_never_lands_between_the_final_check_and_the_save(monkeypatch):+ runner = _runner(monkeypatch)+ seen = []++ def flow(**kwargs):+ seen.append(kwargs)+ yield anon_auth.TimedOut()++ monkeypatch.setattr(anon_auth, "run_sign_in", flow)+ await runner._handle_login_command(_event())+ attempt = runner._login_attempts["login"]+ await _finish_tasks(runner)+ lock, attempts = runner._login_registry()+ with lock:+ attempts["login"] = attempt # the attempt is still live while its save runs+ guard = seen[0]["persist_guard"]+ with guard() as may_persist:+ # The save runs without the registry lock (the event loop takes it), and a replacing+ # /login while it runs is told a sign-in is finishing instead of cancelling a done deal.+ assert may_persist is True and not lock.locked()+ assert await runner._handle_login_command(_event()) == anon_auth.LOGIN_BUSY_ELSEWHERE+ assert attempt.cancelled is False+++async def test_a_cancelled_attempt_never_claims_the_save(monkeypatch):+ runner = _runner(monkeypatch)+ seen = []++ def flow(**kwargs):+ seen.append(kwargs)+ yield anon_auth.TimedOut()++ monkeypatch.setattr(anon_auth, "run_sign_in", flow)+ await runner._handle_login_command(_event())+ attempt = runner._login_attempts["login"]+ await _finish_tasks(runner)+ attempt.cancelled = True+ with seen[0]["persist_guard"]() as may_persist:+ assert may_persist is Falsediff --git a/tests/hermes_cli/test_anon_desktop_signin.py b/tests/hermes_cli/test_anon_desktop_signin.pyindex e7c6c4a5888..63502bc5ef9 100644--- a/tests/hermes_cli/test_anon_desktop_signin.py+++ b/tests/hermes_cli/test_anon_desktop_signin.py@@ -1,9 +1,9 @@-"""Desktop (dashboard API) sign-in over a Nous free-tier identity.+"""Desktop (dashboard API) Nous sign-in: the plain device-code login, then the free tier's handoff.-``POST /api/providers/oauth/nous/start`` registers the connector transfer with the account service-and hands the renderer the transfer's code and consent URL; the poller waits for the transfer, then-takes the token grant, persists the account, and settles the default model. Driven through the real-FastAPI routes against a fake account service (the same fake ``hermes auth upgrade`` is tested with).+``POST /api/providers/oauth/nous/start`` hands the renderer the device page and code; the poller+takes the token grant, persists the account, moves a replaced free tier's apps, and settles the+default model. Driven through the real FastAPI routes against a fake portal (the same fake+``hermes auth upgrade`` is tested with)."""from __future__ import annotations@@ -36,23 +36,22 @@ def _wait_for_terminal(session_id: str, timeout: float = 10.0) -> dict:pytest.fail("poller never left pending")-def test_start_registers_the_transfer_and_completion_settles_the_account(portal, free_account):+def test_start_shows_the_device_code_and_completion_reports_what_moved(portal, free_account):anon_auth.ensure_portal_identity(explicit=True)_write_model_config({"provider": "nous", "default": anon_auth.GUEST_MODEL, "base_url": WELCOME})resp = client.post("/api/providers/oauth/nous/start", headers=HEADERS)assert resp.status_code == 200, resp.textstart = resp.json()- # The renderer shows the transfer's code and consent page, not the generic device page.- assert start["user_code"] == "clm_1"- assert start["verification_url"] == f"{PORTAL}/device"- assert portal.intent_bodies[0]["user_code"] == portal.user_code- assert portal.intent_bodies[0]["device_code"] == portal.device_code+ assert start["user_code"] == portal.user_code+ assert start["verification_url"] == f"{PORTAL}/device?user_code={portal.user_code}"body = _wait_for_terminal(start["session_id"])assert body["status"] == "approved"assert body["account_email"] == EMAILassert body["model"] == FREE_PICK+ assert body["handoff"] == [f"Your apps moved to {EMAIL}: gmail."]+ assert not [p for _, p in portal.calls if "promotion" in p]state = _load_auth_store()["providers"]["nous"]assert "anon_token" not in state and not anon_auth.is_guest_state(state)model_cfg = _model_config()@@ -61,16 +60,14 @@ def test_start_registers_the_transfer_and_completion_settles_the_account(portal,assert not anon_auth.route_is_welcome_host(model_cfg["base_url"])-def test_a_transfer_the_user_declined_is_reported_with_its_reason_and_keeps_the_free_tier(portal, free_account):+def test_an_expired_code_reports_the_timeout_reason_and_keeps_the_free_tier(portal):guest = anon_auth.ensure_portal_identity(explicit=True)- portal.status_sequence = [{"status": "voided", "reason": "user_declined"}]+ portal.token_pending, portal.expires_in = True, 1start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()body = _wait_for_terminal(start["session_id"])- assert body["status"] == "denied"- assert body["reason"] == "user_declined"- assert body["error_message"] == anon_auth.UPGRADE_REASON_COPY["user_declined"]- assert portal.token_grants == 0+ assert body["status"] == "error"+ assert body["reason"] == "timeout"assert _load_auth_store()["providers"]["nous"]["anon_token"] == guest["anon_token"]@@ -93,26 +90,21 @@ def test_a_connector_only_guest_is_not_reported_as_the_free_tier(portal, monkeypassert not nous["status"].get("free_tier")-def test_a_sign_in_cancelled_while_waiting_never_persists_the_account(portal, free_account, monkeypatch):- """The poller is blocked on the transfer when the user cancels; when the wait returns completed,- nothing may reach the auth store."""+def test_a_sign_in_cancelled_while_waiting_stops_the_token_poll_and_persists_nothing(portal, free_account):+ """The poller is blocked on the token endpoint when the user cancels: the poll stops, and+ nothing reaches the auth store."""import threadingfrom hermes_cli import web_server_oauthguest = anon_auth.ensure_portal_identity(explicit=True)- release = threading.Event()-- def _wait_until_released(client, portal_base_url, claim_code, *, expires_in, interval, cancelled=None):- release.wait(10)- return {"status": "completed", "user_id": "nas_user:9", "account_email": EMAIL}- monkeypatch.setattr(anon_auth, "wait_for_promotion", _wait_until_released)+ portal.token_pending = Truethreads_before = set(threading.enumerate())start = client.post("/api/providers/oauth/nous/start", headers=HEADERS).json()assert client.delete(f"/api/providers/oauth/sessions/{start['session_id']}", headers=HEADERS).json()["ok"] is True- release.set()- # Let the poller finish whatever it does with the "completed" result before asserting.for t in set(threading.enumerate()) - threads_before:t.join(timeout=5)+ assert not t.is_alive()+ portal.token_pending = Falseassert portal.token_grants == 0state = _load_auth_store()["providers"]["nous"]assert state["anon_token"] == guest["anon_token"] and anon_auth.is_guest_state(state)diff --git a/tests/hermes_cli/test_anon_failure_modes.py b/tests/hermes_cli/test_anon_failure_modes.pyindex 923cfa13a18..e81daa726e1 100644--- a/tests/hermes_cli/test_anon_failure_modes.py+++ b/tests/hermes_cli/test_anon_failure_modes.py@@ -252,10 +252,6 @@ class TestSignInFailures:assert state.reason == "" and state.copy == anon_sign_in.UPGRADE_NOT_COMPLETEDassert "bad CA bundle" in state.copy_terminal- def test_account_busy_is_retryable(self):- state = anon_sign_in.Failed(reason="account_busy")- assert state.retryable is True and "few seconds" in state.copy-# --- The dev-only host override ------------------------------------------------------------------diff --git a/tests/hermes_cli/test_anon_sign_in_flow.py b/tests/hermes_cli/test_anon_sign_in_flow.pyindex 8392ed139eb..774d108377f 100644--- a/tests/hermes_cli/test_anon_sign_in_flow.py+++ b/tests/hermes_cli/test_anon_sign_in_flow.py@@ -1,41 +1,40 @@-"""``anon_auth.run_sign_in``: the one sign-in composition every surface renders.+"""``anon_auth.run_sign_in``: the one plain device-code sign-in every surface renders.-Driven directly against the same fake account service ``hermes auth upgrade`` is tested with, so the-states, the persistence rules and the cancellation rules are exercised on the real wire rather than-mocked away. Each test asserts a single ruled property of the flow.+Driven directly against the same fake portal ``hermes auth upgrade`` is tested with, so the states,+the persistence rules, the cancel rules and the free tier's handoff are exercised on the real wire+rather than mocked away. Each test asserts a single ruled property of the flow."""from __future__ import annotations+import contextlib+import sslimport threadingimport timeimport pytest-from hermes_cli import anon_auth-from hermes_cli.auth import _auth_file_path+from hermes_cli import anon_auth, auth_device_flow+from hermes_cli.auth import _auth_file_path, _load_auth_storefrom tests.hermes_cli.test_anon_upgrade import (- EMAIL, FREE_PICK, PORTAL, WELCOME, _shared_store, _write_model_config, free_account, portal)+ EMAIL, FREE_PICK, PORTAL, WELCOME, _write_model_config, free_account, portal)__all__ = ["free_account", "portal"]+def _drain(**kwargs):"""Run a sign-in to its end and return every state it yielded."""return list(anon_auth.run_sign_in(**kwargs))+def _seed_free_tier() -> dict:return anon_auth.ensure_portal_identity(explicit=True)-def _stub_wait(monkeypatch, outcome, *, before=None):- """Replace the promotion wait with one that returns *outcome* (running *before* first)."""- def _wait(client, portal_base_url, claim_code, *, expires_in, interval, cancelled=None):- if before is not None:- before()- return dict(outcome)- monkeypatch.setattr(anon_auth, "wait_for_promotion", _wait)-def _voided(reason: str) -> dict:- return {"status": "voided", "reason": reason}+def _auth_bytes() -> bytes:+ path = _auth_file_path()+ return path.read_bytes() if path.exists() else b""+def test_a_completed_sign_in_yields_code_waiting_then_completed(portal, free_account):_seed_free_tier()@@ -45,131 +44,130 @@ def test_a_completed_sign_in_yields_code_waiting_then_completed(portal, free_accassert [s.kind for s in states] == ["code", "waiting", "completed"]code, completed = states[0], states[-1]- assert code.link.startswith(PORTAL)- assert code.code == "clm_1"+ assert code.link == f"{PORTAL}/device?user_code={portal.user_code}"+ assert code.code == portal.user_codeassert completed.email == EMAILassert completed.model == FREE_PICKassert completed.model_changed is True-def test_declined_yields_declined_and_persists_nothing(portal, tmp_path):++def test_no_surface_calls_the_promotion_endpoints(portal, free_account):_seed_free_tier()- before = _auth_file_path().read_bytes()- shared_before = _shared_store(tmp_path)- portal.status_sequence = [_voided("user_declined")]- terminal = [s for s in _drain() if s.terminal]+ _drain()++ assert not [p for _, p in portal.calls if "promotion" in p]- assert len(terminal) == 1- assert terminal[0].kind == "declined"- assert terminal[0].copy == anon_auth.UPGRADE_REASON_COPY["user_declined"]- assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before- assert _shared_store(tmp_path) == shared_before-def test_a_timeout_yields_timed_out_and_keeps_the_enriched_detail(portal, monkeypatch):+def test_the_email_comes_from_the_access_token_not_the_claim_answer(portal, free_account):_seed_free_tier()- _stub_wait(monkeypatch, {"status": "timeout"})+ portal.claim_reply = {**portal.claim_reply, "account_email": "[email protected]"}- state = _drain()[-1]- assert state.kind == "timed_out"- assert state.copy == anon_auth.UPGRADE_TIMED_OUT- assert portal.token_grants == 0+ assert _drain()[-1].email == EMAIL- # The token poll can time out too, and its guidance is enriched at the source.- from hermes_cli import auth_device_flow- enriched = auth_device_flow._nous_device_auth_timeout_message(PORTAL)- _stub_wait(monkeypatch, {"status": "completed", "account_email": EMAIL})- def _timeout(**kwargs):- raise TimeoutError(enriched)- monkeypatch.setattr(auth_device_flow, "_poll_for_token", _timeout)+def test_the_handoff_result_rides_the_completed_state(portal, free_account):+ _seed_free_tier()+ portal.claim_reply = {**portal.claim_reply, "connectors": {+ "kind": "moved", "moved_toolkits": ["gmail"], "dropped_toolkits": ["slack"]}}- state = _drain()[-1]- assert state.kind == "timed_out"- assert state.detail == enriched- assert state.copy == anon_auth.UPGRADE_TIMED_OUT- assert portal.token_grants == 0+ completed = _drain()[-1]-def test_a_retired_identity_yields_retired_and_clears_the_free_tier(portal, monkeypatch):- guest = _seed_free_tier()- cleared = []- real_clear = anon_auth.clear_dead_guest+ assert completed.handoff == (f"Your apps moved to {EMAIL}: gmail.", f"Reconnect in {EMAIL}: slack.")+ assert completed.copy.splitlines()[:3] == [f"Signed in as {EMAIL}.", *completed.handoff]- def _spy(reason, *, dead_token=None):- cleared.append((reason, dead_token))- real_clear(reason, dead_token=dead_token)- monkeypatch.setattr(anon_auth, "clear_dead_guest", _spy)- portal.status_sequence = [_voided("account_not_anonymous")]- state = _drain()[-1]+def test_no_identity_on_disk_signs_in_without_minting_or_claiming(portal, free_account, monkeypatch):+ monkeypatch.setattr(anon_auth, "mint_guest",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("run_sign_in must not mint")))++ states = _drain()- assert state.kind == "retired"- assert state.copy == anon_auth.UPGRADE_REASON_COPY["account_retired"]- assert cleared == [("retired", guest["anon_token"])]- from hermes_cli.auth import _load_auth_store- assert "nous" not in _load_auth_store().get("providers", {})+ assert states[-1].kind == "completed" and states[-1].handoff == ()+ assert portal.claims == []+ assert not anon_auth.is_guest_state(_load_auth_store()["providers"]["nous"])-def test_a_server_superseded_outcome_yields_superseded(portal, tmp_path):++def test_an_expired_code_yields_timed_out_and_keeps_the_enriched_detail(portal):_seed_free_tier()- before = _auth_file_path().read_bytes()- portal.status_sequence = [_voided("superseded")]+ before = _auth_bytes()+ portal.token_pending, portal.expires_in = True, 1state = _drain()[-1]- assert state.kind == "superseded"- assert state.copy == anon_auth.UPGRADE_REASON_COPY["superseded"]+ assert state.kind == "timed_out"+ assert state.copy == anon_auth.UPGRADE_TIMED_OUT+ assert state.detail == auth_device_flow._nous_device_auth_timeout_message(PORTAL)assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before+ assert _auth_bytes() == before+-def test_a_retired_identity_yields_retired_even_when_cleanup_fails(portal, monkeypatch):+def test_an_expired_token_answer_yields_timed_out(portal):_seed_free_tier()+ portal.token_error = "expired_token"- def _retired(*args, **kwargs):- raise anon_auth.AnonCredentialDead("retired")+ state = _drain()[-1]- def _read_only(*args, **kwargs):- raise OSError("read-only store")+ assert state.kind == "timed_out" and state.copy == anon_auth.UPGRADE_TIMED_OUT+ assert portal.token_grants == 0- monkeypatch.setattr(anon_auth, "register_promotion_intent", _retired)- monkeypatch.setattr(anon_auth, "clear_dead_guest", _read_only)- states = _drain()+def test_the_portal_override_is_read_inside_the_profile_scope(portal, free_account, monkeypatch):+ in_scope = []- assert [s.kind for s in states] == ["retired"]+ @contextlib.contextmanager+ def _scope():+ in_scope.append(True)+ try:+ yield None+ finally:+ in_scope.pop()- "reason,expected",- [("account_busy", anon_auth.UPGRADE_REASON_COPY["account_busy"]),- ("wat", anon_auth.UPGRADE_NOT_COMPLETED)])-def test_an_unknown_reason_yields_failed_with_the_generic_copy(portal, reason, expected):- _seed_free_tier()- portal.status_sequence = [_voided(reason)]+ from hermes_cli import auth_nous+ reads = []+ real_override = auth_nous._nous_portal_env_override+ monkeypatch.setattr(auth_nous, "_nous_portal_env_override",+ lambda: (reads.append(bool(in_scope)), real_override())[1])- state = _drain()[-1]+ assert _drain(scope=_scope)[-1].kind == "completed"+ assert reads and all(reads[:1])- assert state.kind == "failed"- assert state.copy == expected-def test_a_transport_error_yields_failed_without_leaking_the_detail_into_chat_copy(- portal, monkeypatch, tmp_path):+def test_the_portal_override_wins_over_a_saved_portal(portal, monkeypatch):+ guest = _seed_free_tier()+ from hermes_cli.auth import _save_auth_store, _save_provider_state+ store = _load_auth_store()+ _save_provider_state(store, "nous", {**guest, "portal_base_url": "https://portal.nousresearch.com"})+ _save_auth_store(store)+ asked = []++ def _record(client, portal_base_url, client_id, scope):+ asked.append(portal_base_url)+ raise RuntimeError("stop after the code request")+ monkeypatch.setattr(auth_device_flow, "_request_device_code", _record)++ _drain()++ assert asked == [PORTAL]+++def test_a_transport_error_yields_failed_without_leaking_the_detail_into_chat_copy(portal, monkeypatch):_seed_free_tier()- before = _auth_file_path().read_bytes()- detail = "boom at https://portal.example.test/api/anonymous/promotion-intent"+ before = _auth_bytes()+ detail = "boom at https://portal.example.test/api/oauth/device/code"def _boom(*a, **kw):raise RuntimeError(detail)- monkeypatch.setattr(anon_auth, "register_promotion_intent", _boom)+ monkeypatch.setattr(auth_device_flow, "_request_device_code", _boom)state = _drain()[-1]assert state.kind == "failed"assert state.copy == anon_auth.UPGRADE_NOT_COMPLETED- lowered = state.copy.lower()- for banned in ("http://", "https://", "/anonymous/", "anonymous"):- assert banned not in lowered+ assert "https://" not in state.copy.lower()assert detail in state.copy_terminal- assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before+ assert _auth_bytes() == before+def test_a_persist_failure_yields_failed_rather_than_raising(portal, free_account, monkeypatch):_seed_free_tier()@@ -186,6 +184,7 @@ def test_a_persist_failure_yields_failed_rather_than_raising(portal, free_accounassert "read-only home" in states[-1].copy_terminalassert settles == []+def test_a_settle_failure_yields_failed_rather_than_raising(portal, free_account, monkeypatch):_seed_free_tier()persists = []@@ -205,8 +204,9 @@ def test_a_settle_failure_yields_failed_rather_than_raising(portal, free_accountassert "config is read-only" in states[-1].copy_terminalassert len(persists) == 1-def test_already_signed_in_short_circuits_before_any_network(portal):- from hermes_cli.auth import _load_auth_store, _save_auth_store, _save_provider_state++def test_already_signed_in_short_circuits_before_any_network_unless_replacing(portal):+ from hermes_cli.auth import _save_auth_store, _save_provider_statestore = _load_auth_store()_save_provider_state(store, "nous", {"auth_method": "oauth_device_code", "access_token": "x"})_save_auth_store(store)@@ -215,145 +215,69 @@ def test_already_signed_in_short_circuits_before_any_network(portal):states = _drain()assert [s.kind for s in states] == ["already_signed_in"]- assert states[0].ok is True- assert states[0].precondition is True- assert portal.calls == []--def test_guests_switched_off_yields_unavailable(portal):- _seed_free_tier()- from hermes_cli.config import load_config, save_config- config = load_config()- config["nous"] = {"guest": False}- save_config(config)- portal.calls.clear()-- states = _drain()-- assert [s.kind for s in states] == ["unavailable"]- assert states[0].copy == anon_auth.UPGRADE_UNAVAILABLE_CHAT- assert states[0].copy_terminal == anon_auth.UPGRADE_UNAVAILABLE+ assert states[0].ok is True and states[0].precondition is Trueassert portal.calls == []+ gen = anon_auth.run_sign_in(replace_account=True)+ assert next(gen).kind == "code"+ gen.close()-def test_no_identity_on_disk_yields_unavailable_without_touching_the_portal(portal, monkeypatch):- """A sign-in never creates the identity it signs in from (the trial claim and connector use do).- With nothing on disk the flow yields ``Unavailable`` and makes no portal call and no mint attempt."""- monkeypatch.setattr(anon_auth, "ensure_portal_identity",- lambda **kwargs: (_ for _ in ()).throw(AssertionError("run_sign_in must not mint")))- monkeypatch.setattr(anon_auth, "mint_guest",- lambda *a, **k: (_ for _ in ()).throw(AssertionError("run_sign_in must not mint")))- states = _drain()-- assert [s.kind for s in states] == ["unavailable"]- assert states[-1].copy_terminal == anon_auth.UPGRADE_UNAVAILABLE- assert states[-1].copy == anon_auth.UPGRADE_UNAVAILABLE_CHAT- assert portal.calls == []--def test_cancelling_before_the_wait_persists_nothing(portal, tmp_path):+def test_cancelling_before_the_wait_persists_nothing(portal):_seed_free_tier()- before = _auth_file_path().read_bytes()+ before = _auth_bytes()stop = []# Driven by hand so the flag flips exactly between the code and the wait.gen = anon_auth.run_sign_in(cancelled=lambda: bool(stop))- first = next(gen)- assert first.kind == "code"+ assert next(gen).kind == "code"stop.append(True)- rest = list(gen)- assert [s.kind for s in rest] == ["superseded"]- assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before+ assert [s.kind for s in gen] == ["cancelled"]+ assert portal.token_polls == 0+ assert _auth_bytes() == before+-def test_cancelling_during_the_wait_ends_it_within_a_second(portal, tmp_path):+def test_cancelling_during_the_token_poll_stops_it_within_a_second(portal):_seed_free_tier()- before = _auth_file_path().read_bytes()- portal.status_sequence = [{"status": "pending"}]+ before = _auth_bytes()+ portal.token_pending = Truestop = threading.Event()- outcomes = []- real_wait = anon_auth.wait_for_promotion-- def _recording_wait(*args, **kwargs):- outcome = real_wait(*args, **kwargs)- outcomes.append(outcome)- return outcomegen = anon_auth.run_sign_in(cancelled=stop.is_set)- first = next(gen)- assert first.kind == "code"- anon_auth.wait_for_promotion = _recording_wait+ assert next(gen).kind == "code"+ timer = threading.Timer(0.2, stop.set)+ timer.start()try:- timer = threading.Timer(0.2, stop.set)- timer.start()started = time.monotonic()- rest = list(gen)+ rest = [s.kind for s in gen]elapsed = time.monotonic() - startedfinally:- anon_auth.wait_for_promotion = real_waittimer.cancel()+ polls = portal.token_polls+ assert rest == ["waiting", "cancelled"]assert elapsed < 3.0- assert outcomes == [{"status": "cancelled"}]- assert [s.kind for s in rest] == ["waiting", "superseded"]- assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before-[email protected]("cancel_wins", [False, True])-def test_cancelling_during_a_completed_status_request_obeys_the_surface_policy(- portal, free_account, cancel_wins):- _seed_free_tier()- calls = 0-- def _cancelled():- nonlocal calls- calls += 1- return calls > 2+ assert polls >= 1 and portal.token_polls == polls # the generator is done: nothing polls on+ assert _auth_bytes() == before- states = _drain(cancelled=_cancelled, cancel_wins_after_promotion=cancel_wins)- assert states[-1].kind == ("superseded" if cancel_wins else "completed")- assert portal.token_grants == (0 if cancel_wins else 1)- from hermes_cli.auth import _load_auth_store- state = _load_auth_store()["providers"]["nous"]- assert anon_auth.is_guest_state(state) is cancel_wins--def _cancel_after_a_completed_promotion(portal, monkeypatch, *, cancel_wins: bool):+def test_a_cancel_that_lands_with_the_token_grant_still_saves_nothing(portal, free_account):_seed_free_tier()+ before = _auth_bytes()stop = threading.Event()+ portal.on_token = stop.set- def _wait(client, portal_base_url, claim_code, *, expires_in, interval, cancelled=None):- stop.set() # the surface cancels while this call is blocked- return {"status": "completed", "user_id": "nas_user:9", "account_email": EMAIL}- monkeypatch.setattr(anon_auth, "wait_for_promotion", _wait)- return list(anon_auth.run_sign_in(- cancelled=stop.is_set, cancel_wins_after_promotion=cancel_wins))--def test_a_desktop_style_cancel_after_a_completed_promotion_persists_nothing(- portal, free_account, monkeypatch, tmp_path):- _seed_free_tier()- before = _auth_file_path().read_bytes()-- states = _cancel_after_a_completed_promotion(portal, monkeypatch, cancel_wins=True)-- assert states[-1].kind == "superseded"- assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before--def test_a_gateway_style_supersede_after_a_completed_promotion_still_signs_in(- portal, free_account, monkeypatch):- states = _cancel_after_a_completed_promotion(portal, monkeypatch, cancel_wins=False)+ states = _drain(cancelled=stop.is_set)- assert states[-1].kind == "completed"+ assert states[-1].kind == "cancelled"assert portal.token_grants == 1- from hermes_cli.auth import _load_auth_store- state = _load_auth_store()["providers"]["nous"]- assert not anon_auth.is_guest_state(state)+ assert _auth_bytes() == before+ assert portal.claims == []-def test_a_persist_guard_that_refuses_persists_nothing_and_never_settles(- portal, free_account, monkeypatch, tmp_path):- import contextlib++def test_a_persist_guard_that_refuses_persists_nothing_and_never_settles(portal, free_account, monkeypatch):_seed_free_tier()- before = _auth_file_path().read_bytes()+ before = _auth_bytes()settles = []monkeypatch.setattr(anon_auth, "settle_after_upgrade", lambda state: settles.append(state) or {})@@ -361,60 +285,78 @@ def test_a_persist_guard_that_refuses_persists_nothing_and_never_settles(def _refuse():yield False- states = list(anon_auth.run_sign_in(persist_guard=_refuse))+ states = _drain(persist_guard=_refuse)- assert states[-1].kind == "superseded"+ assert states[-1].kind == "cancelled"assert settles == []- assert _auth_file_path().read_bytes() == before+ assert _auth_bytes() == before+-def test_persistence_happens_only_after_the_promotion_and_the_token_grant(portal, free_account):+def test_persistence_happens_only_after_the_token_grant(portal, free_account):_seed_free_tier()- before = _auth_file_path().read_bytes()- seen = {}- for state in anon_auth.run_sign_in():- seen[state.kind] = _auth_file_path().read_bytes()+ before = _auth_bytes()+ seen = {state.kind: _auth_bytes() for state in anon_auth.run_sign_in()}assert seen["code"] == beforeassert seen["waiting"] == beforeassert seen["completed"] != before- paths = [p for _, p in portal.calls]- assert "/api/oauth/token" in paths-def test_the_scope_is_entered_for_the_preconditions_and_the_persist_but_never_around_a_wait(++def test_a_token_without_a_scope_keeps_the_requested_scope(portal, free_account, monkeypatch):+ from hermes_cli import auth_nous+ from hermes_cli.auth import PROVIDER_REGISTRY+ real_poll = auth_device_flow._poll_for_token+ monkeypatch.setattr(auth_device_flow, "_poll_for_token",+ lambda **kw: {k: v for k, v in real_poll(**kw).items() if k != "scope"})+ saved = []+ real_persist = auth_nous.persist_nous_credentials+ monkeypatch.setattr(auth_nous, "persist_nous_credentials",+ lambda state, **kw: (saved.append(state), real_persist(state, **kw))[1])++ assert _drain()[-1].kind == "completed"+ assert saved[0]["scope"] == PROVIDER_REGISTRY["nous"].scope+++def test_the_ca_bundle_is_honoured_for_the_whole_sign_in(portal, free_account, monkeypatch):+ import certifi+ monkeypatch.setenv("HERMES_CA_BUNDLE", certifi.where())+ seen = []+ from hermes_cli import auth_nous+ real_client = auth_nous._nous_http_client++ def _recording(timeout_seconds, verify):+ seen.append(verify)+ return real_client(timeout_seconds, verify)++ assert _drain(client_factory=_recording)[-1].kind == "completed"+ assert seen and isinstance(seen[0], ssl.SSLContext)+++def test_the_scope_is_entered_for_the_precondition_and_the_persist_but_never_around_a_wait(portal, free_account, monkeypatch):- import contextlib_seed_free_tier()events = []@contextlib.contextmanagerdef _scope():- events.append(("enter", time.monotonic(), threading.get_ident()))+ events.append(("enter", threading.get_ident()))try:yield Nonefinally:- events.append(("exit", time.monotonic(), threading.get_ident()))+ events.append(("exit", threading.get_ident()))++ real_poll = auth_device_flow._poll_for_token- def _wait(client, portal_base_url, claim_code, *, expires_in, interval, cancelled=None):- events.append(("wait-start", time.monotonic(), threading.get_ident()))- time.sleep(0.2)- events.append(("wait-end", time.monotonic(), threading.get_ident()))- return {"status": "completed", "account_email": EMAIL}- monkeypatch.setattr(anon_auth, "wait_for_promotion", _wait)+ def _poll(**kwargs):+ events.append(("poll", threading.get_ident()))+ return real_poll(**kwargs)+ monkeypatch.setattr(auth_device_flow, "_poll_for_token", _poll)states = []- yields = []for state in anon_auth.run_sign_in(scope=_scope):- yields.append(time.monotonic())+ events.append(("yield", threading.get_ident()))states.append(state)assert states[-1].kind == "completed"- pairs = [e for e in events if e[0] in ("enter", "exit")]- assert [e[0] for e in pairs] == ["enter", "exit", "enter", "exit"]- for first, second in (pairs[0:2], pairs[2:4]):- assert first[2] == second[2] # one thread per scope- wait_start = next(e[1] for e in events if e[0] == "wait-start")- wait_end = next(e[1] for e in events if e[0] == "wait-end")- for first, second in (pairs[0:2], pairs[2:4]):- assert not (first[1] <= wait_start and wait_end <= second[1])- # and never held across a yield, which would hand the scope to the consumer's thread- assert not any(first[1] <= at <= second[1] for at in yields)+ kinds = [kind for kind, _ in events]+ assert kinds == ["enter", "exit", "yield", "yield", "poll", "enter", "exit", "yield"]diff --git a/tests/hermes_cli/test_anon_surfaces.py b/tests/hermes_cli/test_anon_surfaces.pyindex be54c2972a2..836a8e8f6d3 100644--- a/tests/hermes_cli/test_anon_surfaces.py+++ b/tests/hermes_cli/test_anon_surfaces.py@@ -21,6 +21,7 @@ import pytestfrom hermes_cli import (anon_auth,auth_commands,+ guest_handoff,nous_account,nous_auth_keepalive,portal_cli,@@ -179,6 +180,14 @@ def test_keepalive_does_not_start_for_free_tier(isolated_store, monkeypatch):monkeypatch.setattr(nous_auth_keepalive, "_keepalive_thread", None)+_HANDOFF_VIEWS = [+ *({"state": "claimed", "account_email": "[email protected]", "connectors_kind": kind,+ "moved_toolkits": ["gmail"], "dropped_toolkits": ["slack"]} for kind in ("moved", "conflict", "none")),+ # The retrying line names Hermes as a subject ("Hermes keeps trying"), not a command; it is not checked here.+ {"state": "failed", "error": "no_destination"}, {"state": "gone", "probably_moved": True},+]++def test_no_chat_copy_of_any_sign_in_state_leaks_a_terminal_verb_or_a_forbidden_word():placeholders = {"link": "https://example.test/sign-in",@@ -191,6 +200,8 @@ def test_no_chat_copy_of_any_sign_in_state_leaks_a_terminal_verb_or_a_forbidden_"reason": "unknown","detail": "private detail","retry_after": 0.0,+ # Every handoff result line a completed sign-in can carry.+ "handoff": tuple(line for view in _HANDOFF_VIEWS for line in guest_handoff.result_lines(view)),}forbidden = re.compile(r"claim|nous portal|anonymous|guest", re.IGNORECASE)terminal_or_url = re.compile(r"hermes |https?://", re.IGNORECASE)diff --git a/tests/hermes_cli/test_anon_upgrade.py b/tests/hermes_cli/test_anon_upgrade.pyindex 23392465525..f12b63853bc 100644--- a/tests/hermes_cli/test_anon_upgrade.py+++ b/tests/hermes_cli/test_anon_upgrade.py@@ -1,8 +1,8 @@-"""``hermes auth upgrade``: the free tier signs into a Nous account, keeping its connectors.+"""``hermes auth upgrade``: the plain device-code sign-in, then the free tier's apps move over.-Driven through a fake portal covering the device-code endpoints plus the promotion intent/status-surface, so the wire contract (both codes in the intent, status-driven outcome, token grant-persisted over the guest singleton) is exercised rather than mocked away.+Driven through a fake portal covering the device-code endpoints plus the free tier's claim+endpoint, so the wire contract (device code, token grant persisted over the guest singleton, one+claim authorized by the new account) is exercised rather than mocked away."""from __future__ import annotations@@ -40,13 +40,17 @@ class FakePortal:def __init__(self):self.calls: list[tuple[str, str]] = []self.minted = 0- self.intent_bodies: list[dict] = []- self.status_bodies: list[dict] = []+ self.claims: list[tuple[str, dict]] = [] # (authorization header, body) per claim callself.device_code = "dev-code-123"self.user_code = "ABCD-EFGH"- # Sequence of promotion-status payloads; the last one repeats.- self.status_sequence: list[dict] = [{"status": "completed", "user_id": "nas_user:9", "account_email": EMAIL}]+ self.expires_in = 600+ self.token_pending = False # answer authorization_pending until flipped+ self.token_error = "" # an RFC 8628 error code the token endpoint answers with+ self.on_token = None # called when the token grant is issuedself.token_grants = 0+ self.token_polls = 0+ self.claim_reply = {"status": "claimed", "account_email": EMAIL, "cohort_carried": False,+ "connectors": {"kind": "moved", "moved_toolkits": ["gmail"], "dropped_toolkits": []}}def handler(self, request: httpx.Request) -> httpx.Response:path = request.url.path@@ -61,33 +65,31 @@ class FakePortal:return httpx.Response(200, json={"access_token": _jwt(), "token_type": "Bearer", "expires_in": 900,"user_id": "nas_user:1", "org_id": "nas_org:1","inference_base_url": WELCOME})+ if path == "/api/anonymous/claim":+ self.claims.append((request.headers.get("authorization", ""), json.loads(request.content)))+ return httpx.Response(200, json=self.claim_reply)if path == "/api/oauth/device/code":return httpx.Response(200, json={"device_code": self.device_code, "user_code": self.user_code,"verification_uri": f"{PORTAL}/device","verification_uri_complete": f"{PORTAL}/device?user_code={self.user_code}",- "expires_in": 600, "interval": 5})- if path == "/api/anonymous/promotion-intent":- body = json.loads(request.content)- self.intent_bodies.append(body)- if not (body.get("user_code") and body.get("device_code")):- return httpx.Response(400, json={"error": "invalid_request"})- return httpx.Response(200, json={"claim_code": "clm_1", "claim_url": f"{PORTAL}/device",- "expires_in": 600, "interval": 0})- if path == "/api/anonymous/promotion-status":- body = json.loads(request.content)- self.status_bodies.append(body)- idx = min(len(self.status_bodies) - 1, len(self.status_sequence) - 1)- return httpx.Response(200, json=self.status_sequence[idx])+ "expires_in": self.expires_in, "interval": 1})if path == "/api/oauth/token":form = {k: v[0] for k, v in parse_qs(request.content.decode()).items()}if form.get("grant_type") != "urn:ietf:params:oauth:grant-type:device_code":return httpx.Response(400, json={"error": "unsupported_grant_type"})if form.get("device_code") != self.device_code:return httpx.Response(400, json={"error": "invalid_grant"})+ self.token_polls += 1+ if self.token_error:+ return httpx.Response(400, json={"error": self.token_error})+ if self.token_pending:+ return httpx.Response(400, json={"error": "authorization_pending"})self.token_grants += 1+ if self.on_token is not None:+ self.on_token()return httpx.Response(200, json={- "access_token": _jwt(sub="nas_user:9", client_id="hermes-cli", account_tier="free"),+ "access_token": _jwt(sub="nas_user:9", client_id="hermes-cli", account_tier="free", email=EMAIL),"refresh_token": REFRESH_TOKEN, "token_type": "Bearer", "expires_in": 900,"scope": "inference:invoke", "inference_base_url": INFERENCE})return httpx.Response(500, json={"error": f"unexpected {path}"})@@ -128,38 +130,31 @@ def _args():class TestUpgrade:- def test_intent_carries_both_device_codes_from_the_code_request(self, portal):- anon_auth.ensure_portal_identity(explicit=True)- anon_auth.upgrade_guest(_args())- assert len(portal.intent_bodies) == 1- body = portal.intent_bodies[0]- assert body["user_code"] == portal.user_code- assert body["device_code"] == portal.device_code- assert body["token"].startswith("anon_")+ def test_the_plain_device_login_runs_then_one_claim_moves_the_apps(self, portal):+ guest = anon_auth.ensure_portal_identity(explicit=True)+ assert anon_auth.upgrade_guest(_args()) == 0paths = [p for _, p in portal.calls]- assert paths.index("/api/oauth/device/code") < paths.index("/api/anonymous/promotion-intent")- assert paths.index("/api/anonymous/promotion-intent") < paths.index("/api/oauth/token")-- def test_declined_in_browser_prints_copy_and_leaves_auth_store_untouched(self, portal, capsys, tmp_path):- anon_auth.ensure_portal_identity(explicit=True)- before = _auth_file_path().read_bytes()- shared_before = _shared_store(tmp_path)- portal.status_sequence = [{"status": "voided", "reason": "user_declined"}]- code = anon_auth.upgrade_guest(_args())- out = capsys.readouterr().out- assert code == 1- assert anon_auth.UPGRADE_REASON_COPY["user_declined"] in out- assert portal.token_grants == 0- assert _auth_file_path().read_bytes() == before- assert _shared_store(tmp_path) == shared_before+ assert not [p for p in paths if "promotion" in p]+ assert paths.index("/api/oauth/device/code") < paths.index("/api/oauth/token") < paths.index("/api/anonymous/claim")+ assert len(portal.claims) == 1+ bearer, body = portal.claims[0]+ assert body == {"token": guest["anon_token"]}+ assert bearer.startswith("Bearer ") and bearer != f"Bearer {guest.get('access_token')}"++ def test_signs_in_with_no_free_tier_on_disk_and_sends_no_claim(self, portal, capsys):+ assert anon_auth.upgrade_guest(_args()) == 0+ assert f"Signed in as {EMAIL}." in capsys.readouterr().out+ assert portal.claims == [] and portal.minted == 0+ assert not anon_auth.is_guest_state(_load_auth_store()["providers"]["nous"])- def test_completed_promotion_signs_in_and_keeps_no_free_tier_fields(self, portal, capsys, tmp_path):+ def test_completed_sign_in_keeps_no_free_tier_fields_and_prints_what_moved(self, portal, capsys, tmp_path):guest = anon_auth.ensure_portal_identity(explicit=True)assert _shared_store(tmp_path).get("anon_token") == guest["anon_token"]code = anon_auth.upgrade_guest(_args())out = capsys.readouterr().outassert code == 0assert f"Signed in as {EMAIL}." in out+ assert f"Your apps moved to {EMAIL}: gmail." in outlowered = out.lower()for banned in ("guest", "anonymous", "claim"):assert banned not in lowered, f"{banned!r} leaked into user-facing output:\n{out}"@@ -174,13 +169,35 @@ class TestUpgrade:assert shared.get("refresh_token") == REFRESH_TOKENassert "anon_token" not in shared- def test_completed_promotion_is_the_handoff_and_sends_no_claim(self, portal):- from hermes_cli import guest_handoff+ def test_hermes_model_signs_a_connector_free_tier_in_instead_of_refusing(self, portal, monkeypatch, capsys):+ from hermes_cli import model_setup_flows+ from tests.hermes_cli.anon_portal import as_local_desktop_backend+ as_local_desktop_backend(monkeypatch)+ assert anon_auth.guest_without_free_tier(anon_auth.ensure_portal_identity(explicit=True))+ logins = []+ monkeypatch.setattr(model_setup_flows, "_run_login", lambda login_fn, *args: logins.append(args))++ model_setup_flows._model_flow_nous({})++ assert len(logins) == 1+ assert anon_auth.UPGRADE_HINT not in capsys.readouterr().out++ def test_the_terminal_device_login_prints_what_moved(self, portal, monkeypatch, capsys):+ import argparse+ from hermes_cli import auth_nous+ from hermes_cli.auth import PROVIDER_REGISTRYanon_auth.ensure_portal_identity(explicit=True)- assert anon_auth.upgrade_guest(_args()) == 0- assert ("POST", "/api/anonymous/claim") not in portal.calls- status = guest_handoff.handoff_status()- assert status["state"] == "claimed" and status["account_email"] == EMAIL+ account = {"access_token": _jwt(sub="nas_user:9", client_id="hermes-cli", account_tier="free", email=EMAIL),+ "refresh_token": REFRESH_TOKEN, "portal_base_url": PORTAL, "inference_base_url": INFERENCE,+ "client_id": "hermes-cli", "expires_in": 900}+ monkeypatch.setattr(auth_nous, "_offer_shared_nous_import", lambda timeout: None)+ monkeypatch.setattr(auth_nous, "_nous_device_code_login", lambda **kw: dict(account))+ monkeypatch.setattr(auth_nous, "_pick_nous_model_after_login", lambda *a: None)++ auth_nous._login_nous(argparse.Namespace(no_browser=True, timeout=15.0), PROVIDER_REGISTRY["nous"])++ assert f"Your apps moved to {EMAIL}: gmail." in capsys.readouterr().out+ assert len(portal.claims) == 1FREE_PICK = "upstage/solar-pro4:free"diff --git a/tests/hermes_cli/test_login_cli_command.py b/tests/hermes_cli/test_login_cli_command.pyindex df8bf98fc44..2e77efb3ec2 100644--- a/tests/hermes_cli/test_login_cli_command.py+++ b/tests/hermes_cli/test_login_cli_command.py@@ -40,7 +40,8 @@ def test_the_cli_handler_prints_the_code_then_drains_off_thread(monkeypatch):cli, workers, output = _cli(monkeypatch)states = iter([anon_auth.Code("https://example.test/sign-in", "CODE-1", 900, 5),- anon_auth.Completed(email="[email protected]", model="model-1", model_changed=True),+ anon_auth.Completed(email="[email protected]", model="model-1", model_changed=True,+ handoff=("Your apps moved to [email protected]: gmail.",)),])monkeypatch.setattr(anon_auth, "run_sign_in", lambda **_kwargs: states)monkeypatch.setattr(@@ -57,7 +58,8 @@ def test_the_cli_handler_prints_the_code_then_drains_off_thread(monkeypatch):]assert workers[0][0].started is Trueassert workers[0][0].target() == (- "Signed in as [email protected].\nDefault model is now model-1.")+ "Signed in as [email protected].\nYour apps moved to [email protected]: gmail.\n"+ "Default model is now model-1.")@pytest.mark.parametrize("terminal,initial_model,expected_model",@@ -65,7 +67,7 @@ def test_the_cli_handler_prints_the_code_then_drains_off_thread(monkeypatch):(anon_auth.Completed(model="model-1", model_changed=True), anon_auth.GUEST_MODEL, "model-1"),(anon_auth.Completed(model="model-1", model_changed=True),"openrouter/some-model", "openrouter/some-model"),- (anon_auth.Declined(), anon_auth.GUEST_MODEL, anon_auth.GUEST_MODEL),+ (anon_auth.Cancelled(), anon_auth.GUEST_MODEL, anon_auth.GUEST_MODEL),],)def test_the_drain_only_moves_the_free_tier_model_on_completion(diff --git a/tests/hermes_cli/test_plain_login_settle.py b/tests/hermes_cli/test_plain_login_settle.pynew file mode 100644index 00000000000..14be35c9956--- /dev/null+++ b/tests/hermes_cli/test_plain_login_settle.py@@ -0,0 +1,92 @@+"""Every plain device login that saves a Nous account over the free tier settles the config itself.++The guest handoff only moves apps; moving a config left on the free tier's route (the welcome model+on the welcome host) to the account is each sign-in's own completion step, run once the auth-store+locks are released. Driven against the fake portal ``hermes auth upgrade`` is tested with.+"""++from __future__ import annotations++import argparse+from datetime import UTC, datetime, timedelta+from types import SimpleNamespace++import pytest++from hermes_cli import anon_auth, auth_nous, guest_handoff+from tests.hermes_cli.test_anon_upgrade import (+ EMAIL, FREE_PICK, INFERENCE, PORTAL, REFRESH_TOKEN, WELCOME, _jwt, _model_config, _write_model_config,+ free_account, portal)++__all__ = ["free_account", "portal"]+++def _account() -> dict:+ return {"access_token": _jwt(sub="nas_user:9", client_id="hermes-cli", account_tier="free", email=EMAIL),+ "refresh_token": REFRESH_TOKEN, "portal_base_url": PORTAL, "inference_base_url": INFERENCE,+ "client_id": "hermes-cli", "expires_in": 900,+ "expires_at": (datetime.now(UTC) + timedelta(minutes=15)).isoformat()}+++def _terminal_login(monkeypatch):+ monkeypatch.setattr(auth_nous, "_offer_shared_nous_import", lambda timeout: None)+ monkeypatch.setattr(auth_nous, "_pick_nous_model_after_login", lambda *a: None)+ from hermes_cli.auth import PROVIDER_REGISTRY+ auth_nous._login_nous(argparse.Namespace(no_browser=True, timeout=15.0), PROVIDER_REGISTRY["nous"])+++def _auth_add(monkeypatch):+ from hermes_cli import auth_commands+ auth_commands._add_nous_oauth_credential(SimpleNamespace(label=None, timeout=None, no_browser=True), "nous")+++def _step_up(monkeypatch):+ auth_nous.step_up_nous_billing_scope(open_browser=False)+++def _tool_login(monkeypatch):+ from hermes_cli import nous_subscription+ monkeypatch.setattr(nous_subscription, "_confirm", lambda prompt: True)+ assert nous_subscription._run_nous_portal_login_only(capability="Web search") is True++[email protected]("surface", [_terminal_login, _auth_add, _step_up, _tool_login],+ ids=["hermes model / login", "auth add nous", "billing step-up", "tool setup login"])+def test_the_sign_in_settles_the_config_once_after_its_locks_are_released(+ portal, free_account, monkeypatch, surface):+ from hermes_cli import auth+ anon_auth.ensure_portal_identity(explicit=True)+ _write_model_config({"provider": "nous", "default": anon_auth.GUEST_MODEL, "base_url": WELCOME})+ monkeypatch.setattr(auth, "_nous_device_code_login", lambda **kw: _account())+ monkeypatch.setattr(auth_nous, "_nous_device_code_login", lambda **kw: _account())+ settles = []+ real_settle = anon_auth.settle_after_upgrade++ def _recording(state):+ settles.append(guest_handoff._holds_auth_locks())+ return real_settle(state)+ monkeypatch.setattr(anon_auth, "settle_after_upgrade", _recording)++ surface(monkeypatch)++ assert settles == [False]+ model_cfg = _model_config()+ assert model_cfg["default"] == FREE_PICK+ assert model_cfg["base_url"] == INFERENCE.rstrip("/")++[email protected]("surface", [_terminal_login, _auth_add, _tool_login],+ ids=["hermes model / login", "auth add nous", "tool setup login"])+def test_the_terminal_sign_in_prints_what_moved(portal, free_account, monkeypatch, capsys, surface):+ from hermes_cli import auth+ anon_auth.ensure_portal_identity(explicit=True)+ portal.claim_reply = {**portal.claim_reply, "connectors": {+ "kind": "moved", "moved_toolkits": ["gmail"], "dropped_toolkits": ["slack"]}}+ monkeypatch.setattr(auth, "_nous_device_code_login", lambda **kw: _account())+ monkeypatch.setattr(auth_nous, "_nous_device_code_login", lambda **kw: _account())++ surface(monkeypatch)++ out = capsys.readouterr().out+ assert f"Your apps moved to {EMAIL}: gmail." in out+ assert f"Reconnect in {EMAIL}: slack." in outdiff --git a/tests/hermes_cli/test_shared_metrics_signals.py b/tests/hermes_cli/test_shared_metrics_signals.pyindex 71de653b66e..bc9e307845e 100644--- a/tests/hermes_cli/test_shared_metrics_signals.py+++ b/tests/hermes_cli/test_shared_metrics_signals.py@@ -374,8 +374,8 @@ def _poll(provider, status, body):def _guest_sign_in(token_status, token_body):- """The Desktop free-tier sign-in (guest promotion): the real ``run_sign_in`` generator recorded- onto a dashboard session; the promotion completes, the token poll gets ``token_*`` until expiry."""+ """The Desktop sign-in over a free tier: the real ``run_sign_in`` generator recorded onto a+ dashboard session; the token poll gets ``token_*`` until expiry."""def run(monkeypatch):import httpx@@ -391,8 +391,6 @@ def _guest_sign_in(token_status, token_body):replies = {"/api/oauth/device/code": (200, {"device_code": "d", "user_code": "U", "verification_uri": "https://p/v","verification_uri_complete": "https://p/v?c=U", "expires_in": 30, "interval": 1}),- "/api/anonymous/promotion-intent": (200, {"claim_code": "C", "claim_url": "/claim", "interval": 1}),- "/api/anonymous/promotion-status": (200, {"status": "completed"}),"/api/oauth/token": (token_status, token_body)}def reply(request):diff --git a/tests/hermes_cli/test_web_oauth_dispatch.py b/tests/hermes_cli/test_web_oauth_dispatch.pyindex 5e3a9d1aebb..2cb2d07971a 100644--- a/tests/hermes_cli/test_web_oauth_dispatch.py+++ b/tests/hermes_cli/test_web_oauth_dispatch.py@@ -464,59 +464,6 @@ def test_codex_worker_final_save_is_atomic_with_cancel_delete(tmp_path, monkeypa-def test_nous_dashboard_poller_preserves_effective_scope_when_token_omits_scope(monkeypatch):- from hermes_cli import auth as auth_mod-- session_id = "nous-effective-scope-test"- _web_server_oauth._oauth_sessions[session_id] = {- "session_id": session_id,- "provider": "nous",- "flow": "device_code",- "created_at": time.time(),- "status": "pending",- "error_message": None,- "portal_base_url": "https://portal.nousresearch.com",- "client_id": "hermes-cli",- "device_code": "device-code",- "interval": 5,- "expires_at": time.time() + 600,- "scope": auth_mod.DEFAULT_NOUS_SCOPE,- }- captured_state = {}-- def fake_refresh_nous_oauth_from_state(state, **kwargs):- captured_state.update(state)- return {**state, "agent_key": "jwt-agent-key"}-- monkeypatch.setattr(- auth_mod,- "_poll_for_token",- lambda **kwargs: {- "access_token": "access-token",- "refresh_token": "refresh-token",- "expires_in": 3600,- "token_type": "Bearer",- },- )- monkeypatch.setattr(- auth_mod,- "refresh_nous_oauth_from_state",- fake_refresh_nous_oauth_from_state,- )- monkeypatch.setattr(auth_mod, "persist_nous_credentials", lambda state: None)-- try:- _web_server_oauth._nous_plain_poller(session_id)- assert captured_state["scope"] == auth_mod.DEFAULT_NOUS_SCOPE- assert _web_server_oauth._oauth_sessions[session_id]["status"] == "approved"- finally:- _web_server_oauth._oauth_sessions.pop(session_id, None)------def test_anthropic_dashboard_oauth_is_removed_and_external():"""Anthropic subscription OAuth is not minted by the dashboard anymore."""diff --git a/website/docs/developer-guide/cli-internals.md b/website/docs/developer-guide/cli-internals.mdindex a13071ff269..f01bda84c55 100644--- a/website/docs/developer-guide/cli-internals.md+++ b/website/docs/developer-guide/cli-internals.md@@ -112,34 +112,40 @@ weeks, months and years. The combined timeout is capped below the native signedunit limits cannot overflow subprocess polling. Zero/unknown/infinite phaselimits use the bounded fallback. This does not change active-turn drain settings.-## Nous free tier sign-in+## Nous sign-in-Sign-in completion is one function, `settle_after_upgrade`, called by every caller that persists an-account over a free-tier identity (CLI `upgrade_guest`, the desktop poller): it moves a config on the-welcome route to the account's host and the tier's recommended default-(`models.recommended_nous_default_model`, shared with `GET /api/model/recommended-default`).+Every Nous sign-in is the plain device-code login. Sign-in completion is one function,+`settle_after_upgrade`, called once per completion: it moves a config on the welcome route to the+account's host and the tier's recommended default (`models.recommended_nous_default_model`, shared+with `GET /api/model/recommended-default`).The shared flow, states, and copy live in `anon_sign_in.py`; CLI rendering lives in-`anon_sign_in_cli.py`. `anon_auth.py` keeps identity, promotion polling, and settlement, and-re-exports the existing sign-in API. The flow resolves identity and persistence collaborators-through `anon_auth` at call time to preserve module-attribute monkeypatch seams.+`anon_sign_in_cli.py`. `anon_auth.py` keeps identity and settlement, and re-exports the sign-in+API. The flow resolves identity and persistence collaborators through `anon_auth` at call time to+preserve module-attribute monkeypatch seams.The sign-in itself is one composition: `anon_auth.run_sign_in()` yields `SignInState`s (`Code`,-`Waiting`, `Completed`, `Declined`, `Superseded`, `TimedOut`, `Retired`, `Failed`,-`AlreadySignedIn`, `Unavailable`). It reads the current state itself, holds one absolute deadline-across both waits, persists only after a completed promotion **and** a token grant, runs-`settle_after_upgrade` exactly once per completion, and never lets a persist or settle failure-escape as an exception — it becomes `Failed`. Every state carries its own `.copy` (the chat form,-which never contains a raw exception, a URL or a `hermes` verb) and `.copy_terminal`, so no caller-maps a reason to a string. `cancelled()` stops an attempt; `cancel_wins_after_promotion` decides-what happens when the server had already completed the transfer — the desktop keeps `True` (a-DELETE means "not on this machine"), the gateway passes `False` (a supersede must not discard a-transfer the user actually approved). `scope` is entered only around the precondition and persist-blocks, never across a `yield` or a network wait, because `run_in_executor` does not carry-contextvars. `upgrade_guest` (`hermes auth upgrade`), the CLI `/login` handler and the desktop-promotion poller are renderers over it; a surface that needs the cancel check and the save to be-atomic passes `persist_guard`. The desktop's plain "connect another Nous account" device-code login-is a separate path (`_nous_plain_poller`) and must stay one.+`Waiting`, `Completed`, `Cancelled`, `TimedOut`, `Failed`, `AlreadySignedIn`). It requests a device+code, polls the token endpoint on one deadline (an expired code is `TimedOut`), saves the account,+runs `settle_after_upgrade` exactly once, and never lets a persist or settle failure escape as an+exception: it becomes `Failed`. It works with or without a free tier on disk. `Completed.email`+comes from the access token's `email` claim; `Completed.handoff` carries the guest handoff's result+lines (what moved, what to reconnect). Every state carries its own `.copy` (the chat form, which+never contains a raw exception, a URL or a `hermes` verb) and `.copy_terminal`, so no caller maps a+reason to a string. `cancelled()` is checked at least once a second inside the token poll and once more+before the save; a cancel always wins and nothing is saved. TLS verification comes from+`_resolve_verify`, so `HERMES_CA_BUNDLE` and friends apply. `scope` is entered only around the+precondition and persist blocks, never across a `yield` or a network wait, because+`run_in_executor` does not carry contextvars. `replace_account=True` lets a signed-in install sign in+again (the desktop's "connect another account"); otherwise a signed-in install gets+`AlreadySignedIn` before any network. `upgrade_guest` (`hermes auth upgrade`), the CLI and TUI+`/login`, the gateway `/login` and the desktop start route are renderers over it; a surface that+needs the cancel check and the save to be atomic passes `persist_guard`. `hermes model` and+`hermes auth add nous` keep `_login_nous` (it carries `--portal-url`, `--ca-bundle`, `--insecure`+and the shared-store import); that is the same plain device login, and it prints the handoff result+the same way. Every sign-in that saves an account (`run_sign_in`, `_login_nous`, `hermes auth add+nous`, the billing step-up, the tool-setup login) calls `settle_after_upgrade` itself once its locks+are released; the handoff runner never settles.### Guest handoff after a sign-indiff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex b754a73d61e..99b18a350fe 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -722,7 +722,7 @@ briefs are labelled user turns appended at a turn boundary, preserving role alte`GatewayLoginCommandsMixin` (`gateway/slash_commands_login.py`). It refuses outside a paired DM:`chat_type in {"dm","private"}`, a truthy `chat_id`, and a platform whose `"dm"` really is a pairedconversation — ntfy, raft and a2a all report `chat_type="dm"` for a broadcast topic, a channel and-an agent peer, so posting a consent link there would publish it.+an agent peer, so posting a sign-in link and code there would publish them.**It binds the whole install.** The sign-in writes the singleton `providers.nous`, so whoeverapproves the code owns this gateway's inference and connectors for every chat it serves. Slash@@ -730,15 +730,15 @@ gating is opt-in (`gateway/slash_access.py`): with no `allow_admin_from` set, evDM the bot can run it. Operators of shared gateways must set it.The handler returns its ack at once and drains `anon_auth.run_sign_in` on a **private single-worker-executor** (`_login_executor`), never the shared 10-thread gateway pool — a promotion wait can last+executor** (`_login_executor`), never the shared 10-thread gateway pool — the token poll can lastthe code's full expiry, and a live worker in the shared pool makes shutdown skip the SessionDBclose/checkpoint. One attempt per process, stamped with the identity that started it: the same-identity's second `/login` supersedes (the loser ends with the superseded copy pushed into its own-chat); a different identity is refused. `task.cancel()` cannot interrupt a blocking poll inside a-worker thread, so shutdown and supersede both work through `attempt.cancelled`, which-`wait_for_promotion` now polls on a ≤1 s tick. A shutdown-cancelled attempt pushes nothing — the-task is dying and its adapters may already be gone — but if the server had already completed the-transfer it still persists, because that transfer is irreversible.+identity's second `/login` cancels the first (the loser ends with the cancelled copy pushed into its+own chat); a different identity is refused. `task.cancel()` cannot interrupt a blocking poll inside+a worker thread, so shutdown and the replacement both work through `attempt.cancelled`, which the+token poll checks on a ≤1 s tick and once more before the save. A cancelled attempt saves nothing.+A shutdown-cancelled attempt pushes nothing — the task is dying and its adapters may already be+gone. The completion copy carries what the free tier's handoff moved.On completion the handler **evicts** every cached agent still on `nous/welcome` and clears anysession model override pinned to it. It does not switch agents in place and does not write a model