The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore(free-tier): keep the rehearsal server out of the repo; the docs page explains the stand-in instead
Robin Fernandesd89cacc25f84
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 4951e96d129..451de21d401 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -205,10 +205,9 @@ From `apps/desktop`, use a fresh temporary directory for each rehearsal and runbefore `npm run dev`. Stop Electron and its dev server after the run.To rehearse the free tier's failure handling (the account service refusing or-unreachable at boot, the welcome host rate-limiting or refusing mid-chat), run-`python scripts/free_tier_fault_server.py` from the repo root and start the-desktop with the environment it prints; switch scenarios from the desktop's-JavaScript console. The walkthrough is in+unreachable at boot, the welcome host rate-limiting or refusing mid-chat), point+the desktop at a local stand-in for both services with `HERMES_PORTAL_BASE_URL`,+`NOUS_INFERENCE_BASE_URL` and `HERMES_EXTRA_WELCOME_HOSTS`. See`website/docs/developer-guide/free-tier-fault-rehearsal.md`.## The taste test before you hand offdiff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.pyindex 780fc376ed1..b360577f3bf 100644--- a/hermes_cli/anon_auth.py+++ b/hermes_cli/anon_auth.py@@ -189,9 +189,10 @@ def guest_carries_inference() -> bool:WELCOME_HOSTS = frozenset({"welcome-api.nousresearch.com"})# Dev-only: extra hostnames that count as the welcome host, comma-separated (for example-# ``127.0.0.1`` while ``NOUS_INFERENCE_BASE_URL`` points at ``scripts/free_tier_fault_server.py``).-# Read from the environment, which the user controls, so it sits at the same trust level as the-# URL override itself; it never widens the NETWORK-side allowlist in ``auth_nous``.+# ``127.0.0.1`` while ``NOUS_INFERENCE_BASE_URL`` points at a local stand-in; see+# website/docs/developer-guide/free-tier-fault-rehearsal.md). Read from the environment, which the+# user controls, so it sits at the same trust level as the URL override itself; it never widens+# the NETWORK-side allowlist in ``auth_nous``.EXTRA_WELCOME_HOSTS_ENV = "HERMES_EXTRA_WELCOME_HOSTS"diff --git a/scripts/free_tier_fault_server.py b/scripts/free_tier_fault_server.pydeleted file mode 100644index 98616ef4dc5..00000000000--- a/scripts/free_tier_fault_server.py+++ /dev/null@@ -1,501 +0,0 @@-#!/usr/bin/env python3-"""Fault-injecting stand-in for the two services behind the Nous free tier.--One process plays both the account service (NAS, ``/api/anonymous/*`` and the device-code-endpoints a sign-in touches) and the welcome inference host (``/v1/chat/completions``), answering-with the exact status codes, bodies and headers the real services send, so Hermes' failure-handling can be rehearsed end to end without touching production. Which failure it serves is a-live switch: change it from the desktop's JavaScript console, ``curl``, or a browser, and watch-the desktop react.--Run::-- python scripts/free_tier_fault_server.py # 127.0.0.1:8765- python scripts/free_tier_fault_server.py --port 9000 --inference rate_limited--then start Hermes Desktop pointed at it (the script prints the exact environment lines). See-``website/docs/developer-guide/free-tier-fault-rehearsal.md`` for the walkthrough.--Control surface (all CORS-open, so a renderer can call them)::-- GET /__scenarios the catalogue: every scenario, per service, with what it does- GET /__scenario the switches as they stand- POST /__scenario {"nas": ..., "inference": ..., "once": bool, "retry_after": N}- POST /__signin {"status": "completed" | "voided", "reason": "..."} settle a pending sign-in- GET /__log the last requests the server answered- POST /__reset back to the happy path, log cleared--Stdlib only: no dependencies, nothing to install.-"""--from __future__ import annotations--import argparse-import base64-import json-import secrets-import threading-import time-from collections import deque-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer-from typing import Any, Dict, Optional-from urllib.parse import parse_qs, urlparse--WELCOME_MODEL = "nous/welcome"-REAL_WELCOME_HOST = "welcome-api.nousresearch.com"-UPGRADE_URL = "https://portal.nousresearch.com/signup"--# --- Scenario catalogue ---------------------------------------------------------------------------#-# Names are what the control endpoint accepts. Each entry says what the real service does in that-# situation, so a rehearsal reads as the situation rather than the status code.--NAS_SCENARIOS: Dict[str, str] = {- "ok": "The account service answers normally: sign-ups mint, exchanges return a JWT.",- "not_enabled": "404 not_found on every /api/anonymous route: the surface is not enabled on this deployment.",- "paused": "503 temporarily_disabled: the ops breaker is tripped (transient, no wait hinted).",- "rate_limited": "429 temporarily_unavailable with Retry-After: too many sign-ups from this address.",- "server_error": "500 with a non-JSON body on every /api/anonymous route.",- "timeout": "Every /api/anonymous request hangs past the client's 5 s budget.",- "pow": "Token exchange answers 428 pow_required: proof of work enforced (sign-ups still mint).",- "locked": "Token exchange answers 403 account_locked: the account is locked.",- "dead_once": "The NEXT token exchange answers 404 unknown_token (reaped / claimed); the replacement works.",- "signin_busy": "Starting a sign-in (promotion-intent) answers 429 with Retry-After.",- "signin_paused": "Starting a sign-in answers 503 temporarily_disabled.",- "signin_server_error": "Starting a sign-in answers 500.",-}--INFERENCE_SCENARIOS: Dict[str, str] = {- "ok": "Chat completions answer with a short canned reply (streaming or not).",- "rate_limited": "429 reason=rate_limited, retry_after 600: the allowance is used up (long wait -> stop and say so).",- "rate_limited_short": "429 reason=rate_limited, retry_after 5: a short wait the turn rides out quietly.",- "at_capacity": "429 reason=at_capacity, retry_after 30: the tier is busy (retried in place, bounded).",- "model_not_free": "429 reason=model_not_free, alternates=[nous/welcome]: the session asked for another model.",- "tier_disabled": "403 with only the generic permission message: WELCOME_MODE=off on the gateway.",- "wrong_host": "400 'Anonymous accounts must use https://welcome-api...': the route points at the paid host.",- "bare_429": "429 with x-ratelimit-* headers showing an exhausted bucket and no reason field.",- "upstream_503": "503 'The requested model is currently unavailable.': the upstream provider is down.",- "upstream_500": "500 generic: an upstream 5xx surfaced by the gateway.",- "invalid_token": "401 invalid_token / anonymous_credential_revoked: the session behind the JWT is gone.",- "timeout": "The request hangs for two minutes.",-}---_FAIRSHARE_MESSAGE = ("You've reached this model's current fair-share rate limit. It adapts to demand — "- "retry after the indicated delay, or try an alternate model.")---def _fairshare(reason: str, message: str, **extra: Any) -> Dict[str, Any]:- return {"status": 429, "message": message, "reason": reason, "alternates": [], "upgrade_url": UPGRADE_URL, **extra}---# Static inference answers: scenario -> (status, body, default Retry-After seconds). ``retry_after``-# in a fairshare body and every wait header are filled in per request from the live override.-INFERENCE_RESPONSES: Dict[str, tuple] = {- "rate_limited": (429, _fairshare("rate_limited", _FAIRSHARE_MESSAGE), 600),- "rate_limited_short": (429, _fairshare("rate_limited", _FAIRSHARE_MESSAGE), 5),- "at_capacity": (429, _fairshare("at_capacity", "The free tier is at capacity and briefly paused. It reopens "- "automatically — retry after the indicated delay."), 30),- "model_not_free": (429, _fairshare("model_not_free", "This model isn't available on the free tier.",- alternates=[WELCOME_MODEL]), 0),- "tier_disabled": (403, {"status": 403, "message": "You tried to access something that you don't have permissions for."}, 0),- "wrong_host": (400, {"status": 400, "message": "This request is not valid. Check the model name and other parameters. "- f"Additional info: Anonymous accounts must use https://{REAL_WELCOME_HOST} for inference."}, 0),- "bare_429": (429, {"status": 429, "message": "Hold up for a bit, you've exceeded the rate limit on your API key."}, 600),- "upstream_503": (503, {"status": 503, "message": "The requested model is currently unavailable."}, 0),- "upstream_500": (500, {"status": 500, "message": "Something unexpected happened while processing your request. "- "Please try again in a moment, or contact us if the issue persists."}, 0),- "invalid_token": (401, {"status": 401, "error": "invalid_token", "subcause": "anonymous_credential_revoked",- "message": "The anonymous account behind this token is gone"}, 0),-}---def _jwt(**claims: Any) -> str:- def seg(obj: Any) -> str:- return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()- payload = {"sub": "nas_user:rehearsal", "client_id": "nas-anonymous", "account_tier": "anonymous",- "scope": "inference:invoke tool:invoke", "iss": "free-tier-fault-server",- "iat": int(time.time()), "exp": int(time.time()) + 900, **claims}- return f"{seg({'alg': 'RS256', 'typ': 'JWT'})}.{seg(payload)}.{seg({'sig': 'rehearsal'})}"---class State:- """The switches, guarded by one lock (the server is threaded)."""-- def __init__(self, *, nas: str = "ok", inference: str = "ok", welcome_url: str = "") -> None:- self.lock = threading.Lock()- self.nas = nas- self.inference = inference- self.once = False- self.retry_after: Optional[int] = None- self.welcome_url = welcome_url- self.minted = 0- self.dead_tokens: set[str] = set()- self.signin: Dict[str, Any] = {"status": "pending"}- self.log: deque[Dict[str, Any]] = deque(maxlen=100)-- def snapshot(self) -> Dict[str, Any]:- with self.lock:- return {"nas": self.nas, "inference": self.inference, "once": self.once,- "retry_after": self.retry_after, "minted": self.minted, "signin": dict(self.signin),- "welcome_url": self.welcome_url}-- def set(self, payload: Dict[str, Any]) -> Dict[str, Any]:- with self.lock:- if "nas" in payload:- name = str(payload["nas"] or "ok")- if name not in NAS_SCENARIOS:- raise ValueError(f"unknown nas scenario {name!r}; one of {sorted(NAS_SCENARIOS)}")- self.nas = name- if "inference" in payload:- name = str(payload["inference"] or "ok")- if name not in INFERENCE_SCENARIOS:- raise ValueError(f"unknown inference scenario {name!r}; one of {sorted(INFERENCE_SCENARIOS)}")- self.inference = name- if "once" in payload:- self.once = bool(payload["once"])- if "retry_after" in payload:- value = payload["retry_after"]- self.retry_after = None if value in (None, "") else max(0, int(value))- return self.snapshot()-- def consume_once(self, service: str) -> None:- """After a one-shot failure was served, drop that service back to the happy path."""- with self.lock:- if self.once:- setattr(self, service, "ok")-- def reset(self) -> None:- with self.lock:- self.nas = self.inference = "ok"- self.once = False- self.retry_after = None- self.dead_tokens.clear()- self.signin = {"status": "pending"}- self.log.clear()---STATE = State()---class Handler(BaseHTTPRequestHandler):- server_version = "free-tier-fault-server/1"-- # --- plumbing ---------------------------------------------------------------------------------- def log_message(self, fmt: str, *args: Any) -> None: # quieter than the default- pass-- def _cors(self) -> None:- self.send_header("Access-Control-Allow-Origin", "*")- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")- self.send_header("Access-Control-Allow-Headers", "content-type, authorization")-- def _send(self, status: int, body: Any = None, *, headers: Optional[Dict[str, str]] = None,- raw: Optional[bytes] = None, content_type: str = "application/json") -> None:- data = raw if raw is not None else json.dumps(body if body is not None else {}).encode()- self.send_response(status)- self.send_header("Content-Type", content_type)- self.send_header("Content-Length", str(len(data)))- for key, value in (headers or {}).items():- self.send_header(key, value)- self._cors()- self.end_headers()- self.wfile.write(data)- with STATE.lock:- STATE.log.append({"at": time.time(), "method": self.command, "path": self.path, "status": status,- "scenario": {"nas": STATE.nas, "inference": STATE.inference}})-- def _read_json(self) -> Dict[str, Any]:- length = int(self.headers.get("Content-Length") or 0)- raw = self.rfile.read(length) if length else b""- if not raw:- return {}- try:- parsed = json.loads(raw)- return parsed if isinstance(parsed, dict) else {}- except ValueError:- # Form-encoded (the device-code endpoints post forms).- return {k: v[0] for k, v in parse_qs(raw.decode(errors="replace")).items()}-- def do_OPTIONS(self) -> None: # noqa: N802- self.send_response(204)- self._cors()- self.end_headers()-- def do_GET(self) -> None: # noqa: N802- path = urlparse(self.path).path- if path == "/__scenarios":- self._send(200, {"nas": NAS_SCENARIOS, "inference": INFERENCE_SCENARIOS})- elif path == "/__scenario":- query = {k: v[0] for k, v in parse_qs(urlparse(self.path).query).items()}- if query:- self._control_set(query)- else:- self._send(200, STATE.snapshot())- elif path == "/__log":- with STATE.lock:- entries = list(STATE.log)- self._send(200, {"requests": entries}) # outside the lock: _send appends to the log- elif path == "/v1/models":- self._send(200, {"object": "list", "data": [{"id": WELCOME_MODEL, "object": "model", "owned_by": "nous"}]})- elif path.startswith("/__claim"):- self._send(200, raw=(- b"<html><body><h1>Free tier fault server</h1><p>This stands in for the sign-in page. "- b"Settle the sign-in with <code>POST /__signin</code>.</p></body></html>"),- content_type="text/html")- elif path in ("/", "/healthcheck"):- self._send(200, {"ok": True, "service": "free-tier-fault-server"})- else:- self._send(404, {"status": 404, "message": "Couldn't find that, sorry."})-- def do_POST(self) -> None: # noqa: N802- path = urlparse(self.path).path- body = self._read_json()- if path == "/__scenario":- self._control_set(body)- elif path == "/__signin":- with STATE.lock:- STATE.signin = {"status": str(body.get("status") or "pending"), **{- k: v for k, v in body.items() if k != "status"}}- self._send(200, STATE.snapshot())- elif path == "/__reset":- STATE.reset()- self._send(200, STATE.snapshot())- elif path.startswith("/api/anonymous/"):- self._nas(path, body)- elif path == "/api/oauth/device/code":- self._device_code(body)- elif path == "/api/oauth/token":- self._oauth_token(body)- elif path in ("/v1/chat/completions", "/chat/completions"):- self._inference(body)- else:- self._send(404, {"status": 404, "message": "Couldn't find that, sorry."})-- def _control_set(self, payload: Dict[str, Any]) -> None:- try:- self._send(200, STATE.set(payload))- except ValueError as exc:- self._send(400, {"error": str(exc)})-- # --- the account service (NAS) ----------------------------------------------------------------- def _retry_after(self, default: int) -> int:- with STATE.lock:- return default if STATE.retry_after is None else STATE.retry_after-- def _nas_gate(self, scenario: str) -> bool:- """The shared gate every /api/anonymous route runs first. True when a refusal was sent."""- if scenario == "not_enabled":- self._send(404, {"error": "not_found"})- elif scenario == "paused":- self._send(503, {"error": "temporarily_disabled",- "error_description": "The anonymous-account surface is currently switched off."})- elif scenario == "server_error":- self._send(500, raw=b"<html><body>Internal Server Error</body></html>", content_type="text/html")- elif scenario == "timeout":- time.sleep(12)- return False- else:- return False- STATE.consume_once("nas")- return True-- def _nas(self, path: str, body: Dict[str, Any]) -> None:- with STATE.lock:- scenario = STATE.nas- if self._nas_gate(scenario):- return- if path == "/api/anonymous/create":- if scenario == "rate_limited":- wait = self._retry_after(30)- STATE.consume_once("nas")- self._send(429, {"error": "temporarily_unavailable",- "error_description": "Too many anonymous account creations from this address. Try again later."},- headers={"Retry-After": str(wait)})- return- with STATE.lock:- STATE.minted += 1- n = STATE.minted- self._send(201, {"user_id": f"nas_user:rehearsal-{n}", "org_id": f"nas_org:rehearsal-{n}",- "token": f"anon_rehearsal_{n:04d}_{secrets.token_hex(4)}", "idle_ttl_days": 14})- return- if path == "/api/anonymous/token":- token = str(body.get("token") or "")- if not token.startswith("anon_"):- self._send(400, {"error": "invalid_request", "error_description": 'Body must be { token: "anon_…" }.'})- return- with STATE.lock:- dead = token in STATE.dead_tokens- if scenario == "dead_once" and not dead:- # One-shot by definition: this credential is gone for good, the next one works.- STATE.dead_tokens.add(token)- STATE.nas = "ok"- dead = True- if dead:- self._send(404, {"error": "unknown_token", "error_description": "No anonymous account matches this token."})- return- if scenario == "rate_limited":- STATE.consume_once("nas")- self._send(429, {"error": "temporarily_unavailable",- "error_description": "Too many token exchanges. Try again later."},- headers={"Retry-After": str(self._retry_after(30))})- return- if scenario == "pow":- STATE.consume_once("nas")- self._send(428, {"error": "pow_required", "pow": {- "challenge": secrets.token_hex(16), "alg": "blake2s-hashcash-v1", "bits": 31, "count": 16,- "expires_in": 1800}})- return- if scenario == "locked":- STATE.consume_once("nas")- self._send(403, {"error": "account_locked"})- return- with STATE.lock:- welcome = STATE.welcome_url- payload: Dict[str, Any] = {- "access_token": _jwt(sid=token[-8:]), "token_type": "Bearer", "expires_in": 900,- "user_id": "nas_user:rehearsal", "org_id": "nas_org:rehearsal"}- if welcome:- payload["inference_base_url"] = welcome- self._send(200, payload)- return- if path == "/api/anonymous/promotion-intent":- if scenario == "signin_busy":- STATE.consume_once("nas")- self._send(429, {"error": "temporarily_unavailable",- "error_description": "Too many promotion requests. Try again later."},- headers={"Retry-After": str(self._retry_after(45))})- return- if scenario == "signin_paused":- STATE.consume_once("nas")- self._send(503, {"error": "temporarily_disabled",- "error_description": "The anonymous-account surface is currently switched off."})- return- if scenario == "signin_server_error":- STATE.consume_once("nas")- self._send(500, {"error": "internal_error"})- return- code = f"{secrets.token_hex(2).upper()}-{secrets.token_hex(2).upper()}"- with STATE.lock:- STATE.signin = {"status": "pending"}- host = self.headers.get("Host") or "127.0.0.1"- self._send(200, {"claim_code": code, "claim_url": f"http://{host}/__claim?code={code}",- "expires_in": 900, "interval": 2})- return- if path == "/api/anonymous/promotion-status":- with STATE.lock:- outcome = dict(STATE.signin)- self._send(200, outcome if outcome.get("status") != "pending" else {"status": "pending"})- return- if path == "/api/anonymous/claim":- self._send(401, {"error": "unauthorized"})- return- self._send(404, {"error": "not_found"})-- def _device_code(self, body: Dict[str, Any]) -> None:- host = self.headers.get("Host") or "127.0.0.1"- code = secrets.token_hex(8)- self._send(200, {"device_code": f"dc_{code}", "user_code": f"{code[:4].upper()}-{code[4:8].upper()}",- "verification_uri": f"http://{host}/__claim",- "verification_uri_complete": f"http://{host}/__claim?device={code}",- "expires_in": 900, "interval": 2})-- def _oauth_token(self, body: Dict[str, Any]) -> None:- # A completed sign-in is not something this stand-in can finish honestly (the real- # portal issues signed tokens the agent then verifies), so the token poll stays pending.- self._send(400, {"error": "authorization_pending",- "error_description": "The free tier fault server never completes a sign-in; rehearse the failure paths here and the happy path against staging."})-- # --- the welcome inference host ---------------------------------------------------------------- def _inference(self, body: Dict[str, Any]) -> None:- with STATE.lock:- scenario = STATE.inference- if scenario == "timeout":- STATE.consume_once("inference")- time.sleep(120)- self._send(504, {"status": 504, "message": "timed out"})- return- canned = INFERENCE_RESPONSES.get(scenario)- if canned is None:- self._reply(str(body.get("model") or WELCOME_MODEL), stream=bool(body.get("stream")))- return- status, payload, default_wait = canned- wait = self._retry_after(default_wait)- headers = {"Retry-After": str(wait)} if default_wait or "reason" in payload else {}- if payload.get("reason") in ("rate_limited", "at_capacity"):- headers["RateLimit-Policy"] = '"fairshare";q=0;qu="tokens";w=60'- headers["RateLimit"] = f'"fairshare";r=0;t={wait}'- if scenario == "bare_429":- headers.update({"x-ratelimit-limit-requests": "30", "x-ratelimit-remaining-requests": "0",- "x-ratelimit-reset-requests": str(wait)})- if "reason" in payload:- payload = {**payload, "retry_after": wait}- STATE.consume_once("inference")- self._send(status, payload, headers=headers)-- def _reply(self, model: str, *, stream: bool) -> None:- text = ("Hello from the free tier fault server. Everything is working; switch a scenario on "- "POST /__scenario to rehearse a failure.")- now = int(time.time())- ident = f"chatcmpl-rehearsal-{secrets.token_hex(4)}"- if not stream:- self._send(200, {"id": ident, "object": "chat.completion", "created": now, "model": model,- "choices": [{"index": 0, "message": {"role": "assistant", "content": text},- "finish_reason": "stop"}],- "usage": {"prompt_tokens": 12, "completion_tokens": 24, "total_tokens": 36}})- return- chunks = []- for i, piece in enumerate(text.split(" ")):- delta = {"content": (" " if i else "") + piece}- if i == 0:- delta["role"] = "assistant"- chunks.append({"id": ident, "object": "chat.completion.chunk", "created": now, "model": model,- "choices": [{"index": 0, "delta": delta, "finish_reason": None}]})- chunks.append({"id": ident, "object": "chat.completion.chunk", "created": now, "model": model,- "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],- "usage": {"prompt_tokens": 12, "completion_tokens": 24, "total_tokens": 36}})- raw = "".join(f"data: {json.dumps(c)}\n\n" for c in chunks) + "data: [DONE]\n\n"- self._send(200, raw=raw.encode(), content_type="text/event-stream")---def make_server(host: str = "127.0.0.1", port: int = 8765, *, nas: str = "ok", inference: str = "ok",- welcome_url: Optional[str] = None) -> ThreadingHTTPServer:- """Build (not start) the server; tests bind port 0 and read ``server.server_address``."""- global STATE- STATE = State(nas=nas, inference=inference, welcome_url=welcome_url or "")- server = ThreadingHTTPServer((host, port), Handler)- server.daemon_threads = True- if not welcome_url:- STATE.welcome_url = f"http://{server.server_address[0]}:{server.server_address[1]}/v1"- return server---def main() -> None:- parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])- parser.add_argument("--host", default="127.0.0.1")- parser.add_argument("--port", type=int, default=8765)- parser.add_argument("--nas", default="ok", choices=sorted(NAS_SCENARIOS))- parser.add_argument("--inference", default="ok", choices=sorted(INFERENCE_SCENARIOS))- args = parser.parse_args()- server = make_server(args.host, args.port, nas=args.nas, inference=args.inference)- base = f"http://{args.host}:{args.port}"- print(f"free tier fault server on {base} (nas={args.nas}, inference={args.inference})")- print("Point Hermes at it with:")- print(f" export HERMES_GUEST_ONBOARDING=1 HERMES_PORTAL_BASE_URL={base} "- f"NOUS_INFERENCE_BASE_URL={base}/v1 HERMES_EXTRA_WELCOME_HOSTS={args.host}")- print("Switch a scenario with:")- print(f" curl -s -X POST {base}/__scenario -d '{{\"inference\": \"rate_limited\"}}'")- print(f" fetch('{base}/__scenario', {{method: 'POST', body: JSON.stringify({{nas: 'paused'}})}})")- try:- server.serve_forever()- except KeyboardInterrupt:- pass- finally:- server.server_close()---if __name__ == "__main__":- main()diff --git a/tests/hermes_cli/test_anon_failure_modes.py b/tests/hermes_cli/test_anon_failure_modes.pyindex 6df978f69e2..808788ece5f 100644--- a/tests/hermes_cli/test_anon_failure_modes.py+++ b/tests/hermes_cli/test_anon_failure_modes.py@@ -291,6 +291,21 @@ class TestSignInFailures:assert state.retryable is True and "few seconds" in state.copy+# --- The dev-only host override ------------------------------------------------------------------+++def test_extra_welcome_hosts_make_a_local_stand_in_the_welcome_host(monkeypatch):+ """``HERMES_EXTRA_WELCOME_HOSTS`` (env-only) extends the ROUTE predicate so a rehearsal against a+ local stand-in gets the free tier's rules — including the route-keyed dark-tier 403."""+ monkeypatch.delenv("HERMES_EXTRA_WELCOME_HOSTS", raising=False)+ assert anon_auth.route_is_welcome_host("http://127.0.0.1:8765/v1") is False+ monkeypatch.setenv("HERMES_EXTRA_WELCOME_HOSTS", "127.0.0.1, localhost")+ assert anon_auth.route_is_welcome_host("http://127.0.0.1:8765/v1") is True+ assert anon_auth.route_is_welcome_host("http://localhost:9/v1") is True+ assert anon_auth.welcome_route_refusal(403, "You tried to access something", "http://127.0.0.1:8765/v1") == "tier_disabled"+ assert anon_auth.route_is_welcome_host("https://inference-api.nousresearch.com/v1") is False++# --- The spoken wait -----------------------------------------------------------------------------diff --git a/tests/scripts/test_free_tier_fault_server.py b/tests/scripts/test_free_tier_fault_server.pydeleted file mode 100644index 84f4213345a..00000000000--- a/tests/scripts/test_free_tier_fault_server.py+++ /dev/null@@ -1,195 +0,0 @@-"""``scripts/free_tier_fault_server.py`` speaks the real free-tier wire contract: Hermes' own client-code, pointed at it, reaches the same ``anon_*`` codes and welcome refusals it reaches against-production. That is what makes a rehearsal against it worth anything."""--from __future__ import annotations--import importlib.util-import json-import sys-import threading-from pathlib import Path--import httpx-import pytest--REPO_ROOT = Path(__file__).resolve().parents[2]-SCRIPT = REPO_ROOT / "scripts" / "free_tier_fault_server.py"---def _load():- spec = importlib.util.spec_from_file_location("free_tier_fault_server", SCRIPT)- module = importlib.util.module_from_spec(spec)- sys.modules[spec.name] = module- spec.loader.exec_module(module)- return module---def server():- module = _load()- srv = module.make_server("127.0.0.1", 0)- thread = threading.Thread(target=srv.serve_forever, daemon=True)- thread.start()- host, port = srv.server_address- base = f"http://{host}:{port}"- try:- yield module, base- finally:- srv.shutdown()- srv.server_close()---def _post(base: str, path: str, body=None, **kw) -> httpx.Response:- return httpx.post(f"{base}{path}", json=body or {}, timeout=5.0, **kw)---class TestControlSurface:- def test_catalogue_switches_and_reset(self, server):- module, base = server- catalogue = httpx.get(f"{base}/__scenarios", timeout=5.0).json()- assert set(catalogue["nas"]) == set(module.NAS_SCENARIOS)- assert set(catalogue["inference"]) == set(module.INFERENCE_SCENARIOS)-- state = _post(base, "/__scenario", {"inference": "rate_limited", "retry_after": 42}).json()- assert state["inference"] == "rate_limited" and state["retry_after"] == 42- assert httpx.get(f"{base}/__scenario?nas=paused", timeout=5.0).json()["nas"] == "paused"- assert _post(base, "/__scenario", {"nas": "nope"}).status_code == 400-- assert _post(base, "/__reset").json() == {**_post(base, "/__reset").json(), "nas": "ok", "inference": "ok"}-- def test_reading_the_log_never_wedges_the_next_request(self, server):- _module, base = server- assert httpx.get(f"{base}/__log", timeout=5.0).status_code == 200- assert httpx.get(f"{base}/__scenario", timeout=5.0).status_code == 200- assert httpx.get(f"{base}/__log", timeout=5.0).json()["requests"][-1]["path"] == "/__scenario"-- def test_the_control_surface_is_cors_open_for_a_renderer(self, server):- _module, base = server- preflight = httpx.options(f"{base}/__scenario", timeout=5.0)- assert preflight.status_code == 204- assert preflight.headers["access-control-allow-origin"] == "*"- assert "POST" in preflight.headers["access-control-allow-methods"]-- def test_once_drops_back_to_the_happy_path_after_one_failure(self, server):- _module, base = server- _post(base, "/__scenario", {"inference": "upstream_503", "once": True})- assert _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []}).status_code == 503- assert _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []}).status_code == 200---class TestNasContract:- def test_the_happy_path_mints_and_exchanges(self, server):- _module, base = server- minted = _post(base, "/api/anonymous/create").json()- assert minted["token"].startswith("anon_") and minted["idle_ttl_days"] == 14- exchanged = _post(base, "/api/anonymous/token", {"token": minted["token"]}).json()- assert exchanged["access_token"].count(".") == 2 and exchanged["expires_in"] == 900- assert exchanged["inference_base_url"] == f"{base}/v1"-- @pytest.mark.parametrize("scenario,status,error", [- ("not_enabled", 404, "not_found"),- ("paused", 503, "temporarily_disabled"),- ("rate_limited", 429, "temporarily_unavailable"),- ])- def test_gate_and_limit_refusals_match_the_service(self, server, scenario, status, error):- _module, base = server- _post(base, "/__scenario", {"nas": scenario})- response = _post(base, "/api/anonymous/create")- assert response.status_code == status and response.json()["error"] == error- if status == 429:- assert int(response.headers["Retry-After"]) > 0-- def test_exchange_refusals_match_the_service(self, server):- _module, base = server- token = _post(base, "/api/anonymous/create").json()["token"]- for scenario, status, error in (("pow", 428, "pow_required"), ("locked", 403, "account_locked")):- _post(base, "/__scenario", {"nas": scenario})- response = _post(base, "/api/anonymous/token", {"token": token})- assert response.status_code == status and response.json()["error"] == error- _post(base, "/__scenario", {"nas": "dead_once"})- assert _post(base, "/api/anonymous/token", {"token": token}).json()["error"] == "unknown_token"- fresh = _post(base, "/api/anonymous/create").json()["token"]- assert _post(base, "/api/anonymous/token", {"token": fresh}).status_code == 200-- def test_hermes_own_client_reaches_the_same_codes_against_it(self, server, monkeypatch, tmp_path):- """The point of the stand-in: ``ensure_portal_identity`` classifies its answers exactly as- it classifies production's."""- from hermes_cli import anon_auth, free_tier_bootstrap- _module, base = server- monkeypatch.setenv("HERMES_PORTAL_BASE_URL", base)- monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-store"))- monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")- anon_auth.reset_mint_memo_for_tests()- free_tier_bootstrap.reset_for_tests()-- _post(base, "/__scenario", {"nas": "paused"})- with pytest.raises(anon_auth.AuthError) as exc:- anon_auth.ensure_portal_identity(explicit=True)- assert exc.value.code == anon_auth.ANON_GATE_PAUSED-- _post(base, "/__scenario", {"nas": "ok"})- state = anon_auth.ensure_portal_identity(explicit=True, force=True)- assert anon_auth.is_guest_state(state)---class TestInferenceContract:- def test_the_happy_path_answers_streaming_and_plain(self, server):- _module, base = server- plain = _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []}).json()- assert plain["choices"][0]["message"]["content"]- streamed = _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": [], "stream": True})- assert streamed.headers["content-type"].startswith("text/event-stream")- assert streamed.text.rstrip().endswith("data: [DONE]")-- @pytest.mark.parametrize("scenario,reason,retry_after", [- ("rate_limited", "rate_limited", 600), ("rate_limited_short", "rate_limited", 5),- ("at_capacity", "at_capacity", 30), ("model_not_free", "model_not_free", 0),- ])- def test_structured_refusals_parse_as_welcome_refusals(self, server, scenario, reason, retry_after):- from hermes_cli.anon_auth import parse_welcome_refusal- _module, base = server- _post(base, "/__scenario", {"inference": scenario})- response = _post(base, "/v1/chat/completions", {"model": "gpt-5", "messages": []})- assert response.status_code == 429- refusal = parse_welcome_refusal(response.json())- assert refusal["reason"] == reason and refusal["retry_after"] == retry_after- if reason == "model_not_free":- assert refusal["alternates"] == ["nous/welcome"]-- def test_route_refusals_and_outages_match_the_gateway(self, server):- from hermes_cli.anon_auth import welcome_route_refusal- _module, base = server- _post(base, "/__scenario", {"inference": "wrong_host"})- response = _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []})- assert welcome_route_refusal(response.status_code, response.json()["message"]) == "anon_on_paid_host"- _post(base, "/__scenario", {"inference": "tier_disabled"})- response = _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []})- assert response.status_code == 403 and "reason" not in response.json()- assert welcome_route_refusal(403, response.json()["message"], f"{base}/v1") is None # not a welcome host...- _post(base, "/__scenario", {"inference": "bare_429"})- response = _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []})- assert response.headers["x-ratelimit-remaining-requests"] == "0"- for scenario, status in (("upstream_503", 503), ("upstream_500", 500), ("invalid_token", 401)):- _post(base, "/__scenario", {"inference": scenario})- assert _post(base, "/v1/chat/completions", {"model": "nous/welcome", "messages": []}).status_code == status-- def test_the_dev_host_override_makes_the_stand_in_the_welcome_host(self, server, monkeypatch):- from hermes_cli.anon_auth import route_is_welcome_host, welcome_route_refusal- _module, base = server- assert route_is_welcome_host(f"{base}/v1") is False- monkeypatch.setenv("HERMES_EXTRA_WELCOME_HOSTS", "127.0.0.1, localhost")- assert route_is_welcome_host(f"{base}/v1") is True- assert route_is_welcome_host("http://localhost:9/v1") is True- # ...and with it, the generic 403 reads as the tier refusing, exactly as in production.- assert welcome_route_refusal(403, "You tried to access something", f"{base}/v1") == "tier_disabled"- assert route_is_welcome_host("https://welcome-api.nousresearch.com/v1") is True- assert route_is_welcome_host("https://inference-api.nousresearch.com/v1") is False---def test_the_script_runs_as_a_program():- import subprocess- result = subprocess.run([sys.executable, str(SCRIPT), "--help"], capture_output=True, text=True, timeout=30)- assert result.returncode == 0- assert "--inference" in result.stdout and "rate_limited" in result.stdout- assert json.dumps(sorted(_load().INFERENCE_SCENARIOS)) # the catalogue is JSON-serialisablediff --git a/website/docs/developer-guide/free-tier-fault-rehearsal.md b/website/docs/developer-guide/free-tier-fault-rehearsal.mdindex 3b9859770d9..94079254ab9 100644--- a/website/docs/developer-guide/free-tier-fault-rehearsal.md+++ b/website/docs/developer-guide/free-tier-fault-rehearsal.md@@ -1,7 +1,7 @@---sidebar_position: 6title: "Rehearsing Free-Tier Failures"-description: "Drive every way the Nous free tier can refuse or fail, from the desktop's JavaScript console, against a local stand-in for the account service and the welcome host"+description: "Point Hermes Desktop at a local stand-in for the account service and the welcome host to watch its free-tier failure handling"---# Rehearsing Free-Tier Failures@@ -9,33 +9,15 @@ description: "Drive every way the Nous free tier can refuse or fail, from the deThe Nous free tier depends on two services: the account service (NAS), which creates thefree-tier identity and exchanges it for short-lived tokens, and the welcome inference host, whichserves the free model under its own rate limits and capacity caps. Hermes has a ruled behaviour for-every way either one can refuse or fail (see `hermes_cli/anon_auth.py`, the `ANON_*` codes and the-welcome refusal parser). This page is how you watch those behaviours happen on a real desktop+every way either can refuse or fail: the `ANON_*` codes and the welcome refusal parser in+`hermes_cli/anon_auth.py`, and the onboarding notice and sign-in screens keyed on them in the+desktop. Those behaviours are pinned by tests (`tests/hermes_cli/test_anon_failure_modes.py`,+`tests/agent/test_welcome_tier_recovery.py`). This page is how to watch them on a real desktopwithout touching production.-`scripts/free_tier_fault_server.py` is a single stdlib-only process that plays **both** services-and answers with the exact status codes, bodies and headers the real ones send. Which failure it-serves is a live switch you flip from the desktop's JavaScript console, `curl`, or a browser tab.+## Point Hermes at a stand-in-## 1. Start the stand-in--From the repo root:--```bash-python scripts/free_tier_fault_server.py-```--It listens on `127.0.0.1:8765` and prints the environment Hermes needs. You can also start it-already failing:--```bash-python scripts/free_tier_fault_server.py --nas paused --inference rate_limited-```--## 2. Start Hermes Desktop against it--Use a fresh temporary home so the rehearsal starts from a first launch, and add the four-variables the server printed to the usual guided-onboarding command from `apps/desktop`:+Run any local HTTP server that answers as the two services do, then start the desktop with:```bashD=$(mktemp -d)@@ -49,104 +31,37 @@ env -u NODE_ENV \npm run dev```-What each one does:-| Variable | Why ||---|---|| `HERMES_GUEST_ONBOARDING=1` | The free tier's launch gate; nothing is created without it. || `HERMES_PORTAL_BASE_URL` | Sends every account-service call (sign-up, token exchange, sign-in) to the stand-in. |-| `NOUS_INFERENCE_BASE_URL` | Sends chat completions to the stand-in instead of the welcome host. This override is trusted as the user's own setting and bypasses the network-side host allowlist. |-| `HERMES_EXTRA_WELCOME_HOSTS` | Dev-only. Makes Hermes treat `127.0.0.1` as the welcome host, so the free-tier route rules (model pinning, the dark-tier 403, the "sign in for a bigger allowance" copy) apply exactly as they do in production. Comma-separated hostnames; ports are ignored. It never widens the allowlist for URLs the network hands back. |--On a clean start the desktop boots, mints an identity against the stand-in, and lands on the-free-tier ready screen. Send a message and the stand-in replies with a canned line.--## 3. Flip a scenario--From the desktop's JavaScript console (View → Toggle Developer Tools):--```js-await (await fetch('http://127.0.0.1:8765/__scenario', {- method: 'POST',- body: JSON.stringify({ inference: 'rate_limited' })-})).json()-```--Or from a shell:--```bash-curl -s -X POST http://127.0.0.1:8765/__scenario -d '{"nas": "paused"}'-```--Then do the thing the scenario is about (send a message, restart the app, click *Try again*,-start a sign-in) and watch what the desktop says. The full catalogue, with what each scenario-means, is at `GET /__scenarios`; the current switches at `GET /__scenario`; the requests the-server has answered, with the scenario that was live for each, at `GET /__log`.--Control fields:--| Field | Meaning |-|---|---|-| `nas` | The account-service scenario (sign-up, token exchange, sign-in). |-| `inference` | The welcome-host scenario (chat completions). |-| `once` | `true` makes the next failure a one-off: after serving it, that service drops back to `ok`. Use it for "rate limited once, then fine". |-| `retry_after` | Overrides the wait the server names, in seconds, for any scenario that names one. |--`POST /__reset` puts everything back to the happy path and clears the log.--## 4. What to rehearse, and what you should see--**At boot (the account service).** Set the `nas` scenario, then quit and relaunch the desktop-with a fresh `HERMES_HOME`, or click *Try again* on the notice.--| Scenario | The desktop should |-|---|---|-| `not_enabled` | Show the provider picker with the "can't start without a Nous account" notice, no retry button, and the Nous row as the way in. |-| `paused` | Show the "paused for a moment" notice with *Try again*; the backend retries on its own with a one-minute floor, and the picker gives way by itself when the stand-in is set back to `ok`. |-| `rate_limited` | Show the "lots of people are getting started" notice naming the wait; the backend retries after `Retry-After`. |-| `server_error`, `timeout` | Show the "couldn't reach / had a hiccup" notice with *Try again* and **no** sign-in pointer, since the same service would refuse the sign-in. |-| `pow` | Show the proof-of-work sentence and point at sign-in; no retry. |-| `locked` | Show the "can't continue without signing in" notice. |-| `dead_once` | Nothing visible: the next token exchange fails as "unknown token", Hermes retires the identity and mints a replacement silently. Check `GET /__log` to see the two exchanges. |--**Mid-chat (the welcome host).** Set the `inference` scenario, then send a message.--| Scenario | The desktop should |-|---|---|-| `rate_limited` | Stop and say the allowance is used up, name the reset ("about 10 minutes"), and offer sign-in. The next send is refused locally until the reset. |-| `rate_limited_short` | Wait the few seconds quietly, then the reply arrives (set `once: true` first). |-| `at_capacity` | Retry with the named delay, then, once the retries are spent, say the free service is busy and offer both doors. |-| `model_not_free` | Only reachable when the session asks for another model; Hermes moves back to the free model once and retries. |-| `tier_disabled` | Say that using Hermes without signing in is switched off, stop retrying, and offer both doors. |-| `wrong_host` | Heal silently: Hermes re-reads its route and retries. The "different Nous server" sentence appears only if `NOUS_INFERENCE_BASE_URL` is the thing pointing at the wrong place. |-| `bare_429` | Same as `rate_limited`, driven by the `x-ratelimit-*` headers instead of the body. |-| `upstream_503`, `upstream_500` | Retry with backoff, then say the free model is having trouble responding. |-| `invalid_token` | Silent: one credential refresh, then a re-mint against the account service. |-| `timeout` | The turn's own transport timeout and retries. |--**Signing in.** With an identity in place, open the sign-in dialog from the status-bar chip, with-`nas` set to `signin_busy`, `signin_paused` or `signin_server_error`. The dialog should show-the "busy, try again in about a minute" or "couldn't reach" screen with *Try again*, and the-free-tier session should still be there afterwards. The stand-in can start a sign-in and report-`pending`, and you can settle it as declined or busy:--```bash-curl -s -X POST http://127.0.0.1:8765/__signin -d '{"status": "voided", "reason": "user_declined"}'-```--A **completed** sign-in is deliberately not something the stand-in can finish: the real portal-issues signed tokens the agent then verifies. Rehearse the happy path of a sign-in against-staging.--## 5. Notes--- The stand-in is for rehearsal, not for tests of Hermes' own logic. Those live in- `tests/hermes_cli/test_anon_failure_modes.py` and `tests/agent/test_welcome_tier_recovery.py`- and drive the same client code through in-process fakes. `tests/scripts/test_free_tier_fault_server.py`- checks that the stand-in speaks the real contract, which is what makes a rehearsal against it- meaningful.-- Because `HERMES_EXTRA_WELCOME_HOSTS` changes routing rules, never set it outside a rehearsal- environment. It is read from the environment only, is never written to config, and is not- shown in setup.-- The renderer talks to the stand-in's control surface directly (it is CORS-open). If a future- content-security policy blocks that, the `curl` forms above do the same thing.+| `NOUS_INFERENCE_BASE_URL` | Sends chat completions to the stand-in. Trusted as the user's own setting; bypasses the network-side host allowlist. |+| `HERMES_EXTRA_WELCOME_HOSTS` | Dev-only. Makes Hermes treat the stand-in's hostname as the welcome host, so the free-tier route rules (model pinning, the route-keyed dark-tier 403, the "sign in for a bigger allowance" copy) apply as in production. Comma-separated hostnames, ports ignored. Never widens the allowlist for URLs the network hands back, and never belongs outside a rehearsal environment. |++## What the stand-in has to speak++On the account-service side: `POST /api/anonymous/create` (201 with an `anon_` token),+`POST /api/anonymous/token` (200 with `access_token`, `expires_in`, `inference_base_url`), and,+for sign-in rehearsals, `POST /api/oauth/device/code`, `/api/anonymous/promotion-intent` and+`/api/anonymous/promotion-status`. The refusals Hermes classifies are the ones NAS actually sends:+404 `not_found`, 503 `temporarily_disabled`, 429 with `Retry-After`, 428 `pow_*`, 404+`unknown_token`, 403 `account_locked`; see the code table at the top of `anon_auth.py`.++On the inference side: `POST /v1/chat/completions` (streaming or not), with the gateway's+structured 429 body `{status, message, reason, retry_after, alternates, upgrade_url}` for+`rate_limited` / `at_capacity` / `model_not_free`, a generic-bodied 403 for a dark tier, the+"Anonymous accounts must use…" 400 for a wrong host, and plain 5xx for outages.++A small stdlib `http.server` with a `POST /__scenario` switch is enough; keep it CORS-open and you+can flip scenarios from the desktop's JavaScript console with one `fetch`. One such server was+written alongside this work and can be regenerated from the description above; it is not kept in+the repo because it only serves one-off manual rehearsal and would drift silently from the real+services.++## Reading the result++The failure-to-message mapping the desktop should follow is in the pull request that introduced+it and in the tests named above: the boot-time notice above the provider picker (with *Try again*+when a retry can work, and the sign-in pointer only when the account service answered at all), the+chat copy for each welcome refusal, and the sign-in dialog's busy / unreachable / unavailable+screens.