Skip to content

The agent that grows with you

fix(free-tier): stamp the trial in the mint's own write; grandfather only pre-change guests

alt-glitch7079d7ff5a9f
diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.py
index d858d56cb45..b9529c4e0a7 100644
--- a/hermes_cli/anon_auth.py
+++ b/hermes_cli/anon_auth.py
@@ -213,7 +213,7 @@ def free_inference_active(state: Any = None) -> bool:
"""The welcome trial carries inference here: a guest that claimed it (or was grandfathered),
guests still allowed, and this is the desktop's local backend. *state* defaults to the profile's."""
state = current_nous_state() if state is None else state
- return (is_guest_state(state) and bool(state.get(WELCOME_CLAIM_FLAG)) and guest_allowed()
+ return (is_guest_state(state) and state.get(WELCOME_CLAIM_FLAG) is True and guest_allowed()
and on_local_desktop_backend())
@@ -488,10 +488,12 @@ def _shared_identity_key(state: Any) -> Optional[str]:
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]) -> dict[str, Any]:
+def _mint_locked(client: httpx.Client, portal: str, auth_store: dict[str, Any], *,
+ welcome_claim: bool) -> 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)."""
+ next attempt exchanges the stored one instead of minting again). *welcome_claim* is written in
+ that same save, so a claimed guest is never left unstamped."""
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)
@@ -501,6 +503,8 @@ def _mint_locked(client: httpx.Client, portal: str, auth_store: dict[str, Any])
"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"),
+ # Always present: an absent key marks a guest minted before the claim existed (grandfathering).
+ WELCOME_CLAIM_FLAG: welcome_claim,
}
_store_provider_state(auth_store, "nous", state, set_active=False)
_save_auth_store(auth_store)
@@ -607,7 +611,8 @@ def _note_mint_failure(err: AuthError) -> MintFailure:
return failure
-def _reconcile_and_provision(*, timeout_seconds: float, force: bool = False) -> Optional[dict[str, Any]]:
+def _reconcile_and_provision(*, timeout_seconds: float, force: bool = False,
+ welcome_claim: bool = False) -> 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
@@ -644,7 +649,7 @@ def _reconcile_and_provision(*, timeout_seconds: float, force: bool = False) ->
verify = _resolve_verify(insecure=None, ca_bundle=None, auth_state=None)
try:
with _nous_http_client(timeout_seconds, verify) as client:
- return _mint_locked(client, portal, auth_store)
+ return _mint_locked(client, portal, auth_store, welcome_claim=welcome_claim)
except Exception as exc:
# Noted before the locks are released, so a caller queued on them sees the cooldown.
err = classify_mint_exception(exc)
@@ -656,6 +661,7 @@ def _reconcile_and_provision(*, timeout_seconds: float, force: bool = False) ->
def ensure_portal_identity(
*, explicit: bool, timeout_seconds: float = GUEST_MINT_TIMEOUT_SECONDS, force: bool = False,
+ welcome_claim: bool = False,
) -> 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).
@@ -663,8 +669,9 @@ def ensure_portal_identity(
``explicit`` is required and must be True: the only callers are the first hosted connector action
(``tools.connectors.gateway.config.ensure_guest_identity``), the connectors dead-credential
replacement (``managed_tool_gateway._replace_dead_guest_token``) and the desktop's welcome-trial
- claim (``welcome_trial.claim_desktop_free_tier``), which stamps the guest it gets back. An
- unstamped guest serves connectors only.
+ claim (``welcome_trial.claim_desktop_free_tier``), which passes ``welcome_claim=True`` so a guest
+ it mints carries the stamp from its first write. Every other guest is minted with
+ ``welcome_claim: False`` and serves connectors only.
Nothing creates an identity as a side effect of reading status, resolving a provider or fetching a
connector bearer (NS-845 Q1.2).
@@ -685,7 +692,8 @@ def ensure_portal_identity(
if failure and not force and not current_nous_state() and time.monotonic() < failure.not_before:
return None # in cooldown (or terminal) for this profile; do not hammer the portal
try:
- state = _reconcile_and_provision(timeout_seconds=timeout_seconds, force=force)
+ state = _reconcile_and_provision(timeout_seconds=timeout_seconds, force=force,
+ welcome_claim=welcome_claim)
except Exception as exc:
err = classify_mint_exception(exc)
noted = getattr(err, "mint_failure", None) or _note_mint_failure(err)
diff --git a/hermes_cli/welcome_trial.py b/hermes_cli/welcome_trial.py
index 12e9ce825f4..571713db15b 100644
--- a/hermes_cli/welcome_trial.py
+++ b/hermes_cli/welcome_trial.py
@@ -2,9 +2,10 @@
Only the backend the desktop spawned on this machine can claim it, only when this machine has never
used Hermes (``install_state``), and only with no provider and no Nous identity yet. The claim mints a
-guest, stamps ``WELCOME_CLAIM_FLAG`` on it and marks the machine, so the trial is never claimed twice
-here. A claim that is lost later (the guest is reaped, ``auth.json`` is deleted, the user signs in) is
-never made again: that user lands on provider setup and sign-in like anyone else.
+guest stamped with ``WELCOME_CLAIM_FLAG`` in the mint's own write and marks the machine, so the trial
+is never claimed twice here. A claim that is lost later (the guest is reaped, ``auth.json`` is
+deleted, the user signs in) is never made again: that user lands on provider setup and sign-in like
+anyone else.
Guests that ran on the free model before the claim existed keep it (:func:`grandfather_existing_guest`).
Enforcement is client-side; the account service's own entitlement check follows separately.
@@ -80,44 +81,41 @@ def claim_desktop_free_tier(*, assume_fresh: bool = False, force: bool = False)
if reason := claim_blocker(assume_fresh=assume_fresh):
logger.debug("welcome trial not claimed: %s", reason)
return None
- state = anon_auth.ensure_portal_identity(explicit=True, force=force)
+ state = anon_auth.ensure_portal_identity(explicit=True, force=force, welcome_claim=True)
if state is None: # still inside the cooldown of the last failure
failure = anon_auth.last_mint_failure() or {}
raise anon_auth._anon_err(str(failure.get("error") or anon_auth.ANON_FAILURE_COPY[anon_auth.ANON_SERVER_ERROR]),
str(failure.get("error_code") or anon_auth.ANON_SERVER_ERROR),
retry_after=failure.get("retry_after"))
- claimed = _record_claim()
+ from hermes_cli.install_state import mark_machine_used
+
+ mark_machine_used()
logger.info("Nous free tier: welcome trial claimed on this machine")
- return claimed
+ return state
def grandfather_existing_guest() -> bool:
"""A guest from before the claim existed keeps the free model when this home already chatted on
- it. Connector-only guests never qualify. Records the claim once; True when it did."""
+ it. Only a guest with no ``welcome_claim`` key qualifies: every guest minted since carries the
+ key, so a connector guest (``False``) never does. Records the claim once; True when it did."""
if not anon_auth.on_local_desktop_backend():
return False
state = anon_auth.current_nous_state()
- if not anon_auth.is_guest_state(state) or state.get(anon_auth.WELCOME_CLAIM_FLAG):
+ if not anon_auth.is_guest_state(state) or anon_auth.WELCOME_CLAIM_FLAG in state:
return False
from hermes_constants import get_default_hermes_root, get_hermes_home
homes = dict.fromkeys((get_hermes_home(), get_default_hermes_root()))
if not any(_chatted_on_welcome(home / "state.db") for home in homes):
return False
- _record_claim()
- logger.info("Nous free tier: existing free-model guest kept its trial")
- return True
-
-
-def _record_claim() -> Optional[dict[str, Any]]:
from hermes_cli.auth_nous import _write_shared_nous_state
from hermes_cli.install_state import mark_machine_used
- state = anon_auth.set_guest_flag(anon_auth.WELCOME_CLAIM_FLAG)
- if state is not None:
- _write_shared_nous_state(state)
+ if (stamped := anon_auth.set_guest_flag(anon_auth.WELCOME_CLAIM_FLAG)) is not None:
+ _write_shared_nous_state(stamped)
mark_machine_used()
- return state
+ logger.info("Nous free tier: existing free-model guest kept its trial")
+ return True
def _chatted_on_welcome(db: Path) -> bool:
diff --git a/tests/hermes_cli/test_welcome_trial.py b/tests/hermes_cli/test_welcome_trial.py
index 6fa92ebe51f..109b029ddcd 100644
--- a/tests/hermes_cli/test_welcome_trial.py
+++ b/tests/hermes_cli/test_welcome_trial.py
@@ -1,6 +1,8 @@
"""The desktop's welcome trial (``hermes_cli.welcome_trial``): who may claim it, what a claim leaves
behind, which guests keep the free model, and that a connector guest never asks for inference."""
+import contextlib
+
import pytest
from hermes_cli import anon_auth, install_state, welcome_trial
@@ -22,6 +24,18 @@ def test_a_first_install_on_the_local_desktop_backend_claims_the_trial(portal, m
assert portal.creates() == 1
+def test_the_claim_is_stamped_by_the_mint_write_itself(portal, monkeypatch):
+ def lost_second_write(_flag):
+ raise OSError("disk full")
+ monkeypatch.setattr(anon_auth, "set_guest_flag", lost_second_write)
+ as_local_desktop_backend(monkeypatch)
+
+ with contextlib.suppress(OSError):
+ welcome_trial.claim_desktop_free_tier()
+
+ assert anon_auth.free_inference_active()
+
+
BLOCKED = {
"the CLI": lambda mp, home: None,
"an SSH backend": lambda mp, home: (mp.setenv("HERMES_DESKTOP", "1"), mp.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)),
@@ -71,12 +85,26 @@ def _chat(db_path, model: str) -> None:
db.close()
+def _legacy_guest() -> None:
+ """A guest minted before the claim existed: no welcome_claim key at all, in either store."""
+ from hermes_cli.auth import _load_auth_store, _load_provider_state, _save_auth_store, _store_provider_state
+ from hermes_cli.auth_nous import _write_shared_nous_state
+
+ anon_auth.ensure_portal_identity(explicit=True)
+ store = _load_auth_store()
+ state = dict(_load_provider_state(store, "nous"))
+ state.pop(anon_auth.WELCOME_CLAIM_FLAG, None)
+ _store_provider_state(store, "nous", state, set_active=False)
+ _save_auth_store(store)
+ _write_shared_nous_state(state)
+
+
@pytest.mark.parametrize(("model", "kept"), [(anon_auth.GUEST_MODEL, True), ("anthropic/claude", False)])
def test_a_guest_that_chatted_on_the_free_model_keeps_it(portal, monkeypatch, model, kept):
from hermes_constants import get_hermes_home
as_local_desktop_backend(monkeypatch)
- anon_auth.ensure_portal_identity(explicit=True)
+ _legacy_guest() # grandfathering is only for guests minted before the key existed
_chat(get_hermes_home() / "state.db", model)
assert welcome_trial.grandfather_existing_guest() is kept
@@ -89,3 +117,47 @@ def test_a_lost_claim_is_not_replaced(portal, monkeypatch):
assert welcome_trial.claim_desktop_free_tier() is None
assert portal.creates() == 1
+
+
+def test_a_reaped_claimant_replaced_by_a_connector_guest_is_not_grandfathered(portal, monkeypatch):
+ from hermes_constants import get_hermes_home
+
+ claimed_trial(monkeypatch)
+ _chat(get_hermes_home() / "state.db", anon_auth.GUEST_MODEL)
+ anon_auth.clear_dead_guest("anon_credential_dead")
+ anon_auth.ensure_portal_identity(explicit=True) # a connector action mints the replacement
+
+ assert welcome_trial.grandfather_existing_guest() is False
+ assert not anon_auth.free_inference_active()
+
+
+LOSSES = {
+ "reaped": (lambda: anon_auth.clear_dead_guest("anon_credential_dead"), 1),
+ "replaced_by_connector": (lambda: (anon_auth.clear_dead_guest("anon_credential_dead"),
+ anon_auth.ensure_portal_identity(explicit=True)), 2),
+}
+
+
[email protected]("loss", list(LOSSES))
+def test_a_lost_trial_is_never_claimed_again_after_a_relaunch(portal, monkeypatch, loss):
+ from hermes_cli import free_tier_bootstrap
+ from hermes_cli.auth import resolve_provider
+ from hermes_cli.auth_constants import AuthError
+ from hermes_constants import get_hermes_home
+
+ lose, creates = LOSSES[loss]
+ claimed_trial(monkeypatch)
+ _chat(get_hermes_home() / "state.db", anon_auth.GUEST_MODEL)
+ lose()
+ install_state.probe.cache_clear() # the relaunch
+ free_tier_bootstrap.reset_for_tests()
+ free_tier_bootstrap.run_bootstrap(announce=False)
+
+ assert welcome_trial.claim_desktop_free_tier() is None
+ assert portal.creates() == creates
+ assert welcome_trial.grandfather_existing_guest() is False
+ assert not anon_auth.free_inference_active()
+ with pytest.raises(AuthError):
+ resolve_provider("auto")
+ record = free_tier_bootstrap.current_record()
+ assert (record.provider_configured, record.free_tier_account) == (False, False)