The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(delegation): pluggable delegation providers
Teknium919322f6c3aa
diff --git a/agent/delegation_provider.py b/agent/delegation_provider.pynew file mode 100644index 00000000000..5565ece1f19--- /dev/null+++ b/agent/delegation_provider.py@@ -0,0 +1,90 @@+"""Delegation Provider ABC.++A delegation provider decides HOW one ``delegate_task`` task becomes a child run: which model,+provider, endpoint and reasoning effort the child uses, or which Hermes profile it runs as. It may+also add per-task parameters to the ``delegate_task`` schema (an enum of profile names, of titled+model options, ...). Providers register via :meth:`PluginContext.register_delegation_provider`;+``delegation.backend`` in config.yaml selects the active one (unset = ``default``, today's+behaviour). Core keeps the whole lifecycle (spawn, isolation, roles, depth, concurrency,+background units, stop fan-out, results, ``output_schema``, progress); a provider only answers+"which route does this task take".++Everything crossing this interface is plain JSON data (no live agent objects), so a provider runs+unchanged in-process and under ``plugins.isolation: host``.++Route vocabulary (:meth:`DelegationProvider.route_task` returns a dict with any of):++* ``model``, ``provider``, ``base_url``, ``api_key``, ``api_mode``, ``request_overrides``,+ ``reasoning_effort``, ``fallback_providers`` - shaped exactly like the ``delegation`` config+ section and resolved by the same credential resolver ``delegation.*`` uses (empty route = the+ child inherits the parent's route, like an empty ``delegation`` section).+* ``profile`` - the name of a Hermes profile. Core runs the child as that profile: its config,+ primary model and credentials, skills, ``SOUL.md`` and terminal policy, bound through the same+ scope helpers a multiplexed gateway uses for a routed turn. A profile route ignores the other+ route keys; the profile's own config decides them.+* ``label`` - short text shown with the child's progress and result (e.g. the option title).+"""++from __future__ import annotations++import abc+from typing import Any, Mapping++from agent.provider_base import ProviderBase++#: Per-task property names core owns. A provider-declared parameter with one of these names is+#: refused at schema-build time: plugins add parameters, they never redefine core ones, and the+#: raw route fields (``provider``/``model``/``base_url``/``api_key``) never become model-facing.+RESERVED_TASK_PARAMETERS = frozenset({+ "goal", "context", "output_schema", "images", "group", "role", "toolsets",+ "acp_command", "acp_args", "provider", "model", "base_url", "api_key", "api_mode",+})++#: Keys a route may carry; anything else in a provider's answer is ignored.+ROUTE_KEYS = frozenset({+ "model", "provider", "base_url", "api_key", "api_mode", "request_overrides",+ "reasoning_effort", "fallback_providers", "profile", "label",+})+++class DelegationRouteError(ValueError):+ """Raised by :meth:`DelegationProvider.route_task` to refuse a task; the message becomes the+ ``delegate_task`` tool error the model reads, so phrase it as an instruction."""+++class DelegationProvider(ProviderBase):+ """Abstract base class for a pluggable delegation strategy.++ :attr:`name` is the ``delegation.backend`` value. Every method receives ``config``, the+ ``delegation`` section of the active profile's config.yaml (read-only), so provider settings+ live next to the other delegation knobs (``delegation.model_map``, ``delegation.profiles``).+ """++ def is_available(self) -> bool:+ """Whether this provider can run here. MUST NOT make network calls; False -> ``default``."""+ return True++ def task_parameters(self, config: Mapping[str, Any]) -> dict[str, dict[str, Any]]:+ """Extra per-task JSON-schema properties, ``{name: schema}``, merged into+ ``delegate_task``'s ``tasks.items.properties``.++ Called when the tool definitions are built for a session, never mid-conversation, and the+ result must be deterministic for a given ``config`` (same input, same bytes): the schema+ is 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.+ """+ return {}++ def description(self, config: Mapping[str, Any]) -> str:+ """Optional guidance appended to the ``delegate_task`` description (same caching rule+ as :meth:`task_parameters`)."""+ return ""++ @abc.abstractmethod+ def route_task(self, task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:+ """Return the route for one task (vocabulary in the module docstring).++ ``task`` carries ``goal``, ``context``, ``index`` and the values the model supplied for+ this provider's :meth:`task_parameters` (absent when omitted). Raise+ :class:`DelegationRouteError` to refuse the task.+ """diff --git a/agent/delegation_registry.py b/agent/delegation_registry.pynew file mode 100644index 00000000000..8219df513e5--- /dev/null+++ b/agent/delegation_registry.py@@ -0,0 +1,74 @@+"""Delegation provider registry.++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.+"""++from __future__ import annotations++import logging+from typing import Any, Mapping, Optional++from agent.delegation_provider import DelegationProvider+from agent.provider_registry import ProviderRegistry, is_available_safe, lower_key++logger = logging.getLogger(__name__)++DEFAULT_BACKEND = "default"+++class DefaultDelegationProvider(DelegationProvider):+ """Today's strategy: every task takes the route the ``delegation`` section describes."""++ @property+ def name(self) -> str:+ return DEFAULT_BACKEND++ def route_task(self, task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:+ return dict(config)+++def _reject_builtin_collision(key: str) -> None:+ logger.warning("Delegation provider '%s' shadows the built-in strategy; registration ignored.", key)+++_registry: ProviderRegistry[DelegationProvider] = ProviderRegistry(+ label="Delegation", provider_cls=DelegationProvider, logger=logger, normalize=lower_key,+ builtin_names=frozenset({DEFAULT_BACKEND}), on_builtin_collision=_reject_builtin_collision,+)+_registry.export(globals())++_BUILTIN_DEFAULT = DefaultDelegationProvider()+_warned_fallbacks: set[str] = set()+++def configured_backend(config: Mapping[str, Any]) -> str:+ """``delegation.backend`` normalized; blank/non-string means ``default``."""+ raw = config.get("backend") if isinstance(config, Mapping) else None+ 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)+ if name == DEFAULT_BACKEND:+ 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_DEFAULTdiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex bd0cbc8302b..23e95e8fbf6 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1338,10 +1338,10 @@ DEFAULT_CONFIG = {# hindsight, supermemory, mem0, openviking, holographic). Empty = built-in only."provider": "",},- # Subagent delegation — override the provider:model used by delegate_task so children run on a- # cheaper/faster model. Uses the same runtime provider resolution as CLI/gateway startup, so- # every configured provider is supported.+ # Subagent delegation. `backend` = the strategy plugin routing each delegate_task task ("default": the keys+ # below, else the parent's route); the provider:model pin uses the CLI/gateway runtime provider resolution."delegation": {+ "backend": "default","model": "", # e.g. "google/gemini-3-flash-preview" (empty = inherit parent)"provider": "", # e.g. "openrouter" (empty = inherit parent provider + credentials)# Fallback chain for delegated children (same entry format as the top-level list).diff --git a/hermes_cli/plugin_isolation.py b/hermes_cli/plugin_isolation.pyindex 2d1497e49f2..e8d10ca251a 100644--- a/hermes_cli/plugin_isolation.py+++ b/hermes_cli/plugin_isolation.py@@ -63,6 +63,7 @@ HOST_OBJECT_BASES: dict[str, str] = {"register_secret_source": "agent.secret_sources.base:SecretSource","register_tts_provider": "agent.tts_provider:TTSProvider","register_transcription_provider": "agent.transcription_provider:TranscriptionProvider",+ "register_delegation_provider": "agent.delegation_provider:DelegationProvider","register_context_engine": "agent.context_engine:ContextEngine","register_context_reference": "agent.context_references:ContextReferenceProvider","register_memory_provider": "agent.memory_provider:MemoryProvider",diff --git a/hermes_cli/plugin_validate_private_imports.py b/hermes_cli/plugin_validate_private_imports.pyindex 93f0df56a32..1b2796470a5 100644--- a/hermes_cli/plugin_validate_private_imports.py+++ b/hermes_cli/plugin_validate_private_imports.py@@ -27,6 +27,7 @@ from hermes_cli.plugin_validate_core_override import _hermes_top_level, _python__PUBLIC = frozenset({# developer-guide / plugins docs"agent.account_usage", "agent.browser_provider", "agent.context_engine", "agent.credential_pool",+ "agent.delegation_provider","agent.image_gen_provider", "agent.memory_manager", "agent.memory_provider", "agent.secret_scope","agent.secret_sources.base", "agent.subagent_lifecycle", "agent.terminal_env_provider","agent.transports", "agent.transports.chat_completions", "agent.video_gen_provider",diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex b62729861a3..fa4138b32ba 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -58,6 +58,7 @@ from hermes_cli.plugins_dispatch import (is_valid_system_prompt_section_id, resolve_plugin_command_result,)from hermes_cli.plugins_ledger import PluginLedgerMixin, PluginRegistration+from hermes_cli.plugins_registrars import _NAME_NORMALIZERS, _SCOPED_PROVIDER_REGISTRARSfrom hermes_cli.plugins_state import (PluginState, _locked_plugin_state, _nested_plugin_mapping, _nested_plugin_value,_plugin_relative_segments, _plugin_settings_entry, save_plugin_setting,@@ -1009,60 +1010,8 @@ class PluginContext:from hermes_cli.plugins_content import register_automation_blueprint, register_skill# -- scoped provider registrars -------------------------------------------------------------------# Every ``register_<category>_provider`` shares one body (:meth:`PluginContext._register_scoped_provider`):-# type-check, register in the scope-keyed process-global registry, lease the slot so unload restores-# the displaced entry. Rows: (method, kind, registry module, base-class module:attr, label, docstring,-# options). ``normalize``: ``strip`` (default), ``lower`` (strip+lowercase) or ``None`` (raw name).-_SCOPED_PROVIDER_REGISTRARS: tuple[tuple[str, str, str, str, str, str, dict[str, Any]], ...] = (- ("register_image_gen_provider", "image_gen_provider", "agent.image_gen_registry",- "agent.image_gen_provider:ImageGenProvider", "image_gen provider",- "Register an :class:`agent.image_gen_provider.ImageGenProvider`; "- "``provider.name`` is matched by ``image_gen.provider``.", {"article": "an"}),- ("register_video_gen_provider", "video_gen_provider", "agent.video_gen_registry",- "agent.video_gen_provider:VideoGenProvider", "video_gen provider",- "Register an :class:`agent.video_gen_provider.VideoGenProvider`; "- "``provider.name`` is matched by ``video_gen.provider``.", {}),- ("register_web_search_provider", "web_search_provider", "agent.web_search_registry",- "agent.web_search_provider:WebSearchProvider", "web provider",- "Register an :class:`agent.web_search_provider.WebSearchProvider`; "- "``provider.name`` is matched by ``web.search_backend`` / ``web.extract_backend`` / ``web.backend``.",- {}),- ("register_browser_provider", "browser_provider", "agent.browser_registry",- "agent.browser_provider:BrowserProvider", "browser provider",- "Register an :class:`agent.browser_provider.BrowserProvider`; "- "``provider.name`` is matched by ``browser.cloud_provider`` (consulted by "- "``tools.browser_tool_cloud._get_cloud_provider``).", {}),- ("register_terminal_environment_provider", "terminal_environment_provider",- "agent.terminal_env_registry", "agent.terminal_env_provider:TerminalEnvironmentProvider",- "terminal environment provider",- "Register a :class:`agent.terminal_env_provider.TerminalEnvironmentProvider`; ``provider.name`` "- "is matched by ``terminal.backend`` when no built-in backend has that name. Built-in names (local, "- "docker, modal, daytona, vercel_sandbox, ssh) are rejected — plugins never shadow "- "in-tree backends.",- {"normalize": "lower", "reject_message": "Plugin '%s' terminal environment provider rejected: %s"}),- ("register_secret_source", "secret_source", "agent.secret_sources.registry",- "agent.secret_sources.base:SecretSource", "secret source",- "Register a :class:`agent.secret_sources.base.SecretSource`, run by ``load_hermes_dotenv()`` "- "(after ``~/.hermes/.env``, before credentials are read) when ``secrets.<name>`` is enabled. The "- "orchestrator owns ordering/precedence/provenance; the source only fetches. Since dotenv usually "- "loads before discovery, the manager re-pulls enabled plugin sources afterwards.",- {"normalize": None, "register": "register_source", "param": "source"}),- ("register_tts_provider", "tts_provider", "agent.tts_registry",- "agent.tts_provider:TTSProvider", "TTS provider",- "Register an :class:`agent.tts_provider.TTSProvider`; ``provider.name`` is matched by "- "``tts.provider`` unless it is a built-in name (rejected with a warning) or a "- "``tts.providers.<name>: type: command`` entry shares it (command-providers win).",- {"normalize": "lower"}),- ("register_transcription_provider", "transcription_provider", "agent.transcription_registry",- "agent.transcription_provider:TranscriptionProvider", "transcription provider",- "Register an :class:`agent.transcription_provider.TranscriptionProvider`; ``provider.name`` is "- "matched by ``stt.provider`` unless it is a built-in name (rejected) or a ``stt.providers.<name>: "- "type: command`` entry shares it (command-providers win).", {"normalize": "lower"}),-)+# One generated ``register_<category>_provider`` method per row of plugins_registrars.py's table.-_NAME_NORMALIZERS: dict[Optional[str], Optional[Callable[[str], str]]] = {- "strip": lambda n: n.strip(), "lower": lambda n: n.strip().lower(), None: None,-}def _make_scoped_provider_registrar(method_name, kind, registry_mod, base_ref, label, doc, options):diff --git a/hermes_cli/plugins_registrars.py b/hermes_cli/plugins_registrars.pynew file mode 100644index 00000000000..e3c4f4d6b4e--- /dev/null+++ b/hermes_cli/plugins_registrars.py@@ -0,0 +1,70 @@+"""The ``register_<category>_provider`` table behind :class:`hermes_cli.plugins.PluginContext`.++Every ``register_<category>_provider`` shares one body (:meth:`PluginContext._register_scoped_provider`):+type-check, register in the scope-keyed process-global registry, lease the slot so unload restores+the displaced entry. ``hermes_cli.plugins`` generates one ctx method per row. Rows: (method, kind,+registry module, base-class module:attr, label, docstring, options). ``normalize``: ``strip``+(default), ``lower`` (strip+lowercase) or ``None`` (raw name). Object-taking rows also need a+``plugin_isolation.HOST_OBJECT_BASES`` entry so the provider works under ``plugins.isolation: host``.+"""++from __future__ import annotations++from typing import Any, Callable, Optional++_SCOPED_PROVIDER_REGISTRARS: tuple[tuple[str, str, str, str, str, str, dict[str, Any]], ...] = (+ ("register_image_gen_provider", "image_gen_provider", "agent.image_gen_registry",+ "agent.image_gen_provider:ImageGenProvider", "image_gen provider",+ "Register an :class:`agent.image_gen_provider.ImageGenProvider`; "+ "``provider.name`` is matched by ``image_gen.provider``.", {"article": "an"}),+ ("register_video_gen_provider", "video_gen_provider", "agent.video_gen_registry",+ "agent.video_gen_provider:VideoGenProvider", "video_gen provider",+ "Register an :class:`agent.video_gen_provider.VideoGenProvider`; "+ "``provider.name`` is matched by ``video_gen.provider``.", {}),+ ("register_web_search_provider", "web_search_provider", "agent.web_search_registry",+ "agent.web_search_provider:WebSearchProvider", "web provider",+ "Register an :class:`agent.web_search_provider.WebSearchProvider`; "+ "``provider.name`` is matched by ``web.search_backend`` / ``web.extract_backend`` / ``web.backend``.",+ {}),+ ("register_browser_provider", "browser_provider", "agent.browser_registry",+ "agent.browser_provider:BrowserProvider", "browser provider",+ "Register an :class:`agent.browser_provider.BrowserProvider`; "+ "``provider.name`` is matched by ``browser.cloud_provider`` (consulted by "+ "``tools.browser_tool_cloud._get_cloud_provider``).", {}),+ ("register_terminal_environment_provider", "terminal_environment_provider",+ "agent.terminal_env_registry", "agent.terminal_env_provider:TerminalEnvironmentProvider",+ "terminal environment provider",+ "Register a :class:`agent.terminal_env_provider.TerminalEnvironmentProvider`; ``provider.name`` "+ "is matched by ``terminal.backend`` when no built-in backend has that name. Built-in names (local, "+ "docker, modal, daytona, vercel_sandbox, ssh) are rejected — plugins never shadow "+ "in-tree backends.",+ {"normalize": "lower", "reject_message": "Plugin '%s' terminal environment provider rejected: %s"}),+ ("register_secret_source", "secret_source", "agent.secret_sources.registry",+ "agent.secret_sources.base:SecretSource", "secret source",+ "Register a :class:`agent.secret_sources.base.SecretSource`, run by ``load_hermes_dotenv()`` "+ "(after ``~/.hermes/.env``, before credentials are read) when ``secrets.<name>`` is enabled. The "+ "orchestrator owns ordering/precedence/provenance; the source only fetches. Since dotenv usually "+ "loads before discovery, the manager re-pulls enabled plugin sources afterwards.",+ {"normalize": None, "register": "register_source", "param": "source"}),+ ("register_tts_provider", "tts_provider", "agent.tts_registry",+ "agent.tts_provider:TTSProvider", "TTS provider",+ "Register an :class:`agent.tts_provider.TTSProvider`; ``provider.name`` is matched by "+ "``tts.provider`` unless it is a built-in name (rejected with a warning) or a "+ "``tts.providers.<name>: type: command`` entry shares it (command-providers win).",+ {"normalize": "lower"}),+ ("register_transcription_provider", "transcription_provider", "agent.transcription_registry",+ "agent.transcription_provider:TranscriptionProvider", "transcription provider",+ "Register an :class:`agent.transcription_provider.TranscriptionProvider`; ``provider.name`` is "+ "matched by ``stt.provider`` unless it is a built-in name (rejected) or a ``stt.providers.<name>: "+ "type: command`` entry shares it (command-providers win).", {"normalize": "lower"}),+ ("register_delegation_provider", "delegation_provider", "agent.delegation_registry",+ "agent.delegation_provider:DelegationProvider", "delegation provider",+ "Register an :class:`agent.delegation_provider.DelegationProvider`; ``provider.name`` is matched by "+ "``delegation.backend``. It decides each ``delegate_task`` task's route (model/provider or a Hermes "+ "profile) and may add per-task schema parameters; core keeps the subagent lifecycle.",+ {"normalize": "lower"}),+)++_NAME_NORMALIZERS: dict[Optional[str], Optional[Callable[[str], str]]] = {+ "strip": lambda n: n.strip(), "lower": lambda n: n.strip().lower(), None: None,+}diff --git a/tests/hermes_cli/test_plugin_host_delegation.py b/tests/hermes_cli/test_plugin_host_delegation.pynew file mode 100644index 00000000000..89e5c55875f--- /dev/null+++ b/tests/hermes_cli/test_plugin_host_delegation.py@@ -0,0 +1,74 @@+"""plugins.isolation: host — a delegation provider plugin runs out of process and still routes tasks."""++import json+import os+import sys++import hermes_yaml as yaml+import pytest++from hermes_cli import plugins as plugins_mod+from hermes_cli.plugins import PluginManager++HOSTED_PROVIDER = '''+import os+from agent.delegation_provider import DelegationProvider, DelegationRouteError++class Hosted(DelegationProvider):+ @property+ def name(self):+ return "hosted-map"++ def task_parameters(self, config):+ return {"option": {"type": "string", "enum": ["a", "b"], "description": f"pid {os.getpid()}"}}++ def route_task(self, task, config):+ if task.get("option") == "b":+ raise DelegationRouteError("b is closed")+ return {"model": f"model-{task.get('option')}-{os.getpid()}", "label": task.get("option")}++def register(ctx):+ ctx.register_delegation_provider(Hosted())+'''++[email protected]("posix") # the host is a child process+def test_hosted_delegation_provider_extends_schema_and_routes_from_the_host(tmp_path, monkeypatch):+ from agent.delegation_provider import DelegationProvider+ from agent.delegation_registry import get_active_provider+ from tools.delegate_tool_routes import resolve_task_routes, schema_extension++ home = tmp_path / ".hermes"+ plugin_dir = home / "plugins" / "hosted-map"+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump({"name": "hosted-map", "version": "1.0"}), encoding="utf-8")+ (plugin_dir / "__init__.py").write_text(HOSTED_PROVIDER, encoding="utf-8")+ (home / "config.yaml").write_text(yaml.safe_dump(+ {"plugins": {"enabled": ["hosted-map"], "isolation": "host"}}), encoding="utf-8")+ empty_bundled = tmp_path / "bundled"+ empty_bundled.mkdir()+ monkeypatch.setenv("HOME", str(tmp_path / "os-home"))+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: empty_bundled)+ manager = PluginManager()+ manager.discover_and_load()+ try:+ assert manager._plugins["hosted-map"].error is None+ assert not any("hosted-map" in name or "hosted_map" in name for name in sys.modules)+ config = {"backend": "hosted-map"}+ provider = get_active_provider(config)+ assert isinstance(provider, DelegationProvider) and provider.name == "hosted-map"++ params, _ = schema_extension(config)+ host_pid = int(params["option"]["description"].split()[-1])+ assert params["option"]["enum"] == ["a", "b"] and host_pid != os.getpid()++ routes, err = resolve_task_routes([{"goal": "route me through the host", "option": "a"}], config, None)+ assert err is None+ assert (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+ assert json.dumps(params) == json.dumps(schema_extension(config)[0])+ finally:+ manager.unload()+ manager._plugin_host().shutdown()diff --git a/tests/tools/test_delegation_backends.py b/tests/tools/test_delegation_backends.pynew file mode 100644index 00000000000..c38aeedef3c--- /dev/null+++ b/tests/tools/test_delegation_backends.py@@ -0,0 +1,209 @@+"""delegation.backend: pluggable delegation providers decide each delegate_task task's route.++Real discovery through PluginManager against a temp HERMES_HOME, real delegate_task, real credential+resolution; only child construction/run are stubbed where a test reads what they were handed.+"""++import json+import types++import hermes_yaml as yaml+import pytest++from hermes_cli import plugins as plugins_mod+from hermes_cli.plugins import PluginManager++PROBE_PLUGIN = '''+from agent.delegation_provider import DelegationProvider, DelegationRouteError++class Options(DelegationProvider):+ @property+ def name(self):+ return "probe-options"++ def task_parameters(self, config):+ opts = config.get("probe_options") or []+ return {"option": {"type": "string", "enum": [o["name"] for o in opts],+ "description": "; ".join(f"{o['name']}: {o['description']}" for o in opts)}}++ def description(self, config):+ return "Pick an `option` per task."++ def route_task(self, task, config):+ if task.get("option") == "refused":+ raise DelegationRouteError("that option is reserved for humans")+ for o in config.get("probe_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"]}+ return dict(config)++def register(ctx):+ ctx.register_delegation_provider(Options())+'''++OPTIONS = [+ {"name": "fast", "description": "cheap and quick", "base_url": "http://127.0.0.1:9/v1", "model": "fast-model"},+ {"name": "deep", "description": "slow and careful", "base_url": "http://127.0.0.1:9/v1", "model": "deep-model",+ "reasoning_effort": "high"},+ {"name": "refused", "description": "never allowed", "base_url": "http://127.0.0.1:9/v1", "model": "x"},+]+++def _home(tmp_path, monkeypatch, delegation: dict, plugins=("probe-options",)):+ home = tmp_path / ".hermes"+ 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"}), encoding="utf-8")+ (plugin_dir / "__init__.py").write_text(PROBE_PLUGIN, encoding="utf-8")+ (home / "config.yaml").write_text(yaml.safe_dump(+ {"plugins": {"enabled": list(plugins)}, "delegation": delegation}), encoding="utf-8")+ empty_bundled = tmp_path / "bundled"+ empty_bundled.mkdir()+ monkeypatch.setenv("HOME", str(tmp_path / "os-home"))+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: empty_bundled)+ manager = PluginManager()+ manager.discover_and_load()+ return home, manager+++def _definition():+ from tools.registry import registry+ return registry.get_definitions({"delegate_task"})[0]["function"]+++def _task_props(definition):+ return definition["parameters"]["properties"]["tasks"]["items"]["properties"]+++def recorded(monkeypatch):+ """Record what each child is built with; children 'complete' immediately."""+ from tools import delegate_tool as dt+ built = []++ def build(**kwargs):+ built.append(kwargs)+ return types.SimpleNamespace(tool_progress_callback=None, model=kwargs.get("model"))++ monkeypatch.setattr(dt, "_build_child_preserving_parent_tools", build)+ monkeypatch.setattr(dt, "_run_single_child", lambda task_index, goal, child=None, parent_agent=None, **kw: {+ "task_index": task_index, "status": "completed", "summary": "ok", "api_calls": 1, "duration_seconds": 0})+ return built+++def _parent():+ return types.SimpleNamespace(session_id="root", model="parent-model", provider="openrouter",+ tool_progress_callback=None, _delegate_spinner=None, request_overrides={},+ _safe_print=lambda line: None)+++def test_selected_plugin_backend_extends_schema_and_routes_each_task(tmp_path, monkeypatch, recorded):+ _, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options", "probe_options": OPTIONS})+ try:+ from agent.delegation_registry import get_active_provider+ from tools.delegate_tool import delegate_task+ from tools.delegate_tool_config import _load_config++ assert get_active_provider(_load_config()).name == "probe-options"+ definition = _definition()+ option = _task_props(definition)["option"]+ assert option["enum"] == ["fast", "deep", "refused"]+ assert "deep: slow and careful" in option["description"]+ assert definition["description"].endswith("Pick an `option` per task.")+ # Byte-stable for a session: the same config yields the same definition.+ assert json.dumps(_definition()) == json.dumps(definition)++ out = json.loads(delegate_task(tasks=[+ {"goal": "summarize the quick thing", "option": "fast"},+ {"goal": "think hard about the slow thing", "option": "deep"},+ {"goal": "no option: plain delegation config"},+ ], parent_agent=_parent()))+ assert [r["status"] for r in out["results"]] == ["completed"] * 3+ fast, deep, plain = recorded+ assert (fast["model"], fast["override_base_url"], fast["override_api_key"]) == (+ "fast-model", "http://127.0.0.1:9/v1", "k-fast")+ assert (deep["model"], deep["override_reasoning_effort"]) == ("deep-model", "high")+ # The no-option task falls back to the delegation section, i.e. inherit the parent.+ assert plain["model"] is None and plain["override_provider"] is None and plain["profile_home"] is None+ finally:+ manager.unload()+++def test_model_supplied_parameters_are_enforced_before_any_child_is_built(tmp_path, monkeypatch, recorded):+ _, manager = _home(tmp_path, monkeypatch, {"backend": "probe-options", "probe_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"}],+ 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+ finally:+ 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."""+ from tools.delegate_tool import delegate_task++ definitions = []+ 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=())+ try:+ definitions.append(json.dumps(_definition()))+ 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+++def test_plugin_parameters_never_redefine_core_or_route_fields(tmp_path, monkeypatch):+ from agent.delegation_provider import DelegationProvider+ from tools.delegate_tool_routes import schema_extension++ class Greedy(DelegationProvider):+ @property+ def name(self):+ return "greedy"++ def task_parameters(self, config):+ return {"goal": {"type": "string"}, "model": {"type": "string"}, "api_key": {"type": "string"},+ "tier": {"type": "string", "enum": ["a", "b"]}}++ def route_task(self, task, config):+ return {}++ from agent.delegation_registry import _registry++ greedy = Greedy()+ _registry.register(greedy)+ try:+ params, _ = schema_extension({"backend": "greedy"})+ assert set(params) == {"tier"}+ finally:+ _registry.restore_registration("greedy", greedy, None)+++def test_backend_key_reads_through_the_real_loader(tmp_path, monkeypatch):+ """``delegation.backend`` defaults to ``default`` and a configured value reaches the registry."""+ from agent.delegation_registry import configured_backend+ from hermes_cli.config import load_config+ from tools.delegate_tool_config import _load_config++ _, manager = _home(tmp_path / "unset", monkeypatch, {}, plugins=())+ try:+ assert load_config()["delegation"]["backend"] == "default"+ assert configured_backend(_load_config()) == "default"+ finally:+ manager.unload()+ _, manager = _home(tmp_path / "set", monkeypatch, {"backend": " Probe-Options "})+ try:+ assert configured_backend(_load_config()) == "probe-options"+ finally:+ manager.unload()diff --git a/tests/tools/test_delegation_profile_route.py b/tests/tools/test_delegation_profile_route.pynew file mode 100644index 00000000000..55a70ed0ca5--- /dev/null+++ b/tests/tools/test_delegation_profile_route.py@@ -0,0 +1,135 @@+"""A profile route runs the child AS that profile: its config, model, credentials and SOUL, never the+launching profile's — through the same scope binding a multiplexed gateway uses for a routed turn."""++import json+import threading+from unittest.mock import MagicMock, patch++import hermes_yaml as yaml+import pytest+++def _write_profile(home, *, host, model, key, secret, effort, soul=None):+ # A hosted (non-loopback) endpoint: the key must come from the profile's own secrets.+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text(yaml.safe_dump({+ "model": {"provider": "custom", "base_url": f"https://{host}/v1", "default": model, "key_env": "PROFILE_KEY"},+ "agent": {"reasoning_effort": effort},+ }), encoding="utf-8")+ (home / ".env").write_text(f"PROFILE_KEY={key}\nPROBE_SECRET={secret}\n", encoding="utf-8")+ if soul:+ (home / "SOUL.md").write_text(soul, encoding="utf-8")+++def two_profiles(tmp_path, monkeypatch):+ launch = tmp_path / "os-home" / ".hermes"+ _write_profile(launch, host="launch.invalid", model="launch-model", key="launch-key", secret="launch-secret",+ effort="medium")+ coder = launch / "profiles" / "coder"+ _write_profile(coder, host="coder.invalid", model="coder-model", key="coder-key", secret="coder-secret",+ effort="low", soul="I am the coder profile.")+ monkeypatch.setenv("HOME", str(tmp_path / "os-home"))+ monkeypatch.setenv("HERMES_HOME", str(launch))+ # The launch profile's secrets live in the process env, as after a normal dotenv load.+ monkeypatch.setenv("PROFILE_KEY", "launch-key")+ monkeypatch.setenv("PROBE_SECRET", "launch-secret")+ return launch, coder+++def _snapshot():+ from agent.secret_scope import get_secret+ from hermes_cli.config import load_config_readonly+ from hermes_constants import get_hermes_home+ return {"home": str(get_hermes_home()), "secret": get_secret("PROBE_SECRET"),+ "model": load_config_readonly()["model"]["default"]}+++def _parent():+ parent = MagicMock()+ parent.base_url, parent.api_key, parent.provider = "https://openrouter.ai/api/v1", "parent-key", "openrouter"+ parent.api_mode, parent.model, parent.platform = "chat_completions", "parent-model", "cli"+ parent.providers_allowed = parent.providers_ignored = parent.providers_order = parent.provider_sort = None+ parent._session_db, parent._delegate_depth, parent._active_children = None, 0, []+ parent._active_children_lock = threading.Lock()+ parent._print_fn = parent.tool_progress_callback = parent.thinking_callback = None+ parent._credential_pool = MagicMock(name="launch-pool")+ return parent+++def test_profile_route_resolves_the_target_profiles_model_and_key(two_profiles):+ from tools.delegate_tool_routes import _route_to_task_route++ launch, coder = two_profiles+ route = _route_to_task_route({"profile": "coder", "label": "coder"}, _parent(), {})+ assert route.profile_home == coder and route.label == "coder"+ assert (route.creds["model"], route.creds["base_url"], route.creds["api_key"]) == (+ "coder-model", "https://coder.invalid/v1", "coder-key")+ assert route.reasoning_effort == "low"+ assert _snapshot() == {"home": str(launch), "secret": "launch-secret", "model": "launch-model"}+++def test_unknown_profile_is_refused_with_an_instruction(two_profiles):+ from agent.delegation_provider import DelegationRouteError+ from tools.delegate_tool_routes import _route_to_task_route++ with pytest.raises(DelegationRouteError, match="hermes profile list"):+ _route_to_task_route({"profile": "nobody"}, _parent(), {})+++def test_child_is_built_and_converses_inside_the_target_profile_scope(two_profiles):+ from tools.delegate_tool import _build_child_agent, _route_overrides+ from tools.delegate_tool_child_run import _ChildRun+ from tools.delegate_tool_routes import _route_to_task_route++ launch, coder = two_profiles+ parent = _parent()+ route = _route_to_task_route({"profile": "coder"}, parent, {})+ seen = {}++ def construct(**kwargs):+ seen["built"] = {**_snapshot(), **{k: kwargs.get(k) for k in ("model", "base_url", "api_key")},+ "soul": kwargs.get("load_soul_identity")}+ return MagicMock(session_id="child-1")++ with patch("run_agent.AIAgent", side_effect=construct):+ child = _build_child_agent(task_index=0, goal="work as coder", context=None, toolsets=None,+ model=route.creds["model"], max_iterations=5, task_count=1,+ parent_agent=parent, **_route_overrides(route))+ assert seen["built"] == {"home": str(coder), "secret": "coder-secret", "model": "coder-model",+ "base_url": "https://coder.invalid/v1", "api_key": "coder-key",+ "soul": True}+ assert child._credential_pool is not parent._credential_pool # never the launch profile's pool+ assert _snapshot()["secret"] == "launch-secret"++ class _Child:+ provider, model, _delegate_profile_home = "custom", "coder-model", coder++ def run_conversation(self, user_message, **kw):+ from agent.prompt_builder import load_soul_md+ seen["ran"] = {**_snapshot(), "soul": load_soul_md()}+ return {"final_response": "ok", "completed": True}++ class _Parent:+ _current_task_id = None++ run = _ChildRun(_Child(), _Parent(), 0, "work as coder", None, None)+ with patch("tools.delegate_tool_child_run._create_isolated_worktree", return_value=None):+ run.seed_workspace()+ result, failure, _ = run.await_child()+ assert failure is None and result["final_response"] == "ok"+ assert seen["ran"]["home"] == str(coder) and seen["ran"]["secret"] == "coder-secret"+ assert seen["ran"]["model"] == "coder-model" and "coder profile" in (seen["ran"]["soul"] or "")+ assert _snapshot() == {"home": str(launch), "secret": "launch-secret", "model": "launch-model"}+++def test_secret_missing_from_target_profile_never_falls_back_to_the_launch_env(two_profiles):+ from agent.secret_scope import get_secret+ from tools.delegate_tool_routes import delegated_profile_scope++ _, coder = two_profiles+ (coder / ".env").write_text("PROFILE_KEY=coder-key\n", encoding="utf-8")+ with delegated_profile_scope(coder):+ assert get_secret("PROBE_SECRET") is None # launch value sits in os.environ; never borrowed+ assert get_secret("PROBE_SECRET") == "launch-secret"+ assert json.loads(json.dumps(_snapshot()))["model"] == "launch-model"diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex e26a07686b8..c7861541195 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -137,7 +137,11 @@ no `delegate_task`, `clarify`, `memory`, `send_message`, `cronjob`; keeps `execu`orchestrator` (keeps `delegate_task`; gated by `delegation.orchestrator_enabled`, bounded by`delegation.max_spawn_depth`, default 2). Config knobs under `delegation:`:`max_concurrent_children, independent_completions, max_spawn_depth, child_timeout_seconds, orchestrator_enabled,-subagent_auto_approve, inherit_mcp_toolsets, max_iterations`. **Child processes:** a child's background+subagent_auto_approve, inherit_mcp_toolsets, max_iterations, backend`. **Routes:** `delegation.backend` picks a+delegation provider (`agent/delegation_provider.py`, `ctx.register_delegation_provider`) that answers each task's route+(`tools/delegate_tool_routes.py`: model/provider fields resolved like the `delegation` section, or `profile` → the child+is built 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 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 56c58a154b4..7f476c123de 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -224,12 +224,18 @@ def _build_child_agent(routing_cfg: Optional[dict[str, Any]] = None,# Legacy; accepted for wire compat but ignored (capability is depth-derived).role: str = "leaf",+ # Per-task route from the delegation provider (tools/delegate_tool_routes.py): a reasoning+ # effort that beats delegation.reasoning_effort, and the profile home the child runs as.+ override_reasoning_effort: Any = None,+ profile_home: Optional[Path] = None,):"""Build (don't run) a child AIAgent on the main thread. override_* (from delegation config) replace parent- inheritance so children can run on a different provider:model pair."""+ inheritance so children can run on a different provider:model pair. ``profile_home`` builds (and later runs,+ see ``_ChildRun.await_child``) the child inside that profile's scope; it never shares the parent's pool."""import uuid as _uuidfrom run_agent import AIAgentfrom agent.delegation_context import delegated_child_context+ from tools.delegate_tool_routes import delegated_profile_scope# Role is depth-derived: a child may delegate iff the kill switch is on and# depth budget remains below max_spawn_depth. The `role` arg is ignored.child_depth = getattr(parent_agent, "_delegate_depth", 0) + 1@@ -262,45 +268,54 @@ def _build_child_agent(depth=max(0, child_depth - 1), # 0 = first-level child for the UImodel=model or getattr(parent_agent, "model", None), toolsets=child_toolsets, session_ref=child_session_ref,)- rt = _resolve_child_runtime(- parent_agent, delegation_cfg, parent_api_key, model=model, override_provider=override_provider,- override_base_url=override_base_url, override_api_key=override_api_key, override_api_mode=override_api_mode,- override_acp_command=override_acp_command,- override_acp_args=override_acp_args,- routing_cfg=routing_cfg,- )- if override_request_overrides is not None:- # honored whenever set, incl. the inherit branch where- # _resolve_delegation_credentials already merged OVER the parent's- request_overrides = dict(override_request_overrides)- else:- request_overrides = {} if override_provider else dict(getattr(parent_agent, "request_overrides", {}) or {})- parent_sid = getattr(parent_agent, "session_id", None)- child_session_db = _open_child_session_db(parent_agent)- with delegated_child_context():- try:- child = AIAgent(- **rt, max_iterations=max_iterations, prefill_messages=getattr(parent_agent, "prefill_messages", None),- enabled_toolsets=child_toolsets, disabled_toolsets=child_disabled_toolsets, quiet_mode=True,- ephemeral_system_prompt=child_prompt, log_prefix=f"[subagent-{task_index}]", platform="subagent",- side_agent=True,- skip_context_files=True, skip_memory=True, clarify_callback=None,- thinking_callback=(- (lambda text: _safe_progress(child_progress_cb, "_thinking", text) if text else None)- if child_progress_cb else None- ),- session_db=child_session_db, parent_session_id=parent_sid, request_overrides=request_overrides,- session_id=getattr(child_session_db, "reserved_session_id", None),- tool_progress_callback=child_progress_cb,- iteration_budget=None, # fresh budget per subagent- )- except BaseException:- # No child close() will ever run: release the dedicated handle here.- if child_session_db is not None:- with _quiet(None):- from hermes_state_registry import release_or_close- release_or_close(child_session_db)- raise+ with delegated_profile_scope(profile_home):+ rt = _resolve_child_runtime(+ parent_agent, delegation_cfg, parent_api_key, model=model, override_provider=override_provider,+ override_base_url=override_base_url, override_api_key=override_api_key, override_api_mode=override_api_mode,+ override_acp_command=override_acp_command,+ override_acp_args=override_acp_args,+ routing_cfg=routing_cfg, override_reasoning_effort=override_reasoning_effort,+ )+ if override_request_overrides is not None:+ # honored whenever set, incl. the inherit branch where+ # _resolve_delegation_credentials already merged OVER the parent's+ request_overrides = dict(override_request_overrides)+ else:+ request_overrides = {} if override_provider else dict(getattr(parent_agent, "request_overrides", {}) or {})+ parent_sid = getattr(parent_agent, "session_id", None)+ child_session_db = _open_child_session_db(parent_agent)+ with delegated_child_context():+ try:+ child = AIAgent(+ **rt, max_iterations=max_iterations, prefill_messages=getattr(parent_agent, "prefill_messages", None),+ enabled_toolsets=child_toolsets, disabled_toolsets=child_disabled_toolsets, quiet_mode=True,+ ephemeral_system_prompt=child_prompt, log_prefix=f"[subagent-{task_index}]", platform="subagent",+ side_agent=True,+ skip_context_files=True, skip_memory=True, clarify_callback=None,+ thinking_callback=(+ (lambda text: _safe_progress(child_progress_cb, "_thinking", text) if text else None)+ if child_progress_cb else None+ ),+ session_db=child_session_db, parent_session_id=parent_sid, request_overrides=request_overrides,+ session_id=getattr(child_session_db, "reserved_session_id", None),+ tool_progress_callback=child_progress_cb,+ iteration_budget=None, # fresh budget per subagent+ # A profile route carries that profile's identity (its SOUL.md under the bound home).+ **({"load_soul_identity": True} if profile_home is not None else {}),+ )+ except BaseException:+ # No child close() will ever run: release the dedicated handle here.+ if child_session_db is not None:+ with _quiet(None):+ from hermes_state_registry import release_or_close+ release_or_close(child_session_db)+ raise+ # Shared pool lets children rotate credentials on rate limits. A profile child loads ITS profile's pool+ # (inside the scope) and never shares the launching parent's.+ child_pool = _resolve_child_credential_pool(+ rt["provider"], None if profile_home is not None else parent_agent, rt["base_url"],+ effective_requested_provider=rt.get("requested_provider"),+ )child._print_fn = getattr(parent_agent, "_print_fn", None)_apply_child_cache_ttl(child)if child_session_db is not None:@@ -322,10 +337,7 @@ def _build_child_agent(# parent delete orphans them (mirrors /branch's ``_branched_from``).if parent_sid and getattr(child, "_session_init_model_config", None) is not None:child._session_init_model_config["_delegate_from"] = parent_sid- # Shared pool lets children rotate credentials on rate limits.- child_pool = _resolve_child_credential_pool(- rt["provider"], parent_agent, rt["base_url"], effective_requested_provider=rt.get("requested_provider"),- )+ child._delegate_profile_home = profile_home # _ChildRun.await_child runs the conversation in this scopeif child_pool is not None:child._credential_pool = child_pool@@ -421,18 +433,26 @@ def _credential_overrides(creds: dict[str, Any], routing_cfg: dict[str, Any]) ->}+def _route_overrides(route: Any) -> dict[str, Any]:+ """``_build_child_agent`` kwargs for one task route (``tools.delegate_tool_routes.TaskRoute``)."""+ return {+ **_credential_overrides(route.creds, route.routing_cfg),+ "override_reasoning_effort": route.reasoning_effort, "profile_home": route.profile_home,+ }++def _build_children(- task_list: list[dict[str, Any]], task_schemas: list[Optional[dict[str, Any]]], creds: dict[str, Any], *,- top_role: str, max_iterations: int, parent_agent, routing_cfg: dict[str, Any],+ task_list: list[dict[str, Any]], task_schemas: list[Optional[dict[str, Any]]], routes: list[Any], *,+ top_role: str, max_iterations: int, parent_agent,live_deleg_id: Optional[str], live_writers: list, task_images: Optional[list[Optional[list[str]]]] = None,) -> tuple[list[tuple], Optional[str]]:- """Build every child on the main thread (construction is not thread-safe);+ """Build every child on the main thread (construction is not thread-safe), each on its task's route;``(children, None)`` or ``([], error)`` on an explicit-pin preflight failure."""from tools.delegation_live_log import wrap_progress_callbackfrom tools.delegation_output_schema import append_output_contract- overrides = _credential_overrides(creds, routing_cfg)children = []for i, t in enumerate(task_list):+ route = routes[i]_task_schema = task_schemas[i] if i < len(task_schemas) else None_child_context = t.get("context")if _task_schema is not None:@@ -441,8 +461,8 @@ def _build_children(child = _build_child_preserving_parent_tools(task_index=i, goal=t["goal"], context=_child_context,toolsets=None, # always inherit the parent's toolsets- model=creds["model"], max_iterations=max_iterations, task_count=len(task_list),- parent_agent=parent_agent, role=_normalize_role(t.get("role") or top_role), **overrides,+ model=route.creds["model"], max_iterations=max_iterations, task_count=len(task_list),+ parent_agent=parent_agent, role=_normalize_role(t.get("role") or top_role), **_route_overrides(route),)except ValueError as exc:# An owner refusal can land mid-batch: the siblings built so far hold reservations.@@ -464,6 +484,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.labelif live_deleg_id:child._delegation_id = live_deleg_id_ident_ref = getattr(child, "_progress_identity_ref", None)@@ -473,6 +495,20 @@ def _build_children(return children, None+def _routes_for(task_list: list[dict[str, Any]], cfg: dict[str, Any], credentials_cfg: Optional[dict[str, Any]],+ parent_agent: Any) -> tuple[list[Any], Optional[str]]:+ """Per-task routes: an internal caller's explicit ``credentials_cfg`` (e.g. /review → auxiliary.review) owns+ every task's route; otherwise the active delegation provider decides each one."""+ from tools.delegate_tool_routes import resolve_task_routes, route_for_config+ if credentials_cfg is None:+ return resolve_task_routes(task_list, cfg, parent_agent)+ try:+ route = route_for_config(credentials_cfg, parent_agent)+ except ValueError as exc:+ return [], str(exc)+ return [route] * len(task_list), None++def _oneshot_spawn_budget(parent_agent: Any, requested: int) -> Optional[str]:"""Charge *requested* children against the finite one-shot session's total (delegation.oneshot_max_children);the error text tells the model to do the work inline. Interactive and gateway sessions are never charged."""@@ -543,24 +579,23 @@ def delegate_task("delegate_task: ignoring caller-supplied max_iterations=%s; using delegation.max_iterations=%s from config",max_iterations, default_max_iter,)- # credentials_cfg (internal callers only, e.g. /review → auxiliary.review) is- # a per-call routing owner shaped like the delegation config section. Keep- # the route and its fallback policy together through child construction.- routing_cfg = credentials_cfg if credentials_cfg is not None else cfg- try:- creds = _resolve_delegation_credentials(routing_cfg, parent_agent)- except ValueError as exc:- # Explicit-pin preflight failures (e.g. pinned delegation.command missing from PATH) refuse the- # spawn loudly (#80450).- return tool_error(str(exc))max_children = _get_max_concurrent_children()task_list, err = _normalize_task_list(goal, context, tasks, output_schema, top_role, max_children)if not err:task_schemas, err = _coerce_task_schemas(task_list, output_schema)if not err:task_images, err = _coerce_task_images(task_list, images)+ if not err:+ # One route per task from the active delegation provider (delegation.backend), or from credentials_cfg+ # (internal callers only, e.g. /review → auxiliary.review: a per-call routing owner shaped like the+ # delegation section, kept together with its fallback policy through child construction). Explicit-pin+ # preflight failures (e.g. pinned delegation.command missing from PATH) refuse the spawn loudly (#80450).+ routes, err = _routes_for(task_list, cfg, credentials_cfg, parent_agent)if err:return tool_error(err)+ # 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))if err:return tool_error(err)@@ -589,8 +624,8 @@ def delegate_task(origin = _capture_origin()children, err = _build_children(- task_list, task_schemas, creds, top_role=top_role, max_iterations=default_max_iter, parent_agent=parent_agent,- routing_cfg=routing_cfg, live_deleg_id=live_deleg_id, live_writers=live_writers, task_images=task_images,+ task_list, task_schemas, routes, top_role=top_role, max_iterations=default_max_iter, parent_agent=parent_agent,+ live_deleg_id=live_deleg_id, live_writers=live_writers, task_images=task_images,)if err:return tool_error(err)@@ -693,8 +728,16 @@ def _build_dynamic_schema_overrides() -> dict:k: v for k, v in tasks["items"]["properties"].items() if k != "group"}}+ # The active delegation provider's per-task parameters and guidance (delegation.backend; none for the+ # built-in default). Built from config with the rest of the definition, never per turn.+ from tools.delegate_tool_routes import schema_extension+ extra_params, addendum = schema_extension(_load_config())+ if extra_params:+ tasks = overrides_params["properties"]["tasks"]+ tasks["items"] = {**tasks["items"], "properties": {**tasks["items"]["properties"], **extra_params}}+ description = _build_top_level_description(independent_completions=independent_completions)return {- "description": _build_top_level_description(independent_completions=independent_completions),+ "description": f"{description}\n{addendum}" if addendum else description,"parameters": overrides_params,}diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex 4ee0b12bc33..addbaa5f876 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -614,6 +614,9 @@ def _build_result_entry(# Model-visible per-delegation spend (unlike _child_cost_usd above).entry["cost_usd"] = round(entry["_child_cost_usd"], 6)entry["cost_status"] = _cost_status if isinstance(_cost_status, str) and _cost_status else "unknown"+ _route_label = getattr(child, "_delegate_route_label", None)+ if isinstance(_route_label, str) and _route_label:+ entry["route"] = _route_label # the delegation provider's label (profile name, model-map option)if status == "failed":entry["error"] = result.get("error", "Subagent did not produce a response.")# Classified reason from the child loop (e.g. "rate_limit", "billing")@@ -857,7 +860,10 @@ class _ChildRun:def _run_with_thread_capture():worker_thread_holder["t"] = threading.current_thread()from agent.delegation_context import delegated_child_context- with delegated_child_context(str(getattr(child, "session_id", "") or "")):+ from tools.delegate_tool_routes import delegated_profile_scope+ # A profile-routed child converses as that profile (config, secrets, skills, terminal policy).+ with delegated_profile_scope(getattr(child, "_delegate_profile_home", None)), \+ delegated_child_context(str(getattr(child, "session_id", "") or "")):return child.run_conversation(user_message=user_message, task_id=self.child_task_id, stream_callback=self.relay_text,)diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.pyindex 357d1ba43a8..54b87a8ad13 100644--- a/tools/delegate_tool_config.py+++ b/tools/delegate_tool_config.py@@ -492,7 +492,7 @@ def _resolve_child_runtime(parent_agent, delegation_cfg: dict, parent_api_key: Any, *, model: Optional[str], override_provider: Optional[str],override_base_url: Optional[str], override_api_key: Optional[str], override_api_mode: Optional[str],override_acp_command: Optional[str], override_acp_args: Optional[list[str]],- routing_cfg: Optional[dict[str, Any]] = None,+ routing_cfg: Optional[dict[str, Any]] = None, override_reasoning_effort: Any = None,) -> dict[str, Any]:"""Child credentials, transport and routing (config override > parent inherit) as ``AIAgent`` kwargs. Rules thatare easy to break: api_mode is re-derived (not inherited) when the child's provider differs from the parent's@@ -568,11 +568,13 @@ def _resolve_child_runtime(getattr(parent_agent, "requested_provider", None) or effective_provider)- # Reasoning: delegation.reasoning_effort > parent. Keep the raw value — a- # YAML ``false`` must disable thinking, not coerce to "" and inherit.+ # Reasoning: the task route's effort (delegation provider) > delegation.reasoning_effort > parent.+ # Keep the raw value — a YAML ``false`` must disable thinking, not coerce to "" and inherit.child_reasoning = getattr(parent_agent, "reasoning_config", None)try:- delegation_effort = delegation_cfg.get("reasoning_effort")+ delegation_effort = override_reasoning_effort+ if not (delegation_effort or delegation_effort is False):+ delegation_effort = delegation_cfg.get("reasoning_effort")if delegation_effort or delegation_effort is False:from hermes_constants import parse_reasoning_effortparsed = parse_reasoning_effort(delegation_effort)diff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pynew file mode 100644index 00000000000..c288b79d14c--- /dev/null+++ b/tools/delegate_tool_routes.py@@ -0,0 +1,219 @@+"""Per-task child routes from the active delegation provider (``delegation.backend``).++``delegate_task`` asks the active :class:`agent.delegation_provider.DelegationProvider` for one+route per task, validates the model's provider-declared parameters, turns each route into the+credential bundle child construction already consumes (the same resolver ``delegation.*`` uses),+and binds a profile route's scope around the child's construction and conversation. The provider+never touches the lifecycle; this module is the whole contract between the two.+"""++from __future__ import annotations++import contextlib+import json+import logging+import re+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Iterator, Mapping, Optional++from agent.delegation_provider import (+ RESERVED_TASK_PARAMETERS, ROUTE_KEYS, DelegationProvider, DelegationRouteError,+)++logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module++_PARAM_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")+++@dataclass+class TaskRoute:+ """How core builds one child: the credential bundle, the config block owning its fallback+ policy, an optional reasoning override, and the profile home it runs as (None = this one)."""++ creds: dict[str, Any]+ routing_cfg: dict[str, Any]+ reasoning_effort: Any = None+ profile_home: Optional[Path] = None+ label: Optional[str] = None+++def _active_provider(config: Mapping[str, Any]) -> DelegationProvider:+ from agent.delegation_registry import get_active_provider+ return get_active_provider(config)+++def _declared_parameters(provider: DelegationProvider, config: Mapping[str, Any]) -> dict[str, dict[str, Any]]:+ """The provider's per-task parameters, minus anything malformed or reserved (warned)."""+ try:+ raw = provider.task_parameters(config)+ except Exception: # plugin boundary: a broken provider costs its parameters, never the delegate_task tool+ logger.warning("delegation provider %s.task_parameters() raised; no extra parameters", provider.name,+ exc_info=True)+ return {}+ if not isinstance(raw, Mapping):+ return {}+ accepted: dict[str, dict[str, Any]] = {}+ for name, schema in raw.items():+ if not isinstance(name, str) or not _PARAM_NAME_RE.match(name) or name in RESERVED_TASK_PARAMETERS:+ logger.warning("delegation provider %s: task parameter %r refused (reserved or invalid name)",+ provider.name, name)+ continue+ if isinstance(schema, Mapping):+ accepted[name] = json.loads(json.dumps(schema)) # plain, detached copy+ return accepted+++def schema_extension(config: Mapping[str, Any]) -> tuple[dict[str, dict[str, Any]], str]:+ """``(extra task properties, description addendum)`` for the active provider; empty for the+ built-in default so its schema stays byte-identical."""+ from agent.delegation_registry import DEFAULT_BACKEND+ provider = _active_provider(config)+ if provider.name == DEFAULT_BACKEND:+ return {}, ""+ try:+ addendum = provider.description(config)+ except Exception: # plugin boundary: a broken provider costs its guidance, never the delegate_task tool+ logger.warning("delegation provider %s.description() raised", provider.name, exc_info=True)+ addendum = ""+ return _declared_parameters(provider, config), addendum.strip() if isinstance(addendum, str) else ""+++def _param_error(index: int, name: str, value: Any, schema: Mapping[str, Any]) -> Optional[str]:+ enum = schema.get("enum")+ if isinstance(enum, list) and value not in enum:+ return f"Task {index}: '{name}' must be one of {', '.join(map(str, enum))} (got {value!r})."+ return None+++def _clean_route(provider_name: str, route: Any) -> dict[str, Any]:+ """The route keys of a provider's answer. Other keys are dropped silently: returning the whole+ ``delegation`` section (``dict(config)``, the default route) legitimately carries lifecycle knobs."""+ if not isinstance(route, Mapping):+ raise DelegationRouteError(f"delegation backend '{provider_name}' returned no route.")+ return {k: v for k, v in route.items() if k in ROUTE_KEYS}+++def _profile_home(name: Any) -> Path:+ from hermes_cli.profiles import get_profile_dir, profile_exists+ if not isinstance(name, str) or not name.strip() or not profile_exists(name):+ raise DelegationRouteError(f"Profile {name!r} does not exist (see `hermes profile list`).")+ return Path(get_profile_dir(name))+++def delegated_profile_scope(home: Any) -> Iterator[None]:+ """Run the block as profile ``home``: HERMES_HOME override, that profile's secret scope,+ multiplex semantics when it is not this process's own profile, and its terminal policy - the+ binding a multiplexed gateway applies to a routed turn (gateway/AGENTS.md § Profile scope).+ A no-op for anything but a path (``None``: no profile route) and for the home already in effect."""+ from hermes_constants import get_hermes_home, get_routing_process_hermes_home, hermes_home_key+ if not isinstance(home, (str, Path)) or hermes_home_key(home) == hermes_home_key(get_hermes_home()):+ yield+ return+ from agent.secret_scope import (+ reset_multiplex_context, reset_secret_scope, set_multiplex_context, set_secret_scope,+ )+ from hermes_cli.env_loader import hydrate_profile_secret_sources+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from tools.terminal_scope import install_profile_terminal_scope, reset_terminal_scope+ from tui_gateway.launch_profile_policy import owner_secret_scope++ routed = hermes_home_key(home) != hermes_home_key(get_routing_process_hermes_home())+ hydrate_profile_secret_sources(home)+ home_token = set_hermes_home_override(str(home))+ secret_token = set_secret_scope(owner_secret_scope(home), profile_home=str(home))+ mux_token = set_multiplex_context(True) if routed else None+ terminal_token = install_profile_terminal_scope(home)+ try:+ yield+ finally:+ reset_terminal_scope(terminal_token)+ if mux_token is not None:+ reset_multiplex_context(mux_token)+ reset_secret_scope(secret_token)+ reset_hermes_home_override(home_token)+++def _profile_route(home: Path, label: Optional[str]) -> TaskRoute:+ """The profile's own primary route, resolved inside its scope (its config.yaml + secrets). The+ child never borrows the launching profile's key, pool or fallback chain."""+ from hermes_cli.config import load_config_readonly+ from hermes_cli.runtime_provider import resolve_runtime_provider+ from tools.delegate_tool_config import _credential_bundle+ with delegated_profile_scope(home):+ cfg = load_config_readonly() or {}+ model_cfg = cfg.get("model")+ if isinstance(model_cfg, dict):+ model = model_cfg.get("default") or model_cfg.get("model")+ else:+ model = model_cfg if isinstance(model_cfg, str) else None+ try:+ rt = resolve_runtime_provider(target_model=model or None)+ except Exception as exc:+ raise DelegationRouteError(f"Profile at {home} has no usable model provider: {exc}") from exc+ agent_cfg = cfg.get("agent") if isinstance(cfg.get("agent"), dict) else {}+ fallback = cfg.get("fallback_providers")+ creds = _credential_bundle(+ model or rt.get("model") or None, rt.get("provider"), rt.get("base_url"),+ rt.get("api_key") or "no-key-required", rt.get("api_mode"), dict(rt.get("request_overrides") or {}),+ command=rt.get("command"), args=list(rt.get("args") or []),+ )+ return TaskRoute(creds, {"fallback_providers": fallback if isinstance(fallback, list) else []},+ agent_cfg.get("reasoning_effort"), home, label)+++def _route_to_task_route(route: dict[str, Any], parent_agent: Any, cache: dict[str, TaskRoute]) -> TaskRoute:+ key = json.dumps(route, sort_keys=True, default=str)+ if key in cache:+ return cache[key]+ label = route.get("label") if isinstance(route.get("label"), str) else None+ if route.get("profile"):+ resolved = _profile_route(_profile_home(route["profile"]), label)+ else:+ from tools.delegate_tool import _resolve_delegation_credentials # the facade is the patch seam+ resolved = TaskRoute(_resolve_delegation_credentials(route, parent_agent), route,+ route.get("reasoning_effort"), None, label)+ cache[key] = resolved+ return resolved+++def _route_one(provider: DelegationProvider, declared: dict[str, dict[str, Any]], index: int,+ task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:+ 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])+ if error:+ raise DelegationRouteError(error)+ payload = {"goal": task.get("goal"), "context": task.get("context"), "index": index, **params}+ try:+ return _clean_route(provider.name, provider.route_task(payload, config))+ except DelegationRouteError as exc:+ raise DelegationRouteError(f"Task {index}: {exc}") from exc+ except Exception as exc:+ logger.warning("delegation provider %s.route_task() raised", provider.name, exc_info=True)+ raise DelegationRouteError(f"Task {index}: delegation backend '{provider.name}' failed: {exc}") from exc+++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)+ declared = _declared_parameters(provider, config)+ cache: dict[str, TaskRoute] = {}+ routes: list[TaskRoute] = []+ try:+ for i, task in enumerate(task_list):+ routes.append(_route_to_task_route(_route_one(provider, declared, i, task, config), parent_agent, cache))+ except ValueError as exc: # DelegationRouteError and the credential resolver's refusals+ return [], str(exc)+ return routes, None+++def route_for_config(routing_cfg: dict[str, Any], parent_agent: Any) -> TaskRoute:+ """The route an internal caller's explicit config block describes (``/review`` ->+ ``auxiliary.review``); bypasses the provider, as those callers own their route."""+ from tools.delegate_tool import _resolve_delegation_credentials # the facade is the patch seam+ return TaskRoute(_resolve_delegation_credentials(routing_cfg, parent_agent), routing_cfg)diff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.mdnew file mode 100644index 00000000000..b982468e1c7--- /dev/null+++ b/website/docs/developer-guide/delegation-provider-plugin.md@@ -0,0 +1,123 @@+---+title: Delegation Provider Plugins+sidebar_label: Delegation provider plugins+---++# Delegation Provider Plugins++A delegation provider decides **how each `delegate_task` task becomes a child run**: which model,+provider, endpoint and reasoning effort the subagent uses, or which Hermes profile it runs as. It can+also add per-task parameters to the `delegate_task` schema, such as an enum of profile names or of+titled model options, so the model picks a route per task.++Hermes core keeps the whole subagent lifecycle: spawning, isolation, leaf/orchestrator roles, depth+limits, concurrency, background completion units, stop fan-out, result assembly, `output_schema`+validation and progress. A provider only answers "which route does this task take".++The active provider is `delegation.backend` in `config.yaml`. 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.++## Skeleton++```python+# ~/.hermes/plugins/delegation-tiers/__init__.py+from agent.delegation_provider import DelegationProvider, DelegationRouteError+++class Tiers(DelegationProvider):+ @property+ def name(self) -> str:+ return "tiers" # delegation.backend: tiers++ def task_parameters(self, config):+ tiers = config.get("tiers") or [] # your own delegation.<key> settings+ return {"tier": {+ "type": "string",+ "enum": [t["name"] for t in tiers],+ "description": "; ".join(f"{t['name']}: {t['description']}" for t in tiers),+ }}++ def description(self, config):+ return "Set `tier` per task to pick the model that fits it."++ def route_task(self, task, config):+ for t in config.get("tiers") or []:+ if t["name"] == task.get("tier"):+ return {"provider": t["provider"], "model": t["model"], "label": t["name"]}+ if task.get("tier"):+ raise DelegationRouteError(f"Unknown tier {task['tier']!r}.")+ return dict(config) # no tier: the default route+++def register(ctx):+ ctx.register_delegation_provider(Tiers())+```++```yaml+# plugin.yaml+name: delegation-tiers+version: 1.0.0+description: Pick a model tier per subagent.+```++```bash+hermes plugins enable delegation-tiers+hermes config set delegation.backend tiers+```++## The interface++`DelegationProvider` (`agent/delegation_provider.py`) subclasses the shared `ProviderBase`. Every+method receives `config`, the `delegation` section of the active profile's `config.yaml`, so provider+settings live next to the other delegation knobs.++| Member | Required | Contract |+|---|---|---|+| `name` | yes | The `delegation.backend` value. `default` is reserved for the built-in strategy. |+| `route_task(task, config)` | yes | Return the route dict for one task. `task` carries `goal`, `context`, `index` and the values the model supplied for your parameters. Raise `DelegationRouteError` to refuse; its message is the tool error the model reads. |+| `task_parameters(config)` | no | `{name: json_schema}` merged into `tasks.items.properties`. Core enforces `enum` before `route_task` runs and refuses core-owned names (`goal`, `context`, `output_schema`, `images`, `group`, `role`, `toolsets`, `provider`, `model`, `base_url`, `api_key`, `api_mode`, `acp_command`, `acp_args`). |+| `description(config)` | no | Guidance appended to the `delegate_task` description. |+| `is_available()` | no | No network calls. `False` makes delegation use `default`. |++### Routes++A route is a dict with any of:++- `model`, `provider`, `base_url`, `api_key`, `api_mode`, `request_overrides`, `reasoning_effort`,+ `fallback_providers`: shaped exactly like the `delegation` section and resolved by the same+ credential resolver. An empty route inherits the parent's route; `dict(config)` is the default route.+- `profile`: the name of a Hermes profile. The child runs **as that profile**: its `config.yaml`,+ primary model and credentials, credential pool, fallback chain, skills, `SOUL.md` and terminal+ policy. Core binds that profile's scope (HERMES_HOME override, secret scope, multiplex semantics,+ terminal policy) around the child's construction and conversation, the same binding a multiplexed+ gateway applies to a routed turn, so a secret missing from the target profile is never read from+ the launching profile's environment. The child's transcript stays in the launching profile's+ session database (it is the parent's work) and it keeps the parent's toolset. Other route keys are+ ignored on a profile route.+- `label`: short text reported as `route` on the child's result (an option title, a profile name).++Unknown keys are dropped.++## Prompt caching++The `delegate_task` definition, including your parameters and description, is built once when a+session's tool list is assembled. `task_parameters` and `description` must be deterministic for a+given `config`: same config, same bytes. Never derive them from the clock, the network or anything+that changes during a conversation.++## Process isolation++Every argument and return value is plain JSON, so a provider runs unchanged under+`plugins.isolation: host`: Hermes holds a proxy that subclasses `DelegationProvider` and every call+runs in the plugin host process.++## Testing++Load the plugin through the real discovery path against a temporary `HERMES_HOME` whose+`config.yaml` sets `plugins.enabled` and `delegation.backend`, then assert on behaviour: the+`delegate_task` definition from `tools.registry.registry.get_definitions({"delegate_task"})` carries+your parameter, and `tools.delegate_tool.delegate_task(...)` hands each child the route you chose.+`tests/tools/test_delegation_backends.py` in the Hermes repo is a complete example.diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex da03a6ca276..484ec9b9c18 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -25,6 +25,7 @@ Hermes has several distinct pluggable interfaces — some use Python `register_*| A **video-generation backend** | [Video Generation Provider Plugins](../video-gen-provider-plugin.md) || A **web-search / extract backend** | [Web Search Provider Plugins](../web-search-provider-plugin.md) || A **cloud browser backend** (Browserbase-style CDP session provider) | [Browser Provider Plugins](../browser-provider-plugin.md) |+| A **delegation strategy** (pick a profile or a named model per subagent) | [Delegation Provider Plugins](../delegation-provider-plugin.md) — `ctx.register_delegation_provider()` || A **computer-use driver** (desktop control behind the `computer_use` tool) | [Computer-use backend plugins](#computer-use-backend-plugins) — `ctx.register_computer_use_provider()` || A **secret-manager backend** (vault / password manager / OS keystore) | [Secret Source Plugins](../secret-source-plugin.md) || A **dashboard OIDC/auth provider** | [Web Dashboard — custom providers](../../user-guide/features/web-dashboard.md#custom-providers) — `ctx.register_dashboard_auth_provider()` |diff --git a/website/docs/developer-guide/subagent-lifecycle-api.md b/website/docs/developer-guide/subagent-lifecycle-api.mdindex a2bd44613dd..56d9388d075 100644--- a/website/docs/developer-guide/subagent-lifecycle-api.md+++ b/website/docs/developer-guide/subagent-lifecycle-api.md@@ -82,3 +82,7 @@ delegation config > parent; the selected provider supplies its own credentialbundle. An unresolvable provider raises `SubagentLifecycleError` before launch.Core does not expose `provider` to the model: the plugin chooses it, for examplefrom operator config.++The lifecycle API does not consult `delegation.backend`: the plugin that launches a child already chooses+its route. To change how `delegate_task` routes the model's subagents, write a+[delegation provider plugin](delegation-provider-plugin.md).diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex 2dc4175ba35..3b734a88f71 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -291,7 +291,21 @@ delegation:Resolution order: `delegation.base_url` (direct endpoint) takes precedence, then `delegation.provider` (full credential bundle resolved via the runtime provider system), and when neither is set children inherit the parent's provider and credentials; `delegation.model` applies in all cases, and when it is empty children inherit the parent's model. Setting `delegation.provider` alongside `delegation.base_url` keeps the explicit endpoint but carries that provider's request overrides and max output tokens into the child. An explicit `delegation.request_overrides` dict is honored on every branch and merges over those runtime-derived values (see [Configuration](#configuration) below).-Note that the pin is global: `delegate_task` has no per-task model parameter, so every child in a batch runs on the configured delegation model. For quality-sensitive subtasks that need a stronger model, either leave `delegation.model` unset for that session or hand the task to the [kanban board](kanban.md#per-task-model-override), which does support a per-task model override.+Note that the pin is global: with the default strategy `delegate_task` has no per-task model parameter, so every child in a batch runs on the configured delegation model. For quality-sensitive subtasks that need a stronger model, either leave `delegation.model` unset for that session, use a delegation strategy plugin (below), or hand the task to the [kanban board](kanban.md#per-task-model-override), which does support a per-task model override.++### Delegation strategies (`delegation.backend`)++`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**: each child runs as one of your Hermes profiles, with that profile's model, credentials, skills and persona;+- a **named model map**: you list titled options (`fast`, `deep`, ...) with a description and a provider/model each, and the model picks one per task.++```yaml+delegation:+ backend: model-map # the plugin's backend name+```++The model only ever sees the names and descriptions you configured, never raw provider, model or key fields. 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 `/review` Commanddiff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 3899f0cf5e2..3ac7f3010f3 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -115,6 +115,7 @@ Every `ctx.*` API below is available inside a plugin's `register(ctx)` function.| Distribute via pip | `[project.entry-points."hermes_agent.plugins"]` || Register a gateway platform (Discord, Telegram, IRC, …) | `ctx.register_platform(name, label, adapter_factory, check_fn, ...)` — see [Adding Platform Adapters](../../developer-guide/adding-platform-adapters.md) || Register an image-generation backend | `ctx.register_image_gen_provider(provider)` — see [Image Generation Provider Plugins](../../developer-guide/image-gen-provider-plugin.md) |+| Register a delegation strategy (how each `delegate_task` subagent is routed) | `ctx.register_delegation_provider(provider)` — see [Delegation Provider Plugins](../../developer-guide/delegation-provider-plugin.md) || Register a video-generation backend | `ctx.register_video_gen_provider(provider)` — see [Video Generation Provider Plugins](../../developer-guide/video-gen-provider-plugin.md) || Register a context-compression engine | `ctx.register_context_engine(engine)` — see [Context Engine Plugins](../../developer-guide/context-engine-plugin.md) || Register a terminal execution backend (cloud sandbox) | `ctx.register_terminal_environment_provider(provider)` — see [Terminal Environment Plugins](../../developer-guide/terminal-environment-plugin.md) |@@ -382,6 +383,7 @@ The table above shows the four plugin categories, but within "General plugins" t| A **memory backend** (Honcho, Mem0, Supermemory, …) | Memory plugin — subclass `MemoryProvider` in `plugins/memory/<name>/` | [Memory Provider Plugins](../../developer-guide/memory-provider-plugin.md) || A **context-compression strategy** | Context-engine plugin — `ctx.register_context_engine()` | [Context Engine Plugins](../../developer-guide/context-engine-plugin.md) || An **image-generation backend** (DALL·E, SDXL, …) | Backend plugin — `ctx.register_image_gen_provider()` | [Image Generation Provider Plugins](../../developer-guide/image-gen-provider-plugin.md) |+| A **delegation strategy** (a profile or named model per subagent) | Backend plugin — `ctx.register_delegation_provider()`, selected by `delegation.backend` | [Delegation Provider Plugins](../../developer-guide/delegation-provider-plugin.md) || A **video-generation backend** (Veo, Kling, Pixverse, Grok-Imagine, Runway, …) | Backend plugin — `ctx.register_video_gen_provider()` | [Video Generation Provider Plugins](../../developer-guide/video-gen-provider-plugin.md) || A **computer-use driver** (desktop control behind the `computer_use` tool) | Single-select provider plugin — `ctx.register_computer_use_provider()`, selected by `computer_use.backend` | [Computer-use backend plugins](../../developer-guide/plugins/index.md#computer-use-backend-plugins) || A **TTS backend** (any CLI — Piper, VoxCPM, Kokoro, xtts, voice-cloning scripts, …) | Config-driven (recommended) — declare under `tts.providers.<name>` with `type: command` in `config.yaml`. OR Python backend plugin — `ctx.register_tts_provider()` for Python-SDK / streaming engines that need more than a shell template. | [TTS Setup](./tts.md#custom-command-providers) · [Python plugin guide](./tts.md#python-plugin-providers) |diff --git a/website/sidebars.ts b/website/sidebars.tsindex 59c6eab5443..99988dd328f 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -832,6 +832,7 @@ const sidebars: SidebarsConfig = {'developer-guide/web-search-provider-plugin','developer-guide/browser-provider-plugin','developer-guide/terminal-environment-plugin',+ 'developer-guide/delegation-provider-plugin','developer-guide/plugins/application-declarations','developer-guide/plugins/catalog-submission',],