The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(agent): bounded auto-recovery ladder after retries and fallback are spent (#85426, #107307)
teknium10752127c5e63
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 3f09b85b8ed..8b8962db8bf 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -1372,6 +1372,12 @@ def _apply_agent_section(agent, _agent_cfg):except (TypeError, ValueError):_api_retries = 3agent._api_max_retries = _api_retries+ # Bounded post-exhaustion auto-recovery cycles once retries AND the fallback chain are spent+ # on a transient outage (agent/turn_recovery_autorecover.py). 0 disables the ladder.+ try:+ agent._auto_recovery_cycles = max(int(_agent_section.get("auto_recovery_cycles", 5)), 0)+ except (TypeError, ValueError):+ agent._auto_recovery_cycles = 5def _positive_int(raw: Any, *, reject: tuple = ()) -> Optional[int]:diff --git a/agent/turn_api_error.py b/agent/turn_api_error.pyindex b19dd9ecf01..464801c0cc5 100644--- a/agent/turn_api_error.py+++ b/agent/turn_api_error.py@@ -373,6 +373,17 @@ def settle_unrecovered_error(active_system_prompt = _arm_fallback_restart(agent, api_messages, active_system_prompt, _retry)retry_count = compression_attempts = 0return _verdict("break")+ # Fallback first (above); only with nothing left to move to does the bounded auto-recovery+ # ladder park the turn on a transient outage instead of ending it (#85426, #107307).+ from agent.turn_recovery_autorecover import auto_recover_after_exhaustion+ _ladder = auto_recover_after_exhaustion(+ agent, api_error, classified, _retry, messages=messages,+ conversation_history=conversation_history, api_call_count=api_call_count,+ )+ if _ladder is not None:+ if _ladder["action"] == "continue":+ retry_count = 0+ return _verdict(_ladder["action"], _ladder.get("result"))return _verdict("return", max_retries_exhausted_result(agent, api_error, classified, max_retries=max_retries, is_rate_limited=is_rate_limited,error_msg=error_msg, api_kwargs=api_kwargs, api_messages=api_messages,diff --git a/agent/turn_recovery_autorecover.py b/agent/turn_recovery_autorecover.pynew file mode 100644index 00000000000..0dfa2bc10d0--- /dev/null+++ b/agent/turn_recovery_autorecover.py@@ -0,0 +1,128 @@+"""Bounded post-exhaustion auto-recovery ladder for a pre-delivery turn (#85426, #107307).++Runs from ``settle_unrecovered_error`` once ``max_retries`` is spent AND the fallback chain has+nothing left to move to (fallback stays first). While the provider is only *temporarily* away+(5xx, overloaded/529, connect/read timeouts) and no answer text has reached the user yet, the+turn parks with a visible countdown instead of ending in "API failed after N retries", then+re-enters the ordinary retry loop. Cycles: ``agent.auto_recovery_cycles`` (default 5) with a+jittered 15/30/60/60/60 s schedule; a provider ``Retry-After`` wins up to 120 s. Non-retryable+classes (auth, format, content policy, billing, entitlement) never enter, and an interrupt+cancels the wait cleanly. Overload-class errors use this same schedule — there is no separate+overload backoff path.+"""++from __future__ import annotations++import logging+from typing import Any, Dict, Optional++from agent.error_classifier import FailoverReason++logger = logging.getLogger("agent.conversation_loop")++# Transient transport verdicts: the provider is expected back. Everything else (auth, format,+# content policy, billing, entitlement, overflow, model-not-found ...) is deterministic for this+# request and stays out.+_LADDER_REASONS = frozenset({FailoverReason.overloaded, FailoverReason.server_error, FailoverReason.timeout})++_LADDER_BASE_DELAY_S = 15.0+_LADDER_CAP_S = 60.0+# A provider that names its own cooldown knows better than the schedule, within reason.+_RETRY_AFTER_CAP_S = 120.0++# How the user stops the wait on this surface; the ladder text must say so plainly.+_STOP_HINTS = {+ "cli": "press Esc to stop",+ "tui": "press Esc to stop",+ "desktop": "press Esc to stop",+ "api_server": "cancel the request to stop",+ "cron": "",+}+_DEFAULT_STOP_HINT = "send /stop to cancel"+++def auto_recovery_cycles(agent: Any) -> int:+ """Configured ``agent.auto_recovery_cycles`` (0 disables the ladder)."""+ 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)+ 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)+++def ladder_eligible(agent: Any, classified: Any) -> bool:+ """True when the ladder may engage: cycles configured, a transient transport verdict, and no+ answer text streamed to the user yet (delivered text is never replayed by this path)."""+ if auto_recovery_cycles(agent) <= 0 or classified.reason not in _LADDER_REASONS:+ return False+ streamed = getattr(agent, "_current_streamed_assistant_text", "") or ""+ return not agent._has_content_after_think_block(streamed)+++def ladder_notice(agent: Any, *, wait_s: float, cycle: int, total: int) -> str:+ hint = _STOP_HINTS.get(str(getattr(agent, "platform", "") or "").lower(), _DEFAULT_STOP_HINT)+ text = f"⏳ Provider temporarily unavailable — retrying automatically in {wait_s:.0f}s (cycle {cycle}/{total})"+ return f"{text}; {hint}" if hint else text+++def auto_recover_after_exhaustion(+ agent: Any, api_error: Any, classified: Any, _retry: Any, *, messages: Any,+ conversation_history: Any, api_call_count: int,+) -> Optional[Dict[str, Any]]:+ """Run one recovery cycle after retries + fallback exhausted. Returns ``{"action": "continue"}``+ when the wait completed (caller zeroes ``retry_count`` and re-enters the retry loop),+ ``{"action": "break"}`` when a steering correction arrived mid-wait, ``{"action": "return",+ "result": …}`` when the user interrupted, and ``None`` when the ladder does not apply or is spent."""+ from agent.turn_recovery import interruptible_backoff_sleep++ if not ladder_eligible(agent, classified):+ return None+ total = auto_recovery_cycles(agent)+ used = int(getattr(_retry, "auto_recovery_cycles_used", 0) or 0)+ if used >= total:+ agent._emit_diagnostic_status(+ f"⏳ Automatic recovery gave up after {total} cycles — the provider is still unavailable."+ )+ return None+ cycle = used + 1+ _retry.auto_recovery_cycles_used = cycle+ wait_s = ladder_wait_seconds(cycle, api_error)+ notice = ladder_notice(agent, wait_s=wait_s, cycle=cycle, total=total)+ # Durable line on every surface (CLI print, TUI status.update, gateway bubble, api_server SSE)+ # plus the live wait line (spinner / thinking.delta / activity heartbeat).+ agent._emit_diagnostic_status(notice)+ agent._emit_diagnostic_wait(notice)+ logger.warning(+ "%sProvider unavailable (%s) — auto-recovery cycle %d/%d, retrying in %.0fs %s",+ agent.log_prefix, classified.reason.value, cycle, total, wait_s, agent._client_log_context(),+ )+ interrupted = interruptible_backoff_sleep(+ agent, wait_s, _retry, messages=messages, conversation_history=conversation_history,+ api_call_count=api_call_count,+ abort_message="Interrupt detected during automatic recovery wait, aborting.",+ interrupt_text=f"Operation interrupted: waiting for the provider to recover (cycle {cycle}/{total}).",+ activity_label=f"auto-recovery wait ({cycle}/{total})",+ )+ if interrupted is not None:+ return {"action": "return", "result": interrupted}+ if _retry.restart_with_redirected_messages:+ return {"action": "break"}+ return {"action": "continue"}diff --git a/agent/turn_retry_state.py b/agent/turn_retry_state.pyindex 243b8a2c753..f5f2925a425 100644--- a/agent/turn_retry_state.py+++ b/agent/turn_retry_state.py@@ -44,6 +44,8 @@ class TurnRetryState:has_retried_429: bool = False# Persistent 401/403 already escalated to the fallback chain once this attempt.auth_failover_attempted: bool = False+ # Post-exhaustion auto-recovery cycles spent on this API call (agent.auto_recovery_cycles caps it).+ auto_recovery_cycles_used: int = 0# Restart signals (read by the outer loop after the attempt)restart_with_compressed_messages: bool = Falsediff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 908b1e31b67..b715f8da041 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -1213,6 +1213,15 @@ agent:# underneath this wrapper — this is the Hermes-level loop.# api_max_retries: 3+ # Once api_max_retries AND the fallback chain are spent on a transient outage+ # (5xx, overloaded/529, connect/read timeouts) and nothing has been delivered+ # yet, Hermes waits and retries this many more cycles (jittered 15/30/60/60/60s;+ # a provider Retry-After wins, up to 120s) showing "Provider temporarily+ # unavailable — retrying automatically in Ns (cycle k/5); press Esc to stop"+ # instead of ending the turn. Auth/format/billing/policy errors never enter.+ # Set 0 to disable (default 5).+ # auto_recovery_cycles: 5+# After the agent edits code without fresh passing verification, nudge it to# verify before finishing. Off by default (false). Set true to force it on# everywhere, or "auto" for the surface-aware mode: on for interactivediff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 4b519f3ca7c..fd9284377f4 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -107,6 +107,12 @@ DEFAULT_CONFIG = {# whole call; the OpenAI SDK also retries transient errors (max_retries=2). Set 1 for fast# failover to fallback providers; raise to tolerate longer provider hiccups."api_max_retries": 3,+ # Once api_max_retries AND the fallback chain are spent on a transient outage (5xx,+ # overloaded/529, connect/read timeouts) with nothing delivered yet, wait and retry this many+ # more cycles (jittered 15/30/60/60/60s; a provider Retry-After wins up to 120s) with a+ # visible "retrying automatically" countdown instead of ending the turn. Esc/interrupt stops+ # the wait; auth/format/billing/policy errors never enter. 0 disables.+ "auto_recovery_cycles": 5,# Seconds the Codex/Responses stream may keep reading after its terminal frame so the relay# finalizer can run. Relays that never close the SSE socket after response.completed would# otherwise wedge the turn until the idle watchdog discards the already-billed responsediff --git a/tests/agent/test_turn_recovery_autorecover.py b/tests/agent/test_turn_recovery_autorecover.pynew file mode 100644index 00000000000..a2ef49473f8--- /dev/null+++ b/tests/agent/test_turn_recovery_autorecover.py@@ -0,0 +1,159 @@+"""Bounded post-exhaustion auto-recovery ladder (#85426, #107307): fallback first, transient+outages only, visible on every surface, interrupt cancels."""+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from agent.error_classifier import classify_api_error+from agent.turn_api_error import settle_unrecovered_error+from agent.turn_recovery_autorecover import ladder_wait_seconds+from agent.turn_retry_state import TurnRetryState+++class _Err(Exception):+ def __init__(self, status_code, message, headers=None):+ super().__init__(message)+ self.status_code = status_code+ self.message = message+ self.response = SimpleNamespace(headers=headers or {})+ self.body = None+++class _Agent:+ """Real seams: fallback state, the status/wait callbacks the surfaces read, the streamed-text+ gate and the interrupt flag; everything else the terminal path touches is a no-op."""+ log_prefix = ""+ verbose = False+ provider = "custom"+ platform = "cli"+ _credential_pool = None+ _current_streamed_assistant_text = ""+ _interrupt_requested = False+ sleep_outcome = None # what the (patched) interruptible wait returns++ def __init__(self, *, fallback_left=False, cycles=5, platform="cli"):+ self.statuses, self.waits, self.activated = [], [], []+ self._fallback_left = fallback_left+ self._auto_recovery_cycles = cycles+ self.platform = platform++ def _has_pending_fallback(self):+ return self._fallback_left++ def _try_activate_fallback(self, **kwargs):+ self.activated.append(True)+ return self._fallback_left++ def _try_recover_primary_transport(self, *a, **k):+ return False++ def _has_content_after_think_block(self, text):+ return bool(text.strip())++ def _emit_diagnostic_status(self, text):+ self.statuses.append(str(text))++ def _emit_diagnostic_wait(self, text):+ self.waits.append(str(text))++ def _summarize_api_error(self, error):+ return str(error)++ def _client_log_context(self):+ return ""++ def clear_interrupt(self, **kwargs):+ return False++ def __getattr__(self, name):+ return lambda *args, **kwargs: None+++def _settle(agent, err, retry=None):+ retry = retry or TurnRetryState(primary_recovery_attempted=True)+ classified = classify_api_error(err, provider=agent.provider)+ with patch("agent.conversation_loop._is_copilot_provider", lambda a: False), \+ patch("agent.conversation_loop._arm_fallback_restart", lambda a, m, s, r: s), \+ patch("agent.turn_recovery.interruptible_backoff_sleep", lambda agent, *a, **k: agent.sleep_outcome), \+ patch("agent.turn_api_error.max_retries_exhausted_result", lambda *a, **k: {"failed": True}), \+ patch("agent.turn_api_error.nonretryable_client_error_result", lambda *a, **k: {"failed": True, "nonretryable": True}):+ return settle_unrecovered_error(+ agent, api_error=err, classified=classified, _retry=retry, status_code=err.status_code,+ error_msg=str(err).lower(), is_context_length_error=False, is_rate_limited=False,+ _is_zai_coding_overload=False, _provider=agent.provider, _base="http://x", _model="m",+ messages=[], api_messages=[], api_kwargs=None, active_system_prompt=None,+ conversation_history=None, approx_tokens=0, retry_count=3, max_retries=3,+ compression_attempts=0, api_call_count=1,+ ), retry++[email protected]("status,message", [(503, "Service temporarily unavailable"), (529, "Overloaded")])+def test_transient_exhaustion_without_fallback_enters_ladder_and_retries(status, message):+ """No fallback left + 5xx/overloaded + nothing delivered -> one visible cycle, then retry from 0."""+ agent = _Agent()+ verdict, retry = _settle(agent, _Err(status, message))+ assert (verdict.action, verdict.retry_count, retry.auto_recovery_cycles_used) == ("continue", 0, 1)+ assert agent.statuses == agent.waits and len(agent.statuses) == 1+ line = agent.statuses[0]+ assert "retrying automatically in" in line and "(cycle 1/5)" in line and "press Esc to stop" in line+++def test_ladder_is_bounded_and_yields_to_fallback_and_shuns_nonretryable():+ agent = _Agent()+ spent = TurnRetryState(primary_recovery_attempted=True, auto_recovery_cycles_used=5)+ verdict, _ = _settle(agent, _Err(503, "down"), retry=spent)+ assert verdict.action == "return" and verdict.result == {"failed": True}+ assert any("gave up after 5 cycles" in s for s in agent.statuses)++ # Fallback first: a remaining fallback engages and the ladder never runs.+ fb = _Agent(fallback_left=True)+ verdict, retry = _settle(fb, _Err(503, "down"))+ assert (verdict.action, fb.activated, retry.auto_recovery_cycles_used) == ("break", [True], 0)++ # Non-retryable classes never enter (401 here) and delivered text is never replayed.+ auth = _Agent()+ verdict, retry = _settle(auth, _Err(401, "Incorrect API key provided"))+ assert verdict.result.get("nonretryable") and retry.auto_recovery_cycles_used == 0+ streamed = _Agent()+ streamed._current_streamed_assistant_text = "Here is the first half of the answer"+ verdict, retry = _settle(streamed, _Err(503, "down"))+ assert (verdict.action, retry.auto_recovery_cycles_used) == ("return", 0)++ # Disabled by config.+ off = _Agent(cycles=0)+ verdict, retry = _settle(off, _Err(503, "down"))+ assert (verdict.action, retry.auto_recovery_cycles_used, off.statuses) == ("return", 0, [])+++def test_ladder_schedule_honours_retry_after_and_platform_stop_hint(monkeypatch):+ import agent.retry_utils as retry_utils+ calls = []++ def _recording_backoff(attempt, *, base_delay, max_delay, jitter_ratio):+ calls.append((attempt, base_delay, max_delay))+ return min(base_delay * 2 ** (attempt - 1), max_delay)+ monkeypatch.setattr(retry_utils, "jittered_backoff", _recording_backoff)++ plain = _Err(503, "down")+ assert [ladder_wait_seconds(c, plain) for c in (1, 2, 3, 4, 5)] == [15, 30, 60, 60, 60]+ assert calls[0] == (1, 15.0, 60.0)+ assert ladder_wait_seconds(1, _Err(529, "Overloaded", {"Retry-After": "4"})) == 4+ # Past the 60 s cap the provider's own cooldown is honoured, up to 120 s.+ assert ladder_wait_seconds(1, _Err(529, "Overloaded", {"Retry-After": "90"})) == 90+ assert ladder_wait_seconds(1, _Err(529, "Overloaded", {"Retry-After": "900"})) == 120++ tg = _Agent(platform="telegram")+ _settle(tg, plain)+ assert "send /stop to cancel" in tg.statuses[0]+ cron = _Agent(platform="cron")+ _settle(cron, plain)+ assert cron.statuses[0].endswith("(cycle 1/5)")+++def test_interrupt_during_ladder_wait_returns_interrupted_result():+ agent = _Agent()+ agent.sleep_outcome = {"interrupted": True, "completed": False}+ verdict, retry = _settle(agent, _Err(503, "down"))+ assert verdict.action == "return" and verdict.result["interrupted"] is True+ assert retry.auto_recovery_cycles_used == 1diff --git a/tests/agent/test_turn_retry_state.py b/tests/agent/test_turn_retry_state.pyindex 367981ebebf..ea78810b5ec 100644--- a/tests/agent/test_turn_retry_state.py+++ b/tests/agent/test_turn_retry_state.py@@ -34,6 +34,7 @@ EXPECTED_FIELDS = {"primary_recovery_attempted","has_retried_429","auth_failover_attempted",+ "auto_recovery_cycles_used","restart_with_compressed_messages","restart_with_length_continuation","restart_with_rebuilt_messages",diff --git a/tests/gateway/test_api_server_status_stream.py b/tests/gateway/test_api_server_status_stream.pynew file mode 100644index 00000000000..c966bd78c0c--- /dev/null+++ b/tests/gateway/test_api_server_status_stream.py@@ -0,0 +1,73 @@+"""Agent status lines reach the OpenAI-compatible SSE writers as ``hermes.status`` events (#85426):+the auto-recovery countdown must not leave an API client staring at a silent socket."""++import asyncio+import time+import uuid+from unittest.mock import patch++import pytest++from gateway.platforms.api_server import ThreadSafeAsyncQueue+from tests.gateway.test_api_server_reasoning_stream import (+ _fake_writer_env, _frames, _stub_create_agent_runtime, adapter, # noqa: F401+)++_LADDER = "⏳ Provider temporarily unavailable — retrying automatically in 15s (cycle 1/5); cancel the request to stop"+++async def test_chat_completions_stream_forwards_agent_status_callback(adapter, monkeypatch):+ """``_spawn_stream_agent`` wires ``status_callback`` into ``AIAgent(...)``; a status line arrives+ as an ``event: hermes.status`` frame and never as answer ``content``."""+ import gateway.platforms.api_server as api_mod++ class FakeAgent:+ def __init__(self, **kwargs):+ self._status_callback = kwargs.get("status_callback")+ self._stream_delta_callback = kwargs.get("stream_delta_callback")+ self.session_id = kwargs.get("session_id")++ def run_conversation(self, **kwargs):+ self._status_callback("lifecycle", _LADDER)+ self._stream_delta_callback("answer")+ return {"final_response": "answer", "completed": True}++ _stub_create_agent_runtime(monkeypatch, FakeAgent)+ monkeypatch.setattr(adapter, "_ensure_session_db", lambda: None)+ request, written, fake_response = _fake_writer_env()+ stream_q = ThreadSafeAsyncQueue()+ agent_task, agent_ref = adapter._spawn_stream_agent(+ stream_q, user_message="q", conversation_history=[], session_id="api-session")+ with patch.object(api_mod.web, "StreamResponse", return_value=fake_response):+ await adapter._write_sse_chat_completion(+ request, "chatcmpl-x", "hermes-agent", int(time.time()), stream_q, agent_task, agent_ref)+ frames = _frames(written)+ assert [d for e, d in frames if e == "hermes.status"] == [{"kind": "lifecycle", "text": _LADDER}]+ content = "".join(d["choices"][0]["delta"].get("content") or "" for e, d in frames if e is None)+ assert content == "answer"+++async def test_responses_stream_emits_status_event_outside_output_items(adapter):+ import gateway.platforms.api_server as api_mod+ request, written, fake_response = _fake_writer_env()+ stream_q = ThreadSafeAsyncQueue()++ async def _agent():+ stream_q.put_nowait(("__status__", {"kind": "lifecycle", "text": _LADDER}))+ stream_q.put_nowait("final text")+ return {"final_response": "final text", "completed": True}, None++ agent_task = asyncio.ensure_future(_agent())+ agent_task.add_done_callback(lambda _f: stream_q.put_nowait(None))+ with patch.object(api_mod.web, "StreamResponse", return_value=fake_response):+ await adapter._write_sse_responses(+ request=request, response_id=f"resp_{uuid.uuid4().hex[:28]}", model="hermes-agent",+ created_at=int(time.time()), stream_q=stream_q, agent_task=agent_task, agent_ref=[None],+ conversation_history=[], user_message="q", instructions=None, conversation=None,+ store=False, session_id=None)+ frames = _frames(written)+ assert [d for e, d in frames if e == "hermes.status"] == [{"kind": "lifecycle", "text": _LADDER}]+ completed = next(d for e, d in frames if e == "response.completed")+ assert [o["type"] for o in completed["response"]["output"]] == ["message"]diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 3b013987925..5d46f2d61d1 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1208,6 +1208,7 @@ agent:# "unlimited"/"inf"/"infinity"/"infinite"/0/-1 = no limitbudget_warning_ratio: null # Optional one-time checkpoint warning, e.g. 0.75api_max_retries: 3 # Retries per provider before fallback engages (default: 3)+ auto_recovery_cycles: 5 # Wait-and-retry cycles after retries + fallback are spent on an outage (0 = off)````agent.max_turns` is **unlimited by default** — the turn cap caused more problems than it solved (silent mid-task truncation), so out of the box Hermes runs a conversation turn to completion. To impose a cap, set a positive integer. To be explicit about "no limit", any of these case-insensitive spellings work: `"none"`, `"null"`, `"unlimited"`, `"infinite"`, `"infinity"`, `"inf"`, `0`, `-1` (they resolve to a `sys.maxsize` sentinel so the loop never exits on a turn count).@@ -1216,6 +1217,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.+`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 and content-policy errors never enter the ladder. Set `0` to disable it.+## Wall-Clock Run BudgetSeparate from the iteration budget, you can give each conversation run an optional **wall-clock** budget. This is designed for one-shot and eval-harness invocations that run under a hard external ceiling (e.g. a 900-second per-task limit): without it, a run can time out with the work essentially done — one generation short of emitting the final answer, or stuck in a single hung provider call.