Skip to content

The agent that grows with you

refactor(delegate): _Batch dataclass owns batch execution/dispatch; _quiet best-effort contextmanager

Teknium64957b7e02a7
diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py
index dff4c9d7c1e..fd81c43d530 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -11,11 +11,9 @@ the delegation call and the summary result, never the child's intermediate
tool calls or reasoning.
"""
-import json
import logging
import time
import weakref
-from dataclasses import dataclass
from typing import Any, Dict, List, Optional
@@ -43,7 +41,8 @@ from tools.delegate_tool_config import ( # noqa: F401
_subagent_auto_approve, _subagent_auto_deny,
)
from tools.delegate_tool_dispatch import ( # noqa: F401
- _dispatch_background, _run_children_parallel,
+ _Batch, _announce_batch, _capture_origin, _dispatch_background, _execute_and_aggregate, _run_batch,
+ _run_children_parallel,
)
from tools.delegate_tool_progress import ( # noqa: F401
DelegateEvent, SUBAGENT_FAILURE_STATUSES, _batch_prefix, _build_child_progress_callback,
@@ -441,55 +440,6 @@ def _run_single_child(
)
-@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)."""
-
- task_list: List[Dict[str, Any]]
- children: List[tuple]
- parent_agent: Any
- max_children: int
- live_deleg_id: Optional[str]
- live_writers: list
- live_paths: list
- origin_ui_session_id: str
- origin_owner_transport: Any
- origin_owner_session_record: Any
- overall_start: float
-
-
-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."""
- if n_tasks <= 1 or not live_deleg_id:
- return
- _hdr = f" πŸ”€ [{format_batch_tag(live_deleg_id)}] delegating {n_tasks} tasks"
- _hdr_spinner = getattr(parent_agent, "_delegate_spinner", None)
- if _hdr_spinner:
- try:
- _hdr_spinner.print_above(_hdr)
- return
- except Exception:
- pass
- _emit_parent_console(parent_agent, _hdr)
-
-def _capture_origin() -> tuple[str, str, Any, Any]:
- """``(wake_sid, ui_session_id, owner_transport, owner_session_record)`` of the
- ORIGINATING session, captured BEFORE building any child: AIAgent construction
- clobbers the HERMES_SESSION_ID ContextVar/os.environ with the subagent's id."""
- from tools.async_delegation import _current_origin_session_id
-
- _origin_wake_sid = _current_origin_session_id()
- try:
- from gateway.session_context import get_session_env
-
- _origin_ui_session_id = get_session_env("HERMES_UI_SESSION_ID", "")
- except Exception:
- _origin_ui_session_id = ""
- transport, record = _capture_gateway_steer_authority(_origin_ui_session_id)
- return _origin_wake_sid, _origin_ui_session_id, transport, record
-
def _build_children(
task_list: List[Dict[str, Any]],
task_schemas: List[Optional[Dict[str, Any]]],
@@ -557,66 +507,6 @@ def _build_children(
children.append((i, t, child))
return children, None
-def _finalize_live_transcripts(results: list, live_writers: list, live_paths: list) -> None:
- """Close out live transcripts (files are retained as the full-fidelity
- record; retention pruning happens on future dispatches)."""
- for entry in results:
- _idx = entry.get("task_index", -1)
- _w = live_writers[_idx] if isinstance(_idx, int) and 0 <= _idx < len(live_writers) else None
- if _w is not None:
- try:
- _w.finalize(entry)
- except Exception:
- logger.debug("Live transcript finalize failed", exc_info=True)
- if _idx < len(live_paths):
- entry["live_transcript"] = live_paths[_idx]
-
-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.
- """
- from tools.delegation_live_log import update_manifest_statuses
-
- results: list = []
- n_tasks = len(batch.task_list)
- if n_tasks == 1:
- _i, _t, child = batch.children[0]
- results.append(_run_single_child(
- _i,
- _t["goal"],
- child,
- batch.parent_agent,
- owner_session_id=batch.origin_ui_session_id or None,
- owner_transport=batch.origin_owner_transport,
- owner_session_record=batch.origin_owner_session_record,
- ))
- else:
- _run_children_parallel(
- batch.children,
- results,
- parent_agent=batch.parent_agent,
- n_tasks=n_tasks,
- max_children=batch.max_children,
- task_labels=[t["goal"][:40] for t in batch.task_list],
- live_deleg_id=batch.live_deleg_id,
- honor_parent_interrupt=honor_parent_interrupt,
- origin_ui_session_id=batch.origin_ui_session_id,
- origin_owner_transport=batch.origin_owner_transport,
- origin_owner_session_record=batch.origin_owner_session_record,
- )
-
- _finalize_child_results(results, batch.task_list, batch.children, batch.parent_agent)
- total_duration = round(time.monotonic() - batch.overall_start, 2)
- _finalize_live_transcripts(results, batch.live_writers, batch.live_paths)
- 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)
- return combined
def delegate_task(
goal: Optional[str] = None,
@@ -707,7 +597,7 @@ def delegate_task(
task_list, context, model=creds.get("model"), provider=creds.get("provider")
)
_announce_batch(parent_agent, len(task_list), live_deleg_id)
- _origin_wake_sid, _origin_ui_session_id, _origin_owner_transport, _origin_owner_session_record = _capture_origin()
+ origin = _capture_origin()
children, err = _build_children(
task_list,
@@ -722,28 +612,10 @@ def delegate_task(
if err:
return tool_error(err)
batch = _Batch(
- task_list, children, parent_agent, max_children, live_deleg_id, live_writers, live_paths,
- _origin_ui_session_id, _origin_owner_transport, _origin_owner_session_record, overall_start,
+ task_list, children, parent_agent, creds, context, top_role, max_children,
+ live_deleg_id, live_writers, live_paths, *origin, overall_start,
)
-
- def _run(*, honor_parent_interrupt: bool = True) -> dict:
- return _execute_and_aggregate(batch, honor_parent_interrupt=honor_parent_interrupt)
-
- if background:
- return _dispatch_background(
- parent_agent=parent_agent,
- context=context,
- task_list=task_list,
- children=children,
- creds=creds,
- top_role=top_role,
- live_deleg_id=live_deleg_id,
- live_paths=live_paths,
- origin_wake_sid=_origin_wake_sid,
- origin_ui_session_id=_origin_ui_session_id,
- execute_and_aggregate=_run,
- )
- return json.dumps(_run(), ensure_ascii=False)
+ return _run_batch(batch, background)
# ── OpenAI function-calling schema ──────────────────────────────────────────
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index 2053b66e783..43b07333d88 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -1,7 +1,7 @@
"""Batch execution + background dispatch for delegate_task.
-Split out of ``tools/delegate_tool.py`` (zero-back-ref regions of ``delegate_task``);
-``delegate_task`` stays the orchestrator and calls these with its locals.
+``delegate_task`` builds a ``_Batch`` (children + origin identity) and hands it to
+``_run_batch``; everything here runs it synchronously or as ONE detached async unit.
"""
from __future__ import annotations
@@ -9,20 +9,76 @@ from __future__ import annotations
import contextvars
import json
import logging
+import time
from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait
+from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from tools.delegate_tool_child_run import _detach_child, _fabricated_entry, _signal_child_stop
from tools.delegate_tool_progress import (
- SUBAGENT_FAILURE_STATUSES,
- _clean_error_text,
- _print_completion_line,
- format_batch_tag,
+ SUBAGENT_FAILURE_STATUSES, _clean_error_text, _print_completion_line, _quiet, format_batch_tag,
)
+from tools.delegate_tool_registry import _capture_gateway_steer_authority
+from tools.delegate_tool_results import _finalize_child_results
# Log-record parity with the origin module.
logger = logging.getLogger("tools.delegate_tool")
+
+@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)."""
+
+ task_list: List[Dict[str, Any]]
+ children: List[tuple]
+ parent_agent: Any
+ creds: Dict[str, Any]
+ 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
+ overall_start: float
+
+ def owner_kwargs(self) -> Dict[str, Any]:
+ """Steer/stop authority of the originating session, passed to every child run."""
+ return {
+ "owner_session_id": self.origin_ui_session_id or None,
+ "owner_transport": self.origin_owner_transport,
+ "owner_session_record": self.origin_owner_session_record,
+ }
+
+
+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."""
+ if n_tasks <= 1 or not live_deleg_id:
+ return
+ _hdr = f" πŸ”€ [{format_batch_tag(live_deleg_id)}] delegating {n_tasks} tasks"
+ _print_completion_line(parent_agent, getattr(parent_agent, "_delegate_spinner", None), _hdr, console_line=_hdr)
+
+
+def _capture_origin() -> tuple[str, str, Any, Any]:
+ """``(wake_sid, ui_session_id, owner_transport, owner_session_record)`` of the
+ ORIGINATING session, captured BEFORE building any child: AIAgent construction
+ clobbers the HERMES_SESSION_ID ContextVar/os.environ with the subagent's id."""
+ from tools.async_delegation import _current_origin_session_id
+
+ _origin_wake_sid = _current_origin_session_id()
+ _origin_ui_session_id = ""
+ with _quiet(None):
+ from gateway.session_context import get_session_env
+
+ _origin_ui_session_id = get_session_env("HERMES_UI_SESSION_ID", "")
+ transport, record = _capture_gateway_steer_authority(_origin_ui_session_id)
+ return _origin_wake_sid, _origin_ui_session_id, transport, record
+
+
def _future_entry(future: Any, idx: int, child: Any) -> Dict[str, Any]:
"""The finished Future's entry, or a fabricated error entry if it raised."""
try:
@@ -30,6 +86,7 @@ def _future_entry(future: Any, idx: int, child: Any) -> Dict[str, Any]:
except Exception as exc:
return _fabricated_entry(idx, "error", str(exc), child)
+
def _report_child_done(parent_agent, spinner_ref, entry, tag, task_labels, n_tasks, remaining) -> None:
"""Print one completion line for a finished child and refresh the spinner text."""
idx = entry["task_index"]
@@ -45,28 +102,12 @@ def _report_child_done(parent_agent, spinner_ref, entry, tag, task_labels, n_tas
completion_line += f" β€” {_err_line}"
_print_completion_line(parent_agent, spinner_ref, completion_line)
if spinner_ref and remaining > 0:
- try:
- spinner_ref.update_text(
- f"πŸ”€ {'[' + tag + '] ' if tag else ''}{remaining} task{'s' if remaining != 1 else ''} remaining"
- )
- except Exception as e:
- logger.debug("Spinner update_text failed: %s", e)
-
-def _run_children_parallel(
- children: List[tuple],
- results: list,
- *,
- parent_agent: Any,
- n_tasks: int,
- max_children: int,
- task_labels: List[str],
- live_deleg_id: Optional[str],
- honor_parent_interrupt: bool,
- origin_ui_session_id: str,
- origin_owner_transport: Any,
- origin_owner_session_record: Any,
-) -> None:
- """Run a batch of built children in parallel, appending entries to ``results``.
+ with _quiet("Spinner update_text failed: %s"):
+ spinner_ref.update_text(f"πŸ”€ {'[' + tag + '] ' if tag else ''}{remaining} task{'s' if remaining != 1 else ''} remaining")
+
+
+def _run_children_parallel(batch: _Batch, results: list, *, honor_parent_interrupt: bool) -> None:
+ """Run the batch's children in parallel, appending entries to ``results``.
Polls futures with a short ``wait()`` timeout instead of ``as_completed()``
so a wedged child cannot block the parent forever after an interrupt;
@@ -75,51 +116,40 @@ def _run_children_parallel(
``results`` ends sorted by task_index.
"""
from tools.delegate_tool import _run_single_child
-
- completed_count = 0
- spinner_ref = getattr(parent_agent, "_delegate_spinner", None)
- _tag = format_batch_tag(live_deleg_id)
- # Fabricated entries for still-pending futures carry the correct _delegate_role.
- _child_by_index = {i: child for (i, _, child) in children}
-
# 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.
from tools.daemon_pool import DaemonThreadPoolExecutor
- with DaemonThreadPoolExecutor(max_workers=max_children) as executor:
- futures = {}
- for i, t, child in children:
- future = executor.submit(
- contextvars.copy_context().run,
- _run_single_child,
- task_index=i,
- goal=t["goal"],
- child=child,
- parent_agent=parent_agent,
- owner_session_id=origin_ui_session_id or None,
- owner_transport=origin_owner_transport,
- owner_session_record=origin_owner_session_record,
- )
- futures[future] = i
-
- pending = set(futures.keys())
+
+ parent_agent, n_tasks = batch.parent_agent, len(batch.task_list)
+ task_labels = [t["goal"][:40] for t in batch.task_list]
+ completed_count = 0
+ spinner_ref = getattr(parent_agent, "_delegate_spinner", None)
+ _tag = format_batch_tag(batch.live_deleg_id)
+ # Fabricated entries for still-pending futures carry the correct _delegate_role.
+ _child_by_index = {i: child for (i, _, child) in batch.children}
+
+ with DaemonThreadPoolExecutor(max_workers=batch.max_children) as executor:
+ futures = {
+ executor.submit(
+ contextvars.copy_context().run, _run_single_child,
+ task_index=i, goal=t["goal"], child=child, parent_agent=parent_agent, **batch.owner_kwargs(),
+ ): i
+ for i, t, child in batch.children
+ }
+ pending = set(futures)
while pending:
- if (honor_parent_interrupt and getattr(parent_agent, "_interrupt_requested", False) is True):
+ if honor_parent_interrupt and getattr(parent_agent, "_interrupt_requested", False) is True:
# Parent interrupted β€” collect whatever finished and abandon the
# rest (children already got the interrupt signal).
for f in pending:
idx = futures[f]
- if f.done():
- entry = _future_entry(f, idx, _child_by_index.get(idx))
- else:
- entry = _fabricated_entry(
- idx,
- "interrupted",
- "Parent agent interrupted β€” child did not finish in time",
- _child_by_index.get(idx),
+ results.append(
+ _future_entry(f, idx, _child_by_index.get(idx)) if f.done()
+ else _fabricated_entry(
+ idx, "interrupted", "Parent agent interrupted β€” child did not finish in time", _child_by_index.get(idx),
)
- results.append(entry)
- completed_count += 1
+ )
break
done, pending = _cf_wait(pending, timeout=0.5, return_when=FIRST_COMPLETED)
@@ -127,12 +157,53 @@ def _run_children_parallel(
entry = _future_entry(future, futures[future], _child_by_index.get(futures[future]))
results.append(entry)
completed_count += 1
-
_report_child_done(parent_agent, spinner_ref, entry, _tag, task_labels, n_tasks, n_tasks - completed_count)
# Sort by task_index so results match input order
results.sort(key=lambda r: r["task_index"])
+
+def _finalize_live_transcripts(results: list, live_writers: list, live_paths: list) -> None:
+ """Close out live transcripts (files are retained as the full-fidelity
+ record; retention pruning happens on future dispatches)."""
+ for entry in results:
+ _idx = entry.get("task_index", -1)
+ _w = live_writers[_idx] if isinstance(_idx, int) and 0 <= _idx < len(live_writers) else None
+ if _w is not None:
+ with _quiet("Live transcript finalize failed", exc_info=True):
+ _w.finalize(entry)
+ if _idx < len(live_paths):
+ entry["live_transcript"] = live_paths[_idx]
+
+
+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.
+ """
+ from tools.delegate_tool import _run_single_child
+ from tools.delegation_live_log import update_manifest_statuses
+
+ results: list = []
+ if len(batch.task_list) == 1:
+ _i, _t, child = batch.children[0]
+ results.append(_run_single_child(_i, _t["goal"], child, batch.parent_agent, **batch.owner_kwargs()))
+ else:
+ _run_children_parallel(batch, results, honor_parent_interrupt=honor_parent_interrupt)
+
+ _finalize_child_results(results, batch.task_list, batch.children, batch.parent_agent)
+ total_duration = round(time.monotonic() - batch.overall_start, 2)
+ _finalize_live_transcripts(results, batch.live_writers, batch.live_paths)
+ 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)
+ return combined
+
+
_SYNC_FALLBACK_NOTES = {
"no_async": (
"background=true is not available in this session β€” it cannot "
@@ -150,13 +221,15 @@ _SYNC_FALLBACK_NOTES = {
),
}
-def _run_sync_with_note(execute_and_aggregate: Any, reason: str) -> str:
+
+def _run_sync_with_note(batch: _Batch, reason: str) -> str:
"""Inline fallback: run the batch now and explain why it was not detached."""
- result = execute_and_aggregate()
+ result = _execute_and_aggregate(batch)
if isinstance(result, dict):
result["note"] = _SYNC_FALLBACK_NOTES[reason]
return json.dumps(result, ensure_ascii=False)
+
def _resolve_async_wake_sid(origin_wake_sid: str) -> Optional[str]:
"""Wake target for a detached batch, or None to force synchronous execution.
@@ -186,6 +259,7 @@ def _resolve_async_wake_sid(origin_wake_sid: str) -> Optional[str]:
return origin_wake_sid
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.
@@ -201,7 +275,7 @@ def _resolve_async_session_key(parent_agent: Any, origin_ui_session_id: str) ->
session_key = get_current_session_key(default="")
agent_session_id = str(getattr(parent_agent, "session_id", "") or "")
- try:
+ with _quiet(None):
from gateway.session_context import get_session_env
source = get_session_env("HERMES_SESSION_SOURCE", "")
@@ -210,12 +284,11 @@ def _resolve_async_session_key(parent_agent: Any, origin_ui_session_id: str) ->
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
- except Exception:
- pass
if not session_key and agent_session_id:
session_key = agent_session_id
return session_key, origin_ui_session_id
+
def _batch_progress_token(child_agents: List[Any]) -> tuple:
"""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
@@ -235,6 +308,7 @@ def _batch_progress_token(child_agents: List[Any]) -> tuple:
parts.append(None)
return tuple(parts), in_tool
+
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."""
n = len(goals)
@@ -277,41 +351,27 @@ def _dispatched_payload(dispatch: dict, goals: List[str], child_agents: List[Any
)
return payload
-def _dispatch_background(
- *,
- parent_agent: Any,
- context: Optional[str],
- task_list: List[Dict[str, Any]],
- children: List[tuple],
- creds: Dict[str, Any],
- top_role: str,
- live_deleg_id: Optional[str],
- live_paths: List[str],
- origin_wake_sid: str,
- origin_ui_session_id: str,
- execute_and_aggregate: Any,
-) -> str:
+
+def _dispatch_background(batch: _Batch) -> str:
"""Dispatch the WHOLE batch as one async unit and return the tool result JSON.
- ``execute_and_aggregate`` 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 it synchronously (with an explanatory
+ 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 it 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(origin_wake_sid)
+ 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."
- )
- return _run_sync_with_note(execute_and_aggregate, "no_async")
+ logger.info("delegate_task: async delivery unsupported on this session runtime; running the batch synchronously instead.")
+ return _run_sync_with_note(batch, "no_async")
- session_key, origin_ui_session_id = _resolve_async_session_key(parent_agent, origin_ui_session_id)
- child_agents = [c for (_, _, c) in children]
+ 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 interrupt-propagation list (_build_child_agent attached
# them, which is correct for sync runs).
@@ -323,35 +383,41 @@ def _dispatch_background(
for c in child_agents:
_signal_child_stop(c, "Async delegation cancelled")
- goals = [t["goal"] for t in task_list]
+ goals = [t["goal"] for t in batch.task_list]
dispatch = dispatch_async_delegation_batch(
goals=goals,
- context=context,
+ context=batch.context,
# Metadata for the completion block only; subagents inherit the
# parent's toolsets (no model-facing toolsets arg).
toolsets=None,
- role=top_role,
- model=creds["model"],
+ 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(honor_parent_interrupt=False),
+ 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=live_deleg_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, live_paths), ensure_ascii=False)
+ 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.",
+ "delegate_task: async pool at capacity (%s); running the whole batch synchronously instead.",
dispatch.get("error", "rejected"),
)
- return _run_sync_with_note(execute_and_aggregate, "at_capacity")
+ return _run_sync_with_note(batch, "at_capacity")
+
+
+def _run_batch(batch: _Batch, background: bool) -> str:
+ """Tool result JSON: a dispatch handle (background) or the joined combined results."""
+ if background:
+ return _dispatch_background(batch)
+ return json.dumps(_execute_and_aggregate(batch), ensure_ascii=False)
diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py
index 41feee84c68..3f97c22736f 100644
--- a/tools/delegate_tool_progress.py
+++ b/tools/delegate_tool_progress.py
@@ -9,6 +9,7 @@ import logging
import enum
import os
import threading
+from contextlib import contextmanager
from typing import Any, Dict, List, Optional
from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock
@@ -20,14 +21,25 @@ logger = logging.getLogger("tools.delegate_tool")
# the parent-facing failure summary so every surface agrees.
SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"})
+@contextmanager
+def _quiet(log_message: Optional[str], *log_args: Any, exc_info: bool = False):
+ """Best-effort block: any Exception is swallowed (never reaches the run) and,
+ when ``log_message`` is given, logged at debug β€” the exception fills a trailing
+ unsatisfied ``%s``."""
+ try:
+ yield
+ except Exception as exc:
+ if log_message is None:
+ return
+ if log_message.count("%") > len(log_args):
+ log_args = log_args + (exc,)
+ logger.debug(log_message, *log_args, exc_info=exc_info)
+
def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None:
"""Invoke a child progress callback; relay failures never reach the run."""
- if not cb:
- return
- try:
- cb(event_type, *args, **kwargs)
- except Exception as e:
- logger.debug("Progress callback %s failed: %s", event_type, e)
+ if cb:
+ with _quiet("Progress callback %s failed: %s", event_type):
+ cb(event_type, *args, **kwargs)
def _clean_error_text(error: Any, max_chars: int = 200) -> str:
"""Reduce an error payload (traceback / JSON wall) to one clean line: the
@@ -147,13 +159,11 @@ def _build_child_system_prompt(
# (identity belongs to the parent). workspace_path comes only from
# explicit sources (_resolve_workspace_hint, never bare getcwd), so the
# install-tree-fallback leak doesn't apply. Best-effort.
- try:
+ _ctx_files = ""
+ with _quiet("subagent: workspace context-files load failed", exc_info=True):
from agent.prompt_builder import build_context_files_prompt
_ctx_files = build_context_files_prompt(cwd=str(workspace_path), skip_soul=True)
- except Exception:
- logger.debug("subagent: workspace context-files load failed", exc_info=True)
- _ctx_files = ""
if _ctx_files.strip():
parts.append(
"\nThe workspace's project context files are reproduced "
@@ -263,22 +273,19 @@ def _emit_parent_console(parent_agent, line: str) -> None:
bare ``print()`` would land on stdout and corrupt JSON-RPC framing."""
printer = getattr(parent_agent, "_safe_print", None)
if callable(printer):
- try:
+ with _quiet(None):
printer(line)
return
- except Exception:
- pass
print(line)
-def _print_completion_line(parent_agent: Any, spinner_ref: Any, line: str) -> None:
- """Above-spinner line when a spinner exists (console fallback if it raises), else console."""
+def _print_completion_line(parent_agent: Any, spinner_ref: Any, line: str, console_line: Optional[str] = None) -> None:
+ """Above-spinner line when a spinner exists (console fallback if it raises), else console
+ (``console_line`` when given, else the line indented two spaces)."""
if spinner_ref:
- try:
+ with _quiet(None):
spinner_ref.print_above(line)
return
- except Exception:
- pass
- _emit_parent_console(parent_agent, f" {line}")
+ _emit_parent_console(parent_agent, f" {line}" if console_line is None else console_line)
def _short(text: str, n: int) -> str:
return (text[:n] + "...") if len(text) > n else text
@@ -334,19 +341,14 @@ class _ChildProgressRelay:
return
payload = self._identity_kwargs()
payload.update(kwargs) # caller overrides (e.g. status, duration_seconds)
- try:
+ with _quiet("Parent callback failed: %s"):
self.parent_cb(event_type, tool_name, preview, args, **payload)
- except Exception as e:
- logger.debug("Parent callback failed: %s", e)
def _tree_line(self, text: str) -> None:
"""Print one tree-view line above the CLI spinner (no-op without a spinner)."""
- if not self.spinner:
- return
- try:
- self.spinner.print_above(f" {self._prefix()}β”œβ”€ {text}")
- except Exception as e:
- logger.debug("Spinner print_above failed: %s", e)
+ if self.spinner:
+ with _quiet("Spinner print_above failed: %s"):
+ self.spinner.print_above(f" {self._prefix()}β”œβ”€ {text}")
def _flush(self) -> None:
"""Flush remaining batched tool names to the gateway."""
@@ -390,10 +392,8 @@ class _ChildProgressRelay:
if summary_text:
self._tree_line(f"πŸ”€ {summary_text}")
if self.parent_cb:
- try:
+ with _quiet("Parent callback relay failed: %s"):
self.parent_cb("subagent_progress", f"{self._prefix()}{summary_text}")
- except Exception as e:
- logger.debug("Parent callback relay failed: %s", e)
def _on_tool_started(self, tool_name, preview, args, kwargs):
self.tool_count += 1