The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(delegate): dispatch β _Batch.run_child, one future-entry resolver, inline transcript finalize
Teknium089d1aa29604
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.pyindex 180f38ee22c..d75bece0434 100644--- a/tools/delegate_tool_dispatch.py+++ b/tools/delegate_tool_dispatch.py@@ -49,18 +49,21 @@ class _Batch: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_id": self.origin_ui_session_id or None,+ "owner_transport": self.origin_owner_transport,"owner_session_record": self.origin_owner_session_record,}+ def run_child(self, i: int, task: Dict[str, Any], child: Any) -> Dict[str, Any]:+ 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())+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)-+ if n_tasks > 1 and live_deleg_id:+ _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@@ -72,125 +75,93 @@ def _capture_origin() -> tuple[str, str, Any, Any]: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:- return future.result()- except Exception as exc:- return _fabricated_entry(idx, "error", str(exc), child)-+ return (_origin_wake_sid, _origin_ui_session_id, *_capture_gateway_steer_authority(_origin_ui_session_id))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."""+ """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"."""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}"completion_line = f"{'β' if status == 'completed' else 'β'} [{_slot}] {label} ({entry.get('duration_seconds', 0)}s)"- # Failed/errored/timed-out children: say WHY on the same line β a bare β- # reads as "silently dropped".- if status in SUBAGENT_FAILURE_STATUSES:- _err_line = _clean_error_text(entry.get("error"), max_chars=120)- if _err_line:- completion_line += f" β {_err_line}"+ _err_line = _clean_error_text(entry.get("error"), max_chars=120) if status in SUBAGENT_FAILURE_STATUSES else ""+ if _err_line:+ completion_line += f" β {_err_line}"_print_completion_line(parent_agent, spinner_ref, completion_line)if spinner_ref and remaining > 0: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;on parent interrupt the still-pending children are reported as- ``interrupted`` and abandoned. Prints one completion line per child.- ``results`` ends sorted by task_index.+ ``interrupted`` and abandoned (they already got the interrupt signal).+ Prints one completion line per child. ``results`` ends sorted by task_index."""- from tools.delegate_tool import _run_single_child# 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 DaemonThreadPoolExecutorparent_agent, n_tasks = batch.parent_agent, len(batch.task_list)task_labels = [t["goal"][:40] for t in batch.task_list]- completed_count = 0spinner_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.+ # Fabricated entries for still-pending / raised futures carry the correct _delegate_role._child_by_index = {i: child for (i, _, child) in batch.children}+ 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))+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- }+ futures = {executor.submit(contextvars.copy_context().run, batch.run_child, i, t, child): 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:- # Parent interrupted β collect whatever finished and abandon the- # rest (children already got the interrupt signal).- for f in pending:- idx = futures[f]- 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.extend(_entry_of(f, futures[f]) for f in pending)break-done, pending = _cf_wait(pending, timeout=0.5, return_when=FIRST_COMPLETED)for future in done:- entry = _future_entry(future, futures[future], _child_by_index.get(futures[future]))+ entry = _entry_of(future, 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]-+ _report_child_done(parent_agent, spinner_ref, entry, _tag, task_labels, n_tasks, n_tasks - len(results))+ results.sort(key=lambda r: r["task_index"]) # match input orderdef _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 backgroundthe batch JOINS on itself here so ONE consolidated results block re-enters- the conversation.+ the conversation. Live transcripts are finalized but retained as the+ full-fidelity record (retention pruning happens on future dispatches)."""- from tools.delegate_tool import _run_single_childfrom tools.delegation_live_log import update_manifest_statusesresults: 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()))+ results.append(batch.run_child(*batch.children[0]))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)+ 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]update_manifest_statuses(batch.live_deleg_id, results)combined: Dict[str, Any] = {"results": results, "total_duration_seconds": total_duration}@@ -198,22 +169,23 @@ def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = Truecombined["live_transcripts"] = list(batch.live_paths)return combined-_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 ""one-shot runner such as `hermes -z`, a cron job, a Kanban "- "worker, or a stateless HTTP endpoint). The subagent(s) ran SYNCHRONOUSLY and the result is included above."+ "worker, or a stateless HTTP endpoint). The subagent(s) ran "+ "SYNCHRONOUSLY and the result is included above."),"at_capacity": (- "The background delegation pool was at capacity (delegation.max_concurrent_children), so the subagent(s) ran "+ "The background delegation pool was at capacity "+ "(delegation.max_concurrent_children), so the subagent(s) ran ""SYNCHRONOUSLY and the result is included above. Raise "- "delegation.max_concurrent_children in config.yaml to allow more concurrent background delegations."+ "delegation.max_concurrent_children in config.yaml to allow "+ "more concurrent background delegations."),}-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(batch)@@ -221,7 +193,6 @@ def _run_sync_with_note(batch: _Batch, reason: str) -> str: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.@@ -241,14 +212,16 @@ def _resolve_async_wake_sid(origin_wake_sid: str) -> Optional[str]:return ""if origin_wake_sid:logger.info(- "delegate_task: async delivery unsupported on this session, but a session id is bound (%s) β dispatching "- "in the background and waking the session via self-post when it completes instead of forcing synchronous "- "execution.", origin_wake_sid,+ "delegate_task: async delivery unsupported on this "+ "session, but a session id is bound (%s) β dispatching "+ "in the background and waking the session via self-post "+ "when it completes instead of forcing synchronous "+ "execution.",+ origin_wake_sid,)return origin_wake_sidreturn 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.@@ -271,10 +244,7 @@ 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_idif source == "tui" and agent_session_id:session_key = agent_session_id- if not session_key and agent_session_id:- session_key = agent_session_id- return session_key, origin_ui_session_id-+ return session_key or agent_session_id, origin_ui_session_iddef _batch_progress_token(child_agents: List[Any]) -> tuple:"""Progress token for the async registry's stale monitor: every child's@@ -295,7 +265,6 @@ 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)@@ -308,12 +277,14 @@ def _dispatched_payload(dispatch: dict, goals: List[str], child_agents: List[Any"note": ("Subagent is running in the background. You and the user can ""keep working; its full result re-enters the conversation as a "- "new message when it finishes. Do not wait or poll β just continue."+ "new message when it finishes. Do not wait or poll β just "+ "continue."if n == 1 elsef"{n} subagents are running in parallel in the background. You "f"and the user can keep working; they wait on each other and "f"their consolidated results re-enter the conversation as a "- f"single message once ALL of them finish. Do not wait or poll β just continue."+ f"single message once ALL of them finish. Do not wait or poll "+ f"β just continue."),}sids = [getattr(c, "_subagent_id", None) for c in child_agents]@@ -323,18 +294,19 @@ def _dispatched_payload(dispatch: dict, goals: List[str], child_agents: List[Any"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."+ "redirect one, action='stop' with subagent_id to end one "+ "early.")if live_paths:payload["live_transcripts"] = list(live_paths)payload["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."+ "task). Read or `tail -f` these paths at any time to watch "+ "a child work while it runs.")return payload-def _dispatch_background(batch: _Batch) -> str:"""Dispatch the WHOLE batch as one async unit and return the tool result JSON.@@ -346,6 +318,7 @@ def _dispatch_background(batch: _Batch) -> str:"""from tools.delegate_tool import _get_max_async_childrenfrom 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.")@@ -388,7 +361,6 @@ def _dispatch_background(batch: _Batch) -> str:)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(@@ -397,7 +369,6 @@ def _dispatch_background(batch: _Batch) -> str:)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: