The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(delegation): service_tier is a route field checked by core
Teknium572ecbe43d6a
diff --git a/agent/delegation_provider.py b/agent/delegation_provider.pyindex abf8f27e7b2..6f73d15da7a 100644--- a/agent/delegation_provider.py+++ b/agent/delegation_provider.py@@ -18,6 +18,9 @@ Route vocabulary (:meth:`DelegationProvider.route_task` returns a dict with any``reasoning_effort``, ``fallback_providers`` - shaped exactly like the ``delegation`` configsection and resolved by the same credential resolver ``delegation.*`` uses (empty route = thechild inherits the parent's route, like an empty ``delegation`` section).+* ``service_tier`` - ``normal``, ``fast`` or ``ultrafast``, checked like ``/fast`` against the+ resolved route (and, for ultrafast, the Codex account); a tier the route does not offer refuses+ the task, and the tier is re-applied after the child is built.* ``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 samescope helpers a multiplexed gateway uses for a routed turn. A profile route ignores the other@@ -46,7 +49,7 @@ RESERVED_TASK_PARAMETERS = frozenset({#: 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",+ "reasoning_effort", "service_tier", "fallback_providers", "profile", "label",})diff --git a/tests/tools/test_delegation_route_fields.py b/tests/tools/test_delegation_route_fields.pynew file mode 100644index 00000000000..685c18ec238--- /dev/null+++ b/tests/tools/test_delegation_route_fields.py@@ -0,0 +1,120 @@+"""Route fields a delegation backend returns: ``service_tier`` is checked like ``/fast`` and survives child+construction, an unknown ``reasoning_effort`` is a tool error, and every backend-routed result reports what the+child actually ran on. Real ``delegate_task``, real credential resolution and tier gates; only the child's+construction and run are stubbed where a test reads what they were handed.++Tier behaviour ported from #140614 (per-task speed tiers, unsupportedpastels).+"""++import json+import threading+from unittest.mock import MagicMock, patch++import pytest++from agent.delegation_provider import DelegationProvider++CODEX = {"base_url": "https://chatgpt.com/backend-api/codex", "api_key": "codex-key", "model": "gpt-6-astra"}+LOCAL = {"base_url": "http://127.0.0.1:8080/v1", "api_key": "k", "model": "qwen3-local"}+++class _Backend(DelegationProvider):+ """Answers task ``index`` with ``routes[index]``."""++ def __init__(self, routes):+ self.routes = routes++ @property+ def name(self):+ return "route-fields"++ def route_task(self, task, config):+ route = self.routes[task["index"]]+ return dict(config) if route is None else dict(route)+++def _parent(request_overrides=None):+ 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", "anthropic/claude-sonnet-4", "cli"+ parent.request_overrides = request_overrides or {}+ parent.reasoning_config = {"enabled": True, "effort": "medium"}+ 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+ return parent+++def _construct(**kwargs):+ child = MagicMock()+ child.request_overrides = dict(kwargs.get("request_overrides") or {})+ child.provider, child.model = kwargs.get("provider"), kwargs.get("model")+ child.reasoning_config, child.service_tier = kwargs.get("reasoning_config"), kwargs.get("service_tier")+ return child+++def _spawn(routes, *, cfg=None, parent=None, construct=_construct, provider=None):+ """``(tool result, [AIAgent kwargs], [built children])`` for one task per route."""+ batches = []+ with (+ patch("tools.delegate_tool._load_config", return_value=cfg or {}),+ patch("tools.delegate_tool_routes._active_provider", return_value=provider or _Backend(routes)),+ patch("run_agent.AIAgent", side_effect=construct) as agent,+ patch("tools.delegate_tool._run_batch",+ side_effect=lambda batch, background: batches.append(batch) or '{"status": "built"}'),+ ):+ from tools.delegate_tool import delegate_task+ result = json.loads(delegate_task(tasks=[{"goal": f"task number {i}"} for i in range(len(routes))],+ parent_agent=parent or _parent()))+ children = [c for _, _, c in batches[0].children] if batches else []+ return result, [call.kwargs for call in agent.call_args_list], children+++def test_route_tier_reaches_the_child_and_its_sibling_keeps_the_default():+ result, (fast, plain), _ = _spawn([{**CODEX, "service_tier": "fast"}, None])+ assert result == {"status": "built"}+ assert fast["request_overrides"]["service_tier"] == "priority" and fast["service_tier"] == "priority"+ assert "service_tier" not in plain["request_overrides"] and plain.get("service_tier") is None++[email protected]("route, needle", [+ ({**LOCAL, "service_tier": "fast"}, "not available"), # a local route has no fast tier: never a silent normal+ ({**CODEX, "service_tier": "turbo"}, "turbo"),+ ({**CODEX, "service_tier": "auto"}, "auto"), # bounded windows are per user turn, meaningless for a child+])+def test_a_tier_the_route_does_not_offer_fails_before_any_child_is_built(route, needle):+ result, built, _ = _spawn([route, None])+ assert needle in result["error"] and built == []++[email protected]("account_offers, expected", [(False, None), (True, "ultrafast"), (None, "ultrafast")])+def test_ultrafast_follows_the_codex_account_like_the_fast_command(account_offers, expected):+ """The Codex backend serves another tier to a plan without ultrafast; refuse unless the account lists it."""+ with patch("agent.codex_service_tiers.codex_account_offers_tier", return_value=account_offers):+ result, built, _ = _spawn([{**CODEX, "model": "gpt-6.1-sol", "service_tier": "ultrafast"}])+ if expected is None:+ assert "not available" in result["error"] and built == []+ else:+ assert built[0]["request_overrides"]["service_tier"] == expected+++def test_route_tier_survives_a_provider_extra_body_merged_at_construction():+ """Child setup can merge a custom provider's extra_body (carrying its own tier) after the route's overrides."""+ def construct(**kwargs):+ child = _construct(**kwargs)+ child.request_overrides = {**child.request_overrides, "extra_body": {"service_tier": "priority", "x": 1}}+ return child++ parent = _parent(request_overrides={"service_tier": "priority"})+ _, _, (child,) = _spawn([{**CODEX, "service_tier": "normal"}], parent=parent, construct=construct)+ assert child.request_overrides == {"extra_body": {"x": 1}}+ assert parent.request_overrides == {"service_tier": "priority"} # the parent is untouched+++def test_default_backend_never_reads_a_tier_from_the_delegation_section():+ """``service_tier`` is not a delegation-section key: the default route stays exactly today's."""+ from agent.delegation_registry import get_active_provider+ result, (child,), _ = _spawn([None], cfg={**CODEX, "service_tier": "fast"}, provider=get_active_provider({}))+ assert result == {"status": "built"}+ assert child.get("service_tier") is None and "service_tier" not in child["request_overrides"]diff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 7f476c123de..1545d60345e 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -50,6 +50,7 @@ from tools.delegate_tool_registry import (from tools.delegate_tool_tasks import (_MAX_TASK_IMAGES, _coerce_task_images, _coerce_task_schemas, _normalize_task_images, _normalize_task_list,)+from tools.delegate_tool_tuning import pin_child_service_tierfrom tools.delegate_tool_toolsets import (DELEGATE_BLOCKED_TOOLS, _expand_parent_toolsets, _resolve_child_toolsets, _strip_blocked_tools,)@@ -228,6 +229,7 @@ def _build_child_agent(# effort that beats delegation.reasoning_effort, and the profile home the child runs as.override_reasoning_effort: Any = None,profile_home: Optional[Path] = None,+ override_service_tier: Optional[str] = None, # a route's checked speed tier (tools/delegate_tool_tuning.py)):"""Build (don't run) a child AIAgent on the main thread. override_* (from delegation config) replace parentinheritance so children can run on a different provider:model pair. ``profile_home`` builds (and later runs,@@ -276,6 +278,8 @@ def _build_child_agent(override_acp_args=override_acp_args,routing_cfg=routing_cfg, override_reasoning_effort=override_reasoning_effort,)+ if override_service_tier:+ rt["service_tier"] = override_service_tierif override_request_overrides is not None:# honored whenever set, incl. the inherit branch where# _resolve_delegation_credentials already merged OVER the parent's@@ -429,6 +433,7 @@ def _credential_overrides(creds: dict[str, Any], routing_cfg: dict[str, Any]) ->"override_request_overrides": creds.get("request_overrides"),"override_acp_command": creds.get("command"),"override_acp_args": creds.get("args"),+ "override_service_tier": creds.get("service_tier"),"routing_cfg": routing_cfg,}@@ -470,6 +475,7 @@ def _build_children(_detach_child(parent_agent, built)_close_child(built, "Failed to close child after a refused sibling")return [], str(exc)+ pin_child_service_tier(child, route.creds)if _task_schema is not None:with _quiet("Could not attach output schema to child %d", i):child._delegate_output_schema = _task_schemadiff --git a/tools/delegate_tool_routes.py b/tools/delegate_tool_routes.pyindex aef09e9b26a..d3f6fae3164 100644--- a/tools/delegate_tool_routes.py+++ b/tools/delegate_tool_routes.py@@ -28,8 +28,8 @@ _PARAM_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")@dataclassclass 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)."""+ """How core builds one child: the credential bundle (with a route's speed tier applied), 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]@@ -216,8 +216,11 @@ def _route_to_task_route(route: dict[str, Any], parent_agent: Any, cache: dict[scache[key] = _profile_route(_profile_home(route["profile"]))else:from tools.delegate_tool import _resolve_delegation_credentials # the facade is the patch seam- cache[key] = TaskRoute(_resolve_delegation_credentials(route, parent_agent), route,- route.get("reasoning_effort"), None, None)+ creds = _resolve_delegation_credentials(route, parent_agent)+ if route.get("service_tier") not in (None, ""):+ from tools.delegate_tool_tuning import task_service_tier+ creds = {**creds, **task_service_tier(str(route["service_tier"]), creds, parent_agent)}+ cache[key] = TaskRoute(creds, route, route.get("reasoning_effort"), None, None)return replace(cache[key], label=label)@@ -243,14 +246,19 @@ def resolve_task_routes(task_list: list[dict[str, Any]], config: Mapping[str, An"""One :class:`TaskRoute` per task from the active provider, or ``([], error)``. Identicalroutes resolve credentials once per call (the default provider resolves exactly once, asbefore the seam)."""+ from agent.delegation_registry import DEFAULT_BACKENDprovider = _active_provider(config)declared = _declared_parameters(provider, config)+ from_backend = provider.name != DEFAULT_BACKENDcache: 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+ route = _route_one(provider, declared, i, task, config)+ if not from_backend:+ route.pop("service_tier", None) # not a delegation-section key: the default route stays today's+ routes.append(_route_to_task_route(route, parent_agent, cache))+ except ValueError as exc: # DelegationRouteError, the credential resolver's and the tier check's refusalsreturn [], str(exc)return routes, None