The 22 files that build, run and track delegated children leave tools/ for agent/subagents/, and the two completion-notice files go to agent/completion_notices/. Every file is a rename: the lines that change in them are imports, module names in strings, and comments or docstrings that name a sibling module. tools/delegate_task_tool.py and tools/delegate_tool_tasks.py, the tool and its argument handling, stay. 42 test files whose only subject is a moved module move to tests/agent/subagents/, whose conftest imports the autouse fixtures they ran under in tests/tools/. Six old module names stay importable through hermes_agent/compat/moves.py because pinned catalog plugins import them: tools.async_delegation, tools.delegate_tool, tools.delegate_tool_config, tools.delegate_tool_registry, tools.delegation_live_log and tools.process_registry_awaiting. The last one also keeps a generated file at its old path: releases v0.22.3 to v0.23.5 import it inside ProcessRegistry._prune_if_needed, which runs on every background process start, and no idle process of those releases has it loaded. Loggers follow their modules, so delegation's log lines are under `hermes logs --component agent` and no longer under `--component tools`.
288 lines
17 KiB
Python
288 lines
17 KiB
Python
"""The ``delegate_task`` model tool: its schema, the description built for each session, the shaping of a
|
|
model-sent call and the registration. ``agent.subagents.spawn.delegate_task`` does the work."""
|
|
|
|
from typing import Any
|
|
|
|
from agent.subagents import config as delegate_tool_config
|
|
from agent.subagents.spawn import delegate_task
|
|
from agent.subagents.config import _get_max_concurrent_children, _get_max_spawn_depth, _get_orchestrator_enabled
|
|
from tools.delegate_tool_tasks import _MAX_TASK_IMAGES
|
|
from tools.registry import registry
|
|
|
|
|
|
def check_delegate_requirements() -> bool:
|
|
"""Delegation has no external requirements -- always available."""
|
|
return True
|
|
|
|
|
|
# ── OpenAI function-calling schema ──────────────────────────────────────────
|
|
|
|
def _build_top_level_description(*, independent_completions=None) -> str:
|
|
"""delegate_task description: ONLY guidance stated nowhere else in the schema
|
|
(limits live in the 'tasks' parameter description, rebuilt per get_definitions())."""
|
|
try:
|
|
orchestration_available = _get_max_spawn_depth() >= 2 and _get_orchestrator_enabled()
|
|
except Exception:
|
|
orchestration_available = False
|
|
# Mention recursion only where it's actually available. send_message is deliberately not named (gateway-internal
|
|
# vocabulary); model_tools session-filters the list to tools the session has.
|
|
if orchestration_available:
|
|
restrictions_rule = (
|
|
"- Children cannot call clarify, memory, or cronjob.\n"
|
|
f"- Children can themselves delegate while depth remains (max_spawn_depth={_get_max_spawn_depth()}); the "
|
|
"runtime derives this from depth automatically.\n"
|
|
)
|
|
else:
|
|
restrictions_rule = "- Children cannot call delegate_task, clarify, memory, or cronjob.\n"
|
|
from agent.subagents.config import _get_independent_completions
|
|
|
|
if independent_completions is None:
|
|
independent_completions = _get_independent_completions()
|
|
delivery = _DELIVERY_INDEPENDENT if independent_completions else _DELIVERY_JOINED
|
|
return _DESCRIPTION_HEAD.format(delivery=delivery) + restrictions_rule + _DESCRIPTION_TAIL
|
|
|
|
# The independent variant states the dispatch-time choice and its cost: a parent that meant to answer once but left
|
|
# tasks ungrouped is woken per result and spends a filler turn on each.
|
|
_DELIVERY_JOINED = " (one message per call)"
|
|
_DELIVERY_INDEPENDENT = (
|
|
", one message per `group`. Choose at dispatch: if you will respond only once ALL tasks are done, give every "
|
|
"task the same `group`; give a task its own `group` only when you will act on its result the moment it lands, "
|
|
"because each separate result re-enters alone and costs a turn"
|
|
)
|
|
|
|
_DESCRIPTION_DELIVERY = (
|
|
"Sessions without a later-result consumer (including one-shot CLI and cron) join parallel children "
|
|
"and return results in this tool call. "
|
|
"Otherwise runs in the background: dispatch returns live transcript paths and results re-enter "
|
|
"as a new message when subagents finish{delivery}. Background results are delivered only "
|
|
"BETWEEN your turns: finish whatever does not depend on them, then give a one-line status and END YOUR TURN. Never "
|
|
"wait or poll on transcripts, artifact files, or CI for a child.\n\n"
|
|
)
|
|
_ONESHOT_DESCRIPTION_DELIVERY = "Parallel children are joined and their results return in this tool call.\n\n"
|
|
_DESCRIPTION_HEAD = (
|
|
"Spawn isolated subagents. Each gets its own conversation, terminal session, and toolset, and only its final "
|
|
"summary returns to you.\n\n"
|
|
+ _DESCRIPTION_DELIVERY +
|
|
"USE FOR: reasoning-heavy subtasks, work that would flood your context, or independent parallel workstreams.\n"
|
|
"DO NOT USE FOR (use these instead):\n"
|
|
"- Mechanical multi-step work with no reasoning needed -> execute_code\n"
|
|
"- A single tool call -> call the tool directly\n"
|
|
"- Tasks needing user interaction -> subagents cannot ask questions\n"
|
|
"- Durable work that must survive this session -> cronjob or terminal(background=True, notify=True, "
|
|
"persist_on_release=True); /stop, /new, or process exit halts running subagents (whole tree); each returns an "
|
|
"'interrupted' completion with partial output.\n\n"
|
|
"RULES:\n"
|
|
"- Children know nothing of this conversation: pass everything needed via 'context', including any required "
|
|
"output language, tone, or style (e.g. \"respond in Chinese\").\n"
|
|
"- Child summaries are SELF-REPORTS, not verified facts: a child claiming \"uploaded successfully\" or "
|
|
"\"file written\" may be wrong. For external side effects (uploads, remote writes, publishing), require a "
|
|
"verifiable handle (URL, ID, absolute path) and verify it yourself before telling the user the operation "
|
|
"succeeded.\n"
|
|
"- Children cannot close tracked work: a child asked to close it returns findings instead; "
|
|
"the parent applies the transition.\n"
|
|
)
|
|
_DESCRIPTION_TAIL = (
|
|
"- Children inherit the parent model unless pinned via delegation.provider / delegation.model in config.yaml."
|
|
)
|
|
|
|
def _build_dynamic_schema_overrides() -> dict:
|
|
"""Per-call schema overrides (ToolEntry.dynamic_schema_overrides): every
|
|
get_definitions() pass rewrites the descriptions to the user's actual limits."""
|
|
from agent.subagents.config import _get_independent_completions
|
|
|
|
independent_completions = _get_independent_completions()
|
|
overrides_params = {**DELEGATE_TASK_SCHEMA["parameters"]}
|
|
# Copy properties so the static schema dict is never mutated.
|
|
overrides_params["properties"] = {k: dict(v) for k, v in DELEGATE_TASK_SCHEMA["parameters"]["properties"].items()}
|
|
tasks = overrides_params["properties"]["tasks"]
|
|
tasks["maxItems"] = _get_max_concurrent_children()
|
|
if independent_completions:
|
|
tasks["items"] = {**tasks["items"], "required": ["goal", "group"]}
|
|
else:
|
|
tasks["items"] = {**tasks["items"], "properties": {
|
|
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 agent.subagents.routes import schema_extension
|
|
extra_params, addendum = schema_extension(delegate_tool_config._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": f"{description}\n{addendum}" if addendum else description,
|
|
"parameters": overrides_params,
|
|
}
|
|
|
|
def _p(type_: str, description: str, **extra) -> dict:
|
|
return {"type": type_, **extra, "description": description}
|
|
|
|
DELEGATE_TASK_SCHEMA = {
|
|
"name": "delegate_task",
|
|
# description is a placeholder: the real text, and tasks.maxItems, are built per get_definitions() call by
|
|
# _build_dynamic_schema_overrides() so the model sees the user's actual max_concurrent_children / max_spawn_depth.
|
|
# Lazy (not at import) so cli.CLI_CONFIG isn't forced to load before the test conftest redirects HERMES_HOME.
|
|
"description": (
|
|
"Spawn one or more subagents in isolated contexts. "
|
|
"Description is rebuilt at every get_definitions() call to reflect the user's current delegation limits."
|
|
),
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
# The handler also accepts the legacy single-goal shape (top-level `goal`/`context`/`output_schema`),
|
|
# wrapped into a one-entry batch at dispatch, and a per-task `role` (legacy, ignored: capability is
|
|
# depth-derived). Both unadvertised on purpose (old transcripts only); do not re-add. maxItems is the
|
|
# user's delegation.max_concurrent_children, set by _build_dynamic_schema_overrides(); a constant
|
|
# here would misstate a configured limit. delegate_task() refuses a longer list with a clear error.
|
|
"tasks": {
|
|
"type": "array",
|
|
"minItems": 1,
|
|
"items": {
|
|
"type": "object",
|
|
"properties": {
|
|
"goal": _p(
|
|
"string",
|
|
"What this subagent should accomplish. Be specific and self-contained.",
|
|
),
|
|
"context": _p(
|
|
"string",
|
|
"Background THIS child needs: file paths, error messages, constraints. Each child "
|
|
"sees only its own context — repeat shared background in every task that needs it.",
|
|
),
|
|
"output_schema": _p(
|
|
"object",
|
|
"JSON Schema this child's final answer must validate against (told to the "
|
|
"child up front; parent validates with one bounded correction retry; result gains "
|
|
"schema_valid, plus schema_errors on failure — the child's raw text is still returned "
|
|
"as summary, never discarded). Keep it forgiving — require only fields you will read.",
|
|
),
|
|
"images": _p(
|
|
"array",
|
|
"Images this child must SEE: local file paths or http(s) URLs — e.g. a "
|
|
"screenshot the user sent, a design mock, a chart. Vision-capable children receive the "
|
|
"pixels on their first turn; non-vision children get path hints for vision_analyze. Text "
|
|
"files do NOT belong here — put paths in 'context' instead.",
|
|
items={"type": "string"},
|
|
maxItems=_MAX_TASK_IMAGES,
|
|
),
|
|
"group": _p(
|
|
"string",
|
|
"Result-delivery bucket. Tasks sharing a group return together in ONE message once all of "
|
|
"them finish; a task with its own group returns alone when it finishes. Does not order "
|
|
"execution; if B needs A's output, dispatch B after A returns.",
|
|
),
|
|
},
|
|
"required": ["goal"],
|
|
},
|
|
"description": (
|
|
"One entry per subagent; several run in parallel. The user sets the entry limit with "
|
|
"delegation.max_concurrent_children. Required when spawning."
|
|
),
|
|
},
|
|
# `background` (bool) is also accepted — DEPRECATED, ignored: top-level
|
|
# delegations always run in the background. Unadvertised; do not re-add.
|
|
"action": _p(
|
|
"string",
|
|
"Live control of running children: "
|
|
"'list' = ids/goals/status/transcripts; 'steer' = queue "
|
|
"course-correction text into one child without stopping it; 'stop' = end one child "
|
|
"early (partial result still returns); 'continue' = give a FINISHED child a follow-up: "
|
|
"it resumes its own conversation and returns like a spawn. "
|
|
"Control actions return immediately; tasks are ignored unless spawning.",
|
|
enum=["spawn", "list", "steer", "stop", "continue"], default="spawn",
|
|
),
|
|
"subagent_id": _p("string", "Required for action='steer'/'stop'/'continue' (ids from the spawn response or action='list')."),
|
|
"message": _p(
|
|
"string",
|
|
"Required for action='steer': the course correction, delivered to the child as a user "
|
|
"message after its current tool calls. Be directive and specific. "
|
|
"For 'continue': the child's next instruction.",
|
|
),
|
|
},
|
|
"required": [],
|
|
},
|
|
}
|
|
|
|
|
|
_LIVE_CONTROL_PARAMS = frozenset({"action", "subagent_id", "message"})
|
|
|
|
|
|
def oneshot_delegate_function(function: dict) -> dict:
|
|
"""A built delegate_task definition minus live control and ``group``, for a one-shot or inline-gateway session
|
|
(agent/oneshot_footprint.py): its children are joined inside the call, so ``action`` list/steer/stop never has a
|
|
running child to reach, ``group`` never changes delivery, and the background-delivery paragraph never applies.
|
|
The handler still accepts those arguments."""
|
|
description = function.get("description") or ""
|
|
for delivery in (_DELIVERY_INDEPENDENT, _DELIVERY_JOINED):
|
|
description = description.replace(_DESCRIPTION_DELIVERY.format(delivery=delivery), _ONESHOT_DESCRIPTION_DELIVERY)
|
|
params = function["parameters"]
|
|
properties = {k: v for k, v in params["properties"].items() if k not in _LIVE_CONTROL_PARAMS}
|
|
items = properties["tasks"]["items"]
|
|
properties["tasks"] = {**properties["tasks"], "items": {
|
|
**items, "properties": {k: v for k, v in items["properties"].items() if k != "group"},
|
|
"required": [k for k in items["required"] if k != "group"],
|
|
}}
|
|
return {**function, "description": description, "parameters": {**params, "properties": properties}}
|
|
|
|
|
|
def session_joins_delegation(agent: Any) -> bool:
|
|
"""Whether *agent*'s top-level delegations join in the call because the ``delegate_task`` the model sees is the
|
|
joined variant (a gateway session with ``delegation.gateway_mode`` inline). Dispatch follows the schema bytes,
|
|
which ride the session's tools[] pin: a config change can never leave the model reading "results return in
|
|
this tool call" while children detach, or the reverse. One-shot sessions keep their own fallback (and note)."""
|
|
if getattr(agent, "_oneshot_session", None) is True:
|
|
return False
|
|
for tool in getattr(agent, "tools", None) or ():
|
|
function = tool.get("function") if isinstance(tool, dict) else None
|
|
if isinstance(function, dict) and function.get("name") == "delegate_task":
|
|
return _ONESHOT_DESCRIPTION_DELIVERY in (function.get("description") or "")
|
|
return False
|
|
|
|
|
|
def adopt_session_delegation_mode(agent: Any) -> None:
|
|
"""Re-freeze *agent*'s inline decision (``agent_joins_delegation``) from the ``delegate_task`` it carries once a
|
|
fresh agent has restored its session's tools[] pin, so the pin is authoritative: a later rebuild from fresh
|
|
definitions (compaction boundary, ``/reload mcp``, Bot Chat refresh) derives the session's variant, not the one
|
|
the current config would build."""
|
|
tools = getattr(agent, "tools", None) or ()
|
|
if any(isinstance(tool, dict) and (tool.get("function") or {}).get("name") == "delegate_task" for tool in tools):
|
|
agent._delegation_inline = session_joins_delegation(agent)
|
|
|
|
|
|
def _model_background_value(args: dict, parent_agent=None) -> bool:
|
|
"""Background flag for the MODEL-facing dispatch path (registry fallback). Top-level delegations always run in the
|
|
background — the model does not choose — for single tasks and fan-out batches alike (one async unit, one
|
|
consolidated result); an orchestrator subagent (depth > 0) is the exception since it needs its workers' results
|
|
within its own turn. The live path is ``run_agent._dispatch_delegate_task``; this mirrors it for the rare case
|
|
the intercept is bypassed. Direct Python callers keep the synchronous default."""
|
|
return not getattr(parent_agent, "_delegate_depth", 0) > 0
|
|
|
|
_MODEL_HIDDEN_TASK_FIELDS = {"acp_command", "acp_args"}
|
|
|
|
def _strip_model_hidden_task_fields(tasks: Any) -> Any:
|
|
"""Drop trusted-config-only task fields from model-supplied tasks (same list object back when nothing changed)."""
|
|
if not isinstance(tasks, list) or not any(isinstance(t, dict) and _MODEL_HIDDEN_TASK_FIELDS & t.keys() for t in tasks):
|
|
return tasks
|
|
return [{k: v for k, v in t.items() if k not in _MODEL_HIDDEN_TASK_FIELDS} if isinstance(t, dict) else t for t in tasks]
|
|
|
|
|
|
registry.register(
|
|
name="delegate_task",
|
|
toolset="delegation",
|
|
schema=DELEGATE_TASK_SCHEMA,
|
|
handler=lambda args, **kw: delegate_task(
|
|
goal=args.get("goal"), context=args.get("context"), tasks=_strip_model_hidden_task_fields(args.get("tasks")),
|
|
max_iterations=args.get("max_iterations"), role=args.get("role"),
|
|
background=_model_background_value(args, kw.get("parent_agent")), output_schema=args.get("output_schema"),
|
|
images=args.get("images"), action=args.get("action"), subagent_id=args.get("subagent_id"), message=args.get("message"),
|
|
parent_agent=kw.get("parent_agent"),
|
|
),
|
|
check_fn=check_delegate_requirements,
|
|
emoji="🔀",
|
|
dynamic_schema_overrides=_build_dynamic_schema_overrides,
|
|
# The single-task top-level shape, kept for old transcripts.
|
|
compat_args=("goal", "context", "images", "max_iterations", "output_schema", "role"),
|
|
)
|