The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): a pinned job never falls back to the global fallback chain (#120312)
Austin Pickette7bff4b6d831
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 4a9ea985b96..c70b868a534 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -40,7 +40,7 @@ from cron.env_settings import cron_env_settingfrom hermes_cli._subprocess_compat import windows_hide_flagsfrom hermes_cli.config import (load_config, load_config_readonly)-from hermes_cli.fallback_config import get_fallback_chain+from hermes_cli.fallback_config import get_fallback_chain, scoped_fallback_chainfrom hermes_time import now as _hermes_nowfrom agent.interrupt_compat import request_hard_interruptfrom agent.delegation_context import (@@ -99,11 +99,35 @@ def _set_cron_session_title(session_db, session_id, base_title):return deduped-def _fallback_chain_phrase() -> str:- """Backup-provider clause for a provider-failure notice: "the backups failed too" vs "none- configured" (most installs). Fails open to the former if config can't be read — never crash- delivery.+def _job_route_pinned(job: dict) -> bool:+ """True when the job carries its own provider, model or endpoint. Unpinned jobs store none of+ these (they follow the main model at fire time), so any value is an explicit operator pin."""+ return any(isinstance(job.get(k), str) and job[k].strip() for k in ("provider", "model", "base_url"))+++def _job_fallback_chain(job: dict, cfg: Any) -> Optional[list]:+ """The fallback chain this job may walk, at credential resolution AND mid-run (#100437).++ A pinned job never borrows the global ``fallback_providers`` chain, the same rule a pinned+ ``delegate_task`` child follows (``scoped_fallback_chain``): a chain entry is a different+ provider and usually a different model, which is exactly what the pin ruled out. Same-provider+ credential-pool rotation is not the chain and still applies. Unpinned jobs inherit the chain.+ """+ return scoped_fallback_chain(+ get_fallback_chain(cfg), None, pinned=_job_route_pinned(job), owner="cron job")+++def _fallback_chain_phrase(job: Optional[dict] = None) -> str:+ """Backup-provider clause for a provider-failure notice: "pinned, no fallback" vs "the backups+ failed too" vs "none configured" (most installs). Fails open to "the backups failed too" if+ config can't be read — never crash delivery."""+ if job is not None and _job_route_pinned(job):+ return (+ "This job is pinned to its own provider/model, so it does not fall back to "+ f"`fallback_providers`; `hermes cron edit {job.get('id')} --unpin` lets it follow the "+ "main model and its fallback chain."+ )try:cfg = load_config() or {}chain = get_fallback_chain(cfg)@@ -294,7 +318,7 @@ def _summarize_cron_failure_for_delivery(job: dict, error: str | None) -> str:if not job.get("no_agent"):notice = provider_failure_notice(job_name, job_id, classify_cron_failure_reason(text),- backup_provider_phrase=_fallback_chain_phrase(), provider=job.get("provider"))+ backup_provider_phrase=_fallback_chain_phrase(job), provider=job.get("provider"))if notice is not None:return notice@@ -1698,7 +1722,8 @@ def _resolve_job_runtime(job: dict, job_id: str, jc: _CronJobConfig) -> tuple[di"""Resolve the runtime, walking the fallback chain on auth/transient-network errors. Returns``(runtime, model)``; provider+model swap atomically (never swap only the provider while keepinga paid primary model). Provider precedence: per-job pin > cron.model_provider > persisted- global config (None lets resolve_runtime_provider read it)."""+ global config (None lets resolve_runtime_provider read it). A pinned job has no chain here+ (``_job_fallback_chain``): its resolve failure is the job's failure."""from hermes_cli.runtime_provider import (resolve_runtime_provider, format_runtime_provider_error)from hermes_cli.auth import AuthError@@ -1724,10 +1749,13 @@ def _resolve_job_runtime(job: dict, job_id: str, jc: _CronJobConfig) -> tuple[diif not (is_auth or is_transient_net):raise RuntimeError(format_runtime_provider_error(resolve_exc)) from resolve_exc+ chain = _job_fallback_chain(job, jc.cfg) or []logger.warning(- "Job '%s': primary provider resolve failed (%s: %s), trying fallback",- job_id, "auth" if is_auth else "transient network", resolve_exc)- for entry in get_fallback_chain(jc.cfg):+ "Job '%s': primary provider resolve failed (%s: %s), %s",+ job_id, "auth" if is_auth else "transient network", resolve_exc,+ "trying fallback" if chain else (+ "not falling back: the job is pinned" if _job_route_pinned(job) else "no fallback configured"))+ for entry in chain:if not isinstance(entry, dict):continuefb_provider = str(entry.get("provider") or "").strip()@@ -2362,7 +2390,9 @@ def _resolve_cron_agent_setup(job: dict, job_id: str, job_name: str, jc) -> _Crosetup.reasoning_config = _resolve_job_reasoning_config(job, _cfg if isinstance(_cfg, dict) else {}, str(setup.model))- setup.fallback_model = get_fallback_chain(_cfg) or None+ # Mid-run provider ladder: same rule as resolution above, so a pinned job cannot be swapped+ # onto the global chain by a 5xx/429 either.+ setup.fallback_model = _job_fallback_chain(job, _cfg)setup.credential_pool = _load_credential_pool(setup.runtime, job_id)# MCP servers must be registered before AIAgent is constructed._init_cron_mcp_tools(job_id)diff --git a/cron/scheduler_preflight.py b/cron/scheduler_preflight.pyindex d0f8ca7f3c0..b77c8fd3e83 100644--- a/cron/scheduler_preflight.py+++ b/cron/scheduler_preflight.py@@ -85,10 +85,11 @@ def _cron_preflight_enabled(cfg: dict) -> bool:def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:"""READ-ONLY probe: would provider resolution fail for lack of a key? Mirrors run_job's- requested-provider computation. Skipped when a fallback chain exists — auth-fallback may- legitimately rescue a missing primary key, so blocking here would break that contract."""+ requested-provider computation. Skipped when the job has a fallback chain — auth-fallback may+ legitimately rescue a missing primary key. A pinned job has none (``_job_fallback_chain``), so+ its missing key blocks even when the global chain is configured."""try:- if _sched.get_fallback_chain(cfg):+ if _sched._job_fallback_chain(job, cfg):return Noneexcept Exception:return None # fail-open: never block on a preflight-internal errordiff --git a/hermes_cli/fallback_config.py b/hermes_cli/fallback_config.pyindex 35282d457cb..afa368391a0 100644--- a/hermes_cli/fallback_config.py+++ b/hermes_cli/fallback_config.py@@ -2,8 +2,11 @@from __future__ import annotations+import loggingfrom typing import Any+logger = logging.getLogger(__name__)+def _normalized_base_url(value: Any) -> str:return value.strip().rstrip("/") if isinstance(value, str) else ""@@ -115,3 +118,27 @@ def get_fallback_chain(config: dict[str, Any] | None) -> list[dict[str, Any]]:seen.add(identity)chain.append(entry)return chain+++def scoped_fallback_chain(+ inherited: list[dict[str, Any]] | None, declared: Any, *, pinned: bool, owner: str,+) -> list[dict[str, Any]] | None:+ """Fallback chain for a route owner that can pin its own primary (delegated child, cron job).++ A pinned owner (explicit provider, endpoint or model) never borrows the *inherited* chain: the+ operator chose that route, and a chain entry is a different provider and usually a different+ model. Predictability beats liveness for an explicit pin. An unpinned owner inherits the chain+ when *declared* is absent/None. An explicit ``[]`` disables fallback either way; any other+ *declared* value is the owner's own chain, normalized by :func:`get_fallback_chain` (malformed+ entries are dropped; nothing usable left falls back to the pinned/inherited default).+ """+ default = None if pinned else (inherited or None)+ if declared is None:+ return default+ if declared == []:+ return None+ normalized = get_fallback_chain({"fallback_providers": declared})+ if not normalized:+ logger.warning("%s fallback_providers has no usable routes; using the %s default",+ owner, "pinned" if pinned else "inherited")+ return normalized or defaultdiff --git a/tests/cron/test_cron_pinned_job_fallback.py b/tests/cron/test_cron_pinned_job_fallback.pynew file mode 100644index 00000000000..a3ad92b0d5e--- /dev/null+++ b/tests/cron/test_cron_pinned_job_fallback.py@@ -0,0 +1,178 @@+"""A cron job with its own provider/model/base_url pin never walks the global fallback chain (#100437).++Two vectors, one rule (``cron.scheduler._job_fallback_chain``, shared with delegate_task's pinned+children via ``hermes_cli.fallback_config.scoped_fallback_chain``):++- credential resolution: an AuthError / DNS blip on the pinned primary must not resolve a+ ``fallback_providers`` entry instead;+- mid-run: the chain handed to ``AIAgent(fallback_model=...)`` is what the conversation loop's+ provider ladder walks on a 5xx/429, so a pinned job must get none.++Unpinned jobs (which store no provider/model since jobs follow the main model) keep inheriting+the chain at both points. Drives the real ``run_job`` with AIAgent and+``resolve_runtime_provider`` mocked.+"""++from unittest.mock import MagicMock, patch++import pytest++from cron import scheduler+from cron.scheduler import _CronJobConfig, _resolve_job_runtime, run_job+from hermes_cli.auth import AuthError++_CONFIG = (+ "model:\n"+ " default: gpt-5.6-sol\n"+ " provider: openai-codex\n"+ "fallback_providers:\n"+ " - provider: openrouter\n"+ " model: z-ai/glm-5.2\n"+)+_CHAIN = [{"provider": "openrouter", "model": "z-ai/glm-5.2"}]+++def _runtime(provider):+ return {"api_key": "k", "base_url": "https://example.invalid/v1", "provider": provider,+ "api_mode": "chat_completions"}+++def _run(tmp_path, job, *, primary_error=None):+ """Run *job*; the primary resolve raises *primary_error* (if any), fallback entries succeed.+ Returns ``(success, error, requested providers, AIAgent kwargs — {} when never built)``."""+ (tmp_path / "config.yaml").write_text(_CONFIG, encoding="utf-8")+ requested = []++ def resolve(**kwargs):+ requested.append(kwargs.get("requested"))+ if kwargs.get("requested") == "openrouter":+ return _runtime("openrouter")+ if primary_error is not None:+ raise primary_error+ return _runtime(kwargs.get("requested") or "openai-codex")++ 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("tools.mcp_tool_discovery.discover_mcp_tools", return_value=[]), \+ patch("run_agent.AIAgent") as agent_cls:+ agent_cls.return_value.run_conversation.return_value = {"final_response": "ok"}+ success, _output, _final, error = run_job(dict(job))+ kwargs = agent_cls.call_args.kwargs if agent_cls.called else {}+ return success, error, requested, kwargs+++def _job(**pin):+ return {"id": "pin-job", "name": "pin job", "prompt": "hi", "model": None, "provider": None,+ "base_url": None, **pin}+++PINS = [+ pytest.param({"provider": "anthropic", "model": "claude-sonnet-5"}, id="provider+model"),+ pytest.param({"model": "claude-sonnet-5"}, id="model-only"),+ pytest.param({"provider": "anthropic"}, id="provider-only"),+ pytest.param({"provider": "custom", "base_url": "http://127.0.0.1:8080/v1", "model": "local"},+ id="endpoint"),+]++[email protected]("pin", PINS)+def test_pinned_job_primary_auth_failure_does_not_land_on_the_global_chain(tmp_path, pin):+ success, error, requested, agent_kwargs = _run(+ tmp_path, _job(**pin), primary_error=AuthError("No credentials stored"))+ assert success is False+ assert "No credentials stored" in (error or "")+ assert "openrouter" not in requested+ assert agent_kwargs == {} # the job failed; nothing ran on a substituted route+++def test_pinned_job_dns_blip_does_not_land_on_the_global_chain(tmp_path):+ import httpx++ success, _error, requested, agent_kwargs = _run(+ tmp_path, _job(provider="xai-oauth", model="grok-4.5"),+ primary_error=httpx.ConnectError("[Errno 8] nodename nor servname provided, or not known"))+ assert success is False+ assert set(requested) == {"xai-oauth"} # preflight probe + real resolve; no chain entry+ assert agent_kwargs == {}++[email protected]("pin", PINS)+def test_resolve_job_runtime_does_not_walk_the_chain_for_a_pinned_job(pin):+ """The resolver itself, below preflight (which can be off: ``cron.preflight: false``)."""+ jc = _CronJobConfig(cfg={"fallback_providers": list(_CHAIN)}, model=pin.get("model") or "gpt-5.6-sol",+ model_cfg={}, cron_default_provider="")+ resolve = MagicMock(side_effect=AuthError("No credentials stored"))+ with patch("hermes_cli.runtime_provider.resolve_runtime_provider", resolve):+ with pytest.raises(RuntimeError, match="No credentials stored"):+ _resolve_job_runtime(_job(**pin), "pin-job", jc)+ assert resolve.call_count == 1+++def test_resolve_job_runtime_walks_the_chain_for_an_unpinned_job():+ jc = _CronJobConfig(cfg={"fallback_providers": list(_CHAIN)}, model="gpt-5.6-sol",+ model_cfg={}, cron_default_provider="")++ def resolve(**kwargs):+ if kwargs.get("requested") == "openrouter":+ return _runtime("openrouter")+ raise AuthError("No credentials stored")++ with patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=resolve):+ runtime, model = _resolve_job_runtime(_job(), "free-job", jc)+ assert (runtime["provider"], model) == ("openrouter", "z-ai/glm-5.2")++[email protected]("pin", PINS)+def test_pinned_job_agent_gets_no_runtime_fallback_ladder(tmp_path, pin):+ success, error, _requested, agent_kwargs = _run(tmp_path, _job(**pin))+ assert (success, error) == (True, None)+ assert agent_kwargs["fallback_model"] is None+++def test_unpinned_job_still_walks_the_global_chain_at_resolve_time(tmp_path):+ success, error, requested, agent_kwargs = _run(+ tmp_path, _job(), primary_error=AuthError("No Codex credentials stored"))+ assert (success, error) == (True, None)+ assert requested == [None, "openrouter"]+ assert (agent_kwargs["provider"], agent_kwargs["model"]) == ("openrouter", "z-ai/glm-5.2")+++def test_unpinned_job_agent_inherits_the_global_chain_mid_run(tmp_path):+ success, error, _requested, agent_kwargs = _run(tmp_path, _job())+ assert (success, error) == (True, None)+ assert agent_kwargs["fallback_model"] == _CHAIN+++def test_legacy_snapshot_keys_are_not_a_pin(tmp_path):+ """Records written before jobs followed the main model carry *_snapshot keys; they follow the+ main model now, so they keep the chain too."""+ job = _job(provider_snapshot="openai-codex", model_snapshot="gpt-5.6-sol")+ success, error, _requested, agent_kwargs = _run(tmp_path, job)+ assert (success, error) == (True, None)+ assert agent_kwargs["fallback_model"] == _CHAIN+++def test_pinned_job_same_provider_credential_pool_still_loads(tmp_path):+ """Credential-pool rotation stays on the pinned provider; it is not the fallback chain."""+ pool = MagicMock()+ pool.has_credentials.return_value = True+ with patch("agent.credential_pool.load_pool", return_value=pool) as load_pool:+ success, error, _requested, agent_kwargs = _run(+ tmp_path, _job(provider="anthropic", model="claude-sonnet-5"))+ assert (success, error) == (True, None)+ load_pool.assert_called_once_with("anthropic")+ assert agent_kwargs["credential_pool"] is pool+ assert agent_kwargs["fallback_model"] is None+++def test_pinned_job_failure_notice_does_not_promise_a_backup(monkeypatch):+ monkeypatch.setattr(scheduler, "load_config", lambda: {"fallback_providers": list(_CHAIN)})+ phrase = scheduler._fallback_chain_phrase(_job(provider="anthropic", model="claude-sonnet-5"))+ assert "pinned" in phrase and "--unpin" in phrase+ assert "succeeded" not in phrase+ assert scheduler._fallback_chain_phrase(_job()) == "No backup provider succeeded either."diff --git a/tests/cron/test_preflight_config.py b/tests/cron/test_preflight_config.pyindex 9aafdb7d74e..5d6bd3f668b 100644--- a/tests/cron/test_preflight_config.py+++ b/tests/cron/test_preflight_config.py@@ -189,6 +189,36 @@ class TestMissingProviderKeyBlocks:assert success is Trueassert error is None+ def test_global_chain_does_not_rescue_a_pinned_job(self, tmp_path):+ """A pinned job never walks the global chain (#100437), so the chain must not skip the+ missing-key check for it either: block before the agent is built."""+ (tmp_path / "config.yaml").write_text(+ "fallback_providers:\n"+ " - provider: openrouter\n"+ " model: z-ai/glm-5.2\n",+ encoding="utf-8",+ )+ calls = []++ def resolve(**kwargs):+ calls.append(kwargs.get("requested"))+ if kwargs.get("requested") == "anthropic":+ from hermes_cli.auth import AuthError++ raise AuthError("no key")+ return {**_RUNTIME, "provider": kwargs.get("requested")}++ job = _job(provider="anthropic", model="claude-sonnet-5")+ with cron_jobs.use_cron_store(tmp_path):+ cron_jobs.save_jobs([job])+ success, output, final_response, error, agent_constructed = \+ _run_job_patched(job, tmp_path, resolve=resolve)++ assert agent_constructed is False+ assert success is False+ assert "provider credential missing" in (error or "")+ assert "openrouter" not in calls+class TestHealthyJobUnaffected:def test_healthy_job_runs_normally(self, tmp_path):diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.pyindex 8fa216b0989..56fefb0c786 100644--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@ -1083,7 +1083,9 @@ class TestRunJobConfigEnvVarExpansion:Regression for Daily Focus Kickoff 2026-08-11: xai-oauth token refreshraised httpx.ConnectError ([Errno 8] nodename nor servname provided)and the scheduler only tried fallbacks on AuthError, so the job died- before XAI_API_KEY / Anthropic could rescue it.+ before XAI_API_KEY / Anthropic could rescue it. The job follows the+ main model (unpinned): a pinned job never walks the global chain+ (#100437, tests/cron/test_cron_pinned_job_fallback.py)."""import httpx@@ -1102,8 +1104,6 @@ class TestRunJobConfigEnvVarExpansion:"id": "dns-fallback","name": "dns fallback","prompt": "hi",- "provider": "xai-oauth",- "model": "grok-4.5",}fake_db = MagicMock()requested = []@@ -1135,14 +1135,15 @@ class TestRunJobConfigEnvVarExpansion:assert success is True, errorassert error is None- assert requested == ["xai-oauth", "xai"]+ assert requested == [None, "xai"]kwargs = mock_agent_cls.call_args.kwargsassert kwargs["provider"] == "xai"assert kwargs["model"] == "grok-4.5"def test_auth_fallback_switches_provider_and_model_together(self, tmp_path):- """Codex auth failure must produce OpenRouter+GLM, never OpenRouter+GPT."""+ """Codex auth failure must produce OpenRouter+GLM, never OpenRouter+GPT (unpinned job:+ a pinned one does not walk the global chain, #100437)."""from hermes_cli.auth import AuthError(tmp_path / "config.yaml").write_text(@@ -1159,15 +1160,13 @@ class TestRunJobConfigEnvVarExpansion:"id": "auth-fallback","name": "auth fallback","prompt": "hi",- "provider": "openai-codex",- "model": "gpt-5.6-sol",}fake_db = MagicMock()requested = []def resolve_runtime(**kwargs):requested.append(kwargs.get("requested"))- if kwargs.get("requested") == "openai-codex":+ if kwargs.get("requested") in (None, "openai-codex"):raise AuthError("No Codex credentials stored")assert kwargs["requested"] == "openrouter"assert kwargs["target_model"] == "z-ai/glm-5.2"@@ -1189,7 +1188,7 @@ class TestRunJobConfigEnvVarExpansion:assert success is Trueassert error is None- assert requested == ["openai-codex", "openrouter"]+ assert requested == [None, "openrouter"]kwargs = mock_agent_cls.call_args.kwargsassert kwargs["provider"] == "openrouter"assert kwargs["model"] == "z-ai/glm-5.2"diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.pyindex c4003d603d7..e7b9db5aa76 100644--- a/tools/delegate_tool_config.py+++ b/tools/delegate_tool_config.py@@ -6,7 +6,7 @@ import loggingimport osfrom typing import Any, Dict, List, Optionalfrom utils import base_url_hostname, is_truthy_value-from hermes_cli.fallback_config import get_fallback_chain+from hermes_cli.fallback_config import scoped_fallback_chainlogger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module@@ -471,18 +471,12 @@ def _resolve_child_fallback_chain(parent_agent, routing_cfg: Any, pinned: bool)Pinned children (provider, endpoint or model override) never borrow the parent chain;unpinned children inherit it when ``fallback_providers`` is absent/null. An explicit ``[]``disables fallback either way. Malformed entries are dropped by the canonical normalizer.+ Same rule as a pinned cron job (``cron/scheduler.py::_job_fallback_chain``)."""- default = None if pinned else (getattr(parent_agent, "_fallback_chain", None) or None)- declared = routing_cfg.get("fallback_providers") if isinstance(routing_cfg, dict) else None- if declared is None:- return default- if declared == []:- return None- normalized = get_fallback_chain({"fallback_providers": declared})- if not normalized:- logger.warning("delegation fallback_providers has no usable routes; using the %s default",- "pinned" if pinned else "inherited")- return normalized or default+ return scoped_fallback_chain(+ getattr(parent_agent, "_fallback_chain", None),+ routing_cfg.get("fallback_providers") if isinstance(routing_cfg, dict) else None,+ pinned=pinned, owner="delegation")def _resolve_child_runtime(diff --git a/website/docs/developer-guide/cron-internals.md b/website/docs/developer-guide/cron-internals.mdindex 15c8bd5f0ee..d0ddd4175ef 100644--- a/website/docs/developer-guide/cron-internals.md+++ b/website/docs/developer-guide/cron-internals.md@@ -322,7 +322,7 @@ Windows continues to use `taskkill /F /T`.`run_job()` passes the user's configured fallback providers and credential pool into the `AIAgent` instance:-- **Fallback providers** — reads `fallback_providers` (list) or `fallback_model` (legacy dict) from `config.yaml`, matching the gateway's `_load_fallback_model()` pattern. Passed as `fallback_model=` to `AIAgent.__init__`, which normalizes both formats into a fallback chain.+- **Fallback providers** — reads `fallback_providers` (list) or `fallback_model` (legacy dict) from `config.yaml`, matching the gateway's `_load_fallback_model()` pattern. Passed as `fallback_model=` to `AIAgent.__init__`, which normalizes both formats into a fallback chain. **Unpinned jobs only:** `_job_fallback_chain()` returns no chain for a job carrying its own `provider`, `model` or `base_url`, and the same answer feeds the credential-resolution walk in `_resolve_job_runtime()`, the pre-dispatch key check, and the mid-run ladder, so a pinned job never lands on a global chain entry (#100437). It shares `hermes_cli.fallback_config.scoped_fallback_chain()` with pinned delegation children.- **Credential pool** — loads via `load_pool(provider)` from `agent.credential_pool` using the resolved runtime provider name. Only passed when the pool has credentials (`pool.has_credentials()`). Enables same-provider key rotation on 429/rate-limit errors.This mirrors the gateway's behavior — without it, cron agents would fail on rate limits without attempting recovery.diff --git a/website/docs/developer-guide/provider-runtime.md b/website/docs/developer-guide/provider-runtime.mdindex 7f12e7ddb3d..cae44ae79dd 100644--- a/website/docs/developer-guide/provider-runtime.md+++ b/website/docs/developer-guide/provider-runtime.md@@ -213,7 +213,7 @@ Hermes supports a configured fallback provider chain — a list of `(provider, m- **Subagent delegation** (`tools/delegate_tool.py`): subagents inherit the parent's provider but not the fallback config- **Auxiliary tasks**: use their own independent provider auto-detection chain (see Auxiliary model routing above)-Cron jobs **do** support fallback: `run_job()` reads `fallback_providers` (or legacy `fallback_model`) from `config.yaml` and passes it to `AIAgent(fallback_model=...)`, matching the gateway's `_load_fallback_model()` pattern. See [Cron Internals](./cron-internals.md).+Unpinned cron jobs **do** support fallback: `run_job()` reads `fallback_providers` (or legacy `fallback_model`) from `config.yaml` and passes it to `AIAgent(fallback_model=...)`, matching the gateway's `_load_fallback_model()` pattern. A job with its own `provider` / `model` / `base_url` gets no chain, the same rule as a pinned delegation child. See [Cron Internals](./cron-internals.md).### Test coveragediff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex c419c6db59b..1aaf1da3de3 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -79,8 +79,10 @@ Hermes will use the unified `cronjob_manage` tool internally.Before constructing any agent machinery for a scheduled run, the schedulervalidates that the job's configuration can actually produce a successful run:-- the provider API key resolves (skipped when a `fallback_providers` chain is- configured, since the fallback path may rescue a missing primary key),+- the provider API key resolves (skipped for an unpinned job when a+ `fallback_providers` chain is configured, since the fallback path may rescue a+ missing primary key; a pinned job does not use that chain, so it is always+ checked),- attached skills are ready (no missing required environment variables,commands, or credential files),- delivery platform targets are known and have gateway credentials configured@@ -1007,12 +1009,16 @@ From the CLI: `hermes cron create "every 6h" "Scan for news" --continuity`, and## Provider recovery-Cron jobs inherit your configured fallback providers and credential pool rotation. If the primary API key is rate-limited or the provider returns an error, the cron agent can:+If the primary API key is rate-limited or the provider returns an error, the cron agent can:-- **Fall back to an alternate provider** if you have `fallback_providers` (or the legacy `fallback_model`) configured in `config.yaml`-- **Rotate to the next credential** in your [credential pool](../configuration.md#credential-pool-strategies) for the same provider+- **Rotate to the next credential** in your [credential pool](../configuration.md#credential-pool-strategies) for the same provider. This applies to every job, pinned or not.+- **Fall back to an alternate provider** from `fallback_providers` (or the legacy `fallback_model`) in `config.yaml` — **unpinned jobs only**. That covers a failure while resolving credentials before the run starts and a provider error mid-run.-This means cron jobs that run at high frequency or during peak hours are more resilient — a single rate-limited key won't fail the entire run.+A job with its own `provider`, `model` or `base_url` (set with `--provider` / `--model`, `--pin`, the dashboard, or `jobs.json`) never falls back to the global chain. The pin says which route the job runs on, and a fallback entry is a different provider and usually a different model, so when the pinned route fails the run fails and the failure alert says so. This is the same rule [subagent delegation](./delegation.md) applies to a pinned child. To keep fallback for a job, leave it unpinned: it follows `cron.model` / `cron.model_provider` (or the main model) and walks the chain like any other unpinned job.++Before this rule, a pinned job whose provider failed could run on the first working `fallback_providers` entry instead, with a one-line notice in its output. If you relied on that, unpin the job (`hermes cron edit <job_id> --unpin`) and set the model through `cron.model` instead.++A single rate-limited key therefore does not fail a run that has another credential for the same provider, and unpinned jobs still survive a provider outage when a chain is configured.## Run failures (`last_error`)diff --git a/website/docs/user-guide/features/fallback-providers.md b/website/docs/user-guide/features/fallback-providers.mdindex 6c47a6f2d0b..489f6a86beb 100644--- a/website/docs/user-guide/features/fallback-providers.md+++ b/website/docs/user-guide/features/fallback-providers.md@@ -201,7 +201,7 @@ fallback_providers:| Messaging gateway (Telegram, Discord, etc.) | ✔ || Desktop app / TUI chats | ✔ (a chain added or edited while a chat is open applies from its next turn) || Subagent delegation | ✔ (`delegation.fallback_providers` when set; otherwise only unpinned children inherit the parent chain; `[]` disables) |-| Cron jobs | ✔ (cron agents inherit configured fallback providers) |+| Cron jobs | ✔ (unpinned jobs inherit the configured chain; a job with its own provider/model/base_url never falls back to it) || Auxiliary tasks on `provider: auto` | ✔ (try per-task fallback, then the main fallback chain before built-in aux discovery) |:::tip@@ -427,7 +427,7 @@ See [Subagent Delegation](./delegation.md) for full configuration details.## Cron Job Providers-Cron jobs inherit your configured `fallback_providers` chain (or legacy `fallback_model`) when they create an agent. To use a different primary provider for a cron job, configure `provider` and `model` overrides on the cron job itself:+Unpinned cron jobs inherit your configured `fallback_providers` chain (or legacy `fallback_model`), both when the primary's credentials fail to resolve before the run and when the provider errors mid-run. A job pinned to its own provider, model or endpoint does **not**: if that route fails, the run fails (same-provider [credential pool](../configuration.md#credential-pool-strategies) rotation still applies). This matches how a pinned [delegation](./delegation.md) child behaves. Pin a cron job with `provider` and `model` overrides on the job itself:```pythoncronjob(@@ -439,7 +439,7 @@ cronjob()```-See [Scheduled Tasks (Cron)](./cron.md) for full configuration details.+To keep fallback for a job, leave it unpinned and choose its model with `cron.model` / `cron.model_provider` instead. See [Scheduled Tasks (Cron)](./cron.md#provider-recovery) for details.---@@ -458,4 +458,4 @@ See [Scheduled Tasks (Cron)](./cron.md) for full configuration details.| Title generation | Layered (see above) | `auxiliary.title_generation` || Triage specifier | Layered (see above) | `auxiliary.triage_specifier` || Delegation | Uses `delegation.fallback_providers` when declared; otherwise only unpinned children inherit the parent chain | `delegation.provider` / `delegation.model` / `delegation.fallback_providers` |-| Cron jobs | Inherit the configured `fallback_providers` chain; optional per-job provider override | Per-job `provider` / `model` |+| Cron jobs | Unpinned jobs inherit the configured `fallback_providers` chain; a job with its own `provider` / `model` / `base_url` never falls back to it | Per-job `provider` / `model`, or `cron.model` / `cron.model_provider` |