The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: surface the pre-agent provider fallback on the TUI/Desktop gateway and cron too
teknium1adf33e3110cb
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex a38c17bc93a..f1a6cb60696 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -1589,6 +1589,12 @@ def _resolve_job_runtime(job: dict, job_id: str, jc: _CronJobConfig) -> tuple[dilogger.info("Job '%s': fallback resolved to %s model %s",job_id, runtime.get("provider"), fb_model)+ # Delivered with the job output (#74349): a cron agent has no status rail, so the+ # switch would otherwise stay in the scheduler log only. run_job pops it.+ from hermes_cli.fallback_config import pre_agent_fallback_notice+ runtime["_fallback_notice"] = pre_agent_fallback_notice(+ requested or (jc.model_cfg.get("provider") if isinstance(jc.model_cfg, dict) else ""),+ model, runtime.get("provider"), fb_model)return runtime, fb_modelexcept Exception as fb_exc:logger.debug("Job '%s': fallback %s failed: %s", job_id, fb_provider, fb_exc)@@ -2170,6 +2176,7 @@ class _CronAgentSetup:reasoning_config: Any = Nonefallback_model: Any = Nonecredential_pool: Any = None+ fallback_notice: Optional[str] = Nonedef _resolve_cron_agent_setup(job: dict, job_id: str, job_name: str, jc) -> _CronAgentSetup:@@ -2195,6 +2202,7 @@ def _resolve_cron_agent_setup(job: dict, job_id: str, job_name: str, jc) -> _Croreturn setupsetup.runtime, setup.model = _resolve_job_runtime(job, job_id, jc)+ setup.fallback_notice = setup.runtime.pop("_fallback_notice", None)setup.reasoning_config = _resolve_job_reasoning_config(job, _cfg if isinstance(_cfg, dict) else {}, str(setup.model))@@ -2334,6 +2342,11 @@ def run_job(agent, prompt, job, job_id, job_name, scope.task_id, cancel_event,worker_state=_worker_state)final_response = _final_response_from_result(result, job_id, job_name, AIAgent)+ if (setup.fallback_notice and final_response.strip() and not _is_cron_silence_response(final_response)+ and _cron_failure_marker_error(final_response) is None):+ # Pre-agent provider switch (#74349) rides with the delivered report; silence and the+ # agent-declared failure marker keep their first-line/whole-response contract.+ final_response = f"{setup.fallback_notice}\n\n{final_response}"# Keep final_response clean for delivery logic (empty = no delivery).logged_response = final_response if final_response else "(No response generated)"output = _run_doc_header(job, job_name, job_id, prompt) + f"## Response\n\n{logged_response}\n"diff --git a/gateway/run.py b/gateway/run.pyindex 94cdeb776e2..77b88154ca0 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -40,7 +40,7 @@ from agent.interrupt_compat import request_hard_interruptfrom agent.turn_context import compression_made_progressfrom agent.session_activity import ActivityProvenancefrom hermes_cli.config import _is_ssh_remote_tilde_cwd, cfg_get-from hermes_cli.fallback_config import get_fallback_chain+from hermes_cli.fallback_config import get_fallback_chain, pre_agent_fallback_notice# Per-session AIAgent cache bounds (agents are heavy); see _enforce_agent_cache_cap/_session_housekeeping_watcher._AGENT_CACHE_MAX_SIZE = 128@@ -2224,13 +2224,10 @@ def _resolve_runtime_agent_kwargs() -> dict:# Carry fallback notice metadata so the gateway can surface a# user-visible provider switch (#74349). The caller must pop# ``_fallback_notice`` before forwarding kwargs to AIAgent.- fb_provider = fb_config.get("provider") or fb_config.get("requested_provider") or "unknown"- fb_model = fb_config.get("model") or "default"- primary_desc = "/".join(filter(None, [_primary_provider, _primary_model])) or "primary"- fallback_desc = "/".join(filter(None, [fb_provider, fb_model]))- fb_config["_fallback_notice"] = (- f"⚠️ Provider fallback: {primary_desc} unavailable; "- f"using {fallback_desc} for this response."+ fb_config["_fallback_notice"] = pre_agent_fallback_notice(+ _primary_provider, _primary_model,+ fb_config.get("provider") or fb_config.get("requested_provider") or "unknown",+ fb_config.get("model") or "default",)return fb_configraise RuntimeError(format_runtime_provider_error(auth_exc)) from auth_excdiff --git a/hermes_cli/fallback_config.py b/hermes_cli/fallback_config.pyindex f440398c19f..35282d457cb 100644--- a/hermes_cli/fallback_config.py+++ b/hermes_cli/fallback_config.py@@ -59,6 +59,17 @@ def effective_runtime_provider(return resolved+def pre_agent_fallback_notice(+ primary_provider: Any, primary_model: Any, fallback_provider: Any, fallback_model: Any+) -> str:+ """User-visible one-shot line for a provider switch made during credential resolution, before+ any AIAgent exists (#74349). Shared by the messaging gateway, the TUI/Desktop gateway and cron+ so the three pre-agent fallback paths cannot drift in wording."""+ primary_desc = "/".join(str(p).strip() for p in (primary_provider, primary_model) if p) or "primary"+ fallback_desc = "/".join(str(p).strip() for p in (fallback_provider, fallback_model) if p) or "fallback"+ return f"⚠️ Provider fallback: {primary_desc} unavailable; using {fallback_desc} for this response."++def _iter_fallback_entries(raw: Any) -> list[dict[str, Any]]:candidates = [raw] if isinstance(raw, dict) else raw if isinstance(raw, list) else []diff --git a/tests/cron/test_cron_pre_agent_fallback_notice.py b/tests/cron/test_cron_pre_agent_fallback_notice.pynew file mode 100644index 00000000000..eb1a1e046f6--- /dev/null+++ b/tests/cron/test_cron_pre_agent_fallback_notice.py@@ -0,0 +1,55 @@+"""A cron job whose primary provider failed credential resolution and ran on a fallback entry must say+so in the delivered report (#74349): the cron agent has no status rail, so the pre-agent switch would+otherwise live only in the scheduler log. Drives the real ``run_job`` path with AIAgent and+``resolve_runtime_provider`` mocked."""+from unittest.mock import MagicMock, patch++from cron.scheduler import run_job+from hermes_cli.auth import AuthError++_JOB = {"id": "fb-test", "name": "fb test", "prompt": "hello", "model": None, "provider": None,+ "provider_snapshot": None, "base_url": None}+++def _run(tmp_path, *, response: str, primary_fails: bool):+ (tmp_path / "config.yaml").write_text(+ "model:\n default: gpt-5.6-sol\n provider: openai-codex\n"+ "fallback_providers:\n - provider: anthropic\n model: claude-sonnet-5\n api_key: fb-key\n")++ def _resolve(**kwargs):+ # An unpinned job resolves the primary with requested=None (persisted config); only the+ # fallback entry names its provider explicitly.+ if primary_fails and kwargs.get("requested") != "anthropic":+ raise AuthError("expired")+ return {"api_key": "k", "base_url": "https://example.invalid/v1",+ "provider": kwargs.get("requested") or "openai-codex", "api_mode": "chat_completions"}++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._get_hermes_home", return_value=tmp_path), \+ patch("cron.scheduler_delivery._resolve_origin", return_value=None), \+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \+ patch("hermes_state_registry.acquire", return_value=MagicMock()), \+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=_resolve), \+ patch("run_agent.AIAgent") as agent_cls:+ agent_cls.return_value.run_conversation.return_value = {"final_response": response}+ success, _output, final, error = run_job(dict(_JOB))+ return success, final, error, agent_cls.call_args.kwargs+++def test_fallback_run_prepends_the_switch_notice_to_the_delivered_report(tmp_path):+ success, final, error, agent_kwargs = _run(tmp_path, response="Morning brief: all green.", primary_fails=True)+ assert (success, error) == (True, None)+ assert agent_kwargs["provider"] == "anthropic" and agent_kwargs["model"] == "claude-sonnet-5"+ assert "_fallback_notice" not in agent_kwargs+ first, _, rest = final.partition("\n\n")+ assert "openai-codex/gpt-5.6-sol" in first and "anthropic/claude-sonnet-5" in first+ assert rest == "Morning brief: all green."+++def test_primary_run_and_silent_fallback_run_are_untouched(tmp_path):+ _s, final, _e, _k = _run(tmp_path, response="Morning brief: all green.", primary_fails=False)+ assert final == "Morning brief: all green."+ # [SILENT] keeps its whole-response contract so the delivery stays suppressed.+ _s, final, _e, _k = _run(tmp_path, response="[SILENT]", primary_fails=True)+ assert final == "[SILENT]"diff --git a/tests/tui_gateway/test_pre_agent_fallback_notice.py b/tests/tui_gateway/test_pre_agent_fallback_notice.pynew file mode 100644index 00000000000..3fdcea87a3c--- /dev/null+++ b/tests/tui_gateway/test_pre_agent_fallback_notice.py@@ -0,0 +1,47 @@+"""A TUI/Desktop agent built on a credential-resolution fallback (primary AuthError -> fallback_providers+entry) must carry the same one-shot switch notice the messaging gateway surfaces (#74349), and the+private notice key must never reach the AIAgent constructor. Drives the real ``_make_agent``."""+from unittest.mock import patch++from hermes_cli.auth import AuthError+++class _StubAgent:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+++def _build(monkeypatch, tmp_path, *, primary_fails: bool):+ from tui_gateway import server++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_IGNORE_RULES", "1")+ (tmp_path / "config.yaml").write_text("model:\n default: gpt-5.6-sol\n provider: openai-codex\n")+ monkeypatch.setattr(server, "_hermes_home", tmp_path)+ monkeypatch.setattr(server, "_get_db", lambda: None)+ monkeypatch.setattr(server, "_load_fallback_model",+ lambda: [{"provider": "anthropic", "model": "claude-sonnet-5", "api_key": "fb"}])++ def _resolve(**kwargs):+ if primary_fails and kwargs.get("requested") != "anthropic":+ raise AuthError("expired")+ return {"api_key": "k", "base_url": "https://example.invalid/v1",+ "provider": kwargs.get("requested") or "openai-codex", "api_mode": "chat_completions"}++ with patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=_resolve), \+ patch("run_agent.AIAgent", _StubAgent):+ return server._make_agent("sid", "key", context_cwd_is_launch_artifact=False)+++def test_fallback_build_attaches_the_switch_notice_outside_agent_kwargs(monkeypatch, tmp_path):+ agent = _build(monkeypatch, tmp_path, primary_fails=True)+ assert (agent.kwargs["provider"], agent.kwargs["model"]) == ("anthropic", "claude-sonnet-5")+ assert "_fallback_notice" not in agent.kwargs+ notice = agent._pending_fallback_notice+ assert "openai-codex/gpt-5.6-sol" in notice and "anthropic/claude-sonnet-5" in notice+++def test_primary_build_carries_no_notice(monkeypatch, tmp_path):+ agent = _build(monkeypatch, tmp_path, primary_fails=False)+ assert agent.kwargs["provider"] == "openai-codex"+ assert not hasattr(agent, "_pending_fallback_notice")diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 40bf6bcb17b..0b16a021f70 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2265,6 +2265,13 @@ def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[strif resolution.used_fallback:if not resolution.selected_model:raise RuntimeError("Auth fallback resolved without a model")+ # Same pre-agent switch the messaging gateway surfaces (#74349); _make_agent pops it onto the+ # agent's one-shot notice so the TUI/Desktop user sees which provider actually answered.+ from hermes_cli.fallback_config import pre_agent_fallback_notice+ # requested_provider=None means resolve_runtime_provider read the persisted config provider.+ primary_provider = requested_provider or (_load_cfg().get("model") or {}).get("provider")+ resolution.runtime["_fallback_notice"] = pre_agent_fallback_notice(+ primary_provider, model, resolution.runtime.get("provider"), resolution.selected_model)return resolution.selected_model, resolution.runtimeif resolution.runtime.get("source") == "local-runtime":# Live supervisor beat any persisted loopback URL for this identity.@@ -2337,6 +2344,7 @@ def _make_agent(register_from_config(cfg)system_prompt = _startup_system_prompt(cfg, session_id or key)model, runtime = _resolve_agent_model_runtime(model_override, provider_override)+ fallback_notice = runtime.pop("_fallback_notice", None)_pr = _load_provider_routing()platform = _resolve_agent_platform(platform_override)ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))@@ -2368,6 +2376,9 @@ def _make_agent(if context_cwd_is_launch_artifact is None:context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)+ if fallback_notice:+ # Emitted once on the first successful reply via _emit_pending_fallback_notice -> status_callback.+ agent._pending_fallback_notice = fallback_noticereturn agent