Files
hermes-agent/hermes_cli/anon_auth.py
Siddharth Balyan 4bdd64b334 The free tier is created in one place, at boot, only behind HERMES_GUEST_ONBOARDING=1 (NS-847) (#107697)
* fix(auth): close the free tier's gaps against the gateway's welcome-tier contract

The inference gateway's welcome tier (NousResearch/api DOCS/anon-tier/plan.md) serves an
anonymous account exactly one model on its own host, refuses everything else with a structured
429, cross-refuses a request on the wrong host with a 400 (403 while the tier is dark), and
tells a signed-in account that still asks for `nous/welcome` what to switch to in an
`x-nous-model-switch` header. Four client-side gaps against that contract:

- Auxiliary calls were refused on every session. The auxiliary client asked the welcome host
  for the Portal's recommended compaction/vision model, a guaranteed 429 `model_not_free`
  before each fallback. On the welcome host it now uses `nous/welcome` (its backing model
  covers auxiliary work) and skips Nous for vision, which the welcome model does not take.

- The structured 429 body was never read. The classifier now parses `reason` /
  `retry_after` / `alternates` / `upgrade_url`: `model_not_free` and `feature_not_free` are
  non-retryable gates that fall back; `at_capacity`, `admission_closed` and `rate_limited`
  are rate limits that honour `retry_after` and never rotate the free tier's only credential.
  The wrong-host 400 and the dark-tier 403 are deterministic, so they abort this route and
  fall back instead of retrying or re-exchanging. The terminal paths say what happened and
  name the sign-in (`/login` in a chat, `hermes auth upgrade` in a terminal).

- The `x-nous-model-switch` header was ignored. The chat-completions transport records it
  beside the rate-limit and credits headers; the next call moves the session, and the config
  default when it still names `nous/welcome`, to the backing model the gateway named.

- A guest fell back to the paid host. With `inference_base_url` absent from the exchange or
  outside the host allowlist, routing defaulted to inference-api, where every request is a
  400. A guest now defaults to the welcome literal at the exchange, in the shared store's
  shape, and in effective routing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit fc758aad7efceff6223fc144a9b5c69f13e41bd8)

* feat(auth): the free tier is set up on request; nous.guest_setup decides whether also on first use

A caller that names nous/welcome on a Nous route with no Nous identity in reach — the guided
setup's session (provider=nous, which skips the resolver's nothing-configured rung), the free-tier
picker row, a bare --provider nous pointed at it — is asking for the free tier. The OAuth runtime
rung now sets it up there instead of failing "not logged in", so the guided chat no longer races
the root profile's first-run mint.

nous.guest_setup is the policy seam: "auto" (default) keeps today's first-use setup wherever
nothing else is configured; "on-request" mints only when the free tier is asked for by name
(nous/welcome, /login, hermes auth upgrade, replacing a retired identity). Implicit callers —
the resolver's last rung, the first-run check, free_tier.status, the CLI's background setup, the
connector token path — still adopt what the shared store holds, so every profile follows the one
identity the guided setup created, but never create one on their own.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit ae915ddc65ecdb81b81e29b604671d15cd49233c)
(cherry picked from commit 62ad1ff3ab200ea064975a32c502041b25910165)

* feat(auth): the guided setup provisions the free tier explicitly; nous.guest_setup is auto | explicit

Two questions govern the free tier: may it exist (nous.guest) and who may CREATE the identity
(nous.guest_setup). "auto" (default) keeps today's first-use setup wherever nothing else is
configured. "explicit" means Hermes never creates one on its own: the only creator is the new
provision_free_tier() primitive, exposed as the free_tier.provision RPC, which the guided setup
on Hermes Desktop calls as its first step — on the root gateway, before the setup profile and
before the guided chat exists — so the identity lands in the root store every profile reads
through and is there before any session asks for nous/welcome. That closes the race against the
backend's own setup, and makes "only when the setup-bot flow is used" literally true.

The earlier "on-request" tier is replaced: it minted whenever any caller named nous/welcome
(the hermes model row, --provider nous), which treated a model name as intent and was broader
than the guided setup. Under "explicit" a nous/welcome request with no identity fails "not
logged in" as before the free tier existed, and /login or hermes auth upgrade report nothing to
sign in from. Implicit callers still adopt an identity the shared store holds, and a retired
credential is replaced (a continuation, not a creation).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit c63d2c935c1e59016164fdfb90cf70b4094466a0)

* fix(auth): remove the nous.guest_setup knob; the free tier is created on first use

`nous.guest_setup: auto | explicit` decided who may CREATE the free-tier identity. Under its
default every line it added was inert (`may_mint` always true), nothing in tree set `explicit`,
unknown values read as `auto`, and under `explicit` a CLI-only install could never get an
identity, which contradicts the first-run contract (first command mints, then chats).

The mint race the knob accompanied is already benign: every caller takes the profile lock then
the shared-store lock, and the loser adopts what the winner wrote. What makes the guided setup
win deterministically is `provision_free_tier()` behind the `free_tier.provision` RPC, which
stays. `nous.guest` remains the only free-tier policy.

Removed: `guest_setup_policy()` and its constants, the `explicit=` / `may_mint=` threading through
`ensure_portal_identity` and `_reconcile_and_provision`, the flag at the three replacement call
sites (now no-ops), the config default, the docs section, and the four `guest_setup` test-config
entries. The three policy tests that hold regardless of the knob are kept under
`TestExplicitProvision`; the two that only tested the knob are deleted.

(cherry picked from commit d8a50526d93c374c0067dd935b5a65055e0af261)

* fix(gateway): a server-driven model switch off nous/welcome does not evict the cached agent

When a signed-in account still asks the paid host for `nous/welcome`, the inference gateway
serves the current backing model and names it in `x-nous-model-switch`. `apply_model_switch`
moves the live session to that model and moves `config.yaml`'s default off the alias in the
same step. The messaging gateway's fallback-eviction check compares the agent's model with the
config default and evicts on any mismatch that is not a /model override, so when the config
write did not land (unreadable config, lock) the cached agent was evicted once per turn, and
prompt caching with it.

`apply_model_switch` now stamps the alias it moved the session off on the agent, and
`_is_intentional_model_switch` treats "agent moved off the alias the config still carries" as
deliberate, beside the existing /model override case. The check takes the agent and the config
model instead of a bare model string; its one caller in `_run_agent_evict_on_fallback` passes them.

(cherry picked from commit 696d1ec86b69db28bf002c841e9389b85178a954)

* fix(auth): the free tier outranks implicit host credentials in provider resolution

On a fresh install with a leftover ~/.aws profile, resolve_provider("auto")
reached the Bedrock rung before the free-tier rung, so the first turn ran on
Bedrock and failed 403 while the free tier was still being minted in the
background at agent setup (NS-829). Live on a Mac with ~/.aws present: 28 s,
three retries, no answer; the next process then switched to nous/welcome.

The free-tier rung now sits directly above the Bedrock chain: when nous.guest
is on, an existing free-tier identity answers, else a blocking mint runs, and
only then does the boto chain get a say. Everything above is unchanged and
still wins: CLI creds, config.yaml model.provider, env keys, the OpenRouter
pool, a logged-in active_provider. nous.guest: false skips the rung, and a
failed mint still falls through to Bedrock and the no-provider guidance.

Tests: six precedence cases (identity present, fresh mint, free tier off, env
key still wins, sign-in still wins, failed mint falls through). The opt-out
test now neutralizes the AWS chain like the precedence tests do; on a machine
with ~/.aws it was failing for the same reason as the bug.

Live after the fix, same Mac, AWS credentials visible, isolated shared store:
identity minted 2 s in, turn on model=nous/welcome provider=nous, answer in
11 s.

(cherry picked from commit a04b05260cd334dd7199ad9b6cd5b2538364c75a)

* fix(auth): review follow-ups for the free-tier rung (NS-829)

