The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(delegation): the default delegation strategy is a bundled plugin
Teknium5c353467dc7a
diff --git a/agent/delegation_provider.py b/agent/delegation_provider.pyindex f2e0012dc1b..1ff587aaa6e 100644--- a/agent/delegation_provider.py+++ b/agent/delegation_provider.py@@ -5,7 +5,7 @@ provider, endpoint and reasoning effort the child uses, or which Hermes profilealso add per-task parameters to the ``delegate_task`` schema (an enum of profile names, of titledmodel 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,+behaviour, provided by the bundled ``plugins/delegation/default`` plugin). 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".diff --git a/agent/delegation_registry.py b/agent/delegation_registry.pyindex 6db15ba89df..f1313d8bc0d 100644--- a/agent/delegation_registry.py+++ b/agent/delegation_registry.py@@ -2,18 +2,19 @@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 (a session may override it, ``agent/delegation_backends.py``).-Unset (or ``default``) is the built-in strategy, today's behaviour: every child follows the-``delegation`` section (``delegation.provider`` / ``delegation.model`` / ``delegation.base_url`` ...,-else the parent's route). A configured backend that is not registered or reports unavailable fails-closed: ``delegate_task`` returns a tool error naming the backend and the fix, and never quietly runs-the children on another route. Its schema parameters are absent, since the schema is built from the-same resolution.+``delegation.backend`` in config.yaml, ``default`` when unset. The default strategy (today's+behaviour: every child follows the ``delegation`` section, else the parent's route) is itself a+plugin, the bundled ``plugins/delegation/default``, registered through the same seam as any other.+A session may override the selection (``agent/delegation_backends.py``). A configured backend that is+not registered or reports unavailable fails closed: ``delegate_task`` returns a tool error naming the+backend and the fix, and never quietly runs the children on another route. Its schema parameters are+absent, since the schema is built from the same resolution."""from __future__ import annotationsimport logging+import refrom typing import Any, Mapping, Optionalfrom agent.delegation_provider import DelegationProvider, DelegationRouteError@@ -23,38 +24,12 @@ 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-- @property- def display_name(self) -> str:- return "Default"-- @property- def summary(self) -> str:- return "Every subagent uses delegation.model / delegation.provider, else the parent's model."-- def route_task(self, task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:- # The delegation section has no speed tier: an unknown key there never becomes one.- return {k: v for k, v in config.items() if k != "service_tier"}---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()+_BUNDLED_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")def configured_backend(config: Mapping[str, Any]) -> str:@@ -63,23 +38,68 @@ def configured_backend(config: Mapping[str, Any]) -> str:return lower_key(raw) if isinstance(raw, str) and raw.strip() else DEFAULT_BACKEND+class _BundledRegistrar:+ """The one ``ctx`` method a bundled strategy's ``register()`` calls."""++ def register_delegation_provider(self, provider: DelegationProvider) -> None:+ _registry.register(provider)+++def _load_bundled(name: str) -> Optional[DelegationProvider]:+ """Load the bundled strategy ``plugins/delegation/<name>/`` on first use when the plugin sweep has+ not registered it (a runtime that never ran discovery, or pinned it with zero plugins): delegation+ is a core tool and must not depend on the sweep. ``plugins.disabled`` still wins."""+ import importlib.util+ from hermes_cli.plugins import get_bundled_plugins_dir+ from hermes_cli.plugins_discovery import _get_disabled_plugins+ if not _BUNDLED_NAME_RE.match(name): # the name comes from config.yaml: never a path+ return None+ plugin_dir = get_bundled_plugins_dir() / "delegation" / name+ if not (plugin_dir / "plugin.yaml").is_file() or {name, f"delegation/{name}"} & _get_disabled_plugins():+ return None+ spec = importlib.util.spec_from_file_location(+ f"hermes_bundled_delegation_{name.replace('-', '_')}", plugin_dir / "__init__.py",+ submodule_search_locations=[str(plugin_dir)])+ if spec is None or spec.loader is None:+ return None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ module.register(_BundledRegistrar())+ return _registry.get_provider(name)+++def _usable(name: str) -> Optional[DelegationProvider]:+ """The registered, available provider for ``name``: registry, else a bundled strategy of that+ name, else one plugin discovery sweep (a caller that never imported ``model_tools``)."""+ provider = _registry.get_provider(name) or _load_bundled(name)+ if provider is None:+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ provider = _registry.get_provider(name)+ if provider is None or not is_available_safe(provider, logger, "delegation provider %s.is_available() raised %s"):+ return None+ return provider++def backend_status(name: str) -> tuple[Optional[DelegationProvider], str]:"""``(provider, "")`` when backend ``name`` can run here, else ``(provider or None, reason)``; the reason isthe user-facing fix (it becomes the ``delegate_task`` tool error)."""- if name == DEFAULT_BACKEND:- return _BUILTIN_DEFAULT, ""- provider: Optional[DelegationProvider] = _registry.get_provider(name)- if provider is None:+ provider = _usable(name)+ if provider is not None:+ return provider, ""+ registered = _registry.get_provider(name)+ if registered is None and name == DEFAULT_BACKEND:+ return None, ("No default delegation strategy is available: the bundled plugin delegation/default is "+ "disabled. Remove it from plugins.disabled in config.yaml.")+ if registered is None:return None, (f"Delegation backend '{name}' is not installed: no enabled plugin provides it. Install or enable the "f"plugin that does (`hermes plugins list`), or switch back to the default backend "f"(`hermes config set delegation.backend default`).")- if not is_available_safe(provider, logger, "delegation provider %s.is_available() raised %s"):- return provider, (- f"Delegation backend '{name}' is unavailable here (its plugin reports it cannot run). Fix its setup, or "- f"switch back to the default backend: `/delegation default` for this session, or "- f"`hermes config set delegation.backend default`.")- return provider, ""+ return registered, (+ f"Delegation backend '{name}' is unavailable here (its plugin reports it cannot run). Fix its setup, or "+ f"switch back to the default backend: `/delegation default` for this session, or "+ f"`hermes config set delegation.backend default`.")def get_active_provider(config: Mapping[str, Any]) -> DelegationProvider:diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex d721988f552..c346225656b 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -80,7 +80,7 @@ bare names resolve through the catalog or error.| General | `plugins/<name>/`, `~/.hermes/plugins/`, `./.hermes/plugins/`, pip entry points | `PluginManager` (`hermes_cli/plugins.py`), later-wins | `register(ctx)` registers hooks (`pre_tool_call`, `post_tool_call`, `pre_llm_call`, `post_llm_call`, `on_session_start`, `on_session_end`), tools (`ctx.register_tool`), CLI subcommands (`ctx.register_cli_command` — argparse tree wired into `hermes` at startup, no `main.py` change), language packs (`provides_locales` in the manifest auto-registers `locales/<lang>[.tui|.desktop].yaml` via `ctx.register_locale_dir`; manifest-only packs need no `__init__.py`; `hermes_cli/plugin_validate_locales.py` validates them) || Memory provider | `plugins/memory/<name>/` | `plugins/memory/__init__.py`: bundled → `$HERMES_HOME/plugins/` → `./.hermes/plugins/` (opt-in `HERMES_ENABLE_PROJECT_PLUGINS`) → `hermes_agent.memory_providers` entry points; **bundled-first** | Activated by name via `memory.provider`, so a dropped-in dir must not shadow a shipped one (reverse of general later-wins). Enumerates without importing. Implements `MemoryProvider` ABC (`agent/memory_provider.py`), orchestrated by `agent/memory_manager.py`: `sync_turn`, `prefetch`, `shutdown`, optional `post_setup`. `cli.py` with `register_cli(subparser)` is wired by `discover_plugin_cli_commands()` — only for the ACTIVE provider, so `hermes --help` stays clean || Model provider | `plugins/model-providers/<name>/` | `providers/__init__.py._discover_providers()`, **lazy**, on first `get_provider_profile()`/`list_providers()`; bundled → `$HERMES_HOME/plugins/model-providers/` → legacy `providers/<name>.py` | `__init__.py` calls `providers.register_provider(ProviderProfile(...))` at load; **last-writer-wins** so a user plugin overrides a bundled profile. `PluginManager` records `kind: model-provider` manifests but does NOT import them (would double-instantiate); manifests without `kind:` are auto-coerced by source heuristic (`register_provider` + `ProviderProfile`) |-| Context engine / image-gen / others | `plugins/context_engine/`, `plugins/image_gen/`, ... | ABC + orchestrator + per-plugin directory | Plug into `agent/context_engine.py`, `agent/image_gen_provider.py` |+| Context engine / image-gen / delegation / others | `plugins/context_engine/`, `plugins/image_gen/`, `plugins/delegation/`, ... | ABC + orchestrator + per-plugin directory | Plug into `agent/context_engine.py`, `agent/image_gen_provider.py`, `agent/delegation_provider.py` (`plugins/delegation/default` IS today's delegation routing) || Platform adapters | `plugins/platforms/<name>/adapter.py` | gateway | Token-lock and scoped-secret rules in `gateway/AGENTS.md` (`irc`, `feishu` are canonical) |**Discovery timing pitfall:** `discover_plugins()` runs only as a side effect of importingdiff --git a/plugins/delegation/default/__init__.py b/plugins/delegation/default/__init__.pynew file mode 100644index 00000000000..bf0952550b8--- /dev/null+++ b/plugins/delegation/default/__init__.py@@ -0,0 +1,38 @@+"""Default delegation strategy (``delegation.backend: default``).++Every ``delegate_task`` task takes the route the ``delegation`` config section describes: a+``delegation.base_url`` endpoint, a ``delegation.provider`` pin, ``delegation.model`` and+``delegation.reasoning_effort``, or, when those are empty, the parent's own route. It adds no+schema parameters. Bundled ``kind: backend``, so it is always loaded; other strategies are plugins+of the same kind (``agent/delegation_provider.py``).+"""++from __future__ import annotations++from typing import Any, Mapping++from agent.delegation_provider import DelegationProvider+++class DefaultDelegationProvider(DelegationProvider):+ """Route every task through the ``delegation`` section."""++ @property+ def name(self) -> str:+ return "default"++ @property+ def display_name(self) -> str:+ return "Default"++ @property+ def summary(self) -> str:+ return "Every subagent uses delegation.model / delegation.provider, else the parent's model."++ def route_task(self, task: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]:+ # The delegation section has no speed tier: an unknown key there never becomes one.+ return {k: v for k, v in config.items() if k != "service_tier"}+++def register(ctx) -> None:+ ctx.register_delegation_provider(DefaultDelegationProvider())diff --git a/plugins/delegation/default/plugin.yaml b/plugins/delegation/default/plugin.yamlnew file mode 100644index 00000000000..988b8c37c9b--- /dev/null+++ b/plugins/delegation/default/plugin.yaml@@ -0,0 +1,5 @@+name: default+version: 1.0.0+description: "Default delegation strategy: every delegate_task subagent follows the delegation section of config.yaml (delegation.provider / model / base_url ...), else inherits the parent's model and credentials."+author: NousResearch+kind: backenddiff --git a/tests/tools/test_delegation_backends.py b/tests/tools/test_delegation_backends.pyindex b11d71041ae..5c4c999d166 100644--- a/tests/tools/test_delegation_backends.py+++ b/tests/tools/test_delegation_backends.py@@ -10,9 +10,13 @@ import typesimport hermes_yaml as yamlimport pytest+from pathlib import Path+from hermes_cli import plugins as plugins_modfrom hermes_cli.plugins import PluginManager+REPO_PLUGINS = Path(__file__).resolve().parents[2] / "plugins"+PROBE_PLUGIN = '''from agent.delegation_provider import DelegationProvider, DelegationRouteError@@ -51,19 +55,22 @@ OPTIONS = []-def _home(tmp_path, monkeypatch, delegation: dict, plugins=("probe-options",)):+def _home(tmp_path, monkeypatch, delegation: dict, plugins=("probe-options",), disabled=()):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()+ {"plugins": {"enabled": list(plugins), "disabled": list(disabled)}, "delegation": delegation}),+ encoding="utf-8")+ # Bundled plugins: only the delegation category (the default strategy is a bundled plugin).+ bundled = tmp_path / "bundled"+ bundled.mkdir()+ (bundled / "delegation").symlink_to(REPO_PLUGINS / "delegation", target_is_directory=True)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)+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: bundled)manager = PluginManager()manager.discover_and_load()return home, manager@@ -386,3 +393,54 @@ def test_backend_settings_come_from_its_own_backends_block(tmp_path, monkeypatchassert _task_props(_definition())["option"]["enum"] == []finally:manager.unload()+++def test_default_strategy_is_the_bundled_plugin_through_the_same_seam(tmp_path, monkeypatch, recorded):+ from agent.delegation_registry import get_active_provider+ from tools.delegate_tool import delegate_task++ _, manager = _home(tmp_path / "on", monkeypatch, {"model": "pinned-model"}, plugins=())+ try:+ assert manager._plugins["delegation/default"].enabled+ provider = get_active_provider({})+ assert provider.name == "default"+ assert type(provider).__module__.startswith("hermes_plugins.delegation__default")+ delegate_task(tasks=[{"goal": "one plain delegated task"}], parent_agent=_parent())+ assert recorded[-1]["model"] == "pinned-model"+ finally:+ manager.unload()+ # Disabling the bundled default is the one way to have no strategy: a clear refusal, base schema.+ _, manager = _home(tmp_path / "off", monkeypatch, {}, plugins=(), disabled=("delegation/default",))+ try:+ out = json.loads(delegate_task(tasks=[{"goal": "one plain delegated task"}], parent_agent=_parent()))+ assert "delegation/default is disabled" in out["error"]+ assert "option" not in _task_props(_definition())+ finally:+ manager.unload()+++def test_runtime_with_zero_plugins_loaded_still_delegates_on_the_bundled_default(tmp_path, monkeypatch, recorded):+ """Delegation is a core tool: a runtime whose plugin sweep never ran (or was pinned empty) loads the+ bundled default strategy on first use instead of losing delegate_task."""+ from agent.delegation_registry import _load_bundled, _registry+ from tools.delegate_tool import delegate_task++ home = tmp_path / ".hermes"+ home.mkdir(parents=True)+ (home / "config.yaml").write_text(yaml.safe_dump({"delegation": {"model": "pinned-model"}}), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ pinned = PluginManager()+ pinned._discovered = True # zero plugins, discovery never runs+ monkeypatch.setattr(plugins_mod, "_plugin_manager", pinned)+ previous = _registry.snapshot_registration("default")+ if previous is not None:+ _registry.restore_registration("default", previous, None)+ try:+ delegate_task(tasks=[{"goal": "one plain delegated task"}], parent_agent=_parent())+ assert recorded[-1]["model"] == "pinned-model"+ assert _registry.get_provider("default").name == "default"+ assert _load_bundled("../../tools") is None # config text never becomes a path+ finally:+ current = _registry.snapshot_registration("default")+ if current is not None:+ _registry.restore_registration("default", current, previous)diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex 7ce02bf5486..77c4335ee75 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -142,7 +142,8 @@ delegation provider (`agent/delegation_provider.py`, `ctx.register_delegation_pr`delegation.backends.<name>`) that answers each task's route (`tools/delegate_tool_routes.py`: model/provider fieldsresolved like the `delegation` section, `service_tier` checked like `/fast` in `delegate_tool_tuning.py`, or `profile` →the child is built, leases and converses inside that profile's scope) and may add enum-checked per-task schema params; it-never owns lifecycle. Fails closed: an unusable backend is a tool error naming it (never a silent `default`), an+never owns lifecycle. The `default` strategy is the bundled `plugins/delegation/default` plugin (no core special case+beyond selecting it). Fails closed: an unusable backend is a tool error naming it (never a silent `default`), anunroutable task is refused alone (`TaskRoute.error`); a session override (`agent/delegation_backends.py`) beats config. Internal `credentials_cfg` callers (/review) and the lifecycle API bypass it. **Child processes:** a child's backgroundprocesses are killed at its teardown and their notices are suppressed in the parent; `process_manage(action="handoff")`(children only) flips `ProcessSession.owner_task_id` to the parent under the registry lockdiff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pyindex 555d86a7355..b20d60c4078 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -79,15 +79,12 @@ def _declared_parameters(provider: DelegationProvider, config: Mapping[str, Any]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+ """``(extra task properties, description addendum)`` for the active provider (none for the+ default strategy, whose schema is the base one)."""try:provider = _active_provider(config)except DelegationRouteError:return {}, "" # fails closed at spawn time, with the fix; the schema just stays the base one- 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 tooldiff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.mdindex 1d4b62e37d9..80b8f40472c 100644--- a/website/docs/developer-guide/delegation-provider-plugin.md+++ b/website/docs/developer-guide/delegation-provider-plugin.md@@ -15,8 +15,11 @@ limits, concurrency, background completion units, stop fan-out, result assembly,validation and progress. A provider only answers "which route does this task take".The active provider is `delegation.backend` in `config.yaml`; a provider's own settings live under-`delegation.backends.<backend name>`. The built-in `default` strategy is today's behaviour: every child follows the `delegation` section (`delegation.provider`,-`delegation.model`, `delegation.base_url`, ...), or inherits the parent's route when those are empty.+`delegation.backends.<backend name>`. The `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. It is itself a plugin, the bundled+`plugins/delegation/default/` (`kind: backend`, always loaded), registered through the same+`ctx.register_delegation_provider()` seam as yours; it is also the smallest complete example.A configured backend that is not installed or reports unavailable **fails closed**: `delegate_task`returns a tool error naming the backend and the fix, no child starts, and its schema parameters areabsent. A session can override the backend (`agent.delegation_backends`, below).@@ -88,7 +91,7 @@ is the default route, and `self.settings(config)` is your backend's own block,| Member | Required | Contract ||---|---|---|-| `name` | yes | The `delegation.backend` value. `default` is reserved for the built-in strategy. |+| `name` | yes | The `delegation.backend` value. `default` belongs to the bundled default 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`, `index`, `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. |diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 3ac7f3010f3..46d79ded23f 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -159,6 +159,7 @@ Within each source, Hermes also recognizes sub-category directories that route p| `plugins/` (root) | General plugins — tools, hooks, slash commands, CLI commands, bundled skills | `PluginManager` (kind: `standalone` or `backend`) || `plugins/platforms/<name>/` | Gateway channel adapters (`ctx.register_platform()`) | `PluginManager` (kind: `platform`, one level deeper) || `plugins/image_gen/<name>/` | Image-generation backends (`ctx.register_image_gen_provider()`) | `PluginManager` (kind: `backend`, one level deeper) |+| `plugins/delegation/<name>/` | Delegation strategies (`ctx.register_delegation_provider()`); `default` is today's routing | `PluginManager` (kind: `backend`, one level deeper) || `plugins/memory/<name>/` | Memory providers (subclass `MemoryProvider`) | **Own loader** in `plugins/memory/__init__.py` (kind: `exclusive` — one active at a time) || `plugins/context_engine/<name>/` | Context-compression engines (`ctx.register_context_engine()`) | **Own loader** in `plugins/context_engine/__init__.py` (one active at a time) || `plugins/model-providers/<name>/` | LLM provider profiles (`register_provider(ProviderProfile(...))`) | **Own loader** in `providers/__init__.py` (lazily scanned on first `get_provider_profile()` call) |