Skip to content

The agent that grows with you

refactor(delegate): compact task validation + toolset resolution (inline MCP preservation, single strip)

Teknium5a3cbf51aa9c
diff --git a/tools/delegate_tool_tasks.py b/tools/delegate_tool_tasks.py
index 864591cfb96..3e658d6a2dd 100644
--- a/tools/delegate_tool_tasks.py
+++ b/tools/delegate_tool_tasks.py
@@ -9,23 +9,6 @@ import json
import re
from typing import Any, Dict, List, Optional
-def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]:
- if not isinstance(tasks, str):
- return None, None
- raw = tasks.strip()
- if not raw:
- return None, "Provide either 'goal' (single task) or 'tasks' (batch)."
- try:
- parsed = json.loads(raw)
- except json.JSONDecodeError as exc:
- return None, (
- "tasks must be a JSON array of task objects; received a string "
- f"that could not be parsed as JSON ({exc.msg})."
- )
- if not isinstance(parsed, list):
- return None, (f"tasks must be a JSON array of task objects; parsed " f"{type(parsed).__name__} instead.")
- return parsed, None
-
# Placeholder shapes for batch goal validation: bare 'TODO' / 'task N' labels,
# or unexpanded template markers. The marker regex is deliberately NARROW —
# only snake_case / space-separated placeholder identifiers (`<feature_name>`,
@@ -34,27 +17,40 @@ def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str,
# generics (`Vec<T>`), HTML tags (`<div>`), dict snippets (`{"key": 1}`), glob
# braces (`{a,b}`) and f-string style (`{i}`).
_PLACEHOLDER_GOAL_RE = re.compile(r"^(todo|task\s*\d+)$", re.IGNORECASE)
-
_TEMPLATE_MARKER_RE = re.compile(
r"<[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+>|\{[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+\}"
)
-
_MIN_BATCH_GOAL_LEN = 10
+def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]:
+ """``(parsed_list, None)`` for a JSON-array string, ``(None, error)`` for a bad string, ``(None, None)`` otherwise."""
+ if not isinstance(tasks, str):
+ return None, None
+ raw = tasks.strip()
+ if not raw:
+ return None, "Provide either 'goal' (single task) or 'tasks' (batch)."
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ return None, f"tasks must be a JSON array of task objects; received a string that could not be parsed as JSON ({exc.msg})."
+ if not isinstance(parsed, list):
+ return None, f"tasks must be a JSON array of task objects; parsed {type(parsed).__name__} instead."
+ return parsed, None
+
def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]:
- """Validate a tasks=[...] batch beyond per-task goal presence; actionable
- error string or None.
+ """Batch-only quality gate beyond per-task goal presence; actionable error or None.
No minimum count: a one-entry array is the canonical single-task shape
(legacy top-level `goal` is wrapped into one). Duplicate goals are
deliberately NOT rejected — identical-goal fan-outs (best-of-N / ensemble
- sampling) are legitimate and blocking them broke real workflows.
+ sampling) are legitimate and blocking them broke real workflows. The
+ too-short check applies only to multi-task fan-outs (terse goals there are
+ usually unexpanded templates); a SINGLE task legitimately uses short goals
+ ("Fix the tests").
"""
for i, task in enumerate(task_list):
goal = str(task.get("goal", "")).strip()
- normalized = " ".join(goal.lower().split())
-
- if _PLACEHOLDER_GOAL_RE.match(normalized):
+ if _PLACEHOLDER_GOAL_RE.match(" ".join(goal.lower().split())):
return (
f"Task {i} has a placeholder goal ({goal!r}). Replace it "
"with a specific, self-contained description of what the subagent should accomplish."
@@ -67,14 +63,9 @@ def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]:
"calling delegate_task — subagents cannot resolve placeholders."
)
if len(goal) < _MIN_BATCH_GOAL_LEN and len(task_list) >= 2:
- # Multi-task fan-outs with terse goals are usually unexpanded
- # templates; a SINGLE task legitimately uses short goals
- # ("Fix the tests"), so one-entry arrays keep the historical
- # single-`goal` exemption.
return (
f"Task {i} goal is too short ({goal!r}). Write a specific, "
- "self-contained goal of at least "
- f"{_MIN_BATCH_GOAL_LEN} characters so the subagent knows "
+ f"self-contained goal of at least {_MIN_BATCH_GOAL_LEN} characters so the subagent knows "
"exactly what to do."
)
return None
@@ -101,10 +92,9 @@ def _normalize_task_list(
)
task_list = tasks
elif goal and isinstance(goal, str) and goal.strip():
- single_task: Dict[str, Any] = {"goal": goal, "context": context, "role": top_role}
+ task_list = [{"goal": goal, "context": context, "role": top_role}]
if output_schema is not None:
- single_task["output_schema"] = output_schema
- task_list = [single_task]
+ task_list[0]["output_schema"] = output_schema
else:
return None, (
"No tasks provided. Pass tasks=[{goal: '...', context: '...'}, "
@@ -116,14 +106,9 @@ def _normalize_task_list(
return None, f"Task {i} must be an object, got {type(task).__name__}."
if not task.get("goal", "").strip():
return None, f"Task {i} is missing a 'goal'."
-
- # Batch-only quality gate (placeholders, template markers); the single-goal
- # form is exempt because short goals are valid there.
- if tasks is not None and isinstance(tasks, list):
- batch_error = _validate_batch_tasks(task_list)
- if batch_error:
- return None, batch_error
- return task_list, None
+ # The single-goal form is exempt from the batch gate (short goals are valid there).
+ batch_error = _validate_batch_tasks(task_list) if isinstance(tasks, list) else None
+ return (None, batch_error) if batch_error else (task_list, None)
def _coerce_task_schemas(
task_list: List[Dict[str, Any]], output_schema: Optional[Dict[str, Any]]
diff --git a/tools/delegate_tool_toolsets.py b/tools/delegate_tool_toolsets.py
index 8e2c40bd1cd..f49ad87d096 100644
--- a/tools/delegate_tool_toolsets.py
+++ b/tools/delegate_tool_toolsets.py
@@ -24,6 +24,7 @@ DELEGATE_BLOCKED_TOOLS = frozenset(
"cronjob_manage", # no scheduling more work in the parent's name
]
)
+DEFAULT_TOOLSETS = ["terminal", "file", "web"]
def _is_mcp_toolset_name(name: str) -> bool:
"""Return True for canonical MCP toolsets and their registered aliases."""
@@ -44,45 +45,22 @@ def _expand_parent_toolsets(parent_toolsets: set) -> set:
A parent on a composite like ``hermes-cli`` must still let a child request
``web``/``terminal``; bare name intersection would reject them.
"""
- parent_tool_names: set = set()
- for ts_name in parent_toolsets:
- ts_def = TOOLSETS.get(ts_name)
- if ts_def:
- parent_tool_names.update(ts_def.get("tools", []))
-
- if not parent_tool_names:
- return set(parent_toolsets)
-
+ parent_tool_names = {t for ts_name in parent_toolsets for t in (TOOLSETS.get(ts_name) or {}).get("tools", [])}
expanded = set(parent_toolsets)
- for ts_name, ts_def in TOOLSETS.items():
- if ts_name in expanded:
- continue
- ts_tools = ts_def.get("tools", [])
- if ts_tools and set(ts_tools).issubset(parent_tool_names):
- expanded.add(ts_name)
+ if parent_tool_names:
+ expanded.update(
+ ts_name for ts_name, ts_def in TOOLSETS.items()
+ if ts_name not in expanded and ts_def.get("tools") and set(ts_def["tools"]).issubset(parent_tool_names)
+ )
return expanded
-def _preserve_parent_mcp_toolsets(child_toolsets: List[str], parent_toolsets: set[str]) -> List[str]:
- """Append any parent MCP toolsets that are missing from a narrowed child."""
- preserved = list(child_toolsets)
- for toolset_name in sorted(parent_toolsets):
- if _is_mcp_toolset_name(toolset_name) and toolset_name not in preserved:
- preserved.append(toolset_name)
- return preserved
-
-DEFAULT_TOOLSETS = ["terminal", "file", "web"]
-
def _strip_blocked_tools(toolsets: List[str]) -> List[str]:
"""Remove toolsets whose tools are ALL blocked (derived from DELEGATE_BLOCKED_TOOLS
- so the two can't drift) plus composite toolsets children must never get."""
- _COMPOSITE_BLOCKED_TOOLSETS = frozenset({"delegation"})
- blocked_toolset_names = {
- name
- for name, defn in TOOLSETS.items()
- if name in _COMPOSITE_BLOCKED_TOOLSETS
- or all(t in DELEGATE_BLOCKED_TOOLS for t in defn.get("tools", []))
+ so the two can't drift) plus composite toolsets children must never get
+ (``delegation``, ``kanban``)."""
+ blocked_toolset_names = {"delegation", "kanban"} | {
+ name for name, defn in TOOLSETS.items() if all(t in DELEGATE_BLOCKED_TOOLS for t in defn.get("tools", []))
}
- blocked_toolset_names.add("kanban")
return [t for t in toolsets if t not in blocked_toolset_names]
def _blocked_toolsets_for_role(role: str) -> List[str]:
@@ -92,10 +70,7 @@ def _blocked_toolsets_for_role(role: str) -> List[str]:
if role == "orchestrator":
blocked_names.discard("delegate_task")
return sorted(
- name
- for name, defn in TOOLSETS.items()
- if defn.get("tools")
- and set(defn.get("tools", ())).issubset(blocked_names)
+ name for name, defn in TOOLSETS.items() if defn.get("tools") and set(defn.get("tools", ())).issubset(blocked_names)
)
def _resolve_child_toolsets(
@@ -118,9 +93,7 @@ def _resolve_child_toolsets(
elif parent_agent and hasattr(parent_agent, "valid_tool_names"):
import model_tools
parent_toolsets = {
- ts
- for name in parent_agent.valid_tool_names
- if (ts := model_tools.get_toolset_for_tool(name)) is not None
+ ts for name in parent_agent.valid_tool_names if (ts := model_tools.get_toolset_for_tool(name)) is not None
}
else:
parent_toolsets = set(DEFAULT_TOOLSETS)
@@ -129,14 +102,15 @@ def _resolve_child_toolsets(
expanded_parent = _expand_parent_toolsets(parent_toolsets)
child_toolsets = [t for t in toolsets if t in expanded_parent]
if _get_inherit_mcp_toolsets():
- child_toolsets = _preserve_parent_mcp_toolsets(child_toolsets, parent_toolsets)
- child_toolsets = _strip_blocked_tools(child_toolsets)
+ # Append any parent MCP toolsets missing from the narrowed child.
+ child_toolsets += [
+ name for name in sorted(parent_toolsets) if _is_mcp_toolset_name(name) and name not in child_toolsets
+ ]
elif parent_agent and parent_enabled is not None:
- child_toolsets = _strip_blocked_tools(parent_enabled)
- elif parent_toolsets:
- child_toolsets = _strip_blocked_tools(sorted(parent_toolsets))
+ child_toolsets = parent_enabled
else:
- child_toolsets = _strip_blocked_tools(DEFAULT_TOOLSETS)
+ child_toolsets = sorted(parent_toolsets) or DEFAULT_TOOLSETS
+ child_toolsets = _strip_blocked_tools(child_toolsets)
raw_parent_disabled = getattr(parent_agent, "disabled_toolsets", None)
inherited_disabled = (