auth_nous.py 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. """Nous Portal OAuth: device-code login, refresh, shared-store mirroring, JWT selection, status.
  2. Split out of ``hermes_cli/auth.py``; origin helpers are imported lazily inside each function
  3. so ``hermes_cli.auth.<name>`` patches still intercept (and no import cycle).
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import hashlib
  8. import json
  9. import os
  10. import threading
  11. import time
  12. import uuid
  13. from contextlib import contextmanager, suppress
  14. from datetime import datetime, timezone, UTC
  15. from pathlib import Path
  16. from typing import TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Optional
  17. from urllib.parse import urlparse
  18. from hermes_cli.auth_codex import _pool_entries
  19. from hermes_cli.auth_constants import (
  20. _decode_jwt_claims, AUTH_LOCK_TIMEOUT_SECONDS, AuthError, DEFAULT_NOUS_CLIENT_ID,
  21. DEFAULT_NOUS_INFERENCE_URL, DEFAULT_NOUS_PORTAL_URL, DEFAULT_NOUS_SCOPE, DEFAULT_NOUS_WELCOME_URL,
  22. DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS, NOUS_AUTH_PATH_INVOKE_JWT, NOUS_BILLING_MANAGE_SCOPE,
  23. NOUS_DEVICE_CODE_SOURCE, NOUS_INFERENCE_INVOKE_SCOPE, NOUS_INVOKE_JWT_MIN_TTL_SECONDS,
  24. WELCOME_CLAIM_FLAG, _nous_err, httpx)
  25. from hermes_cli.guest_handoff import drain, note_replacement, result_lines
  26. if TYPE_CHECKING: # annotation-only; the runtime import would be a cycle
  27. from hermes_cli.auth import ProviderConfig
  28. # Log-record parity with the origin module (caplog tests pin "hermes_cli.auth").
  29. logger = logging.getLogger("hermes_cli.auth")
  30. _UNUSABLE_JWT_RELOGIN = "Re-authenticate with: hermes auth add nous"
  31. def _unusable_invoke_jwt_error(reason: str, *, no_refresh_token: bool = False) -> AuthError:
  32. """Shared ``relogin=True`` error for an access token that is not a usable inference JWT.
  33. With no refresh token the failure is a state-shape one (nothing to redeem), so it carries the
  34. terminal ``nous_auth_missing_refresh_token`` code the pool recognises instead of the JWT
  35. ``reason``, which would bench the row as a transient outage (#113718).
  36. """
  37. detail = " and no refresh token is available" if no_refresh_token else ""
  38. return _nous_err(
  39. f"Nous Portal access token is not a usable inference JWT ({reason}){detail}. "
  40. f"{_UNUSABLE_JWT_RELOGIN}",
  41. "nous_auth_missing_refresh_token" if no_refresh_token else reason, relogin=True)
  42. def _token_fingerprint(token: Any) -> Optional[str]:
  43. """Return a short hash fingerprint for telemetry without leaking token bytes."""
  44. cleaned = token.strip() if isinstance(token, str) else ""
  45. return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()[:12] if cleaned else None
  46. def _oauth_trace(event: str, *, sequence_id: Optional[str] = None, **fields: Any) -> None:
  47. if os.getenv("HERMES_OAUTH_TRACE", "").strip().lower() not in {"1", "true", "yes", "on"}:
  48. return
  49. payload: dict[str, Any] = {"event": event}
  50. if sequence_id:
  51. payload["sequence_id"] = sequence_id
  52. payload.update(fields)
  53. logger.info("oauth_trace %s", json.dumps(payload, sort_keys=True, ensure_ascii=False))
  54. def _iso_after(now: datetime, ttl_seconds: int) -> str:
  55. """ISO timestamp *ttl_seconds* after *now* (UTC)."""
  56. return datetime.fromtimestamp(now.timestamp() + ttl_seconds, tz=UTC).isoformat()
  57. # Nous agent-key slots; a fresh login persists them as None, quarantine strips them.
  58. _NOUS_EMPTY_AGENT_KEY_FIELDS: dict[str, Any] = {
  59. "agent_key": None, "agent_key_id": None, "agent_key_expires_at": None,
  60. "agent_key_expires_in": None, "agent_key_reused": None, "agent_key_obtained_at": None}
  61. _NOUS_STALE_PORTAL_HOSTS: frozenset[str] = frozenset({"api.nousresearch.com"})
  62. def _portal_entitlement_message(capability: str) -> str:
  63. """Portal entitlement notice for *capability* (fresh account data), "" when unavailable."""
  64. from hermes_cli.nous_account import (
  65. format_nous_portal_entitlement_message, get_nous_portal_account_info)
  66. account_info = get_nous_portal_account_info(force_fresh=True)
  67. return format_nous_portal_entitlement_message(account_info, capability=capability) or ""
  68. def _format_nous_entitlement_auth_error(error: AuthError) -> str:
  69. with suppress(Exception):
  70. if message := _portal_entitlement_message("Nous model access"):
  71. return message
  72. return f"{error} Check credits or billing in Nous Portal, then retry."
  73. def _migrate_stale_nous_portal_url(providers: dict[str, Any]) -> None:
  74. nous = providers.get("nous")
  75. if not isinstance(nous, dict):
  76. return
  77. stored = (nous.get("portal_base_url") or "").strip()
  78. if stored and urlparse(stored).hostname in _NOUS_STALE_PORTAL_HOSTS:
  79. logger.warning(
  80. "auth: migrating stale nous portal_base_url %s -> %s", stored, DEFAULT_NOUS_PORTAL_URL)
  81. nous["portal_base_url"] = DEFAULT_NOUS_PORTAL_URL
  82. # Allowlist of hosts the Nous Portal proxy will forward inference JWTs to — a bearer sent anywhere
  83. # else would leak. Consulted only for URLs from the NETWORK side (Portal refresh responses);
  84. # the NOUS_INFERENCE_BASE_URL env override bypasses it (documented dev/staging escape hatch, the
  85. # user set it themselves).
  86. _ALLOWED_NOUS_INFERENCE_HOSTS: frozenset[str] = frozenset({
  87. "inference-api.nousresearch.com",
  88. # Free-tier (anonymous) host: serves the single ``nous/welcome`` model.
  89. "welcome-api.nousresearch.com"})
  90. def _nous_inference_host_allowed(hostname: Optional[str]) -> bool:
  91. """Production hosts always; otherwise only the host the operator named in
  92. ``NOUS_INFERENCE_BASE_URL``.
  93. A non-production Portal's refresh response names that environment's inference gateway. The
  94. Portal-returned value is network provenance, so it does not get bearer-receive authority on
  95. its own — not even for a Nous-owned host: the operator's explicit override is the authority,
  96. and the network value is accepted exactly when it agrees with it. Then the persisted endpoint,
  97. the pricing scope and the proxy all follow the environment the operator chose, and the
  98. per-turn "refusing inference URL host" warning stops.
  99. """
  100. if hostname in _ALLOWED_NOUS_INFERENCE_HOSTS:
  101. return True
  102. if not hostname:
  103. return False
  104. override = _nous_inference_env_override()
  105. return override is not None and urlparse(override).hostname == hostname
  106. def _validate_nous_inference_url_from_network(url: Optional[str]) -> Optional[str]:
  107. """Validate a Portal-returned inference URL against the host allowlist.
  108. Defense-in-depth: a compromised refresh response (MITM, response injection) could otherwise
  109. redirect every proxy request — bearing the user's inference JWT — to an attacker endpoint.
  110. """
  111. cleaned = url.strip() if isinstance(url, str) else ""
  112. if not cleaned:
  113. return None
  114. try:
  115. parsed = urlparse(cleaned)
  116. except Exception:
  117. return None
  118. if parsed.scheme != "https":
  119. logger.warning(
  120. "nous: refusing non-https inference URL scheme %r from Portal response", parsed.scheme)
  121. return None
  122. if not _nous_inference_host_allowed(parsed.hostname):
  123. logger.warning(
  124. "nous: refusing inference URL host %r from Portal response "
  125. "(not in allowlist); falling back to default",
  126. parsed.hostname)
  127. return None
  128. return cleaned.rstrip("/")
  129. def _scoped_operator_override(*names: str) -> Optional[str]:
  130. """The first set operator routing override among ``names`` (``NOUS_INFERENCE_BASE_URL``,
  131. ``HERMES_PORTAL_BASE_URL`` / its ``NOUS_PORTAL_BASE_URL`` alias), resolved through the profile
  132. secret scope, or None.
  133. ``get_secret`` already reads ``os.environ`` for a single-profile process, so the only time it
  134. raises is a multi-profile call that has lost its profile scope. That call has no authority to
  135. route on the launch profile's value — returning the ambient env there would send a secondary's
  136. tokens to the launch profile's Portal or inference host — so the override is simply absent.
  137. Absent is not free: default routing then applies, so a non-production deployment's token is
  138. spent against the production hosts. One WARNING per lost-scope event names the override; the
  139. downstream "ignoring invalid portal_base_url" line never says which caller lost its scope.
  140. """
  141. from agent.secret_scope import UnscopedSecretError, get_secret
  142. try:
  143. for name in names:
  144. value = get_secret(name)
  145. if value:
  146. return value
  147. return None
  148. except UnscopedSecretError:
  149. logger.warning(
  150. "nous: %s unreadable — no profile secret scope on a multiplexed call; treating the "
  151. "override as absent (default routing applies). The caller needs a profile scope binding.",
  152. "/".join(names))
  153. return None
  154. def _nous_inference_env_override() -> Optional[str]:
  155. """User-set ``NOUS_INFERENCE_BASE_URL`` override (trailing slash stripped) or None.
  156. Documented dev/staging escape hatch; the env source is trusted, so unlike Portal-returned URLs
  157. it is intentionally NOT gated by the network host allowlist. Read through the profile-aware
  158. resolver so a multiplexed profile uses its own override and never inherits the default
  159. profile's process-wide value (#65941).
  160. """
  161. from hermes_cli.auth import _optional_base_url
  162. return _optional_base_url(_scoped_operator_override("NOUS_INFERENCE_BASE_URL"))
  163. def _nous_portal_env_override() -> Optional[str]:
  164. """``HERMES_PORTAL_BASE_URL`` / ``NOUS_PORTAL_BASE_URL`` override or None.
  165. Documented dev/staging escape hatch (e.g. hosted agents on the staging Portal). Trusted env
  166. source: must NOT be gated by ``_NOUS_PORTAL_ALLOWED_HOSTS``, which rejects untrusted
  167. NETWORK-provided values persisted to auth.json, not operator config. Read through the
  168. profile secret scope like ``_nous_inference_env_override``: it is reached on every routed
  169. turn (``_nous_effective_routing``), and a raw environ read would POST a multiplexed
  170. secondary's refresh token to the DEFAULT profile's Portal.
  171. """
  172. from hermes_cli.auth import _optional_base_url
  173. return _optional_base_url(_scoped_operator_override("HERMES_PORTAL_BASE_URL", "NOUS_PORTAL_BASE_URL"))
  174. def _nous_portal_base_url(state: dict[str, Any]) -> str:
  175. """HERMES_PORTAL_BASE_URL / NOUS_PORTAL_BASE_URL is the trusted operator override and wins
  176. OUTRIGHT, bypassing the host allowlist (which exists to reject an untrusted network-provided
  177. value, not one the operator configured). Otherwise the stored/default value, allowlist-gated."""
  178. env_portal_override = _nous_portal_env_override()
  179. if env_portal_override:
  180. return env_portal_override.rstrip("/")
  181. from hermes_cli.auth import _NOUS_PORTAL_ALLOWED_HOSTS, _optional_base_url
  182. portal_base_url = _optional_base_url(state.get("portal_base_url")) or DEFAULT_NOUS_PORTAL_URL
  183. portal_base_url = portal_base_url.rstrip("/")
  184. host = urlparse(portal_base_url).hostname
  185. if host and host not in _NOUS_PORTAL_ALLOWED_HOSTS:
  186. logger.warning(
  187. "auth: ignoring invalid portal_base_url %r (host %r not in allowlist), using default",
  188. portal_base_url, host)
  189. return DEFAULT_NOUS_PORTAL_URL
  190. return portal_base_url
  191. def _scope_values(raw_scope: Any) -> set[str]:
  192. # OAuth token responses return a space-separated string; collections are kept for JWT ``scp``
  193. # claims and older stored fixtures.
  194. scopes: set[str] = set()
  195. if isinstance(raw_scope, str):
  196. scopes.update(part for part in raw_scope.replace(",", " ").split() if part.strip())
  197. elif isinstance(raw_scope, (list, tuple, set, frozenset)):
  198. scopes.update(*(_scope_values(item) for item in raw_scope if isinstance(item, str)))
  199. return scopes
  200. def _nous_invoke_jwt_status(
  201. token: Any, *, scope: Any = None, expires_at: Any = None,
  202. min_ttl_seconds: int = NOUS_INVOKE_JWT_MIN_TTL_SECONDS) -> Optional[str]:
  203. """Return None when the token can be used for inference, else a reason."""
  204. from hermes_cli.auth import _is_expiring
  205. claims = _decode_jwt_claims(token)
  206. if not claims:
  207. return "access_token_not_jwt"
  208. scopes = (_scope_values(scope) | _scope_values(claims.get("scope"))
  209. | _scope_values(claims.get("scp")))
  210. if NOUS_INFERENCE_INVOKE_SCOPE not in scopes:
  211. return "missing_inference_invoke_scope"
  212. exp = claims.get("exp")
  213. skew = max(0, int(min_ttl_seconds))
  214. if isinstance(exp, (int, float)):
  215. return "invoke_jwt_expiring" if float(exp) <= (time.time() + skew) else None
  216. return "invoke_jwt_expiry_unknown_or_expiring" if _is_expiring(expires_at, skew) else None
  217. def _nous_invoke_jwt_is_usable(
  218. token: Any, *, scope: Any = None, expires_at: Any = None,
  219. min_ttl_seconds: int = NOUS_INVOKE_JWT_MIN_TTL_SECONDS) -> bool:
  220. from hermes_cli.auth import _nous_invoke_jwt_status
  221. return _nous_invoke_jwt_status(
  222. token, scope=scope, expires_at=expires_at, min_ttl_seconds=min_ttl_seconds) is None
  223. def _state_invoke_jwt_status(state: dict[str, Any], token: Any) -> Optional[str]:
  224. """``_nous_invoke_jwt_status`` for *token* using *state*'s scope / expires_at (patchable)."""
  225. from hermes_cli.auth import _nous_invoke_jwt_status
  226. return _nous_invoke_jwt_status(
  227. token, scope=state.get("scope"), expires_at=state.get("expires_at"))
  228. def _assert_nous_inference_jwt_usable(state: dict[str, Any], *, access_token: Any = None) -> None:
  229. token = state.get("access_token") if access_token is None else access_token
  230. reason = _state_invoke_jwt_status(state, token)
  231. if reason is not None:
  232. raise _unusable_invoke_jwt_error(reason)
  233. def _remaining_ttl(expires_at: Any, fallback_expires_in: Any) -> int:
  234. """Seconds until *expires_at* (ISO), else *fallback_expires_in* coerced to a TTL."""
  235. from hermes_cli.auth import _coerce_ttl_seconds, _parse_iso_timestamp
  236. expires_epoch = _parse_iso_timestamp(expires_at)
  237. if expires_epoch is not None:
  238. return max(0, int(expires_epoch - time.time()))
  239. return _coerce_ttl_seconds(fallback_expires_in)
  240. def _nous_jwt_expires_at(token: Any, fallback_expires_at: Any = None) -> Optional[str]:
  241. claims = _decode_jwt_claims(token)
  242. exp = claims.get("exp")
  243. if isinstance(exp, (int, float)):
  244. with suppress(Exception):
  245. return datetime.fromtimestamp(float(exp), tz=UTC).isoformat()
  246. return fallback_expires_at if isinstance(fallback_expires_at, str) else None
  247. def _set_nous_agent_key_from_invoke_jwt(
  248. state: dict[str, Any], *, obtained_at: Optional[str] = None) -> None:
  249. from hermes_cli.auth import _nonempty_str
  250. access_token = state.get("access_token")
  251. if not _nonempty_str(access_token):
  252. return
  253. existing_obtained_at = state.get("agent_key_obtained_at")
  254. if not obtained_at:
  255. reuse = state.get("agent_key") == access_token and _nonempty_str(existing_obtained_at)
  256. obtained_at = existing_obtained_at if reuse else datetime.now(UTC).isoformat()
  257. expires_at = _nous_jwt_expires_at(access_token, state.get("expires_at"))
  258. expires_in = _remaining_ttl(expires_at, state.get("expires_in"))
  259. if expires_at:
  260. state["expires_at"] = expires_at
  261. state["expires_in"] = expires_in
  262. state.update(
  263. agent_key=access_token, agent_key_id=None, agent_key_expires_at=expires_at,
  264. agent_key_expires_in=expires_in, agent_key_reused=False, agent_key_obtained_at=obtained_at)
  265. def _select_nous_invoke_jwt(
  266. state: dict[str, Any], *, access_token: Any = None, sequence_id: Optional[str] = None) -> None:
  267. from hermes_cli.auth import _nonempty_str
  268. if _nonempty_str(access_token):
  269. state["access_token"] = access_token
  270. _set_nous_agent_key_from_invoke_jwt(state)
  271. logger.debug("Nous inference auth: using NAS invoke JWT")
  272. _oauth_trace(
  273. "nous_invoke_jwt_selected", sequence_id=sequence_id,
  274. access_token_fp=_token_fingerprint(state.get("access_token")))
  275. # Derived from expires_at/JWT exp and tick down between reads; persisting only these changes makes
  276. # auth.json noisy and defeats the mtime-keyed auth-status cache.
  277. _NOUS_EFFECTIVE_STATE_IGNORED_KEYS = frozenset({"expires_in", "agent_key_expires_in"})
  278. def _nous_effective_provider_state(state: dict[str, Any]) -> dict[str, Any]:
  279. return {k: v for k, v in state.items() if k not in _NOUS_EFFECTIVE_STATE_IGNORED_KEYS}
  280. NOUS_SHARED_STORE_FILENAME = "nous_auth.json"
  281. _nous_shared_lock_holder = threading.local()
  282. def _nous_shared_auth_dir() -> Path:
  283. """Directory of the shared Nous token store: ``HERMES_SHARED_AUTH_DIR`` or ``<root>/shared/``.
  284. Outside any named profile so all profiles share it (``hermes --profile X auth add nous --type
  285. oauth`` one-tap imports it). Written on login AND every runtime refresh so the refresh_token
  286. stays current across profiles; a stale token just falls back to device-code.
  287. """
  288. override = os.getenv("HERMES_SHARED_AUTH_DIR", "").strip()
  289. if override:
  290. return Path(override).expanduser()
  291. from hermes_constants import get_default_hermes_root
  292. return get_default_hermes_root() / "shared"
  293. def _nous_shared_store_path() -> Path:
  294. path = _nous_shared_auth_dir() / NOUS_SHARED_STORE_FILENAME
  295. # Seat belt (mirrors the _auth_file_path() guard): under pytest, refuse a path under the real
  296. # user's Hermes root so a test that forgot HERMES_SHARED_AUTH_DIR fails loudly instead of
  297. # corrupting cross-profile state.
  298. if os.environ.get("PYTEST_CURRENT_TEST"):
  299. from hermes_constants import get_default_hermes_root
  300. real_home_shared = (
  301. get_default_hermes_root() / "shared" / NOUS_SHARED_STORE_FILENAME).resolve(strict=False)
  302. try:
  303. resolved = path.resolve(strict=False)
  304. except Exception:
  305. resolved = path
  306. if resolved == real_home_shared:
  307. raise RuntimeError(
  308. f"Refusing to touch real user shared Nous auth store during test run: "
  309. f"{path}. Set HERMES_SHARED_AUTH_DIR to a tmp_path in your test fixture.")
  310. return path
  311. @contextmanager
  312. def _nous_shared_store_lock(timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS):
  313. """Cross-profile lock for the shared Nous OAuth store.
  314. Lock ordering invariant: if both this and ``_auth_store_lock`` need to be held, acquire
  315. ``_auth_store_lock`` FIRST. All runtime refresh paths follow this order.
  316. """
  317. from hermes_cli.auth import _file_lock
  318. try:
  319. lock_path = _nous_shared_store_path().with_suffix(".lock")
  320. except RuntimeError:
  321. yield # No HERMES_HOME yet (pre-setup): fall through without locking.
  322. return
  323. with _file_lock(
  324. lock_path, _nous_shared_lock_holder, timeout_seconds,
  325. f"Timed out waiting for shared Nous auth lock ({lock_path})"):
  326. yield
  327. def _shared_lock_timeout(timeout_seconds: float) -> float:
  328. return max(timeout_seconds + 5.0, AUTH_LOCK_TIMEOUT_SECONDS)
  329. # OAuth fields mirrored between a profile's Nous state and the shared cross-profile store.
  330. _NOUS_SHARED_STATE_KEYS = (
  331. "access_token", "refresh_token", "token_type", "scope", "client_id", "portal_base_url",
  332. "inference_base_url", "obtained_at", "expires_at",
  333. # Guest (``auth_method: anonymous``) identity: the ``anon_`` credential is the refresh material.
  334. "auth_method", "account_tier", "anon_token", "user_id", "org_id")
  335. # Shared-store key: an account's latest refresh, kept beside a different identity the store holds.
  336. _SHARED_RENEWAL_KEY = "renewal"
  337. def _nous_state_order(a: dict[str, Any], b: dict[str, Any]) -> Optional[int]:
  338. """1 when *a* holds the later-ISSUED token pair than *b*, -1 the earlier, 0 tied, None unstamped.
  339. The forked-grant heal's ordering (``auth_oauth_grants.oauth_pair_order``): JWT ``iat``, then
  340. ``obtained_at`` (which also breaks an equal whole-second ``iat``); expiry only orders states
  341. lacking an issue stamp, since a later rotation can carry a shorter TTL.
  342. A side stamped only by expiry against one stamped only by issue time is a tie (no adopt, no
  343. push); JWT states carry both claims, so they always order.
  344. """
  345. from hermes_cli.auth_oauth_grants import oauth_pair_order
  346. return oauth_pair_order(a, b)
  347. def _same_known_nous_identity(a: dict[str, Any], b: dict[str, Any]) -> bool:
  348. """True when *a* and *b* are provably the same identity. An account whose access token carries no
  349. JWT ``sub`` is UNKNOWN, never "the same" as another unknown one."""
  350. identity = _nous_identity(a)
  351. return identity[1] not in (None, "") and identity == _nous_identity(b)
  352. def _merge_shared_nous_oauth_state(state: dict[str, Any]) -> bool:
  353. """Adopt the shared store's OAuth tokens into a profile-local Nous state when they are NEWER.
  354. An older shared copy (a failed shared write after this profile refreshed) never overwrites the
  355. profile: its refresh token is already redeemed, and replaying it trips the Portal's reuse
  356. detection (forced re-login). When the profile is the newer one it is pushed to the shared
  357. store instead, so sibling profiles stop reading the stale copy. Caller holds the shared lock.
  358. """
  359. from hermes_cli.auth import _nonempty_str, _read_shared_nous_state
  360. shared = _read_shared_nous_state() or {}
  361. renewed = shared.get(_SHARED_RENEWAL_KEY)
  362. if isinstance(renewed, dict) and _nous_identity(renewed) == _nous_identity(state):
  363. shared = renewed
  364. shared_refresh = shared.get("refresh_token")
  365. if not _nonempty_str(shared_refresh):
  366. return False # a free-tier identity has no refresh token; nothing to merge into an OAuth state
  367. refresh_changed = shared_refresh.strip() != str(state.get("refresh_token") or "").strip()
  368. order = _nous_state_order(shared, state)
  369. # A quarantined profile has no access token, so its identity reads as unknown: it must still
  370. # recover from a sibling's re-login (ca6513542d5), so an empty profile adopts on order alone.
  371. known_same = _same_known_nous_identity(shared, state)
  372. same = known_same or not _nonempty_str(state.get("access_token"))
  373. # Unstamped on both sides: no evidence either way, keep the legacy "a different token wins".
  374. # Never across identities: a profile signed in as one account keeps it (profiles are islands).
  375. if not (same and (order == 1 or (order is None and refresh_changed))):
  376. if order == -1 and refresh_changed and known_same:
  377. _oauth_trace(
  378. "nous_shared_store_older_than_profile",
  379. shared_refresh_token_fp=_token_fingerprint(shared_refresh),
  380. refresh_token_fp=_token_fingerprint(state.get("refresh_token")))
  381. _write_shared_nous_state(state, renewal=True)
  382. return False
  383. for key in _NOUS_SHARED_STATE_KEYS:
  384. value = shared.get(key)
  385. if value not in {None, ""}:
  386. state[key] = value
  387. return True
  388. def _nous_shared_shape(src: dict[str, Any]) -> dict[str, Any]:
  389. """The defaulted OAuth core (tokens + routing + expiry) shared across profiles."""
  390. return {
  391. "access_token": src.get("access_token"), "refresh_token": src.get("refresh_token"),
  392. "token_type": src.get("token_type") or "Bearer",
  393. "scope": src.get("scope") or DEFAULT_NOUS_SCOPE,
  394. "client_id": src.get("client_id") or DEFAULT_NOUS_CLIENT_ID,
  395. "portal_base_url": src.get("portal_base_url") or DEFAULT_NOUS_PORTAL_URL,
  396. # A guest's route defaults to the welcome host: the paid host cross-refuses its JWT.
  397. "inference_base_url": src.get("inference_base_url") or (
  398. DEFAULT_NOUS_WELCOME_URL if src.get("auth_method") == "anonymous" else DEFAULT_NOUS_INFERENCE_URL),
  399. "obtained_at": src.get("obtained_at"), "expires_at": src.get("expires_at"),
  400. # WELCOME_CLAIM_FLAG travels too: an adopted connector guest that lost it would read as pre-trial.
  401. **{k: src[k] for k in ("auth_method", "account_tier", "anon_token", "user_id", "org_id", "connectors_token",
  402. WELCOME_CLAIM_FLAG)
  403. if src.get(k) not in (None, "")}}
  404. def _nous_identity(state: dict[str, Any]) -> tuple[str, Any]:
  405. """Who a Nous state is: the guest's ``anon_`` credential, else the account's JWT subject (which,
  406. unlike the refresh token, survives a refresh)."""
  407. from hermes_cli.anon_auth import is_guest_state
  408. if is_guest_state(state):
  409. return "guest", state.get("anon_token")
  410. return "account", _decode_jwt_claims(state.get("access_token")).get("sub")
  411. def _shared_copy_is_newer(held: Optional[dict[str, Any]], state: dict[str, Any], *, same: bool) -> bool:
  412. """True when the shared store already holds a NEWER copy of *state*'s account (a renewal never
  413. rolls it back to an older, possibly already-redeemed refresh token)."""
  414. from hermes_cli.anon_auth import is_guest_state
  415. if held is None or is_guest_state(state):
  416. return False
  417. copy = held if same else held.get(_SHARED_RENEWAL_KEY)
  418. if not isinstance(copy, dict) or not _same_known_nous_identity(copy, state):
  419. return False
  420. return _nous_state_order(copy, state) == 1
  421. def _write_shared_nous_state(state: dict[str, Any], *, renewal: bool) -> None:
  422. """Persist a minimal copy of the Nous OAuth state to the shared store.
  423. The store holds one identity, which profiles adopt or import. Only a sign-in (or a mint) changes
  424. it, so only a sign-in can replace a guest there. A *renewal* (a token refresh) of another
  425. identity is kept beside it under ``renewal``: siblings on that account read their next
  426. single-use refresh token from there (``_merge_shared_nous_oauth_state``).
  427. Best-effort: failures are logged and swallowed; per-profile auth.json stays the source of truth.
  428. """
  429. from hermes_cli.auth import _nonempty_str, _save_private_json
  430. refresh_token = state.get("refresh_token")
  431. # Nothing worth sharing without refresh material: an OAuth refresh_token (with its access token),
  432. # or a guest's anon_ credential, which is the whole identity and may not have been exchanged yet.
  433. is_guest = _nonempty_str(state.get("anon_token"))
  434. if not is_guest and not (_nonempty_str(refresh_token) and _nonempty_str(state.get("access_token"))):
  435. return
  436. shared = {
  437. "_schema": 1, **_nous_shared_shape(state),
  438. "updated_at": datetime.now(UTC).isoformat()}
  439. try:
  440. with _nous_shared_store_lock():
  441. path = _nous_shared_store_path()
  442. held = _read_shared_nous_state()
  443. same = held is not None and _nous_identity(held) == _nous_identity(state)
  444. if renewal and _shared_copy_is_newer(held, state, same=same):
  445. _oauth_trace(
  446. "nous_shared_store_write_skipped_older", path=str(path),
  447. refresh_token_fp=_token_fingerprint(refresh_token))
  448. return
  449. if renewal and held is not None and not same:
  450. shared = {**held, _SHARED_RENEWAL_KEY: _nous_shared_shape(state)}
  451. else:
  452. note_replacement(held, state)
  453. if same and _SHARED_RENEWAL_KEY in held:
  454. shared[_SHARED_RENEWAL_KEY] = held[_SHARED_RENEWAL_KEY]
  455. _save_private_json(path, shared, sort_keys=True)
  456. _oauth_trace(
  457. "nous_shared_store_written", path=str(path),
  458. refresh_token_fp=_token_fingerprint(refresh_token))
  459. except Exception as exc:
  460. logger.debug("Failed to write shared Nous auth store: %s", exc)
  461. def _read_shared_nous_state() -> Optional[dict[str, Any]]:
  462. """Shared Nous OAuth state when present and well-formed, else None.
  463. None (missing / unreadable / malformed / lacking tokens) means "fall through to device-code".
  464. """
  465. from hermes_cli.auth import _nonempty_str
  466. try:
  467. path = _nous_shared_store_path()
  468. except RuntimeError:
  469. return None # Test seat belt tripped — treat as missing
  470. if not path.is_file():
  471. return None
  472. try:
  473. payload = json.loads(path.read_text(encoding="utf-8-sig"))
  474. except (OSError, ValueError) as exc:
  475. logger.debug("Shared Nous auth store at %s is unreadable: %s", path, exc)
  476. return None
  477. if not isinstance(payload, dict):
  478. return None
  479. has_tokens = _nonempty_str(payload.get("anon_token")) or (
  480. _nonempty_str(payload.get("access_token")) and _nonempty_str(payload.get("refresh_token")))
  481. return payload if has_tokens else None
  482. def _clear_shared_nous_state(reason: str) -> None:
  483. """Remove the shared Nous OAuth store after a terminal token failure."""
  484. try:
  485. with _nous_shared_store_lock():
  486. _nous_shared_store_path().unlink(missing_ok=True)
  487. _oauth_trace("nous_shared_store_cleared", reason=reason)
  488. except Exception as exc:
  489. logger.debug("Failed to clear shared Nous auth store: %s", exc)
  490. def _quarantine_forensics(state: dict[str, Any], error: AuthError, reason: str) -> dict[str, Any]:
  491. """Redaction-safe forensic record for a quarantine: fingerprints, sizes and booleans only.
  492. NEVER include a raw token/agent_key (credential-shaped literals get corrupted in logs). The
  493. 12-char SHA-256 prefix correlates to NAS's refreshTokenHash without leaking the secret;
  494. provenance is client_id + agent_key_id (Nous state has no session_id).
  495. """
  496. from hermes_cli.auth import _auth_file_path
  497. forensic: dict[str, Any] = {
  498. "reason": reason, "error_code": error.code, "client_id": state.get("client_id"),
  499. "agent_key_id": state.get("agent_key_id"),
  500. "refresh_token_fp": _token_fingerprint(state.get("refresh_token"))}
  501. # On-disk integrity of the auth store at the moment of quarantine.
  502. try:
  503. auth_path = _auth_file_path()
  504. forensic["auth_json_path"] = str(auth_path)
  505. try:
  506. st = os.stat(auth_path)
  507. forensic.update(
  508. auth_json_size=st.st_size, auth_json_mtime=st.st_mtime, auth_json_exists=True)
  509. except FileNotFoundError:
  510. forensic["auth_json_exists"] = False
  511. except Exception as exc: # pragma: no cover - never let logging break quarantine
  512. forensic["auth_json_stat_error"] = repr(exc)
  513. # Was the token already past its own expiry when it was rejected?
  514. already_expired: Optional[bool] = None
  515. expires_at_raw = state.get("expires_at")
  516. if isinstance(expires_at_raw, str) and expires_at_raw:
  517. try:
  518. parsed = datetime.fromisoformat(expires_at_raw)
  519. already_expired = (parsed.replace(tzinfo=parsed.tzinfo or UTC)
  520. < datetime.now(UTC))
  521. except ValueError:
  522. already_expired = None
  523. forensic["token_already_expired"] = already_expired
  524. return forensic
  525. def _quarantine_nous_oauth_state(state: dict[str, Any], error: AuthError, *, reason: str) -> None:
  526. """Keep routing metadata but remove dead OAuth material so it is not replayed.
  527. Only for terminal errors (``*_refresh_failed`` = HTTP 400/401/403 invalid_grant / revoked /
  528. refresh_token_reused; ``*_auth_missing_refresh_token``), all ``relogin_required=True`` —
  529. transient 429/5xx never quarantine.
  530. """
  531. from hermes_cli.auth import (
  532. _FLAT_OAUTH_TOKEN_KEYS, _last_auth_error_marker, invalidate_nous_auth_status_cache)
  533. # Forensics BEFORE clearing token material: a hosted agent quarantined here is otherwise only
  534. # visible as a later "No access token found" WARNING, too late to root-cause. Managed log
  535. # drains may be WARNING-only, so this MUST be logger.warning.
  536. logger.warning(
  537. "Nous OAuth state quarantined (terminal auth death): %s",
  538. json.dumps(_quarantine_forensics(state, error, reason), sort_keys=True, ensure_ascii=False))
  539. for key in (*_FLAT_OAUTH_TOKEN_KEYS, *_NOUS_EMPTY_AGENT_KEY_FIELDS):
  540. state.pop(key, None)
  541. state["last_auth_error"] = _last_auth_error_marker("nous", error, reason=reason)
  542. _clear_shared_nous_state(reason)
  543. invalidate_nous_auth_status_cache()
  544. def _quarantine_nous_pool_entries(
  545. auth_store: dict[str, Any], error: AuthError, *, reason: str) -> bool:
  546. """Remove singleton-seeded Nous pool entries that contain dead OAuth state."""
  547. entries = _pool_entries(auth_store, "nous")
  548. if entries is None:
  549. return False
  550. singleton_sources = {NOUS_DEVICE_CODE_SOURCE, f"manual:{NOUS_DEVICE_CODE_SOURCE}"}
  551. retained = [
  552. e for e in entries if not (isinstance(e, dict) and e.get("source") in singleton_sources)]
  553. removed = len(retained) != len(entries)
  554. if removed:
  555. auth_store["credential_pool"]["nous"] = retained
  556. _oauth_trace("nous_pool_device_code_quarantined", reason=reason, error_code=error.code)
  557. return removed
  558. def _try_import_shared_nous_state(*, timeout_seconds: float = 15.0) -> Optional[dict[str, Any]]:
  559. """Rehydrate Nous OAuth state from the shared store via a forced refresh.
  560. Returns auth_state ready for ``persist_nous_credentials()``; None on any failure (expired
  561. token, portal unreachable) so the caller falls through to device-code.
  562. """
  563. from hermes_cli.auth import (
  564. _read_shared_nous_state, _write_shared_nous_state, refresh_nous_oauth_from_state,
  565. _is_terminal_nous_refresh_error)
  566. try:
  567. with _nous_shared_store_lock(timeout_seconds=_shared_lock_timeout(timeout_seconds)):
  568. shared = _read_shared_nous_state()
  569. if not shared:
  570. return None
  571. # Full state dict so refresh_nous_oauth_from_state has every field it needs.
  572. state: dict[str, Any] = {
  573. **_nous_shared_shape(shared), "agent_key": None, "agent_key_expires_at": None,
  574. "tls": {"insecure": False, "ca_bundle": None}}
  575. refreshed = refresh_nous_oauth_from_state(
  576. state, timeout_seconds=timeout_seconds, force_refresh=True,
  577. on_state_update=lambda updated, _reason: _write_shared_nous_state(updated, renewal=True))
  578. _write_shared_nous_state(refreshed, renewal=True)
  579. except Exception as exc:
  580. is_auth = isinstance(exc, AuthError)
  581. _oauth_trace(
  582. "nous_shared_import_failed", error_type=type(exc).__name__,
  583. **({"error_code": getattr(exc, "code", None)} if is_auth else {}))
  584. if is_auth and _is_terminal_nous_refresh_error(exc):
  585. _clear_shared_nous_state("shared_import_terminal_refresh_failure")
  586. logger.debug("Shared Nous import failed: %s", exc)
  587. return None
  588. return refreshed
  589. def _refresh_access_token(
  590. *, client: httpx.Client, portal_base_url: str, client_id: str, refresh_token: str,
  591. ) -> dict[str, Any]:
  592. response = client.post(
  593. f"{portal_base_url}/api/oauth/token",
  594. headers={"x-nous-refresh-token": refresh_token},
  595. data={"grant_type": "refresh_token", "client_id": client_id})
  596. if response.status_code == 200:
  597. payload = response.json()
  598. if "access_token" not in payload:
  599. raise _nous_err("Refresh response missing access_token", "invalid_token", relogin=True)
  600. return payload
  601. if 500 <= response.status_code <= 599:
  602. raise AuthError(
  603. f"Nous Portal is temporarily unavailable (HTTP {response.status_code}).",
  604. provider="nous", code="temporarily_unavailable", retryable=True)
  605. # Vercel's Security Checkpoint in front of the Portal answers non-browser clients with a
  606. # 403 (``x-vercel-mitigated: deny``) or 429 (``challenge``) page (#120602). That is the edge
  607. # refusing the request, not the token endpoint rejecting the grant, so keep the credentials
  608. # instead of forcing a re-login.
  609. mitigated = response.headers.get("x-vercel-mitigated") if response.status_code in {403, 429} else None
  610. if mitigated:
  611. from agent.retry_utils import parse_retry_after_seconds
  612. raise AuthError(
  613. f"Nous Portal's edge firewall challenged the token refresh (HTTP {response.status_code}, "
  614. f"x-vercel-mitigated={mitigated}). Credentials kept; try again shortly.",
  615. provider="nous", code="upstream_blocked", retryable=True,
  616. retry_after=parse_retry_after_seconds(response.headers))
  617. from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODES
  618. try:
  619. error_payload = response.json()
  620. except Exception:
  621. error_payload = {}
  622. if not isinstance(error_payload, dict):
  623. error_payload = {}
  624. # Only an explicit OAuth grant-dead code is terminal: a 429/404 gateway body without an
  625. # ``error`` key says nothing about the refresh token, so it must not wipe credentials.
  626. # A 401/403 without an ``error`` code still means the token endpoint rejected the refresh
  627. # token, so it is reported as ``invalid_grant`` (terminal) rather than left unclassified.
  628. raw_code = error_payload.get("error")
  629. if raw_code is None and response.status_code in {401, 403}:
  630. raw_code = "invalid_grant"
  631. code = None if raw_code is None else str(raw_code)
  632. description = str(error_payload.get("error_description") or "Refresh token exchange failed")
  633. relogin = code in _OAUTH_GRANT_DEAD_CODES
  634. # OAuth 2.1 "refresh token reuse": an external process (health check, monitoring tool, custom
  635. # self-heal hook) redeemed Hermes's refresh_token without persisting the rotated token, so the
  636. # server retired the original and revoked the whole session chain as a token-theft signal.
  637. if code == "refresh_token_reused" or "reuse" in description.lower():
  638. description = (
  639. "Nous Portal detected refresh-token reuse and revoked this session.\n"
  640. "This usually means an external process (monitoring script, "
  641. "custom self-heal hook, or another Hermes install sharing "
  642. "~/.hermes/auth.json) called POST /api/oauth/token with Hermes's "
  643. "refresh token without persisting the rotated token back.\n"
  644. "Nous refresh tokens are single-use — only Hermes may call the "
  645. "refresh endpoint. For health checks, use `hermes auth status` "
  646. "instead.\n"
  647. "Re-authenticate with: hermes auth add nous")
  648. relogin = True
  649. raise _nous_err(description, code, relogin=relogin)
  650. def _refresh_nous_or_quarantine(
  651. *, client: httpx.Client, auth_store: dict[str, Any], state: dict[str, Any],
  652. portal_base_url: str, client_id: str, refresh_token: str, reason: str,
  653. persist: Callable[[], None]) -> dict[str, Any]:
  654. """Redeem the refresh token; on terminal failure quarantine state + pool, persist, re-raise."""
  655. from hermes_cli.auth import _refresh_access_token, _is_terminal_nous_refresh_error
  656. try:
  657. return _refresh_access_token(
  658. client=client, portal_base_url=portal_base_url, client_id=client_id,
  659. refresh_token=refresh_token)
  660. except AuthError as exc:
  661. if _is_terminal_nous_refresh_error(exc):
  662. _quarantine_nous_oauth_state(state, exc, reason=reason)
  663. _quarantine_nous_pool_entries(auth_store, exc, reason=reason)
  664. persist()
  665. raise
  666. def _apply_nous_refreshed_tokens(
  667. state: dict[str, Any], refreshed: dict[str, Any], refresh_token: str, *,
  668. inference_base_url: Optional[str] = None) -> None:
  669. """Write a successful Nous token-refresh payload into *state* (tokens + expiry fields).
  670. *inference_base_url*, when given, is the healed network-provenance URL to persist alongside
  671. the rotated tokens (key order in auth.json is preserved from the original login shape).
  672. """
  673. from hermes_cli.auth import _coerce_ttl_seconds
  674. now = datetime.now(UTC)
  675. access_ttl = _coerce_ttl_seconds(refreshed.get("expires_in"))
  676. state["access_token"] = refreshed["access_token"]
  677. state["refresh_token"] = refreshed.get("refresh_token") or refresh_token
  678. state["token_type"] = refreshed.get("token_type") or state.get("token_type") or "Bearer"
  679. state["scope"] = refreshed.get("scope") or state.get("scope")
  680. if inference_base_url is not None:
  681. state["inference_base_url"] = inference_base_url
  682. state["obtained_at"] = now.isoformat()
  683. state["expires_in"] = access_ttl
  684. state["expires_at"] = _iso_after(now, access_ttl)
  685. def _healed_nous_inference_url(refreshed: dict[str, Any]) -> str:
  686. """Validated network-provenance inference URL from a refresh payload, healed to the default.
  687. A Portal URL rejected by the allowlist resets to the production default instead of leaving a
  688. previously-persisted bad host (e.g. a stale staging URL) in place — otherwise a poisoned
  689. auth.json re-validates to None on every refresh and silently re-uses the dead endpoint.
  690. """
  691. url = _validate_nous_inference_url_from_network(refreshed.get("inference_base_url"))
  692. return url or DEFAULT_NOUS_INFERENCE_URL
  693. def _nous_http_client(timeout_seconds: float, verify: Any) -> httpx.Client:
  694. return httpx.Client(
  695. timeout=httpx.Timeout(timeout_seconds), headers={"Accept": "application/json"},
  696. verify=verify)
  697. def _model_priority(mid: str) -> tuple:
  698. """Sort key: opus > pro > haiku/flash > sonnet (sonnet is cheap/fast; best model first)."""
  699. low = mid.lower()
  700. rank = (0 if "opus" in low else 1 if "pro" in low and "sonnet" not in low
  701. else 3 if "sonnet" in low else 2)
  702. return (rank, mid)
  703. def fetch_nous_models(
  704. *, inference_base_url: str, api_key: str, timeout_seconds: float = 15.0,
  705. verify: bool | str = True) -> list[str]:
  706. """Fetch available model IDs from the Nous inference API."""
  707. from hermes_cli.auth import _nonempty_str
  708. with _nous_http_client(timeout_seconds, verify) as client:
  709. response = client.get(
  710. f"{inference_base_url.rstrip('/')}/models",
  711. headers={"Authorization": f"Bearer {api_key}"})
  712. if response.status_code != 200:
  713. description = f"/models request failed with status {response.status_code}"
  714. try:
  715. err = response.json()
  716. description = str(err.get("error_description") or err.get("error") or description)
  717. except Exception as e:
  718. logger.debug("Could not parse error response JSON: %s", e)
  719. raise _nous_err(description, "models_fetch_failed")
  720. data = response.json().get("data")
  721. if not isinstance(data, list):
  722. return []
  723. model_ids: list[str] = []
  724. for item in data:
  725. model_id = item.get("id") if isinstance(item, dict) else None
  726. # Hermes models aren't reliable for agentic tool-calling
  727. if _nonempty_str(model_id) and "hermes" not in model_id.lower():
  728. model_ids.append(model_id.strip())
  729. model_ids.sort(key=_model_priority)
  730. return list(dict.fromkeys(model_ids))
  731. def _agent_key_is_usable(state: dict[str, Any], min_ttl_seconds: int) -> bool:
  732. from hermes_cli.auth import _nonempty_str
  733. key = state.get("agent_key")
  734. return _nonempty_str(key) and _nous_invoke_jwt_is_usable(
  735. key, scope=state.get("scope"), expires_at=state.get("agent_key_expires_at"),
  736. min_ttl_seconds=max(0, int(min_ttl_seconds)))
  737. def refresh_nous_oauth_pure(
  738. access_token: str, refresh_token: str, client_id: str, portal_base_url: str,
  739. inference_base_url: str, *, token_type: str = "Bearer", scope: str = DEFAULT_NOUS_SCOPE,
  740. obtained_at: Optional[str] = None, expires_at: Optional[str] = None,
  741. agent_key: Optional[str] = None, agent_key_expires_at: Optional[str] = None,
  742. timeout_seconds: float = 15.0, insecure: Optional[bool] = None, ca_bundle: Optional[str] = None,
  743. force_refresh: bool = False,
  744. on_state_update: Optional[Callable[[dict[str, Any], str], None]] = None) -> dict[str, Any]:
  745. """Refresh Nous OAuth state without mutating auth.json directly.
  746. ``on_state_update`` fires after a successful access-token refresh so callers owning persistent
  747. state can save the rotated refresh token before later validation can fail.
  748. """
  749. return refresh_nous_oauth_from_state(
  750. {
  751. "access_token": access_token, "refresh_token": refresh_token, "client_id": client_id,
  752. "portal_base_url": portal_base_url, "inference_base_url": inference_base_url,
  753. "token_type": token_type, "scope": scope, "obtained_at": obtained_at,
  754. "expires_at": expires_at, "agent_key": agent_key,
  755. "agent_key_expires_at": agent_key_expires_at,
  756. "tls": {"insecure": insecure, "ca_bundle": ca_bundle}},
  757. timeout_seconds=timeout_seconds, force_refresh=force_refresh,
  758. on_state_update=on_state_update)
  759. def refresh_nous_oauth_from_state(
  760. src: dict[str, Any], *, timeout_seconds: float = 15.0, force_refresh: bool = False,
  761. on_state_update: Optional[Callable[[dict[str, Any], str], None]] = None) -> dict[str, Any]:
  762. """Refresh Nous OAuth from a state dict (defaults filled in) without mutating auth.json."""
  763. from hermes_cli.auth import (
  764. _assert_nous_inference_jwt_usable, _refresh_access_token, _resolve_verify,
  765. _select_nous_invoke_jwt)
  766. tls = src.get("tls") or {}
  767. insecure, ca_bundle = tls.get("insecure"), tls.get("ca_bundle")
  768. state: dict[str, Any] = {
  769. "access_token": src.get("access_token", ""), "refresh_token": src.get("refresh_token", ""),
  770. "client_id": src.get("client_id") or DEFAULT_NOUS_CLIENT_ID,
  771. "portal_base_url": (src.get("portal_base_url") or DEFAULT_NOUS_PORTAL_URL).rstrip("/"),
  772. "inference_base_url": (
  773. src.get("inference_base_url") or DEFAULT_NOUS_INFERENCE_URL).rstrip("/"),
  774. "token_type": src.get("token_type") or "Bearer",
  775. "scope": src.get("scope") or DEFAULT_NOUS_SCOPE,
  776. "obtained_at": src.get("obtained_at"), "expires_at": src.get("expires_at"),
  777. "agent_key": src.get("agent_key"), "agent_key_expires_at": src.get("agent_key_expires_at"),
  778. "tls": {"insecure": bool(insecure), "ca_bundle": ca_bundle}}
  779. verify = _resolve_verify(insecure=insecure, ca_bundle=ca_bundle, auth_state=state)
  780. with _nous_http_client(timeout_seconds or 15.0, verify) as client:
  781. current_invoke_jwt_status = _state_invoke_jwt_status(state, state.get("access_token"))
  782. if force_refresh or current_invoke_jwt_status is not None:
  783. refresh_token_value = state.get("refresh_token")
  784. if not isinstance(refresh_token_value, str) or not refresh_token_value:
  785. if current_invoke_jwt_status is not None:
  786. raise _unusable_invoke_jwt_error(
  787. current_invoke_jwt_status, no_refresh_token=True)
  788. raise _nous_err(
  789. "No refresh token is available for Nous Portal.", "nous_auth_missing_refresh_token",
  790. relogin=True)
  791. refreshed = _refresh_access_token(
  792. client=client, portal_base_url=state["portal_base_url"],
  793. client_id=state["client_id"], refresh_token=refresh_token_value)
  794. _apply_nous_refreshed_tokens(
  795. state, refreshed, refresh_token_value,
  796. inference_base_url=_healed_nous_inference_url(refreshed))
  797. if on_state_update is not None:
  798. on_state_update(dict(state), "post_refresh_access_token")
  799. _assert_nous_inference_jwt_usable(state)
  800. _select_nous_invoke_jwt(state)
  801. return state
  802. def persist_nous_credentials(creds: dict[str, Any], *, label: Optional[str] = None):
  803. """Persist Nous OAuth credentials as the singleton provider state.
  804. Nous credentials are read from ``providers.nous`` (401 recovery, pool seeding) AND
  805. ``credential_pool.nous`` (runtime ``pool.select()``); a pool-only write broke expiry recovery.
  806. So: write the singleton, mirror to the shared store, then ``load_pool("nous")`` upserts the
  807. canonical ``device_code`` entry in place. ``label`` rides in the singleton so re-seeding keeps
  808. it.
  809. """
  810. from hermes_cli.auth import _save_active_provider_state, _write_shared_nous_state
  811. from agent.credential_pool import load_pool
  812. state = dict(creds)
  813. if label and str(label).strip():
  814. state["label"] = str(label).strip()
  815. _save_active_provider_state("nous", state)
  816. _write_shared_nous_state(state, renewal=False)
  817. pool = load_pool("nous")
  818. return next((e for e in pool.entries() if e.source == NOUS_DEVICE_CODE_SOURCE), None)
  819. def _sync_nous_pool_from_auth_store() -> None:
  820. """Best-effort pool reseed after providers.nous changes; never fail login."""
  821. try:
  822. from agent.credential_pool import load_pool
  823. load_pool("nous")
  824. except Exception as exc:
  825. logger.debug("Failed to sync Nous credential pool from auth store: %s", exc)
  826. def _nous_effective_routing(state: dict[str, Any]) -> tuple[str, str, str, str]:
  827. """``(portal_url, stored_inference_url, effective_inference_url, client_id)`` from *state*.
  828. The stored inference URL is re-validated network-provenance (persisted); the effective one
  829. layers the runtime-only ``NOUS_INFERENCE_BASE_URL`` override on top and is never persisted.
  830. """
  831. from hermes_cli.auth import _NOUS_PORTAL_ALLOWED_HOSTS, _optional_base_url
  832. portal_url = (_optional_base_url(state.get("portal_base_url")) or DEFAULT_NOUS_PORTAL_URL).rstrip("/")
  833. # A persisted/stale portal_base_url is where the refresh token gets POSTed — reject any host
  834. # outside the allowlist so a poisoned value can't exfiltrate the bearer, healing to the
  835. # default. Trusted operator env overrides bypass this network-value gate.
  836. env_portal_override = _nous_portal_env_override()
  837. if env_portal_override:
  838. portal_url = env_portal_override.rstrip("/")
  839. else:
  840. parsed_portal_url = urlparse(portal_url)
  841. portal_host, scheme = parsed_portal_url.hostname, parsed_portal_url.scheme
  842. trusted_scheme = scheme == "https" or (
  843. scheme == "http" and portal_host in {"localhost", "127.0.0.1"})
  844. if not portal_host or portal_host not in _NOUS_PORTAL_ALLOWED_HOSTS or not trusted_scheme:
  845. logger.warning(
  846. "auth: ignoring invalid portal_base_url %r "
  847. "(host %r or scheme not allowed), using default",
  848. portal_url, portal_host)
  849. portal_url = DEFAULT_NOUS_PORTAL_URL
  850. # A guest never falls back to the paid host: the gateway cross-refuses an anonymous JWT there
  851. # (400 naming the welcome host), so an absent or disallowed URL heals to the welcome literal.
  852. from hermes_cli.anon_auth import is_guest_state
  853. stored_inference_url = (
  854. _validate_nous_inference_url_from_network(
  855. _optional_base_url(state.get("inference_base_url")))
  856. or (DEFAULT_NOUS_WELCOME_URL if is_guest_state(state) else DEFAULT_NOUS_INFERENCE_URL))
  857. return (
  858. portal_url, stored_inference_url, _nous_inference_env_override() or stored_inference_url,
  859. str(state.get("client_id") or DEFAULT_NOUS_CLIENT_ID))
  860. class _NousRuntimeResolve:
  861. """Working set for one ``resolve_nous_runtime_credentials`` call.
  862. Holds the token pair + routing tuple that shared-store merges / refreshes replace mid-flight.
  863. ``persist`` skips writes where only derived TTL countdowns changed (keeps the mtime-keyed
  864. auth-status cache warm) and mirrors every real write to the shared store (best-effort).
  865. """
  866. def __init__(
  867. self, auth_store: dict[str, Any], state: dict[str, Any], state_source_path: Optional[Path],
  868. *, force_refresh: bool, stale_access_token: Optional[str], timeout_seconds: float) -> None:
  869. self.auth_store, self.state, self._source_path = auth_store, state, state_source_path
  870. self.force_refresh, self.stale_access_token = force_refresh, stale_access_token
  871. self.timeout_seconds = timeout_seconds
  872. self.sequence_id = uuid.uuid4().hex[:12]
  873. self._persisted_state = dict(state)
  874. self.persisted_any = False
  875. self.access_token = state.get("access_token")
  876. self.refresh_token = state.get("refresh_token")
  877. self._reload_routing()
  878. def _reload_routing(self) -> None:
  879. (self.portal_base_url, self.stored_inference_base_url, self.inference_base_url,
  880. self.client_id) = _nous_effective_routing(self.state)
  881. def persist(self, reason: str) -> None:
  882. from hermes_cli.auth import _save_provider_state_to_source, _write_shared_nous_state
  883. state = self.state
  884. persisted = _nous_effective_provider_state(self._persisted_state)
  885. if _nous_effective_provider_state(state) == persisted:
  886. _oauth_trace("nous_state_persist_skipped", sequence_id=self.sequence_id, reason=reason)
  887. return
  888. try:
  889. _save_provider_state_to_source(self.auth_store, "nous", state, self._source_path)
  890. except Exception as exc:
  891. _oauth_trace(
  892. "nous_state_persist_failed", sequence_id=self.sequence_id, reason=reason,
  893. error_type=type(exc).__name__)
  894. raise
  895. _oauth_trace(
  896. "nous_state_persisted", sequence_id=self.sequence_id, reason=reason,
  897. refresh_token_fp=_token_fingerprint(state.get("refresh_token")),
  898. access_token_fp=_token_fingerprint(state.get("access_token")))
  899. self._persisted_state = dict(state)
  900. self.persisted_any = True
  901. _write_shared_nous_state(state, renewal=True)
  902. def shared_lock(self):
  903. return _nous_shared_store_lock(timeout_seconds=_shared_lock_timeout(self.timeout_seconds))
  904. def has_access_token(self) -> bool:
  905. return isinstance(self.access_token, str) and bool(self.access_token)
  906. def invoke_jwt_status(self) -> Optional[str]:
  907. return _state_invoke_jwt_status(self.state, self.access_token)
  908. def merge_shared(self) -> bool:
  909. """Adopt fresher shared-store tokens (caller holds the shared lock). True when merged."""
  910. if not _merge_shared_nous_oauth_state(self.state):
  911. return False
  912. self.access_token = self.state.get("access_token")
  913. self.refresh_token = self.state.get("refresh_token")
  914. self._reload_routing()
  915. return True
  916. def skip_refresh_if_peer_rotated(self) -> None:
  917. """Skip the refresh when a peer already rotated the grant.
  918. Under the store lock: if the bearer that failed upstream is no longer the one on disk and
  919. the on-disk one is usable, adopt it — never re-POST the shared grant.
  920. """
  921. token = self.access_token
  922. if (self.force_refresh and self.stale_access_token and isinstance(token, str) and token
  923. and token != self.stale_access_token and self.invoke_jwt_status() is None):
  924. _oauth_trace(
  925. "refresh_skipped_peer_rotated", sequence_id=self.sequence_id,
  926. access_token_fp=_token_fingerprint(token))
  927. self.force_refresh = False
  928. def refresh(self, client: httpx.Client, invoke_jwt_status: Optional[str]) -> None:
  929. """Redeem the refresh token, apply + persist the rotated pair (caller holds both locks)."""
  930. if not isinstance(self.refresh_token, str) or not self.refresh_token:
  931. raise _unusable_invoke_jwt_error(
  932. invoke_jwt_status or "force_refresh", no_refresh_token=True)
  933. refresh_reason = (
  934. "force_refresh" if self.force_refresh else (invoke_jwt_status or "access_unusable"))
  935. _oauth_trace(
  936. "refresh_start", sequence_id=self.sequence_id, reason=refresh_reason,
  937. refresh_token_fp=_token_fingerprint(self.refresh_token))
  938. refreshed = _refresh_nous_or_quarantine(
  939. client=client, auth_store=self.auth_store, state=self.state,
  940. portal_base_url=self.portal_base_url, client_id=self.client_id,
  941. refresh_token=self.refresh_token, reason="runtime_access_refresh_failure",
  942. persist=lambda: self.persist("terminal_runtime_access_refresh_failure"))
  943. previous_refresh_token = self.refresh_token
  944. # The validated, network-provenance URL is what gets persisted (with the rotated tokens,
  945. # so a later JWT validation failure cannot leave the stores on stale metadata). The
  946. # NOUS_INFERENCE_BASE_URL env override is layered on for the client/return value only.
  947. self.stored_inference_base_url = _healed_nous_inference_url(refreshed)
  948. self.inference_base_url = _nous_inference_env_override() or self.stored_inference_base_url
  949. _apply_nous_refreshed_tokens(
  950. self.state, refreshed, self.refresh_token,
  951. inference_base_url=self.stored_inference_base_url)
  952. self.access_token = self.state["access_token"]
  953. self.refresh_token = self.state["refresh_token"]
  954. _oauth_trace(
  955. "refresh_success", sequence_id=self.sequence_id, reason=refresh_reason,
  956. previous_refresh_token_fp=_token_fingerprint(previous_refresh_token),
  957. new_refresh_token_fp=_token_fingerprint(self.refresh_token))
  958. # Persist immediately so validation failures cannot drop rotated refresh tokens.
  959. self.persist("post_refresh_access_token")
  960. def ensure_usable_access_token(self, client: httpx.Client) -> None:
  961. """Merge from the shared store / refresh until the access token is a usable invoke JWT."""
  962. from hermes_cli.anon_auth import is_guest_state, refresh_guest_state
  963. if is_guest_state(self.state):
  964. # Guest seam: the anon_ credential is the refresh material; re-exchange instead of
  965. # redeeming a rotating refresh token. Quarantine never applies to a guest.
  966. if self.force_refresh or self.invoke_jwt_status() is not None:
  967. refresh_guest_state(self.state, client, purpose="inference")
  968. self.access_token = self.state["access_token"]
  969. self.stored_inference_base_url = self.state.get("inference_base_url") or self.stored_inference_base_url
  970. self.inference_base_url = _nous_inference_env_override() or self.stored_inference_base_url
  971. self.persist("guest_exchange")
  972. return
  973. if not self.has_access_token():
  974. with self.shared_lock():
  975. if self.merge_shared():
  976. self.persist("runtime_shared_merge_missing_access_token")
  977. if not self.has_access_token():
  978. raise _nous_err(
  979. "No access token found for Nous Portal login.", "nous_auth_missing_access_token", relogin=True)
  980. invoke_jwt_status = self.invoke_jwt_status()
  981. self.skip_refresh_if_peer_rotated()
  982. if not (self.force_refresh or invoke_jwt_status is not None):
  983. return
  984. with self.shared_lock():
  985. if self.merge_shared():
  986. invoke_jwt_status = self.invoke_jwt_status()
  987. self.persist("post_shared_merge_access_unusable")
  988. self.skip_refresh_if_peer_rotated()
  989. if self.force_refresh or invoke_jwt_status is not None:
  990. self.refresh(client, invoke_jwt_status)
  991. def resolve_nous_runtime_credentials(
  992. *, timeout_seconds: float = 15.0, insecure: Optional[bool] = None,
  993. ca_bundle: Optional[str] = None, force_refresh: bool = False,
  994. stale_access_token: Optional[str] = None) -> dict[str, Any]:
  995. """Resolve Nous inference credentials for runtime use (refreshing under the auth-store lock).
  996. A guest whose ``anon_`` credential NAS no longer knows (reaped or claimed) is retired and never
  997. replaced here: the welcome trial is claimed once per OS user, so that user goes on to sign-in or
  998. provider setup.
  999. """
  1000. from hermes_cli.anon_auth import AnonCredentialDead, clear_dead_guest
  1001. from hermes_cli.anon_challenge import run_with_challenge
  1002. try:
  1003. # A free-tier exchange may be answered with a browser challenge; it is worked here, after
  1004. # the exchange's locks have unwound, and the exchange is then run once more.
  1005. return run_with_challenge(lambda: _resolve_nous_runtime_credentials(
  1006. timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle,
  1007. force_refresh=force_refresh, stale_access_token=stale_access_token))
  1008. except AnonCredentialDead as dead_exc:
  1009. from hermes_cli.auth import get_provider_auth_state
  1010. dead = get_provider_auth_state("nous") or {}
  1011. clear_dead_guest(str(dead_exc.code or "anon_credential_dead"), dead_token=dead.get("anon_token"))
  1012. raise
  1013. def _resolve_nous_runtime_credentials(
  1014. *, timeout_seconds: float = 15.0, insecure: Optional[bool] = None,
  1015. ca_bundle: Optional[str] = None, force_refresh: bool = False,
  1016. stale_access_token: Optional[str] = None) -> dict[str, Any]:
  1017. """Resolve Nous inference credentials for runtime use (refreshing under the auth-store lock).
  1018. ``stale_access_token`` is the bearer that just failed upstream (401): with ``force_refresh``,
  1019. the refresh POST is skipped if the store (re-read under the lock) already holds a *different*
  1020. usable token — a peer won the rotation; adopt it rather than invalidate a sibling's token.
  1021. """
  1022. from hermes_cli.auth import (
  1023. _assert_nous_inference_jwt_usable, _auth_file_path, _provider_state_transaction,
  1024. _resolve_verify, _select_nous_invoke_jwt, _sync_nous_pool_from_auth_store,
  1025. _tls_state_from_verify)
  1026. with _provider_state_transaction("nous") as (auth_store, state, state_source_path):
  1027. if not state:
  1028. raise _nous_err("Hermes is not logged into Nous Portal.", "nous_auth_missing", relogin=True)
  1029. from hermes_cli.anon_auth import guest_without_free_tier
  1030. if guest_without_free_tier(state):
  1031. # Not terminal (no relogin): the identity stays for connectors.
  1032. raise _nous_err("Hermes is not logged into Nous Portal.", "nous_auth_missing")
  1033. run = _NousRuntimeResolve(
  1034. auth_store, state, state_source_path, force_refresh=force_refresh,
  1035. stale_access_token=stale_access_token, timeout_seconds=timeout_seconds)
  1036. verify = _resolve_verify(insecure=insecure, ca_bundle=ca_bundle, auth_state=state)
  1037. _oauth_trace(
  1038. "nous_runtime_credentials_start", sequence_id=run.sequence_id,
  1039. refresh_token_fp=_token_fingerprint(state.get("refresh_token")))
  1040. with _nous_http_client(timeout_seconds or 15.0, verify) as client:
  1041. run.ensure_usable_access_token(client)
  1042. _assert_nous_inference_jwt_usable(state, access_token=run.access_token)
  1043. _select_nous_invoke_jwt(
  1044. state, access_token=run.access_token, sequence_id=run.sequence_id)
  1045. # Persist routing and TLS metadata for non-interactive refresh — the validated,
  1046. # network-provenance URL, NEVER the env override (a runtime-only overlay; persisting
  1047. # it would leak a dev/staging host into auth.json and survive unsetting it).
  1048. state.update(
  1049. portal_base_url=run.portal_base_url, client_id=run.client_id,
  1050. inference_base_url=run.stored_inference_base_url,
  1051. tls=_tls_state_from_verify(verify))
  1052. run.persist("resolve_nous_runtime_credentials_final")
  1053. if run.persisted_any:
  1054. _sync_nous_pool_from_auth_store()
  1055. api_key = state.get("agent_key")
  1056. if not isinstance(api_key, str) or not api_key:
  1057. raise _nous_err("Failed to resolve a Nous inference API key", "server_error")
  1058. expires_at = state.get("agent_key_expires_at")
  1059. return {
  1060. "provider": "nous", "base_url": run.inference_base_url, "api_key": api_key,
  1061. "key_id": state.get("agent_key_id"), "expires_at": expires_at,
  1062. "expires_in": _remaining_ttl(expires_at, state.get("agent_key_expires_in")),
  1063. "source": NOUS_AUTH_PATH_INVOKE_JWT,
  1064. # Public semantic source label; the concrete store is exposed separately for diagnostics.
  1065. # Refresh persistence uses state_source_path internally and must not overload this field.
  1066. "auth_path": NOUS_AUTH_PATH_INVOKE_JWT,
  1067. "state_path": str(state_source_path or _auth_file_path())}
  1068. def _empty_nous_auth_status() -> dict[str, Any]:
  1069. return {
  1070. "logged_in": False, "portal_base_url": None, "inference_base_url": None,
  1071. "access_expires_at": None, "agent_key_expires_at": None, "has_refresh_token": False,
  1072. "inference_credential_present": False, "credential_source": None}
  1073. def _snapshot_nous_pool_status() -> dict[str, Any]:
  1074. """Best-effort status from the credential pool.
  1075. Fallback only: the auth-store provider state is the runtime source of truth because it is what
  1076. ``resolve_nous_runtime_credentials()`` refreshes.
  1077. """
  1078. from hermes_cli.auth import _parse_iso_timestamp
  1079. try:
  1080. from agent.credential_pool import load_pool
  1081. pool = load_pool("nous")
  1082. # A guest's row is not a Portal login: without its trial stamp in auth.json it runs nothing.
  1083. entries = [e for e in pool.entries() if getattr(e, "auth_method", None) != "anonymous"] if (
  1084. pool and pool.has_credentials()) else []
  1085. if not entries:
  1086. return _empty_nous_auth_status()
  1087. entry = max(entries, key=lambda e: (
  1088. _parse_iso_timestamp(getattr(e, "agent_key_expires_at", None)) or 0.0,
  1089. _parse_iso_timestamp(getattr(e, "expires_at", None)) or 0.0,
  1090. -int(getattr(e, "priority", 0) or 0)))
  1091. attr = lambda name, default=None: getattr(entry, name, default)
  1092. if not attr("runtime_api_key"):
  1093. return _empty_nous_auth_status()
  1094. access_token, refresh_token = attr("access_token"), attr("refresh_token")
  1095. auth_type = str(attr("auth_type", "") or "").strip().lower()
  1096. is_portal_oauth = bool(access_token) and (
  1097. auth_type.startswith("oauth") or bool(refresh_token))
  1098. label = attr("label", "unknown")
  1099. return {
  1100. "logged_in": is_portal_oauth,
  1101. "portal_base_url": (
  1102. (attr("portal_base_url") or DEFAULT_NOUS_PORTAL_URL) if is_portal_oauth else None),
  1103. "inference_base_url": (
  1104. attr("inference_base_url") or attr("runtime_base_url") or attr("base_url")),
  1105. "access_token": access_token if is_portal_oauth else None,
  1106. "access_expires_at": attr("expires_at"),
  1107. "agent_key_expires_at": attr("agent_key_expires_at"),
  1108. "has_refresh_token": bool(refresh_token), "inference_credential_present": True,
  1109. "credential_source": f"pool:{label}", "source": f"pool:{label}"}
  1110. except Exception:
  1111. return _empty_nous_auth_status()
  1112. def _nous_status_from_state(
  1113. state: dict[str, Any], *, logged_in: bool, source: str) -> dict[str, Any]:
  1114. """Auth-store-backed Nous status snapshot (shared by the live and refresh-free variants)."""
  1115. from hermes_cli.anon_auth import is_guest_state
  1116. access_token = state.get("access_token")
  1117. account_tier = state.get("account_tier")
  1118. return {
  1119. "logged_in": logged_in, "portal_base_url": state.get("portal_base_url"),
  1120. "inference_base_url": state.get("inference_base_url"),
  1121. "access_expires_at": state.get("expires_at"),
  1122. "agent_key_expires_at": state.get("agent_key_expires_at"),
  1123. "has_refresh_token": bool(state.get("refresh_token")), "access_token": access_token,
  1124. "inference_credential_present": bool(access_token or state.get("agent_key")),
  1125. "credential_source": "auth_store", "source": source,
  1126. # Free tier: display surfaces render it with the free-tier copy, never as an account login.
  1127. "account_tier": account_tier if isinstance(account_tier, str) else None,
  1128. "free_tier": is_guest_state(state)}
  1129. def _compute_nous_auth_status() -> dict[str, Any]:
  1130. """Uncached implementation of get_nous_auth_status(). See that function."""
  1131. from hermes_cli.anon_auth import guest_without_free_tier
  1132. from hermes_cli.auth import get_provider_auth_state, resolve_nous_runtime_credentials
  1133. state = get_provider_auth_state("nous")
  1134. if not state or guest_without_free_tier(state):
  1135. return _snapshot_nous_pool_status()
  1136. base_status = _nous_status_from_state(
  1137. state, logged_in=bool(state.get("access_token")), source="auth_store")
  1138. try:
  1139. # A status paint must not park on (or open a browser for) a free-tier challenge.
  1140. from hermes_cli.anon_challenge import background_caller
  1141. with background_caller():
  1142. creds = resolve_nous_runtime_credentials()
  1143. refreshed_state = get_provider_auth_state("nous") or state
  1144. base_status.update({
  1145. "logged_in": True,
  1146. "portal_base_url": (
  1147. refreshed_state.get("portal_base_url") or base_status.get("portal_base_url")),
  1148. "inference_base_url": (
  1149. creds.get("base_url") or refreshed_state.get("inference_base_url")
  1150. or base_status.get("inference_base_url")),
  1151. "access_expires_at": (
  1152. refreshed_state.get("expires_at") or base_status.get("access_expires_at")),
  1153. "agent_key_expires_at": (
  1154. creds.get("expires_at") or refreshed_state.get("agent_key_expires_at")
  1155. or base_status.get("agent_key_expires_at")),
  1156. "has_refresh_token": bool(refreshed_state.get("refresh_token")),
  1157. "inference_credential_present": True, "credential_source": "auth_store",
  1158. "source": f"runtime:{creds.get('source', 'portal')}", "key_id": creds.get("key_id")})
  1159. except AuthError as exc:
  1160. base_status.update({
  1161. "logged_in": False, "error": str(exc),
  1162. "relogin_required": bool(getattr(exc, "relogin_required", False)),
  1163. "error_code": getattr(exc, "code", None)})
  1164. return base_status
  1165. def _terminal_quarantine_marker(state: dict[str, Any]) -> Optional[dict[str, Any]]:
  1166. """The persisted ``last_auth_error`` when it is a terminal quarantine with no credential left.
  1167. Only terminal while there is no usable credential: if a later login repopulated tokens the stale
  1168. marker must not keep reporting terminal.
  1169. """
  1170. last_err = state.get("last_auth_error")
  1171. if (isinstance(last_err, dict) and last_err.get("relogin_required")
  1172. and not (state.get("access_token") or state.get("refresh_token"))):
  1173. return last_err
  1174. return None
  1175. def get_nous_auth_status_local() -> dict[str, Any]:
  1176. """Refresh-free Nous auth snapshot for read-only display surfaces.
  1177. NEVER calls ``resolve_nous_runtime_credentials()`` (no refresh POST / single-use token spent);
  1178. ``logged_in`` = usable invoke JWT, or a refresh token not terminally quarantined — not proof
  1179. the server still accepts it.
  1180. """
  1181. from hermes_cli.anon_auth import guest_without_free_tier
  1182. from hermes_cli.auth import get_provider_auth_state
  1183. try:
  1184. state = get_provider_auth_state("nous")
  1185. except Exception:
  1186. state = None
  1187. if not state or guest_without_free_tier(state):
  1188. return _snapshot_nous_pool_status()
  1189. jwt_reason = _state_invoke_jwt_status(state, state.get("access_token"))
  1190. last_err = _terminal_quarantine_marker(state)
  1191. logged_in = (jwt_reason is None) or (bool(state.get("refresh_token")) and last_err is None)
  1192. status = _nous_status_from_state(state, logged_in=logged_in, source="auth_store_local")
  1193. if last_err is not None:
  1194. status.update(
  1195. relogin_required=True, error_code=last_err.get("code"),
  1196. error=last_err.get("message") or "re-login required")
  1197. return status
  1198. # Enum values reported on the dashboard /api/status as ``nous_session_valid``. NAS's health sweep
  1199. # re-mints the bootstrap session ONLY on "terminal"; "valid" and "unknown" are no-ops. Keep this
  1200. # set small and stable — NAS parses it permissively, so new members are non-breaking but rare.
  1201. NOUS_SESSION_VALID = "valid"
  1202. NOUS_SESSION_TERMINAL = "terminal"
  1203. NOUS_SESSION_UNKNOWN = "unknown"
  1204. def get_nous_session_validity() -> str:
  1205. """Classify the Nous bootstrap session for the dashboard /api/status probe.
  1206. Local auth-store state only; polled frequently, so it never resolves or refreshes. ANTI-FLAP:
  1207. only a *terminal* failure maps to "terminal" — a rotation blip, network error, or expiring
  1208. token must NOT (that would trigger a spurious NAS re-mint on a healthy box).
  1209. """
  1210. from hermes_cli.auth import get_provider_auth_state
  1211. try:
  1212. state = get_provider_auth_state("nous")
  1213. except Exception:
  1214. state = None
  1215. if not state:
  1216. return NOUS_SESSION_UNKNOWN
  1217. # The persisted quarantine marker (`last_auth_error.relogin_required=True`, written when the
  1218. # refresh path clears dead tokens) is the strongest, most stable terminal signal — report
  1219. # "terminal" even after the in-memory AuthError is long gone.
  1220. if _terminal_quarantine_marker(state) is not None:
  1221. return NOUS_SESSION_TERMINAL
  1222. if _state_invoke_jwt_status(state, state.get("access_token")) is None:
  1223. return NOUS_SESSION_VALID
  1224. # Missing, malformed, expired, or merely expiring credentials are not proof of a terminal
  1225. # session. Runtime paths own refreshes; the health endpoint stays side-effect free.
  1226. return NOUS_SESSION_UNKNOWN
  1227. def _pool_first_oauth_status(
  1228. provider_id: str, *, is_expiring: Callable[[str, int], bool], auth_mode: str,
  1229. resolve: Callable[[], dict[str, Any]],
  1230. on_pool_miss: Optional[Callable[[], Optional[dict[str, Any]]]] = None) -> dict[str, Any]:
  1231. """Status snapshot for a store-backed OAuth provider (Codex, xAI).
  1232. Pool first (where `hermes auth` / `hermes model` store device_code tokens), then
  1233. *on_pool_miss* for a pool-derived degraded status, then the legacy state via *resolve*.
  1234. The pool read is an observation (``peek``), not a lease: ``select()`` refreshes an expiring
  1235. single-use token and, when that speculative POST fails transiently, benches the entry with a
  1236. persisted cooldown — every credential-gated listing (``/model`` picker, doctor) then shows the
  1237. provider as unconfigured while the runtime resolver still serves it. Refreshing stays with the
  1238. runtime resolver reached through *resolve*, whose failures persist nothing.
  1239. """
  1240. from hermes_cli.auth import _auth_file_path
  1241. try:
  1242. from agent.credential_pool import load_pool
  1243. pool = load_pool(provider_id)
  1244. if pool and pool.has_credentials():
  1245. entry = pool.peek()
  1246. if entry is not None:
  1247. api_key = (
  1248. getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", ""))
  1249. if api_key and not is_expiring(api_key, 0):
  1250. return {
  1251. "logged_in": True, "auth_store": str(_auth_file_path()),
  1252. "last_refresh": getattr(entry, "last_refresh", None),
  1253. "auth_mode": auth_mode,
  1254. "source": f"pool:{getattr(entry, 'label', 'unknown')}", "api_key": api_key,
  1255. # The host this entry's key belongs to, so a caller never pairs it with
  1256. # another provider default (#121486).
  1257. "base_url": str(getattr(entry, "runtime_base_url", None)
  1258. or getattr(entry, "base_url", None) or "").rstrip("/")}
  1259. if on_pool_miss is not None and (degraded := on_pool_miss()):
  1260. return degraded
  1261. except Exception:
  1262. pass
  1263. try:
  1264. creds = resolve()
  1265. return {
  1266. "logged_in": True, "auth_store": str(_auth_file_path()),
  1267. "last_refresh": creds.get("last_refresh"),
  1268. "auth_mode": creds.get("auth_mode"), "source": creds.get("source"),
  1269. "api_key": creds.get("api_key"), "base_url": creds.get("base_url") or ""}
  1270. except AuthError as exc:
  1271. return {"logged_in": False, "auth_store": str(_auth_file_path()), "error": str(exc)}
  1272. def _nous_device_code_login(
  1273. *, portal_base_url: Optional[str] = None, inference_base_url: Optional[str] = None,
  1274. client_id: Optional[str] = None, scope: Optional[str] = None, open_browser: bool = True,
  1275. timeout_seconds: float = 15.0, insecure: bool = False, ca_bundle: Optional[str] = None,
  1276. on_verification: Optional[Callable[[str, str], None]] = None) -> dict[str, Any]:
  1277. """Run the Nous device-code flow and return full OAuth state without persisting."""
  1278. from hermes_cli.auth import (
  1279. PROVIDER_REGISTRY, _coerce_ttl_seconds, _is_remote_session, _optional_base_url,
  1280. _poll_for_token, _print_device_code_instructions, _request_device_code,
  1281. _tls_state_from_verify, format_auth_error, refresh_nous_oauth_from_state)
  1282. pconfig = PROVIDER_REGISTRY["nous"]
  1283. portal_base_url = (
  1284. portal_base_url or os.getenv("HERMES_PORTAL_BASE_URL") or os.getenv("NOUS_PORTAL_BASE_URL")
  1285. or pconfig.portal_base_url).rstrip("/")
  1286. requested_inference_url = (
  1287. inference_base_url or os.getenv("NOUS_INFERENCE_BASE_URL")
  1288. or pconfig.inference_base_url).rstrip("/")
  1289. client_id = client_id or pconfig.client_id
  1290. scope = scope or pconfig.scope
  1291. verify: bool | str = False if insecure else (ca_bundle if ca_bundle else True)
  1292. if _is_remote_session():
  1293. open_browser = False
  1294. print(f"Starting Hermes login via {pconfig.name}...")
  1295. print(f"Portal: {portal_base_url}")
  1296. if insecure:
  1297. print("TLS verification: disabled (--insecure)")
  1298. elif ca_bundle:
  1299. print(f"TLS verification: custom CA bundle ({ca_bundle})")
  1300. with _nous_http_client(timeout_seconds, verify) as client:
  1301. device_data = _request_device_code(
  1302. client=client, portal_base_url=portal_base_url, client_id=client_id, scope=scope)
  1303. verification_url = str(device_data["verification_uri_complete"])
  1304. user_code = str(device_data["user_code"])
  1305. expires_in = int(device_data["expires_in"])
  1306. interval = int(device_data["interval"])
  1307. _print_device_code_instructions(
  1308. verification_url, user_code, open_browser=open_browser, failure_dash="—")
  1309. # Out-of-band consumer (e.g. the TUI gateway, whose stdout is a JSON-RPC pipe): fired AFTER
  1310. # the print/browser block and BEFORE polling so it can render the link while we wait.
  1311. if on_verification is not None:
  1312. with suppress(Exception):
  1313. on_verification(verification_url, user_code)
  1314. effective_interval = max(1, min(interval, DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS))
  1315. print(f"Waiting for approval (polling every {effective_interval}s)...")
  1316. token_data = _poll_for_token(
  1317. client=client, portal_base_url=portal_base_url, client_id=client_id,
  1318. device_code=str(device_data["device_code"]), expires_in=expires_in,
  1319. poll_interval=interval)
  1320. now = datetime.now(UTC)
  1321. token_expires_in = _coerce_ttl_seconds(token_data.get("expires_in", 0))
  1322. resolved_inference_url = (
  1323. _optional_base_url(token_data.get("inference_base_url")) or requested_inference_url)
  1324. if resolved_inference_url != requested_inference_url:
  1325. print(f"Using portal-provided inference URL: {resolved_inference_url}")
  1326. auth_state = {
  1327. "portal_base_url": portal_base_url, "inference_base_url": resolved_inference_url,
  1328. "client_id": client_id, "scope": token_data.get("scope") or scope,
  1329. "token_type": token_data.get("token_type", "Bearer"),
  1330. "access_token": token_data["access_token"],
  1331. "refresh_token": token_data.get("refresh_token"),
  1332. "obtained_at": now.isoformat(), "expires_at": _iso_after(now, token_expires_in),
  1333. "expires_in": token_expires_in, "tls": _tls_state_from_verify(verify),
  1334. **_NOUS_EMPTY_AGENT_KEY_FIELDS}
  1335. try:
  1336. return refresh_nous_oauth_from_state(
  1337. auth_state, timeout_seconds=timeout_seconds, force_refresh=False)
  1338. except AuthError as exc:
  1339. if exc.code == "subscription_required":
  1340. portal_url = auth_state.get("portal_base_url", DEFAULT_NOUS_PORTAL_URL).rstrip("/")
  1341. print()
  1342. print(format_auth_error(exc))
  1343. print(f" Subscribe here: {portal_url}/billing")
  1344. print()
  1345. print("After subscribing, run `hermes model` again to finish setup.")
  1346. raise SystemExit(1)
  1347. raise
  1348. def _mirror_nous_state_best_effort(auth_state: dict[str, Any]) -> None:
  1349. """Mirror to the shared store + reseed the pool, swallowing all errors (same as _login_nous)."""
  1350. from hermes_cli.auth import _sync_nous_pool_from_auth_store, _write_shared_nous_state
  1351. with suppress(Exception):
  1352. _write_shared_nous_state(auth_state, renewal=False)
  1353. with suppress(Exception):
  1354. _sync_nous_pool_from_auth_store()
  1355. def step_up_nous_billing_scope(
  1356. *, open_browser: bool = True, timeout_seconds: float = 15.0,
  1357. on_verification: Optional[Callable[[str, str], None]] = None) -> bool:
  1358. """Re-run the device flow requesting ``billing:manage`` (step-up on 403 insufficient_scope).
  1359. The user must be ADMIN/OWNER and select "Allow Remote Spending" in the portal, else the
  1360. server silently downscopes and this returns False. Persists like ``_login_nous`` minus the
  1361. model picker.
  1362. """
  1363. from hermes_cli.auth import (
  1364. PROVIDER_REGISTRY, _nous_device_code_login, _save_active_provider_state,
  1365. get_provider_auth_state)
  1366. prior = get_provider_auth_state("nous") or {}
  1367. pconfig = PROVIDER_REGISTRY["nous"]
  1368. # Step-up scope: existing scopes (if any) + billing:manage, deduped, order-stable. Falls back
  1369. # to the standard inference+billing set.
  1370. _raw_scope = prior.get("scope")
  1371. prior_scope = _raw_scope.split() if isinstance(_raw_scope, str) else []
  1372. requested = list(dict.fromkeys([
  1373. *(prior_scope or [NOUS_INFERENCE_INVOKE_SCOPE]), NOUS_BILLING_MANAGE_SCOPE]))
  1374. auth_state = _nous_device_code_login(
  1375. portal_base_url=prior.get("portal_base_url") or None,
  1376. inference_base_url=prior.get("inference_base_url") or None,
  1377. client_id=prior.get("client_id") or pconfig.client_id, scope=" ".join(requested),
  1378. open_browser=open_browser, timeout_seconds=timeout_seconds, on_verification=on_verification)
  1379. _save_active_provider_state("nous", auth_state)
  1380. _mirror_nous_state_best_effort(auth_state)
  1381. drain() # a step-up that replaced the free tier hands its apps over
  1382. # Every caller replays the refused billing action next: drop the billing client's 30s token cache
  1383. # here (not per caller) so that replay sends the new token, not the pre-approval one (403 again).
  1384. try:
  1385. from hermes_cli.nous_billing import invalidate_cached_token
  1386. invalidate_cached_token()
  1387. except Exception:
  1388. logger.debug("Billing token cache invalidation failed", exc_info=True)
  1389. from hermes_cli.anon_auth import settle_after_upgrade
  1390. settle_after_upgrade(auth_state) # a step-up that replaced the free tier moves its config too
  1391. granted = auth_state.get("scope")
  1392. return isinstance(granted, str) and NOUS_BILLING_MANAGE_SCOPE in granted.split()
  1393. def _pick_nous_model_after_login(
  1394. auth_state: dict[str, Any], inference_base_url: str) -> Optional[str]:
  1395. """Fetch the curated Nous model list (tier/policy-filtered) and run the interactive picker.
  1396. Returns the selected model id, or None when the user skipped / nothing was selectable.
  1397. Raises on any fetch failure so the caller can print the "Login succeeded, but..." notice.
  1398. """
  1399. from hermes_cli.auth import _prompt_model_selection
  1400. runtime_key = auth_state.get("agent_key") or auth_state.get("access_token")
  1401. if not isinstance(runtime_key, str) or not runtime_key:
  1402. raise _nous_err("No runtime API key available to fetch models", "invalid_token")
  1403. from hermes_cli.models import (
  1404. get_curated_nous_model_ids,
  1405. check_nous_free_tier,
  1406. partition_nous_models_by_tier,
  1407. union_with_nous_on_sale_models,
  1408. union_with_portal_free_recommendations,
  1409. union_with_portal_paid_recommendations,
  1410. )
  1411. from hermes_cli.models_pricing import (
  1412. get_pricing_for_provider,
  1413. nous_policy_allowed_ids,
  1414. restrict_to_nous_policy,
  1415. )
  1416. model_ids = get_curated_nous_model_ids()
  1417. _portal = auth_state.get("portal_base_url", "")
  1418. print()
  1419. unavailable_models: list = []
  1420. unavailable_message = ""
  1421. _policy_narrowed = False
  1422. if model_ids:
  1423. pricing = get_pricing_for_provider("nous")
  1424. # Force fresh account data so recent credit purchases are reflected immediately.
  1425. free_tier = check_nous_free_tier(force_fresh=True)
  1426. # Narrow before the tier split, so a rescued id still has to pass the free/paid predicate.
  1427. _policy_allowed = nous_policy_allowed_ids()
  1428. if free_tier:
  1429. with suppress(Exception):
  1430. unavailable_message = _portal_entitlement_message("paid Nous models")
  1431. # The Portal's free/paidRecommendedModels endpoint is the source of truth for what's
  1432. # available *right now*: newly-launched models show without a CLI release.
  1433. union = (
  1434. union_with_portal_free_recommendations if free_tier
  1435. else union_with_portal_paid_recommendations)
  1436. model_ids, pricing = union(model_ids, pricing, _portal)
  1437. if not free_tier:
  1438. # Paid users also see every model on sale right now (same rule as `hermes model`).
  1439. model_ids = union_with_nous_on_sale_models(model_ids, pricing)
  1440. _before_policy = model_ids
  1441. model_ids = restrict_to_nous_policy(model_ids, _policy_allowed, rescue_empty=True)
  1442. _policy_narrowed = model_ids != _before_policy
  1443. if free_tier:
  1444. model_ids, unavailable_models = partition_nous_models_by_tier(
  1445. model_ids, pricing, free_tier=True)
  1446. if model_ids:
  1447. from hermes_cli.nous_account import nous_policy_notice
  1448. _policy_notice = nous_policy_notice(removed=_policy_narrowed)
  1449. if _policy_notice:
  1450. print(_policy_notice)
  1451. from hermes_cli.model_picker_usage import featured_first, nous_picker_usage
  1452. _usage = nous_picker_usage(warm=True)
  1453. # Window plans: every model is usable; the plan's featured picks lead the list.
  1454. if _usage is not None:
  1455. model_ids = featured_first(model_ids, _usage.featured_model_ids)
  1456. print(
  1457. f"Showing {len(model_ids)} curated models — "
  1458. "use \"Enter custom model name\" for others.")
  1459. return _prompt_model_selection(
  1460. model_ids, pricing=pricing, unavailable_models=unavailable_models, portal_url=_portal,
  1461. unavailable_message=unavailable_message, confirm_provider="nous",
  1462. confirm_base_url=inference_base_url, confirm_api_key=runtime_key,
  1463. usage=_usage)
  1464. if unavailable_models:
  1465. _url = (_portal or DEFAULT_NOUS_PORTAL_URL).rstrip("/")
  1466. print("No free models currently available.")
  1467. print(unavailable_message or f"Upgrade at {_url} to access paid models.")
  1468. else:
  1469. print("No curated models available for Nous Portal.")
  1470. return None
  1471. def _offer_shared_nous_import(timeout_seconds: float) -> Optional[dict[str, Any]]:
  1472. """Codex-style auto-import: offer to rehydrate a Nous credential from another profile.
  1473. Checks the shared store before launching a fresh device-code flow. Returns the refreshed
  1474. auth state when the user accepted and the import succeeded, else None.
  1475. """
  1476. from hermes_cli.auth import _prompt_yes_no, _read_shared_nous_state
  1477. from hermes_cli.anon_auth import is_guest_state
  1478. shared = _read_shared_nous_state()
  1479. if not shared or is_guest_state(shared):
  1480. # A free-tier identity is not an OAuth credential to import; a real sign-in replaces it
  1481. # (persist_nous_credentials overwrites the singleton and the shared store).
  1482. return None
  1483. try:
  1484. shared_path = _nous_shared_store_path()
  1485. except RuntimeError:
  1486. shared_path = None
  1487. print()
  1488. print(f"Found existing Nous OAuth credentials at {shared_path}" if shared_path
  1489. else "Found existing shared Nous OAuth credentials")
  1490. if not _prompt_yes_no("Import these credentials? [Y/n]: ", default="y"):
  1491. return None
  1492. print("Rehydrating Nous session from shared credentials...")
  1493. auth_state = _try_import_shared_nous_state(timeout_seconds=timeout_seconds)
  1494. if auth_state is None:
  1495. print("Could not refresh shared credentials — falling back to device-code login.")
  1496. return auth_state
  1497. def _restore_active_provider(prior_active_provider: Any) -> None:
  1498. """Undo the ``active_provider="nous"`` that ``_save_provider_state`` wrote during login."""
  1499. from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
  1500. with _auth_store_lock():
  1501. auth_store = _load_auth_store()
  1502. if prior_active_provider:
  1503. auth_store["active_provider"] = prior_active_provider
  1504. else:
  1505. auth_store.pop("active_provider", None)
  1506. _save_auth_store(auth_store)
  1507. def _login_nous(args, pconfig: ProviderConfig) -> None:
  1508. """Nous Portal device authorization flow."""
  1509. from hermes_cli.auth import (
  1510. _auth_store_lock, _load_auth_store, _nous_device_code_login, _save_active_provider_state,
  1511. _save_model_choice, _sync_nous_pool_from_auth_store, _update_config_for_provider,
  1512. _write_shared_nous_state, format_auth_error)
  1513. timeout_seconds = getattr(args, "timeout", None) or 15.0
  1514. ca_bundle = (
  1515. getattr(args, "ca_bundle", None) or os.getenv("HERMES_CA_BUNDLE")
  1516. or os.getenv("SSL_CERT_FILE"))
  1517. try:
  1518. auth_state = _offer_shared_nous_import(timeout_seconds)
  1519. if auth_state is None:
  1520. auth_state = _nous_device_code_login(
  1521. portal_base_url=getattr(args, "portal_url", None),
  1522. inference_base_url=getattr(args, "inference_url", None),
  1523. client_id=getattr(args, "client_id", None) or pconfig.client_id,
  1524. scope=getattr(args, "scope", None),
  1525. open_browser=not getattr(args, "no_browser", False),
  1526. timeout_seconds=timeout_seconds, insecure=bool(getattr(args, "insecure", False)),
  1527. ca_bundle=ca_bundle)
  1528. inference_base_url = auth_state["inference_base_url"]
  1529. # Snapshot BEFORE _save_provider_state overwrites active_provider to "nous", so a
  1530. # model-picker "Skip (keep current)" can restore the user's previous provider.
  1531. with _auth_store_lock():
  1532. prior_active_provider = _load_auth_store().get("active_provider")
  1533. saved_to = _save_active_provider_state("nous", auth_state)
  1534. # Mirror to the shared store so other profiles can one-tap import (best-effort inside).
  1535. _write_shared_nous_state(auth_state, renewal=False)
  1536. handoff = drain() # a replaced free tier hands its apps over once both saves land
  1537. _sync_nous_pool_from_auth_store()
  1538. from hermes_cli.anon_auth import settle_after_upgrade
  1539. settle_after_upgrade(auth_state) # a config left on the free tier's route moves to the account
  1540. print()
  1541. print("Login successful!")
  1542. print(f" Auth state: {saved_to}")
  1543. for line in (line for view in handoff for line in result_lines(view)):
  1544. print(f" {line}")
  1545. # Pick the model BEFORE writing the provider to config.yaml so config is never half-updated.
  1546. selected_model = None
  1547. try:
  1548. selected_model = _pick_nous_model_after_login(auth_state, inference_base_url)
  1549. except Exception as exc:
  1550. message = format_auth_error(exc) if isinstance(exc, AuthError) else str(exc)
  1551. print()
  1552. print(f"Login succeeded, but could not fetch available models. Reason: {message}")
  1553. # No model (Skip, fetch failed, nothing curated): keep the previous provider rather than
  1554. # switch to Nous with a mismatched model; the Nous tokens stay saved for future use.
  1555. if not selected_model:
  1556. _restore_active_provider(prior_active_provider)
  1557. print()
  1558. print("No provider change. Nous credentials saved for future use.")
  1559. print(" Run `hermes model` again to switch to Nous Portal.")
  1560. return
  1561. config_path = _update_config_for_provider(
  1562. "nous", inference_base_url, default_model=selected_model)
  1563. _save_model_choice(selected_model)
  1564. print(f"Default model set to: {selected_model}")
  1565. from hermes_cli.model_picker_usage import large_model_notice
  1566. if _notice := large_model_notice(selected_model, "nous"):
  1567. print(f" ⚠ {_notice}") # window plans only (a Large mark exists only on their catalog)
  1568. print(f" Config updated: {config_path} (model.provider=nous)")
  1569. except KeyboardInterrupt:
  1570. print("\nLogin cancelled.")
  1571. raise SystemExit(130)
  1572. except Exception as exc:
  1573. from hermes_cli.auth_error_copy import sign_in_failure_lines
  1574. logger.debug("nous login failed: %r", exc)
  1575. print()
  1576. for line in sign_in_failure_lines(exc, service_host=_portal_host(getattr(args, "portal_url", None))):
  1577. print(line)
  1578. raise SystemExit(1)
  1579. def _portal_host(portal_url: Optional[str]) -> str:
  1580. return urlparse(portal_url or DEFAULT_NOUS_PORTAL_URL).hostname or "portal.nousresearch.com"