The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(delegation): a session can switch its delegation backend
Tekniume4b7c9dc93ec
diff --git a/agent/delegation_backends.py b/agent/delegation_backends.pynew file mode 100644index 00000000000..180c0ab11b4--- /dev/null+++ b/agent/delegation_backends.py@@ -0,0 +1,104 @@+"""Which delegation backend a session uses: the public API behind a ``/delegation`` command.++``delegation.backend`` in config.yaml is the global choice. A session may override it (the ``/model``+convention: session-scoped by default, ``--global`` persists); the override decides routing from the+session's next ``delegate_task`` call. The ``delegate_task`` schema (a backend's per-task parameters)+is part of the cached prompt and keeps following config.yaml, so a backend's own task parameters+appear in sessions started after a global switch; a session switch to a backend whose parameters+the schema lacks routes every task to that backend's default.++Session keys are the ``session_key`` a plugin command handler receives: the gateway/TUI route key, or+the session id on the classic in-process CLI. ``delegate_task`` resolves the same key from the turn's+session context, else from the parent agent's session id.+"""++from __future__ import annotations++import threading+from dataclasses import dataclass+from typing import Any, Mapping, Optional++from agent.delegation_registry import DEFAULT_BACKEND, _registry, backend_status, configured_backend+from agent.provider_registry import lower_key++_session_backends: dict[str, str] = {}+_lock = threading.Lock()+++@dataclass(frozen=True)+class BackendInfo:+ """One selectable delegation backend: ``available`` False carries the ``reason`` it cannot run."""++ name: str+ label: str+ description: str+ available: bool+ reason: str = ""+++def _info(name: str) -> BackendInfo:+ provider, reason = backend_status(name)+ if provider is None:+ return BackendInfo(name, name, "", False, reason)+ return BackendInfo(name, provider.display_name, provider.summary, not reason, reason)+++def list_backends() -> list[BackendInfo]:+ """``default`` first, then every registered backend (unavailable ones included, with their reason)."""+ names = [DEFAULT_BACKEND, *sorted({p.name for p in _registry.list_providers()} - {DEFAULT_BACKEND})]+ return [_info(name) for name in names]+++def get_session_backend(session_key: str) -> Optional[str]:+ """The session's override, ``None`` when it follows config.yaml."""+ with _lock:+ return _session_backends.get(session_key) if session_key else None+++def set_session_backend(session_key: str, name: Optional[str]) -> None:+ """Switch one session's backend; ``None``/blank clears the override. Raises ``ValueError`` (with the+ reason) for a backend that cannot run here, so a typo never leaves the session broken."""+ if not session_key:+ raise ValueError("No session to switch: delegation backends are switched per session.")+ if name is None or not name.strip():+ with _lock:+ _session_backends.pop(session_key, None)+ return+ key = lower_key(name)+ info = _info(key)+ if not info.available:+ raise ValueError(info.reason)+ with _lock:+ _session_backends[session_key] = key+++def set_global_backend(name: str, *, session_key: str = "") -> None:+ """Persist ``delegation.backend`` to the active profile's config.yaml (raw user config, never merged+ defaults) and drop ``session_key``'s override, which would otherwise shadow it."""+ from hermes_cli.config import atomic_config_write, get_config_path, read_user_config_raw+ key = lower_key(name)+ info = _info(key)+ if not info.available:+ raise ValueError(info.reason)+ path = get_config_path()+ user_config = read_user_config_raw(path)+ section = user_config.get("delegation")+ if not isinstance(section, dict):+ section = user_config["delegation"] = {}+ section["backend"] = key+ atomic_config_write(path, user_config)+ if session_key:+ set_session_backend(session_key, None)+++def _current_session_key(parent_agent: Any) -> str:+ from gateway.session_context import get_session_env+ return get_session_env("HERMES_SESSION_KEY", "") or str(getattr(parent_agent, "session_id", "") or "")+++def session_delegation_config(config: Mapping[str, Any], parent_agent: Any) -> Mapping[str, Any]:+ """``config`` (the ``delegation`` section) with the calling session's backend override applied."""+ override = get_session_backend(_current_session_key(parent_agent))+ if override is None or override == configured_backend(config):+ return config+ return {**config, "backend": override}diff --git a/agent/delegation_provider.py b/agent/delegation_provider.pyindex 0cc01bafadf..5b4b188b6f7 100644--- a/agent/delegation_provider.py+++ b/agent/delegation_provider.py@@ -73,6 +73,11 @@ class DelegationProvider(ProviderBase):own = backends.get(self.name) if isinstance(backends, Mapping) else Nonereturn own if isinstance(own, Mapping) else {}+ @property+ def summary(self) -> str:+ """One user-facing line for backend pickers (``/delegation``); never shown to the model."""+ return ""+def is_available(self) -> bool:"""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."""diff --git a/agent/delegation_registry.py b/agent/delegation_registry.pyindex 92f735395df..6db15ba89df 100644--- a/agent/delegation_registry.py+++ b/agent/delegation_registry.py@@ -2,7 +2,7 @@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.+``delegation.backend`` in config.yaml (a session may override it, ``agent/delegation_backends.py``).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@@ -31,6 +31,14 @@ class DefaultDelegationProvider(DelegationProvider):def name(self) -> str:return DEFAULT_BACKEND+ @property+ def display_name(self) -> str:+ return "Default"++ @property+ def summary(self) -> str:+ return "Every subagent uses delegation.model / delegation.provider, else the parent's model."+def route_task(self, task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:# The delegation section has no speed tier: an unknown key there never becomes one.return {k: v for k, v in config.items() if k != "service_tier"}diff --git a/tests/tools/test_delegation_backends.py b/tests/tools/test_delegation_backends.pyindex d58bd7f95f4..c72b4bf8ed4 100644--- a/tests/tools/test_delegation_backends.py+++ b/tests/tools/test_delegation_backends.py@@ -201,6 +201,32 @@ def test_a_backend_route_without_its_own_chain_inherits_delegation_fallback_provmanager.unload()+def test_a_session_backend_switch_routes_that_session_only_and_global_persists(tmp_path, monkeypatch, recorded):+ """``/delegation`` seam: a session override decides that session's routing; ``--global`` writes config.yaml+ and drops the override; a backend that cannot run is refused up front."""+ home, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options",+ "backends": {"probe-options": {"options": OPTIONS}}})+ try:+ from agent.delegation_backends import (+ get_session_backend, list_backends, set_global_backend, set_session_backend,+ )+ from tools.delegate_tool import delegate_task++ assert [(b.name, b.available) for b in list_backends()] == [("default", True), ("probe-options", True)]+ set_session_backend("chat-a", "default")+ for sid in ("chat-a", "chat-b"):+ delegate_task(tasks=[{"goal": "route me", "option": "fast"}], parent_agent=_parent(sid))+ assert [b["model"] for b in recorded] == [None, "fast-model"]+ with pytest.raises(ValueError, match="'nope' is not installed"):+ set_session_backend("chat-a", "nope")++ set_global_backend("default", session_key="chat-a")+ assert yaml.safe_load((home / "config.yaml").read_text())["delegation"]["backend"] == "default"+ assert get_session_backend("chat-a") is None+ finally:+ manager.unload()++def test_plugin_parameters_never_redefine_core_or_route_fields(tmp_path, monkeypatch):from agent.delegation_provider import DelegationProviderfrom tools.delegate_tool_routes import schema_extensiondiff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex e75e3d81a3c..7ce02bf5486 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -143,7 +143,7 @@ delegation provider (`agent/delegation_provider.py`, `ctx.register_delegation_prresolved 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; itnever 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 background+unroutable task is refused alone (`TaskRoute.error`); a session override (`agent/delegation_backends.py`) beats config. 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_routes.py b/tools/delegate_tool_routes.pyindex 19d606cc134..494b11a7786 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -287,9 +287,12 @@ 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 configured backend (``delegation.backend``), or ``([], error)`` when that backend cannot run (fails closed, never another+ """One :class:`TaskRoute` per task from the session's backend (its ``/delegation`` override, else+ ``delegation.backend``), or ``([], error)`` when that backend cannot run (fails closed, never anotherbackend). 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)."""+ from agent.delegation_backends import session_delegation_config+ config = session_delegation_config(config, parent_agent)try:provider = _active_provider(config)except DelegationRouteError as exc:diff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.mdindex 533c3de2930..2c003fb9abd 100644--- a/website/docs/developer-guide/delegation-provider-plugin.md+++ b/website/docs/developer-guide/delegation-provider-plugin.md@@ -19,7 +19,7 @@ The active provider is `delegation.backend` in `config.yaml`; a provider's own s`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 **fails closed**: `delegate_task`returns a tool error naming the backend and the fix, no child starts, and its schema parameters are-absent.+absent. A session can override the backend (`agent.delegation_backends`, below).## Skeleton@@ -148,6 +148,24 @@ Every result entry of a task routed by a non-default backend carries `route`: th`reasoning_effort` is `null` when the provider's default applies; `fallback_activated: true` is addedwhen a fallback provider took over. The `default` backend's children leave the result entry unchanged.+## Picker metadata and session switching++`display_name` and `summary` (one user-facing line; never shown to the model) label your backend in+pickers such as `/delegation`. `agent.delegation_backends` is the public API a picker or slash command+uses:++| Call | Does |+|---|---|+| `list_backends() -> list[BackendInfo]` | `default` first, then every registered backend: `name`, `label`, `description`, `available`, `reason` (the fix, when unavailable). |+| `get_session_backend(session_key) -> str \| None` | The session's override, `None` when it follows `config.yaml`. |+| `set_session_backend(session_key, name \| None)` | Switch one session (`None` clears). Raises `ValueError` with the reason for a backend that cannot run. |+| `set_global_backend(name, *, session_key="")` | Write `delegation.backend` to the active profile's `config.yaml` and drop that session's override. |++`session_key` is the `session_key` a plugin command handler receives. A session switch decides routing+from that session's next `delegate_task` call; the `delegate_task` schema (your parameters) follows+`config.yaml`, because it is part of the cached prompt, so a session switched to a backend whose+parameters it lacks routes every task to that backend's default.+## Prompt cachingThe `delegate_task` definition, including your parameters and description, is built once when adiff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex 0c2098a8c2e..cce6700f0fd 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -331,6 +331,8 @@ The model only ever sees the names and descriptions you configured, never raw pr**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.+**Switching back.** `/delegation default` (from the `advanced-delegation` plugin) switches the current session to the default backend, and `/delegation <backend> --global` writes `delegation.backend` to `config.yaml`, following the `/model` convention. A session switch changes routing from the next `delegate_task` call; the per-task parameters the model sees (option or profile names) follow `config.yaml` and change at the next session. Without the plugin, `hermes config set delegation.backend default` restores the default.+:::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.:::