Skip to content

The agent that grows with you

feat(delegation): per-task completion groups — ungrouped subagents return as they finish

Teknium028fe2c4c857
diff --git a/tests/tools/test_async_delegation.py b/tests/tools/test_async_delegation.py
index 54e9943179d..61d3e3899e1 100644
--- a/tests/tools/test_async_delegation.py
+++ b/tests/tools/test_async_delegation.py
@@ -946,3 +946,87 @@ def test_batch_model_rejection_notice_requires_configured_model_in_text(monkeypa
text = format_process_notification(evt)
assert text is not None
assert "SUBAGENT MODEL REJECTED" not in text
+
+
+# ---------------------------------------------------------------------------
+# Per-group completion units: ungrouped tasks return alone, a `group` returns
+# together, and the units of one call share ONE capacity slot.
+# ---------------------------------------------------------------------------
+
+def _grouped_fanout(monkeypatch, tasks, gates):
+ """delegate_task(tasks) in the background with gated fake children; returns the parsed handle."""
+ from unittest.mock import MagicMock
+ import tools.delegate_tool as dt
+
+ parent = MagicMock()
+ parent._delegate_depth = 0
+ parent.session_id = "sess"
+ parent._interrupt_requested = False
+ parent._active_children = []
+ parent._active_children_lock = None
+
+ def child(task_index, goal, child=None, parent_agent=None, **kw):
+ gates[task_index].wait(timeout=60)
+ return {"task_index": task_index, "status": "completed", "summary": f"done: {goal}", "api_calls": 1,
+ "duration_seconds": 0.1, "model": "m", "exit_reason": "completed"}
+
+ def build(**kw):
+ c = MagicMock()
+ c._delegate_role = "leaf"
+ c._subagent_id = f"s{kw['task_index']}"
+ return c
+
+ creds = {"model": "m", "provider": None, "base_url": None, "api_key": None, "api_mode": None, "command": None,
+ "args": None}
+ monkeypatch.setattr(dt, "_build_child_agent", build)
+ monkeypatch.setattr(dt, "_run_single_child", child)
+ monkeypatch.setattr(dt, "_resolve_delegation_credentials", lambda *a, **k: creds)
+ return json.loads(dt.delegate_task(tasks=tasks, background=True, parent_agent=parent))
+
+
+def test_ungrouped_task_completes_alone_and_group_completes_together(monkeypatch):
+ """A finished ungrouped task must not wait for its siblings; tasks sharing a `group` must."""
+ gates = [threading.Event() for _ in range(4)]
+ tasks = [
+ {"goal": "review PR 1 thoroughly and report"},
+ {"goal": "compare approach A in detail", "group": "cmp"},
+ {"goal": "compare approach B in detail", "group": "cmp"},
+ {"goal": "review PR 2 thoroughly and report"},
+ ]
+ handle = _grouped_fanout(monkeypatch, tasks, gates)
+ assert handle["status"] == "dispatched"
+ by_group = {tuple(u["task_indexes"]): u["group"] for u in handle["units"]}
+ assert by_group == {(0,): None, (1, 2): "cmp", (3,): None}
+
+ gates[3].set()
+ evt = _drain_one()
+ assert [r["task_index"] for r in evt["results"]] == [3] # PR 2 landed while everything else still runs
+ assert "review PR 2" in format_process_notification(evt)
+
+ gates[1].set()
+ assert _drain_one(timeout=0.5) is None # half a group is not a completion
+ gates[2].set()
+ evt = _drain_one()
+ assert evt["group"] == "cmp" and [r["task_index"] for r in evt["results"]] == [1, 2]
+
+ gates[0].set()
+ assert [r["task_index"] for r in _drain_one()["results"]] == [0]
+
+
+def test_units_of_one_call_share_a_single_capacity_slot():
+ """Splitting a call into per-task completions must not consume more pool capacity than the call did."""
+ gate = threading.Event()
+
+ def blocker():
+ gate.wait(timeout=60)
+ return {"results": [], "total_duration_seconds": 0}
+
+ common = dict(goals=["a", "b"], context=None, toolsets=None, role="leaf", model="m", session_key="",
+ runner=blocker, max_async_children=1)
+ first = ad.dispatch_async_delegation_batch(delegation_id="deleg_call-1", task_indexes=[0], **common)
+ second = ad.dispatch_async_delegation_batch(delegation_id="deleg_call-2", task_indexes=[1],
+ slot_key="deleg_call-1", **common)
+ other = ad.dispatch_async_delegation_batch(delegation_id="deleg_other", **common)
+ assert (first["status"], second["status"], other["status"]) == ("dispatched", "dispatched", "rejected")
+ assert ad.active_task_count() == 2
+ gate.set()
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 7e6526a72a8..fa624f2bb7b 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -79,7 +79,10 @@ fixed at the mount, not by adding a tool.
Spawns a subagent with isolated context + terminal session; the parent waits for the summary unless
`background=true`, which returns a delegation id and re-enters the result via the async-delegation
completion queue. Shapes: single (`goal` + optional `context`, `toolsets`) or batch (`tasks: [...]`,
-concurrency capped by `delegation.max_concurrent_children`, default 3). Roles: `leaf` (default;
+concurrency capped by `delegation.max_concurrent_children`, default 3). A background batch is split
+into completion **units** (`delegate_tool_dispatch._units_of`): tasks sharing a `group` join and
+report together; each ungrouped task reports alone as it finishes. Units of one call share ONE pool
+slot (`slot_key` in `async_delegation._dispatch`) — never count units against capacity. Roles: `leaf` (default;
no `delegate_task`, `clarify`, `memory`, `send_message`, `cronjob`; keeps `execute_code`) and
`orchestrator` (keeps `delegate_task`; gated by `delegation.orchestrator_enabled`, bounded by
`delegation.max_spawn_depth`, default 2). Config knobs under `delegation:`:
diff --git a/tools/async_delegation.py b/tools/async_delegation.py
index 1ef7fbdc275..9efa18af4f5 100644
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@ -415,7 +415,7 @@ def _get_executor(max_workers: int) -> ThreadPoolExecutor:
def active_count() -> int:
- """Number of live async delegation UNITS (a whole batch counts as ONE slot)."""
+ """Number of live async delegation UNITS (one per completion message: a task group or an ungrouped task)."""
with _records_lock:
return sum(1 for r in _records.values() if r.get("status") in _LIVE_STATES)
@@ -425,7 +425,8 @@ def active_task_count() -> int:
no goal list counts 1) — the truthful observability figure, unlike slots."""
with _records_lock:
return sum(
- len(r["goals"]) if r.get("is_batch") and isinstance(r.get("goals"), (list, tuple)) and r["goals"] else 1
+ len(r.get("task_indexes") or r["goals"])
+ if r.get("is_batch") and isinstance(r.get("goals"), (list, tuple)) and r["goals"] else 1
for r in _records.values() if r.get("status") in {"running", "finalizing"})
@@ -496,12 +497,15 @@ def _dispatch(
toolsets: Optional[List[str]], role: str, model: Optional[str], session_key: str,
parent_session_id: Optional[str], runner: Callable[[], Dict[str, Any]], origin_ui_session_id: str,
origin_session_id: str, interrupt_fn: Optional[Callable[[], None]], max_async_children: int,
- progress_fn: Optional[Callable[[], tuple]], capacity_error: str,
+ progress_fn: Optional[Callable[[], tuple]], capacity_error: str, slot_key: Optional[str] = None,
+ task_indexes: Optional[List[int]] = None,
) -> Dict[str, Any]:
"""Shared dispatch core for single (``goals is None``) and batch units. Capacity check +
record insert happen under ONE lock hold so concurrent dispatches can't both pass the check
and exceed the cap. At capacity the dispatch is REJECTED (never queued) so a runaway model
- can't pile up unbounded background work."""
+ can't pile up unbounded background work. ``slot_key`` names the pool slot the unit occupies
+ (default: its own id); the units of one delegate_task call share the first unit's id so
+ splitting a call into per-group completions never consumes more capacity than the call did."""
is_batch = goals is not None
label = " batch" if is_batch else ""
classify = _batch_status if is_batch else (lambda r: r.get("status") or "completed")
@@ -515,11 +519,14 @@ def _dispatch(
**_capture_routing_origin(),
"status": "running", "dispatched_at": dispatched_at, "completed_at": None,
"interrupt_fn": interrupt_fn, **({"is_batch": True} if is_batch else {}), "progress_fn": progress_fn,
+ "slot_key": slot_key or delegation_id,
+ # Which of the call's ``goals`` this unit runs (None = all of them).
+ **({"task_indexes": list(task_indexes)} if task_indexes is not None else {}),
# Stale-monitor bookkeeping (see _stale_monitor_loop).
"_progress_token": None, "_progress_ts": dispatched_at, "_interrupted_at": None}
with _records_lock:
- running = sum(1 for r in _records.values() if r.get("status") in _ACTIVE_STATES)
- if running >= max_async_children:
+ active_slots = {r.get("slot_key") or r["delegation_id"] for r in _records.values() if r.get("status") in _ACTIVE_STATES}
+ if record["slot_key"] not in active_slots and len(active_slots) >= max_async_children:
return {"status": "rejected", "error": capacity_error}
_records[delegation_id] = record
_persist_dispatch(record)
@@ -584,21 +591,26 @@ def dispatch_async_delegation_batch(
session_key: str, parent_session_id: Optional[str] = None, runner: Callable[[], Dict[str, Any]],
origin_ui_session_id: str = "", origin_session_id: str = "", interrupt_fn: Optional[Callable[[], None]] = None,
max_async_children: int = _DEFAULT_MAX_ASYNC_CHILDREN, delegation_id: Optional[str] = None,
- progress_fn: Optional[Callable[[], tuple]] = None,
+ progress_fn: Optional[Callable[[], tuple]] = None, slot_key: Optional[str] = None,
+ task_indexes: Optional[List[int]] = None,
) -> Dict[str, Any]:
- """Dispatch a WHOLE fan-out batch as ONE background unit: ``runner`` runs the
- entire batch and returns the combined ``{"results": [...], "total_duration_seconds": N}``
- dict. The batch occupies ONE async slot (in-batch parallelism is bounded
- separately) and produces a SINGLE completion event carrying per-task ``results``."""
+ """Dispatch a fan-out unit (a whole batch, or one ``group`` of a delegate_task call) as ONE
+ background unit: ``runner`` runs its tasks and returns the combined ``{"results": [...],
+ "total_duration_seconds": N}`` dict. The unit occupies ONE async slot — or joins the slot named
+ by ``slot_key`` (in-unit parallelism is bounded separately) — and produces a SINGLE completion
+ event carrying per-task ``results``."""
delegation_id = delegation_id or _new_delegation_id()
- n = len(goals)
- combined_goal = goals[0] if n == 1 else f"{n} parallel subagents: " + "; ".join(g[:40] for g in goals)
+ # ``goals`` is the whole call (result task_index indexes it); the unit's own goals label the record.
+ unit_goals = [goals[i] for i in task_indexes] if task_indexes is not None else list(goals)
+ n = len(unit_goals)
+ combined_goal = unit_goals[0] if n == 1 else f"{n} parallel subagents: " + "; ".join(g[:40] for g in unit_goals)
handle = _dispatch(
delegation_id=delegation_id, goal=combined_goal, goals=goals, context=context,
toolsets=toolsets, role=role, model=model, session_key=session_key,
parent_session_id=parent_session_id, runner=runner,
origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id,
- interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn,
+ interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn, slot_key=slot_key,
+ task_indexes=task_indexes,
capacity_error=(
f"Async delegation capacity reached ({max_async_children} running). Wait for one to finish "
"(its result will re-enter the chat), or raise delegation.max_concurrent_children in "
@@ -651,7 +663,8 @@ def _push_completion_event(record: Dict[str, Any], result: Dict[str, Any], statu
payload = {
"is_batch": True, "results": result.get("results") or [],
"live_transcripts": result.get("live_transcripts"), "error": result.get("error"),
- "total_duration_seconds": result.get("total_duration_seconds")}
+ "total_duration_seconds": result.get("total_duration_seconds"),
+ **({"group": result["group"]} if result.get("group") is not None else {})}
else:
payload = {
"summary": result.get("summary"), "error": result.get("error"), "api_calls": result.get("api_calls", 0),
diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py
index 70e98fe6a6f..5845be46ab1 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -457,8 +457,9 @@ _DESCRIPTION_HEAD = (
"Spawn subagents in isolated contexts; each gets its own conversation, terminal session, and toolset, and only its "
"final summary returns to you. Pass every task in `tasks` — one entry spawns one subagent, several run in parallel "
"(limit in the tasks description).\n\n"
- "Runs in the background: dispatch returns immediately with live transcript paths, and the completed result (one "
- "consolidated message, results in task order) re-enters the conversation on its own. Do NOT wait or poll; continue "
+ "Runs in the background: dispatch returns immediately with live transcript paths, and each completed unit "
+ "re-enters the conversation on its own — an ungrouped task as soon as IT finishes, tasks sharing a `group` "
+ "together once all of them finish. Handle each result as it lands. Do NOT wait or poll; continue "
"other work. While children run, `action` (list/steer/stop) controls them live — steer when a transcript shows a "
"child drifting.\n\n"
"USE FOR: reasoning-heavy subtasks, work that would flood your context with intermediate data, or independent "
@@ -546,6 +547,13 @@ DELEGATE_TASK_SCHEMA = {
"schema_valid, plus schema_errors on failure). Keep it forgiving — require only "
"fields you will read.",
),
+ "group": _p(
+ "string",
+ "Optional completion group. Tasks sharing a group wait for each other and return as ONE "
+ "message (use when you must compare or merge their results); a task without a group "
+ "returns on its own the moment it finishes. Independent work (separate PR reviews, "
+ "unrelated fixes) should stay ungrouped so nothing waits for the slowest sibling.",
+ ),
},
"required": ["goal"],
},
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index 03093da0e6f..6d21dc566aa 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -1,6 +1,7 @@
"""Batch execution + background dispatch for delegate_task: ``delegate_task`` builds a ``_Batch``
-(children + origin identity) and hands it to ``_run_batch``, which runs it synchronously or as ONE
-detached async unit."""
+(children + origin identity) and hands it to ``_run_batch``, which runs it synchronously or as
+detached async units — one per task ``group`` (ungrouped tasks are a unit each), so a finished
+review does not wait for the slowest sibling."""
from __future__ import annotations
@@ -9,7 +10,7 @@ import json
import logging
import time
from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Any, Dict, List, Optional
from tools.delegate_tool_child_run import _detach_child, _fabricated_entry, _signal_child_stop
@@ -42,6 +43,8 @@ class _Batch:
origin_owner_transport: Any
origin_owner_session_record: Any
overall_start: float
+ # Set on per-group units carved out by ``_dispatch_background``; None for the whole batch / ungrouped units.
+ group: Optional[str] = None
def owner_kwargs(self) -> Dict[str, Any]:
"""Steer/stop authority of the originating session, passed to every child run."""
@@ -103,6 +106,7 @@ def _run_children_parallel(batch: _Batch, results: list, *, honor_parent_interru
_tag = format_batch_tag(batch.live_deleg_id, parent_agent)
# Fabricated entries for still-pending / raised futures carry the correct _delegate_role.
_child_by_index = {i: child for (i, _, child) in batch.children}
+ n_here = len(batch.children) # a per-group unit runs a subset; ``n_tasks`` keeps the call-wide ``i/N`` slot
def _entry_of(future, idx):
if not future.done():
@@ -125,17 +129,17 @@ def _run_children_parallel(batch: _Batch, results: list, *, honor_parent_interru
for future in done:
entry = _entry_of(future, futures[future])
results.append(entry)
- _report_child_done(parent_agent, spinner_ref, entry, _tag, task_labels, n_tasks, n_tasks - len(results))
+ _report_child_done(parent_agent, spinner_ref, entry, _tag, task_labels, n_tasks, n_here - len(results))
results.sort(key=lambda r: r["task_index"]) # match input order
def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = True) -> dict:
- """Run all built children, join, finalize (hooks + cost rollup), return the combined dict. Shared by the sync path
- and the background runner: even in the background the batch JOINS on itself here so ONE consolidated results
- block re-enters the conversation. Live transcripts are finalized but retained as the full-fidelity record
- (retention pruning happens on future dispatches)."""
+ """Run the batch's built children, join, finalize (hooks + cost rollup), return the combined dict. Shared by the
+ sync path and the background runner; a background runner receives a per-group unit (a subset of the call's
+ children) so each group JOINS only on itself. Live transcripts are finalized but retained as the full-fidelity
+ record (retention pruning happens on future dispatches)."""
from tools.delegation_live_log import update_manifest_statuses
results: list = []
- if len(batch.task_list) == 1:
+ if len(batch.children) == 1:
results.append(batch.run_child(*batch.children[0]))
else:
_run_children_parallel(batch, results, honor_parent_interrupt=honor_parent_interrupt)
@@ -152,8 +156,11 @@ def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = True
update_manifest_statuses(batch.live_deleg_id, results)
combined: Dict[str, Any] = {"results": results, "total_duration_seconds": total_duration}
- if batch.live_paths:
- combined["live_transcripts"] = list(batch.live_paths)
+ unit_paths = [batch.live_paths[i] for (i, _, _) in batch.children if i < len(batch.live_paths)]
+ if unit_paths:
+ combined["live_transcripts"] = unit_paths
+ if batch.group is not None:
+ combined["group"] = batch.group
return combined
_SYNC_FALLBACK_NOTES = {
@@ -256,9 +263,10 @@ _BACKGROUND_NOTES = {
"conversation as a new message when it finishes. Do not wait or poll — just continue."
),
"many": (
- "{n} subagents are running in parallel in the background. You and the user can keep working; they wait on "
- "each other and their consolidated results re-enter the conversation as a single message once ALL of them "
- "finish. Do not wait or poll — just continue."
+ "{n} subagents are running in parallel in the background as {k} independent unit(s). You and the user can keep "
+ "working; each unit's results re-enter the conversation as their own message as soon as THAT unit finishes "
+ "(tasks sharing a `group` finish together; ungrouped tasks report individually), so act on each as it lands. "
+ "Do not wait or poll — just continue."
),
"control_hint": (
"While a child runs you can orchestrate it live with this same tool: delegate_task(action='list') to see live "
@@ -271,29 +279,66 @@ _BACKGROUND_NOTES = {
),
}
-def _dispatched_payload(dispatch: dict, goals: List[str], child_agents: List[Any], live_paths: List[str]) -> dict:
- """Model-facing handle for an accepted background batch."""
+def _dispatched_payload(batch: _Batch, units: List[tuple[_Batch, str]]) -> dict:
+ """Model-facing handle for an accepted background call: one entry per async unit."""
+ goals = [t["goal"] for t in batch.task_list]
n = len(goals)
payload = {
- "status": "dispatched", "mode": "background", "count": n, "delegation_id": dispatch["delegation_id"],
- "goals": goals, "note": _BACKGROUND_NOTES["one"] if n == 1 else _BACKGROUND_NOTES["many"].format(n=n),
+ "status": "dispatched", "mode": "background", "count": n,
+ "delegation_id": batch.live_deleg_id or units[0][1], "goals": goals,
+ "note": _BACKGROUND_NOTES["one"] if n == 1 else _BACKGROUND_NOTES["many"].format(n=n, k=len(units)),
}
- sids = [getattr(c, "_subagent_id", None) for c in child_agents]
+ if len(units) > 1:
+ payload["units"] = [
+ {"delegation_id": uid, "group": unit.group, "task_indexes": [i for (i, _, _) in unit.children]}
+ for unit, uid in units
+ ]
+ sids = [getattr(c, "_subagent_id", None) for (_, _, c) in batch.children]
if any(isinstance(s, str) and s for s in sids):
payload["subagent_ids"] = sids
payload["control_hint"] = _BACKGROUND_NOTES["control_hint"]
- if live_paths:
- payload["live_transcripts"] = list(live_paths)
+ if batch.live_paths:
+ payload["live_transcripts"] = list(batch.live_paths)
payload["live_transcripts_hint"] = _BACKGROUND_NOTES["live_transcripts_hint"]
return payload
+def _units_of(batch: _Batch) -> List[_Batch]:
+ """Partition the call's children into async units: one per distinct task ``group`` (first-appearance order) and
+ one per ungrouped task. Each unit is a ``_Batch`` sharing the call's task_list/transcripts but owning a subset of
+ ``children``, so a unit joins only on itself and its completion re-enters the conversation on its own."""
+ members: Dict[Any, List[tuple]] = {}
+ for i, t, c in batch.children:
+ g = t.get("group")
+ key = ("g", str(g)) if g not in (None, "") else ("i", i)
+ members.setdefault(key, []).append((i, t, c))
+ return [replace(batch, children=ch, group=(key[1] if key[0] == "g" else None)) for key, ch in members.items()]
+
+def _dispatch_unit(unit: _Batch, unit_id: Optional[str], slot_key: Optional[str], routing: dict) -> dict:
+ """Hand ONE unit to the async registry; the runner joins on that unit's children only."""
+ from tools.async_delegation import dispatch_async_delegation_batch
+ child_agents = [c for (_, _, c) in unit.children]
+
+ def _interrupt():
+ for c in child_agents:
+ _signal_child_stop(c, "Async delegation cancelled")
+
+ return dispatch_async_delegation_batch(
+ # Call-wide goals: completion formatting indexes them by task_index.
+ goals=[t["goal"] for t in unit.task_list], context=unit.context,
+ toolsets=None, # metadata for the completion block only; subagents inherit the parent's toolsets
+ role=unit.top_role, model=unit.creds["model"],
+ runner=lambda: _execute_and_aggregate(unit, honor_parent_interrupt=False),
+ interrupt_fn=_interrupt, delegation_id=unit_id, slot_key=slot_key,
+ task_indexes=[i for (i, _, _) in unit.children] if len(unit.children) < len(unit.task_list) else None,
+ progress_fn=lambda: _batch_progress_token(child_agents), **routing,
+ )
+
def _dispatch_background(batch: _Batch) -> str:
- """Dispatch the WHOLE batch as one async unit and return the tool result JSON. The runner joins on every child and
- yields ONE consolidated results block that re-enters the conversation as a single message when ALL children
- finish. Falls back to running synchronously (with an explanatory ``note``) when the session cannot receive
- detached completions or the async pool is at capacity."""
+ """Dispatch the call as independent async units (see ``_units_of``) and return the tool result JSON. Every unit
+ of one call shares ONE pool slot (``slot_key``), so grouping never changes capacity accounting. Falls back to
+ running synchronously (with an explanatory ``note``) when the session cannot receive detached completions or the
+ async pool is at capacity."""
from tools.delegate_tool import _get_max_async_children
- from tools.async_delegation import dispatch_async_delegation_batch
wake_sid = _resolve_async_wake_sid(batch.origin_wake_sid)
if wake_sid is None:
logger.info("delegate_task: async delivery unsupported on this session runtime; running the batch synchronously instead.")
@@ -301,40 +346,42 @@ def _dispatch_background(batch: _Batch) -> str:
parent_agent = batch.parent_agent
session_key, origin_ui_session_id = _resolve_async_session_key(parent_agent, batch.origin_ui_session_id)
- child_agents = [c for (_, _, c) in batch.children]
- # The batch's lifecycle is owned by the async registry now: drop the children from the parent's
+ # The children's lifecycle is owned by the async registry now: drop them from the parent's
# interrupt-propagation list (_build_child_agent attached them, which is correct for sync runs).
- for c in child_agents:
+ for (_, _, c) in batch.children:
_detach_child(parent_agent, c)
-
- def _batch_interrupt():
- # Cancellation path for the detached batch (owned by the async registry).
- for c in child_agents:
- _signal_child_stop(c, "Async delegation cancelled")
-
- goals = [t["goal"] for t in batch.task_list]
- dispatch = dispatch_async_delegation_batch(
- goals=goals, context=batch.context,
- toolsets=None, # metadata for the completion block only; subagents inherit the parent's toolsets
- role=batch.top_role, model=batch.creds["model"], session_key=session_key,
- origin_ui_session_id=origin_ui_session_id, origin_session_id=wake_sid,
- parent_session_id=getattr(parent_agent, "session_id", None),
- runner=lambda: _execute_and_aggregate(batch, honor_parent_interrupt=False),
- interrupt_fn=_batch_interrupt, max_async_children=_get_max_async_children(),
- # Reuse the live-transcript directory's id (when created) so the returned delegation_id matches
- # cache/delegation/live/<id>/.
- delegation_id=batch.live_deleg_id,
- progress_fn=lambda: _batch_progress_token(child_agents),
- )
- if dispatch.get("status") == "dispatched":
- return json.dumps(_dispatched_payload(dispatch, goals, child_agents, batch.live_paths), ensure_ascii=False)
- # Pool at capacity / schedule failure: the async unit was never accepted, so just run inline (re-attaching to the
- # parent list is not needed).
- logger.info(
- "delegate_task: async pool at capacity (%s); running the whole batch synchronously instead.",
- dispatch.get("error", "rejected"),
+ routing = dict(
+ session_key=session_key, origin_ui_session_id=origin_ui_session_id, origin_session_id=wake_sid,
+ parent_session_id=getattr(parent_agent, "session_id", None), max_async_children=_get_max_async_children(),
)
- return _run_sync_with_note(batch, "at_capacity")
+
+ units = _units_of(batch)
+ dispatched: List[tuple[_Batch, str]] = []
+ inline_results: List[dict] = []
+ slot_key: Optional[str] = None
+ for k, unit in enumerate(units):
+ # One unit keeps the live-transcript directory's id so the returned delegation_id matches
+ # cache/delegation/live/<id>/; several units suffix it (-1, -2, ...) and the call keeps the bare id.
+ unit_id = batch.live_deleg_id if len(units) == 1 else (f"{batch.live_deleg_id}-{k + 1}" if batch.live_deleg_id else None)
+ dispatch = _dispatch_unit(unit, unit_id, slot_key, routing)
+ if dispatch.get("status") == "dispatched":
+ slot_key = slot_key or dispatch["delegation_id"]
+ dispatched.append((unit, dispatch["delegation_id"]))
+ continue
+ if not dispatched:
+ logger.info(
+ "delegate_task: async pool at capacity (%s); running the whole batch synchronously instead.",
+ dispatch.get("error", "rejected"),
+ )
+ return _run_sync_with_note(batch, "at_capacity")
+ # Later units of an admitted call share its slot and cannot be capacity-rejected; a scheduler failure runs
+ # the unit inline so no task is silently dropped.
+ logger.warning("delegate_task: unit %d/%d not accepted (%s); running it inline.", k + 1, len(units), dispatch.get("error"))
+ inline_results.extend(_execute_and_aggregate(unit, honor_parent_interrupt=False)["results"])
+ payload = _dispatched_payload(batch, dispatched)
+ if inline_results:
+ payload["inline_results"] = inline_results
+ return json.dumps(payload, ensure_ascii=False)
def _run_batch(batch: _Batch, background: bool) -> str:
"""Tool result JSON: a dispatch handle (background) or the joined combined results."""
diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py
index 15c9355867a..12944f01606 100644
--- a/tools/process_registry_notifications.py
+++ b/tools/process_registry_notifications.py
@@ -116,14 +116,16 @@ def _preamble(evt: dict, title: str, intro: str, completed_at: float, *, with_go
def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> str:
"""Consolidated block for a delegate_task fan-out that finished as one unit."""
results, goals = evt.get("results") or [], evt.get("goals") or []
- n = len(results) if results else len(goals)
+ # ``goals`` is the whole delegate_task call (task_index indexes it); ``results`` is this unit's subset.
+ n, n_unit = len(goals) or len(results), len(results) or len(goals)
+ group = evt.get("group")
+ unit = f"group '{group}' ({n_unit} subagent(s))" if group is not None else f"{n_unit} subagent(s)"
lines = _preamble(
evt,
f"[ASYNC DELEGATION BATCH COMPLETE — {deleg_id}]",
- f"A background fan-out of {n} subagent(s) you dispatched earlier "
- "has finished. All ran in parallel and waited on each other; their "
- "consolidated results are below. You may have moved on since "
- "dispatching — act on these or re-dispatch if things have changed.",
+ f"A background fan-out unit you dispatched earlier — {unit} — has finished; its consolidated results are "
+ "below. Other units from the same delegate_task call (other groups / ungrouped tasks) report separately as "
+ "they finish. You may have moved on since dispatching — act on these or re-dispatch if things have changed.",
completed_at, with_goal=False)
lines[-1] += f" Total duration: {evt.get('total_duration_seconds', evt.get('duration_seconds', '?'))}s"
if evt.get("error") and not results:
diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.md
index a4ce8aba3b3..e417e55fbe1 100644
--- a/website/docs/user-guide/features/delegation.md
+++ b/website/docs/user-guide/features/delegation.md
@@ -117,12 +117,26 @@ delegate_task(
## Batch Mode Details
-When a top-level agent provides a `tasks` array, Hermes returns one background handle, runs the subagents in parallel, and posts one consolidated result after every child finishes. An orchestrator subagent waits for its batch in the current turn so it can synthesize the results.
+When a top-level agent provides a `tasks` array, Hermes returns one background handle and runs the subagents in parallel. Results come back **per completion unit**, not once at the end:
+
+- A task **without** a `group` is its own unit: its result re-enters the conversation the moment that subagent finishes, so five independent PR reviews land as five messages and the agent acts on each without waiting for the slowest one.
+- Tasks that share a `group` string wait for each other and return as **one** consolidated message (use this when the parent must compare or merge their outputs).
+
+```json
+{"tasks": [
+ {"goal": "Review PR #101 ..."},
+ {"goal": "Review PR #102 ..."},
+ {"goal": "Benchmark approach A ...", "group": "bench"},
+ {"goal": "Benchmark approach B ...", "group": "bench"}
+]}
+```
+
+The dispatch handle lists each unit (`units[].delegation_id`, `group`, `task_indexes`); unit ids are the call's id suffixed `-1`, `-2`, …, and every unit of one call shares a single slot of `delegation.max_concurrent_children`, so grouping never changes capacity accounting. An orchestrator subagent waits for its whole batch in the current turn so it can synthesize the results.
- **Maximum concurrency:** 3 tasks by default (configurable via `delegation.max_concurrent_children` or the `DELEGATION_MAX_CONCURRENT_CHILDREN` env var; floor of 1, no hard ceiling). Batches larger than the limit return a tool error rather than being silently truncated.
- **Thread pool:** Uses `ThreadPoolExecutor` with the configured concurrency limit as max workers
- **Progress display:** In CLI mode, a tree-view shows tool calls from each subagent in real-time with per-task completion lines. In gateway mode, progress is batched and relayed to the parent's progress callback
-- **Result ordering:** Results are sorted by task index to match input order regardless of completion order
+- **Result ordering:** Within a unit, results are sorted by task index to match input order regardless of completion order; `TASK i/N` labels index the whole call
- **Cancellation:** Follow-up messages do not cancel a top-level background batch. `/stop` or closing/resetting the owning session cancels its active children. Synchronous orchestrator children still follow their parent's interrupt state
Synchronous single-task delegation from an orchestrator runs directly without thread pool overhead.