- tests/agent/test_bedrock_integration.py: the Bedrock auto-detect test switches
  the free tier off; its contract is the boto chain, and the free tier now
  sits above it.
- gateway/run_notifications.py: the free-tier startup line reads auth.json
  before consulting the resolver, so a gateway boot on a machine with AWS
  credentials never mints or refreshes over the network.
- hermes_cli/anon_auth.py: module docstring says where the free tier sits in
  the ladder instead of "the ladder is untouched".
- tests/hermes_cli/test_provider_precedence.py: two invariant tests instead of
  six (parametrized ladder cases; a failed mint that returns None or raises
  falls through to Bedrock).

scripts/run_tests.sh on the five affected files: 147 passed, 0 failed.

(cherry picked from commit 10790d148c60ada11b9ecdde2cd2c836c6a82a11)

* feat(auth): HERMES_GUEST_ONBOARDING=1 is the one launch gate for the free tier; HERMES_FORCE_GUEST is gone

The free tier is pre-GA. Until GA it must not exist for anyone who did not
ask for it: no identity minted, no portal traffic, no free-tier copy on any
surface. One environment variable now decides that, and one function reads it.

`guest_enabled()` returns False unless `HERMES_GUEST_ONBOARDING` is exactly
"1"; only then does `nous.guest` (the user's off switch) get consulted. Every
free-tier site already funnels through `guest_enabled()`, so the gate closes
minting, routing, connector entitlement, status lines and the picker row in
one place. With the variable unset, `resolve_provider("auto")` on a fresh
install raises `no_provider_configured` exactly as upstream does.

`HERMES_FORCE_GUEST` and `force_guest_mode()` are removed. They inverted the
gate (forced the tier ON over `nous.guest: false`), their "new" value re-minted
identities as a side effect of provider resolution, and `_has_any_provider_
configured` read them ahead of every other check, making the CLI a second
reader of a flag that must have exactly one. `_forced_new_done` and the
`force` parameter of `_reconcile_and_provision` go with them.

Supersedes the dev lever introduced in fcf9d11679 (rung 1) and hardened in
b5c162c3ec. Ruling: NS-845 Q1.1 (recorded on NS-847).

Not a user preference: the variable is never written to config.yaml or .env
and never shown in setup. It is deleted at GA together with its comment in
anon_auth.py. This is a deliberate, temporary exception to the "no new
HERMES_* env vars for non-secret config" rule.

Tests: fixtures set the gate instead of deleting the old lever; one new
invariant (`test_launch_gate_off_means_no_free_tier_at_all`) proves that "",
"0", "true" and "new" all leave the tier off with zero portal calls, red on the
previous commit. The `HERMES_FORCE_GUEST=new` re-mint test is deleted with the
feature.

* feat(auth): the free-tier identity is created in one place, at boot; every other site is a read

Before this commit eight sites could create a Nous free-tier identity as a
side effect of something else: resolving a provider, the CLI's first-run
check, the CLI's session setup (in the background beside an own key), a
connector bearer read, the desktop polling `free_tier.status`, the sign-in
precondition, the desktop's `free_tier.provision`, and the dead-credential
re-mint. A poll could mint. Provider resolution could hit the network. Two
of them raced each other on a fresh install.

Now `hermes_cli/free_tier_bootstrap.py::run_bootstrap` is the only creator.
`hermes serve` runs it on a daemon thread from `_lifespan` beside the other
background boots; `cmd_chat` runs it synchronously before the first-run
guard. It inventories credentials first (`resolve_provider("auto",
skip_free_tier=True)`: what would carry inference if the free tier did not
exist), creates the identity only when `guest_enabled()`, resolves inference,
records a `SetupRecord` in process memory and broadcasts ONE `setup.ready`
event. It runs on every boot; only the mint is gated.

`ensure_portal_identity` now requires `explicit=True` and raises otherwise.
Its callers are the bootstrap, the desktop's `free_tier.provision` (the
explicit retry when the boot could not create the identity) and the two
dead-credential replacements (`auth_nous.resolve_nous_runtime_credentials`,
`managed_tool_gateway._replace_dead_guest_token`). The background thread
path and `provision_free_tier` are deleted with their last callers.

Reads that used to mint and now only read: `auth.py::resolve_provider`
rung 7 (an existing identity still outranks the Bedrock chain, NS-829
ordering kept), `main.py::_has_any_provider_configured`,
`cli_agent_setup_mixin._ensure_runtime_credentials`,
`managed_tool_gateway.read_nous_access_token` (no identity -> None),
`anon_sign_in.run_sign_in` (no identity -> Unavailable),
`methods_free_tier` `free_tier.status`.

`setup.status` answers from the record for the launch profile, blocking up
to 8 s while the bootstrap is in flight so a client's first poll lands after
the identity exists rather than racing it; a named profile, or a process
that never ran the bootstrap, keeps today's live probe. The record's fields
ride along additively (`ready`, `free_tier`, `other_providers`,
`inference_provider`).

Identity and inference are decoupled (NS-845 Q1.3): the mint sets
`active_provider="nous"` only when the inventory found nothing else usable
(`_mint_locked(carries_inference=)`); an adopted account always does. A token
refresh no longer re-elects the provider it refreshed
(`_save_provider_state_to_source` writes credentials, not the user's
choice) — that write was how an own-key install ended up on the free tier
after the first connector call.

Supersedes the mint sites in fcf9d11679, a42d0748fc (first-run check),
bbbaa8935a (CLI background setup), 0179efc989 (`free_tier.status` mint),
62ad1ff3ab / c63d2c935c / d8a50526d9 (the `nous.guest_setup` knob and
`provision_free_tier`), and a04b05260c (blocking mint in the resolver).
Ruling: NS-845 Q1.2 + Q1.3, recorded on NS-847.

Tests: `TestBootstrapIsTheOneCreator` (one mint per process; own key keeps
inference; reads never reach the portal; a refused mint is memoised),
`free_tier.status` fails loudly if it ever calls the creator, the resolver
stub fails loudly if resolution ever mints, `setup.status` reads the record,
`skip_free_tier` proves the inventory question. The three sign-in tests for
the deleted pre-mint collapse into one (`no identity -> Unavailable, zero
portal calls`). Live: real `_lifespan` boot with a fake portal, gate on and
off (/tmp/ns847-recon/evidence/e2e-rung5-c2-serve-boot.txt), and the CLI
matrix incl. an own-key cell (e2e-rung5-c2-bootstrap.txt), 20/20.

* fix(credits): the welcome host is free-tier evidence, so a free-tier identity never sees "run /topup"

A free-tier identity carries $0 by design, so the portal seed reports
`paid_access=False` for it. `is_free_tier_model` did not know the welcome
host, read that as a depleted account, and every free-tier turn ended with
the credits-depleted notice telling the user to top up an account they do
not have.

Rule (4) in `is_free_tier_model`: a `base_url` on the Nous welcome host
(`anon_auth.route_is_welcome_host`) is the free tier. The host is the
evidence, not the model name: the paid inference host can serve
`nous/welcome` to a named account and that account's depletion is real, so
`("nous/welcome", <inference host>)` stays False. Local data only, like the
three rules above it.

Restores the two contracts dropped by hermes-magic 674e11d1eaa (the
prototype line ran without unit tests): the welcome host is free without
any pricing evidence; the model name alone is not. The first is red without
this fix.

* fix(copy): free-tier text stops promising a connector transfer and never names the config key

Sign-in copy on every surface said "Sign in to keep your connectors" and
ended with "Your connectors are kept." The transfer registry that would
make that true is empty (NS-821): nothing carries over today. The copy now
says what signing in does give ("unlock more models and tools") and the
completion line names the account, not a transfer. The docs page loses the
"connectors carry over" paragraph for the same reason.

The picker's off-state line exposed `nous.guest: false` and the word
"guest"; user copy names the free tier only (R-USR-1).

