The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Free-tier rate limits: renewed token, a prompt card on desktop, streamed status, honest resume model (#129396)
Siddharth Balyanf9549f3d9bd8
diff --git a/agent/initiate_setup_prompt.py b/agent/initiate_setup_prompt.pyindex 14391dbe74a..b1034731631 100644--- a/agent/initiate_setup_prompt.py+++ b/agent/initiate_setup_prompt.py@@ -171,13 +171,14 @@ def intro_resends(prompt: str) -> bool:def _opening(suggested: str | None, said: set, replies: dict):reply = replies.get("name")if reply is None:- card = {"kind": "question", "question": _NAME_QUESTION, "multi_select": False}- if suggested:- card["options"] = [{"id": "suggested", "label": suggested}]+ # ``options`` is required by the tool schema; the history must carry it even when empty.+ card = {"kind": "question", "question": _NAME_QUESTION,+ "options": [{"id": "suggested", "label": suggested}] if suggested else [], "multi_select": False}reply = _json_object((yield "" if INTRO in said else INTRO, "setup_choose", card))if "accent" in replies:returnpicked = reply.get("picked")name = (suggested or "") if picked == "suggested" else picked.strip() if isinstance(picked, str) else ""line = f"Good to meet you, {name}." if name else "Good to meet you."- yield "" if line in said else line, "setup_choose", {"kind": "accent", "question": "Which colour?", "multi_select": False}+ accent = {"kind": "accent", "question": "Which colour?", "options": [], "multi_select": False}+ yield "" if line in said else line, "setup_choose", accentdiff --git a/agent/retry_utils.py b/agent/retry_utils.pyindex 0cec62957d4..86c710f8916 100644--- a/agent/retry_utils.py+++ b/agent/retry_utils.py@@ -172,3 +172,37 @@ def zai_coding_overload_retry_ceiling(short_attempts: int = _ZAI_CODING_OVERLOADbecause the loop gives up when ``retry_count >= ceiling`` BEFORE computing the attempt'sbackoff (the default ``api_max_retries`` of 3 equals ``short_attempts``)."""return short_attempts + len(_ZAI_CODING_OVERLOAD_LONG_BACKOFF) + 1+++# Surfaces where a person watches the turn as it runs (desktop chat, TUI). A provider cooldown+# longer than ``LIVE_RETRY_WAIT_CAP_S`` is not slept through there: a retry before the provider's+# reset only meets the same refusal, and the person sits in front of a spinner for minutes. The+# turn ends at once with the reset time and the ways forward instead. Background surfaces (cron,+# batch, messaging gateways, ``hermes chat -q``) keep the long wait, capped at ``RETRY_AFTER_CAP_S``.+LIVE_SURFACES = frozenset({"desktop", "tui"})+LIVE_RETRY_WAIT_CAP_S = 60.0+# Anthropic Tier 1 input-token buckets reset in ~171s, so a 120s cap re-tripped the limit; 600s+# covers realistic provider windows while still rejecting pathological values (#26293).+RETRY_AFTER_CAP_S = 600.0+++def is_live_surface(platform: Any) -> bool:+ return str(platform or "").strip().lower() in LIVE_SURFACES+++def retry_wait_cap(platform: Any) -> float:+ """The longest single retry wait this surface sits through."""+ return LIVE_RETRY_WAIT_CAP_S if is_live_surface(platform) else RETRY_AFTER_CAP_S+++def provider_retry_after_seconds(error: Any) -> Optional[float]:+ """Provider-declared cooldown: the ``Retry-After`` header, else a ``retry_after`` body field+ (top level or nested under ``error``). None when absent, unparseable or zero — a zero/expired+ cooldown carries no usable wait, and treating it as one would hot-loop the provider."""+ value = parse_retry_after_seconds(getattr(getattr(error, "response", None), "headers", None))+ if value is None:+ body = getattr(error, "body", None)+ if isinstance(body, dict):+ nested = body.get("error")+ value = parse_retry_after_seconds((nested if isinstance(nested, dict) else body).get("retry_after"))+ return value if value is not None and value > 0 else Nonediff --git a/agent/turn_api_error.py b/agent/turn_api_error.pyindex 90c095df3f6..a2d6597aff3 100644--- a/agent/turn_api_error.py+++ b/agent/turn_api_error.py@@ -19,8 +19,8 @@ from agent.api_error_summary import is_provider_stream_parse_errorfrom agent.error_classifier import RETRYABLE_CLIENT_REASONS, FailoverReason, classify_api_errorfrom agent.turn_overflow import recover_from_overflowfrom agent.turn_recovery import (- _NONRETRYABLE_LABELS, abort_turn_on_interrupt, compute_error_backoff, interruptible_backoff_sleep,- log_api_error_attempt,+ _NONRETRYABLE_LABELS, abort_turn_on_interrupt, compute_error_backoff, cooldown_outlasts_live_wait,+ interruptible_backoff_sleep, log_api_error_attempt,max_retries_exhausted_result, nonretryable_client_error_result, recover_after_classification,recover_before_classification, route_classified_error, settle_delivered_partial,)@@ -353,6 +353,13 @@ def settle_unrecovered_error(base_url=_base, model=_model, delivered=_delivered,))+ # A cooldown the live surface will not sit through ends the attempt cycle now (fallback,+ # else the reset time and the ways forward); the copy counts the attempts actually made.+ attempts_made = retry_count+ if is_rate_limited and retry_count < max_retries and cooldown_outlasts_live_wait(agent, api_error):+ logger.info("%sProvider cooldown outlasts the live wait cap — ending retries after attempt %s",+ agent.log_prefix, retry_count)+ retry_count = max_retriesif retry_count >= max_retries:# Before fallback, rebuild the primary client once per API call block for# transient transport errors (stale pool, TCP reset).@@ -389,7 +396,7 @@ def settle_unrecovered_error(return _verdict(_ladder["action"], _ladder.get("result"))_delivered = settle_delivered_partial(agent, messages, current_turn_user_idx)return _verdict("return", max_retries_exhausted_result(- agent, api_error, classified, max_retries=max_retries, is_rate_limited=is_rate_limited,+ agent, api_error, classified, max_retries=min(attempts_made, max_retries), is_rate_limited=is_rate_limited,error_msg=error_msg, api_kwargs=api_kwargs, api_messages=api_messages,messages=messages, conversation_history=conversation_history,api_call_count=api_call_count, approx_tokens=approx_tokens, provider=_provider,diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.pyindex 115231f66a8..05a502f8fae 100644--- a/agent/turn_failure_copy.py+++ b/agent/turn_failure_copy.py@@ -177,6 +177,11 @@ _EXHAUSTED_LEADS: Dict[str, str] = {FailoverReason.timeout.value: "{label} didn't respond in time on any of {attempts} attempts",}_EXHAUSTED_DEFAULT_LEAD = "{label} didn't answer after {attempts} attempts"+# One attempt: a live surface ended the cycle because the provider's cooldown outlasts its wait cap.+_EXHAUSTED_FIRST_ATTEMPT_LEADS: Dict[str, str] = {+ FailoverReason.rate_limit.value: "{label} is rate-limiting requests right now",+ FailoverReason.upstream_rate_limit.value: "{label} is rate-limiting requests right now",+}# Terminal copy for a non-retryable provider rejection, keyed by classifier reason._NONRETRYABLE_COPY: Dict[str, str] = {@@ -363,7 +368,8 @@ def site_copy(code: str, **fields: Any) -> str:def exhausted_copy(reason: str, *, label: str, attempts: int, summary: str, reset_seconds: Optional[float] = None) -> str:"""Chat copy once retries + fallback are exhausted (``max_retries_exhausted_result``). A ratelimit whose reset window is known names it: an 8.6h plan quota is not "wait a minute" (#89401)."""- lead = _EXHAUSTED_LEADS.get(reason, _EXHAUSTED_DEFAULT_LEAD).format(label=label, attempts=attempts)+ leads = _EXHAUSTED_FIRST_ATTEMPT_LEADS if attempts == 1 and reason in _EXHAUSTED_FIRST_ATTEMPT_LEADS else _EXHAUSTED_LEADS+ lead = leads.get(reason, _EXHAUSTED_DEFAULT_LEAD).format(label=label, attempts=attempts)if reset_seconds is not None and reset_seconds >= 120:from agent.retry_utils import format_reset_windowsituation = (f"its usage limit resets in {format_reset_window(reset_seconds)}. "diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 5fdb1627853..1a3ff511780 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -568,6 +568,8 @@ def _recover_format_errors(_WELCOME_ROUTE_HEAL_COPY = {"anon_on_paid_host": "Reconnected to the free model's own route.","named_on_welcome_host": "Reconnected to your Nous account's own route.",+ # The forced refresh re-exchanges the guest's anon_ credential for a new JWT.+ "session_expired": "Renewed the connection to the free model.",}@@ -579,7 +581,8 @@ def _recover_welcome_tier(agent: Any, classified: Any, _retry: TurnRetryState) -turn. ``anon_on_paid_host`` / ``named_on_welcome_host``: this process is pointed at the otheridentity's host (a stale route); re-read the credentials, which heals the URL, and retry. Therefresh reports False when the store yields the same route, so a user-set- ``NOUS_INFERENCE_BASE_URL`` falls straight through to the terminal copy.+ ``NOUS_INFERENCE_BASE_URL`` falls straight through to the terminal copy. ``session_expired``+ (403 ``invalid jwt``): the same forced refresh re-exchanges the free credential.Reads the CLASSIFIER's context (``classified.error_context``): that is where``_nous_welcome_tier`` parks ``welcome_refusal`` / ``welcome_route``. The turn's other context@@ -916,6 +919,9 @@ def _welcome_surface_kind(classified: Any) -> str:route = ctx.get("welcome_route") if isinstance(ctx, dict) else Noneif route == "tier_disabled":return "disabled"+ # The renewal failed but the tier is up: a plain Retry mints a new credential.+ if route == "session_expired":+ return "outage"# A named account on the welcome host has already signed in: no sign-in card, copy only.if route == "named_on_welcome_host":return ""@@ -1143,7 +1149,7 @@ def max_retries_exhausted_result(elif is_rate_limited:_reset = reset_hint(api_error)agent._emit_diagnostic_status(- f"❌ Rate limited after {max_retries} retries — {_final_summary}"+ f"❌ Rate limited after {max_retries} {'attempt' if max_retries == 1 else 'retries'} — {_final_summary}"f"{f' (resets in {_reset})' if _reset else ''}")else:@@ -1357,6 +1363,13 @@ def interruptible_backoff_sleep(_touch_counter += 1if _touch_counter % 150 == 0: # 150 × 0.2s = 30sagent._touch_activity(f"{activity_label}, {int(sleep_end - time.time())}s remaining")+ # A long wait can outlive a short-lived credential (the free tier's JWT lives 15 minutes): the+ # per-iteration pre-expiry adoption never runs between retries, so adopt a fresh key here+ # instead of sending the retry on a dead one.+ try:+ agent._adopt_nous_key_before_expiry()+ except Exception:+ logger.debug("Nous key pre-expiry adoption after backoff failed", exc_info=True)return None@@ -1386,39 +1399,25 @@ def compute_error_backoff(is_zai_coding_overload: bool, base_url: Any, model: Any,) -> float:"""Pick the wait before the next API retry and announce it. Retry-After wins for- rate limits and any other retryable error (capped at 600s: Anthropic Tier 1 buckets- reset in ~171s, so a 120s cap re-tripped the limit); otherwise jittered backoff,- replaced by the adaptive policy for 429s / Z.AI overloads. Normal retries are- buffered; long Z.AI Coding waits surface immediately."""+ rate limits and any other retryable error (capped at ``RETRY_AFTER_CAP_S``); otherwise+ jittered backoff, replaced by the adaptive policy for 429s / Z.AI overloads. Short+ retries are buffered (replayed only if every retry fails); a wait the user will feel —+ over a minute, a long Z.AI Coding wait, or any rate limit on a live surface — is+ announced when it starts. Every line names the attempt that runs after the wait."""# Imported lazily so tests that patch ``agent.retry_utils.jittered_backoff`` /# ``adaptive_rate_limit_backoff`` (incl. the run_agent conftest fast-backoff fixture) intercept.- from agent.retry_utils import adaptive_rate_limit_backoff, jittered_backoff, parse_retry_after_seconds+ from agent.retry_utils import (+ RETRY_AFTER_CAP_S, adaptive_rate_limit_backoff, is_live_surface, jittered_backoff,+ provider_retry_after_seconds,+ )# Respect Retry-After on every retryable provider error, not just 429s. Retryable# 5xx responses (e.g. Cloudflare 520/524) also carry the header or a structured# ``retry_after`` problem-detail body field; ignoring either turns an origin# outage into a retry storm.- _retry_after = parse_retry_after_seconds(- getattr(getattr(api_error, "response", None), "headers", None)- )- if _retry_after is None:- _error_body = getattr(api_error, "body", None)- if isinstance(_error_body, dict):- # Some providers nest it as error.retry_after (the same unwrap- # extract_api_error_context uses), others put it at the top level.- _nested = _error_body.get("error")- _payload = _nested if isinstance(_nested, dict) else _error_body- _retry_after = parse_retry_after_seconds(_payload.get("retry_after"))+ _retry_after = provider_retry_after_seconds(api_error)if _retry_after is not None:- # Cap at 10 minutes. Anthropic Tier 1 input-token buckets reset in ~171s, so a 120s cap- # caused us to retry before the actual reset window and re-trip the limit. 600s covers all- # realistic provider reset windows while still rejecting pathological values. (#26293)- _retry_after = min(_retry_after, 600)- if _retry_after <= 0:- # A zero/expired cooldown (retry-after: 0, or an HTTP-date in the- # past, which the parser clamps to 0.0) carries no usable wait —- # treat it as absent so we never hot-loop the provider.- _retry_after = None+ _retry_after = min(_retry_after, RETRY_AFTER_CAP_S)wait_time = _retry_after if _retry_after is not None else jittered_backoff(retry_count, base_delay=2.0, max_delay=60.0)_backoff_policy = None_adaptive = is_rate_limited or is_zai_coding_overload@@ -1426,48 +1425,65 @@ def compute_error_backoff(wait_time, _backoff_policy = adaptive_rate_limit_backoff(retry_count, base_url=str(base_url), model=model, error=api_error, default_wait=wait_time,)+ _next = f"attempt {retry_count + 1}/{max_retries}"+ _announce_now = wait_time > 60 or (is_rate_limited and is_live_surface(getattr(agent, "platform", "")))_reset = reset_hint(api_error) if _adaptive else ""+ _free_busy = is_rate_limited and _is_welcome_guest(agent, base_url)_wait_reason = "Provider overloaded" if is_zai_coding_overload and not is_rate_limited else "Rate limited"if _adaptive:_policy_note = _ZAI_POLICY_NOTES.get(_backoff_policy or "", "")_rate_limit_status = (+ f"⏱️ The free model is busy. Retrying in {wait_time:.0f}s ({_next})..." if _free_busy elsef"⏱️ {_wait_reason}.{f' Resets in {_reset}.' if _reset else ''} Waiting {wait_time:.1f}s "- f"(attempt {retry_count + 1}/{max_retries}){_policy_note}..."+ f"({_next}){_policy_note}...")- if _backoff_policy == "zai_coding_overload_long":+ if _announce_now or _backoff_policy == "zai_coding_overload_long":agent._emit_diagnostic_status(_rate_limit_status)else:agent._buffer_diagnostic_status(_rate_limit_status)else:- _retry_status = (- f"⏳ Retrying in {wait_time:.1f}s (attempt {retry_count}/{max_retries})..."- )- if _retry_after is not None and _retry_after > 60:- # A 5xx Retry-After can now reach the 600s cap; buffering that wait- # would leave the user silent for minutes, so surface long provider- # cooldowns immediately (mirrors the zai_coding_overload_long path).+ _retry_status = f"⏳ Retrying in {wait_time:.1f}s ({_next})..."+ if _announce_now:agent._emit_diagnostic_status(_retry_status)else:agent._buffer_diagnostic_status(_retry_status)- # The buffered line only replays if every retry fails; the live status- # line is the one thing the user sees meanwhile. Name the wait there so a- # 60s backoff after a 5xx is not an anonymous spinner — this is transient- # (rewritten by the next frame, cleared on recovery), so it does not add- # the transcript chatter the buffer exists to avoid. The reset window- # belongs here too: during the wait this line is the only place the user- # can learn whether to sit it out or switch models.- _live_reason = f"{_wait_reason.lower()} — resets in {_reset}," if _reset else "waiting on provider —"- agent._emit_diagnostic_wait(- f"⏳ {_live_reason} retrying in {wait_time:.0f}s (attempt {retry_count}/{max_retries})"- )+ # The live status line is transient (rewritten by the next frame, cleared on recovery), so+ # it names the wait on every retry without adding transcript chatter. The reset window+ # belongs here too: during the wait this line is where the user learns whether to sit it+ # out or switch models.+ if _free_busy:+ _live_reason = "the free model is busy —"+ else:+ _live_reason = f"{_wait_reason.lower()} — resets in {_reset}," if _reset else "waiting on provider —"+ agent._emit_diagnostic_wait(f"⏳ {_live_reason} retrying in {wait_time:.0f}s ({_next})")logger.warning(- "Retrying API call in %ss (attempt %s/%s) %s policy=%s error=%s",- wait_time, retry_count, max_retries, agent._client_log_context(),- _backoff_policy or "default", api_error,+ "Retrying API call in %ss (%s) %s policy=%s error=%s",+ wait_time, _next, agent._client_log_context(), _backoff_policy or "default", api_error,)return wait_time+def _is_welcome_guest(agent: Any, base_url: Any) -> bool:+ """An anonymous session on the Nous free tier's host (its rate limits get their own copy)."""+ try:+ from hermes_cli.anon_auth import is_anonymous_agent, route_is_welcome_host+ return route_is_welcome_host(base_url) and is_anonymous_agent(agent)+ except Exception:+ return False+++def cooldown_outlasts_live_wait(agent: Any, api_error: Exception) -> bool:+ """True on a live surface when the provider's declared cooldown is longer than the surface+ sits through. A retry before that reset only meets the same refusal (the free tier's+ service-wide pause answered a 600 s retry with a second 429 while its 1069 s window ran),+ so the caller ends the attempt cycle now: fallback, or the reset time and the ways forward."""+ from agent.retry_utils import LIVE_RETRY_WAIT_CAP_S, is_live_surface, provider_retry_after_seconds+ if not is_live_surface(getattr(agent, "platform", "")):+ return False+ cooldown = provider_retry_after_seconds(api_error)+ return cooldown is not None and cooldown > LIVE_RETRY_WAIT_CAP_S++def _codex_soft_failure_error(response: Any) -> Dict[str, Any]:"""``response.error`` of a Codex ``failed``/``cancelled`` Response as ``{"code", "message"}``(the SDK types it as ``ResponseError``; the raw-SSE assembler keeps the dict); ``{}`` when absent."""diff --git a/agent/turn_recovery_autorecover.py b/agent/turn_recovery_autorecover.pyindex 0dfa2bc10d0..a38544c591e 100644--- a/agent/turn_recovery_autorecover.py+++ b/agent/turn_recovery_autorecover.py@@ -46,23 +46,11 @@ def auto_recovery_cycles(agent: Any) -> int:return max(int(getattr(agent, "_auto_recovery_cycles", 0) or 0), 0)-def _retry_after_seconds(api_error: Any) -> Optional[float]:- """Provider-declared cooldown from the ``Retry-After`` header or a ``retry_after`` body field."""- from agent.retry_utils import parse_retry_after_seconds- value = parse_retry_after_seconds(getattr(getattr(api_error, "response", None), "headers", None))- if value is None:- body = getattr(api_error, "body", None)- if isinstance(body, dict):- nested = body.get("error")- value = parse_retry_after_seconds((nested if isinstance(nested, dict) else body).get("retry_after"))- return value if value is not None and value > 0 else None--def ladder_wait_seconds(cycle: int, api_error: Any) -> float:"""Wait before recovery ``cycle`` (1-based): jittered 15/30/60/60/60 s, or the provider's``Retry-After`` when present (honoured past the 60 s cap, up to 120 s)."""- from agent.retry_utils import jittered_backoff- retry_after = _retry_after_seconds(api_error)+ from agent.retry_utils import jittered_backoff, provider_retry_after_seconds+ retry_after = provider_retry_after_seconds(api_error)if retry_after is not None:return min(retry_after, _RETRY_AFTER_CAP_S)return jittered_backoff(cycle, base_delay=_LADDER_BASE_DELAY_S, max_delay=_LADDER_CAP_S, jitter_ratio=0.2)diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.pyindex 6b748bb6652..91e6d3a9492 100644--- a/hermes_cli/anon_auth.py+++ b/hermes_cli/anon_auth.py@@ -636,6 +636,9 @@ _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"),+ # The gateway's answer to an expired or unreadable bearer: the credential, not the tier. A+ # retry that waited out a long rate limit outlives the 15-minute free-tier JWT and lands here.+ ("invalid jwt", "session_expired"),)_WELCOME_ROUTE_COPY = {# Only reachable when the route heal (``turn_recovery._recover_welcome_tier``) could not move@@ -645,6 +648,9 @@ _WELCOME_ROUTE_COPY = {"named_on_welcome_host": "This Nous account needs to reconnect. {model_hint}","tier_disabled": "Using Hermes without signing in is switched off right now. ""Sign in to keep chatting, it's free. {signin}",+ # Only reachable when re-exchanging the free credential failed (``turn_recovery._recover_welcome_tier``).+ "session_expired": "Hermes couldn't renew its connection to the free model. "+ "Send your message again, or sign in to keep chatting, it's free. {signin}",}# The sign-in door, phrased for a chat surface (slash command) and for a terminal._SIGNIN_CHAT = "To sign in: /login."@@ -715,6 +721,7 @@ def welcome_route_refusal(status: Any, message: Any, base_url: Any = None) -> Op``"anon_on_paid_host"``: a free-tier JWT reached the paid host. ``"named_on_welcome_host"``: anaccount 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.+ ``"session_expired"``: the 403 names the bearer (``invalid jwt``); a fresh credential heals it.The dark-tier 403 is keyed on the ROUTE, not the message: the gateway's permission errorcarries only its generic sentence (the detail stays in its logs), so any 403 answered by thediff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 5c54fd08358..3e46a901e82 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -452,13 +452,14 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->_schedule_session_cap_enforcement() # trim detached idle sessions over the capcwd = _sessions[sid]["cwd"]override = session_model_override or {}+ # Reflect the override now so the client doesn't clobber its sticky pick.+ info_model, info_provider = ((override.get("model"), override.get("provider")) if override+ else _session_default_route(_sessions[sid]))messages = _history_to_messages(history, profile_home=profile_home) # hidden seed rows are not on the wire; count what is (as resume does)return _ok(rid, {"session_id": sid, "stored_session_id": key, "message_count": len(messages),**({"messages_omitted": True} if copy_parent_history else {"messages": messages}),- # Reflect the override now so the client doesn't clobber its sticky pick.- "info": {"model": override.get("model") if override else _session_default_model(_sessions[sid]),- **({"provider": override["provider"]} if override.get("provider") else {}),+ "info": {"model": info_model, **({"provider": info_provider} if info_provider else {}),"tools": {}, "skills": {}, "cwd": cwd, "branch": git_probe.branch(cwd),"project": _project_info_for_cwd(cwd), "lazy": True, "desktop_contract": DESKTOP_BACKEND_CONTRACT,"profile_name": _response_profile_name(profile)}})diff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.pyindex 4adbbf447c7..1ed75fb9c4f 100644--- a/tui_gateway/model_switch.py+++ b/tui_gateway/model_switch.py@@ -150,6 +150,21 @@ def _session_default_model(session: dict) -> str:return _resolve_model()+def _session_default_route(session: dict) -> tuple[str, str]:+ """``(model, provider)`` a not-yet-built session of this profile will run on. On the Nous free tier+ the agent build pins ``nous/welcome`` (``pin_model_for_route``), so the configured default — often the+ silent default, with no provider — is not what the session runs; report the pinned route instead."""+ with _session_profile_runtime_scope({"profile_home": session.get("profile_home") or None},+ hydrate_secrets=False):+ model, provider = _resolve_startup_runtime()+ if not provider:+ with contextlib.suppress(Exception):+ from hermes_cli.anon_auth import GUEST_MODEL, free_tier_route+ if free_tier_route():+ return GUEST_MODEL, "nous"+ return model, provider or ""++def _restart_completed_failed_agent_build(sid: str, session: dict, failed_ready: threading.Event | None) -> bool:"""Replace one completed failed build generation and start its retry."""if failed_ready is None:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 94ce83882a1..811c7d54181 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2276,9 +2276,12 @@ def _live_session_identity(session: dict) -> tuple[str, str]:agent = session.get("agent")override = session.get("model_override") or {}model = (str(pending.get("display_model") or "").strip() or mirror.get("model")- or getattr(agent, "model", "") or override.get("model") or _session_default_model(session))+ or getattr(agent, "model", "") or override.get("model"))provider = (str(pending.get("display_provider") or "").strip() or mirror.get("provider")or getattr(agent, "provider", "") or override.get("provider") or "")+ if not model:+ model, default_provider = _session_default_route(session)+ provider = provider or default_providerreturn str(model), str(provider or "")@@ -2792,10 +2795,12 @@ def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:def _lazy_resume_info(cwd: str, *, model: str = "", provider: str = "", profile: str | None = None) -> dict:"""session.info for a not-yet-built session (session.create's shape); tools/skills land with the deferred build."""+ if not model:+ model, default_provider = _session_default_route({"profile_home": _profile_home(profile)})+ provider = provider or default_providerreturn {"cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd),- "model": model or _session_default_model({"profile_home": _profile_home(profile)}),- "tools": {}, "skills": {}, "lazy": True,+ "model": model, "tools": {}, "skills": {}, "lazy": True,"desktop_contract": DESKTOP_BACKEND_CONTRACT, "profile_name": _response_profile_name(profile),**({"provider": provider} if provider else {}),}@@ -3055,9 +3060,11 @@ def _fallback_session_info(session: dict) -> dict:# so a client can clear a stale label instead of retaining it — the same contract `_lazy_session_info`# above already follows.cwd = _session_cwd(session)+ model, provider = _session_default_route(session)return {"cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd), "lazy": True,- "model": _session_default_model(session), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,+ "model": model, "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,+ **({"provider": provider} if provider else {}),}diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 8a507e6c850..9accec0e403 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1234,6 +1234,8 @@ agent:`agent.api_max_retries` controls how many times Hermes retries a provider API call on transient errors (rate limits, connection drops, 5xx) **before** fallback-provider switching engages. The default is `3` — four attempts total. If you have [fallback providers](./features/fallback-providers.md) configured and want to fail over faster, drop this to `0` so the first transient error on your primary immediately hands off to the fallback instead of churning retries against the flaky endpoint.+A rate limit that names its reset (`Retry-After` or a `retry_after` body field) is waited out, capped at 600 s per retry. The Desktop app and the TUI do not sit through a cooldown longer than 60 s: a retry before the reset only meets the same refusal. The turn ends at once and says when the limit lifts, and a configured fallback runs first. Cron jobs, messaging platforms and `hermes chat -q` keep the long wait, and every wait over a minute is announced when it starts.+`agent.auto_recovery_cycles` is the safety net *after* both the retries and the fallback chain are spent. When the failure is a transient outage (HTTP 5xx, an `overloaded`/529 response, a connect or read timeout) and no answer text has reached you yet, Hermes does not end the turn with "API failed after N retries" — it waits and tries again, up to this many cycles (default `5`), with a jittered 15/30/60/60/60 s schedule. A provider `Retry-After` header wins over the schedule (honoured up to 120 s). Every surface shows the same line while it waits — `⏳ Provider temporarily unavailable — retrying automatically in 30s (cycle 2/5); press Esc to stop` on the CLI/TUI/Desktop, a status bubble on messaging platforms (`send /stop to cancel`), a `hermes.status` SSE event on the API server, and a log line for cron jobs. Pressing Esc (or `/stop`) cancels the wait immediately. Fallback still comes first: with a fallback chain configured, exhaustion moves to the next provider as before, and the ladder only engages once the chain has nothing left. Authentication, billing, request-format, entitlement, content-policy and account-policy errors never enter the ladder. Set `0` to disable it.## Wall-Clock Run Budget