The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(delegate): progress relay -> _ChildProgressRelay class + event table; split _dispatch_background into collaborators
Teknium8e9628e9cf05
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.pyindex 8eb674e1029..ef8a3c4edf1 100644--- a/tools/delegate_tool_dispatch.py+++ b/tools/delegate_tool_dispatch.py@@ -9,13 +9,14 @@ from __future__ import annotationsimport contextvarsimport jsonimport logging+from concurrent.futures import FIRST_COMPLETED, wait as _cf_waitfrom typing import Any, Dict, List, Optionalfrom agent.interrupt_compat import request_hard_interruptfrom tools.delegate_tool_progress import (SUBAGENT_FAILURE_STATUSES,_clean_error_text,- _emit_parent_console,+ _print_completion_line,format_batch_tag,)@@ -36,15 +37,12 @@ def _fabricated_entry(idx: int, status: str, error: str, child: Any) -> Dict[str}-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."""- if spinner_ref:- try:- spinner_ref.print_above(line)- return- except Exception:- pass- _emit_parent_console(parent_agent, f" {line}")+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)def _run_children_parallel(@@ -71,59 +69,44 @@ def _run_children_parallel("""from tools.delegate_tool import _run_single_child- _origin_ui_session_id = origin_ui_session_id- _origin_owner_transport = origin_owner_transport- _origin_owner_session_record = origin_owner_session_record- # Batch -- run in parallel with per-task progress linescompleted_count = 0spinner_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.+ # 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 DaemonThreadPoolExecutorwith DaemonThreadPoolExecutor(max_workers=max_children) as executor:futures = {}for i, t, child in children:- child_context = contextvars.copy_context()future = executor.submit(- child_context.run,+ 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,+ owner_session_id=origin_ui_session_id or None,+ owner_transport=origin_owner_transport,+ owner_session_record=origin_owner_session_record,)futures[future] = i- # Poll futures with interrupt checking. as_completed() blocks- # until ALL futures finish — if a child agent gets stuck,- # the parent blocks forever even after interrupt propagation.- # Instead, use wait() with a short timeout so we can bail- # when the parent is interrupted.- # Map task_index -> child agent, so fabricated entries for- # still-pending futures can carry the correct _delegate_role.- _child_by_index = {i: child for (i, _, child) in children}-pending = set(futures.keys())while pending:if (honor_parent_interruptand getattr(parent_agent, "_interrupt_requested", False) is True):- # Parent interrupted — collect whatever finished and- # abandon the rest. Children already received the- # interrupt signal; we just can't wait forever.+ # 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():- try:- entry = f.result()- except Exception as exc:- entry = _fabricated_entry(idx, "error", str(exc), _child_by_index.get(idx))+ entry = _future_entry(f, idx, _child_by_index.get(idx))else:entry = _fabricated_entry(idx,@@ -135,44 +118,27 @@ def _run_children_parallel(completed_count += 1break- from concurrent.futures import wait as _cf_wait, FIRST_COMPLETED-- done, pending = _cf_wait(- pending, timeout=0.5, return_when=FIRST_COMPLETED- )+ done, pending = _cf_wait(pending, timeout=0.5, return_when=FIRST_COMPLETED)for future in done:- try:- entry = future.result()- except Exception as exc:- idx = futures[future]- entry = _fabricated_entry(idx, "error", str(exc), _child_by_index.get(idx))+ entry = _future_entry(future, futures[future], _child_by_index.get(futures[future]))results.append(entry)completed_count += 1- # Print per-task completion line above the spinneridx = entry["task_index"]- label = (- task_labels[idx] if idx < len(task_labels) else f"Task {idx}"- )- dur = entry.get("duration_seconds", 0)+ label = task_labels[idx] if idx < len(task_labels) else f"Task {idx}"status = entry.get("status", "?")icon = "✓" if status == "completed" else "✗"remaining = n_tasks - completed_count- _tag = format_batch_tag(live_deleg_id)_slot = f"{_tag} · {idx+1}/{n_tasks}" if _tag else f"{idx+1}/{n_tasks}"- completion_line = f"{icon} [{_slot}] {label} ({dur}s)"- # Failed/errored/timed-out children: say WHY on the- # same line, cleaned to one short human-readable- # fragment — a bare ✗ reads as "silently dropped".+ completion_line = f"{icon} [{_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- )+ _err_line = _clean_error_text(entry.get("error"), max_chars=120)if _err_line:completion_line += f" — {_err_line}"_print_completion_line(parent_agent, spinner_ref, completion_line)- # Update spinner text to show remaining countif spinner_ref and remaining > 0:try:spinner_ref.update_text(@@ -185,6 +151,181 @@ def _run_children_parallel(results.sort(key=lambda r: r["task_index"])+_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."+ ),+ "at_capacity": (+ "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."+ ),+}+++def _run_sync_with_note(execute_and_aggregate: Any, reason: str) -> str:+ """Inline fallback: run the batch now and explain why it was not detached."""+ result = execute_and_aggregate()+ 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.++ Finite sessions (stateless HTTP requests, one-shot Kanban workers) cannot+ route a detached result back after their turn/process ends. But if a raw+ session id is bound (the API server always binds one), gateway.wake can+ still reach the session by self-POSTing /v1/chat/completions with that id,+ so only fall back to sync when there is truly no session id to wake. Uses+ the origin captured BEFORE child construction — HERMES_SESSION_ID here+ would be the subagent's internal id.+ """+ try:+ from gateway.session_context import async_delivery_supported+ if async_delivery_supported():+ return ""+ except Exception:+ 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,+ )+ 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.++ In desktop/TUI the routable key is the durable AIAgent.session_id: context+ compression can rotate it mid-turn before the TUI-side session dict is+ re-anchored, and a stale approval-context key would orphan the completion+ for any desktop poller to consume. Gateway chats keep the platform+ conversation key (agent:main:...). The CLI (single-process) has no bound+ approval contextvar and no HERMES_SESSION_KEY, so the key resolves empty;+ it drains completions through a positive-ownership filter keyed on the+ durable session_id, so an empty key would fail closed — stamp the parent's+ durable id (compression rotations resolve on the drain side via lineage).+ """+ from tools.approval import get_current_session_key++ session_key = get_current_session_key(default="")+ agent_session_id = str(getattr(parent_agent, "session_id", "") or "")+ try:+ 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+ except Exception:+ pass+ if not session_key and agent_session_id:+ session_key = agent_session_id+ return session_key, origin_ui_session_id+++def _detach_from_parent(parent_agent: Any, child_agents: List[Any]) -> None:+ """Drop the children from the parent's interrupt-propagation list — the+ batch's lifecycle is owned by the async registry now (_build_child_agent+ attached them, correct for sync runs)."""+ if not hasattr(parent_agent, "_active_children"):+ return+ lock = getattr(parent_agent, "_active_children_lock", None)+ for c in child_agents:+ try:+ if lock:+ with lock:+ parent_agent._active_children.remove(c)+ else:+ parent_agent._active_children.remove(c)+ except ValueError:+ pass+++def _batch_progress_token(child_agents: List[Any]) -> tuple:+ """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 ticks on every streamed chunk, tool transition and+ API-call start/completion, so a child streaming a long response is alive+ even though api_call_count only advances when the call completes. A fully+ frozen token past the stale threshold means the detached batch is wedged+ (e.g. stuck inside the first model API call). ``in_tool`` is True while ANY+ child is inside a tool so slow tools get the higher staleness ceiling,+ mirroring the sync-path heartbeat monitor.+ """+ 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+++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)+ payload = {+ "status": "dispatched",+ "mode": "background",+ "count": n,+ "delegation_id": dispatch["delegation_id"],+ "goals": goals,+ "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."+ if n == 1 else+ f"{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 "+ f"— just continue."+ ),+ }+ sids = [getattr(c, "_subagent_id", None) for c in child_agents]+ if any(isinstance(s, str) and s for s in sids):+ payload["subagent_ids"] = sids+ payload["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."+ )+ 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."+ )+ return payload++def _dispatch_background(*,parent_agent: Any,@@ -208,246 +349,58 @@ def _dispatch_background(pool is at capacity."""from tools.delegate_tool import _get_max_async_children-- _execute_and_aggregate = execute_and_aggregate- _origin_wake_sid = origin_wake_sid- _origin_ui_session_id = origin_ui_session_idfrom tools.async_delegation import dispatch_async_delegation_batch- from tools.approval import get_current_session_key- # 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.- try:- from gateway.session_context import async_delivery_supported- _async_ok = async_delivery_supported()- except Exception:- _async_ok = True-- _wake_sid = ""- if not _async_ok:- # The adapter itself cannot push, but if a raw session id is- # bound (the API server always binds one — see- # ApiServerAdapter._bind_api_server_session), gateway.wake can- # still reach the session by self-POSTing /v1/chat/completions- # with that id in X-Hermes-Session-Id once the batch completes.- # Only fall back to forced-sync execution when there is truly no- # session id to wake. Uses the origin captured before child- # construction (see _origin_wake_sid above) — reading- # HERMES_SESSION_ID here would return the subagent's internal id.- _wake_sid = _origin_wake_sid- if _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.",- _wake_sid,- )- _async_ok = True-- if not _async_ok:+ wake_sid = _resolve_async_wake_sid(origin_wake_sid)+ if wake_sid is None:logger.info("delegate_task: async delivery unsupported on this session ""runtime; running the batch synchronously instead.")- _sync_result = _execute_and_aggregate()- if isinstance(_sync_result, dict):- _sync_result["note"] = (- "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."- )- return json.dumps(_sync_result, ensure_ascii=False)-- _session_key = get_current_session_key(default="")- try:- from gateway.session_context import get_session_env-- _source = get_session_env("HERMES_SESSION_SOURCE", "")- # Refresh from the same task-local source when available, but retain- # the immutable value captured before child construction otherwise.- _origin_ui_session_id = (- get_session_env("HERMES_UI_SESSION_ID", "") or _origin_ui_session_id- )- # In desktop/TUI, the routable session key is the durable- # AIAgent.session_id. Context compression can rotate that id during- # the same turn before the TUI-side session dict is re-anchored;- # if we capture the stale approval/session context key here, the- # async completion becomes an orphan and any desktop poller may- # consume it. Gateway chats are different: their session_key is the- # platform conversation key (agent:main:...), so keep it there.- if _source == "tui":- _agent_session_id = str(getattr(parent_agent, "session_id", "") or "")- if _agent_session_id:- _session_key = _agent_session_id- except Exception:- _source = ""- if not _session_key:- # CLI (single-process) path: the approval contextvar is only bound- # during gateway/TUI turns and HERMES_SESSION_KEY is not in the CLI- # environment, so the key resolves empty here. Since #64240 the CLI- # drains completions through a positive-ownership filter keyed on- # the durable AIAgent.session_id — an empty session_key would fail- # closed and the CLI could never claim its own completions, while- # a restored foreign event with an empty key could leak into any- # unfiltered consumer (#64484). Stamp the parent's durable session- # id instead; compression rotations are handled on the drain side- # via resolve_resume_session_id lineage resolution.- _agent_session_id = str(getattr(parent_agent, "session_id", "") or "")- if _agent_session_id:- _session_key = _agent_session_id- _parent_session_id = getattr(parent_agent, "session_id", None)- _child_agents = [c for (_, _, c) in children]-- # Detach every child from the parent's interrupt-propagation list — the- # batch's lifecycle is owned by the async registry now, not the parent- # turn. _build_child_agent attached them (correct for sync runs).- if hasattr(parent_agent, "_active_children"):- _ac_lock = getattr(parent_agent, "_active_children_lock", None)- for _c in _child_agents:- try:- if _ac_lock:- with _ac_lock:- parent_agent._active_children.remove(_c)- else:- parent_agent._active_children.remove(_c)- except ValueError:- pass+ return _run_sync_with_note(execute_and_aggregate, "no_async")- def _batch_runner():- # This batch is detached from the foreground turn. Its lifecycle is- # owned by the async registry and cancelled only via _batch_interrupt.- return _execute_and_aggregate(honor_parent_interrupt=False)+ session_key, origin_ui_session_id = _resolve_async_session_key(parent_agent, origin_ui_session_id)+ child_agents = [c for (_, _, c) in children]+ _detach_from_parent(parent_agent, child_agents)def _batch_interrupt():- for _c in _child_agents:+ # Cancellation path for the detached batch (owned by the async registry).+ for c in child_agents:try:- interrupted = request_hard_interrupt(_c, "Async delegation cancelled")- if not interrupted and hasattr(_c, "_interrupt_requested"):- _c._interrupt_requested = True+ if not request_hard_interrupt(c, "Async delegation cancelled") and hasattr(c, "_interrupt_requested"):+ c._interrupt_requested = Trueexcept Exception:pass- def _batch_progress():- # 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). A fully frozen- # token past the stale threshold means the detached batch is- # wedged (e.g. stuck inside the first model API call — #60203).- # in_tool=True while ANY child is inside a tool so legitimately- # slow tools get the higher staleness ceiling, mirroring the- # sync-path heartbeat monitor.- 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-- _goals = [t["goal"] for t in task_list]+ goals = [t["goal"] for t in task_list]dispatch = dispatch_async_delegation_batch(- goals=_goals,+ goals=goals,context=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"],- session_key=_session_key,- origin_ui_session_id=_origin_ui_session_id,- origin_session_id=_wake_sid,- parent_session_id=_parent_session_id,- runner=_batch_runner,+ 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),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,- progress_fn=_batch_progress,+ progress_fn=lambda: _batch_progress_token(child_agents),)-if dispatch.get("status") == "dispatched":- n = len(_goals)- 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."- if n == 1 else- f"{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 "- f"— just continue."- )- payload = {- "status": "dispatched",- "mode": "background",- "count": n,- "delegation_id": dispatch["delegation_id"],- "goals": _goals,- "note": note,- }- _sids = [- getattr(_c, "_subagent_id", None) for _c in _child_agents- ]- if any(isinstance(s, str) and s for s in _sids):- payload["subagent_ids"] = _sids- payload["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."- )- 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."- )- return json.dumps(payload, ensure_ascii=False)+ return json.dumps(_dispatched_payload(dispatch, goals, child_agents, live_paths), ensure_ascii=False)- # Pool at capacity / schedule failure — children are still attached- # (we detach above only on the parent list, but the async unit was- # never accepted, so re-attaching isn't needed: we just run inline).+ # 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"),)- _cap_result = _execute_and_aggregate()- if isinstance(_cap_result, dict):- _cap_result["note"] = (- "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."- )- return json.dumps(_cap_result, ensure_ascii=False)+ return _run_sync_with_note(execute_and_aggregate, "at_capacity")diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.pyindex f70be4155eb..1fbfd414175 100644--- a/tools/delegate_tool_progress.py+++ b/tools/delegate_tool_progress.py@@ -18,30 +18,29 @@ logger = logging.getLogger("tools.delegate_tool")# Terminal child statuses that mean "the subagent did NOT deliver a usable# result". Shared by the CLI spinner echo, the gateway failure notice, and-# the parent-facing failure summary so every surface agrees on what counts-# as a failure.+# the parent-facing failure summary so every surface agrees.SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"})-def _clean_error_text(error: Any, max_chars: int = 200) -> str:- """Reduce an arbitrary error payload to one clean human-readable line.+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)- Provider/SDK errors routinely arrive as multi-line tracebacks or JSON- walls. For a chat-facing notice we want the single most informative- line: the exception message (last line of a traceback) or the first- non-empty line otherwise, hard-capped in length.- """- text = str(error or "").strip()- if not text:- return ""- lines = [ln.strip() for ln in text.splitlines() if ln.strip()]++def _clean_error_text(error: Any, max_chars: int = 200) -> str:+ """Reduce an error payload (traceback / JSON wall) to one clean line: the+ exception message (last line of a traceback) or the first non-empty line,+ hard-capped in length."""+ lines = [ln.strip() for ln in str(error or "").strip().splitlines() if ln.strip()]if not lines:return ""- # A traceback's last line is the actual exception message.line = lines[-1] if lines[0].startswith("Traceback") else lines[0]- if len(line) > max_chars:- line = line[: max_chars - 3] + "..."- return line+ return line[: max_chars - 3] + "..." if len(line) > max_chars else linedef format_subagent_failure_line(@@ -50,19 +49,13 @@ def format_subagent_failure_line(error: Any = None,duration_seconds: Any = None,) -> str:- """One clean, human-readable line describing a failed subagent.-- Rendered directly to the user (CLI spinner echo, gateway platform- notice) — no JSON, no traceback, no internal field names. Example:-- ⚠️ Subagent failed — "research competitor pricing": Error code: 404 —- model not found (after 12s)- """+ """One clean, human-readable line describing a failed subagent, rendered+ directly to the user (CLI spinner echo, gateway platform notice), e.g.+ ``⚠️ Subagent failed — "research competitor pricing": Error code: 404 (after 12s)``."""goal_label = (goal or "").strip().replace("\n", " ")if len(goal_label) > 60:goal_label = goal_label[:57] + "..."- verb = "timed out" if status == "timeout" else "failed"- line = f"⚠️ Subagent {verb}"+ line = f"⚠️ Subagent {'timed out' if status == 'timeout' else 'failed'}"if goal_label:line += f' — "{goal_label}"'err = _clean_error_text(error)@@ -76,13 +69,11 @@ def format_subagent_failure_line(class DelegateEvent(str, enum.Enum):"""Formal event types emitted during delegation progress.- _build_child_progress_callback normalises incoming legacy strings- (``tool.started``, ``_thinking``, …) to these enum values via- ``_LEGACY_EVENT_MAP``. External consumers (gateway SSE, ACP adapter,- CLI) still receive the legacy strings during the deprecation window.-- TASK_SPAWNED / TASK_COMPLETED / TASK_FAILED are reserved for- future orchestrator lifecycle events and are not currently emitted.+ The relay normalises incoming legacy strings (``tool.started``,+ ``_thinking``, …) to these values via ``_LEGACY_EVENT_MAP``; external+ consumers (gateway SSE, ACP adapter, CLI) still receive the legacy strings+ during the deprecation window. TASK_SPAWNED / TASK_COMPLETED / TASK_FAILED+ are reserved for future orchestrator lifecycle events, not emitted yet."""TASK_SPAWNED = "delegate.task_spawned"@@ -94,8 +85,7 @@ class DelegateEvent(str, enum.Enum):TASK_TOOL_COMPLETED = "delegate.tool_completed"-# Legacy event strings → DelegateEvent mapping.-# Incoming child-agent events use the old names; the callback normalises them.+# Legacy child-agent event strings → DelegateEvent._LEGACY_EVENT_MAP: Dict[str, DelegateEvent] = {"_thinking": DelegateEvent.TASK_THINKING,"reasoning.available": DelegateEvent.TASK_THINKING,@@ -104,6 +94,36 @@ _LEGACY_EVENT_MAP: Dict[str, DelegateEvent] = {"subagent_progress": DelegateEvent.TASK_PROGRESS,}+# Event → _ChildProgressRelay method name. Lifecycle strings are emitted by the+# orchestrator itself (not DelegateEvent). Any other DelegateEvent+# (TASK_TOOL_STARTED and the reserved TASK_* values) takes the tool-started+# path; None means "recognised but ignored".+_LIFECYCLE_EVENTS = frozenset({"subagent.start", "subagent.complete", "subagent.text"})+_EVENT_HANDLERS: Dict[Any, Optional[str]] = {+ "subagent.start": "_on_start",+ "subagent.complete": "_on_complete",+ "subagent.text": "_on_text",+ DelegateEvent.TASK_THINKING: "_on_thinking",+ DelegateEvent.TASK_PROGRESS: "_on_progress",+ DelegateEvent.TASK_TOOL_COMPLETED: None,+}+++def _normalize_event(event_type: Any) -> Any:+ """Lifecycle string / DelegateEvent / legacy string / ``delegate.*`` string+ → dispatch key; None for unknown events."""+ if isinstance(event_type, DelegateEvent) or (+ isinstance(event_type, str) and event_type in _LIFECYCLE_EVENTS+ ):+ return event_type+ event = _LEGACY_EVENT_MAP.get(event_type)+ if event is not None:+ return event+ try:+ return DelegateEvent(event_type)+ except (ValueError, TypeError):+ return None+def _build_child_system_prompt(goal: str,@@ -116,11 +136,9 @@ def _build_child_system_prompt() -> str:"""Build a focused system prompt for a child agent.- When role='orchestrator', appends a delegation-capability block- modeled on OpenClaw's buildSubagentSystemPrompt (canSpawn branch at- inspiration/openclaw/src/agents/subagent-system-prompt.ts:63-95).- The depth note is literal truth (grounded in the passed config) so- the LLM doesn't confabulate nesting capabilities that don't exist.+ role='orchestrator' appends a delegation-capability block (modeled on+ OpenClaw's buildSubagentSystemPrompt); its depth note is literal truth+ grounded in the passed config so the LLM can't confabulate nesting."""parts = ["You are a focused subagent working on a specific delegated task.",@@ -135,17 +153,13 @@ def _build_child_system_prompt(f"{workspace_path}\n""Use this exact path for local repository/workdir operations unless the task explicitly says otherwise.")- # Project context files (AGENTS.md / CLAUDE.md / .cursorrules ...)- # from the workspace, via the SAME discovery/priority/cap logic the- # main agent's system prompt uses. Children are constructed with- # skip_context_files=True (their prompt is this focused one), so- # without this a subagent works in a repo without the repo's own- # conventions unless it thinks to go read them. SOUL.md is skipped —- # identity belongs to the parent. workspace_path comes only from- # explicit sources (_resolve_workspace_hint: TERMINAL_CWD / agent cwd- # hints, never bare getcwd), so the #64590 install-tree-fallback leak- # doesn't apply here. Best-effort: on any failure the child prompt is- # simply built without the block.+ # Project context files (AGENTS.md / CLAUDE.md / .cursorrules ...) via+ # the SAME discovery/priority/cap logic as the main agent's prompt:+ # children are built with skip_context_files=True, so without this a+ # subagent works in a repo blind to its conventions. SOUL.md is skipped+ # (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:from agent.prompt_builder import build_context_files_prompt@@ -212,12 +226,8 @@ def _build_child_system_prompt(def _resolve_workspace_hint(parent_agent) -> Optional[str]:- """Best-effort local workspace hint for child prompts.-- We only inject a path when we have a concrete absolute directory. This avoids- teaching subagents a fake container path while still helping them avoid- guessing `/workspace/...` for local repo tasks.- """+ """Best-effort local workspace hint for child prompts: only a concrete+ absolute directory is ever injected (never a fake container path)."""candidates = [os.getenv("TERMINAL_CWD"),getattr(@@ -243,23 +253,19 @@ _BATCH_ORDINALS_LOCK = threading.Lock()def format_batch_tag(delegation_id: Optional[str]) -> str:- """Short human tag identifying which delegation batch a line belongs to.-- ``deleg_6a664903`` → ``set 1`` (first batch seen in this process),- the next distinct id → ``set 2``, and so on. Several batches (a parent's- fan-out plus a child's nested fan-out, or two concurrent tools) print- interleaved ``[n/N]`` progress lines to the same console; without a batch- tag a ``✓ [3/3]`` and a ``✓ [3/9]`` are indistinguishable, and a raw hex- slice (``[b2ac 3/9]``) is attributable but unreadable. Empty string when- no id is known so callers can concatenate unconditionally.+ """Short human tag for a delegation batch: ``deleg_6a664903`` → ``set 1``+ (first batch seen in this process), the next distinct id → ``set 2``.++ Several batches (a parent's fan-out plus a child's nested fan-out, or two+ concurrent tools) print interleaved ``[n/N]`` lines to one console; without+ a tag ``✓ [3/3]`` and ``✓ [3/9]`` are indistinguishable, and a raw hex+ slice is unreadable. Empty string when no id is known so callers can+ concatenate unconditionally."""if not isinstance(delegation_id, str) or not delegation_id:return ""with _BATCH_ORDINALS_LOCK:- n = _BATCH_ORDINALS.get(delegation_id)- if n is None:- n = len(_BATCH_ORDINALS) + 1- _BATCH_ORDINALS[delegation_id] = n+ n = _BATCH_ORDINALS.setdefault(delegation_id, len(_BATCH_ORDINALS) + 1)return f"set {n}"@@ -274,13 +280,9 @@ def _batch_prefix(delegation_id: Optional[str], task_index: int, task_count: intdef _emit_parent_console(parent_agent, line: str) -> None:- """Emit a human-readable progress line to the parent's console.-- Routes through ``parent_agent._safe_print`` when available so headless- stdio hosts (ACP, gateway API) can redirect non-protocol output to- stderr via their configured ``_print_fn``. A bare ``print()`` would- otherwise land on stdout and corrupt JSON-RPC framing.- """+ """Emit a progress line through ``parent_agent._safe_print`` when available+ so headless stdio hosts (ACP, gateway API) can redirect it to stderr; a+ bare ``print()`` would land on stdout and corrupt JSON-RPC framing."""printer = getattr(parent_agent, "_safe_print", None)if callable(printer):try:@@ -291,216 +293,184 @@ def _emit_parent_console(parent_agent, line: str) -> None:print(line)-def _build_child_progress_callback(- task_index: int,- goal: str,- parent_agent,- task_count: int = 1,- *,- subagent_id: Optional[str] = None,- parent_id: Optional[str] = None,- depth: Optional[int] = None,- model: Optional[str] = None,- toolsets: Optional[List[str]] = None,- session_ref: Optional[Dict[str, Any]] = None,-) -> Optional[callable]:- """Build a callback that relays child agent tool calls to the parent display.-- Two display paths:- CLI: prints tree-view lines above the parent's delegation spinner- Gateway: batches tool names and relays to parent's progress callback+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."""+ if spinner_ref:+ try:+ spinner_ref.print_above(line)+ return+ except Exception:+ pass+ _emit_parent_console(parent_agent, f" {line}")- The identity kwargs (``subagent_id``, ``parent_id``, ``depth``, ``model``,- ``toolsets``) are threaded into every relayed event so the TUI can- reconstruct the live spawn tree and route per-branch controls (kill,- pause) back by ``subagent_id``. All are optional for backward compat —- older callers that ignore them still produce a flat list on the TUI.- Returns None if no display mechanism is available, in which case the- child agent runs with no progress callback (identical to current behavior).- """- spinner = getattr(parent_agent, "_delegate_spinner", None)- parent_cb = getattr(parent_agent, "tool_progress_callback", None)+def _short(text: str, n: int) -> str:+ return (text[:n] + "...") if len(text) > n else text- if not spinner and not parent_cb:- return None # No display → no callback → zero behavior change- # Show 1-indexed prefix only in batch mode (multiple tasks). The batch tag- # (short delegation id) is resolved lazily from session_ref because the- # callback is built before delegate_task stamps ``_delegation_id`` on the- # child; delegate_task drops the id into the same shared ref.- def _prefix() -> str:- deleg = session_ref.get("delegation_id") if session_ref else None- return _batch_prefix(deleg, task_index, task_count)+class _ChildProgressRelay:+ """Callable relaying one child's events to the parent display.- goal_label = (goal or "").strip()+ CLI: prints tree-view lines above the parent's delegation spinner.+ Gateway: batches tool names (``_BATCH_SIZE``) and relays to the parent's+ progress callback, threading the identity kwargs (subagent_id, parent_id,+ depth, model, toolsets) into every event so the TUI can rebuild the live+ spawn tree and route per-branch controls back by ``subagent_id``.+ """- # Gateway: batch tool names, flush periodically_BATCH_SIZE = 5- _batch: List[str] = []- _tool_count = [0] # per-subagent running counter (list for closure mutation)- def _identity_kwargs() -> Dict[str, Any]:+ def __init__(+ self, task_index: int, goal: str, spinner: Any, parent_cb: Any, task_count: int,+ subagent_id, parent_id, depth, model, toolsets, session_ref,+ ) -> None:+ self.task_index, self.task_count, self.goal_label = task_index, task_count, (goal or "").strip()+ self.spinner, self.parent_cb, self.session_ref = spinner, parent_cb, session_ref+ self.subagent_id, self.parent_id, self.depth, self.model, self.toolsets = (+ subagent_id, parent_id, depth, model, toolsets+ )+ self.batch: List[str] = []+ self.tool_count = 0 # per-subagent running counter++ def _prefix(self) -> str:+ # The batch tag is resolved lazily from session_ref: the relay is built+ # before delegate_task stamps ``_delegation_id`` on the child.+ deleg = self.session_ref.get("delegation_id") if self.session_ref else None+ return _batch_prefix(deleg, self.task_index, self.task_count)++ def _identity_kwargs(self) -> Dict[str, Any]:kw: Dict[str, Any] = {- "task_index": task_index,- "task_count": task_count,- "goal": goal_label,+ "task_index": self.task_index, "task_count": self.task_count, "goal": self.goal_label,}- if subagent_id is not None:- kw["subagent_id"] = subagent_id- if parent_id is not None:- kw["parent_id"] = parent_id- if depth is not None:- kw["depth"] = depth- if model is not None:- kw["model"] = model- if toolsets is not None:- kw["toolsets"] = list(toolsets)- # The child's own session id — filled into the shared ref once the- # child agent exists (the callback is built first), so every relayed- # event lets UIs open/inspect the subagent's session directly.- if session_ref and session_ref.get("session_id"):- kw["child_session_id"] = str(session_ref["session_id"])- if session_ref and session_ref.get("delegation_id"):- kw["delegation_id"] = str(session_ref["delegation_id"])- kw["tool_count"] = _tool_count[0]+ for key in ("subagent_id", "parent_id", "depth", "model"):+ if getattr(self, key) is not None:+ kw[key] = getattr(self, key)+ if self.toolsets is not None:+ kw["toolsets"] = list(self.toolsets)+ # child_session_id / delegation_id are filled into the shared ref once+ # the child exists, so every relayed event lets UIs open its session.+ for src, dst in (("session_id", "child_session_id"), ("delegation_id", "delegation_id")):+ if self.session_ref and self.session_ref.get(src):+ kw[dst] = str(self.session_ref[src])+ kw["tool_count"] = self.tool_countreturn kw- def _relay(- event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs- ):- if not parent_cb:+ def _relay(self, event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs):+ if not self.parent_cb:return- payload = _identity_kwargs()+ payload = self._identity_kwargs()payload.update(kwargs) # caller overrides (e.g. status, duration_seconds)try:- parent_cb(event_type, tool_name, preview, args, **payload)+ self.parent_cb(event_type, tool_name, preview, args, **payload)except Exception as e:logger.debug("Parent callback failed: %s", e)- def _tree_line(text: str) -> None:+ def _tree_line(self, text: str) -> None:"""Print one tree-view line above the CLI spinner (no-op without a spinner)."""- if not spinner:+ if not self.spinner:returntry:- spinner.print_above(f" {_prefix()}├─ {text}")+ self.spinner.print_above(f" {self._prefix()}├─ {text}")except Exception as e:logger.debug("Spinner print_above failed: %s", e)- def _flush_batch() -> None:- if parent_cb and _batch:- _relay("subagent.progress", preview=f"🔀 {_prefix()}{', '.join(_batch)}")- _batch.clear()-- def _short(text: str, n: int) -> str:- return (text[:n] + "...") if len(text) > n else text+ def _flush(self) -> None:+ """Flush remaining batched tool names to the gateway."""+ if self.parent_cb and self.batch:+ self._relay("subagent.progress", preview=f"🔀 {self._prefix()}{', '.join(self.batch)}")+ self.batch.clear()- # ── Lifecycle events emitted by the orchestrator itself (not DelegateEvent) ──- def _on_start(tool_name, preview, args, kwargs):- if goal_label:- _tree_line(f"🔀 {_short(goal_label, 55)}")- _relay("subagent.start", preview=preview or goal_label or "", **kwargs)+ # ── Lifecycle events emitted by the orchestrator itself ──+ def _on_start(self, tool_name, preview, args, kwargs):+ if self.goal_label:+ self._tree_line(f"🔀 {_short(self.goal_label, 55)}")+ self._relay("subagent.start", preview=preview or self.goal_label or "", **kwargs)- def _on_complete(tool_name, preview, args, kwargs):+ def _on_complete(self, tool_name, preview, args, kwargs):# Failed child: echo one clean reason line into the CLI tree so the human- # sees WHY, not just a vanished branch. Gateway-side rendering happens in- # TurnRunner.progress_callback off the relayed event.+ # sees WHY, not just a vanished branch (gateway renders off the relayed event).if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES:- _tree_line(- format_subagent_failure_line(- goal_label,- kwargs.get("status"),- error=kwargs.get("summary") or preview,- duration_seconds=kwargs.get("duration_seconds"),- )- )- _relay("subagent.complete", preview=preview, **kwargs)-- def _on_text(tool_name, preview, args, kwargs):- # Streamed child reply text, relayed verbatim so a gateway watch window- # mirrors the child "talking". No spinner echo: CLI/TUI progress- # handlers ignore non-tool events, so this is inert there.- _relay("subagent.text", preview=preview)+ self._tree_line(format_subagent_failure_line(+ self.goal_label, kwargs.get("status"),+ error=kwargs.get("summary") or preview,+ duration_seconds=kwargs.get("duration_seconds"),+ ))+ self._relay("subagent.complete", preview=preview, **kwargs)++ def _on_text(self, tool_name, preview, args, kwargs):+ # Streamed child reply text, relayed verbatim for gateway watch windows;+ # inert on CLI/TUI (their progress handlers ignore non-tool events).+ self._relay("subagent.text", preview=preview)# ── DelegateEvent handlers ──- def _on_thinking(tool_name, preview, args, kwargs):+ def _on_thinking(self, tool_name, preview, args, kwargs):text = preview or tool_name or ""- _tree_line(f'💭 "{_short(text, 55)}"')- _relay("subagent.thinking", preview=text)-- def _on_progress(tool_name, preview, args, kwargs):- # Pre-batched summary from a nested orchestrator's grandchild; upstream- # emits parent_cb("subagent_progress", summary) with the summary in the- # tool_name slot. Pass through: render distinctly (not via the tool- # emoji lookup) and relay upward without re-batching.+ self._tree_line(f'💭 "{_short(text, 55)}"')+ self._relay("subagent.thinking", preview=text)++ def _on_progress(self, tool_name, preview, args, kwargs):+ # Pre-batched summary from a nested orchestrator's grandchild arrives in+ # the tool_name slot: render distinctly (no tool-emoji lookup) and relay+ # upward without re-batching.summary_text = tool_name or preview or ""if summary_text:- _tree_line(f"🔀 {summary_text}")- if parent_cb:+ self._tree_line(f"🔀 {summary_text}")+ if self.parent_cb:try:- parent_cb("subagent_progress", f"{_prefix()}{summary_text}")+ 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(tool_name, preview, args, kwargs):- _tool_count[0] += 1- if subagent_id is not None:+ def _on_tool_started(self, tool_name, preview, args, kwargs):+ self.tool_count += 1+ if self.subagent_id is not None:with _active_subagents_lock:- rec = _active_subagents.get(subagent_id)+ rec = _active_subagents.get(self.subagent_id)if rec is not None:- rec["tool_count"] = _tool_count[0]+ rec["tool_count"] = self.tool_countrec["last_tool"] = tool_name or ""- if spinner:+ if self.spinner:from agent.display import get_tool_emojiline = f"{get_tool_emoji(tool_name or '')} {tool_name}"short = _short(preview, 35) if preview else ""- if short:- line += f' "{short}"'- _tree_line(line)- if parent_cb:- _relay("subagent.tool", tool_name, preview, args)- _batch.append(tool_name or "")- if len(_batch) >= _BATCH_SIZE:- _flush_batch()-- _lifecycle_handlers = {- "subagent.start": _on_start,- "subagent.complete": _on_complete,- "subagent.text": _on_text,- }- # Any other DelegateEvent (TASK_TOOL_STARTED and the reserved TASK_* values)- # takes the tool-started path, as before the table.- _event_handlers = {- DelegateEvent.TASK_THINKING: _on_thinking,- DelegateEvent.TASK_PROGRESS: _on_progress,- DelegateEvent.TASK_TOOL_COMPLETED: None,- }-- def _callback(- event_type, tool_name: str = None, preview: str = None, args=None, **kwargs- ):- handler = _lifecycle_handlers.get(event_type) if isinstance(event_type, str) else None- if handler is None:- # Normalise legacy strings, "delegate.*" strings and DelegateEvent- # values to one DelegateEvent; unknown events are ignored.- if isinstance(event_type, DelegateEvent):- event = event_type- else:- event = _LEGACY_EVENT_MAP.get(event_type)- if event is None:- try:- event = DelegateEvent(event_type)- except (ValueError, TypeError):- return- handler = _event_handlers.get(event, _on_tool_started)- if handler is None:- return- handler(tool_name, preview, args, kwargs)-- def _flush():- """Flush remaining batched tool names to gateway on completion."""- _flush_batch()-- _callback._flush = _flush- return _callback+ self._tree_line(f'{line} "{short}"' if short else line)+ if self.parent_cb:+ self._relay("subagent.tool", tool_name, preview, args)+ self.batch.append(tool_name or "")+ if len(self.batch) >= self._BATCH_SIZE:+ self._flush()++ def __call__(self, event_type, tool_name: str = None, preview: str = None, args=None, **kwargs):+ key = _normalize_event(event_type)+ if key is None:+ return+ method = _EVENT_HANDLERS.get(key, "_on_tool_started")+ if method is not None:+ getattr(self, method)(tool_name, preview, args, kwargs)+++def _build_child_progress_callback(+ task_index: int,+ goal: str,+ parent_agent,+ task_count: int = 1,+ *,+ subagent_id: Optional[str] = None,+ parent_id: Optional[str] = None,+ depth: Optional[int] = None,+ model: Optional[str] = None,+ toolsets: Optional[List[str]] = None,+ session_ref: Optional[Dict[str, Any]] = None,+) -> Optional[callable]:+ """Relay for one child's events (see ``_ChildProgressRelay``), or None when+ the parent has neither a spinner nor a progress callback — the child then+ runs with no progress callback at all (zero behavior change)."""+ spinner = getattr(parent_agent, "_delegate_spinner", None)+ parent_cb = getattr(parent_agent, "tool_progress_callback", None)+ if not spinner and not parent_cb:+ return None+ return _ChildProgressRelay(+ task_index, goal, spinner, parent_cb, task_count,+ subagent_id, parent_id, depth, model, toolsets, session_ref,+ )