The docs page gains the pre-rollout note: until GA nothing on it happens
without `HERMES_GUEST_ONBOARDING=1`. Its "first command mints" and
"replaced on next use" sentences now describe the boot bootstrap.

zh is a strict locale: the `freeTier` block was English placeholder text
copied from `en`; it is now Chinese. `connectorsKept` is renamed
`completedBody` since it no longer talks about connectors.

* feat(desktop): the free-tier launch flag is decided once in Electron and stamped onto every backend spawn

The Python backend reads `HERMES_GUEST_ONBOARDING` and treats exactly "1"
as on. Until now nothing in the desktop set it, so a packaged app could
never turn the free tier on, and a backend spawned by the app could
disagree with the app about whether the tier was live.

`electron/guest-onboarding.ts` owns the decision: `guestOnboardingEnabled`
is true when the launch env has `HERMES_GUEST_ONBOARDING=1` or argv has
`--guest-onboarding` (the packaged-app spelling). It is read ONCE at launch
into a module constant. `desktopBackendSpawnEnv` wraps every backend env
as the outermost call and writes the flag LAST, as "1" or an explicit "0",
so no earlier spread (`process.env`, `backend.env`) can resurrect a stray
value from the parent shell.

Stamped onto all three spawn sites: the primary `serve` spawn, the pooled
per-profile spawn, and the remote SSH `exec env ...` command (which gains
` HERMES_GUEST_ONBOARDING=1` only when on). The embedded terminal PTY and
the backend probes are not backend spawns and do not get it: a
`hermes --tui` typed in the pane must not mint.

The renderer learns the same fact read-only through the existing
`hermes:launch-flags` sync IPC (`guestOnboarding`) and preload
(`window.hermesDesktop.guestOnboardingEnabled`).

Ruling: NS-845 Q1.1 / Q2 (env var is the contract, `--guest-onboarding`
maps to it in main). Two invariant tests on the pure helpers: only "1" or
the argv flag enables; the spawn env carries "1"/"0" as the last word and
preserves every other key.

* feat(desktop): the renderer learns free-tier readiness from one `setup.ready` push, not a 60 s poll

The backend's boot bootstrap now announces `setup.ready` once, after it has
created (or refused) the free-tier identity and resolved the inference
route. The renderer used to discover both by polling `setup.status`,
`setup.runtime_check` and `free_tier.status` every 60 s from
`useStatusSnapshot`; a fresh install's chip, notice strip and onboarding
overlay could sit stale for up to a minute after boot, and three RPCs a
minute per window kept asking a question whose answer changes only at
boundaries the backend already announces.

`handleLifecycleEvent` routes `setup.ready` (active source only, like
`skin.changed`) to `notifySetupReady()`, a one-shot tick atom in
`live-sync.ts` beside the other change ticks. `useStatusSnapshot` listens
to it and runs one readiness round at once (`setup.status` +
`setup.runtime_check` + `free_tier.status`). The readiness legs also run
once on open and on return from another app, as today. The 60 s tick keeps
only `getStatus()`.

`SetupStatusSnapshot` types the record's additive fields (`ready`,
`free_tier`, `other_providers`, `inference_provider`); readiness semantics
are unchanged and still key on `provider_configured` + `runtime_check`.

Ruling: NS-845 Q1.2 (renderer half). Tests: the lifecycle branch fires one
refresh from the active source and none from another; the snapshot hook's
contract is three legs on open, one leg on the tick.

* fix(cli): the banner names the free tier's model instead of "no model configured"

The welcome banner prints before credentials resolve, so on a fresh install
`model` is empty and the banner said, in red, "no model configured — run
/model or hermes setup". Under the free tier that is false: the route is
already known from local state (identity on disk, tier on), and the first
message will run on `nous/welcome`.

