2026-09-02 19:43:56 -07:00
|
|
|
"""Batch execution + background dispatch for delegate_task: ``delegate_task`` builds a ``_Batch``
|
2026-09-06 06:19:11 -07:00
|
|
|
(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."""
|
2026-09-02 13:55:32 -07:00
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import contextvars
|
|
|
|
|
import json
|
|
|
|
|
import logging
|
2026-09-02 17:50:16 -07:00
|
|
|
import time
|
2026-09-02 15:40:23 -07:00
|
|
|
from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait
|
2026-10-22 08:08:22 -07:00
|
|
|
from dataclasses import dataclass, field, replace
|
2026-11-04 01:55:20 -08:00
|
|
|
from functools import partial
|
2026-09-02 13:55:32 -07:00
|
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
|
2026-09-27 17:33:28 -07:00
|
|
|
from hermes_cli.observability.shared_metrics_loop import begin_delegation_run, finish_delegation_unit
|
2026-09-06 08:10:00 -07:00
|
|
|
from tools.async_delegation import _new_delegation_id, record_unit_child
|
2026-11-04 03:20:23 -08:00
|
|
|
from tools.delegate_tool_child_run import _attach_child, _close_child, _detach_child, _fabricated_entry, _signal_child_stop
|
2026-09-02 13:55:32 -07:00
|
|
|
from tools.delegate_tool_progress import (
|
2026-09-14 23:01:23 -07:00
|
|
|
SUBAGENT_FAILURE_STATUSES, _print_completion_line, _quiet, describe_subagent_failure, format_batch_tag,
|
2026-09-02 13:55:32 -07:00
|
|
|
)
|
2026-09-02 17:50:16 -07:00
|
|
|
from tools.delegate_tool_registry import _capture_gateway_steer_authority
|
|
|
|
|
from tools.delegate_tool_results import _finalize_child_results
|
2026-09-02 13:55:32 -07:00
|
|
|
|
2026-09-02 19:43:56 -07:00
|
|
|
logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module
|
2026-09-02 13:55:32 -07:00
|
|
|
|
2026-09-02 17:50:16 -07:00
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class _Batch:
|
|
|
|
|
"""One delegate_task call's built children plus everything needed to run them
|
|
|
|
|
and assemble the combined result (shared by the sync path and the background runner)."""
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
task_list: list[dict[str, Any]]
|
|
|
|
|
children: list[tuple]
|
2026-09-02 17:50:16 -07:00
|
|
|
parent_agent: Any
|
2026-10-08 17:22:54 +02:00
|
|
|
creds: dict[str, Any]
|
2026-09-02 17:50:16 -07:00
|
|
|
context: Optional[str]
|
|
|
|
|
top_role: str
|
|
|
|
|
max_children: int
|
|
|
|
|
live_deleg_id: Optional[str]
|
|
|
|
|
live_writers: list
|
|
|
|
|
live_paths: list
|
|
|
|
|
origin_wake_sid: str
|
|
|
|
|
origin_ui_session_id: str
|
|
|
|
|
origin_owner_transport: Any
|
|
|
|
|
origin_owner_session_record: Any
|
2026-09-07 02:35:42 -07:00
|
|
|
origin_session_history_delivery: bool
|
2026-09-02 17:50:16 -07:00
|
|
|
overall_start: float
|
2026-09-06 06:19:11 -07:00
|
|
|
# Set on per-group units carved out by ``_dispatch_background``; None for the whole batch / ungrouped units.
|
|
|
|
|
group: Optional[str] = None
|
2026-09-06 08:10:00 -07:00
|
|
|
unit_id: Optional[str] = None # the async registry id this unit runs under (``<call_id>-k`` for split calls)
|
2026-08-29 08:22:21 +08:00
|
|
|
live_home: Any = None # explicit profile home for transcripts/manifest (#91996); None = ambient resolve
|
2026-10-22 08:08:22 -07:00
|
|
|
# Result entries of tasks their backend refused (no child): joined into a sync result, listed in a background
|
|
|
|
|
# call's dispatch payload. Units carved for async dispatch never carry them.
|
|
|
|
|
refused: list = field(default_factory=list)
|
2026-09-02 17:50:16 -07:00
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def owner_kwargs(self) -> dict[str, Any]:
|
2026-09-02 17:50:16 -07:00
|
|
|
"""Steer/stop authority of the originating session, passed to every child run."""
|
|
|
|
|
return {
|
2026-09-02 19:04:50 -07:00
|
|
|
"owner_session_id": self.origin_ui_session_id or None, "owner_transport": self.origin_owner_transport,
|
2026-09-02 17:50:16 -07:00
|
|
|
"owner_session_record": self.origin_owner_session_record,
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def run_child(self, i: int, task: dict[str, Any], child: Any) -> dict[str, Any]:
|
2026-09-02 18:52:58 -07:00
|
|
|
from tools.delegate_tool import _run_single_child
|
|
|
|
|
return _run_single_child(task_index=i, goal=task["goal"], child=child, parent_agent=self.parent_agent, **self.owner_kwargs())
|
|
|
|
|
|
2026-09-02 17:50:16 -07:00
|
|
|
|
|
|
|
|
def _announce_batch(parent_agent, n_tasks: int, live_deleg_id: Optional[str]) -> None:
|
|
|
|
|
"""Announce the batch tag once so interleaved ``[tag n/N]`` lines are attributable."""
|
2026-09-02 18:52:58 -07:00
|
|
|
if n_tasks > 1 and live_deleg_id:
|
2026-09-06 02:39:31 -07:00
|
|
|
_hdr = f" 🔀 [{format_batch_tag(live_deleg_id, parent_agent)}] delegating {n_tasks} tasks"
|
2026-09-02 18:52:58 -07:00
|
|
|
_print_completion_line(parent_agent, getattr(parent_agent, "_delegate_spinner", None), _hdr, console_line=_hdr)
|
2026-09-02 17:50:16 -07:00
|
|
|
|
2026-09-07 09:57:02 +08:00
|
|
|
def _capture_origin() -> tuple[str, str, Any, Any, bool]:
|
2026-09-07 02:35:42 -07:00
|
|
|
"""``(wake_sid, ui_session_id, owner_transport, owner_session_record, session_history_delivery)`` of the
|
2026-09-02 17:50:16 -07:00
|
|
|
ORIGINATING session, captured BEFORE building any child: AIAgent construction
|
2026-09-07 09:57:02 +08:00
|
|
|
clobbers the HERMES_SESSION_ID ContextVar/os.environ with the subagent's id. The wake-
|
|
|
|
|
capability flag rides the same request-scoped binding and is captured here for the same
|
|
|
|
|
reason — and fails closed: a binding that never declared it (or a read error) leaves the
|
|
|
|
|
session treated as non-wake-capable (#98619)."""
|
2026-09-02 17:50:16 -07:00
|
|
|
from tools.async_delegation import _current_origin_session_id
|
|
|
|
|
_origin_wake_sid = _current_origin_session_id()
|
|
|
|
|
_origin_ui_session_id = ""
|
2026-09-07 02:35:42 -07:00
|
|
|
_origin_session_history_delivery = False
|
2026-09-02 17:50:16 -07:00
|
|
|
with _quiet(None):
|
2026-09-07 02:35:42 -07:00
|
|
|
from gateway.session_context import get_session_env, session_history_delivery_supported
|
2026-09-02 17:50:16 -07:00
|
|
|
_origin_ui_session_id = get_session_env("HERMES_UI_SESSION_ID", "")
|
2026-09-07 02:35:42 -07:00
|
|
|
_origin_session_history_delivery = session_history_delivery_supported()
|
|
|
|
|
return (_origin_wake_sid, _origin_ui_session_id, *_capture_gateway_steer_authority(_origin_ui_session_id), _origin_session_history_delivery)
|
2026-09-02 17:50:16 -07:00
|
|
|
|
2026-09-02 16:54:15 -07:00
|
|
|
def _report_child_done(parent_agent, spinner_ref, entry, tag, task_labels, n_tasks, remaining) -> None:
|
2026-09-02 19:25:04 -07:00
|
|
|
"""Print one completion line for a finished child and refresh the spinner text. Failed/errored/timed-out children
|
|
|
|
|
say WHY on the same line — a bare ✗ reads as "silently dropped"."""
|
2026-09-02 16:54:15 -07:00
|
|
|
idx = entry["task_index"]
|
|
|
|
|
label = task_labels[idx] if idx < len(task_labels) else f"Task {idx}"
|
|
|
|
|
status = entry.get("status", "?")
|
|
|
|
|
_slot = f"{tag} · {idx+1}/{n_tasks}" if tag else f"{idx+1}/{n_tasks}"
|
2026-09-14 22:46:08 -07:00
|
|
|
schema_invalid = entry.get("schema_valid") is False and status == "completed"
|
|
|
|
|
icon = "⚠" if schema_invalid else ("✓" if status == "completed" else "✗")
|
|
|
|
|
completion_line = f"{icon} [{_slot}] {label} ({entry.get('duration_seconds', 0)}s)"
|
2026-09-14 23:01:23 -07:00
|
|
|
_err_line = (
|
|
|
|
|
describe_subagent_failure(entry.get("failure_reason"), entry.get("error"), max_chars=120)
|
|
|
|
|
if status in SUBAGENT_FAILURE_STATUSES else "")
|
2026-09-14 22:46:08 -07:00
|
|
|
if schema_invalid:
|
|
|
|
|
_err_line = "output_schema not satisfied — raw text returned (schema_valid=false)"
|
2026-09-02 18:52:58 -07:00
|
|
|
if _err_line:
|
|
|
|
|
completion_line += f" — {_err_line}"
|
2026-09-02 16:54:15 -07:00
|
|
|
_print_completion_line(parent_agent, spinner_ref, completion_line)
|
|
|
|
|
if spinner_ref and remaining > 0:
|
2026-09-02 17:50:16 -07:00
|
|
|
with _quiet("Spinner update_text failed: %s"):
|
|
|
|
|
spinner_ref.update_text(f"🔀 {'[' + tag + '] ' if tag else ''}{remaining} task{'s' if remaining != 1 else ''} remaining")
|
|
|
|
|
|
2026-09-19 19:21:49 +08:00
|
|
|
def _record_finished_child(batch: _Batch, entry: Any, honor_parent_interrupt: bool) -> None:
|
|
|
|
|
"""Detached (background) unit: durably record a child on the unit's own row the moment it finishes, so an owner
|
|
|
|
|
death before the unit's join — or anywhere before its durable completion write, the whole remaining window for a
|
|
|
|
|
one-child unit — loses only children still running, never finished work (#116000). Best-effort by construction:
|
|
|
|
|
``record_unit_child`` never raises into the join."""
|
|
|
|
|
if not honor_parent_interrupt and batch.unit_id and isinstance(entry, dict):
|
|
|
|
|
record_unit_child(batch.unit_id, entry)
|
|
|
|
|
|
2026-11-04 03:20:23 -08:00
|
|
|
def _release_unstarted_child(batch: _Batch, child: Any) -> None:
|
|
|
|
|
"""Teardown for a child whose run never started (``_run_single_child``'s finally never runs for it)."""
|
|
|
|
|
_detach_child(batch.parent_agent, child)
|
|
|
|
|
_close_child(child, "Failed to close a subagent that never started")
|
|
|
|
|
|
|
|
|
|
def _run_gated(batch: _Batch, gate: Any, honor_parent_interrupt: bool, i: int, task: dict[str, Any],
|
|
|
|
|
child: Any) -> dict[str, Any]:
|
|
|
|
|
"""``batch.run_child`` behind the prompt-cache warm-up gate; a child stopped while it waited never starts.
|
|
|
|
|
A detached (background) unit ignores the parent's turn interrupt, so only the child's own stop skips it."""
|
|
|
|
|
parent = batch.parent_agent if honor_parent_interrupt else None
|
|
|
|
|
entry = gate.run(child, lambda: batch.run_child(i, task, child), parent=parent)
|
|
|
|
|
if entry is not None:
|
|
|
|
|
return entry
|
|
|
|
|
_release_unstarted_child(batch, child)
|
|
|
|
|
return _fabricated_entry(i, "interrupted", "Stopped while waiting for the batch's shared prompt cache", child)
|
2026-11-04 01:55:20 -08:00
|
|
|
|
2026-09-06 12:09:49 -07:00
|
|
|
def _run_children_parallel(batch: _Batch, results: list, *, honor_parent_interrupt: bool) -> None:
|
2026-09-02 19:25:04 -07:00
|
|
|
"""Run the batch's children in parallel, appending entries to ``results`` (sorted by task_index on return, one
|
|
|
|
|
completion line printed per child). Polls futures with a short ``wait()`` timeout instead of ``as_completed()``
|
|
|
|
|
so a wedged child cannot block the parent forever after an interrupt; on parent interrupt the still-pending
|
|
|
|
|
children are reported ``interrupted`` and abandoned (they already got the interrupt signal)."""
|
|
|
|
|
# Daemon workers (tools.daemon_pool): the `with` block still joins normally, but if the parent is interrupted
|
|
|
|
|
# while a child is wedged, the abandoned worker must not block interpreter exit.
|
2026-09-02 13:55:32 -07:00
|
|
|
from tools.daemon_pool import DaemonThreadPoolExecutor
|
2026-09-02 17:50:16 -07:00
|
|
|
parent_agent, n_tasks = batch.parent_agent, len(batch.task_list)
|
|
|
|
|
task_labels = [t["goal"][:40] for t in batch.task_list]
|
|
|
|
|
spinner_ref = getattr(parent_agent, "_delegate_spinner", None)
|
2026-09-06 02:39:31 -07:00
|
|
|
_tag = format_batch_tag(batch.live_deleg_id, parent_agent)
|
2026-09-02 18:52:58 -07:00
|
|
|
# Fabricated entries for still-pending / raised futures carry the correct _delegate_role.
|
2026-09-02 17:50:16 -07:00
|
|
|
_child_by_index = {i: child for (i, _, child) in batch.children}
|
2026-09-06 06:19:11 -07:00
|
|
|
n_here = len(batch.children) # a per-group unit runs a subset; ``n_tasks`` keeps the call-wide ``i/N`` slot
|
2026-09-02 17:50:16 -07:00
|
|
|
|
2026-09-02 18:52:58 -07:00
|
|
|
def _entry_of(future, idx):
|
|
|
|
|
if not future.done():
|
|
|
|
|
return _fabricated_entry(
|
|
|
|
|
idx, "interrupted", "Parent agent interrupted — child did not finish in time", _child_by_index.get(idx),
|
|
|
|
|
)
|
|
|
|
|
try:
|
|
|
|
|
return future.result()
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
return _fabricated_entry(idx, "error", str(exc), _child_by_index.get(idx))
|
|
|
|
|
|
2026-09-19 16:53:44 -05:00
|
|
|
executor = DaemonThreadPoolExecutor(max_workers=batch.max_children)
|
|
|
|
|
# ``with`` would join every worker on exit, so a child wedged in an
|
|
|
|
|
# uninterruptible call defeats the interrupt fast-path: the poll loop marks
|
|
|
|
|
# it interrupted and returns, then the join hangs forever. Shutdown without
|
|
|
|
|
# waiting on the interrupt path instead (same shape as moa_loop).
|
2026-11-04 03:20:23 -08:00
|
|
|
interrupted, futures = False, {}
|
2026-09-19 16:53:44 -05:00
|
|
|
try:
|
2026-11-04 01:55:20 -08:00
|
|
|
from tools.delegate_tool_config import _get_prefix_stagger_seconds
|
|
|
|
|
from tools.delegate_tool_prefix_gate import PrefixCacheGate
|
|
|
|
|
gate = PrefixCacheGate.for_children(batch.children, _get_prefix_stagger_seconds())
|
2026-11-04 03:20:23 -08:00
|
|
|
run = batch.run_child if gate is None else partial(_run_gated, batch, gate, honor_parent_interrupt)
|
2026-11-04 01:55:20 -08:00
|
|
|
futures = {executor.submit(contextvars.copy_context().run, run, i, t, child): i for i, t, child in batch.children}
|
2026-09-02 17:50:16 -07:00
|
|
|
pending = set(futures)
|
2026-09-02 13:55:32 -07:00
|
|
|
while pending:
|
2026-09-02 17:50:16 -07:00
|
|
|
if honor_parent_interrupt and getattr(parent_agent, "_interrupt_requested", False) is True:
|
2026-09-02 18:52:58 -07:00
|
|
|
results.extend(_entry_of(f, futures[f]) for f in pending)
|
2026-09-19 16:53:44 -05:00
|
|
|
interrupted = True
|
2026-09-02 13:55:32 -07:00
|
|
|
break
|
2026-09-02 15:40:23 -07:00
|
|
|
done, pending = _cf_wait(pending, timeout=0.5, return_when=FIRST_COMPLETED)
|
2026-09-02 13:55:32 -07:00
|
|
|
for future in done:
|
2026-09-02 18:52:58 -07:00
|
|
|
entry = _entry_of(future, futures[future])
|
2026-09-02 13:55:32 -07:00
|
|
|
results.append(entry)
|
2026-09-19 19:21:49 +08:00
|
|
|
# Detached unit: a crash before the join must not lose children that already finished.
|
|
|
|
|
_record_finished_child(batch, entry, honor_parent_interrupt)
|
2026-09-06 06:19:11 -07:00
|
|
|
_report_child_done(parent_agent, spinner_ref, entry, _tag, task_labels, n_tasks, n_here - len(results))
|
2026-09-06 12:07:50 -07:00
|
|
|
if (not honor_parent_interrupt and batch.unit_id and entry.get("status") in SUBAGENT_FAILURE_STATUSES
|
|
|
|
|
and len(results) < n_here):
|
|
|
|
|
# Detached unit, a sibling is still running: tell the parent NOW, not when the last one finishes.
|
|
|
|
|
# Non-durable and separate from the unit's final result (which is still delivered once).
|
feat(delegation): a failed child of a still-running detached fan-out is surfaced to the parent immediately
Batches join on the slowest sibling before ONE consolidated block re-enters
(the design: one results block per fan-out). Failure is the case that
should not wait. In the 1,393-agent refactor run every wave-1 child died in
the 08:29 401 storm; the parent learned of it at 09:36, when the batch's
"unknown outcome" block finally arrived: 66 minutes of a dead wave with
nothing running, the single largest idle gap of the run.
_run_children_parallel, for DETACHED batches only (the sync path prints a
completion line the parent is already watching), pushes ONE
type="async_delegation" event with task_failure_notice=True and a
single-entry results list when a child ends in a failure status while
siblings are still pending. Same event shape and routing fields as the
batch result, so every drain/ownership/format path treats it identically;
the batch record is not finalized and its consolidated result still
arrives unchanged. The formatter renders
"[ASYNC DELEGATION TASK FAILED — <id>, task i/n]" with the task, status,
error and live transcript path, and says the batch result is still coming.
The TUI dedup key distinguishes a notice from the final result and from a
sibling's notice.
Live through the real detached dispatch (3 children, one fails at 0.1 s,
two succeed at 8 s): notice drained at t+0.3 s, batch final at t+8.4 s. On
main the parent hears nothing until t+8.4 s.
Tests (2): the notice reaches the queue with the record's routing fields
while the record stays running, and formats as an early warning; no notice
for a finished batch; dedup key differs from the final result.
Delegation/registry/notification suites (129 files) 1,344 passed.
2026-09-05 01:55:22 -07:00
|
|
|
with _quiet("task failure notice failed", exc_info=True):
|
|
|
|
|
from tools.async_delegation import push_task_failure_notice
|
|
|
|
|
_i = entry.get("task_index", -1)
|
|
|
|
|
_live = batch.live_paths[_i] if isinstance(_i, int) and 0 <= _i < len(batch.live_paths) else None
|
|
|
|
|
push_task_failure_notice(
|
2026-09-06 12:07:50 -07:00
|
|
|
batch.unit_id, {**entry, **({"live_transcript": _live} if _live else {})}, n_tasks=n_tasks)
|
2026-09-19 16:53:44 -05:00
|
|
|
finally:
|
|
|
|
|
# Abandoned workers unwind on their own (daemon threads, and the
|
|
|
|
|
# child-run layer already applies the deferred-close transport drain).
|
|
|
|
|
executor.shutdown(wait=not interrupted, cancel_futures=interrupted)
|
2026-11-04 03:20:23 -08:00
|
|
|
for future, idx in futures.items() if interrupted else ():
|
|
|
|
|
if future.cancelled(): # queued behind max_concurrent_children: never started, so never cleaned up
|
|
|
|
|
_release_unstarted_child(batch, _child_by_index.get(idx))
|
2026-09-02 18:52:58 -07:00
|
|
|
results.sort(key=lambda r: r["task_index"]) # match input order
|
2026-09-02 17:50:16 -07:00
|
|
|
|
|
|
|
|
def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = True) -> dict:
|
2026-09-06 06:19:11 -07:00
|
|
|
"""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)."""
|
2026-09-02 17:50:16 -07:00
|
|
|
from tools.delegation_live_log import update_manifest_statuses
|
|
|
|
|
results: list = []
|
2026-09-06 06:19:11 -07:00
|
|
|
if len(batch.children) == 1:
|
2026-09-02 18:52:58 -07:00
|
|
|
results.append(batch.run_child(*batch.children[0]))
|
2026-09-19 19:21:49 +08:00
|
|
|
# A one-child unit has no join to wait on, but everything after the child returns — host-owned finalize,
|
|
|
|
|
# transcript, manifest, then the durable write — is still owner-lifetime: record before any of it (#116000).
|
|
|
|
|
_record_finished_child(batch, results[-1], honor_parent_interrupt)
|
2026-09-02 17:50:16 -07:00
|
|
|
else:
|
2026-09-06 12:09:49 -07:00
|
|
|
_run_children_parallel(batch, results, honor_parent_interrupt=honor_parent_interrupt)
|
2026-09-02 17:50:16 -07:00
|
|
|
|
|
|
|
|
_finalize_child_results(results, batch.task_list, batch.children, batch.parent_agent)
|
|
|
|
|
total_duration = round(time.monotonic() - batch.overall_start, 2)
|
2026-09-02 18:52:58 -07:00
|
|
|
for entry in results:
|
|
|
|
|
_idx = entry.get("task_index", -1)
|
|
|
|
|
if isinstance(_idx, int) and 0 <= _idx < len(batch.live_writers) and batch.live_writers[_idx] is not None:
|
|
|
|
|
with _quiet("Live transcript finalize failed", exc_info=True):
|
|
|
|
|
batch.live_writers[_idx].finalize(entry)
|
|
|
|
|
if _idx < len(batch.live_paths):
|
|
|
|
|
entry["live_transcript"] = batch.live_paths[_idx]
|
2026-10-22 08:08:22 -07:00
|
|
|
if batch.refused:
|
|
|
|
|
results.extend(batch.refused)
|
|
|
|
|
results.sort(key=lambda r: r["task_index"])
|
2026-08-29 08:22:21 +08:00
|
|
|
update_manifest_statuses(batch.live_deleg_id, results, home=batch.live_home)
|
2026-09-27 17:33:28 -07:00
|
|
|
finish_delegation_unit(batch.task_list, results, background=not honor_parent_interrupt)
|
2026-09-02 17:50:16 -07:00
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
combined: dict[str, Any] = {"results": results, "total_duration_seconds": total_duration}
|
feat(delegation): surface process accounting as top-level process_notes in the sync result; add live stress harness
Stress run with a real orchestrator subagent showed the per-task keys buried in results[] were not relayed
upward; the same prose lines now sit at the top of the sync delegate_task result. evals/subagent_process_handoff/
stress_handoff_live.py runs 12 real parent+child scenarios (handoff, orphan, unread, clean read, cap, exited refusal,
mixed fan-out, parent controlling the inherited process, sibling theft incl. adversarial, nested orchestrator,
5-way burst) and scores them against runtime accounting, never model prose.
2026-09-07 12:44:33 -07:00
|
|
|
# Runtime truth about children's background processes, as prose the parent can't miss inside the JSON.
|
|
|
|
|
from tools.process_registry_notifications import _process_accounting_lines
|
|
|
|
|
process_notes = [line for entry in results for line in _process_accounting_lines(entry)]
|
|
|
|
|
if process_notes:
|
|
|
|
|
combined["process_notes"] = process_notes
|
2026-09-06 06:19:11 -07:00
|
|
|
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
|
2026-09-02 17:50:16 -07:00
|
|
|
return combined
|
|
|
|
|
|
2026-09-02 15:40:23 -07:00
|
|
|
_SYNC_FALLBACK_NOTES = {
|
|
|
|
|
"no_async": (
|
|
|
|
|
"background=true is not available in this session — it cannot "
|
|
|
|
|
"receive a detached subagent result after the turn ends (a "
|
2026-11-01 16:57:21 -08:00
|
|
|
"finite chat using -Q, --oneshot, or non-TTY stdio, `hermes -z`, a /bg background task, a cron "
|
|
|
|
|
"job, a Kanban worker, or a stateless HTTP endpoint). The subagent(s) ran SYNCHRONOUSLY and the result is included above."
|
2026-09-02 15:40:23 -07:00
|
|
|
),
|
|
|
|
|
"at_capacity": (
|
2026-09-02 19:04:50 -07:00
|
|
|
"The background delegation pool was at capacity (delegation.max_concurrent_children), so the subagent(s) ran "
|
2026-09-02 15:40:23 -07:00
|
|
|
"SYNCHRONOUSLY and the result is included above. Raise "
|
2026-09-02 19:04:50 -07:00
|
|
|
"delegation.max_concurrent_children in config.yaml to allow more concurrent background delegations."
|
2026-09-02 15:40:23 -07:00
|
|
|
),
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-02 17:50:16 -07:00
|
|
|
def _run_sync_with_note(batch: _Batch, reason: str) -> str:
|
2026-09-02 15:40:23 -07:00
|
|
|
"""Inline fallback: run the batch now and explain why it was not detached."""
|
2026-09-02 17:50:16 -07:00
|
|
|
result = _execute_and_aggregate(batch)
|
2026-09-02 15:40:23 -07:00
|
|
|
if isinstance(result, dict):
|
|
|
|
|
result["note"] = _SYNC_FALLBACK_NOTES[reason]
|
|
|
|
|
return json.dumps(result, ensure_ascii=False)
|
|
|
|
|
|
2026-10-24 17:42:52 -07:00
|
|
|
def _resolve_async_wake_sid(
|
|
|
|
|
origin_wake_sid: str, origin_session_history_delivery: bool = False, oneshot_session: bool = False,
|
|
|
|
|
) -> Optional[str]:
|
2026-09-07 02:35:42 -07:00
|
|
|
"""Detached result target: empty for push, a resumable API id, or None for inline.
|
2026-09-02 15:40:23 -07:00
|
|
|
|
2026-09-07 02:35:42 -07:00
|
|
|
API completion only persists a row; this does not authorize a model wake. The
|
2026-10-24 17:42:52 -07:00
|
|
|
continuation must read that row, not an authoritative caller-owned snapshot.
|
|
|
|
|
*oneshot_session*: the parent's tools[] froze the one-shot ``delegate_task`` ("joined in this call", no
|
|
|
|
|
list/steer/stop) for the whole session, so a later interactive turn (``chat -q`` then ``--resume``) joins too."""
|
2026-09-10 10:33:47 +00:00
|
|
|
from gateway.session_context import get_session_env
|
|
|
|
|
|
2026-09-10 09:16:59 -07:00
|
|
|
# Finite consumers need the result in this tool round. Owner admission scope
|
|
|
|
|
# wins over legacy standalone launch markers, without changing terminal delivery.
|
|
|
|
|
from gateway.session_finite import finite_turn_required
|
|
|
|
|
finite = finite_turn_required()
|
2026-10-24 17:42:52 -07:00
|
|
|
if oneshot_session or finite is True or (finite is None and get_session_env("HERMES_SINGLE_QUERY_SESSION") == "1"):
|
2026-09-10 10:33:47 +00:00
|
|
|
return None
|
|
|
|
|
|
2026-09-02 15:40:23 -07:00
|
|
|
try:
|
2026-09-03 09:44:26 -07:00
|
|
|
# Finite sessions cannot route a detached subagent result back to the agent after their turn/process
|
|
|
|
|
# ends. This includes stateless HTTP requests (#10760) and one-shot Kanban workers (#63169). Fall
|
|
|
|
|
# back to SYNCHRONOUS execution so the result returns in this same turn instead of handing out a
|
|
|
|
|
# handle with no durable consumer. Mirrors the pool-at-capacity inline fallback below.
|
2026-09-02 15:40:23 -07:00
|
|
|
from gateway.session_context import async_delivery_supported
|
|
|
|
|
if async_delivery_supported():
|
|
|
|
|
return ""
|
|
|
|
|
except Exception:
|
|
|
|
|
return ""
|
2026-09-07 02:35:42 -07:00
|
|
|
if origin_wake_sid and origin_session_history_delivery:
|
2026-09-02 15:40:23 -07:00
|
|
|
logger.info(
|
2026-09-07 02:35:42 -07:00
|
|
|
"delegate_task: session %s resumes server history — detached result will be persisted "
|
|
|
|
|
"for the next client turn (no model wake).", origin_wake_sid,
|
2026-09-02 15:40:23 -07:00
|
|
|
)
|
|
|
|
|
return origin_wake_sid
|
2026-09-07 09:57:02 +08:00
|
|
|
if origin_wake_sid:
|
|
|
|
|
logger.info(
|
2026-09-07 02:35:42 -07:00
|
|
|
"delegate_task: session %s has no declared server-history consumer — running the batch "
|
|
|
|
|
"synchronously so the result returns in this turn.", origin_wake_sid,
|
2026-09-07 09:57:02 +08:00
|
|
|
)
|
2026-09-02 15:40:23 -07:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def _resolve_async_session_key(parent_agent: Any, origin_ui_session_id: str) -> tuple[str, str]:
|
|
|
|
|
"""``(session_key, origin_ui_session_id)`` the async registry routes completions by.
|
|
|
|
|
|
2026-09-02 19:25:04 -07:00
|
|
|
Desktop/TUI: the routable key is the durable AIAgent.session_id — compression can rotate it mid-turn before the
|
|
|
|
|
TUI-side dict is re-anchored, and a stale approval-context key would orphan the completion. Gateway chats keep the
|
|
|
|
|
platform conversation key (agent:main:...). The CLI has no bound approval contextvar and no HERMES_SESSION_KEY, so
|
|
|
|
|
the key resolves empty; its drain is a positive-ownership filter on the durable session_id (empty would fail
|
|
|
|
|
closed), so stamp the parent's durable id.
|
2026-09-02 15:40:23 -07:00
|
|
|
"""
|
2026-09-03 13:49:57 -07:00
|
|
|
from tools.approval_context import get_current_session_key
|
2026-09-02 15:40:23 -07:00
|
|
|
session_key = get_current_session_key(default="")
|
|
|
|
|
agent_session_id = str(getattr(parent_agent, "session_id", "") or "")
|
2026-09-02 17:50:16 -07:00
|
|
|
with _quiet(None):
|
2026-09-02 15:40:23 -07:00
|
|
|
from gateway.session_context import get_session_env
|
|
|
|
|
source = get_session_env("HERMES_SESSION_SOURCE", "")
|
|
|
|
|
# Refresh from the task-local source when available, else retain the
|
|
|
|
|
# immutable value captured before child construction.
|
|
|
|
|
origin_ui_session_id = get_session_env("HERMES_UI_SESSION_ID", "") or origin_ui_session_id
|
|
|
|
|
if source == "tui" and agent_session_id:
|
|
|
|
|
session_key = agent_session_id
|
2026-09-02 18:52:58 -07:00
|
|
|
return session_key or agent_session_id, origin_ui_session_id
|
2026-09-02 17:50:16 -07:00
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _batch_progress_token(child_agents: list[Any]) -> tuple:
|
2026-09-02 19:25:04 -07:00
|
|
|
"""Progress token for the async registry's stale monitor: every child's (api_call_count, current_tool,
|
|
|
|
|
last_activity_ts). last_activity_ts ticks on streamed chunks, tool transitions and API-call start/completion,
|
|
|
|
|
so a child streaming a long response counts as alive; a fully frozen token past the threshold means the batch
|
|
|
|
|
is wedged. ``in_tool`` is True while ANY child is inside a tool so slow tools get the higher ceiling (mirrors
|
|
|
|
|
the sync heartbeat)."""
|
2026-09-03 09:44:26 -07:00
|
|
|
# Progress token for the async registry's stale monitor: the combined (api_call_count, current_tool,
|
|
|
|
|
# last_activity_ts) of every child. last_activity_ts is ticked by _touch_activity on every streamed
|
|
|
|
|
# chunk ("receiving stream response"), every tool transition, and every API-call start/completion — so a
|
|
|
|
|
# child streaming a long response is alive even though api_call_count only advances when the call
|
|
|
|
|
# completes (same liveness signal as the compaction inactivity budget, PR #71508).
|
2026-09-02 15:40:23 -07:00
|
|
|
parts = []
|
|
|
|
|
in_tool = False
|
|
|
|
|
for c in child_agents:
|
|
|
|
|
try:
|
|
|
|
|
summary = c.get_activity_summary()
|
|
|
|
|
tool = summary.get("current_tool")
|
|
|
|
|
parts.append((summary.get("api_call_count", 0), tool, summary.get("last_activity_ts")))
|
|
|
|
|
in_tool = in_tool or bool(tool)
|
|
|
|
|
except Exception:
|
|
|
|
|
parts.append(None)
|
|
|
|
|
return tuple(parts), in_tool
|
|
|
|
|
|
2026-09-02 19:56:03 -07:00
|
|
|
_BACKGROUND_NOTES = {
|
|
|
|
|
"one": (
|
2026-09-07 06:06:24 -07:00
|
|
|
"Subagent is running in the background; its full result re-enters the conversation as a new message when it "
|
|
|
|
|
"finishes. Results are delivered only after you END YOUR TURN: do anything that does not depend on it, then "
|
|
|
|
|
"stop with a one-line status. Do not poll its transcript or artifacts to wait for it."
|
2026-09-02 19:56:03 -07:00
|
|
|
),
|
|
|
|
|
"many": (
|
2026-09-07 06:06:24 -07:00
|
|
|
"{n} subagents are running in parallel in the background as {k} completion unit(s); each unit's results "
|
|
|
|
|
"re-enter the conversation as their own new message when THAT unit finishes. Results are delivered only "
|
|
|
|
|
"after you END YOUR TURN: do anything that does not depend on them, then stop with a one-line status. Do not "
|
|
|
|
|
"poll transcripts or artifacts to wait for them."
|
2026-09-02 19:56:03 -07:00
|
|
|
),
|
|
|
|
|
"control_hint": (
|
|
|
|
|
"While a child runs you can orchestrate it live with this same tool: delegate_task(action='list') to see live "
|
|
|
|
|
"children, action='steer' with subagent_id + message to redirect one, action='stop' with subagent_id to end "
|
|
|
|
|
"one early."
|
|
|
|
|
),
|
|
|
|
|
"live_transcripts_hint": (
|
|
|
|
|
"Each subagent streams a human-readable transcript of its operations to the file listed above (append-only, "
|
|
|
|
|
"one per task). Read or `tail -f` these paths at any time to watch a child work while it runs."
|
|
|
|
|
),
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _dispatched_payload(batch: _Batch, units: list[tuple[_Batch, str]]) -> dict:
|
2026-09-06 06:19:11 -07:00
|
|
|
"""Model-facing handle for an accepted background call: one entry per async unit."""
|
|
|
|
|
goals = [t["goal"] for t in batch.task_list]
|
2026-10-22 08:08:22 -07:00
|
|
|
n = len(batch.children) # running children; refused tasks are listed under "refused"
|
2026-09-02 15:40:23 -07:00
|
|
|
payload = {
|
2026-09-06 06:19:11 -07:00
|
|
|
"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)),
|
2026-09-02 15:40:23 -07:00
|
|
|
}
|
2026-09-06 06:19:11 -07:00
|
|
|
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]
|
2026-09-02 15:40:23 -07:00
|
|
|
if any(isinstance(s, str) and s for s in sids):
|
|
|
|
|
payload["subagent_ids"] = sids
|
2026-09-02 19:56:03 -07:00
|
|
|
payload["control_hint"] = _BACKGROUND_NOTES["control_hint"]
|
2026-10-22 08:08:22 -07:00
|
|
|
if batch.refused:
|
|
|
|
|
payload["refused"] = batch.refused
|
2026-09-06 06:19:11 -07:00
|
|
|
if batch.live_paths:
|
|
|
|
|
payload["live_transcripts"] = list(batch.live_paths)
|
2026-09-02 19:56:03 -07:00
|
|
|
payload["live_transcripts_hint"] = _BACKGROUND_NOTES["live_transcripts_hint"]
|
2026-09-02 15:40:23 -07:00
|
|
|
return payload
|
|
|
|
|
|
2026-10-08 17:22:54 +02:00
|
|
|
def _units_of(batch: _Batch) -> list[_Batch]:
|
2026-09-06 06:19:11 -07:00
|
|
|
"""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
|
2026-09-07 06:06:24 -07:00
|
|
|
``children``, so a unit joins only on itself and its completion re-enters the conversation on its own.
|
|
|
|
|
|
|
|
|
|
Off by default (``delegation.independent_completions``): the whole call is ONE unit and returns as one message.
|
|
|
|
|
A per-task flurry of completions (one new turn each) fragmented orchestrators that had no plan for it."""
|
|
|
|
|
from tools.delegate_tool_config import _get_independent_completions
|
|
|
|
|
if not _get_independent_completions():
|
|
|
|
|
return [batch]
|
2026-10-08 17:22:54 +02:00
|
|
|
members: dict[Any, list[tuple]] = {}
|
2026-09-06 06:19:11 -07:00
|
|
|
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
|
2026-10-18 19:57:04 -07:00
|
|
|
# creds["model"] is None when delegation.model is blank (children inherit): report what the child runs on.
|
|
|
|
|
role=unit.top_role, model=unit.creds["model"] or next(
|
|
|
|
|
(getattr(c, "model", None) for c in child_agents if getattr(c, "model", None)), None),
|
2026-09-06 06:19:11 -07:00
|
|
|
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,
|
2026-09-19 19:54:22 +08:00
|
|
|
# Persist locators before starting workers; live_paths omits failed writers and can be compressed.
|
|
|
|
|
task_transcripts={str(i): str(unit.live_writers[i].path) for i, _, _ in unit.children
|
|
|
|
|
if i < len(unit.live_writers) and unit.live_writers[i] is not None
|
|
|
|
|
and unit.live_writers[i].path is not None},
|
2026-09-06 06:19:11 -07:00
|
|
|
progress_fn=lambda: _batch_progress_token(child_agents), **routing,
|
|
|
|
|
)
|
|
|
|
|
|
2026-09-07 12:51:13 +08:00
|
|
|
def _restore_parent_cancellation(unit: _Batch) -> None:
|
2026-09-13 20:19:50 -07:00
|
|
|
"""Rejected children stay owned by the parent: re-attach them (``_attach_child`` replays a stop that
|
|
|
|
|
arrived while async admission had them detached)."""
|
2026-09-07 12:51:13 +08:00
|
|
|
for _, _, child in unit.children:
|
2026-09-13 20:19:50 -07:00
|
|
|
_attach_child(unit.parent_agent, child)
|
2026-09-07 12:51:13 +08:00
|
|
|
|
2026-09-02 17:50:16 -07:00
|
|
|
def _dispatch_background(batch: _Batch) -> str:
|
2026-09-06 06:19:11 -07:00
|
|
|
"""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."""
|
2026-09-02 13:55:32 -07:00
|
|
|
from tools.delegate_tool import _get_max_async_children
|
2026-10-24 17:42:52 -07:00
|
|
|
wake_sid = _resolve_async_wake_sid(
|
|
|
|
|
batch.origin_wake_sid, batch.origin_session_history_delivery,
|
|
|
|
|
oneshot_session=getattr(batch.parent_agent, "_oneshot_session", None) is True, # agent_is_oneshot's pin
|
|
|
|
|
)
|
2026-09-02 15:40:23 -07:00
|
|
|
if wake_sid is None:
|
2026-09-02 17:50:16 -07:00
|
|
|
logger.info("delegate_task: async delivery unsupported on this session runtime; running the batch synchronously instead.")
|
|
|
|
|
return _run_sync_with_note(batch, "no_async")
|
2026-09-02 13:55:32 -07:00
|
|
|
|
2026-09-02 17:50:16 -07:00
|
|
|
parent_agent = batch.parent_agent
|
|
|
|
|
session_key, origin_ui_session_id = _resolve_async_session_key(parent_agent, batch.origin_ui_session_id)
|
2026-09-06 06:19:11 -07:00
|
|
|
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(),
|
2026-09-02 13:55:32 -07:00
|
|
|
)
|
2026-09-06 06:19:11 -07:00
|
|
|
|
2026-10-22 08:08:22 -07:00
|
|
|
units = [replace(unit, refused=[]) for unit in _units_of(batch)]
|
2026-10-08 17:22:54 +02:00
|
|
|
dispatched: list[tuple[_Batch, str]] = []
|
|
|
|
|
inline_results: list[dict] = []
|
2026-09-06 06:19:11 -07:00
|
|
|
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)
|
2026-09-06 08:10:00 -07:00
|
|
|
unit.unit_id = unit_id = unit_id or _new_delegation_id() # fixed before the runner can start
|
2026-09-07 12:51:13 +08:00
|
|
|
# The worker can start before admission returns. Detach only this unit:
|
|
|
|
|
# unsubmitted units must still receive parent stops while a fallback runs.
|
|
|
|
|
for _, _, child in unit.children:
|
|
|
|
|
_detach_child(parent_agent, child)
|
2026-09-06 06:19:11 -07:00
|
|
|
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
|
2026-09-07 12:51:13 +08:00
|
|
|
_restore_parent_cancellation(unit)
|
2026-09-06 06:19:11 -07:00
|
|
|
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"))
|
2026-09-07 12:51:13 +08:00
|
|
|
inline_results.extend(_execute_and_aggregate(unit)["results"])
|
2026-09-06 06:19:11 -07:00
|
|
|
payload = _dispatched_payload(batch, dispatched)
|
|
|
|
|
if inline_results:
|
|
|
|
|
payload["inline_results"] = inline_results
|
|
|
|
|
return json.dumps(payload, ensure_ascii=False)
|
2026-09-02 17:50:16 -07:00
|
|
|
|
|
|
|
|
def _run_batch(batch: _Batch, background: bool) -> str:
|
|
|
|
|
"""Tool result JSON: a dispatch handle (background) or the joined combined results."""
|
fix(gateway): join delegations in the turn when interim messages are off
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.
New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.
How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
when it builds a session's agent (gateway/session_execution.py), and the
agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
path already uses: "results return in this tool call", no live-control
parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
(session_joins_delegation), so schema and behaviour cannot disagree. The
schema rides the session's tools[] pin: a config change applies from the
next session (/new), as delegation.backend does, and a cache eviction or
restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
parent, so /stop and an interrupting follow-up stop them; the per-child
heartbeat keeps the parent's activity fresh for the inactivity watchdog;
the async completion registry is not used. Nested and one-shot delegation
are unchanged.
Refs #95522.
2026-10-28 14:33:54 +00:00
|
|
|
from tools.delegate_tool import session_joins_delegation
|
2026-09-27 17:33:28 -07:00
|
|
|
# Every unit of this call shares task_list, so its last joined unit emits the call's one row.
|
|
|
|
|
begin_delegation_run(
|
|
|
|
|
batch.task_list, subagents=len(batch.children), depth=getattr(batch.parent_agent, "_delegate_depth", 0) + 1,
|
|
|
|
|
)
|
fix(gateway): join delegations in the turn when interim messages are off
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.
New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.
How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
when it builds a session's agent (gateway/session_execution.py), and the
agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
path already uses: "results return in this tool call", no live-control
parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
(session_joins_delegation), so schema and behaviour cannot disagree. The
schema rides the session's tools[] pin: a config change applies from the
next session (/new), as delegation.backend does, and a cache eviction or
restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
parent, so /stop and an interrupting follow-up stop them; the per-child
heartbeat keeps the parent's activity fresh for the inactivity watchdog;
the async completion registry is not used. Nested and one-shot delegation
are unchanged.
Refs #95522.
2026-10-28 14:33:54 +00:00
|
|
|
if background and not session_joins_delegation(batch.parent_agent):
|
2026-09-02 17:50:16 -07:00
|
|
|
return _dispatch_background(batch)
|
|
|
|
|
return json.dumps(_execute_and_aggregate(batch), ensure_ascii=False)
|