anon_sign_in.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. """The one Nous sign-in: the plain device-code login every surface renders, plus its states and copy."""
  2. from __future__ import annotations
  3. import contextlib
  4. import math
  5. import time
  6. from dataclasses import dataclass
  7. from typing import Any, Callable, ClassVar, ContextManager, Iterator, Optional
  8. from hermes_cli.auth_constants import httpx
  9. UPGRADE_START = "Sign in with a Nous account to unlock more models and tools."
  10. UPGRADE_ALREADY_SIGNED_IN = "Already signed in."
  11. UPGRADE_DO_NOT_SHARE = "Do not share this code."
  12. UPGRADE_TIMED_OUT = "That sign-in link has expired. Start again whenever you're ready."
  13. UPGRADE_NOT_COMPLETED = "Sign-in didn't finish. Try again whenever you're ready."
  14. # The account service was busy or unreachable mid sign-in (an ``anon_*`` code from
  15. # ``anon_auth.classify_mint_exception``): nothing was saved, so the copy reassures before the way forward.
  16. UPGRADE_SERVICE_BUSY = ("Signing in couldn't finish because the Nous service is busy. "
  17. "Try again in {wait}. Your session is still here in the meantime.")
  18. UPGRADE_SERVICE_UNREACHABLE = ("The Nous service couldn't be reached to finish signing you in. "
  19. "Check your internet connection and try again. Your session is still here.")
  20. UPGRADE_NO_DEFAULT_TERMINAL = "No default model is set yet; run `hermes model` to pick one."
  21. UPGRADE_NO_DEFAULT_CHAT = "No default model is set yet; run /model to pick one."
  22. UPGRADE_WAITING = "Waiting for sign-in..."
  23. UPGRADE_WAITING_UP_TO = "Waiting for sign-in, up to {minutes}."
  24. UPGRADE_CANCELLED = "\nSign-in cancelled."
  25. LOGIN_COMMAND = "/login"
  26. LOGIN_STARTING = "Starting sign-in..."
  27. LOGIN_DM_ONLY = "Sign in from a direct message with Hermes."
  28. LOGIN_BUSY_ELSEWHERE = "Another sign-in is already running on this Hermes. Try again in a few minutes."
  29. LOGIN_NOT_ALLOWED = "Only an operator of this Hermes can sign it in."
  30. # The card form (a surface with its own sign-in button) and the chat form (names /login).
  31. FREE_TIER_RATE_LIMIT_CARD = (
  32. "You've used up the allowance for chatting without signing in. It refreshes in {reset}. "
  33. "Sign in for a bigger allowance, it's free.")
  34. FREE_TIER_RATE_LIMIT_CHAT = FREE_TIER_RATE_LIMIT_CARD + " To sign in: /login."
  35. def format_wait_line(expires_in: int) -> str:
  36. """The honest "up to N minutes" line; N = ceil(expires_in / 60), singular at 1."""
  37. n = max(1, math.ceil(max(0, int(expires_in)) / 60))
  38. return UPGRADE_WAITING_UP_TO.format(minutes=f"{n} minute" if n == 1 else f"{n} minutes")
  39. # --- Sign-in states -----------------------------------------------------------------------------
  40. #
  41. # One sign-in composition (:func:`run_sign_in`) yields these; every surface is a renderer over them.
  42. # Each state carries its own user copy, so no renderer ever maps a reason to a string: ``.copy`` is
  43. # the in-chat form (never a raw exception, a URL or a ``hermes`` verb) and ``.copy_terminal`` the
  44. # form a top-level terminal command prints.
  45. @dataclass(frozen=True)
  46. class SignInState:
  47. """One step of a sign-in. Every state carries its own user copy; renderers never map."""
  48. kind: ClassVar[str] = ""
  49. terminal: ClassVar[bool] = True # False only for Code and Waiting
  50. ok: ClassVar[bool] = False # exit-code 0 / "this ended well"
  51. precondition: ClassVar[bool] = False # True only for AlreadySignedIn
  52. @property
  53. def copy(self) -> str:
  54. """The in-chat form."""
  55. return ""
  56. @property
  57. def copy_terminal(self) -> str:
  58. """The terminal form; differs for Completed and Failed."""
  59. return self.copy
  60. @dataclass(frozen=True)
  61. class Code(SignInState):
  62. """The device page link and the sign-in code, plus the clock the caller may show."""
  63. link: str
  64. code: str
  65. expires_in: int
  66. interval: int
  67. kind: ClassVar[str] = "code"
  68. terminal: ClassVar[bool] = False
  69. @property
  70. def copy(self) -> str:
  71. return UPGRADE_DO_NOT_SHARE
  72. @property
  73. def copy_with_wait(self) -> str:
  74. """The do-not-share line plus the honest "up to N minutes"; composed here, never in a renderer."""
  75. return f"{UPGRADE_DO_NOT_SHARE} {format_wait_line(self.expires_in)}"
  76. @dataclass(frozen=True)
  77. class Waiting(SignInState):
  78. kind: ClassVar[str] = "waiting"
  79. terminal: ClassVar[bool] = False
  80. @property
  81. def copy(self) -> str:
  82. return UPGRADE_WAITING
  83. @dataclass(frozen=True)
  84. class Completed(SignInState):
  85. """``handoff`` holds the guest handoff's result lines (what moved, what to reconnect), empty
  86. when the sign-in replaced no free tier. ``handoff_status`` is the latest handoff record it ran,
  87. in ``guest_handoff.wire_status`` form, for a surface that renders the result itself."""
  88. email: str = ""
  89. model: str = ""
  90. model_changed: bool = False
  91. handoff: tuple[str, ...] = ()
  92. handoff_status: Optional[dict[str, Any]] = None
  93. kind: ClassVar[str] = "completed"
  94. ok: ClassVar[bool] = True
  95. def _lines(self, no_default: str) -> str:
  96. lines = [f"Signed in as {self.email}." if self.email else "Signed in.", *self.handoff]
  97. if self.model_changed:
  98. lines.append(f"Default model is now {self.model}." if self.model else no_default)
  99. return "\n".join(lines)
  100. @property
  101. def copy(self) -> str:
  102. return self._lines(UPGRADE_NO_DEFAULT_CHAT)
  103. @property
  104. def copy_terminal(self) -> str:
  105. return self._lines(UPGRADE_NO_DEFAULT_TERMINAL)
  106. @dataclass(frozen=True)
  107. class Cancelled(SignInState):
  108. """Stopped from outside before anything was saved: the user's cancel, a newer /login, a shutdown."""
  109. kind: ClassVar[str] = "cancelled"
  110. @property
  111. def copy(self) -> str:
  112. return UPGRADE_CANCELLED.strip()
  113. @dataclass(frozen=True)
  114. class TimedOut(SignInState):
  115. #: The enriched device-auth guidance, for a surface with room for it. Never shown in a chat.
  116. detail: str = ""
  117. kind: ClassVar[str] = "timed_out"
  118. @property
  119. def copy(self) -> str:
  120. return UPGRADE_TIMED_OUT
  121. @dataclass(frozen=True)
  122. class Failed(SignInState):
  123. """``reason``: an ``anon_*`` code naming the service's verdict (busy, unreachable...), or "" for
  124. anything unnamed. ``retry_after``: the wait the service asked for, in seconds (0 when it named
  125. none). ``retryable``: whether a later attempt can succeed, so a renderer knows to offer "try
  126. again" and when."""
  127. reason: str = ""
  128. detail: str = ""
  129. retry_after: float = 0.0
  130. kind: ClassVar[str] = "failed"
  131. @property
  132. def retryable(self) -> bool:
  133. from hermes_cli import anon_auth as _core
  134. return bool(self.reason.startswith("anon_") and self.reason not in _core.ANON_TERMINAL_CODES)
  135. @property
  136. def copy(self) -> str:
  137. from hermes_cli import anon_auth as _core
  138. if self.reason in _core.ANON_UNREACHABLE_CODES:
  139. return UPGRADE_SERVICE_UNREACHABLE
  140. if self.reason in (_core.ANON_RATE_LIMITED, _core.ANON_GATE_PAUSED):
  141. return UPGRADE_SERVICE_BUSY.format(wait=_core.friendly_wait(self.retry_after or 60))
  142. if self.reason in _core.ANON_FAILURE_COPY:
  143. return _core.anon_failure_copy(self.reason, retry_after=self.retry_after)
  144. return UPGRADE_NOT_COMPLETED
  145. @property
  146. def copy_terminal(self) -> str:
  147. if self.reason and self.copy != UPGRADE_NOT_COMPLETED:
  148. return self.copy
  149. return f"Sign-in failed: {self.detail}" if self.detail else UPGRADE_NOT_COMPLETED
  150. @dataclass(frozen=True)
  151. class AlreadySignedIn(SignInState):
  152. kind: ClassVar[str] = "already_signed_in"
  153. ok: ClassVar[bool] = True
  154. precondition: ClassVar[bool] = True
  155. @property
  156. def copy(self) -> str:
  157. return UPGRADE_ALREADY_SIGNED_IN
  158. def _failed_from_exception(exc: BaseException) -> Failed:
  159. """A ``Failed`` that keeps the service's own verdict: the ``anon_*`` code and wait hint an
  160. ``AuthError`` carries, or the wire's shape for a transport error. The raw detail never reaches a
  161. chat; ``copy_terminal`` may show it when nothing better is known."""
  162. from hermes_cli import anon_auth as _core
  163. err = _core.classify_mint_exception(exc)
  164. reason = str(err.code or "")
  165. if reason == _core.ANON_SERVER_ERROR and not isinstance(exc, _core.AuthError):
  166. # An unnamed local failure (a bad CA bundle, a lock timeout): keep the generic copy and its
  167. # terminal detail rather than blaming the service.
  168. return Failed(reason="", detail=str(exc))
  169. return Failed(reason=reason, detail=str(exc), retry_after=float(err.retry_after or 0.0))
  170. def _default_persist_guard(is_cancelled: Callable[[], bool]) -> Callable[[], ContextManager[bool]]:
  171. """The persist guard used when a surface brings none: proceed unless the attempt was stopped."""
  172. @contextlib.contextmanager
  173. def _guard():
  174. yield not is_cancelled()
  175. return _guard
  176. def _account_email(account_state: dict[str, Any], fallback: Optional[str]) -> str:
  177. """The signed-in account's email, read from its own access token."""
  178. from hermes_cli.auth_constants import _decode_jwt_claims
  179. email = _decode_jwt_claims(account_state.get("access_token")).get("email")
  180. return str(email or fallback or "").strip()
  181. def _handoff_lines(results: list[dict[str, Any]]) -> tuple[str, ...]:
  182. from hermes_cli.guest_handoff import result_lines
  183. return tuple(line for view in results for line in result_lines(view))
  184. def _handoff_status(results: list[dict[str, Any]], replaced: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
  185. """The handoff a completed sign-in reports (``guest_handoff.wire_status`` form): the latest record its
  186. own run attempted, else the replaced free tier's saved record (another process held it), else
  187. None when it replaced no free tier. Read under the scope."""
  188. from hermes_cli import anon_auth as _core
  189. from hermes_cli.guest_handoff import record_status, wire_status
  190. if results:
  191. return wire_status(results[-1])
  192. anon_token = replaced.get("anon_token") if _core.is_guest_state(replaced) else None
  193. status = record_status(anon_token) if isinstance(anon_token, str) and anon_token else None
  194. return wire_status(status) if status else None
  195. def run_sign_in(
  196. *,
  197. timeout_seconds: float = 15.0,
  198. cancelled: Optional[Callable[[], bool]] = None,
  199. replace_account: bool = False,
  200. persist_guard: Optional[Callable[[], ContextManager[bool]]] = None,
  201. scope: Optional[Callable[[], ContextManager[Any]]] = None,
  202. client_factory: Optional[Callable[[float, Any], ContextManager[httpx.Client]]] = None,
  203. ) -> Iterator[SignInState]:
  204. """Sign in with a Nous account: the plain device-code login. Yields :class:`SignInState`s.
  205. One composition behind every surface: device code, then a cancel-aware token poll on one
  206. deadline, then the save. The save is where the guest handoff hooks in (``guest_handoff``): a free
  207. tier the account replaces has its apps moved once the surface's lock is released, and the result
  208. rides :class:`Completed`. :func:`settle_after_upgrade` runs exactly once per completion. Works
  209. with or without a free tier on disk. It always ends by yielding exactly one state whose
  210. ``terminal`` is True: a persist or settle failure becomes ``Failed``, never an exception out of
  211. ``next()``.
  212. *cancelled* is polled before the wait, on a <= 1 s tick inside the token poll, and once more
  213. under *persist_guard* before the save; a cancel always wins and nothing is saved.
  214. *replace_account* lets a signed-in install sign in again (the desktop's "connect another
  215. account"); without it a signed-in install yields ``AlreadySignedIn`` before any network.
  216. *persist_guard* lets a surface make its own cancel check and the save atomic under its own lock.
  217. *scope* is entered only around the two non-network blocks (precondition, persist/settle), never
  218. across a ``yield``: ``run_in_executor`` does not carry contextvars, so the scope has to be
  219. entered inside the generator, on whichever thread is advancing it.
  220. *client_factory* is the HTTP client seam, ``client_factory(timeout_seconds, verify)``.
  221. """
  222. from hermes_cli import anon_auth as _core
  223. from hermes_cli.auth import PROVIDER_REGISTRY, _resolve_verify
  224. from hermes_cli.auth_device_flow import DeviceFlowCancelled, _request_device_code
  225. from hermes_cli.auth_error_copy import is_device_code_expired
  226. from hermes_cli.auth_nous import _nous_http_client, _nous_portal_base_url
  227. from hermes_cli.guest_handoff import drain
  228. is_cancelled = cancelled or (lambda: False)
  229. open_scope = scope or contextlib.nullcontext
  230. # Yielded outside the scope, because a scope must never be held across a ``yield``.
  231. state: Optional[dict[str, Any]] = None
  232. try:
  233. with open_scope():
  234. state = _core.current_nous_state()
  235. # Inside the scope: the operator's Portal override is a profile setting, and it wins over
  236. # a saved URL the same way it does for every other Nous call.
  237. portal = _nous_portal_base_url(state or {})
  238. except Exception as exc: # health: allow BLE001 -- the generator's contract is one terminal state, never a raise
  239. yield Failed(reason="", detail=str(exc))
  240. return
  241. if state and not _core.is_guest_state(state) and not replace_account:
  242. yield AlreadySignedIn()
  243. return
  244. try:
  245. pconfig = PROVIDER_REGISTRY["nous"]
  246. client_id, scope_str = pconfig.client_id, pconfig.scope
  247. # A malformed CA bundle raises here, before the wire: inside the try, so it lands on Failed.
  248. verify = _resolve_verify(insecure=None, ca_bundle=None, auth_state=None)
  249. open_client = client_factory or _nous_http_client
  250. with open_client(timeout_seconds, verify) as client:
  251. device = _request_device_code(client, portal, client_id, scope_str)
  252. expires_in = int(device["expires_in"])
  253. interval = int(device.get("interval") or 5)
  254. deadline = time.monotonic() + max(1, expires_in)
  255. yield Code(link=str(device["verification_uri_complete"]), code=str(device["user_code"]),
  256. expires_in=expires_in, interval=interval)
  257. if is_cancelled():
  258. yield Cancelled()
  259. return
  260. yield Waiting()
  261. token_data = _core._poll_for_token(
  262. client=client, portal_base_url=portal, client_id=client_id,
  263. device_code=str(device["device_code"]), expires_in=max(1, int(deadline - time.monotonic())),
  264. poll_interval=interval, cancelled=is_cancelled)
  265. account_state = _core._account_state_from_token(
  266. token_data, portal_base_url=portal, client_id=client_id, scope=scope_str,
  267. verify=verify, timeout_seconds=timeout_seconds)
  268. except DeviceFlowCancelled:
  269. yield Cancelled()
  270. return
  271. except TimeoutError as exc:
  272. # The code ran out while the token endpoint kept failing (``_poll_device_token_generic`` sets
  273. # the cause): the service was unreachable, not a sign-in left unapproved.
  274. outage = exc.__cause__ if isinstance(exc.__cause__, ConnectionError) else None
  275. yield _failed_from_exception(outage) if outage else TimedOut(detail=str(exc))
  276. return
  277. except Exception as exc:
  278. # The token endpoint's own ``expired_token`` answer is the same timeout as running out the clock.
  279. yield TimedOut(detail=str(exc)) if is_device_code_expired(exc) else _failed_from_exception(exc)
  280. return
  281. guard = persist_guard or _default_persist_guard(is_cancelled)
  282. try:
  283. with open_scope():
  284. with guard() as may_persist:
  285. if may_persist:
  286. _core.persist_nous_credentials(account_state)
  287. if may_persist:
  288. # The handoff runs once the surface's lock is released, never inside it.
  289. handoff = drain()
  290. settled = _core.settle_after_upgrade(account_state)
  291. handoff_status = _handoff_status(handoff, state)
  292. except Exception as exc:
  293. # persist_nous_credentials takes the auth-store lock, writes auth.json, takes the shared
  294. # store's file lock and reseeds the credential pool: a lock timeout or a read-only home
  295. # must not escape next(gen).
  296. yield Failed(reason="", detail=str(exc))
  297. return
  298. if not may_persist: # yielded outside the scope, never across it
  299. yield Cancelled()
  300. return
  301. yield Completed(
  302. email=_account_email(account_state, next((v["account_email"] for v in handoff if v["account_email"]), None)),
  303. model=str(settled.get("model") or ""),
  304. model_changed=bool(settled.get("changed")),
  305. handoff=_handoff_lines(handoff),
  306. handoff_status=handoff_status)