delegate_tool_progress.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. """Child progress relay, console formatting and child system-prompt construction for delegate_task."""
  2. from __future__ import annotations
  3. import logging
  4. import enum
  5. import os
  6. import threading
  7. from contextlib import contextmanager
  8. from typing import Any, Dict, List, Optional
  9. from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock
  10. logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module
  11. # Terminal child statuses that mean "the subagent did NOT deliver a usable result". Shared by the CLI spinner echo,
  12. # the gateway failure notice, and the parent-facing failure summary so every surface agrees.
  13. SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"})
  14. @contextmanager
  15. def _quiet(log_message: Optional[str], *log_args: Any, exc_info: bool = False):
  16. """Best-effort block: any Exception is swallowed (never reaches the run) and, when ``log_message`` is given,
  17. logged at debug — the exception fills a trailing unsatisfied ``%s``."""
  18. try:
  19. yield
  20. except Exception as exc:
  21. if log_message is None:
  22. return
  23. if log_message.count("%") > len(log_args):
  24. log_args = log_args + (exc,)
  25. logger.debug(log_message, *log_args, exc_info=exc_info)
  26. def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None:
  27. """Invoke a child progress callback; relay failures never reach the run."""
  28. if cb:
  29. with _quiet("Progress callback %s failed: %s", event_type):
  30. cb(event_type, *args, **kwargs)
  31. def _clean_error_text(error: Any, max_chars: int = 200) -> str:
  32. """Reduce an error payload (traceback / JSON wall) to one clean line: the exception message (last line of a
  33. traceback) or the first non-empty line, hard-capped in length."""
  34. from tools.delegation_redaction import redact_child_text
  35. lines = [ln.strip() for ln in redact_child_text(str(error or ""), force=False).strip().splitlines() if ln.strip()]
  36. if not lines:
  37. return ""
  38. line = lines[-1] if lines[0].startswith("Traceback") else lines[0]
  39. return line[: max_chars - 3] + "..." if len(line) > max_chars else line
  40. def describe_subagent_failure(failure_reason: Any, error: Any, max_chars: int = 200) -> str:
  41. """Plain-language reason for a failed child: the classified ``failure_reason`` gloss when there is one,
  42. else the child's own error text reduced to one clean line."""
  43. # One gloss table for every surface (agent/turn_failure_copy.py); the child is the subject.
  44. from agent.turn_failure_copy import failure_cause_gloss
  45. gloss = failure_cause_gloss(failure_reason, subject="it", possessive="its")
  46. return gloss or _clean_error_text(error, max_chars)
  47. def _format_duration(seconds: Any) -> str:
  48. if not isinstance(seconds, (int, float)) or seconds <= 0:
  49. return ""
  50. return f"{round(seconds / 60)} min" if seconds >= 120 else f"{round(seconds)}s"
  51. def format_subagent_failure_line(
  52. goal: Optional[str], status: Optional[str], error: Any = None, duration_seconds: Any = None,
  53. failure_reason: Any = None,
  54. ) -> str:
  55. """One clean, human-readable line describing a failed subagent, rendered directly to the user (CLI spinner
  56. echo, gateway platform notice). Says what happened and what to do next; never the raw exception when the
  57. child loop classified the failure, e.g.
  58. ``⚠️ Subagent failed — "research competitor pricing" after 12s: the model it was given was not found at the
  59. AI model service. Details: /agents, or ask me to retry with a smaller task.``"""
  60. goal_label = (goal or "").strip().replace("\n", " ")
  61. if len(goal_label) > 60:
  62. goal_label = goal_label[:57] + "..."
  63. goal_part = f' — "{goal_label}"' if goal_label else ""
  64. elapsed = _format_duration(duration_seconds)
  65. if status == "timeout":
  66. # The child's own timeout text repeats the duration and names mechanisms (API/tool calls); the
  67. # user needs the outcome and the knob.
  68. after = f" after {elapsed}" if elapsed else ""
  69. return (
  70. f"⚠️ Subagent timed out{goal_part}{after} without finishing. I will carry on without it; ask me to "
  71. "retry it, or raise delegation.child_timeout_seconds in config.yaml if these tasks legitimately "
  72. "take longer."
  73. )
  74. line = f"⚠️ Subagent failed{goal_part}"
  75. if elapsed:
  76. line += f" after {elapsed}"
  77. reason = describe_subagent_failure(failure_reason, error)
  78. if reason:
  79. line += f": {reason.rstrip('.')}"
  80. return line + ". Details: /agents, or ask me to retry with a smaller task."
  81. class DelegateEvent(str, enum.Enum):
  82. """Formal delegation progress event types. The relay normalises incoming legacy strings (``tool.started``,
  83. ``_thinking``, …) to these via ``_LEGACY_EVENT_MAP``; external consumers (gateway SSE, ACP adapter, CLI) still
  84. receive the legacy strings during the deprecation window. TASK_SPAWNED / TASK_COMPLETED / TASK_FAILED are
  85. reserved for future orchestrator lifecycle events, not emitted yet."""
  86. TASK_SPAWNED = "delegate.task_spawned"
  87. TASK_PROGRESS = "delegate.task_progress"
  88. TASK_COMPLETED = "delegate.task_completed"
  89. TASK_FAILED = "delegate.task_failed"
  90. TASK_THINKING = "delegate.task_thinking"
  91. TASK_TOOL_STARTED = "delegate.tool_started"
  92. TASK_TOOL_COMPLETED = "delegate.tool_completed"
  93. # Legacy child-agent event strings → DelegateEvent.
  94. _LEGACY_EVENT_MAP: dict[str, DelegateEvent] = {
  95. "_thinking": DelegateEvent.TASK_THINKING,
  96. "reasoning.available": DelegateEvent.TASK_THINKING,
  97. "tool.started": DelegateEvent.TASK_TOOL_STARTED,
  98. "tool.completed": DelegateEvent.TASK_TOOL_COMPLETED,
  99. "subagent_progress": DelegateEvent.TASK_PROGRESS,
  100. }
  101. # Event → _ChildProgressRelay method name. Lifecycle strings are emitted by the orchestrator itself (not
  102. # DelegateEvent). Any other DelegateEvent (TASK_TOOL_STARTED and the reserved TASK_* values) takes the tool-started
  103. # path; None means "recognised but ignored".
  104. _LIFECYCLE_EVENTS = frozenset({"subagent.spawn_requested", "subagent.start", "subagent.complete", "subagent.text"})
  105. _EVENT_HANDLERS: dict[Any, Optional[str]] = {
  106. "subagent.spawn_requested": "_on_spawn_requested",
  107. "subagent.start": "_on_start",
  108. "subagent.complete": "_on_complete",
  109. "subagent.text": "_on_text",
  110. DelegateEvent.TASK_THINKING: "_on_thinking",
  111. DelegateEvent.TASK_PROGRESS: "_on_progress",
  112. DelegateEvent.TASK_TOOL_COMPLETED: None,
  113. }
  114. def _normalize_event(event_type: Any) -> Any:
  115. """Lifecycle string / DelegateEvent / legacy string / ``delegate.*`` string
  116. → dispatch key; None for unknown events."""
  117. if isinstance(event_type, DelegateEvent) or (isinstance(event_type, str) and event_type in _LIFECYCLE_EVENTS):
  118. return event_type
  119. try:
  120. return _LEGACY_EVENT_MAP.get(event_type) or DelegateEvent(event_type)
  121. except (ValueError, TypeError):
  122. return None
  123. _CONTEXT_FILES_INTRO = (
  124. "\nThe workspace's project context files are reproduced below. Their conventions and invariants are binding for "
  125. "your work in this workspace.\n\n"
  126. )
  127. _COMPLETION_INSTRUCTIONS = (
  128. "\nComplete this task using the tools available to you. When finished, provide a clear, concise summary of:\n"
  129. "- What you did\n- What you found or accomplished\n- Any files you created or modified\n- Any issues encountered\n\n"
  130. "Important workspace rule: Never assume a repository lives at /workspace/... or any other container-style path "
  131. "unless the task/context explicitly gives that path. If no exact local path is provided, discover it first before "
  132. "issuing git/workdir-specific commands.\n\n"
  133. "Keep your final summary tight: lead with outcomes, prefer bullet points over paragraphs, and don't replay your "
  134. "whole process. Your response is returned to the parent agent as a summary, and overlong summaries crowd out the "
  135. "parent's context window."
  136. )
  137. _ORCHESTRATOR_BLOCK = (
  138. "\n## Subagent Spawning (Orchestrator Role)\n"
  139. "You have access to the `delegate_task` tool and CAN spawn your own subagents to parallelize independent work.\n\n"
  140. "WHEN to delegate:\n"
  141. "- The goal decomposes into 2+ independent subtasks that can run in parallel (e.g. research A and B simultaneously).\n"
  142. "- A subtask is reasoning-heavy and would flood your context with intermediate data.\n\n"
  143. "WHEN NOT to delegate:\n"
  144. "- Single-step mechanical work — do it directly.\n"
  145. "- Trivial tasks you can execute in one or two tool calls.\n"
  146. "- Re-delegating your entire assigned goal to one worker (that's just pass-through with no value added).\n\n"
  147. "Coordinate your workers' results and synthesize them before reporting back to your parent. You are responsible "
  148. "for the final summary, not your workers.\n\n"
  149. )
  150. _LEAF_CHILDREN_NOTE = (
  151. "Your own children MUST be leaves (cannot delegate further) because they will reach the maximum nesting depth. "
  152. "The system manages this automatically; no parameter override is available."
  153. )
  154. _NESTED_CHILDREN_NOTE = (
  155. "Your own children can themselves delegate because depth remains. The system determines this automatically "
  156. "from the nesting depth; children at the maximum depth cannot delegate further. No parameter override is available."
  157. )
  158. def _build_child_system_prompt(
  159. goal: str, context: Optional[str] = None, *, workspace_path: Optional[str] = None, role: str = "leaf",
  160. max_spawn_depth: int = 2, child_depth: int = 1,
  161. ) -> str:
  162. """Focused system prompt for a child agent. role='orchestrator' appends a delegation-capability block (modeled on
  163. OpenClaw's buildSubagentSystemPrompt); its depth note is literal truth grounded in the passed config so the LLM
  164. can't confabulate nesting."""
  165. # The goal is the child's first user turn (see ``_ChildRun.await_child``).
  166. # Keeping it out of the system prompt avoids sending OAuth Anthropic the
  167. # same task in both roles, while preserving the normal user-turn contract.
  168. parts = ["You are a focused subagent working on a specific delegated task."]
  169. if context and context.strip():
  170. parts.append(f"\nCONTEXT:\n{context}")
  171. if workspace_path and str(workspace_path).strip():
  172. parts.append(
  173. "\nWORKSPACE PATH:\n"
  174. f"{workspace_path}\n"
  175. "Use this exact path for local repository/workdir operations unless the task explicitly says otherwise."
  176. )
  177. # Project context files (AGENTS.md / CLAUDE.md / .cursorrules ...) via the SAME discovery/priority/cap logic
  178. # as the main agent's prompt: children are built with skip_context_files=True, so without this a subagent
  179. # works in a repo blind to its conventions. SOUL.md is skipped (identity belongs to the parent).
  180. # workspace_path comes only from explicit sources (_resolve_workspace_hint, never bare getcwd), so the
  181. # install-tree-fallback leak doesn't apply. Best-effort.
  182. _ctx_files = ""
  183. with _quiet("subagent: workspace context-files load failed", exc_info=True):
  184. # See #64590.
  185. from agent.prompt_builder import build_context_files_prompt
  186. _ctx_files = build_context_files_prompt(cwd=str(workspace_path), skip_soul=True)
  187. if _ctx_files.strip():
  188. parts.append(_CONTEXT_FILES_INTRO + _ctx_files.strip())
  189. parts.append(_COMPLETION_INSTRUCTIONS)
  190. if role == "orchestrator":
  191. child_note = _LEAF_CHILDREN_NOTE if child_depth + 1 >= max_spawn_depth else _NESTED_CHILDREN_NOTE
  192. parts.append(
  193. _ORCHESTRATOR_BLOCK
  194. + f"NOTE: You are at depth {child_depth}. The delegation tree is capped at max_spawn_depth={max_spawn_depth}. "
  195. + child_note
  196. )
  197. return "\n".join(parts)
  198. def _resolve_workspace_hint(parent_agent) -> Optional[str]:
  199. """Best-effort local workspace hint for child prompts: only a concrete
  200. absolute directory is ever injected (never a fake container path)."""
  201. from agent.runtime_cwd import scope_terminal_cwd
  202. candidates = [
  203. scope_terminal_cwd(), getattr(getattr(parent_agent, "_subdirectory_hints", None), "working_dir", None),
  204. getattr(parent_agent, "terminal_cwd", None), getattr(parent_agent, "cwd", None),
  205. ]
  206. for candidate in filter(None, candidates):
  207. with _quiet(None):
  208. text = os.path.abspath(os.path.expanduser(str(candidate)))
  209. if os.path.isabs(text) and os.path.isdir(text):
  210. return text
  211. return None
  212. _BATCH_ORDINALS: dict[str, dict[str, int]] = {}
  213. _BATCH_ORDINALS_LOCK = threading.Lock()
  214. def format_batch_tag(delegation_id: Optional[str], parent_agent: Any = None) -> str:
  215. """Short human tag for a delegation batch: the parent's first fan-out is ``set 1``, its next distinct
  216. delegation id ``set 2``. Several batches (a parent's fan-out plus a child's nested fan-out, or two
  217. concurrent tools) print interleaved ``[n/N]`` lines to one console; without a tag ``✓ [3/3]`` and ``✓ [3/9]``
  218. are indistinguishable, and a raw hex slice is unreadable. Ordinals are scoped per parent conversation
  219. (``parent_agent.session_id``): one process hosts many conversations and every child's own fan-out, so a
  220. process-wide counter showed a user's second wave as ``set 20``. Empty string when no id is known so callers
  221. can concatenate unconditionally."""
  222. if not isinstance(delegation_id, str) or not delegation_id:
  223. return ""
  224. scope = str(getattr(parent_agent, "session_id", None) or "")
  225. with _BATCH_ORDINALS_LOCK:
  226. ordinals = _BATCH_ORDINALS.setdefault(scope, {})
  227. n = ordinals.setdefault(delegation_id, len(ordinals) + 1)
  228. return f"set {n}"
  229. def _batch_prefix(delegation_id: Optional[str], task_index: int, task_count: int, parent_agent: Any = None) -> str:
  230. """``[set 2 · 3/9] `` for batch children, ``[set 2] `` for a lone child,
  231. ``[3/9] `` / ``""`` when the batch id is unknown."""
  232. tag = format_batch_tag(delegation_id, parent_agent)
  233. if task_count > 1:
  234. inner = f"{tag} · {task_index + 1}/{task_count}" if tag else f"{task_index + 1}/{task_count}"
  235. return f"[{inner}] "
  236. return f"[{tag}] " if tag else ""
  237. def _emit_parent_console(parent_agent, line: str) -> None:
  238. """Emit a progress line through ``parent_agent._safe_print`` when available so headless stdio hosts (ACP, gateway
  239. API) can redirect it to stderr; a bare ``print()`` would land on stdout and corrupt JSON-RPC framing."""
  240. printer = getattr(parent_agent, "_safe_print", None)
  241. if callable(printer):
  242. with _quiet(None):
  243. printer(line)
  244. return
  245. print(line)
  246. def _print_completion_line(parent_agent: Any, spinner_ref: Any, line: str, console_line: Optional[str] = None) -> None:
  247. """Above-spinner line when a spinner exists (console fallback if it raises), else console
  248. (``console_line`` when given, else the line indented two spaces)."""
  249. if spinner_ref:
  250. with _quiet(None):
  251. spinner_ref.print_above(line)
  252. return
  253. _emit_parent_console(parent_agent, f" {line}" if console_line is None else console_line)
  254. def _short(text: str, n: int) -> str:
  255. return (text[:n] + "...") if len(text) > n else text
  256. class _ChildProgressRelay:
  257. """Callable relaying one child's events to the parent display. CLI: prints tree-view lines above the parent's
  258. delegation spinner. Gateway: batches tool names (``_BATCH_SIZE``) and relays to the parent's progress callback,
  259. threading the identity kwargs (subagent_id, parent_id, depth, model, toolsets) into every event so the TUI can
  260. rebuild the live spawn tree and route per-branch controls back by ``subagent_id``."""
  261. _BATCH_SIZE = 5
  262. def __init__(
  263. self, task_index: int, goal: str, spinner: Any, parent_cb: Any, task_count: int,
  264. subagent_id, parent_id, depth, model, toolsets, session_ref,
  265. ) -> None:
  266. self.task_index, self.task_count, self.goal_label = task_index, task_count, (goal or "").strip()
  267. # session_ref is a SHARED dict filled in later by the caller — keep the identity.
  268. self.spinner, self.parent_cb, self.session_ref = spinner, parent_cb, session_ref if session_ref is not None else {}
  269. self.subagent_id, self.parent_id, self.depth, self.model, self.toolsets = (
  270. subagent_id, parent_id, depth, model, toolsets
  271. )
  272. self.batch: list[str] = []
  273. self.parent_scope: Any = None # owning parent agent; set by _build_child_progress_callback
  274. self.tool_count = 0 # per-subagent running counter
  275. from agent.runtime_context import current as embedded_context
  276. self.embedded = embedded_context() is not None
  277. def _prefix(self) -> str:
  278. # The batch tag is resolved lazily from session_ref: the relay is built
  279. # before delegate_task stamps ``_delegation_id`` on the child. The parent
  280. # scope rides in the same ref so ordinals match the parent's own lines.
  281. return _batch_prefix(
  282. self.session_ref.get("delegation_id"), self.task_index, self.task_count,
  283. parent_agent=self.session_ref.get("_parent_scope"),
  284. )
  285. def _identity_kwargs(self) -> dict[str, Any]:
  286. kw: dict[str, Any] = {"task_index": self.task_index, "task_count": self.task_count, "goal": self.goal_label}
  287. kw.update({k: getattr(self, k) for k in ("subagent_id", "parent_id", "depth", "model") if getattr(self, k) is not None})
  288. if self.toolsets is not None:
  289. kw["toolsets"] = list(self.toolsets)
  290. # child_session_id / delegation_id are filled into the shared ref once
  291. # the child exists, so every relayed event lets UIs open its session.
  292. for src, dst in (("session_id", "child_session_id"), ("delegation_id", "delegation_id")):
  293. if self.session_ref.get(src):
  294. kw[dst] = str(self.session_ref[src])
  295. kw["tool_count"] = self.tool_count
  296. return kw
  297. def _relay(self, event_type: str, tool_name: str | None = None, preview: str | None = None, args=None, **kwargs):
  298. if self.parent_cb:
  299. # kwargs override identity (e.g. status, duration_seconds).
  300. with _quiet("Parent callback failed: %s"):
  301. self.parent_cb(event_type, tool_name, preview, args, **{**self._identity_kwargs(), **kwargs})
  302. def _tree_line(self, text: str) -> None:
  303. """Print one tree-view line above the CLI spinner (no-op without a spinner)."""
  304. if self.spinner:
  305. with _quiet("Spinner print_above failed: %s"):
  306. self.spinner.print_above(f" {self._prefix()}├─ {text}")
  307. def _flush(self) -> None:
  308. """Flush remaining batched tool names to the gateway."""
  309. if self.parent_cb and self.batch:
  310. self._relay("subagent.progress", preview=f"🔀 {self._prefix()}{', '.join(self.batch)}")
  311. self.batch.clear()
  312. # ── Lifecycle events emitted by the orchestrator itself ──
  313. def _on_spawn_requested(self, tool_name, preview, args, kwargs):
  314. self._relay("subagent.spawn_requested", preview=preview or self.goal_label or "", **kwargs)
  315. def _on_start(self, tool_name, preview, args, kwargs):
  316. if self.goal_label:
  317. self._tree_line(f"🔀 {_short(self.goal_label, 55)}")
  318. self._relay("subagent.start", preview=preview or self.goal_label or "", **kwargs)
  319. def _on_complete(self, tool_name, preview, args, kwargs):
  320. # Failed child: echo one clean reason line into the CLI tree so the human
  321. # sees WHY, not just a vanished branch (gateway renders off the relayed event).
  322. # The echo is an automatic diagnostic presentation: it goes through the warning
  323. # boundary under the parent's turn snapshot. The relayed event (the gateway's
  324. # producer, which classifies it) and the child result are never gated here.
  325. if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES:
  326. from gateway.warning_notifications import render_notification
  327. parent = self.parent_scope
  328. render_notification(
  329. lambda: self._tree_line(format_subagent_failure_line(
  330. self.goal_label, kwargs.get("status"), error=kwargs.get("summary") or preview,
  331. duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
  332. )),
  333. platform=getattr(parent, "_notification_platform", getattr(parent, "platform", "cli")),
  334. user_config=getattr(parent, "_notification_config", None),
  335. )
  336. self._relay("subagent.complete", preview=preview, **kwargs)
  337. def _on_text(self, tool_name, preview, args, kwargs):
  338. # Streamed child reply text, relayed verbatim for gateway watch windows;
  339. # inert on CLI/TUI (their progress handlers ignore non-tool events).
  340. self._relay("subagent.text", preview=preview, **kwargs)
  341. # ── DelegateEvent handlers ──
  342. def _on_thinking(self, tool_name, preview, args, kwargs):
  343. text = preview or tool_name or ""
  344. self._tree_line(f'💭 "{_short(text, 55)}"')
  345. self._relay("subagent.thinking", preview=text)
  346. def _on_progress(self, tool_name, preview, args, kwargs):
  347. # Pre-batched summary from a nested orchestrator's grandchild arrives in the tool_name slot: render distinctly
  348. # (no tool-emoji lookup) and relay upward without re-batching.
  349. summary_text = tool_name or preview or ""
  350. if summary_text:
  351. self._tree_line(f"🔀 {summary_text}")
  352. if self.embedded:
  353. self._relay("subagent.progress", preview=summary_text, **kwargs)
  354. return
  355. if self.parent_cb:
  356. with _quiet("Parent callback relay failed: %s"):
  357. self.parent_cb("subagent_progress", f"{self._prefix()}{summary_text}")
  358. def _on_tool_started(self, tool_name, preview, args, kwargs):
  359. self.tool_count += 1
  360. if self.subagent_id is not None:
  361. with _active_subagents_lock:
  362. rec = _active_subagents.get(self.subagent_id)
  363. if rec is not None:
  364. rec["tool_count"] = self.tool_count
  365. rec["last_tool"] = tool_name or ""
  366. if self.spinner:
  367. from agent.display import get_tool_emoji
  368. line = f"{get_tool_emoji(tool_name or '')} {tool_name}"
  369. short = _short(preview, 35) if preview else ""
  370. self._tree_line(f'{line} "{short}"' if short else line)
  371. if self.parent_cb:
  372. self._relay("subagent.tool", tool_name, preview, args, **kwargs)
  373. self.batch.append(tool_name or "")
  374. if len(self.batch) >= self._BATCH_SIZE:
  375. self._flush()
  376. def __call__(self, event_type, tool_name: str | None = None, preview: str | None = None, args=None, **kwargs):
  377. # Embedded clients persist a tree. Grandchild observations already carry
  378. # their own identity: forward intact instead of reclassifying/relabeling.
  379. if (self.embedded and isinstance(event_type, str) and event_type.startswith("subagent.")
  380. and kwargs.get("subagent_id") and kwargs["subagent_id"] != self.subagent_id):
  381. self._relay(event_type, tool_name, preview, args, **kwargs)
  382. return
  383. key = _normalize_event(event_type)
  384. if self.embedded and key == DelegateEvent.TASK_TOOL_COMPLETED:
  385. self._relay("subagent.tool.completed", tool_name, preview, args, **kwargs)
  386. return
  387. method = None if key is None else _EVENT_HANDLERS.get(key, "_on_tool_started")
  388. if method is not None:
  389. getattr(self, method)(tool_name, preview, args, kwargs)
  390. def _build_child_progress_callback(
  391. task_index: int, goal: str, parent_agent, task_count: int = 1, *, subagent_id: Optional[str] = None,
  392. parent_id: Optional[str] = None, depth: Optional[int] = None, model: Optional[str] = None,
  393. toolsets: Optional[list[str]] = None, session_ref: Optional[dict[str, Any]] = None,
  394. ) -> Optional[callable]:
  395. """Relay for one child's events (see ``_ChildProgressRelay``), or None when the parent has neither a spinner nor a
  396. progress callback — the child then runs with no progress callback at all (zero behavior change)."""
  397. spinner = getattr(parent_agent, "_delegate_spinner", None)
  398. parent_cb = getattr(parent_agent, "tool_progress_callback", None)
  399. if not spinner and not parent_cb:
  400. return None
  401. if session_ref is not None:
  402. # Not an identity kwarg (underscore-prefixed, never relayed); only scopes the batch ordinal.
  403. session_ref["_parent_scope"] = parent_agent
  404. relay = _ChildProgressRelay(
  405. task_index, goal, spinner, parent_cb, task_count, subagent_id, parent_id, depth, model, toolsets, session_ref,
  406. )
  407. relay.parent_scope = parent_agent
  408. return relay