Merge branch 'simp/r2-tools-b-delegate' into simp/integration2
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+576
-847
File diff suppressed because it is too large
Load Diff
+606
-731
File diff suppressed because it is too large
Load Diff
+194
-266
@@ -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.<name>`` 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.<key> > <env_var> > 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:
|
||||
|
||||
+214
-310
@@ -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/<id>/.
|
||||
delegation_id=live_deleg_id,
|
||||
progress_fn=_batch_progress,
|
||||
progress_fn=lambda: _batch_progress_token(child_agents),
|
||||
)
|
||||
|
||||
if dispatch.get("status") == "dispatched":
|
||||
n = len(_goals)
|
||||
note = (
|
||||
"Subagent is running in the background. You and the user can "
|
||||
"keep working; its full result re-enters the conversation as a "
|
||||
"new message when it finishes. Do not wait or poll — just "
|
||||
"continue."
|
||||
if n == 1 else
|
||||
f"{n} subagents are running in parallel in the background. You "
|
||||
f"and the user can keep working; they wait on each other and "
|
||||
f"their consolidated results re-enter the conversation as a "
|
||||
f"single message once ALL of them finish. Do not wait or poll "
|
||||
f"— just continue."
|
||||
)
|
||||
payload = {
|
||||
"status": "dispatched",
|
||||
"mode": "background",
|
||||
"count": n,
|
||||
"delegation_id": dispatch["delegation_id"],
|
||||
"goals": _goals,
|
||||
"note": note,
|
||||
}
|
||||
_sids = [
|
||||
getattr(_c, "_subagent_id", None) for _c in _child_agents
|
||||
]
|
||||
if any(isinstance(s, str) and s for s in _sids):
|
||||
payload["subagent_ids"] = _sids
|
||||
payload["control_hint"] = (
|
||||
"While a child runs you can orchestrate it live with this "
|
||||
"same tool: delegate_task(action='list') to see live "
|
||||
"children, action='steer' with subagent_id + message to "
|
||||
"redirect one, action='stop' with subagent_id to end one "
|
||||
"early."
|
||||
)
|
||||
if live_paths:
|
||||
payload["live_transcripts"] = list(live_paths)
|
||||
payload["live_transcripts_hint"] = (
|
||||
"Each subagent streams a human-readable transcript of its "
|
||||
"operations to the file listed above (append-only, one per "
|
||||
"task). Read or `tail -f` these paths at any time to watch "
|
||||
"a child work while it runs."
|
||||
)
|
||||
return json.dumps(payload, ensure_ascii=False)
|
||||
return json.dumps(_dispatched_payload(dispatch, goals, child_agents, live_paths), ensure_ascii=False)
|
||||
|
||||
# Pool at capacity / schedule failure — children are still attached
|
||||
# (we detach above only on the parent list, but the async unit was
|
||||
# never accepted, so re-attaching isn't needed: we just run inline).
|
||||
# Pool at capacity / schedule failure: the async unit was never accepted,
|
||||
# so just run inline (re-attaching to the parent list is not needed).
|
||||
logger.info(
|
||||
"delegate_task: async pool at capacity (%s); running the whole "
|
||||
"batch synchronously instead.",
|
||||
dispatch.get("error", "rejected"),
|
||||
)
|
||||
_cap_result = _execute_and_aggregate()
|
||||
if isinstance(_cap_result, dict):
|
||||
_cap_result["note"] = (
|
||||
"The background delegation pool was at capacity "
|
||||
"(delegation.max_concurrent_children), so the subagent(s) ran "
|
||||
"SYNCHRONOUSLY and the result is included above. Raise "
|
||||
"delegation.max_concurrent_children in config.yaml to allow "
|
||||
"more concurrent background delegations."
|
||||
)
|
||||
return json.dumps(_cap_result, ensure_ascii=False)
|
||||
return _run_sync_with_note(execute_and_aggregate, "at_capacity")
|
||||
|
||||
+237
-294
@@ -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.<name>`` 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,
|
||||
)
|
||||
|
||||
+63
-142
@@ -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.<name>`` 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.",
|
||||
),
|
||||
}
|
||||
|
||||
+94
-157
@@ -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.<name>`` 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)
|
||||
|
||||
Reference in New Issue
Block a user