The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): refuse a task parameter the session's backend does not declare
Teknium773691ae2f78
diff --git a/agent/delegation_backends.py b/agent/delegation_backends.pyindex 80e21b96e53..34fbf6cb6b5 100644--- a/agent/delegation_backends.py+++ b/agent/delegation_backends.py@@ -4,8 +4,9 @@convention: session-scoped by default, ``--global`` persists); the override decides routing from thesession'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.+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 ``/new`` or ``/delegation <backend>`` as the fix), 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, orthe session id on the classic in-process CLI. ``delegate_task`` resolves the same key from the turn'sdiff --git a/agent/delegation_provider.py b/agent/delegation_provider.pyindex 5b4b188b6f7..f2e0012dc1b 100644--- a/agent/delegation_provider.py+++ b/agent/delegation_provider.py@@ -90,7 +90,8 @@ class DelegationProvider(ProviderBase):Called when the tool definitions are built for a session, never mid-conversation, and theresult must be deterministic for a given ``config`` (same input, same bytes): the schemais part of the cached prompt prefix. Names in :data:`RESERVED_TASK_PARAMETERS` are- refused. An ``enum`` here is enforced by core before :meth:`route_task` runs.+ refused. An ``enum`` here is enforced by core before :meth:`route_task` runs, and a task+ carrying a parameter this method did not declare is refused before it reaches you."""return {}diff --git a/tests/tools/test_delegation_backends.py b/tests/tools/test_delegation_backends.pyindex 3819f0ce43c..d219833244f 100644--- a/tests/tools/test_delegation_backends.py+++ b/tests/tools/test_delegation_backends.py@@ -215,8 +215,17 @@ def test_a_session_backend_switch_routes_that_session_only_and_global_persists(tassert [(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"]+ 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 probe-options`" in owned and "/new" in owned+ assert "'tier'" in unknown and "no installed delegation backend" in unknown and len(recorded) == 3with pytest.raises(ValueError, match="'nope' is not installed"):set_session_backend("chat-a", "nope")@@ -227,6 +236,52 @@ def test_a_session_backend_switch_routes_that_session_only_and_global_persists(tmanager.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."""+ from agent.delegation_provider import DelegationProvider+ from agent.delegation_registry import _registry++ class Profiles(DelegationProvider):+ @property+ def name(self):+ return "probe-profiles"++ def task_parameters(self, config):+ return {"target": {"type": "string", "enum": ["work"]}}++ 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}}})+ profiles = Profiles()+ _registry.register(profiles)+ try:+ from agent.delegation_backends import set_session_backend+ from tools.delegate_tool import delegate_task++ assert "option" in _task_props(_definition())+ set_session_backend("chat-a", "probe-profiles")+ out = json.loads(delegate_task(tasks=[+ {"goal": "the quick thing", "option": "fast"},+ {"goal": "a plain task"},+ {"goal": "a work task", "target": "work"},+ ], parent_agent=_parent("chat-a")))+ refused, plain, work = out["results"]+ assert refused["status"] == "error" and refused["route"] == {"backend": "probe-profiles", "refused": True}+ 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. Start a new session with /new for a delegate_task tool "+ "that matches 'probe-profiles', or switch this session back with `/delegation probe-options`.")+ assert plain["status"] == work["status"] == "completed"+ assert [b["model"] for b in recorded] == ["profile-default-model", "work-model"]+ finally:+ _registry.restore_registration("probe-profiles", profiles, None)+ manager.unload()++def test_a_global_backend_switch_is_refused_on_a_managed_install(tmp_path, monkeypatch):"""Like every other config writer: a package-manager-managed install's config.yaml is never written."""home, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options"})diff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pyindex 494b11a7786..0f314c20af7 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -268,8 +268,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]) -> 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."""+ from agent.delegation_registry import _registry+ listed = ", ".join(f"'{name}'" for name in names)+ owners = sorted({other.name for other in _registry.list_providers() if other.name != provider.name+ and set(names) & set(_declared_parameters(other, config))})+ head = f"Task {index}: this session's delegation backend is '{provider.name}', which does not take {listed}"+ if owners:+ back = " or ".join(f"`/delegation {owner}`" for owner in owners)+ quoted = ", ".join(f"'{owner}'" for owner in owners)+ return (f"{head} (declared by {quoted}), so this task was not started. Start a "+ f"new session with /new for a delegate_task tool that matches '{provider.name}', or switch this "+ f"session back with {back}.")+ 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}, start a new session with /new for a "+ f"tool that matches '{provider.name}'.")++def _route_one(provider: DelegationProvider, declared: dict[str, dict[str, Any]], index: int,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))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])diff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.mdindex dc3d374c087..7a9718e7c7c 100644--- a/website/docs/developer-guide/delegation-provider-plugin.md+++ b/website/docs/developer-guide/delegation-provider-plugin.md@@ -128,7 +128,8 @@ A non-profile route without `fallback_providers` of its own gets `delegation.fal### Refusals are per task-A `DelegationRouteError` from `route_task`, a value outside your parameter's `enum`, an unknown+A `DelegationRouteError` from `route_task`, a parameter your backend did not declare, 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@@ -168,8 +169,18 @@ returns the chosen model id, or `None` when cancelled.`session_key` is the `session_key` a plugin command handler receives. A session switch decides routingfrom 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.+`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:++```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. Start a new session with /new for a delegate_task tool that+matches 'profile_routes', or switch this session back with `/delegation model_map`.+```++A parameter no installed backend declares is refused the same way, with "Resend it without ..." as the fix.## Prompt cachingdiff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex 5dc4f7aabfe..b2989c0cf8a 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -329,9 +329,9 @@ delegation: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.+**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. Without the plugin, `hermes config set delegation.backend default` restores the default.+**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 (`/new`, or `/delegation <backend>` back); 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 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.