diff --git a/MagicMock/mock._session_db.db_path/123598073808400 b/MagicMock/mock._session_db.db_path/123598073808400 new file mode 100644 index 0000000000..f08e555a11 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/123598073808400 differ 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 0000000000..d20f981571 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/123598093110032 differ 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/MagicMock/mock._session_db.db_path/125483604393296 b/MagicMock/mock._session_db.db_path/125483604393296 new file mode 100644 index 0000000000..a921ae0346 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/125483604393296 differ diff --git a/MagicMock/mock._session_db.db_path/125483604393296.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 0000000000..16d7bc3d44 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/125483613186832 differ 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/126670844021456 b/MagicMock/mock._session_db.db_path/126670844021456 new file mode 100644 index 0000000000..d0a247e7aa Binary files /dev/null and b/MagicMock/mock._session_db.db_path/126670844021456 differ 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 0000000000..4e547c7618 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/126670871778000 differ diff --git a/MagicMock/mock._session_db.db_path/126670871778000.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/126670871778000.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/126670871778000.quarantine.lock b/MagicMock/mock._session_db.db_path/126670871778000.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/132161382957648 b/MagicMock/mock._session_db.db_path/132161382957648 new file mode 100644 index 0000000000..ccf54b739f Binary files /dev/null and b/MagicMock/mock._session_db.db_path/132161382957648 differ 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 0000000000..fb203e1636 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/132161402292368 differ diff --git a/MagicMock/mock._session_db.db_path/132161402292368.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/132161402292368.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/132161402292368.quarantine.lock b/MagicMock/mock._session_db.db_path/132161402292368.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/136309983742096 b/MagicMock/mock._session_db.db_path/136309983742096 new file mode 100644 index 0000000000..762f3ba96b Binary files /dev/null and b/MagicMock/mock._session_db.db_path/136309983742096 differ 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 0000000000..7d1ccd14a9 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/136310003043600 differ 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/MagicMock/mock._session_db.db_path/139369483040144 b/MagicMock/mock._session_db.db_path/139369483040144 new file mode 100644 index 0000000000..522c23eb0d Binary files /dev/null and b/MagicMock/mock._session_db.db_path/139369483040144 differ diff --git a/MagicMock/mock._session_db.db_path/139369483040144.fts_rebuild.lock b/MagicMock/mock._session_db.db_path/139369483040144.fts_rebuild.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139369483040144.quarantine.lock b/MagicMock/mock._session_db.db_path/139369483040144.quarantine.lock new file mode 100644 index 0000000000..e69de29bb2 diff --git a/MagicMock/mock._session_db.db_path/139369502342928 b/MagicMock/mock._session_db.db_path/139369502342928 new file mode 100644 index 0000000000..79ef2806e0 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/139369502342928 differ 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/MagicMock/mock._session_db.db_path/139713934067408 b/MagicMock/mock._session_db.db_path/139713934067408 new file mode 100644 index 0000000000..8a7f10506d Binary files /dev/null and b/MagicMock/mock._session_db.db_path/139713934067408 differ 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 0000000000..50bdcbe5e6 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/139713953384784 differ 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/MagicMock/mock._session_db.db_path/140588728862416 b/MagicMock/mock._session_db.db_path/140588728862416 new file mode 100644 index 0000000000..960085b500 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/140588728862416 differ 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 0000000000..1b27f54eb2 Binary files /dev/null and b/MagicMock/mock._session_db.db_path/140588740754704 differ 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 30128f58d7..0decc82898 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -2,26 +2,18 @@ """ 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 contextvars import json import logging import re -import threading import time import weakref from dataclasses import dataclass @@ -29,90 +21,48 @@ 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__) -# 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_sibling_write_reminder, - _build_result_entry, - _cleanup_child_run, - _dump_subagent_timeout_diagnostic, - _emit_child_complete, - _handle_child_wait_failure, - _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, - _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, - 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( [ @@ -124,11 +74,8 @@ 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: @@ -139,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: @@ -154,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. @@ -179,10 +124,7 @@ 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]: +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): @@ -190,7 +132,6 @@ def _preserve_parent_mcp_toolsets( 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). @@ -202,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.""" @@ -221,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.""" @@ -235,27 +173,24 @@ 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]]: """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 = { @@ -270,9 +205,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) @@ -282,48 +215,31 @@ 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 = [] - if effective_role == "orchestrator": - 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"] - ) + 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"]) ) - - if effective_role == "orchestrator" and "delegation" not in child_toolsets: - child_toolsets.append("delegation") 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( parent_agent, @@ -338,8 +254,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); @@ -349,22 +266,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) @@ -374,34 +284,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. @@ -415,74 +314,140 @@ 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) - # 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: + """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: Dict[str, Any], + *, + 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( + **rt, + max_iterations=max_iterations, + prefill_messages=getattr(parent_agent, "prefill_messages", None), + 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), + 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 {})) + ), + tool_progress_callback=child_progress_cb, + iteration_budget=None, # fresh budget per subagent + ) + 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, @@ -511,33 +476,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 +503,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 +511,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 +529,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,46 +567,17 @@ 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 - def _run_single_child( task_index: int, goal: str, @@ -765,24 +605,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 +624,29 @@ 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 - ) + 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 if child_progress_cb and hasattr(child_progress_cb, "_flush"): @@ -907,37 +663,19 @@ 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") - 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 @@ -952,10 +690,7 @@ 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]]: +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() @@ -969,23 +704,16 @@ 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 - -# 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]+)+>" @@ -993,22 +721,15 @@ _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. + """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()) @@ -1041,6 +762,250 @@ 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 +1032,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 +1069,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,21 +1129,16 @@ 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 ────────────────────────────────────────── - 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: @@ -1389,10 +1155,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, " @@ -1428,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: @@ -1442,39 +1204,23 @@ def _build_tasks_param_description() -> str: "is a one-entry array. Required when spawning." ) - 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. - """ - 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() - } + """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"]} + # 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, - } - + return {"description": _build_top_level_description(), "parameters": overrides_params} 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 " @@ -1483,11 +1229,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, @@ -1526,18 +1270,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"], @@ -1575,27 +1315,20 @@ 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). - 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"} - def _strip_model_hidden_task_fields(tasks: Any) -> Any: if not isinstance(tasks, list): return tasks @@ -1605,11 +1338,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 89c6093d03..aebace61ab 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 @@ -15,6 +16,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, ) @@ -25,6 +27,141 @@ 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 { + "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, *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, *reason) 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") + ] + +_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( *, @@ -35,171 +172,74 @@ 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") - for attr in ( - "model", "provider", "api_mode", "base_url", "max_iterations", - "quiet_mode", "skip_memory", "skip_context_files", "platform", - "_delegate_role", "_delegate_depth", - ): + 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", + ] + for attr in _DIAG_CHILD_ATTRS: 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}") + lines.append(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}") + 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: - _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'))}") - except Exception as exc: - _w(f" tool_schema: ") - _w("") - - _w("## Activity summary") - try: - summary = child.get_activity_summary() - for k, v in summary.items(): - _w(f" {k}: {v!r}") - except Exception as exc: - _w(f" ") - _w("") - - _w("## Worker thread stack at timeout") - 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(" ") - 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}" - 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}") - 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: 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). @@ -207,28 +247,18 @@ 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, # 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 +269,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,9 +304,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( child: Any, @@ -309,62 +320,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,43 +379,18 @@ 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 + from tools import subagent_worktree - entry_dict["worktree"] = ( - subagent_worktree.finalize_subagent_worktree(_worktree_info) - ) + try: + 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. logger.warning("worktree finalize failed: %s", e) - try: - from tools import subagent_worktree as _sw - - entry_dict["worktree"] = _sw.unproven_worktree_payload( - _worktree_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", ""), - "commits": 0, - "dirty": False, - "pruned": False, - "inspection_failed": True, - "note": ( - 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 " - "no work." - ), - } + entry_dict["worktree"] = subagent_worktree.unproven_worktree_payload(info, f"finalize raised: {e}") @dataclass @@ -427,6 +401,33 @@ 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 + degrade silently to the shared workspace. Returns the worktree info or None.""" + from tools.delegate_tool import _get_worktree_isolation, _resolve_workspace_hint + + if not _get_worktree_isolation(): + return None + try: + from tools import subagent_worktree + + if not subagent_worktree.local_backend_active(): + logger.debug("worktree isolation skipped: non-local terminal backend") + return None + _parent_cwd = None + try: + from tools.terminal_tool import get_session_cwd as _gsc + + _parent_cwd = _gsc(parent_task_id) + except Exception: + pass + return subagent_worktree.create_subagent_worktree( + _parent_cwd or _resolve_workspace_hint(parent_agent), subagent_id=subagent_id, + ) + except Exception as e: + logger.debug("worktree isolation setup failed: %s", e) + return None def _seed_child_workspace( child: Any, @@ -441,74 +442,38 @@ def _seed_child_workspace( Returns the ids the run needs; ``goal`` comes back extended with the 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. - if _get_worktree_isolation(): + _worktree_info = _create_isolated_worktree(parent_agent, parent_task_id, subagent_id) + if _worktree_info is not None: try: - from tools import subagent_worktree + from tools.terminal_tool import record_session_cwd as _rsc - if subagent_worktree.local_backend_active(): - _parent_cwd = None - try: - from tools.terminal_tool import get_session_cwd as _gsc - - _parent_cwd = _gsc(parent_task_id) - except Exception: - pass - _worktree_info = subagent_worktree.create_subagent_worktree( - _parent_cwd or _resolve_workspace_hint(parent_agent), - subagent_id=_subagent_id, - ) - else: - logger.debug( - "worktree isolation skipped: non-local terminal backend" - ) + _rsc(child_task_id, _worktree_info["path"]) except Exception as e: - logger.debug("worktree isolation setup failed: %s", e) - if _worktree_info is not None: - try: - from tools.terminal_tool import record_session_cwd as _rsc + logger.debug("worktree cwd seed failed: %s", e) + # The child's context is already built; carry the isolation contract on + # the goal message instead (same turn, no system-prompt mutation). + from tools.subagent_worktree import build_worktree_context_note - _rsc(child_task_id, _worktree_info["path"]) - except Exception as e: - logger.debug("worktree cwd seed failed: %s", e) - # The child's context is already built; carry the isolation - # contract on the goal message instead (same turn, no - # system-prompt mutation). - from tools.subagent_worktree import build_worktree_context_note + goal = goal + build_worktree_context_note(_worktree_info) - 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 @@ -516,6 +481,136 @@ 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. + + The interrupt is cooperative: the worker still runs its finally path, so + 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") + ) + _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 _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; ``(result, None)`` or + ``(None, failure)`` on timeout/exception. + + 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 + + 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, @@ -538,43 +633,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,60 +663,47 @@ 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: - 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) - 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", + "status": status, "summary": None, "error": _err, - "exit_reason": "timeout" if is_timeout else "error", + "exit_reason": status, "api_calls": child_api_calls, "duration_seconds": duration, "timeout_seconds": child_timeout if is_timeout else None, @@ -651,60 +716,12 @@ def _handle_child_wait_failure( "_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) + _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 @@ -714,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: @@ -723,67 +739,76 @@ 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 _schema_valid or not _first_text.strip() or result.get("interrupted", False): + return _SchemaOutcome(_output_schema, _schema_valid, _schema_errors, 0) + + # 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) - _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 - ) - - # 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) - +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( child: Any, @@ -798,102 +823,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,119 +863,81 @@ 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 - _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 - 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. 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) - def _emit_child_complete( child: Any, result: Dict[str, Any], @@ -1029,66 +953,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( child: Any, @@ -1108,16 +1005,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 +1019,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 +1050,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") - diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py index 8a82fff102..0cdde7c160 100644 --- a/tools/delegate_tool_config.py +++ b/tools/delegate_tool_config.py @@ -1,7 +1,6 @@ """Delegation config knobs (delegation.* keys) and child credential/provider resolution. -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 @@ -31,6 +30,12 @@ _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 + + return _load_config() + # ── Subagent approval callbacks ───────────────────────────────────────────── # Subagent worker threads don't inherit the CLI's threading.local approval @@ -48,63 +53,59 @@ 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, - ) + 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).""" - 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 +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. """ - from tools.delegate_tool import _load_config - cfg = _load_config() - 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): + 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 - 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: """delegation.worktree_isolation (bool, default False). @@ -113,10 +114,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: """Concurrency cap for background delegations == delegation.max_concurrent_children. @@ -126,10 +124,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; " @@ -138,6 +135,10 @@ 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,30 +148,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. """ - from tools.delegate_tool import _load_config - cfg = _load_config() - val = cfg.get("child_timeout_seconds") - if val is not None: - try: - parsed = float(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) - except (TypeError, ValueError): - pass - else: - return None if parsed <= 0 else max(30.0, parsed) - 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: """delegation.max_spawn_depth floored at 1 (no ceiling). @@ -178,36 +161,22 @@ 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: 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 - 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. @@ -215,20 +184,14 @@ 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.""" - 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]: +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: @@ -240,12 +203,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]: """Base URL the parent is actually calling (live client), not a stale attribute. @@ -255,28 +213,24 @@ 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], @@ -291,24 +245,21 @@ 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: # 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" @@ -316,10 +267,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,22 +278,12 @@ 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", - effective_provider, - exc, - ) + 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. @@ -373,116 +311,79 @@ 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 _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: - """Resolve the child credential bundle from the ``delegation`` config section. +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 - 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 + if not _shutil.which(command): + raise ValueError(message) - explicit_request_overrides = ( - cfg.get("request_overrides") - if isinstance(cfg.get("request_overrides"), dict) - else None +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 +402,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"), @@ -530,6 +424,42 @@ def _resolve_delegation_credentials(cfg: dict, parent_agent) -> dict: "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. + + 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 +470,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: diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py index 8eb674e102..2053b66e78 100644 --- a/tools/delegate_tool_dispatch.py +++ b/tools/delegate_tool_dispatch.py @@ -9,43 +9,48 @@ 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_child_run import _detach_child, _fabricated_entry, _signal_child_stop from tools.delegate_tool_progress import ( SUBAGENT_FAILURE_STATUSES, _clean_error_text, - _emit_parent_console, + _print_completion_line, format_batch_tag, ) # 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: + return future.result() + except Exception as exc: + return _fabricated_entry(idx, "error", str(exc), child) -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 _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: +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.print_above(line) - return - except Exception: - pass - _emit_parent_console(parent_agent, f" {line}") - + 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], @@ -71,59 +76,41 @@ 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. + if (honor_parent_interrupt and getattr(parent_agent, "_interrupt_requested", False) is True): + # Parent interrupted — collect whatever finished and abandon the + # rest (children already got the interrupt signal). for f in pending: idx = futures[f] if f.done(): - 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,55 +122,160 @@ 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) - 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". - 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) - - # Update spinner text to show remaining count - 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"]) +_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. + + 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 + + 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 _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 + 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: + 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( *, @@ -208,246 +300,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] + # 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(): - 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 - except Exception: - pass + # Cancellation path for the detached batch (owned by the async registry). + for c in child_agents: + _signal_child_stop(c, "Async delegation cancelled") - 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..41feee84c6 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 @@ -18,31 +17,27 @@ 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 _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) def _clean_error_text(error: Any, max_chars: int = 200) -> str: - """Reduce an arbitrary error payload to one clean human-readable line. - - 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()] + """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( goal: Optional[str], @@ -50,19 +45,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 +65,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" @@ -93,9 +80,7 @@ class DelegateEvent(str, enum.Enum): TASK_TOOL_STARTED = "delegate.tool_started" 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 +89,32 @@ _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,17 +127,11 @@ 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.", - "", - 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(): @@ -135,27 +140,19 @@ 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 - _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( @@ -210,14 +207,9 @@ 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. - - 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( @@ -237,32 +229,25 @@ 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 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}" - 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.""" @@ -272,15 +257,10 @@ 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 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: @@ -290,6 +270,158 @@ 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: + 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, @@ -304,203 +436,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, + ) diff --git a/tools/delegate_tool_registry.py b/tools/delegate_tool_registry.py index a6e1df794a..22561c22ff 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 @@ -37,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. @@ -50,22 +48,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: """Globally block/unblock new delegate_task spawns. @@ -78,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: @@ -92,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") @@ -106,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) @@ -114,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. @@ -138,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. @@ -162,7 +142,6 @@ def interrupt_subagent(subagent_id: str) -> bool: return False return True - def steer_subagent( subagent_id: str, text: str, @@ -171,20 +150,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 @@ -209,10 +184,7 @@ 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]: +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. @@ -227,6 +199,8 @@ def _capture_gateway_steer_authority( 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. @@ -235,22 +209,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: """True when *child_agent* sits below *parent_agent* in the spawn tree. @@ -272,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. @@ -297,28 +254,19 @@ 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. - 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): @@ -337,13 +285,7 @@ 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: +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 @@ -375,11 +317,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 " @@ -404,54 +342,37 @@ 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, - ) - return tool_error( - f"Could not interrupt '{sid}' — it likely finished in the last " - "moment. Its result arrives as a normal completion message." - ) + if action == "steer" and not (message or "").strip(): + 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.") + 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.", + ), +} diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.py index 3963506314..6477ed3457 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 @@ -15,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], *, @@ -70,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. @@ -83,22 +80,16 @@ 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) - _TOOL_INPUT_TARGET_KEYS = frozenset({ "cwd", "destination_path", @@ -118,14 +109,10 @@ _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): - 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 @@ -149,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] = {} @@ -165,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): @@ -179,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): @@ -190,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): @@ -220,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. @@ -249,13 +230,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 # headroom budget (see _apply_summary_budget). Belt-and-suspenders for @@ -272,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. @@ -302,10 +276,7 @@ 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]]: +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 @@ -357,21 +328,13 @@ def _trim_summary_with_footer( 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 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) @@ -397,25 +360,18 @@ 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 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"] - ] + summaries = [r for r in results if isinstance(r, dict) and isinstance(r.get("summary"), str) and r["summary"]] if not summaries: return @@ -438,9 +394,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: @@ -453,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 @@ -475,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: @@ -493,6 +444,72 @@ 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: + 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]], @@ -504,90 +521,10 @@ 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} + _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)) - 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) - - -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)