From 50d63b28692b6da24f5faf6aebe43b6f70c91022 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:34:51 -0700 Subject: [PATCH 01/11] refactor(delegate): dedupe config knobs via _cfg(), split credential resolution by branch --- tools/delegate_tool_config.py | 365 ++++++++++++++++------------------ 1 file changed, 173 insertions(+), 192 deletions(-) diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py index 8a82fff102..c1bb9c0e36 100644 --- a/tools/delegate_tool_config.py +++ b/tools/delegate_tool_config.py @@ -32,6 +32,13 @@ _LEGACY_MAX_ASYNC_WARNED = False DEFAULT_CHILD_TIMEOUT: Optional[float] = None +def _cfg() -> dict: + """The ``delegation`` section, read through the origin so tests can patch it.""" + from tools.delegate_tool import _load_config + + return _load_config() + + # ── Subagent approval callbacks ───────────────────────────────────────────── # Subagent worker threads don't inherit the CLI's threading.local approval # callback, so prompt_dangerous_approval() would fall back to input() and @@ -60,10 +67,7 @@ def _subagent_auto_approve(command: str, description: str, **kwargs) -> str: def _get_subagent_approval_callback(): """Callback for subagent worker threads per delegation.subagent_auto_approve (default False).""" - from tools.delegate_tool import _load_config - cfg = _load_config() - val = cfg.get("subagent_auto_approve", False) - if is_truthy_value(val): + if is_truthy_value(_cfg().get("subagent_auto_approve", False)): return _subagent_auto_approve return _subagent_auto_deny @@ -73,22 +77,10 @@ def _get_max_concurrent_children() -> int: Floor of 1 is the only bound enforced; there is no ceiling. """ - from tools.delegate_tool import _load_config - cfg = _load_config() - val = cfg.get("max_concurrent_children") + val = _cfg().get("max_concurrent_children") if val is not None: try: result = max(1, int(val)) - if result > 10: - global _HIGH_CONCURRENCY_WARNED - if not _HIGH_CONCURRENCY_WARNED: - _HIGH_CONCURRENCY_WARNED = True - logger.warning( - "delegation.max_concurrent_children=%d: each child consumes API tokens " - "independently. High values multiply cost linearly.", - result, - ) - return result except (TypeError, ValueError): logger.warning( "delegation.max_concurrent_children=%r is not a valid integer; " @@ -97,6 +89,16 @@ def _get_max_concurrent_children() -> int: _DEFAULT_MAX_CONCURRENT_CHILDREN, ) return _DEFAULT_MAX_CONCURRENT_CHILDREN + if result > 10: + global _HIGH_CONCURRENCY_WARNED + if not _HIGH_CONCURRENCY_WARNED: + _HIGH_CONCURRENCY_WARNED = True + logger.warning( + "delegation.max_concurrent_children=%d: each child consumes API tokens " + "independently. High values multiply cost linearly.", + result, + ) + return result env_val = os.getenv("DELEGATION_MAX_CONCURRENT_CHILDREN") if env_val: try: @@ -113,9 +115,7 @@ def _get_worktree_isolation() -> bool: parallel children never contend for one working copy. Git-only and local-backend-only; otherwise silently ignored (shared workspace as before). """ - from tools.delegate_tool import _load_config - cfg = _load_config() - return bool(cfg.get("worktree_isolation", False)) + return bool(_cfg().get("worktree_isolation", False)) def _get_max_async_children() -> int: @@ -126,10 +126,9 @@ def _get_max_async_children() -> int: A leftover ``delegation.max_async_children`` key is ignored with a one-time deprecation warning. """ - from tools.delegate_tool import _get_max_concurrent_children, _load_config + from tools.delegate_tool import _get_max_concurrent_children global _LEGACY_MAX_ASYNC_WARNED - cfg = _load_config() - if cfg.get("max_async_children") is not None and not _LEGACY_MAX_ASYNC_WARNED: + if _cfg().get("max_async_children") is not None and not _LEGACY_MAX_ASYNC_WARNED: _LEGACY_MAX_ASYNC_WARNED = True logger.warning( "delegation.max_async_children is deprecated and ignored; " @@ -139,6 +138,12 @@ def _get_max_async_children() -> int: return _get_max_concurrent_children() +def _parse_timeout(raw: Any) -> Optional[float]: + """Seconds → None (<= 0 disables) or max(30, value). Raises on non-numeric.""" + parsed = float(raw) + return None if parsed <= 0 else max(30.0, parsed) + + def _get_child_timeout() -> Optional[float]: """Hard wall-clock cap for one child, or None (default: no timeout). @@ -147,28 +152,22 @@ def _get_child_timeout() -> Optional[float]: staleness monitor. delegation.child_timeout_seconds > 0 opts in (floor 30 s); 0 or negative disables. Env fallback: DELEGATION_CHILD_TIMEOUT_SECONDS. """ - from tools.delegate_tool import _load_config - cfg = _load_config() - val = cfg.get("child_timeout_seconds") + val = _cfg().get("child_timeout_seconds") if val is not None: try: - parsed = float(val) + return _parse_timeout(val) except (TypeError, ValueError): logger.warning( "delegation.child_timeout_seconds=%r is not a valid number; " "using default (no timeout)", val, ) - else: - return None if parsed <= 0 else max(30.0, parsed) env_val = os.getenv("DELEGATION_CHILD_TIMEOUT_SECONDS") if env_val: try: - parsed = float(env_val) + return _parse_timeout(env_val) except (TypeError, ValueError): pass - else: - return None if parsed <= 0 else max(30.0, parsed) return DEFAULT_CHILD_TIMEOUT @@ -178,9 +177,7 @@ def _get_max_spawn_depth() -> int: Depth 0 is the parent; agents at depths 0..N-1 may spawn, depth N is the leaf floor. Default 1 is flat. Each extra level multiplies API cost. """ - from tools.delegate_tool import _load_config - cfg = _load_config() - val = cfg.get("max_spawn_depth") + val = _cfg().get("max_spawn_depth") if val is None: return MAX_DEPTH try: @@ -205,9 +202,7 @@ def _get_max_spawn_depth() -> int: def _get_orchestrator_enabled() -> bool: """delegation.orchestrator_enabled kill switch (default True): False forces every child to leaf.""" - from tools.delegate_tool import _load_config - cfg = _load_config() - val = cfg.get("orchestrator_enabled", True) + val = _cfg().get("orchestrator_enabled", True) if isinstance(val, bool): return val # Accept "true"/"false" strings from YAML that doesn't auto-coerce. @@ -218,14 +213,13 @@ def _get_orchestrator_enabled() -> bool: def _get_inherit_mcp_toolsets() -> bool: """Whether narrowed child toolsets should keep the parent's MCP toolsets.""" - from tools.delegate_tool import _load_config - cfg = _load_config() - return is_truthy_value(cfg.get("inherit_mcp_toolsets"), default=True) + return is_truthy_value(_cfg().get("inherit_mcp_toolsets"), default=True) def _normalized_runtime_url(value: Any) -> str: return str(value or "").strip().rstrip("/") + def _inherit_parent_capabilities( parent_agent, override_provider, override_base_url ) -> Optional[dict]: @@ -255,29 +249,27 @@ def _inherit_parent_base_url(parent_agent, fallback_base_url: Optional[str]) -> """ surface_url = _normalized_runtime_url(fallback_base_url) client_kwargs = getattr(parent_agent, "_client_kwargs", None) - if isinstance(client_kwargs, dict): - kwargs_url = _normalized_runtime_url(client_kwargs.get("base_url")) - if ( - kwargs_url - and kwargs_url != surface_url - and kwargs_url.startswith(("http://", "https://")) - ): - return kwargs_url - client = getattr(parent_agent, "client", None) - if client is not None: + live_candidates = ( + client_kwargs.get("base_url") if isinstance(client_kwargs, dict) else None, # OpenAI SDK exposes base_url as httpx.URL — coerce before comparing. - live_url = _normalized_runtime_url(getattr(client, "base_url", "")) - if ( - live_url - and live_url != surface_url - and live_url.startswith(("http://", "https://")) - ): - return live_url - + getattr(client, "base_url", "") if client is not None else None, + ) + for raw in live_candidates: + url = _normalized_runtime_url(raw) + if url and url != surface_url and url.startswith(("http://", "https://")): + return url return fallback_base_url or None +def _loaded_pool(key: Any): + """``load_pool(key)`` when it holds credentials, else None.""" + from agent.credential_pool import load_pool + + pool = load_pool(key) + return pool if pool is not None and pool.has_credentials() else None + + def _resolve_child_credential_pool( effective_provider: Optional[str], parent_agent, @@ -291,15 +283,14 @@ def _resolve_child_credential_pool( pool across different custom endpoints would overwrite the child's delegated base_url on lease. """ - if not effective_provider: - return getattr(parent_agent, "_credential_pool", None) - - parent_provider = getattr(parent_agent, "provider", None) or "" parent_pool = getattr(parent_agent, "_credential_pool", None) + if not effective_provider: + return parent_pool + parent_provider = getattr(parent_agent, "provider", None) or "" if effective_provider == "custom": try: - from agent.credential_pool import get_custom_provider_pool_key, load_pool + from agent.credential_pool import get_custom_provider_pool_key child_key = get_custom_provider_pool_key(effective_base_url) if child_key is None: @@ -316,10 +307,7 @@ def _resolve_child_credential_pool( and parent_key == child_key ): return parent_pool - - pool = load_pool(child_key) - if pool is not None and pool.has_credentials(): - return pool + return _loaded_pool(child_key) except Exception as exc: logger.debug( "Could not resolve custom credential pool for child endpoint '%s': %s", @@ -330,13 +318,8 @@ def _resolve_child_credential_pool( if parent_pool is not None and effective_provider == parent_provider: return parent_pool - try: - from agent.credential_pool import load_pool - - pool = load_pool(effective_provider) - if pool is not None and pool.has_credentials(): - return pool + return _loaded_pool(effective_provider) except Exception as exc: logger.debug( "Could not load credential pool for child provider '%s': %s", @@ -374,115 +357,84 @@ def _merge_request_overrides(runtime_overrides, explicit_overrides): return merged or None -def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: - """Resolve the child credential bundle from the ``delegation`` config section. +# Native-SDK providers speak their own wire protocol and can't be reached via +# chat_completions against a base_url: always take the runtime-provider path +# (a configured base_url still flows through it, e.g. a Bedrock region). +_NATIVE_SDK_PROVIDERS = frozenset({"bedrock", "vertex", "google", "google-genai"}) +_EXPLICIT_API_MODES = frozenset({"chat_completions", "codex_responses", "anthropic_messages"}) - Three branches: ``base_url`` set → direct endpoint (``api_key`` None means - inherit the parent's key, so providers keyed outside OPENAI_API_KEY work); - ``provider`` set → full bundle via the runtime provider system (same path as - CLI/gateway startup); neither → None values, child inherits everything. - ``request_overrides`` is honored on every branch. Raises ValueError with a - user-facing message on credential failure. - """ - configured_model = str(cfg.get("model") or "").strip() or None - configured_provider = str(cfg.get("provider") or "").strip() or None - configured_base_url = str(cfg.get("base_url") or "").strip() or None - configured_api_key = str(cfg.get("api_key") or "").strip() or None - configured_api_mode = str(cfg.get("api_mode") or "").strip().lower() or None - explicit_request_overrides = ( - cfg.get("request_overrides") - if isinstance(cfg.get("request_overrides"), dict) - else None +def _require_pinned_command(command: Optional[str], message: str) -> None: + """A pinned ACP transport command must exist on PATH — refuse loudly rather + than let the child silently fall back to another transport.""" + if not command: + return + import shutil as _shutil + + if not _shutil.which(command): + raise ValueError(message) + + +def _direct_endpoint_credentials(cfg_values: dict, explicit_request_overrides) -> dict: + """``delegation.base_url`` branch: provider/api_mode from URL heuristics.""" + configured_model, configured_provider, configured_base_url, configured_api_key, configured_api_mode = ( + cfg_values["model"], cfg_values["provider"], cfg_values["base_url"], + cfg_values["api_key"], cfg_values["api_mode"], ) + # Shared URL-based api_mode detector so Anthropic-compatible direct + # endpoints (/anthropic suffix: Azure AI Foundry, MiniMax, Zhipu, LiteLLM) + # get the Messages transport instead of 404ing on chat_completions. + from hermes_cli.runtime_provider import _detect_api_mode_for_url - # Native-SDK providers speak their own wire protocol and can't be reached - # via chat_completions against a base_url: always take the runtime-provider - # path (a configured base_url still flows through it, e.g. a Bedrock region). - _NATIVE_SDK_PROVIDERS = {"bedrock", "vertex", "google", "google-genai"} - _provider_lower = (configured_provider or "").strip().lower() - _is_native_sdk_provider = _provider_lower in _NATIVE_SDK_PROVIDERS + base_lower = configured_base_url.lower() + host = base_url_hostname(configured_base_url) + provider = "custom" + api_mode = _detect_api_mode_for_url(configured_base_url) or "chat_completions" + if host == "chatgpt.com" and "/backend-api/codex" in base_lower: + provider, api_mode = "openai-codex", "codex_responses" + elif host == "api.anthropic.com": + provider, api_mode = "anthropic", "anthropic_messages" + elif "api.kimi.com/coding" in base_lower: + api_mode = "anthropic_messages" + # Explicit delegation.api_mode always wins over the URL heuristic. + if configured_api_mode in _EXPLICIT_API_MODES: + api_mode = configured_api_mode - if configured_base_url and not _is_native_sdk_provider: - api_key = configured_api_key # None → inherited from parent in _build_child_agent + # provider configured ALONGSIDE base_url: pull that provider's request + # personality (request_overrides / max_output_tokens) onto the explicit + # endpoint. Best-effort — a resolution failure only skips the overrides. + request_overrides = None + max_output_tokens = None + if configured_provider: + try: + from hermes_cli.runtime_provider import resolve_runtime_provider - # Shared URL-based api_mode detector so Anthropic-compatible direct - # endpoints (/anthropic suffix: Azure AI Foundry, MiniMax, Zhipu, LiteLLM) - # get the Messages transport instead of 404ing on chat_completions. - from hermes_cli.runtime_provider import _detect_api_mode_for_url + runtime = resolve_runtime_provider( + requested=configured_provider, target_model=configured_model + ) + request_overrides = dict(runtime.get("request_overrides") or {}) or None + max_output_tokens = runtime.get("max_output_tokens") + except Exception as exc: + logger.debug( + "delegation.base_url: runtime resolution for provider '%s' " + "failed; proceeding without request_overrides: %s", + configured_provider, + exc, + ) + return { + "model": configured_model, + "provider": provider, + "base_url": configured_base_url, + "api_key": configured_api_key, # None → inherited from parent in _build_child_agent + "api_mode": api_mode, + "request_overrides": _merge_request_overrides(request_overrides, explicit_request_overrides), + "max_output_tokens": max_output_tokens, + } - base_lower = configured_base_url.lower() - provider = "custom" - api_mode = _detect_api_mode_for_url(configured_base_url) or "chat_completions" - if ( - base_url_hostname(configured_base_url) == "chatgpt.com" - and "/backend-api/codex" in base_lower - ): - provider = "openai-codex" - api_mode = "codex_responses" - elif base_url_hostname(configured_base_url) == "api.anthropic.com": - provider = "anthropic" - api_mode = "anthropic_messages" - elif "api.kimi.com/coding" in base_lower: - provider = "custom" - api_mode = "anthropic_messages" - # Explicit delegation.api_mode always wins over the URL heuristic. - if configured_api_mode in {"chat_completions", "codex_responses", "anthropic_messages"}: - api_mode = configured_api_mode - - # provider configured ALONGSIDE base_url: pull that provider's request - # personality (request_overrides / max_output_tokens) onto the explicit - # endpoint. Best-effort — a resolution failure only skips the overrides. - request_overrides = None - max_output_tokens = None - if configured_provider: - try: - from hermes_cli.runtime_provider import resolve_runtime_provider - - runtime = resolve_runtime_provider( - requested=configured_provider, target_model=configured_model - ) - request_overrides = dict(runtime.get("request_overrides") or {}) or None - max_output_tokens = runtime.get("max_output_tokens") - except Exception as exc: - logger.debug( - "delegation.base_url: runtime resolution for provider '%s' " - "failed; proceeding without request_overrides: %s", - configured_provider, - exc, - ) - - request_overrides = _merge_request_overrides( - request_overrides, explicit_request_overrides - ) - - return { - "model": configured_model, - "provider": provider, - "base_url": configured_base_url, - "api_key": api_key, - "api_mode": api_mode, - "request_overrides": request_overrides, - "max_output_tokens": max_output_tokens, - } - - if not configured_provider: - # Pure inherit; explicit request_overrides still merge OVER the parent's. - return { - "model": configured_model, - "provider": None, - "base_url": None, - "api_key": None, - "api_mode": None, - "request_overrides": _merge_request_overrides( - getattr(parent_agent, "request_overrides", None), - explicit_request_overrides, - ), - "max_output_tokens": None, - } - - # Provider is configured — resolve full credentials +def _runtime_provider_credentials(cfg_values: dict, explicit_request_overrides) -> dict: + """``delegation.provider`` branch: full bundle via the runtime provider system.""" + configured_model, configured_provider = cfg_values["model"], cfg_values["provider"] try: from hermes_cli.runtime_provider import resolve_runtime_provider @@ -501,20 +453,13 @@ def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: f"Delegation provider '{configured_provider}' resolved but has no API key. " f"Set the appropriate environment variable or run 'hermes auth'." ) - - # A pinned ACP transport command must exist — refuse loudly rather than let - # the child silently fall back to another transport. pinned_command = runtime.get("command") - if pinned_command: - import shutil as _shutil - - if not _shutil.which(pinned_command): - raise ValueError( - f"Delegation provider '{configured_provider}' is pinned to the " - f"'{pinned_command}' command, which was not found on PATH. " - f"Install it or choose a different delegation provider." - ) - + _require_pinned_command( + pinned_command, + f"Delegation provider '{configured_provider}' is pinned to the " + f"'{pinned_command}' command, which was not found on PATH. " + f"Install it or choose a different delegation provider.", + ) return { "model": configured_model or runtime.get("model") or None, "provider": configured_provider if runtime.get("provider") == _RUNTIME_PROVIDER_CUSTOM else runtime.get("provider"), @@ -531,6 +476,44 @@ def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: } +def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: + """Resolve the child credential bundle from the ``delegation`` config section. + + Three branches: ``base_url`` set → direct endpoint (``api_key`` None means + inherit the parent's key, so providers keyed outside OPENAI_API_KEY work); + ``provider`` set → full bundle via the runtime provider system (same path as + CLI/gateway startup); neither → None values, child inherits everything. + ``request_overrides`` is honored on every branch. Raises ValueError with a + user-facing message on credential failure. + """ + values = {k: str(cfg.get(k) or "").strip() or None for k in ("model", "provider", "base_url", "api_key")} + values["api_mode"] = str(cfg.get("api_mode") or "").strip().lower() or None + explicit_request_overrides = ( + cfg.get("request_overrides") + if isinstance(cfg.get("request_overrides"), dict) + else None + ) + is_native_sdk_provider = (values["provider"] or "").strip().lower() in _NATIVE_SDK_PROVIDERS + + if values["base_url"] and not is_native_sdk_provider: + return _direct_endpoint_credentials(values, explicit_request_overrides) + if not values["provider"]: + # Pure inherit; explicit request_overrides still merge OVER the parent's. + return { + "model": values["model"], + "provider": None, + "base_url": None, + "api_key": None, + "api_mode": None, + "request_overrides": _merge_request_overrides( + getattr(parent_agent, "request_overrides", None), + explicit_request_overrides, + ), + "max_output_tokens": None, + } + return _runtime_provider_credentials(values, explicit_request_overrides) + + def _load_config() -> dict: """Return the ``delegation`` config section (read-only — do NOT mutate). @@ -540,13 +523,11 @@ def _load_config() -> dict: ``HERMES_IGNORE_USER_CONFIG=1`` is only honored by the legacy loader, so it stays authoritative when that flag is set. """ - prefer_legacy = os.environ.get("HERMES_IGNORE_USER_CONFIG") == "1" - if not prefer_legacy: + if os.environ.get("HERMES_IGNORE_USER_CONFIG") != "1": try: from hermes_cli.config import load_config_readonly - full = load_config_readonly() - cfg = full.get("delegation") or {} + cfg = load_config_readonly().get("delegation") or {} if isinstance(cfg, dict): return cfg except Exception: From 8e9628e9cf05f825c74123914433c51d90049272 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:40:23 -0700 Subject: [PATCH 02/11] refactor(delegate): progress relay -> _ChildProgressRelay class + event table; split _dispatch_background into collaborators --- tools/delegate_tool_dispatch.py | 497 ++++++++++++++---------------- tools/delegate_tool_progress.py | 518 +++++++++++++++----------------- 2 files changed, 469 insertions(+), 546 deletions(-) diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index 8eb674e102..ef8a3c4edf 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -9,13 +9,14 @@ from __future__ import annotations import contextvars import json import logging +from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait from typing import Any, Dict, List, Optional from agent.interrupt_compat import request_hard_interrupt from 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 lines 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. + # 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: - 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_interrupt and 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 += 1 break - 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 spinner idx = 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 count if 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_id from 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) + return _run_sync_with_note(execute_and_aggregate, "no_async") - _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 - - 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 = True except 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//. 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.py index f70be4155e..1fbfd41417 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 line def 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. + """Short human tag for a delegation batch: ``deleg_6a664903`` → ``set 1`` + (first batch seen in this process), the next distinct id → ``set 2``. - ``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. + 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: int def _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,6 +293,163 @@ def _emit_parent_console(parent_agent, line: str) -> None: 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.""" + if spinner_ref: + try: + spinner_ref.print_above(line) + return + except Exception: + pass + _emit_parent_console(parent_agent, f" {line}") + + +def _short(text: str, n: int) -> str: + return (text[:n] + "...") if len(text) > n else text + + +class _ChildProgressRelay: + """Callable relaying one child's events to the parent display. + + 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``. + """ + + _BATCH_SIZE = 5 + + 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": self.task_index, "task_count": self.task_count, "goal": self.goal_label, + } + 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_count + return kw + + def _relay(self, event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs): + if not self.parent_cb: + return + payload = self._identity_kwargs() + payload.update(kwargs) # caller overrides (e.g. status, duration_seconds) + try: + 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) + + 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 ── + 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(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 renders off the relayed event). + if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES: + 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(self, tool_name, preview, args, kwargs): + text = preview or tool_name or "" + 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: + self._tree_line(f"🔀 {summary_text}") + if self.parent_cb: + try: + 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 + if self.subagent_id is not None: + with _active_subagents_lock: + rec = _active_subagents.get(self.subagent_id) + if rec is not None: + rec["tool_count"] = self.tool_count + rec["last_tool"] = tool_name or "" + if self.spinner: + from agent.display import get_tool_emoji + + line = f"{get_tool_emoji(tool_name or '')} {tool_name}" + short = _short(preview, 35) if preview else "" + 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, @@ -304,203 +463,14 @@ def _build_child_progress_callback( 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 - - 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). - """ + """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 # 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) - - goal_label = (goal or "").strip() - - # 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]: - kw: Dict[str, Any] = { - "task_index": task_index, - "task_count": task_count, - "goal": 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] - return kw - - def _relay( - event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs - ): - if not parent_cb: - return - payload = _identity_kwargs() - payload.update(kwargs) # caller overrides (e.g. status, duration_seconds) - try: - 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: - """Print one tree-view line above the CLI spinner (no-op without a spinner).""" - if not spinner: - return - try: - spinner.print_above(f" {_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 - - # ── 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) - - def _on_complete(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. - 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) - - # ── DelegateEvent handlers ── - def _on_thinking(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. - summary_text = tool_name or preview or "" - if summary_text: - _tree_line(f"🔀 {summary_text}") - if parent_cb: - try: - parent_cb("subagent_progress", f"{_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: - with _active_subagents_lock: - rec = _active_subagents.get(subagent_id) - if rec is not None: - rec["tool_count"] = _tool_count[0] - rec["last_tool"] = tool_name or "" - if spinner: - from agent.display import get_tool_emoji - - line = 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 + return None + return _ChildProgressRelay( + task_index, goal, spinner, parent_cb, task_count, + subagent_id, parent_id, depth, model, toolsets, session_ref, + ) From c1f8fd4e40ed287675e756a007e99e9223921840 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:33:00 -0700 Subject: [PATCH 03/11] wip(delegate): child_run dedupe snapshot (unverified; worker died at 401) --- tools/delegate_tool_child_run.py | 1035 +++++++++++++----------------- 1 file changed, 433 insertions(+), 602 deletions(-) diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index 89c6093d03..a7d0030186 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -15,6 +15,7 @@ from typing import Any, Dict, List, Optional from agent.interrupt_compat import request_hard_interrupt from dataclasses import dataclass from tools import file_state +from tools.delegate_tool_progress import _safe_progress from tools.delegate_tool_registry import ( _capture_gateway_steer_authority, _close_subagent_steering, _register_subagent, _unregister_subagent, ) @@ -26,6 +27,92 @@ from tools.delegate_tool_results import ( logger = logging.getLogger("tools.delegate_tool") +def _num(value: Any, default: int = 0) -> int: + """int() for counters that may be mocks/None on test doubles.""" + return int(value) if isinstance(value, (int, float)) else default + + +def _fabricated_entry( + idx: int, status: str, error: str, child: Any, duration: float = 0 +) -> Dict[str, Any]: + """Result entry for a child that raised / never finished / was abandoned.""" + return { + "task_index": idx, + "status": status, + "summary": None, + "error": error, + "api_calls": 0, + "duration_seconds": duration, + "_child_role": getattr(child, "_delegate_role", None), + } + + +def _append_missed_steer(entry: Dict[str, Any], late_steer: Optional[str]) -> None: + """Record steer text that won the race with the child's failure/timeout.""" + if late_steer: + entry["missed_steer"] = late_steer + entry["error"] += ( + " [steer did not land before the subagent stopped: " + f"{late_steer}]" + ) + + +def _close_child(child: Any, log_message: str) -> None: + """Best-effort ``child.close()`` (tool sandboxes, browser daemons, httpx clients).""" + try: + close = getattr(child, "close", None) + if callable(close): + close() + except Exception: + logger.debug(log_message, exc_info=True) + + +def _attach_child(parent_agent: Any, child: Any) -> None: + """Register the child for parent interrupt propagation.""" + if not hasattr(parent_agent, "_active_children"): + return + lock = getattr(parent_agent, "_active_children_lock", None) + if lock: + with lock: + parent_agent._active_children.append(child) + else: + parent_agent._active_children.append(child) + + +def _detach_child(parent_agent: Any, child: Any) -> None: + """Remove the child from parent interrupt propagation (no-op if absent).""" + if not hasattr(parent_agent, "_active_children"): + return + try: + lock = getattr(parent_agent, "_active_children_lock", None) + if lock: + with lock: + parent_agent._active_children.remove(child) + else: + parent_agent._active_children.remove(child) + except (ValueError, UnboundLocalError) as e: + logger.debug("Could not remove child from active_children: %s", e) + + +def _signal_child_stop(child: Any) -> None: + """Cooperative interrupt so the child's worker thread can exit cleanly.""" + try: + if child is not None and not request_hard_interrupt(child) and hasattr(child, "_interrupt_requested"): + child._interrupt_requested = True + except Exception: + pass + + +def _format_thread_stack(frame: Any, indent: str) -> List[str]: + import traceback as _traceback + + return [ + f"{indent}{sub}" + for frame_line in _traceback.format_stack(frame) + for sub in frame_line.rstrip().split("\n") + ] + + def _dump_subagent_timeout_diagnostic( *, child: Any, @@ -35,75 +122,58 @@ def _dump_subagent_timeout_diagnostic( worker_thread: Optional[threading.Thread], goal: str, ) -> Optional[str]: - """Write a structured diagnostic dump for a subagent that timed out - before making any API call. - - See issue #14726: users hit "subagent timed out after 300s with no response" - with zero API calls and no way to inspect what happened. This helper - writes a dedicated log under ``~/.hermes/logs/subagent--.log`` - capturing the child's config, system-prompt / tool-schema sizes, activity - tracker snapshot, and the worker thread's Python stack at timeout. - - Returns the absolute path to the diagnostic file, or None on failure. + """Write a structured diagnostic for a subagent that timed out before any + API call (users hit "timed out with no response" and 0 API calls with no way + to inspect it). Lands under ``~/.hermes/logs/subagent-timeout--.log`` + with the child's config, prompt/schema sizes, activity snapshot and the + worker thread's stack. Returns the path, or None on failure. """ try: from hermes_constants import get_hermes_home import datetime as _dt import sys as _sys - import traceback as _traceback import threading as _threading - hermes_home = get_hermes_home() - logs_dir = hermes_home / "logs" + logs_dir = get_hermes_home() / "logs" try: logs_dir.mkdir(parents=True, exist_ok=True) except Exception: return None subagent_id = getattr(child, "_subagent_id", None) or f"idx{task_index}" - ts = _dt.datetime.now().strftime("%Y%m%d_%H%M%S") - dump_path = logs_dir / f"subagent-timeout-{subagent_id}-{ts}.log" - - lines: List[str] = [] - def _w(line: str = "") -> None: - lines.append(line) - - _w("# Subagent timeout diagnostic — issue #14726") - _w(f"# Generated: {_dt.datetime.now().isoformat()}") - _w("") - _w("## Timeout") - _w(f" task_index: {task_index}") - _w(f" subagent_id: {subagent_id}") - _w(f" configured_timeout: {timeout_seconds}s") - _w(f" actual_duration: {duration_seconds:.2f}s") - _w("") - - _w("## Goal") + dump_path = logs_dir / f"subagent-timeout-{subagent_id}-{_dt.datetime.now().strftime('%Y%m%d_%H%M%S')}.log" _goal_preview = (goal or "").strip() if len(_goal_preview) > 1000: _goal_preview = _goal_preview[:1000] + " ...[truncated]" - _w(_goal_preview or "(empty)") - _w("") - - _w("## Child config") + lines: List[str] = [ + "# Subagent timeout diagnostic — issue #14726", + f"# Generated: {_dt.datetime.now().isoformat()}", + "", + "## Timeout", + f" task_index: {task_index}", + f" subagent_id: {subagent_id}", + f" configured_timeout: {timeout_seconds}s", + f" actual_duration: {duration_seconds:.2f}s", + "", + "## Goal", + _goal_preview or "(empty)", + "", + "## Child config", + ] + _w = lines.append for attr in ( "model", "provider", "api_mode", "base_url", "max_iterations", "quiet_mode", "skip_memory", "skip_context_files", "platform", "_delegate_role", "_delegate_depth", ): try: - val = getattr(child, attr, None) - # Redact api_key-shaped values defensively - if isinstance(val, str) and attr == "base_url": - pass - _w(f" {attr}: {val!r}") + _w(f" {attr}: {getattr(child, attr, None)!r}") except Exception: _w(f" {attr}: ") _w("") _w("## Toolsets") - enabled = getattr(child, "enabled_toolsets", None) - _w(f" enabled_toolsets: {enabled!r}") + _w(f" enabled_toolsets: {getattr(child, 'enabled_toolsets', None)!r}") tool_names = getattr(child, "valid_tool_names", None) if tool_names: _w(f" loaded tool count: {len(tool_names)}") @@ -115,9 +185,7 @@ def _dump_subagent_timeout_diagnostic( _w("## Prompt / schema sizes") try: - sys_prompt = getattr(child, "ephemeral_system_prompt", None) \ - or getattr(child, "system_prompt", None) \ - or "" + sys_prompt = getattr(child, "ephemeral_system_prompt", None) or getattr(child, "system_prompt", None) or "" _w(f" system_prompt_bytes: {len(sys_prompt.encode('utf-8')) if isinstance(sys_prompt, str) else 'n/a'}") _w(f" system_prompt_chars: {len(sys_prompt) if isinstance(sys_prompt, str) else 'n/a'}") except Exception as exc: @@ -125,33 +193,28 @@ def _dump_subagent_timeout_diagnostic( try: tools_schema = getattr(child, "tools", None) if tools_schema is not None: - _schema_json = json.dumps(tools_schema, default=str) _w(f" tool_schema_count: {len(tools_schema)}") - _w(f" tool_schema_bytes: {len(_schema_json.encode('utf-8'))}") + _w(f" tool_schema_bytes: {len(json.dumps(tools_schema, default=str).encode('utf-8'))}") except Exception as exc: _w(f" tool_schema: ") _w("") _w("## Activity summary") try: - summary = child.get_activity_summary() - for k, v in summary.items(): + for k, v in child.get_activity_summary().items(): _w(f" {k}: {v!r}") except Exception as exc: _w(f" ") _w("") _w("## Worker thread stack at timeout") + frames = _sys._current_frames() if worker_thread is not None and worker_thread.is_alive(): - frames = _sys._current_frames() worker_frame = frames.get(worker_thread.ident) - if worker_frame is not None: - stack = _traceback.format_stack(worker_frame) - for frame_line in stack: - for sub in frame_line.rstrip().split("\n"): - _w(f" {sub}") - else: - _w(" ") + lines.extend( + _format_thread_stack(worker_frame, " ") if worker_frame is not None + else [" "] + ) elif worker_thread is None: _w(" ") else: @@ -164,9 +227,7 @@ def _dump_subagent_timeout_diagnostic( _w("## All thread stacks at timeout") try: frames = _sys._current_frames() - by_ident = { - th.ident: th for th in _threading.enumerate() if th.ident - } + by_ident = {th.ident: th for th in _threading.enumerate() if th.ident} worker_ident = worker_thread.ident if worker_thread else None dumped = 0 for ident, frame in frames.items(): @@ -177,11 +238,8 @@ def _dump_subagent_timeout_diagnostic( break th = by_ident.get(ident) name = th.name if th else f"ident={ident}" - daemon = " daemon" if (th and th.daemon) else "" - _w(f" --- {name}{daemon} ---") - for frame_line in _traceback.format_stack(frame): - for sub in frame_line.rstrip().split("\n"): - _w(f" {sub}") + _w(f" --- {name}{' daemon' if (th and th.daemon) else ''} ---") + lines.extend(_format_thread_stack(frame, " ")) dumped += 1 except Exception as exc: _w(f" ") @@ -216,19 +274,13 @@ def _start_heartbeat(child: Any, parent_agent: Any, task_index: int) -> tuple: _heartbeat_stop = threading.Event() # Stale detection: a cycle counts as stale when (tool, iteration, # activity_ts) all froze; thresholds differ idle vs in-tool. - _last_seen_iter = [0] - _last_seen_tool = [None] # type: list - _last_seen_activity_ts = [None] # type: list - _stale_count = [0] + last_seen = {"iter": 0, "tool": None, "ts": None, "stale": 0} def _heartbeat_loop(): while not _heartbeat_stop.wait(_HEARTBEAT_INTERVAL): - if parent_agent is None: - continue - touch = getattr(parent_agent, "_touch_activity", None) + touch = getattr(parent_agent, "_touch_activity", None) if parent_agent is not None else None if not touch: continue - # Pull detail from the child's own activity tracker desc = f"delegate_task: subagent {task_index} working" try: child_summary = child.get_activity_summary() @@ -239,51 +291,34 @@ def _start_heartbeat(child: Any, parent_agent: Any, task_index: int) -> tuple: # A slow model wait refreshes last_activity_ts (direct_api_call # heartbeat), so it never looks stale at the idle threshold. - iter_advanced = child_iter > _last_seen_iter[0] - tool_changed = child_tool != _last_seen_tool[0] - activity_advanced = ( - child_activity_ts is not None - and ( - _last_seen_activity_ts[0] is None - or child_activity_ts > _last_seen_activity_ts[0] - ) + activity_advanced = child_activity_ts is not None and ( + last_seen["ts"] is None or child_activity_ts > last_seen["ts"] ) - if iter_advanced or tool_changed or activity_advanced: - _last_seen_iter[0] = child_iter - _last_seen_tool[0] = child_tool + if child_iter > last_seen["iter"] or child_tool != last_seen["tool"] or activity_advanced: + last_seen["iter"], last_seen["tool"], last_seen["stale"] = child_iter, child_tool, 0 if child_activity_ts is not None: - _last_seen_activity_ts[0] = child_activity_ts - _stale_count[0] = 0 + last_seen["ts"] = child_activity_ts else: - _stale_count[0] += 1 + last_seen["stale"] += 1 - stale_limit = ( - _HEARTBEAT_STALE_CYCLES_IN_TOOL - if child_tool - else _HEARTBEAT_STALE_CYCLES_IDLE - ) - if _stale_count[0] >= stale_limit: + stale_limit = _HEARTBEAT_STALE_CYCLES_IN_TOOL if child_tool else _HEARTBEAT_STALE_CYCLES_IDLE + if last_seen["stale"] >= stale_limit: logger.warning( "Subagent %d appears stale (no progress for %d " "heartbeat cycles, tool=%s) — stopping heartbeat", task_index, - _stale_count[0], + last_seen["stale"], child_tool or "", ) break # stop touching parent, let gateway timeout fire if child_tool: + desc = f"delegate_task: subagent running {child_tool} (iteration {child_iter}/{child_max})" + elif child_summary.get("last_activity_desc", ""): desc = ( - f"delegate_task: subagent running {child_tool} " + f"delegate_task: subagent {child_summary.get('last_activity_desc', '')} " f"(iteration {child_iter}/{child_max})" ) - else: - child_desc = child_summary.get("last_activity_desc", "") - if child_desc: - desc = ( - f"delegate_task: subagent {child_desc} " - f"(iteration {child_iter}/{child_max})" - ) except Exception: pass try: @@ -291,8 +326,7 @@ def _start_heartbeat(child: Any, parent_agent: Any, task_index: int) -> tuple: except Exception: pass - _heartbeat_thread = threading.Thread(target=_heartbeat_loop, daemon=True) - return _heartbeat_stop, _heartbeat_thread + return _heartbeat_stop, threading.Thread(target=_heartbeat_loop, daemon=True) def _register_child( @@ -309,62 +343,50 @@ def _register_child( Test doubles without a stable string ``_subagent_id`` are not registered (returns None) and the caller skips every registry interaction for them. """ - _raw_sid = getattr(child, "_subagent_id", None) - _subagent_id = _raw_sid if isinstance(_raw_sid, str) else None - if _subagent_id: - if owner_session_id is None: - try: - from gateway.session_context import get_session_env - - owner_session_id = get_session_env("HERMES_UI_SESSION_ID", "") or None - except Exception: - owner_session_id = None - if owner_session_id and ( - owner_transport is None or owner_session_record is None - ): - owner_transport, owner_session_record = ( - _capture_gateway_steer_authority(owner_session_id) - ) - _raw_depth = getattr(child, "_delegate_depth", 1) - _tui_depth = max(0, _raw_depth - 1) if isinstance(_raw_depth, int) else 0 - _parent_sid = getattr(child, "_parent_subagent_id", None) - # Owning conversation's durable session id (same lineage completion - # delivery routes by); sourced from the child's stamp so it survives a - # parent_agent rebuild between dispatch and run. - _owner_agent_session_id = ( - str(getattr(child, "_parent_session_id", "") or "") - or str(getattr(parent_agent, "session_id", "") or "") - ) - _delegation_id = getattr(child, "_delegation_id", None) - _register_subagent( - { - "subagent_id": _subagent_id, - "parent_id": _parent_sid if isinstance(_parent_sid, str) else None, - "depth": _tui_depth, - "goal": goal, - "delegation_id": ( - _delegation_id if isinstance(_delegation_id, str) else None - ), - "model": ( - getattr(child, "model", None) - if isinstance(getattr(child, "model", None), str) - else None - ), - "started_at": time.time(), - "status": "running", - "tool_count": 0, - "agent": child, - # list/steer/stop ownership when the weakref chain breaks - # (CLI rebuilds its AIAgent mid-session). - "owner_agent_session_id": _owner_agent_session_id or None, - # Immutable live gateway/TUI session that commissioned this - # child. Empty outside those hosts; RPC authority fails closed. - "owner_session_id": owner_session_id, - "owner_transport": owner_transport, - "owner_session_record": owner_session_record, - } - ) + _subagent_id = getattr(child, "_subagent_id", None) + if not isinstance(_subagent_id, str) or not _subagent_id: + return None + if owner_session_id is None: + try: + from gateway.session_context import get_session_env + owner_session_id = get_session_env("HERMES_UI_SESSION_ID", "") or None + except Exception: + owner_session_id = None + if owner_session_id and (owner_transport is None or owner_session_record is None): + owner_transport, owner_session_record = _capture_gateway_steer_authority(owner_session_id) + _raw_depth = getattr(child, "_delegate_depth", 1) + _parent_sid = getattr(child, "_parent_subagent_id", None) + _delegation_id = getattr(child, "_delegation_id", None) + _model = getattr(child, "model", None) + _register_subagent( + { + "subagent_id": _subagent_id, + "parent_id": _parent_sid if isinstance(_parent_sid, str) else None, + "depth": max(0, _raw_depth - 1) if isinstance(_raw_depth, int) else 0, + "goal": goal, + "delegation_id": _delegation_id if isinstance(_delegation_id, str) else None, + "model": _model if isinstance(_model, str) else None, + "started_at": time.time(), + "status": "running", + "tool_count": 0, + "agent": child, + # Owning conversation's durable session id (same lineage completion + # delivery routes by), sourced from the child's stamp so it survives + # a parent_agent rebuild between dispatch and run; used for + # list/steer/stop ownership when the weakref chain breaks. + "owner_agent_session_id": ( + str(getattr(child, "_parent_session_id", "") or "") + or str(getattr(parent_agent, "session_id", "") or "") + or None + ), + # Immutable live gateway/TUI session that commissioned this child. + # Empty outside those hosts; RPC authority fails closed. + "owner_session_id": owner_session_id, + "owner_transport": owner_transport, + "owner_session_record": owner_session_record, + } + ) return _subagent_id @@ -380,15 +402,13 @@ class _WorktreeReporter: def attach(self, entry_dict: Dict[str, Any]) -> None: """Inspect + prune the child worktree, reporting into the entry.""" - _worktree_info = self.info - if _worktree_info is None: + info = self.info + if info is None: return try: from tools import subagent_worktree - entry_dict["worktree"] = ( - subagent_worktree.finalize_subagent_worktree(_worktree_info) - ) + entry_dict["worktree"] = subagent_worktree.finalize_subagent_worktree(info) except Exception as e: # State is unknown: emit the SAME flagged schema the parent expects, # via the shared factory so the two producers never drift. @@ -396,15 +416,13 @@ class _WorktreeReporter: try: from tools import subagent_worktree as _sw - entry_dict["worktree"] = _sw.unproven_worktree_payload( - _worktree_info, f"finalize raised: {e}" - ) + entry_dict["worktree"] = _sw.unproven_worktree_payload(info, f"finalize raised: {e}") except Exception: # Import itself failed — inline the same shape rather than # dropping the flag (the parent must still see the warning). entry_dict["worktree"] = { - "path": _worktree_info.get("path", ""), - "branch": _worktree_info.get("branch", ""), + "path": info.get("path", ""), + "branch": info.get("branch", ""), "commits": 0, "dirty": False, "pruned": False, @@ -413,7 +431,7 @@ class _WorktreeReporter: f"worktree finalize raised ({e}) and the reporting " "helper was unavailable: 'commits' and 'dirty' are " "UNKNOWN, not zero/clean. Inspect " - f"{_worktree_info.get('path', '')} before assuming " + f"{info.get('path', '')} before assuming " "no work." ), } @@ -442,31 +460,24 @@ def _seed_child_workspace( worktree contract note when isolation engaged. """ from tools.delegate_tool import _get_worktree_isolation, _resolve_workspace_hint - - _subagent_id = subagent_id - _worktree_info = None import uuid as _uuid - child_task_id = _subagent_id or f"subagent-{task_index}-{_uuid.uuid4().hex[:8]}" + child_task_id = subagent_id or f"subagent-{task_index}-{_uuid.uuid4().hex[:8]}" parent_task_id = getattr(parent_agent, "_current_task_id", None) # Seed the child's cwd record from the parent's: same starting directory, - # but the child's later `cd`s stay in its own record. + # but the child's later `cd`s stay in its own record. Per-session container + # isolation keys containers by task_id; the child must share the PARENT's. try: - from tools.terminal_tool import ( - get_session_cwd, - record_session_cwd, - register_container_alias, - ) + from tools.terminal_tool import get_session_cwd, record_session_cwd, register_container_alias record_session_cwd(child_task_id, get_session_cwd(parent_task_id)) - # Per-session container isolation keys containers by task_id; the - # child must share the PARENT's container. register_container_alias(child_task_id, parent_task_id) except Exception as e: logger.debug("Child cwd seed failed: %s", e) # Opt-in worktree isolation: own git worktree off the parent's HEAD, terminal # started there. Git-only, local-backend-only; failures degrade silently. + _worktree_info = None if _get_worktree_isolation(): try: from tools import subagent_worktree @@ -481,12 +492,10 @@ def _seed_child_workspace( pass _worktree_info = subagent_worktree.create_subagent_worktree( _parent_cwd or _resolve_workspace_hint(parent_agent), - subagent_id=_subagent_id, + subagent_id=subagent_id, ) else: - logger.debug( - "worktree isolation skipped: non-local terminal backend" - ) + logger.debug("worktree isolation skipped: non-local terminal backend") except Exception as e: logger.debug("worktree isolation setup failed: %s", e) if _worktree_info is not None: @@ -503,12 +512,9 @@ def _seed_child_workspace( goal = goal + build_worktree_context_note(_worktree_info) - wall_start = time.time() - parent_reads_snapshot = ( - list(file_state.known_reads(parent_task_id)) if parent_task_id else [] - ) worktree.info = _worktree_info - return _ChildWorkspace(child_task_id, parent_task_id, goal, wall_start, parent_reads_snapshot) + parent_reads_snapshot = list(file_state.known_reads(parent_task_id)) if parent_task_id else [] + return _ChildWorkspace(child_task_id, parent_task_id, goal, time.time(), parent_reads_snapshot) @dataclass @@ -517,6 +523,43 @@ class _ChildFailure: close_deferred: bool +def _defer_close_after_timeout(child: Any, child_future: Any) -> None: + """Hand ``child.close()`` to a Future done-callback and drain its transports. + + The interrupt is cooperative: the worker still runs its finally path, so + closing the child now could close SQLite under its final write — the + done-callback is the first safe close boundary. The abandoned worker is + usually parked in an OpenSSL read; NEVER hard-close that transport from this + thread (cross-thread FD release under a live SSL read corrupts native + state) — shutdown() the pooled sockets instead, which settles the read with + EOF so the worker unwinds. One immediate sweep + one delayed re-sweep for a + connection opened in between; a worker that still won't settle keeps its + resources until process exit. + """ + child_future.add_done_callback( + lambda _done: _close_child(child, "Failed to close timed-out child after worker exit") + ) + _drain = getattr(child, "_drain_transports_after_abandonment", None) + if not callable(_drain): + return + + def _drain_once(phase: str) -> None: + try: + _drain(reason=f"delegate_timeout_{phase}") + except Exception: + logger.debug("Timed-out child transport drain (%s) failed", phase, exc_info=True) + + _drain_once("immediate") + + def _drain_resweep() -> None: + if not child_future.done(): + _drain_once("resweep") + + _resweep_timer = threading.Timer(5.0, _drain_resweep) + _resweep_timer.daemon = True + _resweep_timer.start() + + def _handle_child_wait_failure( exc: BaseException, *, @@ -538,43 +581,26 @@ def _handle_child_wait_failure( ``close_deferred=True``) because closing from this thread races the still-unwinding worker's finally path. """ - _timeout_exc = exc - _subagent_id = subagent_id - _child_future = child_future - _worker_thread_holder = worker_thread_holder - _attach_worktree = worktree.attach - _child_close_deferred = False - # No consumer boundary remains once this owner stops waiting for - # the child. Close acceptance before any completion callback and - # retain steer text that won the race with this failure/timeout. - _late_pending_steer = ( - _close_subagent_steering(_subagent_id, child) if _subagent_id else None - ) - # Signal the child to stop so its thread can exit cleanly. - try: - interrupted = child is not None and request_hard_interrupt(child) - if not interrupted and child is not None and hasattr(child, "_interrupt_requested"): - child._interrupt_requested = True - except Exception: - pass + # No consumer boundary remains once this owner stops waiting for the + # child. Close acceptance before any completion callback and retain steer + # text that won the race with this failure/timeout. + _late_pending_steer = _close_subagent_steering(subagent_id, child) if subagent_id else None + _signal_child_stop(child) - is_timeout = isinstance(_timeout_exc, (FuturesTimeoutError, TimeoutError)) + is_timeout = isinstance(exc, (FuturesTimeoutError, TimeoutError)) duration = round(time.monotonic() - child_start, 2) logger.warning( "Subagent %d %s after %.1fs", task_index, - "timed out" if is_timeout else f"raised {type(_timeout_exc).__name__}", + "timed out" if is_timeout else f"raised {type(exc).__name__}", duration, ) - # When a subagent times out BEFORE making any API call, dump a - # diagnostic to help users (and us) see what the child was doing. - # See #14726 — without this, 0-API-call hangs are black boxes. + # A timeout BEFORE any API call is a black box without a diagnostic dump. diagnostic_path: Optional[str] = None child_api_calls = 0 try: - _summary = child.get_activity_summary() - child_api_calls = int(_summary.get("api_call_count", 0) or 0) + child_api_calls = int(child.get_activity_summary().get("api_call_count", 0) or 0) except Exception: pass if is_timeout and child_api_calls == 0: @@ -585,7 +611,7 @@ def _handle_child_wait_failure( # never raises FuturesTimeoutError); guard for the type checker. timeout_seconds=float(child_timeout or 0.0), duration_seconds=float(duration), - worker_thread=_worker_thread_holder.get("t"), + worker_thread=worker_thread_holder.get("t"), goal=goal, ) if diagnostic_path: @@ -595,116 +621,54 @@ def _handle_child_wait_failure( diagnostic_path, ) - if child_progress_cb: - try: - child_progress_cb( - "subagent.complete", - preview=( - f"Timed out after {duration}s" - if is_timeout - else str(_timeout_exc) - ), - status="timeout" if is_timeout else "error", - duration_seconds=duration, - summary="", - ) - except Exception: - pass + status = "timeout" if is_timeout else "error" + _safe_progress( + child_progress_cb, + "subagent.complete", + preview=f"Timed out after {duration}s" if is_timeout else str(exc), + status=status, + duration_seconds=duration, + summary="", + ) - if is_timeout: - if child_api_calls == 0: - _err = ( - f"Subagent timed out after {child_timeout}s without " - f"making any API call — the child never reached its " - f"first LLM request (prompt construction, credential " - f"resolution, or transport may be stuck)." - ) - if diagnostic_path: - _err += f" Diagnostic: {diagnostic_path}" - else: - _err = ( - f"Subagent timed out after {child_timeout}s with " - f"{child_api_calls} API call(s) completed — likely " - f"stuck on a slow API call, tool call, or unresponsive " - f"network request." - ) - if diagnostic_path: - _err += f" Diagnostic: {diagnostic_path}" + if not is_timeout: + _err = str(exc) + elif child_api_calls == 0: + _err = ( + f"Subagent timed out after {child_timeout}s without " + f"making any API call — the child never reached its " + f"first LLM request (prompt construction, credential " + f"resolution, or transport may be stuck)." + ) else: - _err = str(_timeout_exc) + _err = ( + f"Subagent timed out after {child_timeout}s with " + f"{child_api_calls} API call(s) completed — likely " + f"stuck on a slow API call, tool call, or unresponsive " + f"network request." + ) + if is_timeout and diagnostic_path: + _err += f" Diagnostic: {diagnostic_path}" - _error_entry = { - "task_index": task_index, - "status": "timeout" if is_timeout else "error", - "summary": None, - "error": _err, - "exit_reason": "timeout" if is_timeout else "error", - "api_calls": child_api_calls, - "duration_seconds": duration, - "timeout_seconds": child_timeout if is_timeout else None, - "timed_out_after_seconds": duration if is_timeout else None, - "timeout_phase": ( + _error_entry = _fabricated_entry(task_index, status, _err, child, duration) + _error_entry.update( + exit_reason=status, + api_calls=child_api_calls, + timeout_seconds=child_timeout if is_timeout else None, + timed_out_after_seconds=duration if is_timeout else None, + timeout_phase=( "before_first_llm_call" if is_timeout and child_api_calls == 0 else "after_llm_calls" if is_timeout else None ), - "_child_role": getattr(child, "_delegate_role", None), - "diagnostic_path": diagnostic_path, - } - if _late_pending_steer: - _error_entry["missed_steer"] = _late_pending_steer - _error_entry["error"] += ( - " [steer did not land before the subagent stopped: " - f"{_late_pending_steer}]" - ) - _attach_worktree(_error_entry) - if is_timeout and not _child_future.done(): - # The interrupt is cooperative: the worker still runs its finally path, - # so closing the child now could close SQLite under its final write. - # A Future done-callback is the first safe close boundary. - def _close_after_timed_out_worker(_done_future) -> None: - try: - close = getattr(child, "close", None) - if callable(close): - close() - except Exception: - logger.debug( - "Failed to close timed-out child after worker exit", - exc_info=True, - ) - - _child_future.add_done_callback(_close_after_timed_out_worker) - _child_close_deferred = True - - # The abandoned worker is usually parked in an OpenSSL read. NEVER - # hard-close that transport from this thread (cross-thread FD release - # under a live SSL read corrupts native state); shutdown() the pooled - # sockets instead — FD-safe, settles the read with EOF so the worker - # unwinds. One immediate sweep + one delayed re-sweep for a connection - # opened in between; a worker that still won't settle keeps its - # resources until process exit. - _drain = getattr(child, "_drain_transports_after_abandonment", None) - if callable(_drain): - def _drain_once(phase: str) -> None: - try: - _drain(reason=f"delegate_timeout_{phase}") - except Exception: - logger.debug( - "Timed-out child transport drain (%s) failed", - phase, - exc_info=True, - ) - - _drain_once("immediate") - - def _drain_resweep() -> None: - if not _child_future.done(): - _drain_once("resweep") - - _resweep_timer = threading.Timer(5.0, _drain_resweep) - _resweep_timer.daemon = True - _resweep_timer.start() - return _ChildFailure(_error_entry, _child_close_deferred) + diagnostic_path=diagnostic_path, + ) + _append_missed_steer(_error_entry, _late_pending_steer) + worktree.attach(_error_entry) + close_deferred = is_timeout and not child_future.done() + if close_deferred: + _defer_close_after_timeout(child, child_future) + return _ChildFailure(_error_entry, close_deferred) @dataclass @@ -723,66 +687,77 @@ def _validate_child_output_schema( Schema-less children (no dict on ``child._delegate_output_schema``) take no branch here so their result entry stays byte-identical. """ - _relay_child_text = relay_child_text _output_schema = getattr(child, "_delegate_output_schema", None) - _schema_valid: Optional[bool] = None - _schema_errors: List[str] = [] - _schema_retries = 0 - if isinstance(_output_schema, dict): - from tools.delegation_output_schema import ( - build_retry_message, - validate_output, - ) + if not isinstance(_output_schema, dict): + return _SchemaOutcome(_output_schema, None, [], 0) + from tools.delegation_output_schema import build_retry_message, validate_output - _first_text = result.get("final_response") or "" - _schema_valid, _schema_errors = validate_output( - _first_text, _output_schema - ) - if ( - not _schema_valid - and _first_text.strip() - and not result.get("interrupted", False) - ): - # Exactly one retry turn, carrying the validation errors - # verbatim (no schema re-paste — the child already holds - # the contract in its context). - _schema_retries = 1 - _retry_result = None - try: - _retry_result = child.run_conversation( - user_message=build_retry_message(_schema_errors), - task_id=child_task_id, - stream_callback=_relay_child_text, - ) - except Exception as _retry_exc: - logger.warning( - "Subagent %d schema-retry turn failed: %s", - task_index, - _retry_exc, - ) - if isinstance(_retry_result, dict): - _retry_text = _retry_result.get("final_response") or "" - if _retry_text.strip(): - result["final_response"] = _retry_text - try: - result["api_calls"] = int( - result.get("api_calls", 0) or 0 - ) + int(_retry_result.get("api_calls", 0) or 0) - except (TypeError, ValueError): - pass - _retry_messages = _retry_result.get("messages") - if isinstance(_retry_messages, list) and isinstance( - result.get("messages"), list - ): - result["messages"] = result["messages"] + _retry_messages - _schema_valid, _schema_errors = validate_output( - _retry_text, _output_schema - ) + _first_text = result.get("final_response") or "" + _schema_valid, _schema_errors = validate_output(_first_text, _output_schema) + if _schema_valid or not _first_text.strip() or result.get("interrupted", False): + return _SchemaOutcome(_output_schema, _schema_valid, _schema_errors, 0) - # Linearization boundary for registry steering. From this point on the - # child cannot consume another steer. Closing under the registry lock - # either rejects a concurrent caller or drains every previously accepted - return _SchemaOutcome(_output_schema, _schema_valid, _schema_errors, _schema_retries) + # Exactly one retry turn, carrying the validation errors verbatim (no + # schema re-paste — the child already holds the contract in its context). + _retry_result = None + try: + _retry_result = child.run_conversation( + user_message=build_retry_message(_schema_errors), + task_id=child_task_id, + stream_callback=relay_child_text, + ) + except Exception as _retry_exc: + logger.warning("Subagent %d schema-retry turn failed: %s", task_index, _retry_exc) + if isinstance(_retry_result, dict): + _retry_text = _retry_result.get("final_response") or "" + if _retry_text.strip(): + result["final_response"] = _retry_text + try: + result["api_calls"] = int(result.get("api_calls", 0) or 0) + int(_retry_result.get("api_calls", 0) or 0) + except (TypeError, ValueError): + pass + _retry_messages = _retry_result.get("messages") + if isinstance(_retry_messages, list) and isinstance(result.get("messages"), list): + result["messages"] = result["messages"] + _retry_messages + _schema_valid, _schema_errors = validate_output(_retry_text, _output_schema) + return _SchemaOutcome(_output_schema, _schema_valid, _schema_errors, 1) + + +def _build_tool_trace(messages: Any) -> list[Dict[str, Any]]: + """Tool trace from the child's conversation messages, pairing parallel + tool calls with their results by tool_call_id.""" + tool_trace: list[Dict[str, Any]] = [] + trace_by_id: Dict[str, Dict[str, Any]] = {} + if not isinstance(messages, list): + return tool_trace + for msg in messages: + if not isinstance(msg, dict): + continue + if msg.get("role") == "assistant": + for tc in msg.get("tool_calls") or []: + fn = tc.get("function", {}) + arguments = fn.get("arguments", "") + entry_t = { + "tool": fn.get("name", "unknown"), + "args_bytes": len(arguments), + "input_summary": _summarize_tool_arguments(arguments), + } + tool_trace.append(entry_t) + if tc.get("id"): + trace_by_id[tc["id"]] = entry_t + elif msg.get("role") == "tool": + content = _stringify_tool_content(msg.get("content", "")) + result_meta = { + "result_bytes": len(content), + "status": "error" if _looks_like_error_output(content) else "ok", + } + tc_id = msg.get("tool_call_id") + target = trace_by_id.get(tc_id) if tc_id else None + if target is not None: + target.update(result_meta) + elif tool_trace: + tool_trace[-1].update(result_meta) # no tool_call_id: pair with the latest call + return tool_trace def _build_result_entry( @@ -798,102 +773,39 @@ def _build_result_entry( ``_run_single_child`` docstring; a structured failure always wins over the summary-presence heuristic (which is only a fallback for legacy/mock results). """ - _output_schema, _schema_valid, _schema_errors, _schema_retries = ( - schema.schema, schema.valid, schema.errors, schema.retries - ) summary = result.get("final_response") or "" - completed = result.get("completed", False) interrupted = result.get("interrupted", False) - api_calls = result.get("api_calls", 0) - + structured_failure = bool(result.get("failed") or result.get("error")) # "(empty)" is run_agent's give-up sentinel after repeated empty LLM # responses (usually a transport bug) — a failure, not a success. _empty_sentinel = summary.strip() == "(empty)" + usable_summary = bool(summary) and not _empty_sentinel if interrupted: - status = "interrupted" - elif result.get("failed") or result.get("error"): - # A structured failure WINS over the summary heuristic: the loop returns - # the error text as final_response, which would otherwise read as - # "completed". The heuristic only covers legacy/mock results. - status = "failed" - elif _schema_valid is False: - # Declared schema still violated after the bounded retry: the summary - # is unusable under the contract, so status must not say completed - # (orchestrators reading only status/icon would accept an empty - # verdict). None on schema-less runs, which never take this branch. - status = "failed" - elif summary and not _empty_sentinel: - # A summary means the subagent produced usable output. - # exit_reason ("completed" vs "max_iterations") already - # tells the parent *how* the task ended. - status = "completed" + status, exit_reason = "interrupted", "interrupted" + elif structured_failure: + # The loop returns the error text as final_response, which would + # otherwise read as "completed". Never report a provider rejection as + # "max_iterations" — that is only truthful for real budget exhaustion. + status, exit_reason = "failed", "error" else: - status = "failed" + # exit_reason ("completed" vs "max_iterations") tells the parent HOW + # the task ended; completed=False with no failure = budget exhaustion. + exit_reason = "completed" if result.get("completed", False) else "max_iterations" + # A declared schema still violated after the bounded retry makes the + # summary unusable under the contract, so status must not say completed + # (orchestrators reading only status/icon would accept an empty verdict). + status = "completed" if schema.valid is not False and usable_summary else "failed" - # Build tool trace from conversation messages (already in memory). - # Uses tool_call_id to correctly pair parallel tool calls with results. - tool_trace: list[Dict[str, Any]] = [] - trace_by_id: Dict[str, Dict[str, Any]] = {} - messages = result.get("messages") or [] - if isinstance(messages, list): - for msg in messages: - if not isinstance(msg, dict): - continue - if msg.get("role") == "assistant": - for tc in msg.get("tool_calls") or []: - fn = tc.get("function", {}) - arguments = fn.get("arguments", "") - entry_t = { - "tool": fn.get("name", "unknown"), - "args_bytes": len(arguments), - "input_summary": _summarize_tool_arguments(arguments), - } - tool_trace.append(entry_t) - tc_id = tc.get("id") - if tc_id: - trace_by_id[tc_id] = entry_t - elif msg.get("role") == "tool": - content = _stringify_tool_content(msg.get("content", "")) - is_error = _looks_like_error_output(content) - result_meta = { - "result_bytes": len(content), - "status": "error" if is_error else "ok", - } - # Match by tool_call_id for parallel calls - tc_id = msg.get("tool_call_id") - target = trace_by_id.get(tc_id) if tc_id else None - if target is not None: - target.update(result_meta) - elif tool_trace: - # Fallback for messages without tool_call_id - tool_trace[-1].update(result_meta) - - # Determine exit reason - if interrupted: - exit_reason = "interrupted" - elif result.get("failed") or result.get("error"): - # Provider rejection / terminal failure. Do NOT report this as - # iteration-budget exhaustion — "max_iterations" is only truthful - # when the child actually hit its per-delegation iteration cap. - exit_reason = "error" - elif completed: - exit_reason = "completed" - else: - # Genuine budget exhaustion: completed=False with no failure. - exit_reason = "max_iterations" - - # Extract token counts (safe for mock objects) - _input_tokens = getattr(child, "session_prompt_tokens", 0) - _output_tokens = getattr(child, "session_completion_tokens", 0) _model = getattr(child, "model", None) - + _cost = getattr(child, "session_estimated_cost_usd", 0.0) + _cost_status = getattr(child, "session_cost_status", None) # Result entry contract: see the _run_single_child docstring. entry: Dict[str, Any] = { "task_index": task_index, "status": status, "summary": summary, - "api_calls": api_calls, + "api_calls": result.get("api_calls", 0), "duration_seconds": duration, "model": _model if isinstance(_model, str) else None, "exit_reason": exit_reason, @@ -901,70 +813,47 @@ def _build_result_entry( # "completed"), so the parent needs this explicit flag. "truncated": exit_reason == "max_iterations", "tokens": { - "input": ( - _input_tokens if isinstance(_input_tokens, (int, float)) else 0 - ), - "output": ( - _output_tokens if isinstance(_output_tokens, (int, float)) else 0 - ), + "input": _num(getattr(child, "session_prompt_tokens", 0)), + "output": _num(getattr(child, "session_completion_tokens", 0)), }, - "tool_trace": tool_trace, - # Captured before the finally block calls child.close() so the - # parent thread can fire subagent_stop with the correct role. - # Stripped before the dict is serialised back to the model. + "tool_trace": _build_tool_trace(result.get("messages") or []), + # Captured before the finally block calls child.close() so the parent + # thread can fire subagent_stop with the correct role; stripped before + # the dict is serialised back to the model (as is _child_cost_usd, + # folded into the parent's session cost by the aggregator). "_child_role": getattr(child, "_delegate_role", None), - # Folded into the parent's session cost by the aggregator; stripped - # before serialisation back to the model. - "_child_cost_usd": ( - float(getattr(child, "session_estimated_cost_usd", 0.0) or 0.0) - if isinstance( - getattr(child, "session_estimated_cost_usd", 0.0), - (int, float), - ) - else 0.0 - ), + "_child_cost_usd": float(_cost or 0.0) if isinstance(_cost, (int, float)) else 0.0, } # Model-visible per-delegation spend (unlike _child_cost_usd above). entry["cost_usd"] = round(entry["_child_cost_usd"], 6) - _cost_status = getattr(child, "session_cost_status", None) - entry["cost_status"] = ( - _cost_status if isinstance(_cost_status, str) and _cost_status - else "unknown" - ) + entry["cost_status"] = _cost_status if isinstance(_cost_status, str) and _cost_status else "unknown" if status == "failed": - if _schema_valid is False and summary and not _empty_sentinel: + if schema.valid is False and usable_summary: # The child DID respond; name the contract violation instead of # the generic "no response" error. entry["error"] = ( - "Final answer does not satisfy the declared " - "output_schema (after 1 retry)." - if _schema_retries - else "Final answer does not satisfy the declared " - "output_schema." + "Final answer does not satisfy the declared output_schema" + + (" (after 1 retry)." if schema.retries else ".") ) else: - entry["error"] = result.get( - "error", "Subagent did not produce a response." - ) - # Classified reason from the child loop (e.g. "rate_limit", - # "billing", "server_error") — lets the parent distinguish a - # quota wall from a real task error without parsing prose. + entry["error"] = result.get("error", "Subagent did not produce a response.") + # Classified reason from the child loop (e.g. "rate_limit", "billing") + # lets the parent tell a quota wall from a task error without parsing prose. _failure_reason = result.get("failure_reason") if isinstance(_failure_reason, str) and _failure_reason: entry["failure_reason"] = _failure_reason - # T1-24: schema-validation outcome — emitted ONLY when a schema was - # requested, so legacy (schema-less) payloads keep their exact shape. - if isinstance(_output_schema, dict): - entry["schema_valid"] = bool(_schema_valid) - if _schema_retries: - entry["schema_retries"] = _schema_retries - if not _schema_valid and _schema_errors: - entry["schema_errors"] = _schema_errors + # Schema-validation outcome — emitted ONLY when a schema was requested, so + # legacy (schema-less) payloads keep their exact shape. + if isinstance(schema.schema, dict): + entry["schema_valid"] = bool(schema.valid) + if schema.retries: + entry["schema_retries"] = schema.retries + if not schema.valid and schema.errors: + entry["schema_errors"] = schema.errors # A steer queued after the final assistant turn had no tool batch to land - # in; the finalizer hands it back as "pending_steer". Name it so the parent - # sees it was MISSED rather than silently absorbed. + # in; name it so the parent sees it was MISSED rather than silently absorbed. _missed_steer = result.get("pending_steer") if isinstance(_missed_steer, str) and _missed_steer.strip(): entry["missed_steer"] = _missed_steer @@ -982,34 +871,24 @@ def _append_sibling_write_reminder(entry: Dict[str, Any], ws: _ChildWorkspace) - Checks writes by ANY non-parent task_id (not just this child's) so nested orchestrator→worker chains are covered too. """ - parent_task_id, wall_start, parent_reads_snapshot = ( - ws.parent_task_id, ws.wall_start, ws.parent_reads_snapshot - ) + if not (ws.parent_task_id and ws.parent_reads_snapshot): + return try: - if parent_task_id and parent_reads_snapshot: - sibling_writes = file_state.writes_since( - parent_task_id, wall_start, parent_reads_snapshot - ) - if sibling_writes: - mod_paths = sorted( - {p for paths in sibling_writes.values() for p in paths} - ) - if mod_paths: - reminder = ( - "\n\n[NOTE: subagent modified files the parent " - "previously read — re-read before editing: " - + ", ".join(mod_paths[:8]) - + ( - f" (+{len(mod_paths) - 8} more)" - if len(mod_paths) > 8 - else "" - ) - + "]" - ) - if entry.get("summary"): - entry["summary"] = entry["summary"] + reminder - else: - entry["stale_paths"] = mod_paths + sibling_writes = file_state.writes_since(ws.parent_task_id, ws.wall_start, ws.parent_reads_snapshot) + mod_paths = sorted({p for paths in sibling_writes.values() for p in paths}) if sibling_writes else [] + if not mod_paths: + return + reminder = ( + "\n\n[NOTE: subagent modified files the parent " + "previously read — re-read before editing: " + + ", ".join(mod_paths[:8]) + + (f" (+{len(mod_paths) - 8} more)" if len(mod_paths) > 8 else "") + + "]" + ) + if entry.get("summary"): + entry["summary"] = entry["summary"] + reminder + else: + entry["stale_paths"] = mod_paths except Exception: logger.debug("file_state sibling-write check failed", exc_info=True) @@ -1029,65 +908,39 @@ def _emit_child_complete( """ if not child_progress_cb: return - summary, status, api_calls = entry["summary"], entry["status"], entry["api_calls"] - _input_tokens = getattr(child, "session_prompt_tokens", 0) - _output_tokens = getattr(child, "session_completion_tokens", 0) - child_task_id, wall_start = ws.child_task_id, ws.wall_start - _cost_usd = getattr(child, "session_estimated_cost_usd", None) - _reasoning_tokens = getattr(child, "session_reasoning_tokens", 0) + summary, status = entry["summary"], entry["status"] try: - _files_read = list(file_state.known_reads(child_task_id))[:40] + _files_read = list(file_state.known_reads(ws.child_task_id))[:40] except Exception: _files_read = [] try: - _files_written_map = file_state.writes_since( - "", wall_start, [] - ) # all writes since wall_start + _files_written_map = file_state.writes_since("", ws.wall_start, []) # all writes since wall_start except Exception: _files_written_map = {} _files_written = sorted( - { - p - for tid, paths in _files_written_map.items() - if tid == child_task_id - for p in paths - } + {p for tid, paths in _files_written_map.items() if tid == ws.child_task_id for p in paths} )[:40] - _output_tail = _extract_output_tail(result, max_entries=8, max_chars=600) - complete_kwargs: Dict[str, Any] = { "preview": summary[:160] if summary else entry.get("error", ""), "status": status, "duration_seconds": duration, "summary": summary[:500] if summary else entry.get("error", ""), - "input_tokens": ( - int(_input_tokens) if isinstance(_input_tokens, (int, float)) else 0 - ), - "output_tokens": ( - int(_output_tokens) if isinstance(_output_tokens, (int, float)) else 0 - ), - "reasoning_tokens": ( - int(_reasoning_tokens) - if isinstance(_reasoning_tokens, (int, float)) - else 0 - ), - "api_calls": int(api_calls) if isinstance(api_calls, (int, float)) else 0, + "input_tokens": _num(getattr(child, "session_prompt_tokens", 0)), + "output_tokens": _num(getattr(child, "session_completion_tokens", 0)), + "reasoning_tokens": _num(getattr(child, "session_reasoning_tokens", 0)), + "api_calls": _num(entry["api_calls"]), "files_read": _files_read, "files_written": _files_written, - "output_tail": _output_tail, + "output_tail": _extract_output_tail(result, max_entries=8, max_chars=600), } + _cost_usd = getattr(child, "session_estimated_cost_usd", None) if _cost_usd is not None: try: complete_kwargs["cost_usd"] = float(_cost_usd) except (TypeError, ValueError): pass - - if child_progress_cb: - try: - child_progress_cb("subagent.complete", **complete_kwargs) - except Exception as e: - logger.debug("Progress callback completion failed: %s", e) + _safe_progress(child_progress_cb, "subagent.complete", **complete_kwargs) def _cleanup_child_run( @@ -1108,16 +961,13 @@ def _cleanup_child_run( owns it) → pop the child's Relay scope if no turn is active. """ _heartbeat_stop, _heartbeat_thread = heartbeat - _subagent_id = subagent_id - _child_close_deferred = close_deferred _heartbeat_stop.set() if _heartbeat_thread.ident is not None: _heartbeat_thread.join(timeout=5) - # Drop the TUI-facing registry entry. Safe to call even if the - # child was never registered (e.g. ID missing on test doubles). - if _subagent_id: - _unregister_subagent(_subagent_id, agent=child) + # Safe even if the child was never registered (ID missing on test doubles). + if subagent_id: + _unregister_subagent(subagent_id, agent=child) if child_pool is not None and leased_cred_id is not None: try: @@ -1125,38 +975,20 @@ def _cleanup_child_run( except Exception as exc: logger.debug("Failed to release credential lease: %s", exc) - # Restore the parent's tool names so the process-global is correct - # for any subsequent execute_code calls or other consumers. + # Restore the parent's tool names so the process-global is correct for + # any subsequent execute_code calls or other consumers. import model_tools saved_tool_names = getattr(child, "_delegate_saved_tool_names", None) if isinstance(saved_tool_names, list): model_tools._last_resolved_tool_names = list(saved_tool_names) - # Remove child from active tracking + _detach_child(parent_agent, child) - # Unregister child from interrupt propagation - if hasattr(parent_agent, "_active_children"): - try: - lock = getattr(parent_agent, "_active_children_lock", None) - if lock: - with lock: - parent_agent._active_children.remove(child) - else: - parent_agent._active_children.remove(child) - except (ValueError, UnboundLocalError) as e: - logger.debug("Could not remove child from active_children: %s", e) - - # Close tool resources (terminal sandboxes, browser daemons, - # background processes, httpx clients) so subagent subprocesses - # don't outlive the delegation. - if not _child_close_deferred: - try: - close = getattr(child, "close", None) - if callable(close): - close() - except Exception: - logger.debug("Failed to close child agent after delegation") + # Close tool resources (terminal sandboxes, browser daemons, background + # processes, httpx clients) so subagent subprocesses don't outlive the delegation. + if not close_deferred: + _close_child(child, "Failed to close child agent after delegation") # The AIAgent turn boundary normally closes the child scope itself. This # fallback covers failures before that boundary starts, but must not pop @@ -1174,4 +1006,3 @@ def _cleanup_child_run( runtime.unregister_subagent({"child_session_id": child_session_id}) except Exception: logger.debug("Failed to close child Relay session after delegation") - From 4711e8105d8434c6e732c6cbf8344c68a06f4cd7 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:37:47 -0700 Subject: [PATCH 04/11] =?UTF-8?q?refactor(delegate):=20child=5Frun=20dedup?= =?UTF-8?q?e=20=E2=80=94=20shared=20close/attach/detach/stop=20helpers,=20?= =?UTF-8?q?=5Fdefer=5Fclose=5Fafter=5Ftimeout,=20=5Fbuild=5Ftool=5Ftrace,?= =?UTF-8?q?=20=5Fnum;=20single=20=5Ffabricated=5Fentry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mock._session_db.db_path/139369483040144 | Bin 0 -> 237568 bytes .../139369483040144.fts_rebuild.lock | 0 .../139369483040144.quarantine.lock | 0 .../mock._session_db.db_path/139369502342928 | Bin 0 -> 237568 bytes .../139369502342928.fts_rebuild.lock | 0 .../139369502342928.quarantine.lock | 0 tools/delegate_tool_child_run.py | 31 ++++++++++-------- tools/delegate_tool_dispatch.py | 14 +------- 8 files changed, 18 insertions(+), 27 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/139369483040144 create mode 100644 MagicMock/mock._session_db.db_path/139369483040144.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/139369483040144.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/139369502342928 create mode 100644 MagicMock/mock._session_db.db_path/139369502342928.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/139369502342928.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/139369483040144 b/MagicMock/mock._session_db.db_path/139369483040144 new file mode 100644 index 0000000000000000000000000000000000000000..522c23eb0ddfbfc556287e166f902dab0d29fd4b GIT binary patch literal 237568 zcmeI4-)|dNcE?G}7G*lNlHFvv*+iRhvI)sG9b1we+i{dEEsYhzGHFv(9AmKYB#&$;K^p`!J>Yr4y%Ez54JuC$nXJaz0?>N}E@N~Mm`pI7Nm z__aXa91kDp-*ou>rGNe>HT-_y-(#tl|Lh-5P~+6>r@ZTx+279o_w1*~pPTyC)Q3|a z4oKq>1pZ$VkWWtM?k}cOx~Z`T&N~K$q@s3R%X?NF<~X`#Ds4++hSGJ^7E|VjG-mH) zrgP`crSH4yron<~9QIC^na#n+ndQ1%Zpc!jd}B?P24oAS+GZshS^Uv^)0y1dT>8g% zy*b-t32Ar2e>1UJ!d9t}mFP>?q)N3RugZ1lPQ7xwT)!{flJ869jYh3frGdBQYNO;y zhHIe_4f*YcRISmUjkPtYF5i^va&=i=mjW55pld~clx-O-F7LNDEz@PD>vj1pu4NfY zQ#A}F&@j;K49fEL3vFy`i#1(E)18jx=q~Mr(CO;5ZdYx0$lCH+WP7M$hnY&#>XJPH z48LPbH+5%Qv6i&KHl)7 z%8x}_mlu=HiC6@Lt^Ek_{8?~+e+iD&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*^p3%gcoa;Yv$^;&stO|D5{^NG5G65?}w`$cplH(FmrOjN`)5O;>m_j!+lcJhuvJLSsi2RC2$V)~CR92C>K=`h<3$sZ-A{SlHM z)4`r5Vl`<~6eqmv3lt}TIe$oT@+ti5t74!)*=vt{=goKr~+zUm0a=LeKv`xD9aOkqB{n`<1A+dbHVJ&_}&{^M}mpU!eniuU6yNiR=PF>67-gx6+ zYN|_lcu3Z#oUdLzf{k2mG^{PdYU~8O%&VE)<;yegr$_P{W=LSdTjg4Pv$QVNJ!cvw zC~a<(D{B&^$;$=rzz)j|@1cL9_8+|ybzYQR9`2=%-N?t}6fYK+^STzayVedf$@`Y` zLDiJc7JH>DnP--lXC6JftFygfCMz`YsP<^x^8KM{laHmk!m~a|fZR=ZMmQ{MdSkpY zBvkIT_~|d6Qa-$MIrH4o+{}+Rhh>waSBAdir>qFSAhjTBy?F8Y8EU;)jrXZ)yD*de zKE)m7G+tbfDntuoOspSlE&J7(H7uTjvqSL<*)TZ6L-?Q@mp>w?&Q|IE!EaoHH>qT0 z%emkd6J4u5gJ*}gc-v zz`y_ZhrD~R9RxrC1V8`;KmY_l00ck)1V8`;eqRFk_y2xhf*211AOHd&00JNY0w4ea wAOHd&00Lip0{Hj;zW93t3qb$`KmY_l00ck)1V8`;KmY_l;Ij}A|NX!J1)3e;6#xJL literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/139369502342928.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/139369502342928.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139369502342928.quarantine.lock b/MagicMock/mock._session_db.db_path/139369502342928.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index a7d0030186..ca9e2307dc 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -32,17 +32,15 @@ def _num(value: Any, default: int = 0) -> int: return int(value) if isinstance(value, (int, float)) else default -def _fabricated_entry( - idx: int, status: str, error: str, child: Any, duration: float = 0 -) -> Dict[str, Any]: - """Result entry for a child that raised / never finished / was abandoned.""" +def _fabricated_entry(idx: int, status: str, error: str, child: Any) -> Dict[str, Any]: + """Result entry for a child whose Future raised or never finished.""" return { "task_index": idx, "status": status, "summary": None, "error": error, "api_calls": 0, - "duration_seconds": duration, + "duration_seconds": 0, "_child_role": getattr(child, "_delegate_role", None), } @@ -650,19 +648,24 @@ def _handle_child_wait_failure( if is_timeout and diagnostic_path: _err += f" Diagnostic: {diagnostic_path}" - _error_entry = _fabricated_entry(task_index, status, _err, child, duration) - _error_entry.update( - exit_reason=status, - api_calls=child_api_calls, - timeout_seconds=child_timeout if is_timeout else None, - timed_out_after_seconds=duration if is_timeout else None, - timeout_phase=( + _error_entry = { + "task_index": task_index, + "status": status, + "summary": None, + "error": _err, + "exit_reason": status, + "api_calls": child_api_calls, + "duration_seconds": duration, + "timeout_seconds": child_timeout if is_timeout else None, + "timed_out_after_seconds": duration if is_timeout else None, + "timeout_phase": ( "before_first_llm_call" if is_timeout and child_api_calls == 0 else "after_llm_calls" if is_timeout else None ), - diagnostic_path=diagnostic_path, - ) + "_child_role": getattr(child, "_delegate_role", None), + "diagnostic_path": diagnostic_path, + } _append_missed_steer(_error_entry, _late_pending_steer) worktree.attach(_error_entry) close_deferred = is_timeout and not child_future.done() diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index ef8a3c4edf..0aa6b738f7 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -13,6 +13,7 @@ from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait from typing import Any, Dict, List, Optional from agent.interrupt_compat import request_hard_interrupt +from tools.delegate_tool_child_run import _fabricated_entry from tools.delegate_tool_progress import ( SUBAGENT_FAILURE_STATUSES, _clean_error_text, @@ -24,19 +25,6 @@ from tools.delegate_tool_progress import ( logger = logging.getLogger("tools.delegate_tool") -def _fabricated_entry(idx: int, status: str, error: str, child: Any) -> Dict[str, Any]: - """Result entry for a child whose Future raised or never finished.""" - return { - "task_index": idx, - "status": status, - "summary": None, - "error": error, - "api_calls": 0, - "duration_seconds": 0, - "_child_role": getattr(child, "_delegate_role", None), - } - - 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: From 52419bda5d0b0c1f1327b291db070f657d1cec17 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:46:39 -0700 Subject: [PATCH 05/11] refactor(delegate): split delegate_task into _normalize_task_list/_coerce_task_schemas/_build_children/_execute_and_aggregate(_Batch); _build_child_agent -> _open_child_session_db/_construct_child_agent/_announce_child_spawn; _run_single_child -> _lease_child_credential/_await_child/_merge_late_steer --- .../mock._session_db.db_path/125483604393296 | Bin 0 -> 237568 bytes .../125483604393296.fts_rebuild.lock | 0 .../125483604393296.quarantine.lock | 0 .../mock._session_db.db_path/125483613186832 | Bin 0 -> 237568 bytes .../125483613186832.fts_rebuild.lock | 0 .../125483613186832.quarantine.lock | 0 .../mock._session_db.db_path/139713934067408 | Bin 0 -> 237568 bytes .../139713934067408.fts_rebuild.lock | 0 .../139713934067408.quarantine.lock | 0 .../mock._session_db.db_path/139713953384784 | Bin 0 -> 237568 bytes .../139713953384784.fts_rebuild.lock | 0 .../139713953384784.quarantine.lock | 0 tools/delegate_tool.py | 972 +++++++++--------- tools/delegate_tool_child_run.py | 112 +- 14 files changed, 579 insertions(+), 505 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/125483604393296 create mode 100644 MagicMock/mock._session_db.db_path/125483604393296.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/125483604393296.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/125483613186832 create mode 100644 MagicMock/mock._session_db.db_path/125483613186832.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/125483613186832.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/139713934067408 create mode 100644 MagicMock/mock._session_db.db_path/139713934067408.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/139713934067408.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/139713953384784 create mode 100644 MagicMock/mock._session_db.db_path/139713953384784.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/139713953384784.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/125483604393296 b/MagicMock/mock._session_db.db_path/125483604393296 new file mode 100644 index 0000000000000000000000000000000000000000..a921ae03460e7545c073c51813f01a51cdfb46b5 GIT binary patch literal 237568 zcmeI4-)|e&mB&fT7G*lNk~S%uCThk>6Oy$YTb5-zag>yn#tLDXv?(f%Q51s_=aQOe zIK#{gB`Ylu&`Fan`U{K2E>P^|ZTD@v?~A@KunY9154-mh#_XNU zbne`_^nF*|GFUK;!`|&OvoZKMvr>~wby=#HZmi4FfNa53+iadj7JvBubS5`9m;Uix zZ_YMZLfW11-%M{=Y5()Ub(WKPpG<9cY;qT-DNeWDR_*-|K!ivd7^5~^ zeV2_ETkxmmGn1&GJMx#o2|M}_WPBS9bzj+`=n^Q0&28eSsjljEWs5&gANL~QlTAOW z{8*%Qc`@mnh($oy+K&Lwp9S~#m*7}kyD`*xyM#6FrD1UFuzkVW#n+_>-if;-d(hGCeTBSLHT3rc>nZris@#j>ng5AaqmQ~JV49px`zuj)W$aBwrYpW<_qrGJZT)Pw|`h1EZ5i*1EZz8 z%9gE~4RKR=qs=;&Vq2EDle|5QAf?4jW~<(L8D@e}p}M6T20x?7HFkB4*~0#ZU0bTd zl&)EiAtG}C#kQ#ng}->@8)GN$HvhwlM&baYip2gx3tAgnO#VzzCG8xr+SnmO$&GiS&>H1X;{3YlXK>0c12B#<+GY)+OQ)blu}DtJgjEpurfx80 z;4rn>9wnC}>Qe2-Hd)qBrK61M=%#rDv29(`n0Y85&x5?)+d zyjJn*w?g7PE)tLf>a^J4=$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483604393296.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/125483604393296.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/125483604393296.quarantine.lock b/MagicMock/mock._session_db.db_path/125483604393296.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/125483613186832 b/MagicMock/mock._session_db.db_path/125483613186832 new file mode 100644 index 0000000000000000000000000000000000000000..16d7bc3d446e6a42a7d3c8f767472a88daddbf65 GIT binary patch literal 237568 zcmeI4-)|dNcE?G}5@kBJlHFvv*+iRhvI)tx97~oJD{-`0S{f^aWzwdoIL2Zz7;&zs zSq*2HnW1E57YOKNlNS36MbQF_HgD})w?H5IQ0#kw7TA}4X#azKX^SF2(U-**J$HWb z4u_PKY(r+@Y#vVBD7!;C<+Ho!KS#g--=$5IpER7jT$5ES1Ss2im zy_1>BUA&mS@2cAd3#M_{I~`^=`X8rPYjUYBOZC!?4O!}wEtqPH&C$r>58s>0yrQD*f5o*pO=SO}QplR^?48kZ}sSR`f^NmcioketW|*U1qvom*3)A zmZ3CM!%zYZea%k4EMLFS#&&jC!&NlhX11kg&rP@ z(|+&l9U@1H>1Mm*Dy~Iw??kTLN6YHC#|t&o#xCQwYRAmx3m(`!X&kM$cUT-P*EkRZ zqp7>fwyl~CaZ`As&Dxe?Tb8(!ygiH{rO8ZYtKNATW`bd%x~&@qKcmPs_H~Wf!v2R{ z+p5Eqj%^I+;_fCi(|N2@IZJ!rupE~%rsjEv?*VjlbW}TZyid`a&)If0?lwBCuQyN99w`Xl098gm-9-tNmfaT!jHnY2YB z1(lzEJn0?jue++LSvxxlU$;0qY!B0bu)?s5*|sHaRCwg`T4jfFQO9Pa+cGrkz*Hy$ z>V~ilgM^Qs&@i^u#vU0;ZoC(T)-Z<>=hsa?gHv|tgK?74Hfs=FIt4X~MRHOmtb)Mr z=mt~z4pW;QP;xn;F4b=Al4ZSAI?SlHZki_$+toFVna2Y1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0T2KI5CDNc zWCHm8e}Blk2irja1V8`;KmY_l00ck)1V8`;K;ZW!fZzZ3`x3->5C8!X009sH0T2KI x5C8!X009vA;uFB{|NG+a5iA4&5C8!X009sH0T2KI5C8!X0D;d!K>YoG{|jKv-s1oO literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/125483613186832.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/125483613186832.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/125483613186832.quarantine.lock b/MagicMock/mock._session_db.db_path/125483613186832.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139713934067408 b/MagicMock/mock._session_db.db_path/139713934067408 new file mode 100644 index 0000000000000000000000000000000000000000..8a7f10506d823826a950890480330030077d3691 GIT binary patch literal 237568 zcmeI4U2GdycE?G}7G*lNlHFvv*+j`W*@Wa;jx8(lM;s+fOJjwwOxhF`$5<=|BhDo? ztKkeYGnB0C0s)_0iNv z1JZZ|f&Z5T!R!#gv61joCYy z>D;+<>HDs_Ww2lxhrQcnW@GSiW~C;V>atWX-B_2U0oj77w%I(5EdKEQ=}c~JF8$-X z-kfc+gtR;1znR!9VXIWgO7x{`Qn^x>*W{XXr&hjQs@<1v$@itwX1!Xj(7@Yrr9SUT zhHIe_b@`pTRH@RR&GmJuCf}56a%Dx{kOCQ}pld~clx-O-F7LNDEYoGC>vj1pu4NfY zLp2N~&@j;K49fEL3vH~~WDQr*bf;rEx=VW@bhGEz#RC zRF|g(B@*y=$G6|wa+tl#`dhpz-z;se*QJYoKbhL@*yJuuQ=D$Qt=jt`fC!N^Fh*^- z`YszSw%||AXC_fWcjPaF6L$0=$oMuI>b|l=(Irq0o7==uQ(e{T$`*f~KJG=pC!2m$ z`LRgr@?z3C5sQGZwI2bVKMU^fFTt_8c4MgXb_r|TOT*yUVf%u$jcwJ9%XuyCen)g% zcboh}i_3-U9Pn|=)?2!%d@t^f>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)h=Bef7nTJpB>TGYA$qG$8sy$k_d~ayl@T?CKAa@g<5f00m-Wab8 z36*;-e)@~2l#gyNWu94_oB7G+uxxVl%Fvhmj1}RRq!vW27cV|PN39pD@jg>+7iO|Q zq`0G;#*6Dwg=k@niS@&+WxqPJhQ(8Gb|`)!8wO{12p@Fg@<#;K*(%*X_>F7uCY7vg zITzewqHERX@a*uG9P{w7aT1bo;P?N1`S%DGf&d7B00@8p2!H?xfB*=900@A<=OG~e{=fePnik*F literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/139713934067408.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/139713934067408.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139713934067408.quarantine.lock b/MagicMock/mock._session_db.db_path/139713934067408.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139713953384784 b/MagicMock/mock._session_db.db_path/139713953384784 new file mode 100644 index 0000000000000000000000000000000000000000..50bdcbe5e65c71a02a06c04a2c28455b2d235a77 GIT binary patch literal 237568 zcmeI4-)|dNcE?G}7G*lNlHFvv*+iRhvI)tx9P5YWA90i{EsYhzGHFv(9AmK_eS6WOxnL2SI^&Lq{rBWy8&ujE2 z{92%IPKFQkZ#w+``4`XsbNGGVzb8_!{`o(iqQ;5oPkGms>EBNO_w=VHUzqsS#77e! z^-1Fq1pZ$VkWWwM9xSF)x~Z{;&btPMq@s3Q%X?NF<~X`#DlJQ6hSG7=CR64IG-mH+ zCUX}qq#wBImcfE)9QJO9nT`I(sg;^ss>@QnbaP#n`eX~H+G4XbviL{uPiAs6GwC1Q z^X6=kC8XU6|INf^30tK?R-!LmlggF4ye8MAyS4J2Qtg3sTYeywHtW@Lg$CY{EA?4V zGF%IdsLSuvrAn3lY_6|MHTjlYlPfFoh7`y+1zjupqioAyae2SJVVN#7U9Zb;aV^VG z8meI^frh?jr(c$@Uua|7+pOU#n(nkMM|Wv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Qee8fsA6wwg9MPhd_ldsAL3SG={AD;sjH&eva! zc2@M3!XOvo&akg*vq$)hzwUr{USkGxS$@{@1wL5t9RDHm1>v!`-~Q_OAaBcGe?!Xi z0r?xpTgPX&n7c8zQ*dYhL9mned5`^e@{WEx<;v=ZH(&Q+`j0Oi7Sp=vFxw5uA19{$ z5t1L%!JZ~!HEB~6C%o%R6eoc>e@Joi8T{+*()y;nAr<^peijES-pG;@b$=iA}bfE!VuZ3<^y16b(`9mc0gE+Zyy;KZZqtXud$s8l2g2+no2Lo9oq^ z#qJB&Gr8sEbobtHn{@5rz-3eWwPV;qV)=r@n*5BQv%WPewVS3jE7~J=7yGH5xt7Vj z`R3u&RG0GbfUHkBU%h$^8@b$YSX+kG*bR7@S2MY#rKu0nLwOA{BrxIaa;?5uT9@jc zGYt}yHaE(ZHHp&XQo%d0!*auW=$)v&NAE?+e z7_STom3u9I`irNOkM1mGo?D!m`tjzVY;yd{(3kv-72%hp7DTNVFFrpxTBoLi|b*9Xkmnj^~0@YzdEx9#Zz#0D1IRu24{E(A9myNM+DW`D&0T$jjR7A zm8@(z7u;f^Yt`rQ?C_Qx^YE~79G*_q8-D+v_>u$Pg8&GC00@8p2!H?xfB*=900@A< zA2I>_{=Yxu-Gl8Q00JNY0w4eaAOHd&00JNY0wD1F62R~O`+W&wJP3dQ2!H?xfB*=9 y00@8p2!H?xeEA9B_y2wQ_Xrk(00@8p2!H?xfB*=900@8p2!O!nAt3(#zyAg4g56U9 literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/139713953384784.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/139713953384784.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139713953384784.quarantine.lock b/MagicMock/mock._session_db.db_path/139713953384784.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 30128f58d7..6eeb863982 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -17,11 +17,9 @@ The parent's context only sees the delegation call and the summary result, never the child's intermediate tool calls or reasoning. """ -import contextvars import json import logging import re -import threading import time import weakref from dataclasses import dataclass @@ -29,7 +27,7 @@ from typing import Any, Dict, List, Optional from toolsets import TOOLSETS -from tools.terminal_tool import set_approval_callback as _set_subagent_approval_cb +from tools.terminal_tool import set_approval_callback as _set_subagent_approval_cb # noqa: F401 (used via _await_child) from utils import is_truthy_value logger = logging.getLogger(__name__) @@ -40,12 +38,19 @@ logger = logging.getLogger(__name__) # (_spawn_paused, *_WARNED) live only in their owning module. from tools.delegate_tool_child_run import ( # noqa: F401 _WorktreeReporter, + _append_missed_steer, _append_sibling_write_reminder, + _attach_child, + _await_child, _build_result_entry, _cleanup_child_run, _dump_subagent_timeout_diagnostic, _emit_child_complete, + _fabricated_entry, _handle_child_wait_failure, + _lease_child_credential, + _make_text_relay, + _merge_late_steer, _register_child, _seed_child_workspace, _start_heartbeat, @@ -83,6 +88,7 @@ from tools.delegate_tool_progress import ( # noqa: F401 _clean_error_text, _emit_parent_console, _resolve_workspace_hint, + _safe_progress, format_batch_tag, format_subagent_failure_line, ) @@ -484,6 +490,133 @@ def _resolve_child_runtime( ) +def _open_child_session_db(parent_agent) -> Any: + """DEDICATED SessionDB handle for the child, or None. + + The parent's handle can be closed by its own lifecycle while a background + child still flushes (transcript silently dropped). It MUST open the same db + FILE as the parent's handle (non-launch profiles), else lineage / + session_search break; released by the child's close() via _owns_session_db. + """ + parent_session_db = getattr(parent_agent, "_session_db", None) + if parent_session_db is None: + return None + try: + from hermes_state import get_shared_session_db + + _parent_db_path = getattr(parent_session_db, "db_path", None) + return get_shared_session_db(_parent_db_path) if _parent_db_path is not None else get_shared_session_db() + except Exception: + logger.debug( + "subagent: failed to open dedicated SessionDB; child persistence disabled", + exc_info=True, + ) + return None + + +def _construct_child_agent( + rt: _ChildRuntime, + *, + task_index: int, + max_iterations: int, + parent_agent, + child_toolsets: List[str], + child_disabled_toolsets: List[str], + child_prompt: str, + child_progress_cb: Any, + child_session_db: Any, + override_provider: Optional[str], + override_request_overrides: Optional[Dict[str, Any]], +): + """Instantiate the child AIAgent; releases the dedicated SessionDB handle on + a construction failure (no child close() will ever run).""" + from run_agent import AIAgent + from agent.delegation_context import delegated_child_context + + child_thinking_cb = None + if child_progress_cb: + + def _child_thinking(text: str) -> None: + if text: + _safe_progress(child_progress_cb, "_thinking", text) + + child_thinking_cb = _child_thinking + + with delegated_child_context(): + try: + return AIAgent( + base_url=rt.base_url, + api_key=rt.api_key, + model=rt.model, + provider=rt.provider, + capabilities=rt.capabilities, + api_mode=rt.api_mode, + acp_command=rt.acp_command, + acp_args=rt.acp_args, + max_iterations=max_iterations, + reasoning_config=rt.reasoning, + prefill_messages=getattr(parent_agent, "prefill_messages", None), + fallback_model=rt.fallback, + enabled_toolsets=child_toolsets, + disabled_toolsets=child_disabled_toolsets, + quiet_mode=True, + ephemeral_system_prompt=child_prompt, + log_prefix=f"[subagent-{task_index}]", + platform="subagent", + skip_context_files=True, + skip_memory=True, + clarify_callback=None, + thinking_callback=child_thinking_cb, + session_db=child_session_db, + parent_session_id=getattr(parent_agent, "session_id", None), + providers_allowed=rt.providers_allowed, + providers_ignored=rt.providers_ignored, + providers_order=rt.providers_order, + provider_sort=rt.provider_sort, + provider_require_parameters=rt.provider_require_parameters, + provider_data_collection=rt.provider_data_collection, + request_overrides=( + # honored whenever set, incl. the inherit branch where + # _resolve_delegation_credentials already merged OVER the parent's + dict(override_request_overrides) + if override_request_overrides is not None + else ({} if override_provider else dict(getattr(parent_agent, "request_overrides", {}) or {})) + ), + openrouter_min_coding_score=rt.openrouter_min_coding_score, + tool_progress_callback=child_progress_cb, + iteration_budget=None, # fresh budget per subagent + **rt.optional_kwargs, + ) + except BaseException: + if child_session_db is not None: + try: + from hermes_state import release_or_close + release_or_close(child_session_db) + except Exception: + pass + raise + + +def _announce_child_spawn(child, parent_agent, child_progress_cb, *, goal, subagent_id, parent_subagent_id, role) -> None: + """spawn_requested event (now — the child may queue for seconds when the + pool is saturated) plus the subagent_start lifecycle hook.""" + _safe_progress(child_progress_cb, "subagent.spawn_requested", preview=goal) + try: + from hermes_cli.lifecycle import invoke_hook as _invoke_hook + _invoke_hook( + "subagent_start", + parent_session_id=getattr(parent_agent, "session_id", None), + parent_turn_id=getattr(parent_agent, "_current_turn_id", "") or "", + parent_subagent_id=parent_subagent_id, + child_session_id=getattr(child, "session_id", None), + child_subagent_id=subagent_id, + child_role=role, + child_goal=goal, + ) + except Exception: + logger.debug("subagent_start hook invocation failed", exc_info=True) + + def _build_child_agent( task_index: int, goal: str, @@ -511,33 +644,25 @@ def _build_child_agent( override_* (from delegation config) replace parent inheritance so children can run on a different provider:model pair. """ - from run_agent import AIAgent import uuid as _uuid # Role is depth-derived: a child may delegate iff the kill switch is on and # depth budget remains below max_spawn_depth. The `role` arg is ignored. child_depth = getattr(parent_agent, "_delegate_depth", 0) + 1 max_spawn = _get_max_spawn_depth() - orchestrator_ok = _get_orchestrator_enabled() and child_depth < max_spawn - effective_role = "orchestrator" if orchestrator_ok else "leaf" + effective_role = "orchestrator" if _get_orchestrator_enabled() and child_depth < max_spawn else "leaf" # One subagent_id shared by the progress callback, spawn_requested event and # the live registry; parent_id is set when THIS parent is itself a subagent. subagent_id = f"sa-{task_index}-{_uuid.uuid4().hex[:8]}" parent_subagent_id = getattr(parent_agent, "_subagent_id", None) - tui_depth = max(0, child_depth - 1) # 0 = first-level child for the UI delegation_cfg = _load_config() - - child_toolsets, child_disabled_toolsets = _resolve_child_toolsets( - parent_agent, toolsets, effective_role - ) - - workspace_hint = _resolve_workspace_hint(parent_agent) + child_toolsets, child_disabled_toolsets = _resolve_child_toolsets(parent_agent, toolsets, effective_role) child_prompt = _build_child_system_prompt( goal, context, - workspace_path=workspace_hint, + workspace_path=_resolve_workspace_hint(parent_agent), role=effective_role, max_spawn_depth=max_spawn, child_depth=child_depth, @@ -546,7 +671,6 @@ def _build_child_agent( if (not parent_api_key) and hasattr(parent_agent, "_client_kwargs"): parent_api_key = parent_agent._client_kwargs.get("api_key") - effective_model_for_cb = model or getattr(parent_agent, "model", None) child_session_ref: Dict[str, Any] = {} child_progress_cb = _build_child_progress_callback( task_index, @@ -555,25 +679,11 @@ def _build_child_agent( task_count, subagent_id=subagent_id, parent_id=parent_subagent_id, - depth=tui_depth, - model=effective_model_for_cb, + depth=max(0, child_depth - 1), # 0 = first-level child for the UI + model=model or getattr(parent_agent, "model", None), toolsets=child_toolsets, session_ref=child_session_ref, ) - - child_thinking_cb = None - if child_progress_cb: - - def _child_thinking(text: str) -> None: - if not text: - return - try: - child_progress_cb("_thinking", text) - except Exception as e: - logger.debug("Child thinking callback relay failed: %s", e) - - child_thinking_cb = _child_thinking - rt = _resolve_child_runtime( parent_agent, delegation_cfg, @@ -587,93 +697,20 @@ def _build_child_agent( override_acp_command=override_acp_command, override_acp_args=override_acp_args, ) - effective_provider, effective_base_url = rt.provider, rt.base_url - - # DEDICATED SessionDB handle for the child: the parent's can be closed by - # its own lifecycle while a background child still flushes (transcript - # silently dropped). It MUST open the same db FILE as the parent's handle - # (non-launch profiles), else lineage/session_search break; released by the - # child's close() via _owns_session_db. - child_session_db = None - parent_session_db = getattr(parent_agent, "_session_db", None) - if parent_session_db is not None: - try: - from hermes_state import get_shared_session_db - - _parent_db_path = getattr(parent_session_db, "db_path", None) - child_session_db = ( - get_shared_session_db(_parent_db_path) - if _parent_db_path is not None - else get_shared_session_db() - ) - except Exception: - logger.debug( - "subagent: failed to open dedicated SessionDB; child persistence disabled", - exc_info=True, - ) - child_session_db = None - - from agent.delegation_context import delegated_child_context - - with delegated_child_context(): - try: - child = AIAgent( - base_url=rt.base_url, - api_key=rt.api_key, - model=rt.model, - provider=rt.provider, - capabilities=rt.capabilities, - api_mode=rt.api_mode, - acp_command=rt.acp_command, - acp_args=rt.acp_args, - max_iterations=max_iterations, - - reasoning_config=rt.reasoning, - prefill_messages=getattr(parent_agent, "prefill_messages", None), - fallback_model=rt.fallback, - enabled_toolsets=child_toolsets, - disabled_toolsets=child_disabled_toolsets, - quiet_mode=True, - ephemeral_system_prompt=child_prompt, - log_prefix=f"[subagent-{task_index}]", - platform="subagent", - skip_context_files=True, - skip_memory=True, - clarify_callback=None, - thinking_callback=child_thinking_cb, - session_db=child_session_db, - parent_session_id=getattr(parent_agent, "session_id", None), - providers_allowed=rt.providers_allowed, - providers_ignored=rt.providers_ignored, - providers_order=rt.providers_order, - provider_sort=rt.provider_sort, - provider_require_parameters=rt.provider_require_parameters, - provider_data_collection=rt.provider_data_collection, - request_overrides=( - # honored whenever set, incl. the inherit branch where - # _resolve_delegation_credentials already merged OVER the parent's - dict(override_request_overrides) - if override_request_overrides is not None - else ( - {} - if override_provider - else dict(getattr(parent_agent, "request_overrides", {}) or {}) - ) - ), - openrouter_min_coding_score=rt.openrouter_min_coding_score, - tool_progress_callback=child_progress_cb, - iteration_budget=None, # fresh budget per subagent - **rt.optional_kwargs, - ) - except BaseException: - # No child close() will ever run — release the dedicated handle here. - if child_session_db is not None: - try: - from hermes_state import release_or_close - release_or_close(child_session_db) - except Exception: - pass - raise + child_session_db = _open_child_session_db(parent_agent) + child = _construct_child_agent( + rt, + task_index=task_index, + max_iterations=max_iterations, + parent_agent=parent_agent, + child_toolsets=child_toolsets, + child_disabled_toolsets=child_disabled_toolsets, + child_prompt=child_prompt, + child_progress_cb=child_progress_cb, + child_session_db=child_session_db, + override_provider=override_provider, + override_request_overrides=override_request_overrides, + ) child._print_fn = getattr(parent_agent, "_print_fn", None) if child_session_db is not None: child._owns_session_db = True # released by the child's close(), never by the parent @@ -698,43 +735,15 @@ def _build_child_agent( child._session_init_model_config["_delegate_from"] = parent_sid # Shared pool lets children rotate credentials on rate limits. - child_pool = _resolve_child_credential_pool( - effective_provider, parent_agent, effective_base_url - ) + child_pool = _resolve_child_credential_pool(rt.provider, parent_agent, rt.base_url) if child_pool is not None: child._credential_pool = child_pool - # Register child for interrupt propagation - if hasattr(parent_agent, "_active_children"): - lock = getattr(parent_agent, "_active_children_lock", None) - if lock: - with lock: - parent_agent._active_children.append(child) - else: - parent_agent._active_children.append(child) - - # Announce now: the child may queue for seconds when the pool is saturated. - if child_progress_cb: - try: - child_progress_cb("subagent.spawn_requested", preview=goal) - except Exception as exc: - logger.debug("spawn_requested relay failed: %s", exc) - - try: - from hermes_cli.lifecycle import invoke_hook as _invoke_hook - _invoke_hook( - "subagent_start", - parent_session_id=getattr(parent_agent, "session_id", None), - parent_turn_id=getattr(parent_agent, "_current_turn_id", "") or "", - parent_subagent_id=parent_subagent_id, - child_session_id=getattr(child, "session_id", None), - child_subagent_id=subagent_id, - child_role=effective_role, - child_goal=goal, - ) - except Exception: - logger.debug("subagent_start hook invocation failed", exc_info=True) - + _attach_child(parent_agent, child) # interrupt propagation + _announce_child_spawn( + child, parent_agent, child_progress_cb, + goal=goal, subagent_id=subagent_id, parent_subagent_id=parent_subagent_id, role=effective_role, + ) return child @@ -765,24 +774,12 @@ def _run_single_child( # thread before the worker settles races the conversation's finally path. _child_close_deferred = False child_progress_cb = getattr(child, "tool_progress_callback", None) - - child_pool = getattr(child, "_credential_pool", None) - leased_cred_id = None - if child_pool is not None: - leased_cred_id = child_pool.acquire_lease() - if leased_cred_id is not None: - try: - leased_entry = child_pool.current() - if leased_entry is not None and hasattr(child, "_swap_credential"): - child._swap_credential(leased_entry) - except Exception as exc: - logger.debug("Failed to bind child to leased credential: %s", exc) + child_pool, leased_cred_id = _lease_child_credential(child) # Heartbeat keeps the parent's _last_activity_ts moving so the gateway # inactivity timeout doesn't fire while the child works; it stops itself # once the child looks stale (see _HEARTBEAT_STALE_CYCLES_*). heartbeat = _start_heartbeat(child, parent_agent, task_index) - _heartbeat_thread = heartbeat[1] # TUI/RPC registry entry (kill/pause/status by subagent_id); None for test # doubles without a stable id. Unregistered in the finally block. _subagent_id = _register_child( @@ -796,101 +793,31 @@ def _run_single_child( worktree = _WorktreeReporter() try: - _heartbeat_thread.start() - if child_progress_cb: - try: - child_progress_cb("subagent.start", preview=goal) - except Exception as e: - logger.debug("Progress callback start failed: %s", e) + heartbeat[1].start() + _safe_progress(child_progress_cb, "subagent.start", preview=goal) ws = _seed_child_workspace(child, parent_agent, goal, task_index, _subagent_id, worktree) goal = ws.goal - - # Optional hard timeout (off by default — result(timeout=None) blocks - # until the child finishes; stuck-child protection is the heartbeat). - child_timeout = _get_child_timeout() - # Daemon worker: a timed-out child is abandoned below and a stdlib - # non-daemon worker would block interpreter exit at atexit-join time. - from tools.daemon_pool import DaemonThreadPoolExecutor - _timeout_executor = DaemonThreadPoolExecutor( - max_workers=1, - # Non-interactive approval callback in the worker thread so dangerous - # command prompts never fall back to input() and deadlock the parent - # TUI; deny vs approve follows delegation.subagent_auto_approve. - initializer=_set_subagent_approval_cb, - initargs=(_get_subagent_approval_callback(),), + _relay_child_text = _make_text_relay(child_progress_cb) + result, failure = _await_child( + child, + goal, + ws, + _relay_child_text, + task_index=task_index, + subagent_id=_subagent_id, + child_start=child_start, + child_progress_cb=child_progress_cb, + worktree=worktree, ) - # Worker thread handle so the timeout diagnostic can dump its stack. - _worker_thread_holder: Dict[str, Optional[threading.Thread]] = {"t": None} - - def _relay_child_text(delta: str) -> None: - # Forward the child's streamed reply text up the progress relay so - # gateway watch windows mirror it live (subagent.text → message.delta). - # Inert under CLI/TUI: their progress handlers ignore non-tool events. - if not delta or not child_progress_cb: - return - try: - child_progress_cb("subagent.text", preview=delta) - except Exception as e: - logger.debug("Child text relay failed: %s", e) - - def _run_with_thread_capture(): - _worker_thread_holder["t"] = threading.current_thread() - from agent.delegation_context import delegated_child_context - - with delegated_child_context(str(getattr(child, "session_id", "") or "")): - return child.run_conversation( - user_message=goal, - task_id=ws.child_task_id, - stream_callback=_relay_child_text, - ) - - _child_context = contextvars.copy_context() - _child_future = _timeout_executor.submit( - _child_context.run, - _run_with_thread_capture, - ) - try: - result = _child_future.result(timeout=child_timeout) - except Exception as _timeout_exc: - failure = _handle_child_wait_failure( - _timeout_exc, - child=child, - task_index=task_index, - goal=goal, - subagent_id=_subagent_id, - child_future=_child_future, - child_timeout=child_timeout, - child_start=child_start, - child_progress_cb=child_progress_cb, - worker_thread_holder=_worker_thread_holder, - worktree=worktree, - ) + if failure is not None: _child_close_deferred = failure.close_deferred return failure.entry - finally: - # Shut down without waiting — a child stuck on blocking I/O would - # hang wait=True forever. - _timeout_executor.shutdown(wait=False) schema = _validate_child_output_schema( child, result, task_index, ws.child_task_id, _relay_child_text ) - - # Linearization boundary for registry steering: from here the child - # cannot consume another steer. Closing under the registry lock either - # rejects a concurrent caller or drains every accepted exact text into - # the result before callbacks/result assembly run. - _late_pending_steer = ( - _close_subagent_steering(_subagent_id, child) if _subagent_id else None - ) - if _late_pending_steer: - _existing_pending = result.get("pending_steer") - result["pending_steer"] = ( - f"{_existing_pending}\n{_late_pending_steer}" - if isinstance(_existing_pending, str) and _existing_pending - else _late_pending_steer - ) + _merge_late_steer(result, _subagent_id, child) # Flush any remaining batched progress to gateway if child_progress_cb and hasattr(child_progress_cb, "_flush"): @@ -912,32 +839,16 @@ def _run_single_child( ) duration = round(time.monotonic() - child_start, 2) logging.exception(f"[subagent-{task_index}] failed") - if child_progress_cb: - try: - child_progress_cb( - "subagent.complete", - preview=str(exc), - status="failed", - duration_seconds=duration, - summary=str(exc), - ) - except Exception as e: - logger.debug("Progress callback failure relay failed: %s", e) - _error_entry = { - "task_index": task_index, - "status": "error", - "summary": None, - "error": str(exc), - "api_calls": 0, - "duration_seconds": duration, - "_child_role": getattr(child, "_delegate_role", None), - } - if _late_pending_steer: - _error_entry["missed_steer"] = _late_pending_steer - _error_entry["error"] += ( - " [steer did not land before the subagent stopped: " - f"{_late_pending_steer}]" - ) + _safe_progress( + child_progress_cb, + "subagent.complete", + preview=str(exc), + status="failed", + duration_seconds=duration, + summary=str(exc), + ) + _error_entry = _fabricated_entry(task_index, "error", str(exc), child, duration) + _append_missed_steer(_error_entry, _late_pending_steer) worktree.attach(_error_entry) # no-op when isolation never engaged return _error_entry @@ -1041,6 +952,258 @@ def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]: return None +@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 _normalize_task_list( + goal, context, tasks, output_schema, top_role: str, max_children: int +) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: + """``(task_list, None)`` from ``tasks=[...]`` or the legacy single ``goal``, else ``(None, error)``.""" + recovered_tasks, tasks_error = _recover_tasks_from_json_string(tasks) + if tasks_error: + return None, tasks_error + if recovered_tasks is not None: + tasks = recovered_tasks + # Small models emit tasks=[] alongside a single goal: treat as "no batch". + if isinstance(tasks, list) and not tasks: + tasks = None + + if tasks and isinstance(tasks, list): + if len(tasks) > max_children: + return None, ( + f"Too many tasks: {len(tasks)} provided, but " + f"max_concurrent_children is {max_children}. " + f"Either reduce the task count, split into multiple " + f"delegate_task calls, or increase " + f"delegation.max_concurrent_children in config.yaml." + ) + task_list = tasks + elif goal and isinstance(goal, str) and goal.strip(): + single_task: Dict[str, Any] = {"goal": goal, "context": context, "role": top_role} + if output_schema is not None: + single_task["output_schema"] = output_schema + task_list = [single_task] + else: + return None, ( + "No tasks provided. Pass tasks=[{goal: '...', context: '...'}, " + "...] — one entry per subagent (a single task is a one-entry " + "array)." + ) + + for i, task in enumerate(task_list): + if not isinstance(task, dict): + return None, f"Task {i} must be an object, got {type(task).__name__}." + if not task.get("goal", "").strip(): + return None, f"Task {i} is missing a 'goal'." + + # Batch-only quality gate (placeholders, template markers); the single-goal + # form is exempt because short goals are valid there. + if tasks is not None and isinstance(tasks, list): + batch_error = _validate_batch_tasks(task_list) + if batch_error: + return None, batch_error + return task_list, None + + +def _coerce_task_schemas( + task_list: List[Dict[str, Any]], output_schema: Optional[Dict[str, Any]] +) -> tuple[List[Optional[Dict[str, Any]]], Optional[str]]: + """Per-task coerced output schemas. A malformed output_schema fails the whole + call before any child spawns; schema-less tasks resolve to None and take no + new code paths downstream.""" + from tools.delegation_output_schema import coerce_output_schema + + task_schemas: List[Optional[Dict[str, Any]]] = [] + for i, task in enumerate(task_list): + raw_schema = task.get("output_schema") + if raw_schema is None and len(task_list) == 1 and output_schema is not None: + raw_schema = output_schema + coerced_schema, schema_err = coerce_output_schema(raw_schema) + if schema_err: + return [], f"Task {i} output_schema invalid: {schema_err}" + task_schemas.append(coerced_schema) + return task_schemas, None + + +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]]], + creds: Dict[str, Any], + *, + top_role: str, + max_iterations: int, + parent_agent, + live_deleg_id: Optional[str], + live_writers: list, +) -> tuple[List[tuple], Optional[str]]: + """Build every child on the main thread (construction is not thread-safe); + ``(children, None)`` or ``([], error)`` on an explicit-pin preflight failure.""" + from tools.delegation_live_log import wrap_progress_callback + + children = [] + for i, t in enumerate(task_list): + effective_role = _normalize_role(t.get("role") or top_role) + _task_schema = task_schemas[i] if i < len(task_schemas) else None + _child_context = t.get("context") + if _task_schema is not None: + from tools.delegation_output_schema import append_output_contract + + _child_context = append_output_contract(_child_context, _task_schema) + try: + child = _build_child_preserving_parent_tools( + task_index=i, + goal=t["goal"], + context=_child_context, + toolsets=None, # always inherit the parent's toolsets + model=creds["model"], + max_iterations=max_iterations, + task_count=len(task_list), + parent_agent=parent_agent, + override_provider=creds["provider"], + override_base_url=creds["base_url"], + override_api_key=creds["api_key"], + override_api_mode=creds["api_mode"], + override_request_overrides=creds.get("request_overrides"), + override_max_tokens=creds.get("max_output_tokens"), + override_acp_command=creds.get("command"), + override_acp_args=creds.get("args"), + role=effective_role, + ) + except ValueError as exc: + return [], str(exc) + if _task_schema is not None: + try: + child._delegate_output_schema = _task_schema + except Exception: + logger.debug("Could not attach output schema to child %d", i) + # Tee progress events into the live transcript (wrapper keeps the + # _flush contract and swallows writer failures). + _writer = live_writers[i] if i < len(live_writers) else None + if _writer is not None: + child.tool_progress_callback = wrap_progress_callback( + getattr(child, "tool_progress_callback", None), _writer + ) + child._live_transcript_path = str(_writer.path) + if live_deleg_id: + setattr(child, "_delegation_id", live_deleg_id) + _ident_ref = getattr(child, "_progress_identity_ref", None) + if isinstance(_ident_ref, dict): + _ident_ref["delegation_id"] = live_deleg_id + 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, context: Optional[str] = None, @@ -1067,13 +1230,9 @@ def delegate_task( normalized_action = (action or "").strip().lower() if normalized_action in _CONTROL_ACTIONS: - return _handle_control_action( - normalized_action, subagent_id, message, parent_agent - ) + return _handle_control_action(normalized_action, subagent_id, message, parent_agent) if normalized_action and normalized_action != "spawn": - return tool_error( - f"Unknown action '{action}'. Use spawn (default), list, steer, or stop." - ) + return tool_error(f"Unknown action '{action}'. Use spawn (default), list, steer, or stop.") # Operator kill switch (TUI / delegation.pause RPC): blocks NEW spawns only. if is_spawn_paused(): @@ -1108,243 +1267,53 @@ def delegate_task( "using delegation.max_iterations=%s from config", max_iterations, default_max_iter, ) - effective_max_iter = default_max_iter # credentials_cfg (internal callers only, e.g. /review → auxiliary.review) is # a per-call override shaped like the delegation config section. try: - creds = _resolve_delegation_credentials( - credentials_cfg if credentials_cfg else cfg, parent_agent - ) + creds = _resolve_delegation_credentials(credentials_cfg if credentials_cfg else cfg, parent_agent) except ValueError as exc: return tool_error(str(exc)) max_children = _get_max_concurrent_children() - recovered_tasks, tasks_error = _recover_tasks_from_json_string(tasks) - if tasks_error: - return tool_error(tasks_error) - if recovered_tasks is not None: - tasks = recovered_tasks - - # Small models emit tasks=[] alongside a single goal: treat as "no batch". - if isinstance(tasks, list) and not tasks: - tasks = None - - if tasks and isinstance(tasks, list): - if len(tasks) > max_children: - return tool_error( - f"Too many tasks: {len(tasks)} provided, but " - f"max_concurrent_children is {max_children}. " - f"Either reduce the task count, split into multiple " - f"delegate_task calls, or increase " - f"delegation.max_concurrent_children in config.yaml." - ) - task_list = tasks - elif goal and isinstance(goal, str) and goal.strip(): - single_task: Dict[str, Any] = {"goal": goal, "context": context, "role": top_role} - if output_schema is not None: - single_task["output_schema"] = output_schema - task_list = [single_task] - else: - return tool_error( - "No tasks provided. Pass tasks=[{goal: '...', context: '...'}, " - "...] — one entry per subagent (a single task is a one-entry " - "array)." - ) - - if not task_list: - return tool_error("No tasks provided.") - - for i, task in enumerate(task_list): - if not isinstance(task, dict): - return tool_error( - f"Task {i} must be an object, got {type(task).__name__}." - ) - if not task.get("goal", "").strip(): - return tool_error(f"Task {i} is missing a 'goal'.") - - # Batch-only quality gate (placeholders, template markers); the single-goal - # form is exempt because short goals are valid there. - if tasks is not None and isinstance(tasks, list): - batch_error = _validate_batch_tasks(task_list) - if batch_error: - return tool_error(batch_error) - - # A malformed output_schema fails the whole call before any child spawns; - # schema-less tasks resolve to None and take no new code paths downstream. - from tools.delegation_output_schema import coerce_output_schema - - task_schemas: List[Optional[Dict[str, Any]]] = [] - for i, task in enumerate(task_list): - raw_schema = task.get("output_schema") - if raw_schema is None and len(task_list) == 1 and output_schema is not None: - raw_schema = output_schema - coerced_schema, schema_err = coerce_output_schema(raw_schema) - if schema_err: - return tool_error(f"Task {i} output_schema invalid: {schema_err}") - task_schemas.append(coerced_schema) + task_list, err = _normalize_task_list(goal, context, tasks, output_schema, top_role, max_children) + if err: + return tool_error(err) + task_schemas, err = _coerce_task_schemas(task_list, output_schema) + if err: + return tool_error(err) overall_start = time.monotonic() - results = [] - - n_tasks = len(task_list) - task_labels = [t["goal"][:40] for t in task_list] - # Live transcripts: cache/delegation/live//task-.log per task, a # side channel with zero effect on message content or prompt caching. # Best-effort: on failure live_paths is empty and delegation proceeds. - from tools.delegation_live_log import ( - create_live_transcripts, - update_manifest_statuses, - wrap_progress_callback, - ) + from tools.delegation_live_log import create_live_transcripts live_deleg_id, live_writers, live_paths = create_live_transcripts( task_list, context, model=creds.get("model"), provider=creds.get("provider") ) - # Announce the batch tag once so interleaved ``[tag n/N]`` lines are attributable. - if n_tasks > 1 and live_deleg_id: - _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) - except Exception: - _emit_parent_console(parent_agent, _hdr) - else: - _emit_parent_console(parent_agent, _hdr) + _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() - # Capture the ORIGINATING session's wake target BEFORE building any child: - # AIAgent construction clobbers the HERMES_SESSION_ID ContextVar/os.environ - # with the subagent's internal 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 = "" - _origin_owner_transport, _origin_owner_session_record = ( - _capture_gateway_steer_authority(_origin_ui_session_id) + children, err = _build_children( + task_list, + task_schemas, + creds, + top_role=top_role, + max_iterations=default_max_iter, + parent_agent=parent_agent, + live_deleg_id=live_deleg_id, + live_writers=live_writers, + ) + 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, ) - # Build every child on the main thread (construction is not thread-safe). - children = [] - for i, t in enumerate(task_list): - effective_role = _normalize_role(t.get("role") or top_role) - _task_schema = task_schemas[i] if i < len(task_schemas) else None - _child_context = t.get("context") - if _task_schema is not None: - from tools.delegation_output_schema import append_output_contract - - _child_context = append_output_contract(_child_context, _task_schema) - try: - child = _build_child_preserving_parent_tools( - task_index=i, - goal=t["goal"], - context=_child_context, - toolsets=None, # always inherit the parent's toolsets - model=creds["model"], - max_iterations=effective_max_iter, - task_count=n_tasks, - parent_agent=parent_agent, - override_provider=creds["provider"], - override_base_url=creds["base_url"], - override_api_key=creds["api_key"], - override_api_mode=creds["api_mode"], - override_request_overrides=creds.get("request_overrides"), - override_max_tokens=creds.get("max_output_tokens"), - override_acp_command=creds.get("command"), - override_acp_args=creds.get("args"), - role=effective_role, - ) - except ValueError as exc: - return tool_error(str(exc)) # explicit-pin preflight failure - if _task_schema is not None: - try: - child._delegate_output_schema = _task_schema - except Exception: - logger.debug("Could not attach output schema to child %d", i) - # Tee progress events into the live transcript (wrapper keeps the - # _flush contract and swallows writer failures). - _writer = live_writers[i] if i < len(live_writers) else None - if _writer is not None: - child.tool_progress_callback = wrap_progress_callback( - getattr(child, "tool_progress_callback", None), _writer - ) - child._live_transcript_path = str(_writer.path) - if live_deleg_id: - setattr(child, "_delegation_id", live_deleg_id) - _ident_ref = getattr(child, "_progress_identity_ref", None) - if isinstance(_ident_ref, dict): - _ident_ref["delegation_id"] = live_deleg_id - children.append((i, t, child)) - - def _execute_and_aggregate(*, 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. - """ - if n_tasks == 1: - _i, _t, child = children[0] - result = _run_single_child( - _i, - _t["goal"], - child, - parent_agent, - owner_session_id=_origin_ui_session_id or None, - owner_transport=_origin_owner_transport, - owner_session_record=_origin_owner_session_record, - ) - results.append(result) - else: - _run_children_parallel( - children, - results, - parent_agent=parent_agent, - n_tasks=n_tasks, - max_children=max_children, - task_labels=task_labels, - live_deleg_id=live_deleg_id, - honor_parent_interrupt=honor_parent_interrupt, - origin_ui_session_id=_origin_ui_session_id, - origin_owner_transport=_origin_owner_transport, - origin_owner_session_record=_origin_owner_session_record, - ) - - _finalize_child_results(results, task_list, children, parent_agent) - - total_duration = round(time.monotonic() - overall_start, 2) - - # 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] - update_manifest_statuses(live_deleg_id, results) - - combined: Dict[str, Any] = { - "results": results, - "total_duration_seconds": total_duration, - } - if live_paths: - combined["live_transcripts"] = list(live_paths) - return combined + def _run(*, honor_parent_interrupt: bool = True) -> dict: + return _execute_and_aggregate(batch, honor_parent_interrupt=honor_parent_interrupt) if background: return _dispatch_background( @@ -1358,10 +1327,9 @@ def delegate_task( live_paths=live_paths, origin_wake_sid=_origin_wake_sid, origin_ui_session_id=_origin_ui_session_id, - execute_and_aggregate=_execute_and_aggregate, + execute_and_aggregate=_run, ) - - return json.dumps(_execute_and_aggregate(), ensure_ascii=False) + return json.dumps(_run(), ensure_ascii=False) # ── OpenAI function-calling schema ────────────────────────────────────────── diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index ca9e2307dc..5ed5d0864e 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -7,6 +7,7 @@ Split out of ``tools/delegate_tool.py``; every moved name is re-imported there, from __future__ import annotations import logging +import contextvars import json import threading import time @@ -32,15 +33,15 @@ def _num(value: Any, default: int = 0) -> int: return int(value) if isinstance(value, (int, float)) else default -def _fabricated_entry(idx: int, status: str, error: str, child: Any) -> Dict[str, Any]: - """Result entry for a child whose Future raised or never finished.""" +def _fabricated_entry(idx: int, status: str, error: str, child: Any, duration: float = 0) -> Dict[str, Any]: + """Result entry for a child that raised, never finished, or was abandoned.""" return { "task_index": idx, "status": status, "summary": None, "error": error, "api_calls": 0, - "duration_seconds": 0, + "duration_seconds": duration, "_child_role": getattr(child, "_delegate_role", None), } @@ -558,6 +559,111 @@ def _defer_close_after_timeout(child: Any, child_future: Any) -> None: _resweep_timer.start() +def _lease_child_credential(child: Any) -> tuple[Any, Optional[str]]: + """Lease a credential from the child's pool (if any) and bind it; ``(pool, lease_id)``.""" + child_pool = getattr(child, "_credential_pool", None) + if child_pool is None: + return None, None + leased_cred_id = child_pool.acquire_lease() + if leased_cred_id is not None: + try: + leased_entry = child_pool.current() + if leased_entry is not None and hasattr(child, "_swap_credential"): + child._swap_credential(leased_entry) + except Exception as exc: + logger.debug("Failed to bind child to leased credential: %s", exc) + return child_pool, leased_cred_id + + +def _make_text_relay(child_progress_cb: Any): + """Stream callback forwarding the child's reply text up the progress relay so + gateway watch windows mirror it live (subagent.text → message.delta). Inert + under CLI/TUI: their progress handlers ignore non-tool events.""" + + def _relay_child_text(delta: str) -> None: + if delta: + _safe_progress(child_progress_cb, "subagent.text", preview=delta) + + return _relay_child_text + + +def _await_child( + child: Any, + goal: str, + ws: "_ChildWorkspace", + relay_child_text: Any, + *, + task_index: int, + subagent_id: Optional[str], + child_start: float, + child_progress_cb: Any, + worktree: _WorktreeReporter, +) -> tuple[Optional[Dict[str, Any]], Optional[_ChildFailure]]: + """Run the child's conversation on a daemon worker and wait for it. + + Returns ``(result, None)`` or ``(None, failure)`` on timeout/exception. + The hard timeout is off by default (``result(timeout=None)`` blocks until + the child finishes; stuck-child protection is the heartbeat). The worker is + a daemon: a timed-out child is abandoned and a stdlib non-daemon worker + would block interpreter exit at atexit-join time. The worker installs a + non-interactive approval callback so dangerous-command prompts never fall + back to ``input()`` and deadlock the parent TUI (deny vs approve follows + delegation.subagent_auto_approve). + """ + from tools.delegate_tool import ( + _get_child_timeout, _get_subagent_approval_callback, _set_subagent_approval_cb, + ) + from tools.daemon_pool import DaemonThreadPoolExecutor + + child_timeout = _get_child_timeout() + executor = DaemonThreadPoolExecutor( + max_workers=1, initializer=_set_subagent_approval_cb, initargs=(_get_subagent_approval_callback(),), + ) + # Worker thread handle so the timeout diagnostic can dump its stack. + worker_thread_holder: Dict[str, Optional[threading.Thread]] = {"t": None} + + def _run_with_thread_capture(): + worker_thread_holder["t"] = threading.current_thread() + from agent.delegation_context import delegated_child_context + + with delegated_child_context(str(getattr(child, "session_id", "") or "")): + return child.run_conversation( + user_message=goal, task_id=ws.child_task_id, stream_callback=relay_child_text, + ) + + future = executor.submit(contextvars.copy_context().run, _run_with_thread_capture) + try: + return future.result(timeout=child_timeout), None + except Exception as exc: + return None, _handle_child_wait_failure( + exc, + child=child, + task_index=task_index, + goal=goal, + subagent_id=subagent_id, + child_future=future, + child_timeout=child_timeout, + child_start=child_start, + child_progress_cb=child_progress_cb, + worker_thread_holder=worker_thread_holder, + worktree=worktree, + ) + finally: + # Shut down without waiting — a child stuck on blocking I/O would hang wait=True forever. + executor.shutdown(wait=False) + + +def _merge_late_steer(result: Dict[str, Any], subagent_id: Optional[str], child: Any) -> None: + """Linearization boundary for registry steering: from here the child cannot + consume another steer. Closing under the registry lock either rejects a + concurrent caller or drains every accepted exact text into the result + before callbacks/result assembly run.""" + late = _close_subagent_steering(subagent_id, child) if subagent_id else None + if late: + existing = result.get("pending_steer") + result["pending_steer"] = f"{existing}\n{late}" if isinstance(existing, str) and existing else late + + def _handle_child_wait_failure( exc: BaseException, *, From 338da30a4528bb623a7e10abdc1dcc42b19972d3 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:50:57 -0700 Subject: [PATCH 06/11] refactor(delegate): _resolve_child_runtime returns AIAgent kwargs (drop _ChildRuntime; routing-filter table); dispatch reuses _detach_child/_signal_child_stop; control actions -> _CONTROL_OUTCOMES table; attribution lookup dedupe --- .../mock._session_db.db_path/140588728862416 | Bin 0 -> 237568 bytes .../140588728862416.fts_rebuild.lock | 0 .../140588728862416.quarantine.lock | 0 .../mock._session_db.db_path/140588740754704 | Bin 0 -> 237568 bytes .../140588740754704.fts_rebuild.lock | 0 .../140588740754704.quarantine.lock | 0 tools/delegate_tool.py | 184 +++++------------- tools/delegate_tool_child_run.py | 4 +- tools/delegate_tool_dispatch.py | 33 +--- tools/delegate_tool_registry.py | 100 ++++------ 10 files changed, 101 insertions(+), 220 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/140588728862416 create mode 100644 MagicMock/mock._session_db.db_path/140588728862416.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/140588728862416.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/140588740754704 create mode 100644 MagicMock/mock._session_db.db_path/140588740754704.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/140588740754704.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/140588728862416 b/MagicMock/mock._session_db.db_path/140588728862416 new file mode 100644 index 0000000000000000000000000000000000000000..960085b500c4fe5d22da52797060bab4be87ef26 GIT binary patch literal 237568 zcmeI4-)|dNcE?G}7G*lNlHFvv*+iRhvI)tx9P5YWA90i{EsYhzGG$X#9AmK_ht>>`Pk|0gApXw&=O@i+4Dr zq+}a1>wbmU*4%sUJ?DPzIrp49RJ3_-U3Zz(uxO^4r`)y&Vs@B98ek$Uwn{^=AoPE3EwyRJz*V;m7EI%?cRS3i_diapROM1lmTIM&>$21*TQJ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fUJC!fK;-Y%_g$(vHaU*%_Uu;Ps@IZ^lQjZAK3CEY#m zs@q0%_KRVw(2?BGo1qI0=z1-5tJ2MNS;`+GnJ?^0cdO+)rRoFew)|jL+AB);%eA*Q zwrWy!<9>Oy`_yZhoGhoiFAujzv+9oi-e6mUzU#-ZC=ksT$XSCkJ8qlvo^*44<7Tn@ z!u3pUc{$y^H{2#&dpK~})PC(4wvbr9;IJk?Bj~Je%}VX2Y0ZlEh~340YGYd1HyqZsVbym7Ugp(IZfR-igY-~dgA55wc)MJ!ZI#xgn&(V| z1f{Lba%D}TG`Upp4(zbp@E&?6YVXlIQD;Tj<-uO+*!6r&PVr)KIj?I$yKC(-le}*^ zA5=~GY_VIql6hu%dFs)#dpg@6WU@jN4{MLsE#DuQHu+epD?ICi1jyZlXN04&rZ>hb zLqg?Vi=Y1DDdnR(OPS{uXQqC#H7J`LzcTbCKVwDsC8-5b>&1)D&r$2eYP`=>+l86z z4=L^_r}5%?SRq;%VPgGod)cqftU>VRy+xcm`8b+$_P4}Rn7zey!4 zTh0ZynCM#dIXpYOCC5BGY#fKDQ}u@5|0llW!1o{k0w4eaAOHd&00JNY0w4eaAn?ab z0Kfn5k9qfCI|zUP2!H?xfB*=900@8p2!H?x{GkN!`~Ut>f*211AOHd&00JNY0w4ea wAOHd&00Lir0{H!ZU;aIUg&+U|AOHd&00JNY0w4eaAOHd&@OcP`zyI%l0VJ*7GXMYp literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/140588728862416.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/140588728862416.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/140588728862416.quarantine.lock b/MagicMock/mock._session_db.db_path/140588728862416.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/140588740754704 b/MagicMock/mock._session_db.db_path/140588740754704 new file mode 100644 index 0000000000000000000000000000000000000000..1b27f54eb27359b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04(`B@yScs)x_)H{1UlUrR)_s+ZO zwh^8EV%RElBscX|=t4ufUJu=>bYnx7@`p&~3%k;tTKRUVc3-+B-=CNEiqgGu{jKU& zU8+^@mDhStyq?L)a=Q1@XnQoP;pp!Tw>9Xyb_|OG(R_iNH8`{5wmI)fH#Vv_ioNHr zWpXPk>E7MZHtE`fq06TBtH-c~#PS7)wfGr9XMKBK>atHgdVqu(l1Wu^aF*uViw|%QGLONAenGNMOR-k_5O<$`x$hvkO%&_7Z8kKTzoFUqbA_fp4hYnPeieJlB( zYRYGez0zx$r&m^H9zL_Dv;AQvD>U(__GsPmy`gE7kEOc8vpz_G+)a2!I4Wy;W4tmX zRPMF-=`WsAKDxb}d3I@T=EqyZvdQr)LtpYUR)k-YS`f8fy!iYawO*{o`%JZ6n8|*h z;*N3}FRn)wqJ=Rg)(^K={OZga7Ei(1q4KE0w4eaAOHd&00JNY0w4eaAOHfNhk*F||Na+XjNo_x literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/140588740754704.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/140588740754704.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/140588740754704.quarantine.lock b/MagicMock/mock._session_db.db_path/140588740754704.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 6eeb863982..7d68a0583f 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -71,6 +71,7 @@ from tools.delegate_tool_config import ( # noqa: F401 _load_config, _merge_request_overrides, _resolve_child_credential_pool, + _require_pinned_command, _resolve_delegation_credentials, _subagent_auto_approve, _subagent_auto_deny, @@ -307,28 +308,19 @@ def _resolve_child_toolsets( return child_toolsets, child_disabled_toolsets -@dataclass -class _ChildRuntime: - """Provider/transport/routing settings resolved for one child AIAgent.""" - - model: Any - provider: Any - base_url: Any - api_key: Any - api_mode: Any - capabilities: Optional[dict] - acp_command: Any - acp_args: list - reasoning: Any - fallback: Any - providers_allowed: Any - providers_ignored: Any - providers_order: Any - provider_sort: Any - provider_require_parameters: Any - provider_data_collection: Any - openrouter_min_coding_score: Any - optional_kwargs: Dict[str, Any] +# OpenRouter routing filters: inherited from the parent, but reset to these +# defaults under a pinned provider — parent filters (e.g. only=["Anthropic"]) +# would silently force the child back onto the parent's provider. +# openrouter_min_coding_score stays inherited: model-gated, no-op elsewhere. +_ROUTING_FILTER_DEFAULTS = ( + ("providers_allowed", None), + ("providers_ignored", None), + ("providers_order", None), + ("provider_sort", None), + ("provider_require_parameters", False), + ("provider_data_collection", ""), +) +_NOUS_PROVIDERS = frozenset({"nous", "nous-portal", "nousresearch"}) def _resolve_child_runtime( @@ -344,8 +336,9 @@ def _resolve_child_runtime( override_max_tokens: Optional[int], override_acp_command: Optional[str], override_acp_args: Optional[List[str]], -) -> _ChildRuntime: - """Resolve the child's credentials, transport and routing: config override > parent inherit. +) -> Dict[str, Any]: + """Resolve the child's credentials, transport and routing (config override > + parent inherit) as ``AIAgent`` keyword arguments. Rules that are easy to break: api_mode is re-derived (not inherited) when the child's provider differs from the parent's or is Nous Portal (dual-wire); @@ -355,22 +348,15 @@ def _resolve_child_runtime( """ effective_model = model or parent_agent.model effective_provider = override_provider or getattr(parent_agent, "provider", None) - effective_base_url = override_base_url or parent_agent.base_url - if not override_base_url: - effective_base_url = _inherit_parent_base_url(parent_agent, effective_base_url) - effective_api_key = override_api_key or parent_api_key - child_capabilities = _inherit_parent_capabilities( - parent_agent, override_provider, override_base_url - ) + effective_base_url = override_base_url or _inherit_parent_base_url(parent_agent, parent_agent.base_url) # api_mode: each provider has its own wire, so a different provider re-derives # (None) instead of inheriting (404s otherwise). Nous Portal is dual-wire # within one provider (anthropic/* → Messages, else chat_completions), so # same-provider inheritance would pin the child on the wrong wire — re-derive. _parent_provider = getattr(parent_agent, "provider", None) or "" - _effective_provider_norm = (effective_provider or "").strip().lower() if override_api_mode is not None: effective_api_mode = override_api_mode - elif _effective_provider_norm in {"nous", "nous-portal", "nousresearch"}: + elif (effective_provider or "").strip().lower() in _NOUS_PROVIDERS: from hermes_cli.providers import nous_api_mode effective_api_mode = nous_api_mode(effective_model) @@ -380,34 +366,23 @@ def _resolve_child_runtime( effective_api_mode = getattr(parent_agent, "api_mode", None) # A pinned transport that cannot run must fail the spawn loudly, never fall # back silently (delegate_task pre-validates; this covers direct callers). - if override_acp_command: - import shutil as _shutil - - if not _shutil.which(override_acp_command): - raise ValueError( - f"Pinned delegation command '{override_acp_command}' was not " - f"found on PATH. Install it or remove delegation.command from " - f"config.yaml." - ) - effective_acp_command = override_acp_command or getattr( - parent_agent, "acp_command", None + _require_pinned_command( + override_acp_command, + f"Pinned delegation command '{override_acp_command}' was not " + f"found on PATH. Install it or remove delegation.command from " + f"config.yaml.", ) + effective_acp_command = override_acp_command or getattr(parent_agent, "acp_command", None) effective_acp_args = list( - override_acp_args - if override_acp_args is not None - else (getattr(parent_agent, "acp_args", []) or []) + override_acp_args if override_acp_args is not None else (getattr(parent_agent, "acp_args", []) or []) ) - # A pinned provider must use direct API calls; inheriting the parent's ACP # transport would bypass the override credentials entirely. if override_provider and not override_acp_command: - effective_acp_command = None - effective_acp_args = [] - + effective_acp_command, effective_acp_args = None, [] if override_acp_command: # Forced ACP transport requires provider copilot-acp for run_agent to init the client. - effective_provider = "copilot-acp" - effective_api_mode = "chat_completions" + effective_provider, effective_api_mode = "copilot-acp", "chat_completions" # Reasoning: delegation.reasoning_effort > parent. Keep the raw value — a # YAML ``false`` must disable thinking, not coerce to "" and inherit. @@ -428,66 +403,32 @@ def _resolve_child_runtime( except Exception as exc: logger.debug("Could not load delegation reasoning_effort: %s", exc) - # Inherit the parent's fallback chain EXCEPT under a pinned provider: a - # mid-run 429/auth failure must not silently reroute the quiet child onto - # the parent's fallbacks. Predictability > liveness for explicit pins. - parent_fallback = ( - None - if override_provider - else (getattr(parent_agent, "_fallback_chain", None) or None) - ) - - # OpenRouter routing filters are inherited, but cleared under a pinned - # provider — parent filters (e.g. only=["Anthropic"]) would silently force - # the child back onto the parent's provider. - child_providers_allowed = getattr(parent_agent, "providers_allowed", None) - child_providers_ignored = getattr(parent_agent, "providers_ignored", None) - child_providers_order = getattr(parent_agent, "providers_order", None) - child_provider_sort = getattr(parent_agent, "provider_sort", None) - child_provider_require_parameters = getattr( - parent_agent, "provider_require_parameters", False - ) - child_provider_data_collection = getattr( - parent_agent, "provider_data_collection", None - ) or "" - child_openrouter_min_coding_score = getattr(parent_agent, "openrouter_min_coding_score", None) - if override_provider: - child_providers_allowed = None - child_providers_ignored = None - child_providers_order = None - child_provider_sort = None - child_provider_require_parameters = False - child_provider_data_collection = "" - # openrouter_min_coding_score stays inherited: model-gated, no-op elsewhere. - + kwargs: Dict[str, Any] = { + "base_url": effective_base_url, + "api_key": override_api_key or parent_api_key, + "model": effective_model, + "provider": effective_provider, + "capabilities": _inherit_parent_capabilities(parent_agent, override_provider, override_base_url), + "api_mode": effective_api_mode, + "acp_command": effective_acp_command, + "acp_args": effective_acp_args, + "reasoning_config": child_reasoning, + # Inherit the parent's fallback chain EXCEPT under a pinned provider: a + # mid-run 429/auth failure must not silently reroute the quiet child onto + # the parent's fallbacks. Predictability > liveness for explicit pins. + "fallback_model": None if override_provider else (getattr(parent_agent, "_fallback_chain", None) or None), + "openrouter_min_coding_score": getattr(parent_agent, "openrouter_min_coding_score", None), + } + for attr, pinned_default in _ROUTING_FILTER_DEFAULTS: + kwargs[attr] = pinned_default if override_provider else getattr(parent_agent, attr, pinned_default) + if not override_provider: + kwargs["provider_data_collection"] = kwargs["provider_data_collection"] or "" child_max_tokens = ( - override_max_tokens - if override_max_tokens is not None - else getattr(parent_agent, "max_tokens", None) + override_max_tokens if override_max_tokens is not None else getattr(parent_agent, "max_tokens", None) ) - child_optional_kwargs: Dict[str, Any] = {} if isinstance(child_max_tokens, int): - child_optional_kwargs["max_tokens"] = child_max_tokens - return _ChildRuntime( - model=effective_model, - provider=effective_provider, - base_url=effective_base_url, - api_key=effective_api_key, - api_mode=effective_api_mode, - capabilities=child_capabilities, - acp_command=effective_acp_command, - acp_args=effective_acp_args, - reasoning=child_reasoning, - fallback=parent_fallback, - providers_allowed=child_providers_allowed, - providers_ignored=child_providers_ignored, - providers_order=child_providers_order, - provider_sort=child_provider_sort, - provider_require_parameters=child_provider_require_parameters, - provider_data_collection=child_provider_data_collection, - openrouter_min_coding_score=child_openrouter_min_coding_score, - optional_kwargs=child_optional_kwargs, - ) + kwargs["max_tokens"] = child_max_tokens + return kwargs def _open_child_session_db(parent_agent) -> Any: @@ -515,7 +456,7 @@ def _open_child_session_db(parent_agent) -> Any: def _construct_child_agent( - rt: _ChildRuntime, + rt: Dict[str, Any], *, task_index: int, max_iterations: int, @@ -545,18 +486,9 @@ def _construct_child_agent( with delegated_child_context(): try: return AIAgent( - base_url=rt.base_url, - api_key=rt.api_key, - model=rt.model, - provider=rt.provider, - capabilities=rt.capabilities, - api_mode=rt.api_mode, - acp_command=rt.acp_command, - acp_args=rt.acp_args, + **rt, max_iterations=max_iterations, - reasoning_config=rt.reasoning, prefill_messages=getattr(parent_agent, "prefill_messages", None), - fallback_model=rt.fallback, enabled_toolsets=child_toolsets, disabled_toolsets=child_disabled_toolsets, quiet_mode=True, @@ -569,12 +501,6 @@ def _construct_child_agent( thinking_callback=child_thinking_cb, session_db=child_session_db, parent_session_id=getattr(parent_agent, "session_id", None), - providers_allowed=rt.providers_allowed, - providers_ignored=rt.providers_ignored, - providers_order=rt.providers_order, - provider_sort=rt.provider_sort, - provider_require_parameters=rt.provider_require_parameters, - provider_data_collection=rt.provider_data_collection, request_overrides=( # honored whenever set, incl. the inherit branch where # _resolve_delegation_credentials already merged OVER the parent's @@ -582,10 +508,8 @@ def _construct_child_agent( if override_request_overrides is not None else ({} if override_provider else dict(getattr(parent_agent, "request_overrides", {}) or {})) ), - openrouter_min_coding_score=rt.openrouter_min_coding_score, tool_progress_callback=child_progress_cb, iteration_budget=None, # fresh budget per subagent - **rt.optional_kwargs, ) except BaseException: if child_session_db is not None: @@ -735,7 +659,7 @@ def _build_child_agent( child._session_init_model_config["_delegate_from"] = parent_sid # Shared pool lets children rotate credentials on rate limits. - child_pool = _resolve_child_credential_pool(rt.provider, parent_agent, rt.base_url) + child_pool = _resolve_child_credential_pool(rt["provider"], parent_agent, rt["base_url"]) if child_pool is not None: child._credential_pool = child_pool diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index 5ed5d0864e..a95c2b10c4 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -93,10 +93,10 @@ def _detach_child(parent_agent: Any, child: Any) -> None: logger.debug("Could not remove child from active_children: %s", e) -def _signal_child_stop(child: Any) -> None: +def _signal_child_stop(child: Any, *reason: str) -> None: """Cooperative interrupt so the child's worker thread can exit cleanly.""" try: - if child is not None and not request_hard_interrupt(child) and hasattr(child, "_interrupt_requested"): + if child is not None and not request_hard_interrupt(child, *reason) and hasattr(child, "_interrupt_requested"): child._interrupt_requested = True except Exception: pass diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index 0aa6b738f7..84d92d5b85 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -12,8 +12,7 @@ import logging from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait from typing import Any, Dict, List, Optional -from agent.interrupt_compat import request_hard_interrupt -from tools.delegate_tool_child_run import _fabricated_entry +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, @@ -228,24 +227,6 @@ def _resolve_async_session_key(parent_agent: Any, origin_ui_session_id: str) -> 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. @@ -349,16 +330,16 @@ def _dispatch_background( 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) + # 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). + for c in child_agents: + _detach_child(parent_agent, c) def _batch_interrupt(): # Cancellation path for the detached batch (owned by the async registry). for c in child_agents: - try: - if not request_hard_interrupt(c, "Async delegation cancelled") and hasattr(c, "_interrupt_requested"): - c._interrupt_requested = True - except Exception: - pass + _signal_child_stop(c, "Async delegation cancelled") goals = [t["goal"] for t in task_list] dispatch = dispatch_async_delegation_batch( diff --git a/tools/delegate_tool_registry.py b/tools/delegate_tool_registry.py index a6e1df794a..21d366eb5d 100644 --- a/tools/delegate_tool_registry.py +++ b/tools/delegate_tool_registry.py @@ -50,21 +50,10 @@ def get_subagent_attribution(task_id: Optional[str]) -> Optional[Dict[str, Any]] if not task_id or not isinstance(task_id, str): return None with _active_subagents_lock: - record = _active_subagents.get(task_id) - if record is not None: - return { - "subagent_id": task_id, - "goal": record.get("goal"), - "delegation_id": record.get("delegation_id"), - } - retained = _recent_subagents.get(task_id) - if retained is not None: - return { - "subagent_id": task_id, - "goal": retained.get("goal"), - "delegation_id": retained.get("delegation_id"), - } - return None + record = _active_subagents.get(task_id) or _recent_subagents.get(task_id) + if record is None: + return None + return {"subagent_id": task_id, "goal": record.get("goal"), "delegation_id": record.get("delegation_id")} def set_spawn_paused(paused: bool) -> bool: @@ -404,54 +393,41 @@ def _handle_control_action( "completion message). Use action='list' to see live children." ) - if action == "stop": - if interrupt_subagent(sid): - return json.dumps( - { - "action": "stop", - "subagent_id": sid, - "status": "interrupt_requested", - "note": ( - "The subagent stops at its next iteration boundary " - "(in-flight tool calls are asked to cancel). Its " - "partial result still re-enters the conversation as a " - "completion message — do not wait or poll." - ), - }, - ensure_ascii=False, - ) + if action == "steer" and not (message or "").strip(): return tool_error( - f"Could not interrupt '{sid}' — it likely finished in the last " - "moment. Its result arrives as a normal completion message." + "action='steer' requires a non-empty 'message' describing the " + "course correction." ) + outcome = _CONTROL_OUTCOMES.get(action) + if outcome is None: + return tool_error(f"Unknown action '{action}'. Use spawn, list, steer, or stop.") + status, note, failure = outcome + ok = interrupt_subagent(sid) if action == "stop" else steer_subagent(sid, message.strip()) + if ok: + return json.dumps({"action": action, "subagent_id": sid, "status": status, "note": note}, ensure_ascii=False) + return tool_error(failure.format(sid=sid)) - if action == "steer": - text = (message or "").strip() - if not text: - return tool_error( - "action='steer' requires a non-empty 'message' describing the " - "course correction." - ) - if steer_subagent(sid, text): - return json.dumps( - { - "action": "steer", - "subagent_id": sid, - "status": "queued", - "note": ( - "Steering text queued. The subagent sees it appended " - "to its next tool result — the current tool call is " - "never cut. If the child finishes before a delivery " - "boundary remains, the text is reported back as " - "missed_steer in its completion entry." - ), - }, - ensure_ascii=False, - ) - return tool_error( - f"Subagent '{sid}' is no longer accepting steering (finishing or " - "already finished). Its result arrives as a normal completion " - "message; re-delegate a follow-up task if more work is needed." - ) - return tool_error(f"Unknown action '{action}'. Use spawn, list, steer, or stop.") +# action -> (success status, success note, failure error template) +_CONTROL_OUTCOMES = { + "stop": ( + "interrupt_requested", + "The subagent stops at its next iteration boundary " + "(in-flight tool calls are asked to cancel). Its " + "partial result still re-enters the conversation as a " + "completion message — do not wait or poll.", + "Could not interrupt '{sid}' — it likely finished in the last " + "moment. Its result arrives as a normal completion message.", + ), + "steer": ( + "queued", + "Steering text queued. The subagent sees it appended " + "to its next tool result — the current tool call is " + "never cut. If the child finishes before a delivery " + "boundary remains, the text is reported back as " + "missed_steer in its completion entry.", + "Subagent '{sid}' is no longer accepting steering (finishing or " + "already finished). Its result arrives as a normal completion " + "message; re-delegate a follow-up task if more work is needed.", + ), +} From 884c69729134c50ca99437efa566a92212b4884f Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:54:15 -0700 Subject: [PATCH 07/11] refactor(delegate): split _finalize_child_results (memory/hooks/cost rollup), lift _create_isolated_worktree and _report_child_done, collapse dead worktree-attach import fallback --- .../mock._session_db.db_path/132161382957648 | Bin 0 -> 237568 bytes .../132161382957648.fts_rebuild.lock | 0 .../132161382957648.quarantine.lock | 0 .../mock._session_db.db_path/132161402292368 | Bin 0 -> 237568 bytes .../132161402292368.fts_rebuild.lock | 0 .../132161402292368.quarantine.lock | 0 tools/delegate_tool_child_run.py | 98 ++++------ tools/delegate_tool_config.py | 3 +- tools/delegate_tool_dispatch.py | 46 ++--- tools/delegate_tool_progress.py | 3 +- tools/delegate_tool_registry.py | 23 +-- tools/delegate_tool_results.py | 175 ++++++++---------- 12 files changed, 153 insertions(+), 195 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/132161382957648 create mode 100644 MagicMock/mock._session_db.db_path/132161382957648.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/132161382957648.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/132161402292368 create mode 100644 MagicMock/mock._session_db.db_path/132161402292368.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/132161402292368.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/132161382957648 b/MagicMock/mock._session_db.db_path/132161382957648 new file mode 100644 index 0000000000000000000000000000000000000000..ccf54b739ff3b41917f5738d5f2db14d5bf0e17c GIT binary patch literal 237568 zcmeI4-)|dNcE?G}7G*lNlHFvv*+iRhvI)tx6ib%nA90i{EsYhzGHFv(9AmK_eS6WOxnL2SI^&Lq{rBWy8&ujE2 z{JKQnoD3i6-*ouBX;uC@{J!ts6RB7K{GU!yRrz`qPsyO#Eu%qlu6D zr11y>|1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d3sQaWu-by?W8Qj<${S*q8{Yin{%3Y!Ov$d+!^Nn-QvDj!h2B{eM5Wu`kTxt3)p zrrKh`w++=WoLR}X3?@}8(VW@)Z^;#@U>Vx0!BDBZAyuk%$z=OsQ&ys{YE9x&(Y&Hu z)R>U;)Fwo|R#Db7OHj<8i(H^oS@o^cHR%m$rCM5-H&*0AVMAV*SL)JAX`^1)Q;iOj zN*hwSQkMx>QMy&D-jN)akSZf`;$hA6Oe>K`!(OU|G zT!=fvzOKz4;WPfa1KxR!8O&w*S!!nOHza?YnD$3VeoO~@ znuyh;O;Mcit}juX1m^r9#mQ&zueVF&?)G26Vj^x>f1sx-8`nk<1r%rMtEAol@;$ zmY37rd&6zgwTAhf`Bs z%EJS)KIMG%>M?BOa>HS58CGLA;ALLT_gtyDJ`etces(a2fNKo3` zC|A}bN|Q?k@4ybr4ez0MqV^uW6LnUUT^{VEj@`(|*yQj1LK_)9S@v!!2-SYi`X_Jqoy27(QNPyf;ct$uXYkFh6G9*;) zwfN~To>D%#vy^#mac1hrn}f2+@hd}L@-tS1Uy@o7wO+jV{2aAjtj7CHwOyFWexKrw zavCqLhZUlQ5hm6Tx0e0t%o-F=!P%ksg=`p{;URq3jmsYqRA;Mn|KK;S{+m>?vgKTG zi;1pPpTo1mTXM|9!^UxVI#qA@{eR+14tx&+AOHd&00JNY0w4eaAOHd&00Mu=1n~R+ z{*ZSMwu1l&fB*=900@8p2!H?xfB*=9!0$@{zyI&|C5Z7L00JNY0w4eaAOHd&00JNY s0wD0^CxGAo_vPOsSO@|j00JNY0w4eaAOHd&00JNY0-uL~`1}9<7sDRkkN^Mx literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/132161382957648.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/132161382957648.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/132161382957648.quarantine.lock b/MagicMock/mock._session_db.db_path/132161382957648.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/132161402292368 b/MagicMock/mock._session_db.db_path/132161402292368 new file mode 100644 index 0000000000000000000000000000000000000000..fb203e163614263ab679f511d33b86685b15acb5 GIT binary patch literal 237568 zcmeI4-)|dNcE?G}7G*lNlHFvv*+iRhvI)sG{XRLCEsYhzGG$X#9AmK_ht>>`Pk|0gApXw&=O@i+4Dr zq+}a1>wbmU*4%sUJ?DPzIrp49RJ3_-U3Zz(wCuL(N(-sSQzuTOz9UJgRO$r%d6oWz zUsvgyli>sXn-0IAXT@QTqg$rZwlroaT}N#(WqwFw_HJf6 zci}?%fvavCESSb&?{t~j7<`;rsmbNKEY-_5*JWuywqUAlR-%!`AH6r7$<58Be|*oI zvrU$eb|?Hd6PqP$l?qvjzI08hRO|AZT$AqBDtF4Y2hwf%fmGhAZ&a!@@Qz%qmpsXE zEi|Gozg?HA8}w&ueO;=_x8#~!U6D7XK*lNPTG1b6TLz2E`|S;%3JGo>5AV^rnWmaxeL=2r`v9;_CW|BLL?20Q5&wl z$3~0I`&09oNmS4s`ODyh9eoHgzKw=@pzKm~36#U;HgVKcSM|EG#h<57dJ*u+mLFAq zEYiBXm~>9XA|Pz-M}X(gg8TbRaICJ~80x%T!W#F|FgSMEfnaT8M|IofNy6DNyfkQs1 zbZpu}F+gMO%8u&n2y=B*o5DFd1!EyhfoGE^C{())i9SZhY1HSFr>11kg&rP@(?Rd- zA0mf}>1LWqoupb zwyl~CaZ`As%{rE1Tb8(!ygiH{rNvBUtKNATW`a?nx~&@qKcmPs_H>Qe!v2R{+p5Eq zu5AqI;_fCi(|N2@IZJ!rupE~%rsjEv?*VjlbX7_R$sVtXJj(6HPf40W2v~oXj;%Mi zy?e~&xmi%|>TZyid`a&)If0?lwBCuQy9c5F`Xl098gm-9-WkX`aT!jHnY2YB1(lzE zJn0?kuRE%#Se`HSTZU%sn+jz>-4M26 znDF5f8pgKT*d;^Bjd!Ea8s$*p{JQC9aLO(NFpe|YW(}f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which re-imports every name (patch targets stay valid). """ from __future__ import annotations diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index 84d92d5b85..7993c795b6 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -32,6 +32,29 @@ def _future_entry(future: Any, idx: int, child: Any) -> Dict[str, Any]: 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"] + 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}" + _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, @@ -111,28 +134,7 @@ def _run_children_parallel( results.append(entry) completed_count += 1 - idx = entry["task_index"] - 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 - _slot = f"{_tag} · {idx+1}/{n_tasks}" if _tag else f"{idx+1}/{n_tasks}" - 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) - if _err_line: - 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) + _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"]) diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py index 1fbfd41417..27a1b3ba72 100644 --- a/tools/delegate_tool_progress.py +++ b/tools/delegate_tool_progress.py @@ -1,7 +1,6 @@ """Child progress relay, console formatting and child system-prompt construction for delegate_task. -Split out of ``tools/delegate_tool.py``; every moved name is re-imported there, so -``tools.delegate_tool.`` keeps resolving (and monkeypatching) as before. +Split out of ``tools/delegate_tool.py``, which re-imports every name (patch targets stay valid). """ from __future__ import annotations diff --git a/tools/delegate_tool_registry.py b/tools/delegate_tool_registry.py index 21d366eb5d..df6d606bb4 100644 --- a/tools/delegate_tool_registry.py +++ b/tools/delegate_tool_registry.py @@ -1,7 +1,6 @@ """Live-subagent registry + model-facing control plane (list/steer/stop) for delegate_task. -Split out of ``tools/delegate_tool.py``; every moved name is re-imported there, so -``tools.delegate_tool.`` keeps resolving (and monkeypatching) as before. +Split out of ``tools/delegate_tool.py``, which re-imports every name (patch targets stay valid). """ from __future__ import annotations @@ -217,6 +216,10 @@ def _capture_gateway_steer_authority( return None, None +# Registry record fields never exposed to the TUI/RPC snapshot. +_PRIVATE_RECORD_KEYS = frozenset({"agent", "owner_session_id", "owner_transport", "owner_session_record", "accepting_steer"}) + + def list_active_subagents() -> List[Dict[str, Any]]: """Snapshot of the currently running subagent tree. @@ -224,21 +227,7 @@ def list_active_subagents() -> List[Dict[str, Any]]: tool_count, status}. Safe to call from any thread — returns a copy. """ with _active_subagents_lock: - return [ - { - k: v - for k, v in r.items() - if k - not in { - "agent", - "owner_session_id", - "owner_transport", - "owner_session_record", - "accepting_steer", - } - } - for r in _active_subagents.values() - ] + return [{k: v for k, v in r.items() if k not in _PRIVATE_RECORD_KEYS} for r in _active_subagents.values()] def _is_descendant_of(child_agent: Any, parent_agent: Any, max_hops: int = 8) -> bool: diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.py index 3963506314..f2b13ec278 100644 --- a/tools/delegate_tool_results.py +++ b/tools/delegate_tool_results.py @@ -1,7 +1,6 @@ """Subagent result post-processing: summary budget/spill, tool-trace summaries, lifecycle hooks and cost rollup. -Split out of ``tools/delegate_tool.py``; every moved name is re-imported there, so -``tools.delegate_tool.`` keeps resolving (and monkeypatching) as before. +Split out of ``tools/delegate_tool.py``, which re-imports every name (patch targets stay valid). """ from __future__ import annotations @@ -83,17 +82,12 @@ def _stringify_tool_content(content: Any) -> str: if isinstance(content, str): return content if isinstance(content, list): - parts = [] - for item in content: - if isinstance(item, dict): - text = item.get("text") - if isinstance(text, str): - parts.append(text) - else: - parts.append(json.dumps(item, ensure_ascii=False, default=str)) - else: - parts.append(str(item)) - return "\n".join(parts) + return "\n".join( + item["text"] if isinstance(item, dict) and isinstance(item.get("text"), str) + else json.dumps(item, ensure_ascii=False, default=str) if isinstance(item, dict) + else str(item) + for item in content + ) if isinstance(content, dict): return json.dumps(content, ensure_ascii=False, default=str) return str(content) @@ -249,12 +243,7 @@ def _looks_like_error_output(content: Any) -> bool: pass first = content.splitlines()[0].strip().lower() if content.splitlines() else "" - return ( - first.startswith("error:") - or first.startswith("failed:") - or first.startswith("traceback ") - or first.startswith("exception:") - ) + return first.startswith(("error:", "failed:", "traceback ", "exception:")) # Hard per-summary character ceiling layered on top of the dynamic @@ -494,6 +483,76 @@ def _parent_finalization_lock(parent_agent) -> threading.RLock: return lock +def _notify_memory_manager(results, task_list, child_by_index, parent_agent) -> None: + memory = getattr(parent_agent, "_memory_manager", None) if parent_agent else None + if not memory: + return + for entry in results: + try: + task_index = entry.get("task_index", -1) + in_range = isinstance(task_index, int) and 0 <= task_index < len(task_list) + memory.on_delegation( + task=task_list[task_index]["goal"] if in_range else "", + result=entry.get("summary", "") or "", + child_session_id=getattr(child_by_index.get(task_index), "session_id", ""), + ) + except Exception: + pass + + +def _fire_subagent_stop_hooks(results, child_by_index, parent_agent) -> float: + """Pop the model-hidden ``_child_role`` / ``_child_cost_usd`` fields from every + entry, fire ``subagent_stop`` per child, and return the summed child cost.""" + try: + from hermes_cli.plugins import invoke_hook as invoke_hook + except Exception: + invoke_hook = None + + children_cost_total = 0.0 + for entry in results: + child_role = entry.pop("_child_role", None) + child_cost = entry.pop("_child_cost_usd", 0.0) + try: + if child_cost: + children_cost_total += float(child_cost) + except (TypeError, ValueError): + pass + if invoke_hook is None: + continue + try: + child = child_by_index.get(entry.get("task_index", -1)) + invoke_hook( + "subagent_stop", + parent_session_id=getattr(parent_agent, "session_id", None), + parent_turn_id=getattr(parent_agent, "_current_turn_id", "") or "", + child_session_id=getattr(child, "session_id", None), + child_role=child_role, + child_summary=entry.get("summary"), + child_status=entry.get("status"), + tool_call_history=_subagent_stop_tool_call_history(entry.get("tool_trace")), + duration_ms=int((entry.get("duration_seconds") or 0) * 1000), + ) + except Exception: + logger.debug("subagent_stop hook invocation failed", exc_info=True) + return children_cost_total + + +def _rollup_children_cost(parent_agent, children_cost_total: float) -> None: + """Fold the children's spend into the parent's session cost (source/status + only set when the parent had none of its own).""" + if children_cost_total <= 0.0: + return + try: + current = float(getattr(parent_agent, "session_estimated_cost_usd", 0.0) or 0.0) + parent_agent.session_estimated_cost_usd = current + children_cost_total + if getattr(parent_agent, "session_cost_source", "none") in {None, "", "none"}: + parent_agent.session_cost_source = "subagent" + if getattr(parent_agent, "session_cost_status", "unknown") in {None, "", "unknown"}: + parent_agent.session_cost_status = "estimated" + except Exception: + logger.debug("Subagent cost rollup failed", exc_info=True) + + def _finalize_child_results( results: List[Dict[str, Any]], task_list: List[Dict[str, Any]], @@ -504,82 +563,8 @@ def _finalize_child_results( with _parent_finalization_lock(parent_agent): _apply_summary_budget(results, parent_agent) child_by_index = {index: child for index, _task, child in children} - - if parent_agent and getattr(parent_agent, "_memory_manager", None): - for entry in results: - try: - task_index = entry.get("task_index", -1) - task_goal = ( - task_list[task_index]["goal"] - if isinstance(task_index, int) - and 0 <= task_index < len(task_list) - else "" - ) - child = child_by_index.get(task_index) - parent_agent._memory_manager.on_delegation( - task=task_goal, - result=entry.get("summary", "") or "", - child_session_id=getattr(child, "session_id", ""), - ) - except Exception: - pass - - parent_session_id = getattr(parent_agent, "session_id", None) - try: - from hermes_cli.plugins import invoke_hook as invoke_hook - except Exception: - invoke_hook = None - - children_cost_total = 0.0 - for entry in results: - child_role = entry.pop("_child_role", None) - child_cost = entry.pop("_child_cost_usd", 0.0) - try: - if child_cost: - children_cost_total += float(child_cost) - except (TypeError, ValueError): - pass - if invoke_hook is None: - continue - try: - child_index = entry.get("task_index", -1) - child = child_by_index.get(child_index) - invoke_hook( - "subagent_stop", - parent_session_id=parent_session_id, - parent_turn_id=getattr(parent_agent, "_current_turn_id", "") or "", - child_session_id=getattr(child, "session_id", None), - child_role=child_role, - child_summary=entry.get("summary"), - child_status=entry.get("status"), - tool_call_history=_subagent_stop_tool_call_history( - entry.get("tool_trace") - ), - duration_ms=int((entry.get("duration_seconds") or 0) * 1000), - ) - except Exception: - logger.debug("subagent_stop hook invocation failed", exc_info=True) - - if children_cost_total > 0.0: - try: - current = float( - getattr(parent_agent, "session_estimated_cost_usd", 0.0) or 0.0 - ) - parent_agent.session_estimated_cost_usd = current + children_cost_total - if getattr(parent_agent, "session_cost_source", "none") in { - None, - "", - "none", - }: - parent_agent.session_cost_source = "subagent" - if getattr(parent_agent, "session_cost_status", "unknown") in { - None, - "", - "unknown", - }: - parent_agent.session_cost_status = "estimated" - except Exception: - logger.debug("Subagent cost rollup failed", exc_info=True) + _notify_memory_manager(results, task_list, child_by_index, parent_agent) + _rollup_children_cost(parent_agent, _fire_subagent_stop_hooks(results, child_by_index, parent_agent)) def _run_child_lifecycle( From e204008f10aab36b321d71dc8fea5e583b00e145 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:57:22 -0700 Subject: [PATCH 08/11] refactor(delegate): _knob() unifies config>env>default int/float knobs; timeout diagnostic sections -> _diag_sizes/_diag_threads + attr table; drop dead _handle_child_wait_failure re-import --- .../mock._session_db.db_path/136309983742096 | Bin 0 -> 237568 bytes .../136309983742096.fts_rebuild.lock | 0 .../136309983742096.quarantine.lock | 0 .../mock._session_db.db_path/136310003043600 | Bin 0 -> 237568 bytes .../136310003043600.fts_rebuild.lock | 0 .../136310003043600.quarantine.lock | 0 tools/delegate_tool.py | 1 - tools/delegate_tool_child_run.py | 167 +++++++++--------- tools/delegate_tool_config.py | 86 +++++---- 9 files changed, 125 insertions(+), 129 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/136309983742096 create mode 100644 MagicMock/mock._session_db.db_path/136309983742096.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/136309983742096.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/136310003043600 create mode 100644 MagicMock/mock._session_db.db_path/136310003043600.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/136310003043600.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/136309983742096 b/MagicMock/mock._session_db.db_path/136309983742096 new file mode 100644 index 0000000000000000000000000000000000000000..762f3ba96b498b08c5e55dddd58cb587e8ece9fc GIT binary patch literal 237568 zcmeI4-)|h(b;ox}iA$|4(N64a9GmgTj=j4PWs#z&AC?(sMULo&sHL=AT2_N#FxW7ifXJ^a_Rh{O zNjvqfqkaiX;@o@gJ?DPzIrp49OLOzyy6!TmVc9L!l@?P^rY0s*-tsac-NJg-_88@%qJ&anEch`hm#-n zN#hX&{$CQ1Pfg_>ET&Vssj-L7I|hZMqIO)%dsZCgIJ#vjElXpD(s9%#Qx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d($Kk6|O18xCvRu(;MTJ zA)#`w#ZQ0nl=9)7rOb1Sv(rD`8k9|rUm5z6pRywSg4BYj_2R|nXQ=gJHQuMH?ZQm< zhZJ{|(|B<`tPm}XFtL8Hz3f+K)}VL_&JM*dWW(SL58=aZT>gllI$Ndt2fuOk-=vb2 zE$4z;OmwaK44xg{l4BkoHjcy7sd~fj{}W$w;Cm1N0T2KI5C8!X009sH0T2KI5cp#z zfZzZ3$Gm&69RxrC1V8`;KmY_l00ck)1V8`;{!jw={eOQbL5v3h5C8!X009sH0T2KI v5C8!X0D&()0sQ{IFa93ELJ$A}5C8!X009sH0T2KI5C8!X_$&m(-~ac&L&)BL literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/136309983742096.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/136309983742096.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/136309983742096.quarantine.lock b/MagicMock/mock._session_db.db_path/136309983742096.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/136310003043600 b/MagicMock/mock._session_db.db_path/136310003043600 new file mode 100644 index 0000000000000000000000000000000000000000..7d1ccd14a961eb95669b47656b12f32381eda69b GIT binary patch literal 237568 zcmeI4-*X$+b;kiwA}Gib?Zgh^*o;?pYyc5uk)nQBmT3nfS2RWxAc3G|O(wIm#9n|K zE_UJF1t~h2@j!O$c9J;L>9jMM)^F`w)Avr^JJZhOB@gX?;Fq@3@l2;LnRI&Y{=!`> zK+;YPIO>;UN!)wSz31G|J?EZt7c@8SuInz7nwH&GU1=%xcKd;iC z@arOdb3A;Yf79XjXFmPxM)L5)+hpYg6Mv%j1D@7d3eKR5N8sSl?< z9FWE%2>ib!AfKGh-Cs(lbW>vwoOcWgNk#3tmiMeU%yD$fRN9ut45jO+Ev76EY0Tcq zOy|y>OW$|ZErSKqIP9G+GaG}CGb=T@RF|cC>BhP&4agQuwaw;fWbr5OO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lztcO#S}!Us0p@_0iqeGtaEd&3t^@we?nu*=^=HYKu8a z({&WyW~*(b+tE~)gdab;+CfB5}dB})t>1LfIHt($R0o9vQ!!liFy7Q82 zS%zY&Z5DjnPz}SGmu$;mQneDznZ5U>T#*Wvp}iaomC74ZrCOIvwih;KCHkt?BrX-r zE6PQU2}w_FLey&&Wj(V5#r(O*1xl4w-#T5BUYAy?rFD5@MJ^OJV;j^ z=rXCaA(bn2nSd3go3-j~$#Ds((q^veY2s@b@f$TopNRMgB!1TG5seO4vJ~rbeQdi0nP2v6{3giWA=T6^fIG`5gZBR%v}x-jE9ZDnE~d6|ZN>iF&86XL2hm>E2ma z-7=!HUkqD?j^w7^3SDSO*Q=phm2RxdQvLwRd|^krQ!C#t)$U8TBf5XMzQzY zwM=e#Io-QE+9q9lFm&0}{>l+-A+dbHVJ&_}&{^M}mpU!eniuU6yNiR=PQ8-Jz46Au z)Kr)9@Q|!eIbXec1RJ^BXjof@)z}GmnO8Hp%a>=~Pmkm^%#gr@x5~BpW@%ljd(JdW zP}bxksJlsniyOEE{DPAlt=XEV;cdZ>}lJ_m= zgQ_W?E%r)RGEXfp&pdp3S7&>}Ojc;(QSH&X<$FWZCLc?6g=c+`0J)p+jBr@i^u~B) zNT}Rv@zY;CrF?k%a^{((xtX7B4$CG-uMB<3&shp9TK20mYgjx5XNTe!vSDzBhwwo+E`LN&ovqUSgWtFYZ&Jz1 zmUF=^Cc0LA0nZL^$uSQP8zdY< z!0-S2W8OX34gw$m0w4eaAOHd&00JNY0w4eae<%U`{=YwzAjX3L2!H?xfB*=900@8p v2!H?xfWTLu0Dk}9SAUOSAqao~2!H?xfB*=900@8p2!H?xd=UcT@BjN>oM+&- literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/136310003043600.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/136310003043600.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/136310003043600.quarantine.lock b/MagicMock/mock._session_db.db_path/136310003043600.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 7d68a0583f..e24f6a3c88 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -47,7 +47,6 @@ from tools.delegate_tool_child_run import ( # noqa: F401 _dump_subagent_timeout_diagnostic, _emit_child_complete, _fabricated_entry, - _handle_child_wait_failure, _lease_child_credential, _make_text_relay, _merge_late_steer, diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index c2293846eb..d2b4b3a5d0 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -112,6 +112,72 @@ def _format_thread_stack(frame: Any, indent: str) -> List[str]: ] +_DIAG_CHILD_ATTRS = ( + "model", "provider", "api_mode", "base_url", "max_iterations", + "quiet_mode", "skip_memory", "skip_context_files", "platform", + "_delegate_role", "_delegate_depth", +) + + +def _diag_sizes(child: Any) -> List[str]: + lines: List[str] = ["## Prompt / schema sizes"] + try: + sys_prompt = getattr(child, "ephemeral_system_prompt", None) or getattr(child, "system_prompt", None) or "" + lines.append(f" system_prompt_bytes: {len(sys_prompt.encode('utf-8')) if isinstance(sys_prompt, str) else 'n/a'}") + lines.append(f" system_prompt_chars: {len(sys_prompt) if isinstance(sys_prompt, str) else 'n/a'}") + except Exception as exc: + lines.append(f" system_prompt: ") + try: + tools_schema = getattr(child, "tools", None) + if tools_schema is not None: + lines.append(f" tool_schema_count: {len(tools_schema)}") + lines.append(f" tool_schema_bytes: {len(json.dumps(tools_schema, default=str).encode('utf-8'))}") + except Exception as exc: + lines.append(f" tool_schema: ") + return lines + + +def _diag_threads(worker_thread: Optional[threading.Thread]) -> List[str]: + """Worker stack plus all other live threads (bounded to 40): the worker is + often parked on a helper thread, so a pre-HTTP wedge is indistinguishable + from a slow provider without the full picture.""" + import sys as _sys + import threading as _threading + + lines = ["## Worker thread stack at timeout"] + frames = _sys._current_frames() + if worker_thread is not None and worker_thread.is_alive(): + worker_frame = frames.get(worker_thread.ident) + lines.extend( + _format_thread_stack(worker_frame, " ") if worker_frame is not None + else [" "] + ) + elif worker_thread is None: + lines.append(" ") + else: + lines.append(" ") + lines += ["", "## All thread stacks at timeout"] + try: + frames = _sys._current_frames() + by_ident = {th.ident: th for th in _threading.enumerate() if th.ident} + worker_ident = worker_thread.ident if worker_thread else None + dumped = 0 + for ident, frame in frames.items(): + if ident == worker_ident: + continue # already dumped above + if dumped >= 40: + lines.append(f" <{len(frames) - dumped - 1} more threads omitted>") + break + th = by_ident.get(ident) + name = th.name if th else f"ident={ident}" + lines.append(f" --- {name}{' daemon' if (th and th.daemon) else ''} ---") + lines.extend(_format_thread_stack(frame, " ")) + dumped += 1 + except Exception as exc: + lines.append(f" ") + return lines + + def _dump_subagent_timeout_diagnostic( *, child: Any, @@ -130,8 +196,6 @@ def _dump_subagent_timeout_diagnostic( try: from hermes_constants import get_hermes_home import datetime as _dt - import sys as _sys - import threading as _threading logs_dir = get_hermes_home() / "logs" try: @@ -159,97 +223,32 @@ def _dump_subagent_timeout_diagnostic( "", "## Child config", ] - _w = lines.append - for attr in ( - "model", "provider", "api_mode", "base_url", "max_iterations", - "quiet_mode", "skip_memory", "skip_context_files", "platform", - "_delegate_role", "_delegate_depth", - ): + for attr in _DIAG_CHILD_ATTRS: try: - _w(f" {attr}: {getattr(child, attr, None)!r}") + lines.append(f" {attr}: {getattr(child, attr, None)!r}") except Exception: - _w(f" {attr}: ") - _w("") - - _w("## Toolsets") - _w(f" enabled_toolsets: {getattr(child, 'enabled_toolsets', None)!r}") + lines.append(f" {attr}: ") + lines += ["", "## Toolsets", f" enabled_toolsets: {getattr(child, 'enabled_toolsets', None)!r}"] tool_names = getattr(child, "valid_tool_names", None) if tool_names: - _w(f" loaded tool count: {len(tool_names)}") + lines.append(f" loaded tool count: {len(tool_names)}") try: - _w(f" loaded tools: {sorted(tool_names)}") + lines.append(f" loaded tools: {sorted(tool_names)}") except Exception: pass - _w("") - - _w("## Prompt / schema sizes") + lines += [""] + _diag_sizes(child) + ["", "## Activity summary"] try: - sys_prompt = getattr(child, "ephemeral_system_prompt", None) or getattr(child, "system_prompt", None) or "" - _w(f" system_prompt_bytes: {len(sys_prompt.encode('utf-8')) if isinstance(sys_prompt, str) else 'n/a'}") - _w(f" system_prompt_chars: {len(sys_prompt) if isinstance(sys_prompt, str) else 'n/a'}") + lines += [f" {k}: {v!r}" for k, v in child.get_activity_summary().items()] except Exception as exc: - _w(f" system_prompt: ") - try: - tools_schema = getattr(child, "tools", None) - if tools_schema is not None: - _w(f" tool_schema_count: {len(tools_schema)}") - _w(f" tool_schema_bytes: {len(json.dumps(tools_schema, default=str).encode('utf-8'))}") - except Exception as exc: - _w(f" tool_schema: ") - _w("") - - _w("## Activity summary") - try: - for k, v in child.get_activity_summary().items(): - _w(f" {k}: {v!r}") - except Exception as exc: - _w(f" ") - _w("") - - _w("## Worker thread stack at timeout") - frames = _sys._current_frames() - if worker_thread is not None and worker_thread.is_alive(): - worker_frame = frames.get(worker_thread.ident) - lines.extend( - _format_thread_stack(worker_frame, " ") if worker_frame is not None - else [" "] - ) - elif worker_thread is None: - _w(" ") - else: - _w(" ") - _w("") - - # All other live threads (bounded to 40): the worker is often parked on - # a helper thread, so a pre-HTTP wedge is indistinguishable from a slow - # provider without the full picture. - _w("## All thread stacks at timeout") - try: - frames = _sys._current_frames() - by_ident = {th.ident: th for th in _threading.enumerate() if th.ident} - worker_ident = worker_thread.ident if worker_thread else None - dumped = 0 - for ident, frame in frames.items(): - if ident == worker_ident: - continue # already dumped above - if dumped >= 40: - _w(f" <{len(frames) - dumped - 1} more threads omitted>") - break - th = by_ident.get(ident) - name = th.name if th else f"ident={ident}" - _w(f" --- {name}{' daemon' if (th and th.daemon) else ''} ---") - lines.extend(_format_thread_stack(frame, " ")) - dumped += 1 - except Exception as exc: - _w(f" ") - _w("") - - _w("## Notes") - _w(" This file is written ONLY when a subagent times out with 0 API calls.") - _w(" 0-API-call timeouts mean the child never reached its first LLM request.") - _w(" Common causes: oversized prompt rejected by provider, transport hang,") - _w(" credential resolution stuck. See issue #14726 for context.") - + lines.append(f" ") + lines += [""] + _diag_threads(worker_thread) + [ + "", + "## Notes", + " This file is written ONLY when a subagent times out with 0 API calls.", + " 0-API-call timeouts mean the child never reached its first LLM request.", + " Common causes: oversized prompt rejected by provider, transport hang,", + " credential resolution stuck. See issue #14726 for context.", + ] dump_path.write_text("\n".join(lines), encoding="utf-8") return str(dump_path) except Exception as exc: diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py index f2429684dc..9a27b31d12 100644 --- a/tools/delegate_tool_config.py +++ b/tools/delegate_tool_config.py @@ -71,40 +71,49 @@ def _get_subagent_approval_callback(): return _subagent_auto_deny +def _knob(key: str, env_var: str, parse, default, warn_invalid): + """delegation. > > default. A config value that fails ``parse`` + calls ``warn_invalid(value)`` and yields the default; an env value that fails + is silently ignored.""" + val = _cfg().get(key) + if val is not None: + try: + return parse(val) + except (TypeError, ValueError): + warn_invalid(val) + return default + env_val = os.getenv(env_var) + if env_val: + try: + return parse(env_val) + except (TypeError, ValueError): + pass + return default + + def _get_max_concurrent_children() -> int: """delegation.max_concurrent_children > DELEGATION_MAX_CONCURRENT_CHILDREN env > 10. Floor of 1 is the only bound enforced; there is no ceiling. """ - val = _cfg().get("max_concurrent_children") - if val is not None: - try: - result = max(1, int(val)) - except (TypeError, ValueError): + result = _knob( + "max_concurrent_children", "DELEGATION_MAX_CONCURRENT_CHILDREN", lambda v: max(1, int(v)), + _DEFAULT_MAX_CONCURRENT_CHILDREN, + lambda val: logger.warning( + "delegation.max_concurrent_children=%r is not a valid integer; using default %d", + val, _DEFAULT_MAX_CONCURRENT_CHILDREN, + ), + ) + if result > 10 and _cfg().get("max_concurrent_children") is not None: + global _HIGH_CONCURRENCY_WARNED + if not _HIGH_CONCURRENCY_WARNED: + _HIGH_CONCURRENCY_WARNED = True logger.warning( - "delegation.max_concurrent_children=%r is not a valid integer; " - "using default %d", - val, - _DEFAULT_MAX_CONCURRENT_CHILDREN, + "delegation.max_concurrent_children=%d: each child consumes API tokens " + "independently. High values multiply cost linearly.", + result, ) - return _DEFAULT_MAX_CONCURRENT_CHILDREN - if result > 10: - global _HIGH_CONCURRENCY_WARNED - if not _HIGH_CONCURRENCY_WARNED: - _HIGH_CONCURRENCY_WARNED = True - logger.warning( - "delegation.max_concurrent_children=%d: each child consumes API tokens " - "independently. High values multiply cost linearly.", - result, - ) - return result - env_val = os.getenv("DELEGATION_MAX_CONCURRENT_CHILDREN") - if env_val: - try: - return max(1, int(env_val)) - except (TypeError, ValueError): - return _DEFAULT_MAX_CONCURRENT_CHILDREN - return _DEFAULT_MAX_CONCURRENT_CHILDREN + return result def _get_worktree_isolation() -> bool: @@ -151,23 +160,12 @@ def _get_child_timeout() -> Optional[float]: staleness monitor. delegation.child_timeout_seconds > 0 opts in (floor 30 s); 0 or negative disables. Env fallback: DELEGATION_CHILD_TIMEOUT_SECONDS. """ - val = _cfg().get("child_timeout_seconds") - if val is not None: - try: - return _parse_timeout(val) - except (TypeError, ValueError): - logger.warning( - "delegation.child_timeout_seconds=%r is not a valid number; " - "using default (no timeout)", - val, - ) - env_val = os.getenv("DELEGATION_CHILD_TIMEOUT_SECONDS") - if env_val: - try: - return _parse_timeout(env_val) - except (TypeError, ValueError): - pass - return DEFAULT_CHILD_TIMEOUT + return _knob( + "child_timeout_seconds", "DELEGATION_CHILD_TIMEOUT_SECONDS", _parse_timeout, DEFAULT_CHILD_TIMEOUT, + lambda val: logger.warning( + "delegation.child_timeout_seconds=%r is not a valid number; using default (no timeout)", val, + ), + ) def _get_max_spawn_depth() -> int: From 016f31375d09527fb959993d13276747ce00f992 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:59:26 -0700 Subject: [PATCH 09/11] refactor(delegate): join wrapped logical lines that fit in 120 cols (AST-identical) --- .../mock._session_db.db_path/126670844021456 | Bin 0 -> 237568 bytes .../126670844021456.fts_rebuild.lock | 0 .../126670844021456.quarantine.lock | 0 .../mock._session_db.db_path/126670871778000 | Bin 0 -> 237568 bytes .../126670871778000.fts_rebuild.lock | 0 .../126670871778000.quarantine.lock | 0 tools/delegate_tool.py | 59 ++++-------------- tools/delegate_tool_child_run.py | 30 ++------- tools/delegate_tool_config.py | 42 +++---------- tools/delegate_tool_dispatch.py | 5 +- tools/delegate_tool_progress.py | 22 ++----- tools/delegate_tool_registry.py | 22 ++----- tools/delegate_tool_results.py | 24 ++----- 13 files changed, 42 insertions(+), 162 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/126670844021456 create mode 100644 MagicMock/mock._session_db.db_path/126670844021456.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/126670844021456.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/126670871778000 create mode 100644 MagicMock/mock._session_db.db_path/126670871778000.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/126670871778000.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/126670844021456 b/MagicMock/mock._session_db.db_path/126670844021456 new file mode 100644 index 0000000000000000000000000000000000000000..d0a247e7aa222146d49cee14efb471e26a1d1b4b GIT binary patch literal 237568 zcmeI4-)|h(b;ox_iA$|4(N64a9GmgTj=j4PX_2C+AC?(sMULo&s9kBfv@8U{V7PO+ zoN#t#Ju^#+P5@(N$8M2dD2fIRTEDe#P2Y>W7ifXJ^a_Rh{O zNjvqfqkaiX;@o@gJ?DPzIrp49OLODiy6!S*+p=4#D=ns;Or1E9`nDvcQmGU4=Qa8h zeqEw(PKFQkZ#w)w{qxg*8GhgQ?}^l_fALSJsBvQY6W(=Y`gha+J^jha7bbo^@!`aW zebRUYf&Z5T!Oz$&`fwjoG`I z$=rnt=?AX5Ww2lxhrQEbW~2XcYNaNZ>atWX-CUQYKG}k)w%9C*W{XXw^qJWsy&cy%MYZ|X1!Xj(7-!#r9SIP zhHIe_b@}bORH@RR&G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L> z-c`4Z=uqY7C7sy$IGdpgZ^R9Gry?V3Q zec^g0x4fM0-WzU{u00&MY-+!D3|mMnUvOBHpAmG{w`Qew)3jzqd&KTyKeaR0GPyV2 zIGmd5QXU?V^(p78SC3&Mmm3ai%di@|0Wb4vCbzUS^?rINuR(?cCcIUy)i+D)Qr&Z= zL4wleM!B*kQJP#Tcn5Y^Zg>y96Seo~ov5>-?DAkQb?inyCZ~9@xSZFupxw20nMvNa zoDZs|e74vvUCBJNygc>j**%@@4>DPyiHEgE>z3~iOq+Zx)fJxgK?3A%!ZX5AS<@Ti zl_8;Wufq_1~nD zl`ZFjTTFDV`V5{O-jZV;9yX4{)2VvH@Bb5Da^QOq009sH0T2KI5C8!X009sH0TB3O zCV=1n_s6_@upIC_#(|0T2KI5C8!X009sH w0T2KI5CDNMJ^}pxzc2nC!9oxK0T2KI5C8!X009sH0T2KI5cn(v#NYq-znz}mivR!s literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/126670844021456.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/126670844021456.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/126670844021456.quarantine.lock b/MagicMock/mock._session_db.db_path/126670844021456.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/126670871778000 b/MagicMock/mock._session_db.db_path/126670871778000 new file mode 100644 index 0000000000000000000000000000000000000000..4e547c761889827e2d97fb094ec8870143c4e869 GIT binary patch literal 237568 zcmeI4-*X$+b;kiwA}Gib?Zgh^*o;?pYyc5tk)mi>mKg^kS2RWxD1o45O`6$RVlTiA z7rXH8f)t(1cpy7=JNY%8PCJun{noxUeedMGGwn?Jkcaj^$V=Plc&5{rOgcSxf8j0` zAZe!t9QDhwB<{WE-gEBfo^#K+3!0mE*L9akP0MbpuC$nXJaytk>f4f(N~KQFpV#P5 z_;s1SIT=3Czv=M%Z~oCg|04W;;NKIem;d}9Pf_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CRKsvel5H7G+NefzX79ZzSEYhwXfFptrOKvM-Ka|@+Yg(v5`AsdBrX-r zE6PQU2}w_FLey&&Wj(V5#r(O*1tQYoF zqsyf7rc|lcWdc@|Zq_z#OO8uOl{Rx#PZM9mkS|()O_p}qfwU~;`IgvhyQ>?TvZJ?l zlzp1Q&KFD4#Rbot2m_h(`ts*tk2KPtj%~GUa-P7PV)ll-R;hYxt5i4TTAi@E&cJM(HL_r@EC zQ&U~a!$Yz@<$U$(F>K^=qhW0uR%18dWnRtXmX>DTPmkm^%#gr@w<@*zR(V~jd(JdW zP}8fzz)j|@1cL9_8+|ywIs?e5BE~XZscQfiWiH^d0h+IU2B(_KdSkpY zBvkIT_~|d6Qa-%BlzC=xZsx~Z!?MZoD??xMQ&xmukXjJ6UcC7H47FaY#`{#YU6{#! zpW=>k8ZWL#6{3YPCe{zOm;LI@8WvB%*`fG_Y#5y3A$-`4%O4R`XRCDo;5V+pn^dy0 z%!iLO set: return expanded -def _preserve_parent_mcp_toolsets( - child_toolsets: List[str], parent_toolsets: set[str] -) -> List[str]: +def _preserve_parent_mcp_toolsets(child_toolsets: List[str], parent_toolsets: set[str]) -> List[str]: """Append any parent MCP toolsets that are missing from a narrowed child.""" preserved = list(child_toolsets) for toolset_name in sorted(parent_toolsets): @@ -276,9 +274,7 @@ def _resolve_child_toolsets( expanded_parent = _expand_parent_toolsets(parent_toolsets) child_toolsets = [t for t in toolsets if t in expanded_parent] if _get_inherit_mcp_toolsets(): - child_toolsets = _preserve_parent_mcp_toolsets( - child_toolsets, parent_toolsets - ) + child_toolsets = _preserve_parent_mcp_toolsets(child_toolsets, parent_toolsets) child_toolsets = _strip_blocked_tools(child_toolsets) elif parent_agent and parent_enabled is not None: child_toolsets = _strip_blocked_tools(parent_enabled) @@ -293,9 +289,7 @@ def _resolve_child_toolsets( else: inherited_disabled = [] if effective_role == "orchestrator": - inherited_disabled = [ - name for name in inherited_disabled if name != "delegation" - ] + inherited_disabled = [name for name in inherited_disabled if name != "delegation"] child_disabled_toolsets = list( dict.fromkeys( inherited_disabled + _blocked_toolsets_for_role(effective_role) + ["kanban"] @@ -395,10 +389,7 @@ def _resolve_child_runtime( if parsed is not None: child_reasoning = parsed else: - logger.warning( - "Unknown delegation.reasoning_effort '%s', inheriting parent level", - delegation_effort, - ) + logger.warning("Unknown delegation.reasoning_effort '%s', inheriting parent level", delegation_effort) except Exception as exc: logger.debug("Could not load delegation reasoning_effort: %s", exc) @@ -447,10 +438,7 @@ def _open_child_session_db(parent_agent) -> Any: _parent_db_path = getattr(parent_session_db, "db_path", None) return get_shared_session_db(_parent_db_path) if _parent_db_path is not None else get_shared_session_db() except Exception: - logger.debug( - "subagent: failed to open dedicated SessionDB; child persistence disabled", - exc_info=True, - ) + logger.debug("subagent: failed to open dedicated SessionDB; child persistence disabled", exc_info=True) return None @@ -737,9 +725,7 @@ def _run_single_child( _child_close_deferred = failure.close_deferred return failure.entry - schema = _validate_child_output_schema( - child, result, task_index, ws.child_task_id, _relay_child_text - ) + schema = _validate_child_output_schema(child, result, task_index, ws.child_task_id, _relay_child_text) _merge_late_steer(result, _subagent_id, child) # Flush any remaining batched progress to gateway @@ -757,9 +743,7 @@ def _run_single_child( return entry except Exception as exc: - _late_pending_steer = ( - _close_subagent_steering(_subagent_id, child) if _subagent_id else None - ) + _late_pending_steer = (_close_subagent_steering(_subagent_id, child) if _subagent_id else None) duration = round(time.monotonic() - child_start, 2) logging.exception(f"[subagent-{task_index}] failed") _safe_progress( @@ -787,9 +771,7 @@ def _run_single_child( ) -def _recover_tasks_from_json_string( - tasks: Any, -) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: +def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: if not isinstance(tasks, str): return None, None raw = tasks.strip() @@ -803,10 +785,7 @@ def _recover_tasks_from_json_string( f"that could not be parsed as JSON ({exc.msg})." ) if not isinstance(parsed, list): - return None, ( - f"tasks must be a JSON array of task objects; parsed " - f"{type(parsed).__name__} instead." - ) + return None, (f"tasks must be a JSON array of task objects; parsed " f"{type(parsed).__name__} instead.") return parsed, None @@ -1280,10 +1259,7 @@ def _build_top_level_description() -> str: "derives this from depth automatically.\n" ) else: - restrictions_rule = ( - "- Children cannot call delegate_task, clarify, memory, or " - "cronjob.\n" - ) + restrictions_rule = ("- Children cannot call delegate_task, clarify, memory, or " "cronjob.\n") return ( "Spawn subagents in isolated contexts; each gets its own conversation, " @@ -1341,19 +1317,14 @@ def _build_dynamic_schema_overrides() -> dict: get_definitions() pass rewrites the description fields to the user's actual limits. """ - overrides_params = { - **DELEGATE_TASK_SCHEMA["parameters"], - } + overrides_params = {**DELEGATE_TASK_SCHEMA["parameters"]} # Deep-copy properties so we don't mutate the static schema dict. overrides_params["properties"] = { k: dict(v) for k, v in DELEGATE_TASK_SCHEMA["parameters"]["properties"].items() } overrides_params["properties"]["tasks"]["description"] = _build_tasks_param_description() - return { - "description": _build_top_level_description(), - "parameters": overrides_params, - } + return {"description": _build_top_level_description(), "parameters": overrides_params} DELEGATE_TASK_SCHEMA = { @@ -1496,11 +1467,7 @@ def _strip_model_hidden_task_fields(tasks: Any) -> Any: if not isinstance(task, dict): stripped_tasks.append(task) continue - stripped = { - key: value - for key, value in task.items() - if key not in _MODEL_HIDDEN_TASK_FIELDS - } + stripped = {key: value for key, value in task.items() if key not in _MODEL_HIDDEN_TASK_FIELDS} changed = changed or len(stripped) != len(task) stripped_tasks.append(stripped) return stripped_tasks if changed else tasks diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index d2b4b3a5d0..adc58821b7 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -50,10 +50,7 @@ def _append_missed_steer(entry: Dict[str, Any], late_steer: Optional[str]) -> No """Record steer text that won the race with the child's failure/timeout.""" if late_steer: entry["missed_steer"] = late_steer - entry["error"] += ( - " [steer did not land before the subagent stopped: " - f"{late_steer}]" - ) + entry["error"] += (" [steer did not land before the subagent stopped: " f"{late_steer}]") def _close_child(child: Any, log_message: str) -> None: @@ -263,11 +260,7 @@ def _start_heartbeat(child: Any, parent_agent: Any, task_index: int) -> tuple: ``try`` so a failed ``start()`` (OS thread exhaustion) leaves ``ident`` None and the finally-path join can be skipped safely. """ - from tools.delegate_tool import ( - _HEARTBEAT_INTERVAL, - _HEARTBEAT_STALE_CYCLES_IDLE, - _HEARTBEAT_STALE_CYCLES_IN_TOOL, - ) + from tools.delegate_tool import (_HEARTBEAT_INTERVAL, _HEARTBEAT_STALE_CYCLES_IDLE, _HEARTBEAT_STALE_CYCLES_IN_TOOL) _heartbeat_stop = threading.Event() # Stale detection: a cycle counts as stale when (tool, iteration, @@ -593,9 +586,7 @@ def _await_child( back to ``input()`` and deadlock the parent TUI (deny vs approve follows delegation.subagent_auto_approve). """ - from tools.delegate_tool import ( - _get_child_timeout, _get_subagent_approval_callback, _set_subagent_approval_cb, - ) + from tools.delegate_tool import (_get_child_timeout, _get_subagent_approval_callback, _set_subagent_approval_cb) from tools.daemon_pool import DaemonThreadPoolExecutor child_timeout = _get_child_timeout() @@ -610,9 +601,7 @@ def _await_child( from agent.delegation_context import delegated_child_context with delegated_child_context(str(getattr(child, "session_id", "") or "")): - return child.run_conversation( - user_message=goal, task_id=ws.child_task_id, stream_callback=relay_child_text, - ) + return child.run_conversation(user_message=goal, task_id=ws.child_task_id, stream_callback=relay_child_text) future = executor.submit(contextvars.copy_context().run, _run_with_thread_capture) try: @@ -702,11 +691,7 @@ def _handle_child_wait_failure( goal=goal, ) if diagnostic_path: - logger.warning( - "Subagent %d 0-API-call timeout — diagnostic written to %s", - task_index, - diagnostic_path, - ) + logger.warning("Subagent %d 0-API-call timeout — diagnostic written to %s", task_index, diagnostic_path) status = "timeout" if is_timeout else "error" _safe_progress( @@ -949,10 +934,7 @@ def _build_result_entry( _missed_steer = result.get("pending_steer") if isinstance(_missed_steer, str) and _missed_steer.strip(): entry["missed_steer"] = _missed_steer - _miss_note = ( - "[steer did not land — the subagent finished before it could " - f"be delivered: {_missed_steer}]" - ) + _miss_note = ("[steer did not land — the subagent finished before it could " f"be delivered: {_missed_steer}]") entry["summary"] = f"{summary}\n\n{_miss_note}" if summary else _miss_note return entry diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py index 9a27b31d12..935a1a4c3c 100644 --- a/tools/delegate_tool_config.py +++ b/tools/delegate_tool_config.py @@ -57,10 +57,7 @@ def _subagent_auto_deny(command: str, description: str, **kwargs) -> str: def _subagent_auto_approve(command: str, description: str, **kwargs) -> str: """Auto-approve (opt-in YOLO via delegation.subagent_auto_approve): returns 'once'.""" - logger.warning( - "Subagent auto-approved dangerous command: %s (%s)", - command, description, - ) + logger.warning("Subagent auto-approved dangerous command: %s (%s)", command, description) return "once" @@ -180,20 +177,11 @@ def _get_max_spawn_depth() -> int: try: ival = int(val) except (TypeError, ValueError): - logger.warning( - "delegation.max_spawn_depth=%r is not a valid integer; " "using default %d", - val, - MAX_DEPTH, - ) + logger.warning("delegation.max_spawn_depth=%r is not a valid integer; " "using default %d", val, MAX_DEPTH) return MAX_DEPTH floored = max(_MIN_SPAWN_DEPTH, ival) if floored != ival: - logger.warning( - "delegation.max_spawn_depth=%d below floor %d; using %d", - ival, - _MIN_SPAWN_DEPTH, - floored, - ) + logger.warning("delegation.max_spawn_depth=%d below floor %d; using %d", ival, _MIN_SPAWN_DEPTH, floored) return floored @@ -217,9 +205,7 @@ def _normalized_runtime_url(value: Any) -> str: return str(value or "").strip().rstrip("/") -def _inherit_parent_capabilities( - parent_agent, override_provider, override_base_url -) -> Optional[dict]: +def _inherit_parent_capabilities(parent_agent, override_provider, override_base_url) -> Optional[dict]: """Parent's endpoint-trust capability map for a child, or None. ``agent.capabilities`` is a trust decision scoped to one provider+endpoint: @@ -231,11 +217,7 @@ def _inherit_parent_capabilities( parent_caps = getattr(parent_agent, "capabilities", None) if not isinstance(parent_caps, dict): return None - return { - key: value - for key, value in parent_caps.items() - if isinstance(key, str) and isinstance(value, bool) - } + return {key: value for key, value in parent_caps.items() if isinstance(key, str) and isinstance(value, bool)} def _inherit_parent_base_url(parent_agent, fallback_base_url: Optional[str]) -> Optional[str]: @@ -294,9 +276,7 @@ def _resolve_child_credential_pool( # Unregistered endpoint (no custom_providers entry): keep the # child's fixed credential rather than inherit the parent's. return None - parent_key = get_custom_provider_pool_key( - getattr(parent_agent, "base_url", None) - ) + parent_key = get_custom_provider_pool_key(getattr(parent_agent, "base_url", None)) if ( parent_pool is not None and parent_provider == "custom" @@ -318,11 +298,7 @@ def _resolve_child_credential_pool( try: return _loaded_pool(effective_provider) except Exception as exc: - logger.debug( - "Could not load credential pool for child provider '%s': %s", - effective_provider, - exc, - ) + logger.debug("Could not load credential pool for child provider '%s': %s", effective_provider, exc) return None @@ -406,9 +382,7 @@ def _direct_endpoint_credentials(cfg_values: dict, explicit_request_overrides) - try: from hermes_cli.runtime_provider import resolve_runtime_provider - runtime = resolve_runtime_provider( - requested=configured_provider, target_model=configured_model - ) + runtime = resolve_runtime_provider(requested=configured_provider, target_model=configured_model) request_overrides = dict(runtime.get("request_overrides") or {}) or None max_output_tokens = runtime.get("max_output_tokens") except Exception as exc: diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index 7993c795b6..b535b65b63 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -107,10 +107,7 @@ def _run_children_parallel( pending = set(futures.keys()) 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: diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py index 27a1b3ba72..1e640990fe 100644 --- a/tools/delegate_tool_progress.py +++ b/tools/delegate_tool_progress.py @@ -111,9 +111,7 @@ _EVENT_HANDLERS: Dict[Any, Optional[str]] = { 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 - ): + 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: @@ -139,11 +137,7 @@ def _build_child_system_prompt( 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.", - "", - f"YOUR TASK:\n{goal}", - ] + parts = ["You are a focused subagent working on a specific delegated task.", "", f"YOUR TASK:\n{goal}"] if context and context.strip(): parts.append(f"\nCONTEXT:\n{context}") if workspace_path and str(workspace_path).strip(): @@ -162,13 +156,9 @@ def _build_child_system_prompt( try: from agent.prompt_builder import build_context_files_prompt - _ctx_files = build_context_files_prompt( - cwd=str(workspace_path), skip_soul=True - ) + _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 - ) + logger.debug("subagent: workspace context-files load failed", exc_info=True) _ctx_files = "" if _ctx_files.strip(): parts.append( @@ -338,9 +328,7 @@ class _ChildProgressRelay: return _batch_prefix(deleg, self.task_index, self.task_count) def _identity_kwargs(self) -> Dict[str, Any]: - kw: Dict[str, Any] = { - "task_index": self.task_index, "task_count": self.task_count, "goal": self.goal_label, - } + kw: Dict[str, Any] = {"task_index": self.task_index, "task_count": self.task_count, "goal": self.goal_label} for key in ("subagent_id", "parent_id", "depth", "model"): if getattr(self, key) is not None: kw[key] = getattr(self, key) diff --git a/tools/delegate_tool_registry.py b/tools/delegate_tool_registry.py index df6d606bb4..d066f6d131 100644 --- a/tools/delegate_tool_registry.py +++ b/tools/delegate_tool_registry.py @@ -198,9 +198,7 @@ def steer_subagent( return False -def _capture_gateway_steer_authority( - owner_session_id: Optional[str], -) -> tuple[Any, Any]: +def _capture_gateway_steer_authority(owner_session_id: Optional[str]) -> tuple[Any, Any]: """Capture exact request transport + live session generation, if any. This is intentionally an in-process bridge, not a serializable capability. @@ -316,12 +314,7 @@ def _owns_subagent_record(record: Dict[str, Any], parent_agent: Any) -> bool: } -def _handle_control_action( - action: str, - subagent_id: Optional[str], - message: Optional[str], - parent_agent: Any, -) -> str: +def _handle_control_action(action: str, subagent_id: Optional[str], message: Optional[str], parent_agent: Any) -> str: """Synchronous control plane for delegate_task: list/steer/stop. Runs in-turn (never backgrounded) and only over subagents descended from @@ -353,11 +346,7 @@ def _handle_control_action( "live_transcript": getattr(agent, "_live_transcript_path", None), } ) - payload: Dict[str, Any] = { - "action": "list", - "count": len(entries), - "subagents": entries, - } + payload: Dict[str, Any] = {"action": "list", "count": len(entries), "subagents": entries} if not entries: payload["note"] = ( "No live subagents right now. Children that already finished " @@ -383,10 +372,7 @@ def _handle_control_action( ) if action == "steer" and not (message or "").strip(): - return tool_error( - "action='steer' requires a non-empty 'message' describing the " - "course correction." - ) + return tool_error("action='steer' requires a non-empty 'message' describing the " "course correction.") outcome = _CONTROL_OUTCOMES.get(action) if outcome is None: return tool_error(f"Unknown action '{action}'. Use spawn, list, steer, or stop.") diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.py index f2b13ec278..b1bcc891ce 100644 --- a/tools/delegate_tool_results.py +++ b/tools/delegate_tool_results.py @@ -116,10 +116,7 @@ _TOOL_INPUT_URL_KEYS = frozenset({"endpoint", "url", "urls"}) def _sanitize_tool_target(key: str, value: Any) -> Any: """Keep bounded side-effect targets while dropping URL secrets.""" if isinstance(value, list): - cleaned = [ - item for item in (_sanitize_tool_target(key, item) for item in value[:16]) - if item is not None - ] + cleaned = [item for item in (_sanitize_tool_target(key, item) for item in value[:16]) if item is not None] return cleaned or None if not isinstance(value, str) or not value: return None @@ -292,9 +289,7 @@ def _spill_summary_to_file(task_index: int, summary: str) -> Optional[str]: return None -def _trim_summary_with_footer( - summary: str, cap: int, task_index: int -) -> tuple[str, Optional[str]]: +def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple[str, Optional[str]]: """Return (model_text, spill_path) for one over-budget summary. Mirrors web_extract's ``_truncate_with_footer``: keep a head+tail window @@ -402,9 +397,7 @@ def _apply_summary_budget(results: List[Dict[str, Any]], parent_agent) -> None: compression/429 death spiral. """ from tools.delegate_tool import _load_config - summaries = [ - r for r in results if isinstance(r, dict) and isinstance(r.get("summary"), str) and r["summary"] - ] + summaries = [r for r in results if isinstance(r, dict) and isinstance(r.get("summary"), str) and r["summary"]] if not summaries: return @@ -427,9 +420,7 @@ def _apply_summary_budget(results: List[Dict[str, Any]], parent_agent) -> None: if len(summary) <= cap: continue original_len = len(summary) - model_text, spill_path = _trim_summary_with_footer( - summary, cap, entry.get("task_index", -1) - ) + model_text, spill_path = _trim_summary_with_footer(summary, cap, entry.get("task_index", -1)) entry["summary"] = model_text entry["summary_truncated"] = True if spill_path: @@ -567,12 +558,7 @@ def _finalize_child_results( _rollup_children_cost(parent_agent, _fire_subagent_stop_hooks(results, child_by_index, parent_agent)) -def _run_child_lifecycle( - task_index: int, - goal: str, - child=None, - parent_agent=None, -) -> Dict[str, Any]: +def _run_child_lifecycle(task_index: int, goal: str, child=None, parent_agent=None) -> Dict[str, Any]: """Run one child and apply the same host lifecycle used by delegate_task.""" from tools.delegate_tool import _run_single_child result = _run_single_child(task_index, goal, child, parent_agent) From 987bc825746eab4984774da79348a3406b572ee0 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 17:03:05 -0700 Subject: [PATCH 10/11] refactor(delegate): compact docstrings/comments by hand (every WHY kept); collapse orchestrator toolset branches --- .../mock._session_db.db_path/123598073808400 | Bin 0 -> 237568 bytes .../123598073808400.fts_rebuild.lock | 0 .../123598073808400.quarantine.lock | 0 .../mock._session_db.db_path/123598093110032 | Bin 0 -> 237568 bytes .../123598093110032.fts_rebuild.lock | 0 .../123598093110032.quarantine.lock | 0 tools/delegate_tool.py | 170 +++++++----------- tools/delegate_tool_child_run.py | 32 ++-- tools/delegate_tool_dispatch.py | 33 ++-- tools/delegate_tool_registry.py | 50 ++---- tools/delegate_tool_results.py | 37 ++-- 11 files changed, 122 insertions(+), 200 deletions(-) create mode 100644 MagicMock/mock._session_db.db_path/123598073808400 create mode 100644 MagicMock/mock._session_db.db_path/123598073808400.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/123598073808400.quarantine.lock create mode 100644 MagicMock/mock._session_db.db_path/123598093110032 create mode 100644 MagicMock/mock._session_db.db_path/123598093110032.fts_rebuild.lock create mode 100644 MagicMock/mock._session_db.db_path/123598093110032.quarantine.lock diff --git a/MagicMock/mock._session_db.db_path/123598073808400 b/MagicMock/mock._session_db.db_path/123598073808400 new file mode 100644 index 0000000000000000000000000000000000000000..f08e555a11dee1df3ed80a00f450e3da38e89e94 GIT binary patch literal 237568 zcmeI4-*X$+b;kiwA}Gib?Zgh^*o;?pYyc5uk)mi>mKg^kS2RWxAc3G|O(wIm#9n|K zE_UJF1t~h2@j!O$cJga7opvVE`mKFy`rgSy-#XLI?{4TWlbV*@R$XZ+^?2&UiPX0xDV0i{pg*tC zpYZE4eRDE=pnuch_u9|@;id5Vfqze=UjFlcIz^3Bv!C#;S7v`V``@#loP2KT*Ha%( zeK;VEM-cdbNkBe5ox8u3PU)t`9ysq96q1VCbuI5%ahT)imZ`KYjTuVUQCmz|9MYJ* zlbOz4xRAc@s@nz&rg7LiU1l~0A7@r;a;Yv$_0o+ESsIWnm};BN)5ziv-6Uz7Ds9!PoEQBfWZ1Mz!YL_9=$LKhX`h4=#lnlDi!((we z=$-vT~vklwJ7eL$dw0ZSzY&Np@!PnVcb^jh}nF>eVZqZ!}azLi^Js_`(j|U zbXVE7RkI;(3U9Po$5L#|5_gifhY_T-n8|F_J1@gbFe+5Hb;ICi6uHKpt}$EK|FCOY zb(qq%jUip!-GpX3k98_%Y401B<5I@dJ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=!t_=Rj3oZ%sS*p15{5maYubpPNtuECpBva;n| zaEpnqRiDAL!&`F9!^6f&csf;Y`2Bz4OAdSw0w4eaAOHd&00JNY0w4eaAOHe?%mncJ z|NfYF54M8<2!H?xfB*=900@8p2!H?xfWRM00Kfn54<(54AOHd&00JNY0w4eaAOHd& t00JQJ#V3H@|M$h;BUlImAOHd&00JNY0w4eaAOHd&00N(dfcX3W{ulJK-_ig8 literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/123598073808400.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/123598073808400.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/123598073808400.quarantine.lock b/MagicMock/mock._session_db.db_path/123598073808400.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/123598093110032 b/MagicMock/mock._session_db.db_path/123598093110032 new file mode 100644 index 0000000000000000000000000000000000000000..d20f981571f0dc5b08cbbdff0bc89a4e4a373b62 GIT binary patch literal 237568 zcmeI4-)|dNcE?G}7G*lNl5DcvY@*FL*@WbpiY?1O<7l(AG*$@9luc1_jKyLw;#^X* z8qP2?L&?f65YS1J7W)fD(E^J$Z|z&R@5R0s*aG{q5AA=jFKtl-DEhM4qUX*p-reIQaccHc-gRa6ceDRJ`|0r)r+z*4(bPu+ z(s%@c|Ca>hlhe5ei|LeZYV4u&u0bKGs9o3co)w2Vj&7Ms+tQe!bRD(Dl!YOU*}IwP z+_`h<2d=thuwWX8z1wAGWAJfixh9wEvQ#hMT$7~%*@CIIS&2p#|K$DYOm1#2{iA!{ zoNcm%v^(Lynb<60t5nEJ^rdT3rCOI)<(hQ2R=HEIJ&>ax5c1u{-S*NXlq+cH>O-fwSMrprv%>+)M%%QBRP zY8XnOVW8O=l;!Ie+E}y68m^-0PRDX|m-a&Fbah&{tF}92ZFw!SJyfy7Or>FU$({g) z-_g`f-Pu-braH0N{07}@2^yj{nrLuo{XUJks&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yc#$R{9JFhW=xh!Aue1Q)ZJjZ{Cd_j2Z@3+4?KFHhhH@+?9`GEY5qpjn! zTg=^<+bOuS{~*}O`@F|NJ9)>TopN>M!<%n-G5x3K4~l8sbeQdi0nP2 zv6{3giWA=TC5n^4oIj>G`3(N`c6n`6-jE9ZDnE;Z6>nt8iF&7RWOB>P>E2ma-7=!H zUkqD?j^w7^3SDSO*XyBMm2a-eQvLwRd|^krTdUkD*B(f>6P!)*=vt{=goKr~+}|ptHVRk~%HZDv9=p-Niv_r>EV^1h{fP&MVV z#a{VJ=GmpCnMcp<>TGYA$qG$8sy$k_e1B-#@T?CKAa@g<5f00m-Wab836*;- ze)@~2l#lLQ&OE<3H}m7oVcF#9m7y>B87smsNiB$4FJ63pj#@8P<9(*uF3e`?qdHVn@25I*R}<&OxevlY63@Eh0QO)6R0axS>V zMAxd%;o0FWIp*PE<0L$tsyF=pKk+38z6Svi009sH0T2KI5C8!X009sHfj?#f`2Bx> z%)1BMK>!3m00ck)1V8`;KmY_l00cnb4<&%#|M!Oy#CQ+@0T2KI5C8!X009sH0T2KI r5cu*F!0-S2^6wEW1OX5L0T2KI5C8!X009sH0T2Lz&qF}`{eS-pOc~#B literal 0 HcmV?d00001 diff --git a/MagicMock/mock._session_db.db_path/123598093110032.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/123598093110032.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/123598093110032.quarantine.lock b/MagicMock/mock._session_db.db_path/123598093110032.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 8dbac85c3b..7c178d40eb 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -2,19 +2,13 @@ """ Delegate Tool -- Subagent Architecture -Spawns child AIAgent instances with isolated context, inherited toolsets, -and their own terminal sessions. Supports single-task and batch (parallel) -modes. Top-level model calls run in the background; orchestrator children -wait for their own workers so they can synthesize the results. - -Each child gets: - - A fresh conversation (no parent history) - - Its own task_id (own terminal session, file ops cache) - - The parent's toolsets, with child-only blocked tools stripped - - A focused system prompt built from the delegated goal + context - -The parent's context only sees the delegation call and the summary result, -never the child's intermediate tool calls or reasoning. +Spawns child AIAgent instances with a fresh conversation, their own task_id +(terminal session, file-ops cache), the parent's toolsets minus child-blocked +tools, and a focused system prompt built from goal + context. Single-task and +batch (parallel) modes; top-level model calls run in the background while +orchestrator children wait for their own workers. The parent only ever sees +the delegation call and the summary result, never the child's intermediate +tool calls or reasoning. """ import json @@ -32,10 +26,9 @@ from utils import is_truthy_value logger = logging.getLogger(__name__) -# The delegate_tool_* siblings hold the pieces split out of this module. Every -# moved name is re-imported here so ``tools.delegate_tool.`` keeps -# resolving for callers and for tests that patch it. Mutable flag globals -# (_spawn_paused, *_WARNED) live only in their owning module. +# The delegate_tool_* siblings hold the pieces split out of this module; every +# moved name is re-imported so ``tools.delegate_tool.`` keeps resolving for +# callers and patching tests. Mutable flag globals live only in their owning module. from tools.delegate_tool_child_run import ( # noqa: F401 _WorktreeReporter, _append_missed_steer, @@ -133,8 +126,6 @@ DELEGATE_BLOCKED_TOOLS = frozenset( # Nested delegation is granted by depth/role in _build_child_agent, never by the # model naming toolsets (there is no model-facing toolsets argument). - - def _normalize_role(r: Optional[str]) -> str: """'leaf' | 'orchestrator'; None/empty/unknown -> 'leaf' (unknown warns).""" if r is None or not r: @@ -246,20 +237,18 @@ def _resolve_child_toolsets( """Return ``(enabled_toolsets, disabled_toolsets)`` for a child. Children never gain tools the parent lacks: explicit ``toolsets`` are - intersected with the parent's (composite-expanded) set, otherwise the - parent's enabled set is inherited. Blocked tools are stripped twice — whole - blocked toolsets here, and exact one-tool deny toolsets via - ``disabled_toolsets`` so blocked names inside mixed bundles (hermes-cli) - are subtracted AFTER composite expansion and survive registry refreshes. - Orchestrators get ``delegation`` re-added unconditionally (role-granted, - not inherited). + intersected with the parent's (composite-expanded) set, else the parent's + enabled set is inherited. Blocked tools are stripped twice — whole blocked + toolsets here, and exact one-tool deny toolsets via ``disabled_toolsets`` so + blocked names inside mixed bundles (hermes-cli) are subtracted AFTER + composite expansion and survive registry refreshes. Orchestrators get + ``delegation`` re-added unconditionally (role-granted, not inherited). """ # enabled_toolsets=None means "all tools", so derive from loaded tool names. parent_enabled = getattr(parent_agent, "enabled_toolsets", None) if parent_enabled is not None: parent_toolsets = set(parent_enabled) elif parent_agent and hasattr(parent_agent, "valid_tool_names"): - # enabled_toolsets is None (all tools) — derive from loaded tool names import model_tools parent_toolsets = { @@ -284,20 +273,16 @@ def _resolve_child_toolsets( child_toolsets = _strip_blocked_tools(DEFAULT_TOOLSETS) raw_parent_disabled = getattr(parent_agent, "disabled_toolsets", None) - if isinstance(raw_parent_disabled, (list, tuple, set)): - inherited_disabled = [str(name) for name in raw_parent_disabled] - else: - inherited_disabled = [] + inherited_disabled = ( + [str(name) for name in raw_parent_disabled] if isinstance(raw_parent_disabled, (list, tuple, set)) else [] + ) if effective_role == "orchestrator": inherited_disabled = [name for name in inherited_disabled if name != "delegation"] + if "delegation" not in child_toolsets: + child_toolsets.append("delegation") child_disabled_toolsets = list( - dict.fromkeys( - inherited_disabled + _blocked_toolsets_for_role(effective_role) + ["kanban"] - ) + dict.fromkeys(inherited_disabled + _blocked_toolsets_for_role(effective_role) + ["kanban"]) ) - - if effective_role == "orchestrator" and "delegation" not in child_toolsets: - child_toolsets.append("delegation") return child_toolsets, child_disabled_toolsets @@ -789,16 +774,13 @@ def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, return parsed, None -# Placeholder shapes for batch goal validation: bare 'TODO', bare 'task N' -# labels, or goals still carrying unexpanded template markers. -# -# The marker regex is deliberately NARROW: it only fires on snake_case / -# space-separated placeholder identifiers (``, `{file path}`, -# ``) — the shape LLM templates actually leave behind. Bare -# single-word brackets are left alone because legitimate coding goals are -# full of them: generics (`Vec`, `Result`), HTML tags (`
`), -# JSON/dict snippets (`{"key": 1}`), glob braces (`{a,b}`), and f-string -# style (`{i}`) must never be rejected (post-merge audit of #81141). +# Placeholder shapes for batch goal validation: bare 'TODO' / 'task N' labels, +# or unexpanded template markers. The marker regex is deliberately NARROW — +# only snake_case / space-separated placeholder identifiers (``, +# `{file path}`, ``), the shape LLM templates leave behind. Bare +# single-word brackets must never be rejected: legitimate goals are full of +# generics (`Vec`), HTML tags (`
`), dict snippets (`{"key": 1}`), glob +# braces (`{a,b}`) and f-string style (`{i}`). _PLACEHOLDER_GOAL_RE = re.compile(r"^(todo|task\s*\d+)$", re.IGNORECASE) _TEMPLATE_MARKER_RE = re.compile( r"<[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+>" @@ -808,20 +790,14 @@ _MIN_BATCH_GOAL_LEN = 10 def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]: - """Validate a tasks=[...] batch beyond per-task goal presence. + """Validate a tasks=[...] batch beyond per-task goal presence; actionable + error string or None. - Returns an actionable error string, or None when the batch is valid. - - A one-entry array is the canonical single-task shape (the advertised - interface is tasks-only; legacy top-level `goal` is wrapped into a - one-entry batch), so no minimum count is enforced. The placeholder/ - template checks below still run on every entry. - - Duplicate goals are deliberately NOT rejected: identical-goal fan-outs - are a legitimate pattern (best-of-N / ensemble sampling), and blocking - them broke real workflows (post-merge audit of #81141). + No minimum count: a one-entry array is the canonical single-task shape + (legacy top-level `goal` is wrapped into one). Duplicate goals are + deliberately NOT rejected — identical-goal fan-outs (best-of-N / ensemble + sampling) are legitimate and blocking them broke real workflows. """ - for i, task in enumerate(task_list): goal = str(task.get("goal", "")).strip() normalized = " ".join(goal.lower().split()) @@ -1238,11 +1214,8 @@ def delegate_task( def _build_top_level_description() -> str: - """Compose the delegate_task tool description. - - Carries ONLY guidance stated nowhere else in the schema (limits live in - the 'tasks' parameter description, rebuilt per get_definitions() call). - """ + """delegate_task description: ONLY guidance stated nowhere else in the schema + (limits live in the 'tasks' parameter description, rebuilt per get_definitions()).""" try: orchestration_available = _get_max_spawn_depth() >= 2 and _get_orchestrator_enabled() except Exception: @@ -1311,17 +1284,11 @@ def _build_tasks_param_description() -> str: def _build_dynamic_schema_overrides() -> dict: - """Return per-call schema overrides reflecting current config. - - Plugged into ToolEntry.dynamic_schema_overrides so every - get_definitions() pass rewrites the description fields to the user's - actual limits. - """ + """Per-call schema overrides (ToolEntry.dynamic_schema_overrides): every + get_definitions() pass rewrites the descriptions to the user's actual limits.""" overrides_params = {**DELEGATE_TASK_SCHEMA["parameters"]} - # Deep-copy properties so we don't mutate the static schema dict. - overrides_params["properties"] = { - k: dict(v) for k, v in DELEGATE_TASK_SCHEMA["parameters"]["properties"].items() - } + # Copy properties so the static schema dict is never mutated. + overrides_params["properties"] = {k: dict(v) for k, v in DELEGATE_TASK_SCHEMA["parameters"]["properties"].items()} overrides_params["properties"]["tasks"]["description"] = _build_tasks_param_description() return {"description": _build_top_level_description(), "parameters": overrides_params} @@ -1329,14 +1296,11 @@ def _build_dynamic_schema_overrides() -> dict: DELEGATE_TASK_SCHEMA = { "name": "delegate_task", - # NOTE: description / tasks.description / role.description are placeholder - # values. The real text is generated per get_definitions() call by - # _build_dynamic_schema_overrides() (registered via - # dynamic_schema_overrides below) so the model sees the user's actual - # delegation.max_concurrent_children / max_spawn_depth, not the framework - # defaults. Building these lazily (instead of at module import) also - # avoids forcing cli.CLI_CONFIG to load before the test conftest can - # redirect HERMES_HOME. + # description / tasks.description are placeholders: the real text is built per + # get_definitions() call by _build_dynamic_schema_overrides() so the model sees + # the user's actual max_concurrent_children / max_spawn_depth. Lazy (not at + # import) so cli.CLI_CONFIG isn't forced to load before the test conftest + # redirects HERMES_HOME. "description": ( "Spawn one or more subagents in isolated contexts. " "Description is rebuilt at every get_definitions() call to reflect " @@ -1345,11 +1309,9 @@ DELEGATE_TASK_SCHEMA = { "parameters": { "type": "object", "properties": { - # NOTE: the handler also accepts the legacy single-goal shape — - # top-level `goal` (string), `context` (string), `output_schema` - # (object) — wrapped into a one-entry batch at dispatch. Legacy, - # unadvertised (old transcripts/callers only); tasks=[...] is the - # only advertised shape. Do not re-add these to the schema. + # The handler also accepts the legacy single-goal shape (top-level + # `goal`/`context`/`output_schema`), wrapped into a one-entry batch at + # dispatch. Unadvertised on purpose (old transcripts only); do not re-add. "tasks": { "type": "array", "minItems": 1, @@ -1388,18 +1350,14 @@ DELEGATE_TASK_SCHEMA = { }, "required": ["goal"], }, - # No maxItems — the runtime limit is configurable via - # delegation.max_concurrent_children (default 3) and - # enforced with a clear error in delegate_task(). - # NOTE: the handler also accepts a per-task `role` — legacy, - # ignored: delegation capability is depth-derived, not - # caller-declared. Unadvertised on purpose; do not re-add. + # No maxItems — the runtime limit (delegation.max_concurrent_children) + # is enforced with a clear error in delegate_task(). A per-task `role` + # is also accepted — legacy, ignored (capability is depth-derived); + # unadvertised on purpose, do not re-add. "description": "(rebuilt at get_definitions() time)", }, - # NOTE: the handler also accepts `background` (bool) — DEPRECATED, - # ignored: top-level delegations always run in the background. - # Deliberately unadvertised (old transcripts/callers only); do not - # re-add to the schema. + # `background` (bool) is also accepted — DEPRECATED, ignored: top-level + # delegations always run in the background. Unadvertised; do not re-add. "action": { "type": "string", "enum": ["spawn", "list", "steer", "stop"], @@ -1441,18 +1399,14 @@ from tools.registry import registry, tool_error def _model_background_value(args: dict, parent_agent=None) -> bool: """Background flag for the MODEL-facing dispatch path (registry fallback). - Delegations from the top-level agent always run in the background — the - model does not choose. This applies to both a single task and a fan-out - batch (the whole batch is one async unit that joins on all children and - returns one consolidated result). The one - exception is a delegation from an orchestrator subagent (depth > 0), which - needs its workers' results within its own turn. The live path is - ``run_agent._dispatch_delegate_task``; this lambda mirrors it for the rare - case the intercept is bypassed. Direct Python callers of ``delegate_task`` - keep the historical synchronous default. + Top-level delegations always run in the background — the model does not + choose — for single tasks and fan-out batches alike (one async unit, one + consolidated result). The exception is an orchestrator subagent (depth > 0), + which needs its workers' results within its own turn. The live path is + ``run_agent._dispatch_delegate_task``; this mirrors it for the rare case the + intercept is bypassed. Direct Python callers keep the synchronous default. """ - is_subagent = getattr(parent_agent, "_delegate_depth", 0) > 0 - return not is_subagent + return not getattr(parent_agent, "_delegate_depth", 0) > 0 _MODEL_HIDDEN_TASK_FIELDS = {"acp_command", "acp_args"} diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index adc58821b7..a929fb2033 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -502,14 +502,13 @@ def _defer_close_after_timeout(child: Any, child_future: Any) -> None: """Hand ``child.close()`` to a Future done-callback and drain its transports. The interrupt is cooperative: the worker still runs its finally path, so - closing the child now could close SQLite under its final write — the - done-callback is the first safe close boundary. The abandoned worker is - usually parked in an OpenSSL read; NEVER hard-close that transport from this - thread (cross-thread FD release under a live SSL read corrupts native - state) — shutdown() the pooled sockets instead, which settles the read with - EOF so the worker unwinds. One immediate sweep + one delayed re-sweep for a - connection opened in between; a worker that still won't settle keeps its - resources until process exit. + closing now could close SQLite under its final write — the done-callback is + the first safe boundary. The abandoned worker is usually parked in an + OpenSSL read; NEVER hard-close that transport from this thread (cross-thread + FD release under a live SSL read corrupts native state) — shutdown() the + pooled sockets so the read settles with EOF and the worker unwinds. One + immediate sweep + one delayed re-sweep for a connection opened in between; a + worker that still won't settle keeps its resources until process exit. """ child_future.add_done_callback( lambda _done: _close_child(child, "Failed to close timed-out child after worker exit") @@ -575,16 +574,15 @@ def _await_child( child_progress_cb: Any, worktree: _WorktreeReporter, ) -> tuple[Optional[Dict[str, Any]], Optional[_ChildFailure]]: - """Run the child's conversation on a daemon worker and wait for it. + """Run the child's conversation on a daemon worker; ``(result, None)`` or + ``(None, failure)`` on timeout/exception. - Returns ``(result, None)`` or ``(None, failure)`` on timeout/exception. - The hard timeout is off by default (``result(timeout=None)`` blocks until - the child finishes; stuck-child protection is the heartbeat). The worker is - a daemon: a timed-out child is abandoned and a stdlib non-daemon worker - would block interpreter exit at atexit-join time. The worker installs a - non-interactive approval callback so dangerous-command prompts never fall - back to ``input()`` and deadlock the parent TUI (deny vs approve follows - delegation.subagent_auto_approve). + The hard timeout is off by default (``result(timeout=None)`` blocks; stuck + children are the heartbeat's job). Daemon worker: a timed-out child is + abandoned and a non-daemon thread would block interpreter exit at atexit + join. The worker installs a non-interactive approval callback so dangerous + command prompts never fall back to ``input()`` and deadlock the parent TUI + (deny vs approve follows delegation.subagent_auto_approve). """ from tools.delegate_tool import (_get_child_timeout, _get_subagent_approval_callback, _set_subagent_approval_cb) from tools.daemon_pool import DaemonThreadPoolExecutor diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index b535b65b63..0f593f7b82 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -196,15 +196,13 @@ def _resolve_async_wake_sid(origin_wake_sid: str) -> Optional[str]: 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). + Desktop/TUI: the routable key is the durable AIAgent.session_id — compression + can rotate it mid-turn before the TUI-side dict is re-anchored, and a stale + approval-context key would orphan the completion. Gateway chats keep the + platform conversation key (agent:main:...). The CLI has no bound approval + contextvar and no HERMES_SESSION_KEY, so the key resolves empty; its drain + is a positive-ownership filter keyed on the durable session_id, so an empty + key would fail closed — stamp the parent's durable id. """ from tools.approval import get_current_session_key @@ -227,17 +225,12 @@ def _resolve_async_session_key(parent_agent: Any, origin_ui_session_id: str) -> 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. - """ + """Progress token for the async registry's stale monitor: every child's + (api_call_count, current_tool, last_activity_ts). last_activity_ts ticks on + streamed chunks, tool transitions and API-call start/completion, so a child + streaming a long response counts as alive; a fully frozen token past the + threshold means the batch is wedged. ``in_tool`` is True while ANY child is + inside a tool so slow tools get the higher ceiling (mirrors the sync heartbeat).""" parts = [] in_tool = False for c in child_agents: diff --git a/tools/delegate_tool_registry.py b/tools/delegate_tool_registry.py index d066f6d131..50b43b4d93 100644 --- a/tools/delegate_tool_registry.py +++ b/tools/delegate_tool_registry.py @@ -159,20 +159,16 @@ def steer_subagent( owner_transport: Any = None, owner_session_record: Any = None, ) -> bool: - """Queue steering text into a single running subagent without stopping it. + """Queue steering text into a running subagent without stopping it. - The redirection-side mirror of interrupt_subagent(): resolves the live - child in the registry and calls AIAgent.steer(), which appends the text - to the child's last tool result at its next iteration boundary — the - current tool call is never cut. Returns True if a matching subagent - QUEUED the text while the child was still accepting work; False for an - unknown/closed id, an ownership mismatch, a record with no live agent, or - empty text. ``owner_session_id=None`` deliberately preserves the internal - in-process helper contract; gateway callers must pass exact authority. - - Acceptance and completion are linearized by the registry lock. If - acceptance wins but no delivery boundary remains, ``_run_single_child`` - drains the exact text into the completion entry as ``missed_steer``. + Mirror of interrupt_subagent(): calls AIAgent.steer(), which appends the + text to the child's last tool result at its next iteration boundary — the + current tool call is never cut. True iff the text was QUEUED while the child + still accepted work; False for unknown/closed id, ownership mismatch, no + live agent, or empty text. ``owner_session_id=None`` keeps the in-process + helper contract; gateway callers must pass exact authority. Acceptance and + completion are linearized by the registry lock: if acceptance wins but no + delivery boundary remains, the text lands in the entry as ``missed_steer``. """ if not text or not text.strip(): return False @@ -277,24 +273,16 @@ def _resolve_session_lineage(session_id: Optional[str], parent_agent: Any) -> st def _owns_subagent_record(record: Dict[str, Any], parent_agent: Any) -> bool: """True when *parent_agent*'s conversation owns this live-child record. - Two-tier check: - - 1. Object identity — the ``_delegate_parent_ref`` weakref chain stamped - at build time reaches *parent_agent*. Fast path for the common case - where the parent AIAgent object survives the whole run. - 2. Durable conversation lineage — the child was registered with the - owning conversation's durable session id - (``owner_agent_session_id``); match it against the calling parent's - ``session_id``, resolving compression-rotation lineage on both sides. - - Tier 2 exists because the identity chain is BRITTLE across parent-agent - rebuilds: the CLI sets ``self.agent = None`` mid-session (route-signature - change, credential refresh, /model, MoA one-shots) and constructs a NEW - AIAgent for the next turn while the child keeps running with a weakref to - the old object. The delivery path always survived this (it routes by - durable session id); the control path must use the same durable spine or - running children go invisible/unsteerable (observed live: deleg_88454b70 - / sa-0-dc0100f4, 2026-08-17). + Tier 1: object identity — the ``_delegate_parent_ref`` weakref chain reaches + *parent_agent* (fast path while the parent AIAgent survives the run). + Tier 2: durable lineage — the record's ``owner_agent_session_id`` matches the + caller's ``session_id``, resolving compression-rotation lineage on both + sides. Tier 2 exists because the identity chain is BRITTLE across parent + rebuilds: the CLI sets ``self.agent = None`` mid-session (route change, + credential refresh, /model, MoA one-shots) and builds a NEW AIAgent while + the child keeps a weakref to the old one. Delivery always routed by durable + session id; control must use the same spine or running children go + invisible/unsteerable. """ agent = record.get("agent") if _is_descendant_of(agent, parent_agent): diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.py index b1bcc891ce..7c99b982d0 100644 --- a/tools/delegate_tool_results.py +++ b/tools/delegate_tool_results.py @@ -343,19 +343,12 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple[ def _parent_summary_char_budget(parent_agent, n_summaries: int) -> Optional[int]: - """Per-summary character budget sized against the parent's *remaining* - context headroom, split across the batch. - - The overflow this guards against is N summaries entering the parent - context at once (batch fan-out), not any single summary being large. We - take a fraction of the headroom the parent has left (resolved context - length minus what's already in its prompt) and divide it across the batch, - converting tokens→chars at the standard ~4 chars/token estimate. - - Returns the per-summary char budget, or None when the parent's context - state is unknown (no compressor / no token count) — in which case the - caller falls back to the static char ceiling only. - """ + """Per-summary char budget from the parent's *remaining* context headroom + (context length minus prompt tokens minus the compressor's output reserve), + a fraction of it split across the batch at ~4 chars/token. Guards against N + summaries landing at once, not one large summary. None when the parent's + context state is unknown (no compressor / token count) — caller then uses + the static ceiling only.""" try: compressor = getattr(parent_agent, "context_compressor", None) context_length = getattr(compressor, "context_length", None) @@ -383,18 +376,14 @@ def _parent_summary_char_budget(parent_agent, n_summaries: int) -> Optional[int] def _apply_summary_budget(results: List[Dict[str, Any]], parent_agent) -> None: - """Trim subagent summaries in-place so the batch can't overflow the - parent's context window, spilling full text to disk so nothing is lost. + """Trim subagent summaries in-place so a batch can't overflow the parent's + context window; full text is spilled to disk so nothing is lost. - The effective per-summary cap is the MIN of: - - the dynamic headroom budget (remaining parent context ÷ batch size), and - - the static ``delegation.max_summary_chars`` ceiling (0 = disabled). - - When a summary exceeds the cap, its full text is written to a file and the - in-context summary becomes a head slice plus a pointer to that file. This - addresses issue/PR #9126: batch fan-out returned N full summaries verbatim, - blowing the parent context and (on rate-limited providers) triggering a - compression/429 death spiral. + Per-summary cap = MIN(dynamic headroom budget: remaining parent context ÷ + batch size, static ``delegation.max_summary_chars`` ceiling; 0 = disabled). + Over-cap summaries become a head+tail slice plus a pointer to the spill file. + Without this, fan-out returned N full summaries verbatim, blowing the parent + context and (on rate-limited providers) triggering a compression/429 death spiral. """ from tools.delegate_tool import _load_config summaries = [r for r in results if isinstance(r, dict) and isinstance(r.get("summary"), str) and r["summary"]] From 3da2ff88e33438acc61964b515685777f880fb12 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 17:03:55 -0700 Subject: [PATCH 11/11] refactor(delegate): pack re-import block; single blank line between top-level defs (AST-identical) --- tools/delegate_tool.py | 123 +++++-------------------------- tools/delegate_tool_child_run.py | 28 ------- tools/delegate_tool_config.py | 24 ------ tools/delegate_tool_dispatch.py | 10 --- tools/delegate_tool_progress.py | 14 ---- tools/delegate_tool_registry.py | 18 ----- tools/delegate_tool_results.py | 23 ------ 7 files changed, 20 insertions(+), 220 deletions(-) diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 7c178d40eb..0decc82898 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -30,88 +30,39 @@ logger = logging.getLogger(__name__) # moved name is re-imported so ``tools.delegate_tool.`` keeps resolving for # callers and patching tests. Mutable flag globals live only in their owning module. from tools.delegate_tool_child_run import ( # noqa: F401 - _WorktreeReporter, - _append_missed_steer, - _append_sibling_write_reminder, - _attach_child, - _await_child, - _build_result_entry, - _cleanup_child_run, - _dump_subagent_timeout_diagnostic, - _emit_child_complete, - _fabricated_entry, - _lease_child_credential, - _make_text_relay, - _merge_late_steer, - _register_child, - _seed_child_workspace, - _start_heartbeat, + _WorktreeReporter, _append_missed_steer, _append_sibling_write_reminder, _attach_child, + _await_child, _build_result_entry, _cleanup_child_run, _dump_subagent_timeout_diagnostic, + _emit_child_complete, _fabricated_entry, _lease_child_credential, _make_text_relay, + _merge_late_steer, _register_child, _seed_child_workspace, _start_heartbeat, _validate_child_output_schema, ) from tools.delegate_tool_config import ( # noqa: F401 - _DEFAULT_MAX_CONCURRENT_CHILDREN, - _get_child_timeout, - _get_inherit_mcp_toolsets, - _get_max_async_children, - _get_max_concurrent_children, - _get_max_spawn_depth, - _get_orchestrator_enabled, - _get_subagent_approval_callback, - _get_worktree_isolation, - _inherit_parent_base_url, - _inherit_parent_capabilities, - _load_config, - _merge_request_overrides, - _resolve_child_credential_pool, - _require_pinned_command, - _resolve_delegation_credentials, - _subagent_auto_approve, - _subagent_auto_deny, + _DEFAULT_MAX_CONCURRENT_CHILDREN, _get_child_timeout, _get_inherit_mcp_toolsets, + _get_max_async_children, _get_max_concurrent_children, _get_max_spawn_depth, + _get_orchestrator_enabled, _get_subagent_approval_callback, _get_worktree_isolation, + _inherit_parent_base_url, _inherit_parent_capabilities, _load_config, _merge_request_overrides, + _resolve_child_credential_pool, _require_pinned_command, _resolve_delegation_credentials, + _subagent_auto_approve, _subagent_auto_deny, ) from tools.delegate_tool_dispatch import ( # noqa: F401 - _dispatch_background, - _run_children_parallel, + _dispatch_background, _run_children_parallel, ) from tools.delegate_tool_progress import ( # noqa: F401 - DelegateEvent, - SUBAGENT_FAILURE_STATUSES, - _batch_prefix, - _build_child_progress_callback, - _build_child_system_prompt, - _clean_error_text, - _emit_parent_console, - _resolve_workspace_hint, - _safe_progress, - format_batch_tag, - format_subagent_failure_line, + DelegateEvent, SUBAGENT_FAILURE_STATUSES, _batch_prefix, _build_child_progress_callback, + _build_child_system_prompt, _clean_error_text, _emit_parent_console, _resolve_workspace_hint, + _safe_progress, format_batch_tag, format_subagent_failure_line, ) from tools.delegate_tool_registry import ( # noqa: F401 - _CONTROL_ACTIONS, - _active_subagents, - _active_subagents_lock, - _capture_gateway_steer_authority, - _close_subagent_steering, - _handle_control_action, - _is_descendant_of, - _owns_subagent_record, - _register_subagent, - _unregister_subagent, - get_subagent_attribution, - interrupt_subagent, - is_spawn_paused, - list_active_subagents, - set_spawn_paused, - steer_subagent, + _CONTROL_ACTIONS, _active_subagents, _active_subagents_lock, _capture_gateway_steer_authority, + _close_subagent_steering, _handle_control_action, _is_descendant_of, _owns_subagent_record, + _register_subagent, _unregister_subagent, get_subagent_attribution, interrupt_subagent, + is_spawn_paused, list_active_subagents, set_spawn_paused, steer_subagent, ) from tools.delegate_tool_results import ( # noqa: F401 - _apply_summary_budget, - _build_child_preserving_parent_tools, - _finalize_child_results, - _run_child_lifecycle, - _summarize_tool_arguments, + _apply_summary_budget, _build_child_preserving_parent_tools, _finalize_child_results, + _run_child_lifecycle, _summarize_tool_arguments, ) - # Tools that children must never have access to DELEGATE_BLOCKED_TOOLS = frozenset( [ @@ -123,7 +74,6 @@ DELEGATE_BLOCKED_TOOLS = frozenset( ] ) - # Nested delegation is granted by depth/role in _build_child_agent, never by the # model naming toolsets (there is no model-facing toolsets argument). def _normalize_role(r: Optional[str]) -> str: @@ -136,7 +86,6 @@ def _normalize_role(r: Optional[str]) -> str: logger.warning("Unknown delegate_task role=%r, coercing to 'leaf'", r) return "leaf" - def _is_mcp_toolset_name(name: str) -> bool: """Return True for canonical MCP toolsets and their registered aliases.""" if not name: @@ -151,7 +100,6 @@ def _is_mcp_toolset_name(name: str) -> bool: target = None return bool(target and str(target).startswith("mcp-")) - def _expand_parent_toolsets(parent_toolsets: set) -> set: """Add every toolset whose tools are a subset of the parent's tools. @@ -176,7 +124,6 @@ def _expand_parent_toolsets(parent_toolsets: set) -> set: expanded.add(ts_name) return expanded - def _preserve_parent_mcp_toolsets(child_toolsets: List[str], parent_toolsets: set[str]) -> List[str]: """Append any parent MCP toolsets that are missing from a narrowed child.""" preserved = list(child_toolsets) @@ -185,7 +132,6 @@ def _preserve_parent_mcp_toolsets(child_toolsets: List[str], parent_toolsets: se preserved.append(toolset_name) return preserved - DEFAULT_MAX_ITERATIONS = 250 _HEARTBEAT_INTERVAL = 30 # seconds between parent activity heartbeats during delegation # Stale-heartbeat thresholds (cycles of _HEARTBEAT_INTERVAL with no progress). @@ -197,12 +143,10 @@ _HEARTBEAT_STALE_CYCLES_IDLE = 15 # 450s idle between turns → stale _HEARTBEAT_STALE_CYCLES_IN_TOOL = 40 # 1200s stuck on same tool → stale DEFAULT_TOOLSETS = ["terminal", "file", "web"] - def check_delegate_requirements() -> bool: """Delegation has no external requirements -- always available.""" return True - def _strip_blocked_tools(toolsets: List[str]) -> List[str]: """Remove toolsets whose tools are ALL blocked (derived from DELEGATE_BLOCKED_TOOLS so the two can't drift) plus composite toolsets children must never get.""" @@ -216,7 +160,6 @@ def _strip_blocked_tools(toolsets: List[str]) -> List[str]: blocked_toolset_names.add("kanban") return [t for t in toolsets if t not in blocked_toolset_names] - def _blocked_toolsets_for_role(role: str) -> List[str]: """One-tool deny toolsets for the role; passed as ``disabled_toolsets`` so blocked names inside mixed bundles are subtracted AFTER composite expansion.""" @@ -230,7 +173,6 @@ def _blocked_toolsets_for_role(role: str) -> List[str]: and set(defn.get("tools", ())).issubset(blocked_names) ) - def _resolve_child_toolsets( parent_agent, toolsets: Optional[List[str]], effective_role: str ) -> tuple[List[str], List[str]]: @@ -285,7 +227,6 @@ def _resolve_child_toolsets( ) return child_toolsets, child_disabled_toolsets - # OpenRouter routing filters: inherited from the parent, but reset to these # defaults under a pinned provider — parent filters (e.g. only=["Anthropic"]) # would silently force the child back onto the parent's provider. @@ -300,7 +241,6 @@ _ROUTING_FILTER_DEFAULTS = ( ) _NOUS_PROVIDERS = frozenset({"nous", "nous-portal", "nousresearch"}) - def _resolve_child_runtime( parent_agent, delegation_cfg: dict, @@ -405,7 +345,6 @@ def _resolve_child_runtime( kwargs["max_tokens"] = child_max_tokens return kwargs - def _open_child_session_db(parent_agent) -> Any: """DEDICATED SessionDB handle for the child, or None. @@ -426,7 +365,6 @@ def _open_child_session_db(parent_agent) -> Any: logger.debug("subagent: failed to open dedicated SessionDB; child persistence disabled", exc_info=True) return None - def _construct_child_agent( rt: Dict[str, Any], *, @@ -492,7 +430,6 @@ def _construct_child_agent( pass raise - def _announce_child_spawn(child, parent_agent, child_progress_cb, *, goal, subagent_id, parent_subagent_id, role) -> None: """spawn_requested event (now — the child may queue for seconds when the pool is saturated) plus the subagent_start lifecycle hook.""" @@ -512,7 +449,6 @@ def _announce_child_spawn(child, parent_agent, child_progress_cb, *, goal, subag except Exception: logger.debug("subagent_start hook invocation failed", exc_info=True) - def _build_child_agent( task_index: int, goal: str, @@ -642,7 +578,6 @@ def _build_child_agent( ) return child - def _run_single_child( task_index: int, goal: str, @@ -755,7 +690,6 @@ def _run_single_child( close_deferred=_child_close_deferred, ) - def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: if not isinstance(tasks, str): return None, None @@ -773,7 +707,6 @@ def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, return None, (f"tasks must be a JSON array of task objects; parsed " f"{type(parsed).__name__} instead.") return parsed, None - # Placeholder shapes for batch goal validation: bare 'TODO' / 'task N' labels, # or unexpanded template markers. The marker regex is deliberately NARROW — # only snake_case / space-separated placeholder identifiers (``, @@ -788,7 +721,6 @@ _TEMPLATE_MARKER_RE = re.compile( ) _MIN_BATCH_GOAL_LEN = 10 - def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]: """Validate a tasks=[...] batch beyond per-task goal presence; actionable error string or None. @@ -848,7 +780,6 @@ class _Batch: origin_owner_session_record: Any overall_start: float - def _normalize_task_list( goal, context, tasks, output_schema, top_role: str, max_children: int ) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]: @@ -898,7 +829,6 @@ def _normalize_task_list( return None, batch_error return task_list, None - def _coerce_task_schemas( task_list: List[Dict[str, Any]], output_schema: Optional[Dict[str, Any]] ) -> tuple[List[Optional[Dict[str, Any]]], Optional[str]]: @@ -918,7 +848,6 @@ def _coerce_task_schemas( task_schemas.append(coerced_schema) return task_schemas, None - 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: @@ -933,7 +862,6 @@ def _announce_batch(parent_agent, n_tasks: int, live_deleg_id: Optional[str]) -> 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 @@ -950,7 +878,6 @@ def _capture_origin() -> tuple[str, str, Any, Any]: 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]]], @@ -1018,7 +945,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).""" @@ -1033,7 +959,6 @@ def _finalize_live_transcripts(results: list, live_writers: list, live_paths: li 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. @@ -1081,7 +1006,6 @@ def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = True combined["live_transcripts"] = list(batch.live_paths) return combined - def delegate_task( goal: Optional[str] = None, context: Optional[str] = None, @@ -1212,7 +1136,6 @@ def delegate_task( # ── OpenAI function-calling schema ────────────────────────────────────────── - def _build_top_level_description() -> str: """delegate_task description: ONLY guidance stated nowhere else in the schema (limits live in the 'tasks' parameter description, rebuilt per get_definitions()).""" @@ -1268,7 +1191,6 @@ def _build_top_level_description() -> str: "delegation.provider / delegation.model in config.yaml." ) - def _build_tasks_param_description() -> str: """Compose the 'tasks' parameter description with current concurrency limit.""" try: @@ -1282,7 +1204,6 @@ def _build_tasks_param_description() -> str: "is a one-entry array. Required when spawning." ) - def _build_dynamic_schema_overrides() -> dict: """Per-call schema overrides (ToolEntry.dynamic_schema_overrides): every get_definitions() pass rewrites the descriptions to the user's actual limits.""" @@ -1293,7 +1214,6 @@ def _build_dynamic_schema_overrides() -> dict: return {"description": _build_top_level_description(), "parameters": overrides_params} - DELEGATE_TASK_SCHEMA = { "name": "delegate_task", # description / tasks.description are placeholders: the real text is built per @@ -1395,7 +1315,6 @@ DELEGATE_TASK_SCHEMA = { # --- Registry --- from tools.registry import registry, tool_error - def _model_background_value(args: dict, parent_agent=None) -> bool: """Background flag for the MODEL-facing dispatch path (registry fallback). @@ -1408,10 +1327,8 @@ def _model_background_value(args: dict, parent_agent=None) -> bool: """ return not getattr(parent_agent, "_delegate_depth", 0) > 0 - _MODEL_HIDDEN_TASK_FIELDS = {"acp_command", "acp_args"} - def _strip_model_hidden_task_fields(tasks: Any) -> Any: if not isinstance(tasks, list): return tasks diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index a929fb2033..aebace61ab 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -27,12 +27,10 @@ from tools.delegate_tool_results import ( # Log-record parity with the origin module. logger = logging.getLogger("tools.delegate_tool") - def _num(value: Any, default: int = 0) -> int: """int() for counters that may be mocks/None on test doubles.""" return int(value) if isinstance(value, (int, float)) else default - def _fabricated_entry(idx: int, status: str, error: str, child: Any, duration: float = 0) -> Dict[str, Any]: """Result entry for a child that raised, never finished, or was abandoned.""" return { @@ -45,14 +43,12 @@ def _fabricated_entry(idx: int, status: str, error: str, child: Any, duration: f "_child_role": getattr(child, "_delegate_role", None), } - def _append_missed_steer(entry: Dict[str, Any], late_steer: Optional[str]) -> None: """Record steer text that won the race with the child's failure/timeout.""" if late_steer: entry["missed_steer"] = late_steer entry["error"] += (" [steer did not land before the subagent stopped: " f"{late_steer}]") - def _close_child(child: Any, log_message: str) -> None: """Best-effort ``child.close()`` (tool sandboxes, browser daemons, httpx clients).""" try: @@ -62,7 +58,6 @@ def _close_child(child: Any, log_message: str) -> None: except Exception: logger.debug(log_message, exc_info=True) - def _attach_child(parent_agent: Any, child: Any) -> None: """Register the child for parent interrupt propagation.""" if not hasattr(parent_agent, "_active_children"): @@ -74,7 +69,6 @@ def _attach_child(parent_agent: Any, child: Any) -> None: else: parent_agent._active_children.append(child) - def _detach_child(parent_agent: Any, child: Any) -> None: """Remove the child from parent interrupt propagation (no-op if absent).""" if not hasattr(parent_agent, "_active_children"): @@ -89,7 +83,6 @@ def _detach_child(parent_agent: Any, child: Any) -> None: except (ValueError, UnboundLocalError) as e: logger.debug("Could not remove child from active_children: %s", e) - def _signal_child_stop(child: Any, *reason: str) -> None: """Cooperative interrupt so the child's worker thread can exit cleanly.""" try: @@ -98,7 +91,6 @@ def _signal_child_stop(child: Any, *reason: str) -> None: except Exception: pass - def _format_thread_stack(frame: Any, indent: str) -> List[str]: import traceback as _traceback @@ -108,14 +100,12 @@ def _format_thread_stack(frame: Any, indent: str) -> List[str]: for sub in frame_line.rstrip().split("\n") ] - _DIAG_CHILD_ATTRS = ( "model", "provider", "api_mode", "base_url", "max_iterations", "quiet_mode", "skip_memory", "skip_context_files", "platform", "_delegate_role", "_delegate_depth", ) - def _diag_sizes(child: Any) -> List[str]: lines: List[str] = ["## Prompt / schema sizes"] try: @@ -133,7 +123,6 @@ def _diag_sizes(child: Any) -> List[str]: lines.append(f" tool_schema: ") return lines - def _diag_threads(worker_thread: Optional[threading.Thread]) -> List[str]: """Worker stack plus all other live threads (bounded to 40): the worker is often parked on a helper thread, so a pre-HTTP wedge is indistinguishable @@ -174,7 +163,6 @@ def _diag_threads(worker_thread: Optional[threading.Thread]) -> List[str]: lines.append(f" ") return lines - def _dump_subagent_timeout_diagnostic( *, child: Any, @@ -252,7 +240,6 @@ def _dump_subagent_timeout_diagnostic( logger.warning("Subagent timeout diagnostic dump failed: %s", exc) return None - def _start_heartbeat(child: Any, parent_agent: Any, task_index: int) -> tuple: """Build the parent-activity heartbeat thread for one child (not started). @@ -319,7 +306,6 @@ def _start_heartbeat(child: Any, parent_agent: Any, task_index: int) -> tuple: return _heartbeat_stop, threading.Thread(target=_heartbeat_loop, daemon=True) - def _register_child( child: Any, parent_agent: Any, @@ -415,7 +401,6 @@ class _ChildWorkspace: wall_start: float parent_reads_snapshot: list - def _create_isolated_worktree(parent_agent: Any, parent_task_id: Any, subagent_id: Optional[str]): """Opt-in worktree isolation: own git worktree off the parent's HEAD (the child's terminal starts there). Git-only, local-backend-only; failures @@ -444,7 +429,6 @@ def _create_isolated_worktree(parent_agent: Any, parent_task_id: Any, subagent_i logger.debug("worktree isolation setup failed: %s", e) return None - def _seed_child_workspace( child: Any, parent_agent: Any, @@ -497,7 +481,6 @@ class _ChildFailure: entry: Dict[str, Any] close_deferred: bool - def _defer_close_after_timeout(child: Any, child_future: Any) -> None: """Hand ``child.close()`` to a Future done-callback and drain its transports. @@ -533,7 +516,6 @@ def _defer_close_after_timeout(child: Any, child_future: Any) -> None: _resweep_timer.daemon = True _resweep_timer.start() - def _lease_child_credential(child: Any) -> tuple[Any, Optional[str]]: """Lease a credential from the child's pool (if any) and bind it; ``(pool, lease_id)``.""" child_pool = getattr(child, "_credential_pool", None) @@ -549,7 +531,6 @@ def _lease_child_credential(child: Any) -> tuple[Any, Optional[str]]: logger.debug("Failed to bind child to leased credential: %s", exc) return child_pool, leased_cred_id - def _make_text_relay(child_progress_cb: Any): """Stream callback forwarding the child's reply text up the progress relay so gateway watch windows mirror it live (subagent.text → message.delta). Inert @@ -561,7 +542,6 @@ def _make_text_relay(child_progress_cb: Any): return _relay_child_text - def _await_child( child: Any, goal: str, @@ -622,7 +602,6 @@ def _await_child( # Shut down without waiting — a child stuck on blocking I/O would hang wait=True forever. executor.shutdown(wait=False) - def _merge_late_steer(result: Dict[str, Any], subagent_id: Optional[str], child: Any) -> None: """Linearization boundary for registry steering: from here the child cannot consume another steer. Closing under the registry lock either rejects a @@ -633,7 +612,6 @@ def _merge_late_steer(result: Dict[str, Any], subagent_id: Optional[str], child: existing = result.get("pending_steer") result["pending_steer"] = f"{existing}\n{late}" if isinstance(existing, str) and existing else late - def _handle_child_wait_failure( exc: BaseException, *, @@ -753,7 +731,6 @@ class _SchemaOutcome: errors: List[str] retries: int - def _validate_child_output_schema( child: Any, result: Dict[str, Any], task_index: int, child_task_id: str, relay_child_text: Any ) -> _SchemaOutcome: @@ -797,7 +774,6 @@ def _validate_child_output_schema( _schema_valid, _schema_errors = validate_output(_retry_text, _output_schema) return _SchemaOutcome(_output_schema, _schema_valid, _schema_errors, 1) - def _build_tool_trace(messages: Any) -> list[Dict[str, Any]]: """Tool trace from the child's conversation messages, pairing parallel tool calls with their results by tool_call_id.""" @@ -834,7 +810,6 @@ def _build_tool_trace(messages: Any) -> list[Dict[str, Any]]: tool_trace[-1].update(result_meta) # no tool_call_id: pair with the latest call return tool_trace - def _build_result_entry( child: Any, result: Dict[str, Any], @@ -936,7 +911,6 @@ def _build_result_entry( entry["summary"] = f"{summary}\n\n{_miss_note}" if summary else _miss_note return entry - def _append_sibling_write_reminder(entry: Dict[str, Any], ws: _ChildWorkspace) -> None: """Warn the parent when this child wrote files the parent had already read. @@ -964,7 +938,6 @@ def _append_sibling_write_reminder(entry: Dict[str, Any], ws: _ChildWorkspace) - except Exception: logger.debug("file_state sibling-write check failed", exc_info=True) - def _emit_child_complete( child: Any, result: Dict[str, Any], @@ -1014,7 +987,6 @@ def _emit_child_complete( pass _safe_progress(child_progress_cb, "subagent.complete", **complete_kwargs) - def _cleanup_child_run( child: Any, parent_agent: Any, diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py index 935a1a4c3c..0cdde7c160 100644 --- a/tools/delegate_tool_config.py +++ b/tools/delegate_tool_config.py @@ -30,7 +30,6 @@ _LEGACY_MAX_ASYNC_WARNED = False # opts back in. DEFAULT_CHILD_TIMEOUT: Optional[float] = None - def _cfg() -> dict: """The ``delegation`` section, read through the origin so tests can patch it.""" from tools.delegate_tool import _load_config @@ -54,20 +53,17 @@ def _subagent_auto_deny(command: str, description: str, **kwargs) -> str: ) return "deny" - def _subagent_auto_approve(command: str, description: str, **kwargs) -> str: """Auto-approve (opt-in YOLO via delegation.subagent_auto_approve): returns 'once'.""" logger.warning("Subagent auto-approved dangerous command: %s (%s)", command, description) return "once" - def _get_subagent_approval_callback(): """Callback for subagent worker threads per delegation.subagent_auto_approve (default False).""" if is_truthy_value(_cfg().get("subagent_auto_approve", False)): return _subagent_auto_approve return _subagent_auto_deny - def _knob(key: str, env_var: str, parse, default, warn_invalid): """delegation. > > default. A config value that fails ``parse`` calls ``warn_invalid(value)`` and yields the default; an env value that fails @@ -87,7 +83,6 @@ def _knob(key: str, env_var: str, parse, default, warn_invalid): pass return default - def _get_max_concurrent_children() -> int: """delegation.max_concurrent_children > DELEGATION_MAX_CONCURRENT_CHILDREN env > 10. @@ -112,7 +107,6 @@ def _get_max_concurrent_children() -> int: ) return result - def _get_worktree_isolation() -> bool: """delegation.worktree_isolation (bool, default False). @@ -122,7 +116,6 @@ def _get_worktree_isolation() -> bool: """ return bool(_cfg().get("worktree_isolation", False)) - def _get_max_async_children() -> int: """Concurrency cap for background delegations == delegation.max_concurrent_children. @@ -142,13 +135,11 @@ def _get_max_async_children() -> int: ) return _get_max_concurrent_children() - def _parse_timeout(raw: Any) -> Optional[float]: """Seconds → None (<= 0 disables) or max(30, value). Raises on non-numeric.""" parsed = float(raw) return None if parsed <= 0 else max(30.0, parsed) - def _get_child_timeout() -> Optional[float]: """Hard wall-clock cap for one child, or None (default: no timeout). @@ -164,7 +155,6 @@ def _get_child_timeout() -> Optional[float]: ), ) - def _get_max_spawn_depth() -> int: """delegation.max_spawn_depth floored at 1 (no ceiling). @@ -184,7 +174,6 @@ def _get_max_spawn_depth() -> int: logger.warning("delegation.max_spawn_depth=%d below floor %d; using %d", ival, _MIN_SPAWN_DEPTH, floored) return floored - def _get_orchestrator_enabled() -> bool: """delegation.orchestrator_enabled kill switch (default True): False forces every child to leaf.""" val = _cfg().get("orchestrator_enabled", True) @@ -195,16 +184,13 @@ def _get_orchestrator_enabled() -> bool: return val.strip().lower() in {"true", "1", "yes", "on"} return True - def _get_inherit_mcp_toolsets() -> bool: """Whether narrowed child toolsets should keep the parent's MCP toolsets.""" return is_truthy_value(_cfg().get("inherit_mcp_toolsets"), default=True) - def _normalized_runtime_url(value: Any) -> str: return str(value or "").strip().rstrip("/") - def _inherit_parent_capabilities(parent_agent, override_provider, override_base_url) -> Optional[dict]: """Parent's endpoint-trust capability map for a child, or None. @@ -219,7 +205,6 @@ def _inherit_parent_capabilities(parent_agent, override_provider, override_base_ return None return {key: value for key, value in parent_caps.items() if isinstance(key, str) and isinstance(value, bool)} - def _inherit_parent_base_url(parent_agent, fallback_base_url: Optional[str]) -> Optional[str]: """Base URL the parent is actually calling (live client), not a stale attribute. @@ -240,7 +225,6 @@ def _inherit_parent_base_url(parent_agent, fallback_base_url: Optional[str]) -> return url return fallback_base_url or None - def _loaded_pool(key: Any): """``load_pool(key)`` when it holds credentials, else None.""" from agent.credential_pool import load_pool @@ -248,7 +232,6 @@ def _loaded_pool(key: Any): pool = load_pool(key) return pool if pool is not None and pool.has_credentials() else None - def _resolve_child_credential_pool( effective_provider: Optional[str], parent_agent, @@ -301,7 +284,6 @@ def _resolve_child_credential_pool( logger.debug("Could not load credential pool for child provider '%s': %s", effective_provider, exc) return None - def _merge_request_overrides(runtime_overrides, explicit_overrides): """Merge explicit ``delegation.request_overrides`` OVER runtime-derived ones. @@ -329,14 +311,12 @@ def _merge_request_overrides(runtime_overrides, explicit_overrides): merged["extra_body"] = explicit_extra return merged or None - # Native-SDK providers speak their own wire protocol and can't be reached via # chat_completions against a base_url: always take the runtime-provider path # (a configured base_url still flows through it, e.g. a Bedrock region). _NATIVE_SDK_PROVIDERS = frozenset({"bedrock", "vertex", "google", "google-genai"}) _EXPLICIT_API_MODES = frozenset({"chat_completions", "codex_responses", "anthropic_messages"}) - def _require_pinned_command(command: Optional[str], message: str) -> None: """A pinned ACP transport command must exist on PATH — refuse loudly rather than let the child silently fall back to another transport.""" @@ -347,7 +327,6 @@ def _require_pinned_command(command: Optional[str], message: str) -> None: if not _shutil.which(command): raise ValueError(message) - def _direct_endpoint_credentials(cfg_values: dict, explicit_request_overrides) -> dict: """``delegation.base_url`` branch: provider/api_mode from URL heuristics.""" configured_model, configured_provider, configured_base_url, configured_api_key, configured_api_mode = ( @@ -402,7 +381,6 @@ def _direct_endpoint_credentials(cfg_values: dict, explicit_request_overrides) - "max_output_tokens": max_output_tokens, } - def _runtime_provider_credentials(cfg_values: dict, explicit_request_overrides) -> dict: """``delegation.provider`` branch: full bundle via the runtime provider system.""" configured_model, configured_provider = cfg_values["model"], cfg_values["provider"] @@ -446,7 +424,6 @@ def _runtime_provider_credentials(cfg_values: dict, explicit_request_overrides) "args": list(runtime.get("args") or []), } - def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: """Resolve the child credential bundle from the ``delegation`` config section. @@ -484,7 +461,6 @@ def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: } return _runtime_provider_credentials(values, explicit_request_overrides) - def _load_config() -> dict: """Return the ``delegation`` config section (read-only — do NOT mutate). diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index 0f593f7b82..2053b66e78 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -23,7 +23,6 @@ from tools.delegate_tool_progress import ( # Log-record parity with the origin module. logger = logging.getLogger("tools.delegate_tool") - 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: @@ -31,7 +30,6 @@ 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"] @@ -54,7 +52,6 @@ def _report_child_done(parent_agent, spinner_ref, entry, tag, task_labels, n_tas except Exception as e: logger.debug("Spinner update_text failed: %s", e) - def _run_children_parallel( children: List[tuple], results: list, @@ -136,7 +133,6 @@ def _run_children_parallel( # Sort by task_index so results match input order results.sort(key=lambda r: r["task_index"]) - _SYNC_FALLBACK_NOTES = { "no_async": ( "background=true is not available in this session — it cannot " @@ -154,7 +150,6 @@ _SYNC_FALLBACK_NOTES = { ), } - 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() @@ -162,7 +157,6 @@ def _run_sync_with_note(execute_and_aggregate: Any, 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. @@ -192,7 +186,6 @@ 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. @@ -223,7 +216,6 @@ def _resolve_async_session_key(parent_agent: Any, origin_ui_session_id: str) -> 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 @@ -243,7 +235,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) @@ -286,7 +277,6 @@ def _dispatched_payload(dispatch: dict, goals: List[str], child_agents: List[Any ) return payload - def _dispatch_background( *, parent_agent: Any, diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py index 1e640990fe..41feee84c6 100644 --- a/tools/delegate_tool_progress.py +++ b/tools/delegate_tool_progress.py @@ -20,7 +20,6 @@ logger = logging.getLogger("tools.delegate_tool") # the parent-facing failure summary so every surface agrees. SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"}) - 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: @@ -30,7 +29,6 @@ def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None: except Exception as e: logger.debug("Progress callback %s failed: %s", event_type, e) - 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, @@ -41,7 +39,6 @@ def _clean_error_text(error: Any, max_chars: int = 200) -> str: line = lines[-1] if lines[0].startswith("Traceback") else lines[0] return line[: max_chars - 3] + "..." if len(line) > max_chars else line - def format_subagent_failure_line( goal: Optional[str], status: Optional[str], @@ -83,7 +80,6 @@ class DelegateEvent(str, enum.Enum): TASK_TOOL_STARTED = "delegate.tool_started" TASK_TOOL_COMPLETED = "delegate.tool_completed" - # Legacy child-agent event strings → DelegateEvent. _LEGACY_EVENT_MAP: Dict[str, DelegateEvent] = { "_thinking": DelegateEvent.TASK_THINKING, @@ -107,7 +103,6 @@ _EVENT_HANDLERS: Dict[Any, Optional[str]] = { 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.""" @@ -121,7 +116,6 @@ def _normalize_event(event_type: Any) -> Any: except (ValueError, TypeError): return None - def _build_child_system_prompt( goal: str, context: Optional[str] = None, @@ -213,7 +207,6 @@ def _build_child_system_prompt( ) return "\n".join(parts) - def _resolve_workspace_hint(parent_agent) -> Optional[str]: """Best-effort local workspace hint for child prompts: only a concrete absolute directory is ever injected (never a fake container path).""" @@ -236,11 +229,9 @@ def _resolve_workspace_hint(parent_agent) -> Optional[str]: return text return None - _BATCH_ORDINALS: Dict[str, int] = {} _BATCH_ORDINALS_LOCK = threading.Lock() - def format_batch_tag(delegation_id: Optional[str]) -> str: """Short human tag for a delegation batch: ``deleg_6a664903`` → ``set 1`` (first batch seen in this process), the next distinct id → ``set 2``. @@ -257,7 +248,6 @@ def format_batch_tag(delegation_id: Optional[str]) -> str: n = _BATCH_ORDINALS.setdefault(delegation_id, len(_BATCH_ORDINALS) + 1) return f"set {n}" - def _batch_prefix(delegation_id: Optional[str], task_index: int, task_count: int) -> str: """``[set 2 · 3/9] `` for batch children, ``[set 2] `` for a lone child, ``[3/9] `` / ``""`` when the batch id is unknown.""" @@ -267,7 +257,6 @@ def _batch_prefix(delegation_id: Optional[str], task_index: int, task_count: int return f"[{inner}] " return f"[{tag}] " if tag else "" - def _emit_parent_console(parent_agent, line: str) -> None: """Emit a progress line through ``parent_agent._safe_print`` when available so headless stdio hosts (ACP, gateway API) can redirect it to stderr; a @@ -281,7 +270,6 @@ def _emit_parent_console(parent_agent, line: str) -> None: 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.""" if spinner_ref: @@ -292,7 +280,6 @@ def _print_completion_line(parent_agent: Any, spinner_ref: Any, line: str) -> No pass _emit_parent_console(parent_agent, f" {line}") - def _short(text: str, n: int) -> str: return (text[:n] + "...") if len(text) > n else text @@ -436,7 +423,6 @@ class _ChildProgressRelay: if method is not None: getattr(self, method)(tool_name, preview, args, kwargs) - def _build_child_progress_callback( task_index: int, goal: str, diff --git a/tools/delegate_tool_registry.py b/tools/delegate_tool_registry.py index 50b43b4d93..22561c22ff 100644 --- a/tools/delegate_tool_registry.py +++ b/tools/delegate_tool_registry.py @@ -36,7 +36,6 @@ _RECENT_SUBAGENTS_CAP = 200 _recent_subagents: Dict[str, Dict[str, Any]] = {} - def get_subagent_attribution(task_id: Optional[str]) -> Optional[Dict[str, Any]]: """Resolve a process task_id to its originating delegation, if any. @@ -54,7 +53,6 @@ def get_subagent_attribution(task_id: Optional[str]) -> Optional[Dict[str, Any]] return None return {"subagent_id": task_id, "goal": record.get("goal"), "delegation_id": record.get("delegation_id")} - def set_spawn_paused(paused: bool) -> bool: """Globally block/unblock new delegate_task spawns. @@ -66,12 +64,10 @@ def set_spawn_paused(paused: bool) -> bool: _spawn_paused = bool(paused) return _spawn_paused - def is_spawn_paused() -> bool: with _spawn_pause_lock: return _spawn_paused - def _register_subagent(record: Dict[str, Any]) -> None: sid = record.get("subagent_id") if not sid: @@ -80,7 +76,6 @@ def _register_subagent(record: Dict[str, Any]) -> None: with _active_subagents_lock: _active_subagents[sid] = record - def _retain_recent_subagent(record: Dict[str, Any]) -> None: """Keep a bounded attribution stub after a child finishes (lock held).""" sid = record.get("subagent_id") @@ -94,7 +89,6 @@ def _retain_recent_subagent(record: Dict[str, Any]) -> None: while len(_recent_subagents) > _RECENT_SUBAGENTS_CAP: _recent_subagents.pop(next(iter(_recent_subagents)), None) - def _unregister_subagent(subagent_id: str, *, agent: Any = None) -> None: with _active_subagents_lock: record = _active_subagents.get(subagent_id) @@ -102,7 +96,6 @@ def _unregister_subagent(subagent_id: str, *, agent: Any = None) -> None: _active_subagents.pop(subagent_id, None) _retain_recent_subagent(record) - def _close_subagent_steering(subagent_id: str, agent: Any) -> Optional[str]: """Atomically close steer acceptance and drain its final durable artifact. @@ -126,7 +119,6 @@ def _close_subagent_steering(subagent_id: str, agent: Any) -> Optional[str]: return None return pending if isinstance(pending, str) and pending.strip() else None - def interrupt_subagent(subagent_id: str) -> bool: """Request that a single running subagent stop at its next iteration boundary. @@ -150,7 +142,6 @@ def interrupt_subagent(subagent_id: str) -> bool: return False return True - def steer_subagent( subagent_id: str, text: str, @@ -193,7 +184,6 @@ def steer_subagent( logger.debug("steer_subagent(%s) failed: %s", subagent_id, exc) return False - def _capture_gateway_steer_authority(owner_session_id: Optional[str]) -> tuple[Any, Any]: """Capture exact request transport + live session generation, if any. @@ -209,11 +199,9 @@ def _capture_gateway_steer_authority(owner_session_id: Optional[str]) -> tuple[A except Exception: return None, None - # Registry record fields never exposed to the TUI/RPC snapshot. _PRIVATE_RECORD_KEYS = frozenset({"agent", "owner_session_id", "owner_transport", "owner_session_record", "accepting_steer"}) - def list_active_subagents() -> List[Dict[str, Any]]: """Snapshot of the currently running subagent tree. @@ -223,7 +211,6 @@ def list_active_subagents() -> List[Dict[str, Any]]: with _active_subagents_lock: return [{k: v for k, v in r.items() if k not in _PRIVATE_RECORD_KEYS} for r in _active_subagents.values()] - def _is_descendant_of(child_agent: Any, parent_agent: Any, max_hops: int = 8) -> bool: """True when *child_agent* sits below *parent_agent* in the spawn tree. @@ -244,12 +231,10 @@ def _is_descendant_of(child_agent: Any, parent_agent: Any, max_hops: int = 8) -> cur = ancestor return False - # Model-facing control actions accepted by delegate_task(action=...). # "spawn" (or omitted) keeps the historical spawn semantics. _CONTROL_ACTIONS = frozenset({"list", "steer", "stop"}) - def _resolve_session_lineage(session_id: Optional[str], parent_agent: Any) -> str: """Resolve a session id to the tip of its compression lineage. @@ -269,7 +254,6 @@ def _resolve_session_lineage(session_id: Optional[str], parent_agent: Any) -> st except Exception: return sid - def _owns_subagent_record(record: Dict[str, Any], parent_agent: Any) -> bool: """True when *parent_agent*'s conversation owns this live-child record. @@ -301,7 +285,6 @@ def _owns_subagent_record(record: Dict[str, Any], parent_agent: Any) -> bool: _resolve_session_lineage(parent_sid, parent_agent), } - def _handle_control_action(action: str, subagent_id: Optional[str], message: Optional[str], parent_agent: Any) -> str: """Synchronous control plane for delegate_task: list/steer/stop. @@ -370,7 +353,6 @@ def _handle_control_action(action: str, subagent_id: Optional[str], message: Opt return json.dumps({"action": action, "subagent_id": sid, "status": status, "note": note}, ensure_ascii=False) return tool_error(failure.format(sid=sid)) - # action -> (success status, success note, failure error template) _CONTROL_OUTCOMES = { "stop": ( diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.py index 7c99b982d0..6477ed3457 100644 --- a/tools/delegate_tool_results.py +++ b/tools/delegate_tool_results.py @@ -14,7 +14,6 @@ from urllib.parse import urlsplit, urlunsplit # Log-record parity with the origin module. logger = logging.getLogger("tools.delegate_tool") - def _extract_output_tail( result: Dict[str, Any], *, @@ -69,7 +68,6 @@ def _extract_output_tail( tail.reverse() # restore chronological order for display return tail - def _stringify_tool_content(content: Any) -> str: """Return a stable text representation for tool-result content. @@ -92,7 +90,6 @@ def _stringify_tool_content(content: Any) -> str: return json.dumps(content, ensure_ascii=False, default=str) return str(content) - _TOOL_INPUT_TARGET_KEYS = frozenset({ "cwd", "destination_path", @@ -112,7 +109,6 @@ _TOOL_INPUT_TARGET_KEYS = frozenset({ _TOOL_INPUT_URL_KEYS = frozenset({"endpoint", "url", "urls"}) - def _sanitize_tool_target(key: str, value: Any) -> Any: """Keep bounded side-effect targets while dropping URL secrets.""" if isinstance(value, list): @@ -140,11 +136,9 @@ def _sanitize_tool_target(key: str, value: Any) -> Any: return None return bounded - def _empty_input_summary() -> Dict[str, Any]: return {"argument_keys": [], "targets": {}} - def _sanitize_targets(mapping: Dict[str, Any]) -> Dict[str, Any]: """Keep only known side-effect target keys, each sanitized (URL secrets dropped).""" targets: Dict[str, Any] = {} @@ -156,7 +150,6 @@ def _sanitize_targets(mapping: Dict[str, Any]) -> Dict[str, Any]: targets[key] = cleaned return targets - def _summarize_tool_arguments(arguments: Any) -> Dict[str, Any]: """Summarize argument names and side-effect targets without raw payloads.""" if not isinstance(arguments, str): @@ -170,7 +163,6 @@ def _summarize_tool_arguments(arguments: Any) -> Dict[str, Any]: keys = sorted(str(key)[:128] for key in parsed)[:64] return {"argument_keys": keys, "targets": _sanitize_targets(parsed)} - def _sanitize_tool_input_summary(summary: Any) -> Dict[str, Any]: """Re-sanitize a stored input summary before handing it to lifecycle hooks.""" if not isinstance(summary, dict): @@ -181,7 +173,6 @@ def _sanitize_tool_input_summary(summary: Any) -> Dict[str, Any]: safe_targets = _sanitize_targets(targets) if isinstance(targets, dict) else {} return {"argument_keys": safe_keys, "targets": safe_targets} - def _subagent_stop_tool_call_history(tool_trace: Any) -> List[Dict[str, Any]]: """Build a detached, metadata-only tool history for lifecycle hooks.""" if not isinstance(tool_trace, list): @@ -211,7 +202,6 @@ def _subagent_stop_tool_call_history(tool_trace: Any) -> List[Dict[str, Any]]: }) return history - def _looks_like_error_output(content: Any) -> bool: """Conservative stderr/error detector for tool-result previews. @@ -242,7 +232,6 @@ def _looks_like_error_output(content: Any) -> bool: first = content.splitlines()[0].strip().lower() if content.splitlines() else "" return first.startswith(("error:", "failed:", "traceback ", "exception:")) - # Hard per-summary character ceiling layered on top of the dynamic # headroom budget (see _apply_summary_budget). Belt-and-suspenders for # models that ignore the "be concise" instruction. 0 disables the ceiling. @@ -258,7 +247,6 @@ _SUMMARY_HEADROOM_FRACTION = 0.5 # already nearly full — below this we'd be truncating to noise. _MIN_SUMMARY_CHARS = 2000 - def _spill_summary_to_file(task_index: int, summary: str) -> Optional[str]: """Write a subagent's full summary to the delegation cache and return path. @@ -288,7 +276,6 @@ def _spill_summary_to_file(task_index: int, summary: str) -> Optional[str]: logger.debug("Failed to spill subagent summary to file: %s", exc) return None - def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple[str, Optional[str]]: """Return (model_text, spill_path) for one over-budget summary. @@ -341,7 +328,6 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple[ model_text = head + "\n\n[... middle omitted — see footer ...]\n\n" + tail + "\n".join(footer_lines) return model_text, spill_path - def _parent_summary_char_budget(parent_agent, n_summaries: int) -> Optional[int]: """Per-summary char budget from the parent's *remaining* context headroom (context length minus prompt tokens minus the compressor's output reserve), @@ -374,7 +360,6 @@ def _parent_summary_char_budget(parent_agent, n_summaries: int) -> Optional[int] logger.debug("Summary budget computation failed", exc_info=True) return None - def _apply_summary_budget(results: List[Dict[str, Any]], parent_agent) -> None: """Trim subagent summaries in-place so a batch can't overflow the parent's context window; full text is spilled to disk so nothing is lost. @@ -422,14 +407,12 @@ def _apply_summary_budget(results: List[Dict[str, Any]], parent_agent) -> None: spill_path or "none", ) - _PARENT_FINALIZATION_LOCK_GUARD = threading.Lock() _PARENT_FINALIZATION_FALLBACK_LOCK = threading.RLock() _CHILD_CONSTRUCTION_LOCK = threading.RLock() - def _build_child_preserving_parent_tools(**kwargs): """Build a child without leaking its resolved toolset into the parent.""" from tools.delegate_tool import _build_child_agent @@ -444,7 +427,6 @@ def _build_child_preserving_parent_tools(**kwargs): child._delegate_saved_tool_names = parent_tool_names return child - def _parent_finalization_lock(parent_agent) -> threading.RLock: """Return the per-parent lock that serializes lifecycle side effects.""" if parent_agent is None: @@ -462,7 +444,6 @@ def _parent_finalization_lock(parent_agent) -> threading.RLock: return _PARENT_FINALIZATION_FALLBACK_LOCK return lock - def _notify_memory_manager(results, task_list, child_by_index, parent_agent) -> None: memory = getattr(parent_agent, "_memory_manager", None) if parent_agent else None if not memory: @@ -479,7 +460,6 @@ def _notify_memory_manager(results, task_list, child_by_index, parent_agent) -> except Exception: pass - def _fire_subagent_stop_hooks(results, child_by_index, parent_agent) -> float: """Pop the model-hidden ``_child_role`` / ``_child_cost_usd`` fields from every entry, fire ``subagent_stop`` per child, and return the summed child cost.""" @@ -516,7 +496,6 @@ def _fire_subagent_stop_hooks(results, child_by_index, parent_agent) -> float: logger.debug("subagent_stop hook invocation failed", exc_info=True) return children_cost_total - def _rollup_children_cost(parent_agent, children_cost_total: float) -> None: """Fold the children's spend into the parent's session cost (source/status only set when the parent had none of its own).""" @@ -532,7 +511,6 @@ def _rollup_children_cost(parent_agent, children_cost_total: float) -> None: except Exception: logger.debug("Subagent cost rollup failed", exc_info=True) - def _finalize_child_results( results: List[Dict[str, Any]], task_list: List[Dict[str, Any]], @@ -546,7 +524,6 @@ def _finalize_child_results( _notify_memory_manager(results, task_list, child_by_index, parent_agent) _rollup_children_cost(parent_agent, _fire_subagent_stop_hooks(results, child_by_index, parent_agent)) - def _run_child_lifecycle(task_index: int, goal: str, child=None, parent_agent=None) -> Dict[str, Any]: """Run one child and apply the same host lifecycle used by delegate_task.""" from tools.delegate_tool import _run_single_child