The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(delegation): an unusable backend fails closed, an unroutable task is refused alone
Teknium2463bdcbbaf4
diff --git a/agent/delegation_provider.py b/agent/delegation_provider.pyindex 98bf3527321..0cc01bafadf 100644--- a/agent/delegation_provider.py+++ b/agent/delegation_provider.py@@ -74,7 +74,8 @@ class DelegationProvider(ProviderBase):return own if isinstance(own, Mapping) else {}def is_available(self) -> bool:- """Whether this provider can run here. MUST NOT make network calls; False -> ``default``."""+ """Whether this provider can run here. MUST NOT make network calls. False fails delegation closed: a+ ``delegate_task`` call under this backend is a tool error naming it, never a run on another route."""return Truedef task_parameters(self, config: Mapping[str, Any]) -> dict[str, dict[str, Any]]:diff --git a/agent/delegation_registry.py b/agent/delegation_registry.pyindex 76dd071a9bd..92f735395df 100644--- a/agent/delegation_registry.py+++ b/agent/delegation_registry.py@@ -2,12 +2,13 @@Populated by plugins via :meth:`PluginContext.register_delegation_provider`; ``delegate_task``asks :func:`get_active_provider` which strategy turns each task into a child run. Selection is-``delegation.backend`` in config.yaml. Unset (or ``default``) is the built-in strategy, today's-behaviour: every child follows the ``delegation`` section (``delegation.provider`` /-``delegation.model`` / ``delegation.base_url`` ..., else the parent's route). A configured backend-that is not registered or reports unavailable falls back to ``default`` with one warning, so a-disabled plugin never takes delegation down; its schema parameters are absent too, since the-schema is built from the same resolution.+``delegation.backend`` in config.yaml.+Unset (or ``default``) is the built-in strategy, today's behaviour: every child follows the+``delegation`` section (``delegation.provider`` / ``delegation.model`` / ``delegation.base_url`` ...,+else the parent's route). A configured backend that is not registered or reports unavailable fails+closed: ``delegate_task`` returns a tool error naming the backend and the fix, and never quietly runs+the children on another route. Its schema parameters are absent, since the schema is built from the+same resolution."""from __future__ import annotations@@ -15,7 +16,7 @@ from __future__ import annotationsimport loggingfrom typing import Any, Mapping, Optional-from agent.delegation_provider import DelegationProvider+from agent.delegation_provider import DelegationProvider, DelegationRouteErrorfrom agent.provider_registry import ProviderRegistry, is_available_safe, lower_keylogger = logging.getLogger(__name__)@@ -46,7 +47,6 @@ _registry: ProviderRegistry[DelegationProvider] = ProviderRegistry(_registry.export(globals())_BUILTIN_DEFAULT = DefaultDelegationProvider()-_warned_fallbacks: set[str] = set()def configured_backend(config: Mapping[str, Any]) -> str:@@ -55,21 +55,29 @@ def configured_backend(config: Mapping[str, Any]) -> str:return lower_key(raw) if isinstance(raw, str) and raw.strip() else DEFAULT_BACKEND-def get_active_provider(config: Mapping[str, Any]) -> DelegationProvider:- """The provider ``config`` (the ``delegation`` section) selects; ``default`` when unset,- unregistered or unavailable."""- name = configured_backend(config)+def backend_status(name: str) -> tuple[Optional[DelegationProvider], str]:+ """``(provider, "")`` when backend ``name`` can run here, else ``(provider or None, reason)``; the reason is+ the user-facing fix (it becomes the ``delegate_task`` tool error)."""if name == DEFAULT_BACKEND:- return _BUILTIN_DEFAULT+ return _BUILTIN_DEFAULT, ""provider: Optional[DelegationProvider] = _registry.get_provider(name)- if provider is not None and is_available_safe(- provider, logger, "delegation provider %s.is_available() raised %s"):- return provider- if name not in _warned_fallbacks:- _warned_fallbacks.add(name)- logger.warning(- "delegation.backend '%s' is %s; subagents use the default strategy. Install/enable the "- "plugin that provides it (`hermes plugins list`).", name,- "not registered" if provider is None else "unavailable",- )- return _BUILTIN_DEFAULT+ if provider is None:+ return None, (+ f"Delegation backend '{name}' is not installed: no enabled plugin provides it. Install or enable the "+ f"plugin that does (`hermes plugins list`), or switch back to the default backend "+ f"(`hermes config set delegation.backend default`).")+ if not is_available_safe(provider, logger, "delegation provider %s.is_available() raised %s"):+ return provider, (+ f"Delegation backend '{name}' is unavailable here (its plugin reports it cannot run). Fix its setup, or "+ f"switch back to the default backend: `/delegation default` for this session, or "+ f"`hermes config set delegation.backend default`.")+ return provider, ""+++def get_active_provider(config: Mapping[str, Any]) -> DelegationProvider:+ """The provider ``config`` (the ``delegation`` section) selects; ``default`` when unset. Raises+ :class:`DelegationRouteError` naming the backend and the fix when it is not registered or unavailable."""+ provider, reason = backend_status(configured_backend(config))+ if reason or provider is None:+ raise DelegationRouteError(f"{reason} No subagent was started.")+ return providerdiff --git a/tests/hermes_cli/test_plugin_host_delegation.py b/tests/hermes_cli/test_plugin_host_delegation.pyindex 89e5c55875f..40208cb693c 100644--- a/tests/hermes_cli/test_plugin_host_delegation.py+++ b/tests/hermes_cli/test_plugin_host_delegation.py@@ -66,8 +66,8 @@ def test_hosted_delegation_provider_extends_schema_and_routes_from_the_host(tmp_routes, err = resolve_task_routes([{"goal": "route me through the host", "option": "a"}], config, None)assert err is Noneassert (routes[0].creds["model"], routes[0].label) == (f"model-a-{host_pid}", "a")- _, err = resolve_task_routes([{"goal": "refused by the hosted plugin", "option": "b"}], config, None)- assert "b is closed" in err+ refused, err = resolve_task_routes([{"goal": "refused by the hosted plugin", "option": "b"}], config, None)+ assert err is None and "b is closed" in refused[0].errorassert json.dumps(params) == json.dumps(schema_extension(config)[0])finally:manager.unload()diff --git a/tests/tools/test_delegation_backends.py b/tests/tools/test_delegation_backends.pyindex 74a3e49f020..d58bd7f95f4 100644--- a/tests/tools/test_delegation_backends.py+++ b/tests/tools/test_delegation_backends.py@@ -35,7 +35,8 @@ class Options(DelegationProvider):for o in self.settings(config).get("options") or []:if o["name"] == task.get("option"):return {"base_url": o["base_url"], "api_key": "k-" + o["name"], "model": o["model"],- "reasoning_effort": o.get("reasoning_effort"), "label": o["name"]}+ "reasoning_effort": o.get("reasoning_effort"), "label": o["name"],+ "fallback_providers": o.get("fallback_providers")}return dict(config)def register(ctx):@@ -93,8 +94,8 @@ def recorded(monkeypatch):return built-def _parent():- return types.SimpleNamespace(session_id="root", model="parent-model", provider="openrouter",+def _parent(session_id="root"):+ return types.SimpleNamespace(session_id=session_id, model="parent-model", provider="openrouter",tool_progress_callback=None, _delegate_spinner=None, request_overrides={},_safe_print=lambda line: None)@@ -131,36 +132,73 @@ def test_selected_plugin_backend_extends_schema_and_routes_each_task(tmp_path, mmanager.unload()-def test_model_supplied_parameters_are_enforced_before_any_child_is_built(tmp_path, monkeypatch, recorded):+def test_an_unroutable_task_is_refused_alone_and_its_siblings_run(tmp_path, monkeypatch, recorded):+ """Fail closed per task: a bad parameter or a backend refusal refuses that task only, its result entry says why+ and which backend refused it; the call is a tool error only when no task can run."""_, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options", "backends": {"probe-options": {"options": OPTIONS}}})try:from tools.delegate_tool import delegate_task- bad = json.loads(delegate_task(tasks=[{"goal": "a task with a typo in it", "option": "fsat"}],+ out = json.loads(delegate_task(tasks=[+ {"goal": "a task with a typo in it", "option": "fsat"},+ {"goal": "summarize the quick thing", "option": "fast"},+ {"goal": "a task the backend refuses", "option": "refused"},+ ], parent_agent=_parent()))+ typo, fast, refused = out["results"]+ assert [r["task_index"] for r in out["results"]] == [0, 1, 2]+ assert typo["status"] == "error" and "must be one of fast, deep, refused" in typo["error"]+ assert refused["status"] == "error" and "reserved for humans" in refused["error"]+ assert typo["route"] == {"backend": "probe-options", "refused": True}+ assert fast["status"] == "completed" and [b["model"] for b in recorded] == ["fast-model"]++ bad = json.loads(delegate_task(tasks=[{"goal": "only a refused task", "option": "refused"}],parent_agent=_parent()))- assert "must be one of fast, deep, refused" in bad["error"] and not recorded- refused = json.loads(delegate_task(tasks=[{"goal": "a task the backend refuses", "option": "refused"}],- parent_agent=_parent()))- assert "reserved for humans" in refused["error"] and not recorded+ assert "reserved for humans" in bad["error"] and len(recorded) == 1finally:manager.unload()-def test_default_and_unavailable_backends_keep_todays_schema_and_route(tmp_path, monkeypatch, recorded):- """Unset, ``default`` and a backend nobody registered all mean today's behaviour."""+def test_a_missing_backend_fails_closed_and_default_keeps_todays_route(tmp_path, monkeypatch, recorded):+ """Unset and ``default`` are today's behaviour; a backend nobody provides is a tool error naming it and the fix,+ never a quiet run on the default route."""from tools.delegate_tool import delegate_task- definitions = []+ pinned = {"model": "pinned-model", "base_url": "http://127.0.0.1:9/v1", "api_key": "k"}+ definitions, outcomes = [], []for delegation in ({}, {"backend": "default"}, {"backend": "not-installed"}):- delegation = {**delegation, "model": "pinned-model", "base_url": "http://127.0.0.1:9/v1", "api_key": "k"}- _, manager = _home(tmp_path / str(len(definitions)), monkeypatch, delegation, plugins=())+ _, manager = _home(tmp_path / str(len(definitions)), monkeypatch, {**delegation, **pinned}, plugins=())try:definitions.append(json.dumps(_definition()))- delegate_task(tasks=[{"goal": "one plain delegated task"}], parent_agent=_parent())+ outcomes.append(json.loads(delegate_task(tasks=[{"goal": "one plain delegated task"}],+ parent_agent=_parent())))finally:manager.unload()assert len(set(definitions)) == 1 and '"option"' not in definitions[0]- assert [(b["model"], b["override_base_url"]) for b in recorded] == [("pinned-model", "http://127.0.0.1:9/v1")] * 3+ assert [(b["model"], b["override_base_url"]) for b in recorded] == [("pinned-model", "http://127.0.0.1:9/v1")] * 2+ error = outcomes[2]["error"]+ assert "'not-installed' is not installed" in error and "hermes config set delegation.backend default" in error+++def test_a_backend_route_without_its_own_chain_inherits_delegation_fallback_providers(tmp_path, monkeypatch):+ from tools.delegate_tool_config import _resolve_child_fallback_chain+ from tools.delegate_tool_routes import resolve_task_routes++ chain = [{"provider": "openrouter", "model": "backup-model"}]+ options = [{**OPTIONS[0]}, {**OPTIONS[1], "fallback_providers": []}]+ _, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options", "fallback_providers": chain,+ "backends": {"probe-options": {"options": options}}})+ try:+ from tools.delegate_tool_config import _load_config++ routes, err = resolve_task_routes([{"goal": "inherits", "option": "fast"}, {"goal": "own empty chain",+ "option": "deep"}],+ _load_config(), _parent())+ assert err is None+ inherited, disabled = (_resolve_child_fallback_chain(_parent(), r.routing_cfg, pinned=True) for r in routes)+ assert [(e["provider"], e["model"]) for e in inherited] == [("openrouter", "backup-model")]+ assert disabled is None+ finally:+ manager.unload()def test_plugin_parameters_never_redefine_core_or_route_fields(tmp_path, monkeypatch):diff --git a/tests/tools/test_delegation_profile_route.py b/tests/tools/test_delegation_profile_route.pyindex b3278dddc26..025172f2e20 100644--- a/tests/tools/test_delegation_profile_route.py+++ b/tests/tools/test_delegation_profile_route.py@@ -287,8 +287,8 @@ def test_profile_route_is_refused_under_a_managed_worker_config_snapshot(two_promonkeypatch.setattr(safe_worker_policy, "_policy", safe_worker_policy._SafeWorkerPolicy(os.getpid(), False, False, json.dumps(frozen)))- routes, error = _resolve_coder_task()- assert routes == [] and "managed worker" in (error or "")+ (route,), error = _resolve_coder_task()+ assert error is None and "managed worker" in (route.error or "")with pytest.raises(DelegationRouteError):_route_to_task_route({"profile": "coder"}, _parent(), {})@@ -303,9 +303,9 @@ def test_profile_pinned_to_a_missing_acp_command_is_refused_at_routing(two_profimonkeypatch.setenv("HERMES_COPILOT_ACP_COMMAND", "hermes-test-missing-acp-binary")monkeypatch.setenv("COPILOT_ACP_BASE_URL", "acp+tcp://127.0.0.1:9")- routes, error = _resolve_coder_task()- assert routes == []- assert "hermes-test-missing-acp-binary" in (error or "") and "coder" in error+ (route,), error = _resolve_coder_task()+ assert error is None and route.creds == {}+ assert "hermes-test-missing-acp-binary" in (route.error or "") and "coder" in route.errordef test_one_profile_under_two_labels_resolves_once_and_keeps_each_label(two_profiles):diff --git a/tests/tools/test_delegation_route_fields.py b/tests/tools/test_delegation_route_fields.pyindex 69ce37982a8..112678ea3c3 100644--- a/tests/tools/test_delegation_route_fields.py+++ b/tests/tools/test_delegation_route_fields.py@@ -1,5 +1,5 @@"""Route fields a delegation backend returns: ``service_tier`` is checked like ``/fast`` and survives child-construction, an unknown ``reasoning_effort`` is a tool error, and a labelled route's result reports what the+construction, an unknown ``reasoning_effort`` refuses that task, and a backend-routed result reports what thechild actually ran on. Real ``delegate_task``, real credential resolution and tier gates; only the child'sconstruction and run are stubbed where a test reads what they were handed.@@ -62,7 +62,8 @@ def _spawn(routes, *, cfg=None, parent=None, construct=_construct, provider=Nonepatch("tools.delegate_tool_routes._active_provider", return_value=provider or _Backend(routes)),patch("run_agent.AIAgent", side_effect=construct) as agent,patch("tools.delegate_tool._run_batch",- side_effect=lambda batch, background: batches.append(batch) or '{"status": "built"}'),+ side_effect=lambda batch, background: batches.append(batch) or json.dumps(+ {"status": "built", **({"refused": batch.refused} if batch.refused else {})})),):from tools.delegate_tool import delegate_taskresult = json.loads(delegate_task(tasks=[{"goal": f"task number {i}"} for i in range(len(routes))],@@ -83,9 +84,10 @@ def test_route_tier_reaches_the_child_and_its_sibling_keeps_the_default():({**CODEX, "service_tier": "turbo"}, "turbo"),({**CODEX, "service_tier": "auto"}, "auto"), # bounded windows are per user turn, meaningless for a child])-def test_a_tier_the_route_does_not_offer_fails_before_any_child_is_built(route, needle):+def test_a_tier_the_route_does_not_offer_refuses_that_task_and_its_sibling_runs(route, needle):result, built, _ = _spawn([route, None])- assert needle in result["error"] and built == []+ (refused,) = result["refused"]+ assert refused["task_index"] == 0 and needle in refused["error"] and len(built) == 1@pytest.mark.parametrize("account_offers, expected", [(False, None), (True, "ultrafast"), (None, "ultrafast")])@@ -136,9 +138,10 @@ def test_default_backend_never_reads_a_tier_from_the_delegation_section():assert child.get("service_tier") is None and "service_tier" not in child["request_overrides"]-def test_unknown_route_reasoning_effort_is_a_tool_error_not_the_parents_level():+def test_unknown_route_reasoning_effort_refuses_the_task_never_the_parents_level():result, built, _ = _spawn([{**LOCAL, "reasoning_effort": "hgih"}, None])- assert "hgih" in result["error"] and "xhigh" in result["error"] and built == []+ (refused,) = result["refused"]+ assert "hgih" in refused["error"] and "xhigh" in refused["error"] and len(built) == 1def test_the_delegation_sections_own_effort_keeps_its_warn_and_inherit_rule():@@ -154,19 +157,25 @@ def test_labelled_route_result_reports_what_the_child_ran_on():{**LOCAL, "reasoning_effort": "none", "label": "local"}])entry = _build_result_entry(deep, {"final_response": "ok", "completed": True}, 0, 1.0,_SchemaOutcome(None, None, [], 0))- assert entry["route"] == {"label": "deep", "provider": "openai-codex", "model": "gpt-6-astra",- "reasoning_effort": "high", "service_tier": "fast"}+ assert entry["route"] == {"backend": "route-fields", "label": "deep", "provider": "openai-codex",+ "model": "gpt-6-astra", "reasoning_effort": "high", "service_tier": "fast"}assert _fabricated_entry(1, "error", "boom", local)["route"] == {- "label": "local", "provider": "custom", "model": "qwen3-local", "reasoning_effort": "none",- "service_tier": "normal"}+ "backend": "route-fields", "label": "local", "provider": "custom", "model": "qwen3-local",+ "reasoning_effort": "none", "service_tier": "normal"}-def test_unlabelled_route_result_keeps_its_shape():- """The report sits next to a route's label; a route without one (the default strategy, a backend's fallback- to the delegation section) leaves the result entry exactly as before."""+def test_every_backend_routed_result_names_its_backend_and_the_default_keeps_its_shape():+ """An unlabelled backend route still reports its backend and what ran; the default backend's children leave the+ result entry exactly as before."""+ from agent.delegation_registry import get_active_providerfrom tools.delegate_tool_child_run import _SchemaOutcome, _build_result_entry- _, _, (child,) = _spawn([{**LOCAL, "reasoning_effort": "high"}])- entry = _build_result_entry(child, {"final_response": "ok", "completed": True}, 0, 1.0,- _SchemaOutcome(None, None, [], 0))- assert "route" not in entry+ def entry_of(child):+ return _build_result_entry(child, {"final_response": "ok", "completed": True}, 0, 1.0,+ _SchemaOutcome(None, None, [], 0))++ _, _, (routed,) = _spawn([{**LOCAL, "reasoning_effort": "high"}])+ assert entry_of(routed)["route"] == {"backend": "route-fields", "provider": "custom", "model": "qwen3-local",+ "reasoning_effort": "high", "service_tier": "normal"}+ _, _, (plain,) = _spawn([None], cfg=LOCAL, provider=get_active_provider({}))+ assert "route" not in entry_of(plain)diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex 8739280e3ba..e75e3d81a3c 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -142,7 +142,8 @@ delegation provider (`agent/delegation_provider.py`, `ctx.register_delegation_pr`delegation.backends.<name>`) that answers each task's route (`tools/delegate_tool_routes.py`: model/provider fieldsresolved like the `delegation` section, `service_tier` checked like `/fast` in `delegate_tool_tuning.py`, or `profile` →the child is built, leases and converses inside that profile's scope) and may add enum-checked per-task schema params; it-never owns lifecycle. Internal `credentials_cfg` callers (/review) and the lifecycle API bypass it. **Child processes:** a child's background+never owns lifecycle. Fails closed: an unusable backend is a tool error naming it (never a silent `default`), an+unroutable task is refused alone (`TaskRoute.error`). Internal `credentials_cfg` callers (/review) and the lifecycle API bypass it. **Child processes:** a child's backgroundprocesses are killed at its teardown and their notices are suppressed in the parent; `process_manage(action="handoff")`(children only) flips `ProcessSession.owner_task_id` to the parent under the registry lock(`process_registry.transfer_ownership`) so the completion routes and reaps by the new owner; un-handed leftovers land ondiff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 55e2338e33f..6750519935b 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -458,6 +458,8 @@ def _build_children(children = []for i, t in enumerate(task_list):route = routes[i]+ if route.error:+ continue # refused by its backend: no child; its result entry is the refusal_task_schema = task_schemas[i] if i < len(task_schemas) else None_child_context = t.get("context")if _task_schema is not None:@@ -490,8 +492,8 @@ def _build_children(if _writer is not None:child.tool_progress_callback = wrap_progress_callback(getattr(child, "tool_progress_callback", None), _writer)child._live_transcript_path = str(_writer.path)- if route.label:- child._delegate_route = {"label": route.label}+ if route.report() is not None:+ child._delegate_route = route.report()if live_deleg_id:child._delegation_id = live_deleg_id_ident_ref = getattr(child, "_progress_identity_ref", None)@@ -599,10 +601,16 @@ def delegate_task(routes, err = _routes_for(task_list, cfg, credentials_cfg, parent_agent)if err:return tool_error(err)+ # Fail closed per task: a task its backend cannot route is refused alone (its entry carries the error); the call+ # is a tool error only when no task can run.+ runnable = [r for r in routes if not r.error]+ if not runnable:+ return tool_error(" ".join(dict.fromkeys(r.error for r in routes)))+ refused = [r.refused_entry(i) for i, r in enumerate(routes) if r.error]# Batch-level model/provider labels (transcript headers, completion block): blank when tasks took different# routes, so each child reports what it actually runs on.- creds = routes[0].creds if all(r.creds == routes[0].creds for r in routes) else dict.fromkeys(routes[0].creds)- err = _oneshot_spawn_budget(parent_agent, len(task_list))+ creds = runnable[0].creds if all(r.creds == runnable[0].creds for r in runnable) else dict.fromkeys(runnable[0].creds)+ err = _oneshot_spawn_budget(parent_agent, len(runnable))if err:return tool_error(err)@@ -626,6 +634,11 @@ def delegate_task(task_list, context, model=creds.get("model"), provider=creds.get("provider"),home=_live_home,)+ for entry in refused: # done before anything runs: their transcripts end with the refusal+ _writer = live_writers[entry["task_index"]] if entry["task_index"] < len(live_writers) else None+ if _writer is not None:+ with _quiet("Live transcript finalize failed", exc_info=True):+ _writer.finalize(entry)_announce_batch(parent_agent, len(task_list), live_deleg_id)origin = _capture_origin()@@ -638,7 +651,7 @@ def delegate_task(batch = _Batch(task_list, children, parent_agent, creds, context, top_role, max_children,live_deleg_id, live_writers, live_paths, *origin, overall_start,- live_home=_live_home,+ live_home=_live_home, refused=refused,)return _run_batch(batch, background)diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex 25080ea7269..0bdc9d150e5 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -34,8 +34,9 @@ def _str_or_none(value: Any) -> Optional[str]:return value if isinstance(value, str) else Nonedef _route_report(child: Any) -> Optional[dict[str, Any]]:- """What a labelled route's child ran on: the backend's label plus the resolved provider, model, reasoning- effort (None = the provider's default) and speed tier, read off the built child. None for unlabelled routes."""+ """What a backend-routed child actually ran on: its backend and label plus the provider, model, reasoning effort+ (None = the provider's default) and speed tier read off the child when its result is assembled, so a fallback+ provider that took over shows (``fallback_activated``). None for the default backend's unlabelled route."""route = getattr(child, "_delegate_route", None)if not isinstance(route, dict):return None@@ -46,7 +47,8 @@ def _route_report(child: Any) -> Optional[dict[str, Any]]:effort = reasoning.get("effort") if reasoning.get("enabled", True) else "none"return {**route, "provider": _str_or_none(getattr(child, "provider", None)),"model": _str_or_none(getattr(child, "model", None)), "reasoning_effort": _str_or_none(effort),- "service_tier": service_tier_word(getattr(child, "service_tier", None))}+ "service_tier": service_tier_word(getattr(child, "service_tier", None)),+ **({"fallback_activated": True} if getattr(child, "_fallback_activated", False) is True else {})}def _fabricated_entry(idx: int, status: str, error: str, child: Any, duration: float = 0) -> dict[str, Any]:"""Result entry for a child that raised, never finished, or was abandoned."""diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.pyindex 74e81ace981..39662bfaeab 100644--- a/tools/delegate_tool_dispatch.py+++ b/tools/delegate_tool_dispatch.py@@ -10,7 +10,7 @@ import jsonimport loggingimport timefrom concurrent.futures import FIRST_COMPLETED, wait as _cf_wait-from dataclasses import dataclass, replace+from dataclasses import dataclass, field, replacefrom typing import Any, Dict, List, Optionalfrom hermes_cli.observability.shared_metrics_loop import begin_delegation_run, finish_delegation_unit@@ -50,6 +50,9 @@ class _Batch:group: Optional[str] = Noneunit_id: Optional[str] = None # the async registry id this unit runs under (``<call_id>-k`` for split calls)live_home: Any = None # explicit profile home for transcripts/manifest (#91996); None = ambient resolve+ # Result entries of tasks their backend refused (no child): joined into a sync result, listed in a background+ # call's dispatch payload. Units carved for async dispatch never carry them.+ refused: list = field(default_factory=list)def owner_kwargs(self) -> dict[str, Any]:"""Steer/stop authority of the originating session, passed to every child run."""@@ -203,6 +206,9 @@ def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = Truebatch.live_writers[_idx].finalize(entry)if _idx < len(batch.live_paths):entry["live_transcript"] = batch.live_paths[_idx]+ if batch.refused:+ results.extend(batch.refused)+ results.sort(key=lambda r: r["task_index"])update_manifest_statuses(batch.live_deleg_id, results, home=batch.live_home)finish_delegation_unit(batch.task_list, results, background=not honor_parent_interrupt)@@ -348,7 +354,7 @@ _BACKGROUND_NOTES = {def _dispatched_payload(batch: _Batch, units: list[tuple[_Batch, str]]) -> dict:"""Model-facing handle for an accepted background call: one entry per async unit."""goals = [t["goal"] for t in batch.task_list]- n = len(goals)+ n = len(batch.children) # running children; refused tasks are listed under "refused"payload = {"status": "dispatched", "mode": "background", "count": n,"delegation_id": batch.live_deleg_id or units[0][1], "goals": goals,@@ -363,6 +369,8 @@ def _dispatched_payload(batch: _Batch, units: list[tuple[_Batch, str]]) -> dict:if any(isinstance(s, str) and s for s in sids):payload["subagent_ids"] = sidspayload["control_hint"] = _BACKGROUND_NOTES["control_hint"]+ if batch.refused:+ payload["refused"] = batch.refusedif batch.live_paths:payload["live_transcripts"] = list(batch.live_paths)payload["live_transcripts_hint"] = _BACKGROUND_NOTES["live_transcripts_hint"]@@ -435,7 +443,7 @@ def _dispatch_background(batch: _Batch) -> str:parent_session_id=getattr(parent_agent, "session_id", None), max_async_children=_get_max_async_children(),)- units = _units_of(batch)+ units = [replace(unit, refused=[]) for unit in _units_of(batch)]dispatched: list[tuple[_Batch, str]] = []inline_results: list[dict] = []slot_key: Optional[str] = Nonediff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pyindex d68b019c9f8..19d606cc134 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -29,13 +29,27 @@ _PARAM_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")@dataclassclass TaskRoute:"""How core builds one child: the credential bundle (with a route's speed tier applied), the config block- owning its fallback policy, an optional reasoning override, and the profile home it runs as (None = this one)."""+ owning its fallback policy, an optional reasoning override, and the profile home it runs as (None = this one).+ ``error`` set = the backend could not route this task: it is refused alone and its siblings still run."""creds: dict[str, Any]routing_cfg: dict[str, Any]reasoning_effort: Any = Noneprofile_home: Optional[Path] = Nonelabel: Optional[str] = None+ backend: str = "default"+ error: Optional[str] = None++ def report(self) -> Optional[dict[str, Any]]:+ """The ``route`` a backend-routed task's result carries (None for the default backend's unlabelled route)."""+ if self.backend == "default" and not self.label:+ return None+ return {"backend": self.backend, **({"label": self.label} if self.label else {})}++ def refused_entry(self, index: int) -> dict[str, Any]:+ """Result entry for a task this route refused: no child was built for it."""+ return {"task_index": index, "status": "error", "summary": None, "error": self.error, "api_calls": 0,+ "duration_seconds": 0, "route": {**(self.report() or {"backend": self.backend}), "refused": True}}def _active_provider(config: Mapping[str, Any]) -> DelegationProvider:@@ -68,7 +82,10 @@ def schema_extension(config: Mapping[str, Any]) -> tuple[dict[str, dict[str, Any"""``(extra task properties, description addendum)`` for the active provider; empty for thebuilt-in default so its schema stays byte-identical."""from agent.delegation_registry import DEFAULT_BACKEND- provider = _active_provider(config)+ try:+ provider = _active_provider(config)+ except DelegationRouteError:+ return {}, "" # fails closed at spawn time, with the fix; the schema just stays the base oneif provider.name == DEFAULT_BACKEND:return {}, ""try:@@ -207,20 +224,34 @@ def _profile_route(home: Path) -> TaskRoute:ResolvedReasoning(resolve_reasoning_config(cfg, model or "")), home)-def _route_to_task_route(route: dict[str, Any], parent_agent: Any, cache: dict[str, TaskRoute]) -> TaskRoute:+def _with_inherited_fallback(route: dict[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:+ """A route without a fallback chain of its own takes ``delegation.fallback_providers`` (an explicit ``[]`` on the+ route still disables fallback). A profile route keeps its profile's own chain."""+ if route.get("profile") or route.get("fallback_providers") is not None:+ return route+ inherited = config.get("fallback_providers")+ return route if inherited is None else {**route, "fallback_providers": inherited}+++def _resolve_route(route: dict[str, Any], parent_agent: Any, backend: str) -> TaskRoute:+ if route.get("profile"):+ return replace(_profile_route(_profile_home(route["profile"])), backend=backend)+ from tools.delegate_tool import _resolve_delegation_credentials # the facade is the patch seam+ creds = _resolve_delegation_credentials(route, parent_agent)+ if route.get("service_tier") not in (None, ""):+ from tools.delegate_tool_tuning import task_service_tier+ creds = {**creds, **task_service_tier(str(route["service_tier"]), creds, parent_agent)}+ return TaskRoute(creds, route, route.get("reasoning_effort"), None, None, backend)+++def _route_to_task_route(route: dict[str, Any], parent_agent: Any, cache: dict[str, TaskRoute],+ config: Optional[Mapping[str, Any]] = None, backend: str = "default") -> TaskRoute:label = route.get("label") if isinstance(route.get("label"), str) else None+ route = _with_inherited_fallback(route, config or {})# The label is display-only: two labels on one route (or one profile) resolve once.key = json.dumps({k: v for k, v in route.items() if k != "label"}, sort_keys=True, default=str)if key not in cache:- if route.get("profile"):- cache[key] = _profile_route(_profile_home(route["profile"]))- else:- from tools.delegate_tool import _resolve_delegation_credentials # the facade is the patch seam- creds = _resolve_delegation_credentials(route, parent_agent)- if route.get("service_tier") not in (None, ""):- from tools.delegate_tool_tuning import task_service_tier- creds = {**creds, **task_service_tier(str(route["service_tier"]), creds, parent_agent)}- cache[key] = TaskRoute(creds, route, route.get("reasoning_effort"), None, None)+ cache[key] = _resolve_route(route, parent_agent, backend)return replace(cache[key], label=label)@@ -256,20 +287,23 @@ def _route_one(provider: DelegationProvider, declared: dict[str, dict[str, Any]]def resolve_task_routes(task_list: list[dict[str, Any]], config: Mapping[str, Any], parent_agent: Any,) -> tuple[list[TaskRoute], Optional[str]]:- """One :class:`TaskRoute` per task from the active provider, or ``([], error)``. Identical- routes resolve credentials once per call (the default provider resolves exactly once, as- before the seam)."""- provider = _active_provider(config)+ """One :class:`TaskRoute` per task from the configured backend (``delegation.backend``), or ``([], error)`` when that backend cannot run (fails closed, never another+ backend). A task the backend cannot route gets a route with ``error`` set; its siblings are unaffected.+ Identical routes resolve credentials once per call (the default backend resolves exactly once)."""+ try:+ provider = _active_provider(config)+ except DelegationRouteError as exc:+ return [], str(exc)declared = _declared_parameters(provider, config)cache: dict[str, TaskRoute] = {}routes: list[TaskRoute] = []- try:- for i, task in enumerate(task_list):+ for i, task in enumerate(task_list):+ try:route = _route_one(provider, declared, i, task, config)_check_backend_effort(i, route, config)- routes.append(_route_to_task_route(route, parent_agent, cache))- except ValueError as exc: # DelegationRouteError, the credential resolver's and the tier check's refusals- return [], str(exc)+ routes.append(_route_to_task_route(route, parent_agent, cache, config, provider.name))+ except ValueError as exc: # DelegationRouteError, the credential resolver's and the tier check's refusals+ routes.append(TaskRoute({}, {}, backend=provider.name, error=str(exc)))return routes, Nonediff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.mdindex 525de02802a..533c3de2930 100644--- a/website/docs/developer-guide/delegation-provider-plugin.md+++ b/website/docs/developer-guide/delegation-provider-plugin.md@@ -17,8 +17,9 @@ validation and progress. A provider only answers "which route does this task takThe active provider is `delegation.backend` in `config.yaml`; a provider's own settings live under`delegation.backends.<backend name>`. The built-in `default` strategy is today's behaviour: every child follows the `delegation` section (`delegation.provider`,`delegation.model`, `delegation.base_url`, ...), or inherits the parent's route when those are empty.-A configured backend that is not installed or reports unavailable falls back to `default` with one-warning, and its schema parameters disappear with it.+A configured backend that is not installed or reports unavailable **fails closed**: `delegate_task`+returns a tool error naming the backend and the fix, no child starts, and its schema parameters are+absent.## Skeleton@@ -122,16 +123,30 @@ A route is a dict with any of:Unknown keys are dropped. On a profile route, `service_tier` and `reasoning_effort` are ignored too.-Every result entry of a task whose route has a `label` carries `route`: the label plus what the child-actually ran on, read off the built child:+A non-profile route without `fallback_providers` of its own gets `delegation.fallback_providers`; return+`"fallback_providers": []` to disable fallback for a route. A profile route keeps its profile's chain.++### Refusals are per task++A `DelegationRouteError` from `route_task`, a value outside your parameter's `enum`, an unknown+`reasoning_effort`, a tier the route does not offer, or a credential the route cannot resolve refuses+**that task only**: no child is built for it, its result entry is+`{"status": "error", "error": "<your message>", "route": {"backend": "<name>", "refused": true}}`, and+the other tasks run. A background call lists refused entries under `refused` in its dispatch payload.+The call is a tool error only when every task is refused.++### Result `route`++Every result entry of a task routed by a non-default backend carries `route`: the backend, the label+(when set), and what the child actually ran on, read off the child when its result is assembled:```json-"route": {"label": "deep", "provider": "openai-codex", "model": "gpt-6-astra",+"route": {"backend": "model_map", "label": "deep", "provider": "openai-codex", "model": "gpt-6-astra","reasoning_effort": "high", "service_tier": "fast"}```-`reasoning_effort` is `null` when the provider's default applies. A route without a label (the-`default` strategy, your fallback to `dict(config)`) leaves the result entry unchanged.+`reasoning_effort` is `null` when the provider's default applies; `fallback_activated: true` is added+when a fallback provider took over. The `default` backend's children leave the result entry unchanged.## Prompt cachingdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 95af7a65e69..4468904026f 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -3015,7 +3015,7 @@ delegation:oneshot_max_children: 2 # Total subagents a one-shot run (hermes chat -q / --oneshot) may spawn; 0 = unlimited. Interactive and gateway sessions are never capped by this.```-**Delegation strategy (`backend`):** `delegation.backend` picks the strategy plugin that decides each subagent's route. `default` follows the keys below (or the parent's route when they are empty). Plugin strategies such as `model_map` (a named model per task) and `profile_routes` (a Hermes profile per task) read their settings from `delegation.backends.<backend name>`. A backend whose plugin is missing or disabled falls back to `default` with one warning. See [Subagent Delegation → Delegation strategies](features/delegation.md#delegation-strategies-delegationbackend).+**Delegation strategy (`backend`):** `delegation.backend` picks the strategy plugin that decides each subagent's route. `default` follows the keys below (or the parent's route when they are empty). Plugin strategies such as `model_map` (a named model per task) and `profile_routes` (a Hermes profile per task) read their settings from `delegation.backends.<backend name>`. A backend whose plugin is missing or disabled fails closed: `delegate_task` returns a tool error naming it and the fix (`/delegation default`, or `hermes config set delegation.backend default`) instead of running children on another route. A backend route without its own `fallback_providers` uses `delegation.fallback_providers`. See [Subagent Delegation → Delegation strategies](features/delegation.md#delegation-strategies-delegationbackend).**Subagent provider:model override:** By default, subagents inherit the parent agent's provider and model. Set `delegation.provider` and `delegation.model` to route subagents to a different provider:model pair — e.g., use a cheap/fast model for narrowly-scoped subtasks while your primary agent runs an expensive reasoning model.diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex 7af07ebcc94..0c2098a8c2e 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -297,8 +297,10 @@ Note that the pin is global: with the default strategy `delegate_task` has no pe`delegation.backend` selects how each task becomes a subagent. `default` (the default) is everything above. Strategy plugins can let the model choose per task, from options you define:-- a **profile per subagent** (`profile_routes`, from the `delegation-profiles` plugin): each child runs as one of your Hermes profiles, with that profile's model, credentials, skills and persona;-- a **named model map** (`model_map`, from the `delegation-model-map` plugin): you list titled options (`fast`, `deep`, ...) with a description and a provider/model each, and the model picks one per task.+- a **profile per subagent** (`profile_routes`): each child runs as one of your Hermes profiles, with that profile's model, credentials, skills and persona;+- a **named model map** (`model_map`): you list titled options (`fast`, `deep`, ...) with a description and a provider/model each, and the model picks one per task.++Both come from the official `advanced-delegation` plugin, which also adds `hermes delegation config` (create, edit and delete model routes, pick profiles) and the `/delegation` slash command. While `model_map` or `profile_routes` is active, `delegation.model` / `delegation.provider` are inactive: the routes decide.Each strategy's settings live under `delegation.backends.<backend name>`:@@ -325,7 +327,9 @@ delegation:description: Writes and refactors code; runs tests.```-The model only ever sees the names and descriptions you configured, never raw provider, model or key fields. A route's `service_tier` is checked like `/fast`: a tier the route does not offer, or an unknown `reasoning_effort`, fails the spawn with a tool error instead of silently running at another level. Each result of a routed task carries `route` (the option or profile name plus the provider, model, reasoning effort and speed tier the child actually ran on). If the selected plugin is missing or disabled, delegation falls back to `default`. Writing your own: [Delegation Provider Plugins](../../developer-guide/delegation-provider-plugin.md).+The model only ever sees the names and descriptions you configured, never raw provider, model or key fields. Each result of a backend-routed task carries `route`: the backend, the option or profile name, and the provider, model, reasoning effort and speed tier the child actually ran on (`fallback_activated: true` when a fallback provider took over). Writing your own: [Delegation Provider Plugins](../../developer-guide/delegation-provider-plugin.md).++**Failures are explicit, never a silent switch.** If the selected backend is missing (plugin not installed or disabled) or reports it cannot run, `delegate_task` returns a tool error naming the backend and the fix, and no subagent starts; it never quietly runs the children on the default route. Within a batch, a task its backend cannot route (an unknown option, a profile that does not exist, a `service_tier` the route does not offer, an unknown `reasoning_effort`, missing credentials) is refused alone: its result entry has `status: "error"`, the reason, and `route.refused: true`, while the other tasks run. A model route without its own `fallback_providers` uses `delegation.fallback_providers`; `fallback_providers: []` on the route disables fallback for it. A profile route uses that profile's own fallback chain.:::note Profile routes share credentialsListing a profile in `delegation.backends.profile_routes` lets this profile's subagents use that profile's credentials, credential pool, `SOUL.md` and terminal policy. Only list profiles whose keys and terminal access you are happy for this profile's agent to use.