The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): profile routes resolve like the profile's own startup
Teknium46420400b8b1
diff --git a/tests/tools/test_delegation_profile_route.py b/tests/tools/test_delegation_profile_route.pyindex 5e0c4f6b1af..1189ad86397 100644--- a/tests/tools/test_delegation_profile_route.py+++ b/tests/tools/test_delegation_profile_route.py@@ -65,7 +65,7 @@ def test_profile_route_resolves_the_target_profiles_model_and_key(two_profiles):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 route.reasoning_effort.config == {"enabled": True, "effort": "low"}assert _snapshot() == {"home": str(launch), "secret": "launch-secret", "model": "launch-model"}@@ -135,6 +135,73 @@ def test_secret_missing_from_target_profile_never_falls_back_to_the_launch_env(tassert json.loads(json.dumps(_snapshot()))["model"] == "launch-model"+def _set_config(home, **sections):+ cfg = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8"))+ cfg.update(sections)+ (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")+++def _build(route, parent):+ from tools.delegate_tool import _build_child_agent, _route_overrides+ seen = {}++ def construct(**kwargs):+ seen.update(kwargs)+ 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))+ return child, seen+++def test_profile_whose_default_is_an_alias_takes_the_alias_route(two_profiles):+ """Same owner as CLI startup: ``model.default: <alias>`` is the alias's model and endpoint."""+ from tools.delegate_tool_routes import _route_to_task_route++ _, coder = two_profiles+ _set_config(coder, model={"default": "localqwen"},+ model_aliases={"localqwen": {"model": "qwen3-27b", "base_url": "http://127.0.0.1:8099/v1"}})+ route = _route_to_task_route({"profile": "coder"}, _parent(), {})+ assert (route.creds["model"], route.creds["base_url"]) == ("qwen3-27b", "http://127.0.0.1:8099/v1")+++def test_named_custom_profile_child_leases_its_own_account_on_a_shared_url(two_profiles):+ from tools.delegate_tool_routes import _route_to_task_route++ _, coder = two_profiles+ url = "https://gateway.invalid/v1"+ _set_config(coder, model={"provider": "open-ai", "default": "coder-model"},+ providers={"claude-ai": {"api": url, "api_key": "key-a"}, "open-ai": {"api": url, "api_key": "key-b"}})++ def entry(cid, key):+ return {"id": cid, "label": cid, "auth_type": "api_key", "priority": 0, "source": "manual",+ "access_token": key, "base_url": url}+ (coder / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {+ "claude-ai": [entry("a", "pool-key-a")], "open-ai": [entry("b", "pool-key-b")]}}), encoding="utf-8")++ parent = _parent()+ child, _ = _build(_route_to_task_route({"profile": "coder"}, parent, {}), parent)+ assert [e.access_token for e in child._credential_pool.entries()] == ["pool-key-b"]++[email protected]("agent_cfg, expected", [+ ({"reasoning_effort": "high", "reasoning_overrides": {"coder-model": False}}, {"enabled": False}),+ ({}, None), # unset in the target profile: its default, never the launching parent's level+])+def test_profile_child_reasoning_is_the_target_profiles_resolved_setting(two_profiles, agent_cfg, expected):+ from tools.delegate_tool_routes import _route_to_task_route++ _, coder = two_profiles+ _set_config(coder, agent=agent_cfg)+ parent = _parent()+ parent.reasoning_config = {"enabled": True, "effort": "xhigh"}+ with patch("tools.delegate_tool._load_config", return_value={"reasoning_effort": "xhigh"}):+ _, built = _build(_route_to_task_route({"profile": "coder"}, parent, {}), parent)+ assert built["reasoning_config"] == expected++def test_profile_child_lease_and_schema_retry_run_inside_the_target_profile(two_profiles):"""The startup lease (``_swap_credential`` reloads TLS/headers from config) and the output_schema retry turnare child work: they run as the routed profile, like the first conversation."""diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.pyindex 54b87a8ad13..d8e4a213e82 100644--- a/tools/delegate_tool_config.py+++ b/tools/delegate_tool_config.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport loggingimport os-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, NamedTuple, Optionalfrom utils import base_url_hostname, is_truthy_valuefrom hermes_cli.fallback_config import scoped_fallback_chain@@ -488,6 +488,34 @@ def _resolve_child_fallback_chain(parent_agent, routing_cfg: Any, pinned: bool)pinned=pinned, owner="delegation")+class ResolvedReasoning(NamedTuple):+ """A route's FINAL reasoning config, used as-is (``None`` included = the route's own default): a profile route+ resolves its profile's ``agent.reasoning_effort`` / ``reasoning_overrides``, so neither the launching profile's+ ``delegation.reasoning_effort`` nor the parent's level may fill it in."""++ config: Optional[dict]+++def _child_reasoning(parent_agent, delegation_cfg: dict, route_effort: Any) -> Any:+ """Child reasoning config: a :class:`ResolvedReasoning` route value as-is, else the route's raw effort >+ ``delegation.reasoning_effort`` > the parent's level. Keep the raw value — a YAML ``false`` must disable+ thinking, not coerce to "" and inherit."""+ if isinstance(route_effort, ResolvedReasoning):+ return route_effort.config+ child_reasoning = getattr(parent_agent, "reasoning_config", None)+ delegation_effort = route_effort+ if not (delegation_effort or delegation_effort is False):+ delegation_effort = (delegation_cfg or {}).get("reasoning_effort")+ if delegation_effort or delegation_effort is False:+ from hermes_constants import parse_reasoning_effort+ parsed = parse_reasoning_effort(delegation_effort)+ if parsed is None:+ logger.warning("Unknown delegation.reasoning_effort '%s', inheriting parent level", delegation_effort)+ else:+ child_reasoning = parsed+ return child_reasoning++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],@@ -569,21 +597,7 @@ def _resolve_child_runtime()# 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 = 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_effort- parsed = parse_reasoning_effort(delegation_effort)- if parsed is None:- logger.warning("Unknown delegation.reasoning_effort '%s', inheriting parent level", delegation_effort)- else:- child_reasoning = parsed- except Exception as exc:- logger.debug("Could not load delegation reasoning_effort: %s", exc)+ child_reasoning = _child_reasoning(parent_agent, delegation_cfg, override_reasoning_effort)kwargs: dict[str, Any] = {"base_url": effective_base_url, "api_key": override_api_key or parent_api_key, "model": effective_model,diff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pyindex 1d43c37aeb4..0f28a772b0b 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -142,32 +142,55 @@ def child_profile_scope(child: Any) -> contextlib.AbstractContextManager:return delegated_profile_scope(getattr(child, "_delegate_profile_home", None))+def _profile_model_request(cfg: Mapping[str, Any]) -> dict[str, Any]:+ """``resolve_runtime_provider`` kwargs for a profile's primary model, decoded by the same owner CLI startup+ uses (``resolve_startup_model_route``): a ``model.default`` alias takes the alias's model, endpoint and key."""+ from hermes_cli.model_switch import resolve_startup_model_route+ model_cfg = cfg.get("model")+ if isinstance(model_cfg, dict):+ model = model_cfg.get("default") or model_cfg.get("model")+ cfg_provider = str(model_cfg.get("provider") or "").strip()+ else:+ model, cfg_provider = (model_cfg if isinstance(model_cfg, str) else None), ""+ request: dict[str, Any] = {"target_model": model or None}+ if not isinstance(model, str) or not model.strip():+ return request+ startup = resolve_startup_model_route(+ model, current_provider=cfg_provider.lower(), user_providers=cfg.get("providers"),+ custom_providers=cfg.get("custom_providers"), alias_config=dict(cfg))+ if startup is not None:+ request = {"target_model": startup.model, "requested": startup.provider or None,+ "explicit_base_url": startup.base_url or None, "explicit_api_key": startup.api_key or None}+ return request++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."""+ child never borrows the launching profile's key, pool, fallback chain or reasoning level."""from hermes_cli.config import load_config_readonlyfrom hermes_cli.runtime_provider import resolve_runtime_provider- from tools.delegate_tool_config import _credential_bundle+ from hermes_constants import resolve_reasoning_config+ from tools.delegate_tool_config import ResolvedReasoning, _credential_bundlewith 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+ request = _profile_model_request(cfg)try:- rt = resolve_runtime_provider(target_model=model or None)+ rt = resolve_runtime_provider(**request)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 {}+ model = request["target_model"] or rt.get("model") or Nonefallback = cfg.get("fallback_providers")+ # A named custom provider resolves to provider "custom": keep its name as the identity (as delegation.provider+ # does) so two named providers sharing one URL never lease each other's pool.+ requested = str(rt.get("requested_provider") or "").strip()+ provider = requested if rt.get("provider") == "custom" and requested.lower() not in ("", "auto") else rt.get("provider")creds = _credential_bundle(- model or rt.get("model") or None, rt.get("provider"), rt.get("base_url"),+ model, 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)+ ResolvedReasoning(resolve_reasoning_config(cfg, model or "")), home, label)def _route_to_task_route(route: dict[str, Any], parent_agent: Any, cache: dict[str, TaskRoute]) -> TaskRoute:diff --git a/website/docs/developer-guide/delegation-provider-plugin.md b/website/docs/developer-guide/delegation-provider-plugin.mdindex b982468e1c7..8757faceb36 100644--- a/website/docs/developer-guide/delegation-provider-plugin.md+++ b/website/docs/developer-guide/delegation-provider-plugin.md@@ -78,7 +78,7 @@ settings live next to the other delegation knobs.|---|---|---|| `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`). |+| `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. || `is_available()` | no | No network calls. `False` makes delegation use `default`. |@@ -90,9 +90,11 @@ A route is a dict with any of:`fallback_providers`: shaped exactly like the `delegation` section and resolved by the samecredential 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+ primary model and credentials (a `model.default` alias or named provider resolves exactly as at+ CLI startup), credential pool, fallback chain, reasoning (`agent.reasoning_effort` and+ `agent.reasoning_overrides`), 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, its credential lease and every conversation turn, the same binding a multiplexedgateway applies to a routed turn, so a secret missing from the target profile is never read fromthe launching profile's environment. The child's transcript stays in the launching profile'ssession database (it is the parent's work) and it keeps the parent's toolset. Other route keys are