Skip to content

The agent that grows with you

feat(delegation): /delegation saves for the next session; --now rebuilds this session's tools

Teknium552f7353683d
diff --git a/agent/delegation_backends.py b/agent/delegation_backends.py
index ac0df5f2d94..1c3237904a6 100644
--- a/agent/delegation_backends.py
+++ b/agent/delegation_backends.py
@@ -1,29 +1,27 @@
-"""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. After a session switch the model may still send the
-previous backend's parameters: each such task is refused (naming the session's backend, the parameter,
-and the fix: ``/delegation <backend> --global`` then ``/new``, since ``/new`` starts on the saved backend, or
-``/delegation <saved backend>`` back), never run on the new backend's default route.
-
-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.
+"""Which delegation backend Hermes uses: the public API behind a ``/delegation`` command.
+
+``delegation.backend`` in config.yaml is the one choice; ``delegate_task`` reads it at every call. The
+``delegate_task`` schema (a backend's per-task parameters) is part of the cached prompt, so a switch reaches a
+session's tool list from its next session (``/new``). ``apply_now`` opts into rebuilding the calling session's
+tools at its next turn instead: one prompt-cache break, the rule every slash command that changes prompt state
+follows (``--now``). Until then a task carrying parameters the saved backend does not declare is refused
+(``tools/delegate_tool_routes.py``), never run on the new backend's default route.
+
+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. A turn resolves the same key from its session context, else from the
+agent's session id.
"""
from __future__ import annotations
import threading
from dataclasses import asdict, dataclass
-from typing import Any, Mapping, Optional
+from typing import Any
-from agent.delegation_registry import DEFAULT_BACKEND, _registry, backend_status, configured_backend
+from agent.delegation_registry import DEFAULT_BACKEND, _registry, backend_status
from agent.provider_registry import lower_key
-_session_backends: dict[str, str] = {}
+_rebuild_requests: set[str] = set()
_lock = threading.Lock()
@@ -51,39 +49,20 @@ def list_backends() -> list[BackendInfo]:
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:
+def set_global_backend(name: str, *, session_key: str = "", apply_now: bool = False) -> 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. Raises ``PermissionError``
- on a package-manager-managed install (its config.yaml is not ours to write) and ``ValueError`` for a backend
- that cannot run."""
+ defaults). ``apply_now`` also rebuilds ``session_key``'s tool list at that session's next turn, so its
+ ``delegate_task`` offers the new backend's parameters there (an opt-in prompt-cache break); otherwise a
+ session's tools pick the switch up from ``/new``. Raises ``PermissionError`` on a package-manager-managed
+ install (its config.yaml is not ours to write) and ``ValueError`` (with the reason) for a backend that cannot
+ run or an ``apply_now`` without a session, before anything is written."""
from hermes_cli.config import (
atomic_config_write, format_managed_message, get_config_path, is_managed, read_user_config_raw,
)
if is_managed():
raise PermissionError(format_managed_message("set delegation.backend"))
+ if apply_now and not session_key:
+ raise ValueError("No session to apply the switch to: apply_now needs the command's session_key.")
key = lower_key(name)
info = _info(key)
if not info.available:
@@ -95,36 +74,46 @@ def set_global_backend(name: str, *, session_key: str = "") -> None:
section = user_config["delegation"] = {}
section["backend"] = key
atomic_config_write(path, user_config)
- if session_key:
- set_session_backend(session_key, None)
+ if apply_now:
+ with _lock:
+ _rebuild_requests.add(session_key)
-def _current_session_key(parent_agent: Any) -> str:
+def _current_session_key(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 "")
+ return get_session_env("HERMES_SESSION_KEY", "") or str(getattr(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}
+def apply_requested_tool_rebuild(agent: Any) -> bool:
+ """Turn start, after the session's tools are restored: rebuild ``agent.tools`` from the registry if
+ ``set_global_backend(apply_now=True)`` asked for this session, and pin the result to the session row so a
+ later fresh agent restores it. True when the tool list changed. Forks (background review, ``/btw``) and
+ subagents share the session's key but never take its request."""
+ if getattr(agent, "_turn_origin", None) or getattr(agent, "_delegate_depth", 0):
+ return False
+ key = _current_session_key(agent)
+ with _lock:
+ if key not in _rebuild_requests:
+ return False
+ _rebuild_requests.discard(key)
+ from hermes_cli.observability.shared_metrics_efficiency import record_cache_break
+ from tools.mcp_tool_agent import persist_agent_tool_names, refresh_agent_mcp_tools
+ before = getattr(agent, "tools", None)
+ refresh_agent_mcp_tools(agent, quiet_mode=True, content_aware=True)
+ if agent.tools is before:
+ return False
+ persist_agent_tool_names(agent)
+ record_cache_break(agent, "toolset_change")
+ return True
class DelegationBackends:
"""``ctx.delegation_backends``: this API for plugins, as plain data. It is a host remote facade, so a plugin
- running under ``plugins.isolation: host`` lists and switches the owner process's backends and sessions, not
+ running under ``plugins.isolation: host`` lists and switches the owner process's backend and sessions, not
copies in its own process."""
def list_backends(self) -> list[dict[str, Any]]:
return [asdict(info) for info in list_backends()]
- def get_session_backend(self, session_key: str) -> Optional[str]:
- return get_session_backend(session_key)
-
- def set_session_backend(self, session_key: str, name: Optional[str]) -> None:
- set_session_backend(session_key, name)
-
- def set_global_backend(self, name: str, session_key: str = "") -> None:
- set_global_backend(name, session_key=session_key)
+ def set_global_backend(self, name: str, *, session_key: str = "", apply_now: bool = False) -> None:
+ set_global_backend(name, session_key=session_key, apply_now=apply_now)
diff --git a/agent/delegation_registry.py b/agent/delegation_registry.py
index e8ba0a4ef0e..19e2d0f9453 100644
--- a/agent/delegation_registry.py
+++ b/agent/delegation_registry.py
@@ -5,7 +5,7 @@ asks :func:`get_active_provider` which strategy turns each task into a child run
``delegation.backend`` in config.yaml, ``default`` when unset. The default strategy (today's
behaviour: every child follows the ``delegation`` section, else the parent's route) is itself a
plugin, the bundled ``plugins/delegation/default``, registered through the same seam as any other.
-A session may override the selection (``agent/delegation_backends.py``). A configured backend that is
+``agent/delegation_backends.py`` switches it (``/delegation``). 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.
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 009f43c7957..2732c34d082 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -1142,6 +1142,9 @@ def build_turn_context(
if agent._cached_system_prompt is None:
restore_or_build_system_prompt(agent, system_message, conversation_history)
active_system_prompt = agent._cached_system_prompt
+ # `/delegation <backend> --now`: after the pin restore, so a fresh agent rebuilds too.
+ from agent.delegation_backends import apply_requested_tool_rebuild
+ apply_requested_tool_rebuild(agent)
# Bot Mode DM tool — injected ONLY into a bot's canonical "Bot Chat" session (same
# gate as the protocol section); gate is session-stable, so cache-safe.
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index dd51a6f273b..d1d86da165e 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -411,9 +411,6 @@ class GatewayAgentCacheMixin:
state = self._peek_session_state(session_key)
if state is not None:
state.conversation.clear()
- # A /delegation backend pick is conversation-scoped like /model's, but lives with the backends.
- from agent.delegation_backends import set_session_backend
- set_session_backend(session_key, None)
# Legacy plain-dict stores still in _CONVERSATION_SCOPED_STATE (not yet folded into
# SessionState), e.g. _pending_model_notes. SessionState-backed names resolve to MutableMapping
# views (not dict), so the isinstance(dict) guard skips them — already handled above.
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 14e13ab00e3..464b1d9175c 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -391,8 +391,8 @@ class PluginContext:
@cached_property
def delegation_backends(self) -> Any:
- """``agent.delegation_backends.DelegationBackends``: list delegation backends and switch them per session or
- globally (a ``/delegation`` command); a host remote facade, so it acts on the owner process."""
+ """``agent.delegation_backends.DelegationBackends``: list delegation backends and save one, optionally
+ rebuilding the calling session's tools now (``/delegation``); a host remote facade on the owner process."""
from agent.delegation_backends import DelegationBackends
return DelegationBackends()
diff --git a/tests/agent/test_delegation_switch_next_session.py b/tests/agent/test_delegation_switch_next_session.py
new file mode 100644
index 00000000000..446d4002a2e
--- /dev/null
+++ b/tests/agent/test_delegation_switch_next_session.py
@@ -0,0 +1,103 @@
+"""``/delegation <backend>`` saves for the next session; ``--now`` rebuilds this session's tools.
+
+Real AIAgent turns against a recording fake provider, a real delegation backend plugin discovered from a temp
+HERMES_HOME, and the real session DB: each test reads the ``delegate_task`` schema Hermes actually sent.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.history._helpers import NO_BACKGROUND_REVIEW, OFFLINE_CONFIG
+from tests.fakes.fake_llm_provider import FakeLLMServer, write_hermes_home
+from tests.tools.test_delegation_backends import OPTIONS, PROBE_PLUGIN, REPO_PLUGINS
+
+
+def options_backend(monkeypatch):
+ """``delegation.backend: probe-options`` (adds a per-task ``option``) on a fake provider."""
+ import hermes_yaml as yaml
+ from hermes_cli import plugins as plugins_mod
+ from hermes_cli.plugins import PluginManager
+
+ home = Path(os.environ["HERMES_HOME"])
+ plugin_dir = home / "plugins" / "probe-options"
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump({"name": "probe-options", "version": "1.0"}))
+ (plugin_dir / "__init__.py").write_text(PROBE_PLUGIN)
+ bundled = home.parent / "bundled"
+ bundled.mkdir()
+ (bundled / "delegation").symlink_to(REPO_PLUGINS / "delegation", target_is_directory=True)
+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: bundled)
+ srv = FakeLLMServer([]).__enter__()
+ extra = yaml.safe_dump({"plugins": {"enabled": ["probe-options"]}, "delegation": {
+ "backend": "probe-options", "backends": {"probe-options": {"options": OPTIONS}}}})
+ write_hermes_home(home, srv.base_url, extra_config=OFFLINE_CONFIG + NO_BACKGROUND_REVIEW + extra)
+ manager = PluginManager()
+ manager.discover_and_load()
+ yield srv, home
+ manager.unload()
+ srv.__exit__(None, None, None)
+
+
+def _agent(srv, home, session_id):
+ from hermes_state import SessionDB
+ from run_agent import AIAgent
+
+ return AIAgent(provider="custom", base_url=srv.base_url, api_key="sk-fake-e2e", model="fake-model",
+ session_db=SessionDB(db_path=home / "state.db"), session_id=session_id, quiet_mode=True,
+ platform="cli")
+
+
+def _sent_task_fields(srv) -> set[str]:
+ """The per-task fields of ``delegate_task`` in the last main request."""
+ tool = next(t for t in srv.main_requests()[-1]["tools"] if t["function"]["name"] == "delegate_task")
+ return set(tool["function"]["parameters"]["properties"]["tasks"]["items"]["properties"])
+
+
+def _turn(agent, text, history):
+ return agent.run_conversation(text, conversation_history=history, task_id="t")["messages"]
+
+
+def test_a_now_switch_rebuilds_this_sessions_delegate_task_for_the_new_backend(options_backend):
+ from agent.delegation_backends import set_global_backend
+
+ srv, home = options_backend
+ agent = _agent(srv, home, "chat-now")
+ history = _turn(agent, "hello", [])
+ assert "option" in _sent_task_fields(srv)
+
+ set_global_backend("default", session_key="chat-now", apply_now=True)
+ history = _turn(agent, "and now", history)
+ assert "option" not in _sent_task_fields(srv)
+ agent.close()
+
+ # The rebuilt tools are the session's pin: a fresh agent on it (gateway, --resume) restores them.
+ fresh = _agent(srv, home, "chat-now")
+ _turn(fresh, "still here", history)
+ fresh.close()
+ assert "option" not in _sent_task_fields(srv)
+
+
+def test_a_plain_switch_keeps_this_sessions_schema_and_new_sessions_take_the_saved_backend(options_backend):
+ import hermes_yaml as yaml
+ from agent.delegation_backends import set_global_backend
+
+ srv, home = options_backend
+ agent = _agent(srv, home, "chat-plain")
+ history = _turn(agent, "hello", [])
+ before = srv.main_requests()[-1]["tools"]
+
+ set_global_backend("default", session_key="chat-plain")
+ assert yaml.safe_load((home / "config.yaml").read_text())["delegation"]["backend"] == "default"
+ _turn(agent, "and now", history)
+ assert srv.main_requests()[-1]["tools"] == before # the cached tool list is untouched
+ agent.close()
+
+ new = _agent(srv, home, "chat-plain-new") # /new
+ _turn(new, "hello again", [])
+ new.close()
+ assert "option" not in _sent_task_fields(srv)
diff --git a/tests/gateway/test_session_model_reset.py b/tests/gateway/test_session_model_reset.py
index 7b8209f85a4..40c2903bd84 100644
--- a/tests/gateway/test_session_model_reset.py
+++ b/tests/gateway/test_session_model_reset.py
@@ -100,22 +100,3 @@ async def test_new_command_only_clears_own_session():
assert other_key in runner._session_reasoning_overrides
assert session_key not in runner._pending_model_notes
assert other_key in runner._pending_model_notes
-
-
-async def test_new_command_drops_the_sessions_delegation_backend_override():
- """A ``/delegation <mode>`` pick is session-scoped like ``/model``: /new starts the chat on config.yaml's backend
- (the route key survives /new), and other chats keep theirs."""
- from agent.delegation_backends import get_session_backend, set_session_backend
-
- runner = _make_runner()
- session_key = build_session_key(_make_source())
- set_session_backend(session_key, "default")
- set_session_backend("other_session_key", "default")
- try:
- await runner._handle_reset_command(_make_event("/new"))
- assert get_session_backend(session_key) is None
- assert get_session_backend("other_session_key") == "default"
- finally:
- set_session_backend(session_key, None)
- set_session_backend("other_session_key", None)
diff --git a/tests/hermes_cli/test_plugin_host_delegation.py b/tests/hermes_cli/test_plugin_host_delegation.py
index d2583581ed0..25b2397111a 100644
--- a/tests/hermes_cli/test_plugin_host_delegation.py
+++ b/tests/hermes_cli/test_plugin_host_delegation.py
@@ -33,8 +33,8 @@ def register(ctx):
def switch(raw_args, session_key=""):
names = [b["name"] for b in ctx.delegation_backends.list_backends()]
- ctx.delegation_backends.set_session_backend(session_key, raw_args.strip())
- return f"{os.getpid()} {','.join(names)} -> {ctx.delegation_backends.get_session_backend(session_key)}"
+ ctx.delegation_backends.set_global_backend(raw_args.strip(), session_key=session_key, apply_now=True)
+ return f"{os.getpid()} {','.join(names)}"
ctx.register_command("deleg-switch", switch)
'''
@@ -80,15 +80,17 @@ def test_hosted_delegation_provider_extends_schema_and_routes_from_the_host(tmp_
assert err is None and "b is closed" in refused[0].error
assert json.dumps(params) == json.dumps(schema_extension(config)[0])
- # The /delegation seam acts on THIS process's sessions (ctx.delegation_backends is a host remote facade).
- from agent.delegation_backends import get_session_backend, set_session_backend
+ # The /delegation seam acts on THIS process (ctx.delegation_backends is a host remote facade): its
+ # config.yaml, and the --now rebuild THIS process's session runs at its next turn.
+ from agent import delegation_backends
from hermes_cli.plugin_command_dispatch import invoke_plugin_command
out = invoke_plugin_command(plugins_mod.get_plugin_command_handler("deleg-switch"), "default",
session_key="chat-a")
pid, listed = out.split(" ", 1)
- assert int(pid) != os.getpid() and listed == "default,hosted-map -> default"
- assert get_session_backend("chat-a") == "default"
- set_session_backend("chat-a", None)
+ assert int(pid) != os.getpid() and listed == "default,hosted-map"
+ assert yaml.safe_load((home / "config.yaml").read_text())["delegation"]["backend"] == "default"
+ assert delegation_backends._rebuild_requests == {"chat-a"}
+ delegation_backends._rebuild_requests.clear()
finally:
manager.unload()
manager._plugin_host().shutdown()
diff --git a/tests/tools/test_delegation_backends.py b/tests/tools/test_delegation_backends.py
index 7677d8525b8..d315a09f575 100644
--- a/tests/tools/test_delegation_backends.py
+++ b/tests/tools/test_delegation_backends.py
@@ -208,46 +208,10 @@ def test_a_backend_route_without_its_own_chain_inherits_delegation_fallback_prov
manager.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 plainly"}, {"goal": "route me on fast", "option": "fast"}],
- parent_agent=_parent(sid))
- # chat-a's schema still offers `option` (it follows config.yaml); its default backend refuses that task
- # instead of running it on the default route, and a name no backend declares is refused too.
- assert [b["model"] for b in recorded] == [None, None, "fast-model"]
- error = json.loads(delegate_task(tasks=[{"goal": "route me on fast", "option": "fast"},
- {"goal": "route me on a tier", "tier": "a"}],
- parent_agent=_parent("chat-a")))["error"]
- owned, unknown = error.split(" Task 1: ")
- assert "backend is 'default'" in owned and "`/delegation default --global` then `/new`" in owned
- assert "`/delegation probe-options` to switch this session back to the saved backend" in owned
- assert "'tier'" in unknown and "no installed delegation backend" in unknown and len(recorded) == 3
- 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_a_session_switch_refuses_a_task_using_the_previous_backends_parameter(tmp_path, monkeypatch, recorded):
- """The schema keeps the saved backend's parameters for the whole session (cached prompt), so after
- ``/delegation`` switches to another backend a task sending the old ``option`` is refused alone, naming the
- session's backend, the parameter and the fix; it never runs on the new backend's default route."""
+def test_a_saved_switch_refuses_the_previous_backends_parameter_and_names_the_fix(tmp_path, monkeypatch, recorded):
+ """``/delegation <backend>`` saves config.yaml and routing follows it at once, while a running session's
+ schema (cached prompt) still offers the previous backend's parameters: a task sending one is refused alone,
+ naming the backend, the parameter and the fix; it never runs on the new backend's default route."""
from agent.delegation_provider import DelegationProvider
from agent.delegation_registry import _registry
@@ -262,29 +226,40 @@ def test_a_session_switch_refuses_a_task_using_the_previous_backends_parameter(t
def route_task(self, task, config):
return {"model": f"{task.get('target') or 'profile-default'}-model"}
- _, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options",
- "backends": {"probe-options": {"options": OPTIONS}}})
+ home, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options",
+ "backends": {"probe-options": {"options": OPTIONS}}})
profiles = Profiles()
_registry.register(profiles)
try:
- from agent.delegation_backends import set_session_backend
+ from agent.delegation_backends import list_backends, set_global_backend
from tools.delegate_tool import delegate_task
- assert "option" in _task_props(_definition())
- set_session_backend("chat-a", "probe-profiles")
+ assert [b.name for b in list_backends()] == ["default", "probe-options", "probe-profiles"]
+ before = (home / "config.yaml").read_bytes()
+ with pytest.raises(ValueError, match="'nope' is not installed"):
+ set_global_backend("nope")
+ with pytest.raises(ValueError, match="apply_now needs"):
+ set_global_backend("probe-profiles", apply_now=True)
+ assert (home / "config.yaml").read_bytes() == before
+
+ set_global_backend("probe-profiles", session_key="chat-a")
+ assert yaml.safe_load((home / "config.yaml").read_text())["delegation"]["backend"] == "probe-profiles"
out = json.loads(delegate_task(tasks=[
{"goal": "the quick thing", "option": "fast"},
{"goal": "a plain task"},
{"goal": "a work task", "target": "work"},
+ {"goal": "a tier task", "tier": "a"},
], parent_agent=_parent("chat-a")))
- refused, plain, work = out["results"]
+ refused, plain, work, unknown = out["results"]
assert refused["status"] == "error" and refused["route"] == {"backend": "probe-profiles", "refused": True}
- # /new starts on the saved backend, so the advice persists the session's pick first or names the saved one.
assert refused["error"] == (
- "Task 0: this session's delegation backend is 'probe-profiles', which does not take 'option' (declared by "
- "'probe-options'), so this task was not started. Run `/delegation probe-profiles --global` then `/new` for "
- "a session whose delegate_task choices match 'probe-profiles', or `/delegation probe-options` to switch "
- "this session back to the saved backend.")
+ "Task 0: the delegation backend is 'probe-profiles', which does not take 'option' (declared by "
+ "'probe-options'), so this task was not started. This session's delegate_task was built for another "
+ "backend: run `/delegation probe-profiles --now` to rebuild this session's delegate_task for "
+ "'probe-profiles', or start a new session with /new.")
+ assert unknown["error"].startswith(
+ "Task 3: the delegation backend is 'probe-profiles', which does not take 'tier', and no installed "
+ "delegation backend does, so this task was not started. Resend it without 'tier';")
assert plain["status"] == work["status"] == "completed"
assert [b["model"] for b in recorded] == ["profile-default-model", "work-model"]
finally:
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 77c4335ee75..9e9ef9c5d91 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -144,7 +144,7 @@ resolved like the `delegation` section, `service_tier` checked like `/fast` in `
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. The `default` strategy is the bundled `plugins/delegation/default` plugin (no core special case
beyond selecting it). Fails closed: an unusable backend is a tool error naming it (never a silent `default`), an
-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 background
+unroutable task is refused alone (`TaskRoute.error`), as is a task sending a parameter the saved backend lacks (a switch reaches a session's schema at `/new` or with `--now`: `agent/delegation_backends.py`). Internal `credentials_cfg` callers (/review) and the lifecycle API bypass it. **Child processes:** a child's background
processes 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 on
diff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.py
index b20d60c4078..402ec5a5832 100644
--- a/tools/delegate_tool_routes.py
+++ b/tools/delegate_tool_routes.py
@@ -265,36 +265,32 @@ def _check_backend_effort(index: int, route: Mapping[str, Any], config: Mapping[
f"Use none or one of: {', '.join(VALID_REASONING_EFFORTS)}.")
-def _undeclared_error(provider: DelegationProvider, index: int, names: list[str], config: Mapping[str, Any],
- saved: str) -> str:
- """Why a task carrying parameters the session's backend does not declare is refused. The schema follows
- config.yaml for the whole session (cached prompt), so after a ``/delegation`` switch the model can still send
- the previous backend's parameters; dropping them would run the task on this backend's default route.
- ``/new`` starts on the saved backend (``saved``), so the fix persists the session's pick first or names it."""
+def _undeclared_error(provider: DelegationProvider, index: int, names: list[str], config: Mapping[str, Any]) -> str:
+ """Why a task carrying parameters the saved backend does not declare is refused. The schema is cached prompt,
+ so after a ``/delegation`` switch the session's tool list still offers the previous backend's parameters until
+ ``/new`` or ``/delegation <backend> --now``; dropping them would run the task on this backend's default route."""
from agent.delegation_registry import _registry
active = provider.name
listed = ", ".join(f"'{name}'" for name in names)
owners = sorted({other.name for other in _registry.list_providers() if other.name != active
and set(names) & set(_declared_parameters(other, config))})
- head = f"Task {index}: this session's delegation backend is '{active}', which does not take {listed}"
- if saved == active:
- fix = f"start a new session with /new for delegate_task choices that match '{active}'"
- else:
- fix = (f"run `/delegation {active} --global` then `/new` for a session whose delegate_task choices match "
- f"'{active}', or `/delegation {saved}` to switch this session back to the saved backend")
+ head = f"Task {index}: the delegation backend is '{active}', which does not take {listed}"
+ fix = (f"run `/delegation {active} --now` to rebuild this session's delegate_task for '{active}', "
+ f"or start a new session with /new")
if owners:
quoted = ", ".join(f"'{owner}'" for owner in owners)
- return f"{head} (declared by {quoted}), so this task was not started. {fix[0].upper()}{fix[1:]}."
+ return (f"{head} (declared by {quoted}), so this task was not started. This session's delegate_task was "
+ f"built for another backend: {fix}.")
return (f"{head}, and no installed delegation backend does, so this task was not started. Resend it without "
f"{listed}; if this session's delegate_task tool offers {listed}, {fix}.")
def _route_one(provider: DelegationProvider, declared: dict[str, dict[str, Any]], index: int,
- task: Mapping[str, Any], config: Mapping[str, Any], saved: str) -> dict[str, Any]:
+ task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:
undeclared = sorted(name for name, value in task.items()
if value is not None and name not in declared and name not in RESERVED_TASK_PARAMETERS)
if undeclared:
- raise DelegationRouteError(_undeclared_error(provider, index, undeclared, config, saved))
+ raise DelegationRouteError(_undeclared_error(provider, index, undeclared, config))
params = {name: task[name] for name in declared if task.get(name) is not None}
for name, value in params.items():
error = _param_error(index, name, value, declared[name])
@@ -312,14 +308,10 @@ 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 session's backend (its ``/delegation`` override, else
- ``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)."""
- from agent.delegation_backends import session_delegation_config
- from agent.delegation_registry import configured_backend
- saved = configured_backend(config)
- config = session_delegation_config(config, parent_agent)
+ """One :class:`TaskRoute` per task from ``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:
@@ -329,7 +321,7 @@ def resolve_task_routes(task_list: list[dict[str, Any]], config: Mapping[str, An
routes: list[TaskRoute] = []
for i, task in enumerate(task_list):
try:
- route = _route_one(provider, declared, i, task, config, saved)
+ route = _route_one(provider, declared, i, task, config)
_check_backend_effort(i, route, config)
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
diff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.md
index 80b8f40472c..f8487f6b5a1 100644
--- a/website/docs/developer-guide/delegation-provider-plugin.md
+++ b/website/docs/developer-guide/delegation-provider-plugin.md
@@ -22,7 +22,7 @@ inherits the parent's route when those are empty. It is itself a plugin, the bun
`ctx.register_delegation_provider()` seam as yours; it is also the smallest complete example.
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. A session can override the backend (`agent.delegation_backends`, below).
+absent. `/delegation` switches the backend (`agent.delegation_backends`, below).
## Skeleton
@@ -152,7 +152,7 @@ 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 added
when a fallback provider took over. The `default` backend's children leave the result entry unchanged.
-## Picker metadata and session switching
+## Picker metadata and switching backends
`display_name` and `summary` (one user-facing line; never shown to the model) label your backend in
pickers such as `/delegation`. A plugin uses `ctx.delegation_backends` (same methods; `list_backends()` returns
@@ -162,30 +162,28 @@ the plugin host. Core code calls `agent.delegation_backends` directly:
| 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. Raises `PermissionError` on a package-manager-managed install. |
+| `set_global_backend(name, *, session_key="", apply_now=False)` | Write `delegation.backend` to the active profile's `config.yaml`. `apply_now=True` also rebuilds the tool list of the session `session_key` names at its next turn. Raises `PermissionError` on a package-manager-managed install, and `ValueError` with the reason for a backend that cannot run (or `apply_now` without a `session_key`); nothing is written then. |
A plugin command that edits model routes can reuse the interactive model picker under its own heading:
`hermes_cli.auth_model_picker.prompt_model_selection(model_ids, current_model="", title="Select the model for this route:")`
returns the chosen model id, or `None` when cancelled.
-`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 and is never rebuilt mid-conversation. After a
-switch the model can still send the previous backend's parameters, so core refuses each task carrying a
-parameter the session's backend does not declare (fail closed per task, like any other refusal) instead
-of dropping it and running the task on the new backend's default route:
+`session_key` is the `session_key` a plugin command handler receives. `delegate_task` reads
+`delegation.backend` at every call, but its schema (your parameters) is part of the cached prompt, so a switch
+reaches a running session's tool list only from its next session (`/new`). `apply_now=True` (what
+`/delegation <backend> --now` passes) rebuilds that session's tools at its next turn instead, breaking the prompt
+cache once by the user's choice, the same opt-in as `/skills install --now`. Until one of those happens the model
+can still send the previous backend's parameters, so core refuses each task carrying a parameter the saved backend
+does not declare (fail closed per task, like any other refusal) instead of dropping it and running the task on the
+new backend's default route:
```text
-Task 0: this session's delegation backend is 'profile_routes', which does not take 'option' (declared by
-'model_map'), so this task was not started. Run `/delegation profile_routes --global` then `/new` for a
-session whose delegate_task choices match 'profile_routes', or `/delegation model_map` to switch this
-session back to the saved backend.
+Task 0: the delegation backend is 'profile_routes', which does not take 'option' (declared by 'model_map'), so
+this task was not started. This session's delegate_task was built for another backend: run
+`/delegation profile_routes --now` to rebuild this session's delegate_task for 'profile_routes', or start a new
+session with /new.
```
-`/new` starts on the saved backend (`delegation.backend`), so the fix persists the session's pick first or
-names the saved one. When the session follows `config.yaml` (it changed mid-session), the fix is just `/new`.
A parameter no installed backend declares is refused the same way, with "Resend it without ..." first.
## Prompt caching
diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.md
index 659927389bf..53e83662b24 100644
--- a/website/docs/user-guide/features/delegation.md
+++ b/website/docs/user-guide/features/delegation.md
@@ -331,7 +331,7 @@ 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 parameter the selected backend does not take, 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 and lasts until the conversation ends (`/new`, `/resume`, an automatic reset); the per-task parameters the model sees (option or profile names) follow `config.yaml` and change at the next session, because the tool list is part of the cached prompt. Until then, a task that sends the previous backend's parameter (an `option` after switching to `profile_routes`) is refused with a message naming the session's backend, the parameter and the fix (`/delegation <backend> --global` then `/new`, because `/new` starts on the saved backend, or `/delegation <saved backend>` back); it never runs on the new backend's default route. Without the plugin, `hermes config set delegation.backend default` restores the default.
+**Switching back.** `/delegation default` (from the `advanced-delegation` plugin) saves `delegation.backend` to `config.yaml`; subagents route on it from the next `delegate_task` call. The per-task parameters the model sees (option or profile names) are part of the cached tool list, so they change from the next session (`/new`). `/delegation <backend> --now` also rebuilds the current session's tool list at its next turn, at the cost of one prompt-cache miss. Until then, a task that sends the previous backend's parameter (an `option` after switching to `profile_routes`) is refused with a message naming the backend, the parameter and the fix (`/delegation <backend> --now`, or `/new`); it never runs on the new backend's default route. Without the plugin, `hermes config set delegation.backend default` restores the default.
:::note Profile routes share credentials
Listing 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.