`_banner_left_lines` now asks the route the same question when `model` is
empty (`guest_carries_inference()`, a local read) and shows `welcome · Nous
Research`. When nothing resolves the red line stays. Ruling: NS-845 ("the
banner's 'no model configured' line reads the resolved route").

Live: fresh HERMES_HOME + fake portal, gate on -> `welcome · Nous Research`;
gate off -> the red line, zero portal calls.

* fix(aux): vision on the free tier uses nous/welcome too

The text-only modality on the gateway's `nous/welcome` row is DeepSeek V4 Flash's, the
backing model until the repoint; `z-ai/glm-5.3-flash` is natively multimodal and the
repoint declares the welcome row `text+image->text`. Skipping Nous for vision on the
welcome host would have sent every image step past the free tier for no reason, so the
auxiliary client pins the route's one model for every lane. A backing model that takes
no images answers with the upstream's own error, which the ladder handles as it always has.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit 7456e028faba55480db43015dc2c8df3e393a415)

* fix(gateway): hermes gateway run is a boot owner of the free tier too

Rung 5 made every demand-time free-tier site a read: resolve_provider,
the connector token, the /login precondition. That is only correct if
every process that can reach those sites ran the bootstrap first. The
CLI (cmd_chat) and hermes serve (_lifespan) did; the standalone
messaging gateway did not. A fresh HERMES_HOME with the gate on and
`hermes gateway run` reached provider resolution with no identity to
consume, and /login returned Unavailable. Reported by @andrexibiza on
#107697 (P1).

GatewayRunner.start now runs `free_tier_bootstrap.run_bootstrap` on an
executor thread right after startup recovery and BEFORE any adapter
connects, so a fast first DM cannot arrive with nothing to resolve. It
is its own step, not part of the turn-machinery warm-up: the warm-up is
an optimisation with an off switch (HERMES_STARTUP_WARMUP_TIMEOUT<=0);
the bootstrap is correctness and must always run. With the gate unset it
is a local inventory and no network.

Live, real GatewayRunner.start against a fake portal in a fresh home:
  gate on   -> 1 create, identity persisted, resolve_runtime_provider=nous,
               /login precondition sees the identity
  gate off  -> 0 portal calls, no identity, no_provider_configured
Before the fix the gate-on row was identical to the gate-off row.

Test: the bootstrap seam runs before _start_prefilter_platforms and
delegates to the one creator. Red on 5554eb6993 (no seam), green here.

---------

Co-authored-by: Robin Fernandes <robin@soal.org>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 03:45:33 +05:30

853 lines
43 KiB
Python

"""Nous free-tier identity: the ``anonymous`` auth method of the ``nous`` provider.
The identity is created in exactly one place, at boot (``hermes_cli.free_tier_bootstrap``), and only
while ``HERMES_GUEST_ONBOARDING=1`` (see ``guest_enabled``). The bootstrap mints an anonymous Nous
account (``POST /api/anonymous/create``); its ``anon_`` credential is later exchanged for short-lived
JWTs (``POST /api/anonymous/token``). The result is persisted as the singleton ``providers.nous``; it
becomes ``active_provider`` only when the bootstrap's inventory found nothing else usable, so an
install with its own key keeps that key for inference and uses the identity for connectors only. In
the resolver ladder (``resolve_provider``) an existing free-tier identity sits directly above the
implicit AWS Bedrock chain (NS-829): any explicit provider (env key, ``model.provider``, OpenRouter
pool, a logged-in ``active_provider``) beats it, and the ladder never creates one.
Only two mechanics differ from an OAuth login and both are isolated behind ``is_guest_state``:
token acquisition (re-exchange the ``anon_`` credential; there is no refresh token) and routing
(the welcome inference host, single model ``nous/welcome``).
Users are never shown the words guest / anonymous / account for this state: surfaces say
"Nous · free tier". Two user-facing verbs reach the same flow, both keeping the identity's
connectors: ``hermes auth upgrade`` in a terminal and ``/login`` inside a chat.
Lifecycle lives in ONE primitive, :func:`ensure_portal_identity`: adopt what the shared store already
holds, else mint under the shared-store lock. It is the only minter; nothing else calls
:func:`mint_guest`.
"""
from __future__ import annotations
import logging
import os
import time
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Dict, Optional
from hermes_cli.auth_constants import (
AuthError, DEFAULT_NOUS_PORTAL_URL, DEFAULT_NOUS_WELCOME_URL, _decode_jwt_claims, httpx)
logger = logging.getLogger("hermes_cli.auth")
ANON_AUTH_METHOD = "anonymous"
ANON_CLIENT_ID = "nas-anonymous"
ANON_ACCOUNT_TIER = "anonymous"
GUEST_MODEL = "nous/welcome"
ANON_SECRET_HEADER = "x-anonymous-api-secret"
# The shared secret gates the anonymous surface during its integration phase. It is a deployment
# secret (Sid's), read from the environment only.
ANON_SECRET_ENV = "HERMES_ANON_API_SECRET"
# Launch gate for the whole free tier while it is pre-GA: exactly "1" turns it on for this process
# (CLI, gateway, serve backend alike); anything else leaves every surface behaving as if the free
# tier did not exist. ``guest_enabled`` is the only reader. Not a user preference: never written to
# config.yaml or .env, never shown in setup. Deleted at GA together with this comment.
GUEST_ONBOARDING_ENV = "HERMES_GUEST_ONBOARDING"
GUEST_MINT_TIMEOUT_SECONDS = 5.0
# Copy shared by every surface that names the free tier (R-USR-1): never guest / anonymous / account.
FREE_TIER_LABEL = "Nous · free tier"
UPGRADE_HINT = "Run `hermes auth upgrade` to sign in with a Nous account, or /login inside a chat."
FREE_TIER_NOT_SIGNED_IN = (
"You're not signed in. Free inference and connectors are always on. "
"Run `hermes auth` to sign in with a Nous account.")
class AnonCredentialDead(AuthError):
"""NAS no longer knows this ``anon_`` credential (reaped, or claimed into a real account).
The one client rule for reap AND claim: mark dead, re-mint on the next need.
"""
def _anon_err(message: str, code: str) -> AuthError:
return AuthError(message, code=code)
def guest_enabled() -> bool:
"""The free tier is on for this process: the launch gate is set AND ``nous.guest`` (default
True) has not switched it off. The only place either is read."""
if (os.environ.get(GUEST_ONBOARDING_ENV) or "").strip() != "1":
return False
try:
from hermes_cli.config import load_config_readonly
nous_cfg = load_config_readonly().get("nous")
except Exception as exc: # config unreadable: keep today's behaviour (no guest) rather than mint
logger.debug("guest: config unreadable, treating nous.guest as false: %s", exc)
return False
if not isinstance(nous_cfg, dict):
return True
return bool(nous_cfg.get("guest", True))
def is_guest_state(state: Any) -> bool:
return isinstance(state, dict) and state.get("auth_method") == ANON_AUTH_METHOD
def current_nous_state() -> Optional[Dict[str, Any]]:
"""The profile's ``providers.nous`` state without locking or network (status/picker reads)."""
from hermes_cli.auth import _load_auth_store, _load_provider_state
try:
return _load_provider_state(_load_auth_store(), "nous")
except Exception as exc:
logger.debug("guest: auth store unreadable: %s", exc)
return None
def has_guest() -> bool:
return is_guest_state(current_nous_state())
def guest_carries_inference() -> bool:
"""True when the profile's Nous identity is the free tier and the free tier is on.
Profile-level: use for status, picker and notice surfaces. Routing decisions (which model a
request may carry) must use :func:`route_is_welcome_host` on the SELECTED runtime instead: a
credential-pool entry can pick a paid Nous key while the profile singleton is still a guest.
"""
return guest_enabled() and has_guest()
WELCOME_HOSTS = frozenset({"welcome-api.nousresearch.com"})
def pin_model_for_route(provider: Any, base_url: Any, model: Any) -> Any:
"""Model policy at agent START: on the Nous welcome host the model is ``nous/welcome``; anywhere
else the caller's model stands. Used once, when the route is first finalized. Mid-conversation
route changes go through :func:`route_can_serve_model` instead: a conversation's model is never
silently rewritten by a credential rotation.
"""
if provider == "nous" and route_is_welcome_host(base_url):
if model and model != GUEST_MODEL:
logger.info("Nous free tier: using %s instead of configured model %s", GUEST_MODEL, model)
return GUEST_MODEL
return model
def route_can_serve_model(provider: Any, base_url: Any, model: Any) -> bool:
"""Eligibility for a credential ROTATION: the welcome host serves only ``nous/welcome``, so a
conversation on any other model must not be rotated onto it (and a ``nous/welcome`` conversation
may move to the portal host, which serves it too). Non-Nous routes are always eligible."""
if provider != "nous" or not route_is_welcome_host(base_url):
return True
return not model or model == GUEST_MODEL
def route_is_welcome_host(base_url: Any) -> bool:
"""The routing predicate for the free tier: the welcome host serves exactly ``nous/welcome``.
Keyed on the resolved endpoint, never on profile state, so a paid pool credential routed to the
portal host keeps its model even when a guest singleton exists beside it.
"""
from urllib.parse import urlparse
try:
host = (urlparse(str(base_url or "")).hostname or "").lower()
except ValueError:
return False
return host in WELCOME_HOSTS
def anon_secret() -> str:
return (os.environ.get(ANON_SECRET_ENV) or "").strip()
def _anon_headers() -> Dict[str, str]:
headers = {"content-type": "application/json"}
if secret := anon_secret():
headers[ANON_SECRET_HEADER] = secret
return headers
def _raise_for_anon_status(response: httpx.Response, *, action: str) -> Dict[str, Any]:
try:
payload = response.json()
except ValueError:
payload = {}
if not isinstance(payload, dict):
payload = {}
error = str(payload.get("error") or "")
if response.status_code in (200, 201):
return payload
if response.status_code == 404 and error == "unknown_token":
raise AnonCredentialDead("Nous free-tier credential is no longer valid.", code="anon_credential_dead")
if response.status_code == 401 and error == "invalid_shared_secret":
raise _anon_err("Nous free tier is not open on this portal.", "anon_gate_closed")
if response.status_code == 401:
raise AnonCredentialDead("Nous free-tier credential was revoked.", code="anon_credential_dead")
if response.status_code == 429:
raise _anon_err("Nous free tier is rate limited; try again shortly.", "anon_rate_limited")
if response.status_code == 403 and error in {"anonymous_accounts_disabled", "circuit_open"}:
raise _anon_err("Nous free tier is currently disabled.", "anon_gate_closed")
raise _anon_err(
f"Nous free tier {action} failed ({response.status_code}{': ' + error if error else ''}).",
"anon_server_error")
def mint_guest(client: httpx.Client, portal_base_url: str) -> Dict[str, Any]:
"""``POST /api/anonymous/create`` -> ``{user_id, org_id, token, idle_ttl_days}``. Token shown once."""
response = client.post(f"{portal_base_url.rstrip('/')}/api/anonymous/create", headers=_anon_headers(), json={})
payload = _raise_for_anon_status(response, action="sign-up")
token = payload.get("token")
if not isinstance(token, str) or not token.startswith("anon_"):
raise _anon_err("Nous free tier sign-up returned no credential.", "anon_server_error")
return payload
def exchange_anon_jwt(client: httpx.Client, portal_base_url: str, anon_token: str) -> Dict[str, Any]:
"""``POST /api/anonymous/token {token}`` -> ``{access_token, expires_in, inference_base_url, ...}``.
Raises :class:`AnonCredentialDead` on 404 ``unknown_token`` / 401 (reaped or claimed).
"""
response = client.post(
f"{portal_base_url.rstrip('/')}/api/anonymous/token", headers=_anon_headers(), json={"token": anon_token})
payload = _raise_for_anon_status(response, action="token exchange")
if not isinstance(payload.get("access_token"), str) or not payload["access_token"]:
raise _anon_err("Nous free tier token exchange returned no token.", "anon_server_error")
return payload
def apply_exchange_to_state(state: Dict[str, Any], exchanged: Dict[str, Any]) -> None:
"""Write a fresh exchange result into a guest state in place (token, expiry, routing)."""
from hermes_cli.auth_nous import _validate_nous_inference_url_from_network
access_token = exchanged["access_token"]
claims = _decode_jwt_claims(access_token)
now = datetime.now(timezone.utc)
exp = claims.get("exp")
if isinstance(exp, (int, float)):
expires_at = datetime.fromtimestamp(float(exp), tz=timezone.utc)
else:
expires_at = now + timedelta(seconds=int(exchanged.get("expires_in") or 900))
# NAS names the welcome host on every exchange; absent (older NAS) or outside the allowlist
# (a staging host without NOUS_INFERENCE_BASE_URL set), the literal stands in. Never the paid
# host: the gateway cross-refuses an anonymous JWT there.
inference_url = (_validate_nous_inference_url_from_network(exchanged.get("inference_base_url"))
or DEFAULT_NOUS_WELCOME_URL)
scope = claims.get("scope") or claims.get("scp") or state.get("scope")
if isinstance(scope, (list, tuple)):
scope = " ".join(str(s) for s in scope)
state.update(
access_token=access_token, token_type="Bearer", scope=scope,
obtained_at=now.isoformat(), expires_at=expires_at.isoformat(),
expires_in=max(0, int((expires_at - now).total_seconds())),
account_tier=str(claims.get("account_tier") or ANON_ACCOUNT_TIER))
state["inference_base_url"] = inference_url
for key in ("user_id", "org_id"):
if exchanged.get(key):
state[key] = exchanged[key]
state.pop("refresh_token", None)
def _portal_base_url() -> str:
from hermes_cli.auth_nous import _nous_portal_env_override
return (_nous_portal_env_override() or DEFAULT_NOUS_PORTAL_URL).rstrip("/")
def _shared_identity_key(state: Any) -> Optional[str]:
"""Stable identity of a Nous credential: the anon_ token for a guest, the refresh token for an
account. Used to decide whether two stores hold the SAME identity."""
if not isinstance(state, dict):
return None
return state.get("anon_token") if is_guest_state(state) else state.get("refresh_token")
def _mint_locked(
client: httpx.Client, portal: str, auth_store: Dict[str, Any], *, carries_inference: bool = True,
) -> Dict[str, Any]:
"""Mint under the caller's locks. The identity is persisted as soon as ``create`` succeeds, BEFORE
the exchange: a 429 or timeout on the exchange must not lose a credential NAS still honours (the
next attempt exchanges the stored one instead of minting again).
``carries_inference`` decides whether the new identity also becomes ``active_provider``. The
bootstrap passes False when its inventory found another usable provider: the identity exists for
connectors, the user's own provider keeps carrying inference (NS-845 Q1.3)."""
from hermes_cli.auth import _store_provider_state, _save_auth_store
from hermes_cli.auth_nous import _write_shared_nous_state
minted = mint_guest(client, portal)
state: Dict[str, Any] = {
"auth_method": ANON_AUTH_METHOD, "account_tier": ANON_ACCOUNT_TIER,
"anon_token": minted["token"], "client_id": ANON_CLIENT_ID,
"portal_base_url": portal.rstrip("/"),
"user_id": minted.get("user_id"), "org_id": minted.get("org_id"),
"idle_ttl_days": minted.get("idle_ttl_days"),
}
_store_provider_state(auth_store, "nous", state, set_active=carries_inference)
_save_auth_store(auth_store)
_write_shared_nous_state(state)
logger.info("Nous free tier ready (identity minted)")
return state
# Per-process memo: one failed mint is enough for a process (a 429 or a closed gate must not be hit
# twice); ``clear_dead_guest`` resets it because a retired credential is a reason to mint again.
_mint_failed = False
def _reconcile_and_provision(*, timeout_seconds: float, carries_inference: bool = True) -> Optional[Dict[str, Any]]:
"""The lifecycle body, run under profile lock THEN shared lock (the documented order).
1. The shared store is the identity of record for this Hermes root. If it holds an identity
that differs from the profile's, the profile adopts it (a stale guest never outlives a
sibling profile's sign-in, and never overwrites it). An adopted free-tier identity claims
``active_provider`` under the same rule as a mint; an adopted ACCOUNT always does (the user
signed in somewhere on this machine).
2. Otherwise the profile's own identity stands.
3. Nothing anywhere: mint, persisting the credential before exchanging it.
"""
from hermes_cli.auth import (
_auth_store_lock, _load_auth_store, _load_provider_state, _save_auth_store,
_store_provider_state, _resolve_verify)
from hermes_cli.auth_nous import (
_nous_http_client, _nous_shared_store_lock, _read_shared_nous_state, _write_shared_nous_state)
portal = _portal_base_url()
with _auth_store_lock():
auth_store = _load_auth_store()
profile_state = _load_provider_state(auth_store, "nous")
with _nous_shared_store_lock(timeout_seconds=max(timeout_seconds, 5.0)):
shared = _read_shared_nous_state()
if shared and _shared_identity_key(shared) != _shared_identity_key(profile_state):
state = dict(shared)
_store_provider_state(
auth_store, "nous", state,
set_active=carries_inference or not is_guest_state(state))
_save_auth_store(auth_store)
logger.debug("Nous identity adopted from the shared store")
return state
if profile_state:
if not shared:
_write_shared_nous_state(profile_state)
return profile_state
verify = _resolve_verify(insecure=None, ca_bundle=None, auth_state=None)
with _nous_http_client(timeout_seconds, verify) as client:
return _mint_locked(client, portal, auth_store, carries_inference=carries_inference)
def ensure_portal_identity(
*, explicit: bool, timeout_seconds: float = GUEST_MINT_TIMEOUT_SECONDS,
carries_inference: bool = True,
) -> Optional[Dict[str, Any]]:
"""Make sure this profile has a Nous identity (guest or account); mint a guest only if the shared
store has none. Returns the ``providers.nous`` state, or None (disabled / failed once already).
``explicit`` is required and must be True: the only callers are the boot bootstrap
(``free_tier_bootstrap.run_bootstrap``), the desktop's ``free_tier.provision`` retry, and the
dead-credential replacements (``auth_nous.resolve_nous_runtime_credentials``,
``managed_tool_gateway._replace_dead_guest_token``). Nothing creates an identity as a side effect
of reading status, resolving a provider or fetching a connector bearer (NS-845 Q1.2).
Order: ``guest_enabled`` gate -> reconcile with the shared store -> mint. Locks are taken profile
first, then shared, matching every other Nous path. ``carries_inference=False`` leaves
``active_provider`` alone (the identity is for connectors; another provider does inference).
Blocking, bounded by ``timeout_seconds``; the bootstrap puts it on its own thread.
"""
if not explicit:
raise ValueError("ensure_portal_identity: only explicit creators may call this (explicit=True)")
global _mint_failed
if not guest_enabled():
return None
if _mint_failed and not current_nous_state():
return None # this process already tried and failed; do not hammer the portal
try:
return _reconcile_and_provision(
timeout_seconds=timeout_seconds, carries_inference=carries_inference)
except Exception:
_mint_failed = True
raise
def refresh_guest_state(state: Dict[str, Any], client: httpx.Client) -> None:
"""Token-acquisition seam for a guest: re-exchange the ``anon_`` credential in place.
The portal URL is the resolver's canonical one (env override, else the validated stored URL,
else the default), never a raw stored value on its own.
Raises :class:`AnonCredentialDead` when NAS no longer knows the credential; the caller owns
re-minting (:func:`ensure_portal_identity` after :func:`clear_dead_guest`).
"""
anon_token = state.get("anon_token")
if not isinstance(anon_token, str) or not anon_token:
raise AnonCredentialDead("Nous free-tier credential is missing.", code="anon_credential_dead")
from hermes_cli.auth import _nous_portal_base_url
apply_exchange_to_state(state, exchange_anon_jwt(client, _nous_portal_base_url(state), anon_token))
def clear_dead_guest(reason: str, *, dead_token: Optional[str] = None) -> None:
"""Drop a dead guest so the next need re-mints.
Only the identity that actually failed is removed: a stale profile whose credential NAS rejected
must not erase a sibling profile's newer sign-in or replacement guest from the shared store. When
*dead_token* is None the profile's current guest is treated as the failed one.
"""
from hermes_cli.auth import (
_auth_store_lock, _load_auth_store, _load_provider_state, _save_auth_store, _store_section)
from hermes_cli.auth_nous import _clear_shared_nous_state, _nous_shared_store_lock, _read_shared_nous_state
with _auth_store_lock():
auth_store = _load_auth_store()
state = _load_provider_state(auth_store, "nous")
if is_guest_state(state):
token = dead_token or state.get("anon_token")
if state.get("anon_token") == token:
_store_section(auth_store, "providers").pop("nous", None)
_store_section(auth_store, "credential_pool").pop("nous", None)
if auth_store.get("active_provider") == "nous":
auth_store["active_provider"] = None
_save_auth_store(auth_store)
else:
token = dead_token
with _nous_shared_store_lock():
shared = _read_shared_nous_state()
if token and is_guest_state(shared) and shared.get("anon_token") == token:
_clear_shared_nous_state(reason)
global _mint_failed
_mint_failed = False
logger.info("Nous free-tier identity retired (%s); a new one is set up on next use", reason)
# --- Gateway welcome-tier contract: structured refusals and the model-switch header ------------------
#
# The inference gateway answers a welcome-tier request it will not serve with a structured 429
# (``{status, message, reason, retry_after, alternates?, upgrade_url?}``), and a request on the wrong
# host with a 400 (or a 403 while the tier is dark) whose message names the right host. A NAMED
# account that still asks for ``nous/welcome`` is served the id's backing model and told what to
# switch to in the ``x-nous-model-switch`` response header. Every rule for reading those lives here;
# the error classifier and the turn loop only call in.
MODEL_SWITCH_HEADER = "x-nous-model-switch"
# Fairshare refusal reasons the welcome tier can answer with (api ``FairshareRefusalReason``).
WELCOME_REFUSAL_REASONS = frozenset(
{"model_not_free", "feature_not_free", "at_capacity", "admission_closed", "rate_limited"})
# Reasons that mean "not on this tier, ever": no retry helps, only a sign-in or another provider.
WELCOME_TIER_GATE_REASONS = frozenset({"model_not_free", "feature_not_free"})
# Gateway messages (lowercased substrings) for a request on the wrong host or a dark tier.
_WELCOME_ROUTE_REFUSALS = (
("anonymous accounts must use", "anon_on_paid_host"),
("serves anonymous hermes agent accounts only", "named_on_welcome_host"),
("anonymous accounts are not accepted", "tier_disabled"),
)
_WELCOME_ROUTE_COPY = {
"anon_on_paid_host": "The Nous free tier must use its own inference host ({host}); "
"Hermes is pointed at the paid one. Restart Hermes to re-read the route, "
"or unset NOUS_INFERENCE_BASE_URL if you set it.",
"named_on_welcome_host": "This Nous account must use the Nous Portal inference host, "
"not the free tier's. Run /model and pick the Nous row again.",
"tier_disabled": "The Nous free tier is switched off right now. {signin}",
}
_SIGNIN_CHAT = "Sign in with a Nous account for the full catalog: /login."
_SIGNIN_TERMINAL = "Sign in with a Nous account for the full catalog: `hermes auth upgrade`."
def parse_welcome_refusal(body: Any) -> Optional[Dict[str, Any]]:
"""The structured welcome-tier refusal in a gateway 429 body, or None for any other shape.
Returns ``{"reason", "retry_after", "alternates", "upgrade_url"}`` with ``retry_after`` an int
of whole seconds (0 when the gateway sent none) and ``alternates`` a list of model ids.
"""
if not isinstance(body, dict):
return None
reason = body.get("reason")
if not isinstance(reason, str) or reason not in WELCOME_REFUSAL_REASONS:
return None
raw_retry = body.get("retry_after")
try:
retry_after = max(0, int(float(raw_retry))) if raw_retry not in (None, "") else 0
except (TypeError, ValueError):
retry_after = 0
raw_alternates = body.get("alternates")
alternates = [str(a) for a in raw_alternates if isinstance(a, str) and a] if isinstance(raw_alternates, list) else []
upgrade_url = body.get("upgrade_url")
return {"reason": reason, "retry_after": retry_after, "alternates": alternates,
"upgrade_url": upgrade_url if isinstance(upgrade_url, str) else ""}
def welcome_refusal_copy(refusal: Dict[str, Any], *, model: str = "", in_chat: bool = True) -> str:
"""User copy for a structured welcome-tier refusal: what happened and the one way forward.
Never guest / anonymous / claim; ``in_chat`` picks ``/login`` over the terminal verb."""
signin = _SIGNIN_CHAT if in_chat else _SIGNIN_TERMINAL
reason = str(refusal.get("reason") or "")
alternates = refusal.get("alternates") or []
serves = alternates[0] if alternates else GUEST_MODEL
retry = int(refusal.get("retry_after") or 0)
wait = f"Retrying in {retry}s." if retry > 0 else "Try again shortly."
if reason == "model_not_free":
what = f"{model} isn't on the Nous free tier" if model else "That model isn't on the Nous free tier"
return f"{what}; it serves {serves} only. {signin}"
if reason == "feature_not_free":
return f"This feature isn't on the Nous free tier. {signin}"
if reason == "at_capacity":
return f"The Nous free tier is at capacity and briefly paused. {wait} {signin}"
if reason == "admission_closed":
return f"The Nous free tier isn't admitting new sessions right now. {wait} {signin}"
if reason == "rate_limited":
return f"Nous free tier rate limit active \u2014 resets in {retry}s. {signin}"
return f"The Nous free tier refused this request ({reason}). {signin}"
def welcome_route_refusal(status: Any, message: Any) -> Optional[str]:
"""Which host cross-refusal a gateway 400/403 is, by its message; None for any other error.
``"anon_on_paid_host"``: a free-tier JWT reached the paid host. ``"named_on_welcome_host"``: an
account or API key reached the free tier's host. ``"tier_disabled"``: the tier is dark
(``WELCOME_MODE=off``). Each is deterministic for the request: retrying cannot help."""
if status not in (400, 403):
return None
text = str(message or "").lower()
return next((kind for needle, kind in _WELCOME_ROUTE_REFUSALS if needle in text), None)
def welcome_route_refusal_copy(kind: str, *, in_chat: bool = True) -> str:
template = _WELCOME_ROUTE_COPY.get(kind) or "The Nous inference gateway refused this route."
return template.format(
host=DEFAULT_NOUS_WELCOME_URL, signin=_SIGNIN_CHAT if in_chat else _SIGNIN_TERMINAL)
def note_model_switch(agent: Any, headers: Any) -> Optional[str]:
"""Record the gateway's ``x-nous-model-switch`` header on *agent* for the next call, if present.
The header arrives on a NAMED account's response that asked for ``nous/welcome`` (the gateway
served the backing model and billed it normally): the free tier's model no longer belongs in
this install's configuration. Recorded here, applied by :func:`apply_model_switch` between
calls so a response still streaming is never re-labelled under itself. Returns the backing id.
"""
if headers is None:
return None
value = None
try:
value = headers.get(MODEL_SWITCH_HEADER)
if value is None and hasattr(headers, "items"):
value = next((v for k, v in headers.items() if str(k).lower() == MODEL_SWITCH_HEADER), None)
except Exception:
return None
backing = str(value or "").strip()
if not backing:
return None
requested = str(getattr(agent, "model", "") or "")
if backing == requested:
return None
try:
agent._nous_pending_model_switch = (requested, backing)
except Exception:
return None
return backing
def apply_model_switch(agent: Any) -> Optional[str]:
"""Move *agent* (and the config default, when it still names the switched id) to the backing
model the gateway named. Returns the new model, or None when nothing was pending.
Runs once per recorded header, between calls. The conversation keeps its history; only the id
the next request carries changes, so a promoted account stops relying on the gateway's reverse
map. The config write is the same one a sign-in completion uses, so ``hermes model`` and the
gateway's config re-read agree with the live session.
"""
pending = getattr(agent, "_nous_pending_model_switch", None)
if not pending:
return None
agent._nous_pending_model_switch = None
requested, backing = pending
if str(getattr(agent, "model", "") or "") != requested:
return None # the session already moved (a /model, a sign-in sweep)
agent.model = backing
# The gateway's cache check compares agent.model with the config default and evicts on a
# mismatch it did not cause; this pair names the move so the check can recognise exactly this
# server-driven switch even when the config write below did not land.
agent._nous_model_switch = (requested, backing)
logger.info("Nous gateway asked to switch %s -> %s; applied for this session", requested, backing)
try:
from hermes_cli.config import load_config_readonly
raw = load_config_readonly().get("model")
model_cfg = raw if isinstance(raw, dict) else ({"default": raw} if isinstance(raw, str) else {})
if str(model_cfg.get("default") or "").strip() == requested:
from hermes_cli.auth import _update_config_for_provider
_update_config_for_provider(
"nous", str(getattr(agent, "base_url", "") or ""), default_model=backing)
logger.info("Config default model moved %s -> %s", requested, backing)
except Exception as exc:
logger.debug("model switch: config default left as is: %s", exc)
status = getattr(agent, "_buffer_status", None)
if callable(status):
try:
status(f"Model is now {backing} (your account's model; {requested} is the free tier's).")
except Exception:
pass
return backing
# One-time CLI notice: an install whose inference is carried by an explicit provider learns once that
# the free tier (inference + connectors) now exists. The flag lives on the guest state itself so it
# dies with the identity; a fresh guest (re-mint, new profile) may announce itself once more.
GUEST_NOTICE_FLAG = "guest_notice_shown"
FREE_TIER_AVAILABLE_NOTICE = (
"Free Nous inference and connectors are now available. "
"/model to try them, /login to sign in.")
def guest_notice_pending() -> bool:
"""True when a guest identity exists and the one-time availability notice has not been shown."""
state = current_nous_state()
return is_guest_state(state) and not bool(state.get(GUEST_NOTICE_FLAG))
def mark_guest_notice_shown() -> bool:
"""Persist ``guest_notice_shown`` on the guest's ``providers.nous`` state (whichever store holds it).
Returns True when a flag was written; False when there is no guest to mark."""
from hermes_cli.auth import (
_auth_file_path, _load_auth_store, _provider_state_transaction, _same_path, _save_auth_store,
_store_section)
with _provider_state_transaction("nous") as (auth_store, state, source_path):
if not is_guest_state(state) or source_path is None:
return False
if state.get(GUEST_NOTICE_FLAG):
return True
state = dict(state)
state[GUEST_NOTICE_FLAG] = True
if _same_path(source_path, _auth_file_path()):
_store_section(auth_store, "providers")["nous"] = state
_save_auth_store(auth_store)
else:
source_store = _load_auth_store(source_path)
_store_section(source_store, "providers")["nous"] = state
_save_auth_store(source_store, target_path=source_path)
return True
# --- ``hermes auth upgrade``: sign the guest into a real Nous account, keeping its connectors ---------
#
# Wire: the normal device-code flow, with a promotion intent registered on NAS BETWEEN the code
# request and the token poll (``POST /api/anonymous/promotion-intent {token, user_code, device_code}``).
# NAS then transfers the guest's connectors into whichever account approves that device code. We
# watch ``POST /api/anonymous/promotion-status {claim_code}`` until it leaves ``pending``; only a
# ``completed`` promotion is followed by the token grant, which ``persist_nous_credentials`` writes
# over the guest singleton and the shared store. The server never reports expiry: our own
# ``expires_in`` clock ends the wait. User-facing copy never says guest / anonymous / claim.
UPGRADED_AUTH_METHOD = "oauth_device_code"
def register_promotion_intent(
client: httpx.Client, portal_base_url: str, anon_token: str, *, user_code: str, device_code: str,
) -> Dict[str, Any]:
"""``POST /api/anonymous/promotion-intent`` -> ``{claim_code, claim_url, expires_in, interval}``."""
response = client.post(
f"{portal_base_url.rstrip('/')}/api/anonymous/promotion-intent", headers=_anon_headers(),
json={"token": anon_token, "user_code": user_code, "device_code": device_code})
payload = _raise_for_anon_status(response, action="sign-in")
if not isinstance(payload.get("claim_code"), str) or not payload["claim_code"]:
raise _anon_err("Nous free tier sign-in returned no transfer code.", "anon_server_error")
return payload
def _retry_after_seconds(response: httpx.Response, default: float) -> float:
raw = (response.headers.get("retry-after") or "").strip()
try:
return max(0.0, float(raw)) if raw else default
except ValueError:
return default
def _sleep_until(wake: float, cancelled: Optional[Callable[[], bool]]) -> bool:
"""Sleep until the monotonic time *wake*. Returns True when *cancelled* fired first.
Without a hook this is one plain :func:`time.sleep`. With one the sleep is cut into <= 1 s
ticks so an attempt stopped from outside ends in about a second instead of blocking to the
sign-in code's own expiry.
"""
if cancelled is None:
remaining = wake - time.monotonic()
if remaining > 0:
time.sleep(remaining)
return False
while True:
if cancelled():
return True
remaining = wake - time.monotonic()
if remaining <= 0:
return False
time.sleep(min(1.0, remaining))
def wait_for_promotion(
client: httpx.Client, portal_base_url: str, claim_code: str, *, expires_in: int, interval: int,
cancelled: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
"""Poll ``POST /api/anonymous/promotion-status`` until it leaves ``pending`` or our clock runs out.
Returns the final status payload; ``{"status": "timeout"}`` when ``expires_in`` elapsed. 429 honours
``Retry-After``; other non-2xx statuses raise through :func:`_raise_for_anon_status`.
*cancelled* is an optional hook a surface passes to stop an attempt it no longer wants (a newer
sign-in replaced it, the user cancelled, the process is shutting down). It is polled at the top
of every iteration and on a <= 1 s tick while sleeping; once it has fired this call returns
``{"status": "cancelled"}`` for every outcome except a ``completed`` transfer already in hand,
which is reported so the caller's ``cancel_wins_after_promotion`` ruling can decide it.
Passing nothing is today's behaviour.
"""
deadline = time.monotonic() + max(1, int(expires_in))
wait = max(0, int(interval))
while time.monotonic() < deadline:
if cancelled is not None and cancelled():
return {"status": "cancelled"}
response = client.post(
f"{portal_base_url.rstrip('/')}/api/anonymous/promotion-status", headers=_anon_headers(),
json={"claim_code": claim_code})
if response.status_code == 429:
retry = min(_retry_after_seconds(response, default=max(1, wait)),
max(0.0, deadline - time.monotonic()))
if _sleep_until(time.monotonic() + retry, cancelled):
return {"status": "cancelled"}
continue
payload = _raise_for_anon_status(response, action="sign-in")
status = str(payload.get("status") or "unknown")
if status != "pending":
# A completed transfer is already committed on the account service; report it even when
# the hook fired during this request. run_sign_in's cancel_wins_after_promotion
# rules what each surface does with it. Every other terminal outcome loses to a cancel.
if status != "completed" and cancelled is not None and cancelled():
return {"status": "cancelled"}
return payload
if _sleep_until(time.monotonic() + wait, cancelled):
return {"status": "cancelled"}
return {"status": "timeout"}
def _account_state_from_token(
token_data: Dict[str, Any], *, portal_base_url: str, client_id: str, scope: Optional[str], verify: Any,
timeout_seconds: float,
) -> Dict[str, Any]:
"""The ``providers.nous`` shape for the signed-in account (same fields the device-code login writes)."""
from hermes_cli.auth import PROVIDER_REGISTRY, _coerce_ttl_seconds, _optional_base_url, _tls_state_from_verify
from hermes_cli.auth_nous import _NOUS_EMPTY_AGENT_KEY_FIELDS, _iso_after, refresh_nous_oauth_from_state
now = datetime.now(timezone.utc)
ttl = _coerce_ttl_seconds(token_data.get("expires_in", 0))
inference_url = (
_optional_base_url(token_data.get("inference_base_url"))
or PROVIDER_REGISTRY["nous"].inference_base_url.rstrip("/"))
state = {
"portal_base_url": portal_base_url, "inference_base_url": inference_url,
"client_id": client_id, "scope": token_data.get("scope") or scope,
"token_type": token_data.get("token_type", "Bearer"),
"access_token": token_data["access_token"], "refresh_token": token_data.get("refresh_token"),
"obtained_at": now.isoformat(), "expires_at": _iso_after(now, ttl), "expires_in": ttl,
"tls": _tls_state_from_verify(verify), **_NOUS_EMPTY_AGENT_KEY_FIELDS}
state = refresh_nous_oauth_from_state(state, timeout_seconds=timeout_seconds, force_refresh=False)
state["auth_method"] = UPGRADED_AUTH_METHOD
return state
def settle_after_upgrade(account_state: Dict[str, Any]) -> Dict[str, Any]:
"""After a sign-in from the free tier persisted the account: move the config off the free tier's route.
Picking the free-tier row may have written ``model.default: nous/welcome`` and ``model.base_url``
= welcome host. An account cannot keep either: the welcome host refuses account tokens, and the
portal host serves ``nous/welcome`` as a paid model. When the config is on the free tier's route,
``model.base_url`` becomes the account's inference host and ``model.default`` the recommended
default for the account's tier (:func:`hermes_cli.models.recommended_nous_default_model`, the
same pick as ``GET /api/model/recommended-default``), through the same config write a plain Nous
login uses. A config on the user's own model and host is left alone.
Every sign-in completion (CLI ``hermes auth upgrade``, the desktop poller) calls this once, after
``persist_nous_credentials``. Returns ``{"model": str, "changed": bool}``: ``model`` is the default
the config now carries (``""`` when it carries none); ``changed`` says whether this call wrote it.
Never raises: a failed pick or write is logged and reported as ``changed: False`` so the sign-in
itself still counts.
"""
from hermes_cli.config import load_config_readonly
try:
raw = load_config_readonly().get("model")
except Exception as exc:
logger.warning("sign-in completion: config unreadable, default model left as is: %s", exc)
return {"model": "", "changed": False}
model_cfg = raw if isinstance(raw, dict) else ({"default": raw} if isinstance(raw, str) else {})
current = str(model_cfg.get("default") or "").strip()
on_welcome_model = current == GUEST_MODEL
on_welcome_host = route_is_welcome_host(model_cfg.get("base_url"))
if not (on_welcome_model or on_welcome_host):
return {"model": current, "changed": False}
model = current
if on_welcome_model:
from hermes_cli.models import recommended_nous_default_model
try:
model = str(recommended_nous_default_model().get("model") or "")
except Exception as exc:
logger.debug("sign-in completion: recommended default unavailable: %s", exc)
model = ""
try:
from hermes_cli.auth import _update_config_for_provider
# One write: host and default move together, so a failure leaves the config as it was
# rather than the account host paired with the welcome model. No eligible recommendation
# (Portal unreachable, or the plan and org policy admit nothing) clears the default in that
# same write; the runtime's silent default applies until the user picks one with `hermes model`.
_update_config_for_provider(
"nous", str(account_state.get("inference_base_url") or ""),
default_model=model if on_welcome_model else None,
clear_default=on_welcome_model and not model)
except Exception as exc:
logger.warning("sign-in completion: could not update the default model: %s", exc)
return {"model": current, "changed": False}
return {"model": model, "changed": True}
def _poll_for_token(*args, **kwargs) -> Dict[str, Any]:
"""Keep both the sign-in module seam and the device-flow seam live at call time."""
from hermes_cli.auth_device_flow import _poll_for_token as poll
return poll(*args, **kwargs)
def persist_nous_credentials(*args, **kwargs):
"""Keep the existing auth_nous persistence seam behind the sign-in entry point."""
from hermes_cli.auth_nous import persist_nous_credentials as persist
return persist(*args, **kwargs)
# Public sign-in imports remain here for existing callers and module-attribute patches.
# The flow imports this module only inside calls, so either module can be imported first.
from hermes_cli.anon_sign_in import ( # noqa: E402
AlreadySignedIn as AlreadySignedIn,
Code as Code,
Completed as Completed,
Declined as Declined,
FREE_TIER_RATE_LIMIT_CHAT as FREE_TIER_RATE_LIMIT_CHAT,
Failed as Failed,
LOGIN_BUSY_ELSEWHERE as LOGIN_BUSY_ELSEWHERE,
LOGIN_COMMAND as LOGIN_COMMAND,
LOGIN_DM_ONLY as LOGIN_DM_ONLY,
LOGIN_NOT_ALLOWED as LOGIN_NOT_ALLOWED,
LOGIN_STARTING as LOGIN_STARTING,
Retired as Retired,
SignInState as SignInState,
Superseded as Superseded,
TimedOut as TimedOut,
UPGRADE_ALREADY_SIGNED_IN as UPGRADE_ALREADY_SIGNED_IN,
UPGRADE_CANCELLED as UPGRADE_CANCELLED,
UPGRADE_DO_NOT_SHARE as UPGRADE_DO_NOT_SHARE,
UPGRADE_NOT_COMPLETED as UPGRADE_NOT_COMPLETED,
UPGRADE_NO_DEFAULT_CHAT as UPGRADE_NO_DEFAULT_CHAT,
UPGRADE_NO_DEFAULT_TERMINAL as UPGRADE_NO_DEFAULT_TERMINAL,
UPGRADE_REASON_COPY as UPGRADE_REASON_COPY,
UPGRADE_START as UPGRADE_START,
UPGRADE_TIMED_OUT as UPGRADE_TIMED_OUT,
UPGRADE_UNAVAILABLE as UPGRADE_UNAVAILABLE,
UPGRADE_UNAVAILABLE_CHAT as UPGRADE_UNAVAILABLE_CHAT,
UPGRADE_WAITING as UPGRADE_WAITING,
UPGRADE_WAITING_UP_TO as UPGRADE_WAITING_UP_TO,
Unavailable as Unavailable,
Waiting as Waiting,
_RETIRED_REASONS as _RETIRED_REASONS,
_default_persist_guard as _default_persist_guard,
_outcome_state as _outcome_state,
format_wait_line as format_wait_line,
run_sign_in as run_sign_in,
)
from hermes_cli.anon_sign_in_cli import ( # noqa: E402
drain_sign_in_copy as drain_sign_in_copy,
render_sign_in_cli as render_sign_in_cli,
render_sign_in_cli_code as render_sign_in_cli_code,
upgrade_guest as upgrade_guest,
)
FREE_TIER_STATUS_LINE = f"{FREE_TIER_LABEL} \u00b7 {GUEST_MODEL} \u00b7 {LOGIN_COMMAND} to sign in"