The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: failed subagents now surface a clean error to the user (CLI + gateway)
Teknium5a134383fe4e
diff --git a/gateway/run.py b/gateway/run.pyindex a7a6191bf7f..7aa6cf7930a 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4590,6 +4590,36 @@ class TurnRunner:def progress_callback(self, event_type: str, tool_name: str = None, preview: str = None, args: dict = None, **kwargs):"""Callback invoked by agent on tool lifecycle events."""ctx = self._ctx+ # Failed subagent → one clean user-facing notice. Handled FIRST,+ # before every progress-queue gate: platforms that keep+ # tool_progress off (Telegram, Slack, ...) must still hear about a+ # delegation that died — a silently-vanishing subagent looks like+ # the agent just dropped the task (community report, Aug 2026).+ # Success/interrupt completions stay quiet; only terminal failure+ # statuses render, via the same notice rail as credit warnings.+ if event_type == "subagent.complete":+ _sub_status = kwargs.get("status")+ try:+ from tools.delegate_tool import (+ SUBAGENT_FAILURE_STATUSES,+ format_subagent_failure_line,+ )+ if _sub_status in SUBAGENT_FAILURE_STATUSES and ctx._run_still_current():+ _line = format_subagent_failure_line(+ kwargs.get("goal"),+ _sub_status,+ error=kwargs.get("summary") or preview,+ duration_seconds=kwargs.get("duration_seconds"),+ )+ safe_schedule_threadsafe(+ self._runner._deliver_platform_notice(ctx.source, _line),+ ctx._loop_for_step,+ logger=logger,+ log_message="subagent failure notice scheduling error",+ )+ except Exception:+ logger.debug("subagent failure notice failed", exc_info=True)+ return# Live status line (Slack's assistant status): stash the current# tool phrase on the adapter; the _keep_typing refresh renders it# within a couple of seconds. Handled before every other gate@@ -6108,15 +6138,12 @@ class TurnRunner:# who set thinking_progress:true but kept tool_progress:off got a# None callback — so _thinking scratch bubbles never relayed even# though the progress queue was created for them.- agent.tool_progress_callback = (- ctx.progress_callback- if (- ctx.needs_progress_queue- or ctx.log_mode_enabled- or ctx._live_status_adapter is not None- )- else None- )+ # Always attached (previously gated to None when no progress surface+ # was active): the callback body gates each event class itself, and+ # subagent-failure notices must fire even on platforms with+ # tool_progress/thinking off — the None gate was exactly why a dead+ # subagent vanished silently there.+ agent.tool_progress_callback = ctx.progress_callback# Compose ID-bearing lifecycle consumers: Discord's one-time voice# ack and Slack's native task cards both ride the authoritative# start callback, so neither has to infer identity from tool names.diff --git a/tests/gateway/test_subagent_failure_notice.py b/tests/gateway/test_subagent_failure_notice.pynew file mode 100644index 00000000000..d5115bb7e55--- /dev/null+++ b/tests/gateway/test_subagent_failure_notice.py@@ -0,0 +1,171 @@+"""Subagent failures surface as one clean user-facing notice.++Covers the Aug 2026 community report: a delegate_task child that dies+(provider 404, timeout, crash) previously vanished silently on platforms+with tool_progress off — the parent model saw the error but the human never+did. Now:++- ``tools.delegate_tool.format_subagent_failure_line`` renders one clean,+ human-readable line (no tracebacks/JSON walls).+- ``TurnRunner.progress_callback`` intercepts ``subagent.complete`` events+ with a terminal failure status FIRST (before every progress-queue gate)+ and delivers the line via ``_deliver_platform_notice``.+"""++import asyncio+from unittest.mock import MagicMock++import pytest++from gateway.turn_context import TurnContext+from tools.delegate_tool import (+ SUBAGENT_FAILURE_STATUSES,+ _clean_error_text,+ format_subagent_failure_line,+)+++class TestCleanErrorText:+ def test_single_line_passthrough(self):+ assert _clean_error_text("Error code: 404 - model not found") == (+ "Error code: 404 - model not found"+ )++ def test_traceback_takes_last_line(self):+ tb = (+ "Traceback (most recent call last):\n"+ ' File "x.py", line 1, in <module>\n'+ " raise RuntimeError('boom')\n"+ "RuntimeError: boom"+ )+ assert _clean_error_text(tb) == "RuntimeError: boom"++ def test_multiline_non_traceback_takes_first_line(self):+ assert _clean_error_text("first line\nsecond line") == "first line"++ def test_caps_length(self):+ out = _clean_error_text("x" * 500, max_chars=100)+ assert len(out) == 100+ assert out.endswith("...")++ def test_empty_and_none(self):+ assert _clean_error_text("") == ""+ assert _clean_error_text(None) == ""+ assert _clean_error_text(" \n ") == ""+++class TestFormatSubagentFailureLine:+ def test_failed_with_goal_error_duration(self):+ line = format_subagent_failure_line(+ "research competitor pricing",+ "failed",+ error="Error code: 404 - model not found",+ duration_seconds=12.4,+ )+ assert line.startswith("⚠️ Subagent failed")+ assert '"research competitor pricing"' in line+ assert "404" in line+ assert "(after 12s)" in line++ def test_timeout_verb(self):+ line = format_subagent_failure_line("do a thing", "timeout")+ assert "timed out" in line++ def test_long_goal_truncated(self):+ line = format_subagent_failure_line("g" * 200, "failed")+ assert "g" * 57 + "..." in line+ assert "g" * 61 not in line++ def test_no_goal_no_error(self):+ line = format_subagent_failure_line(None, "error")+ assert line == "⚠️ Subagent failed"++ def test_multiline_goal_flattened(self):+ line = format_subagent_failure_line("a\nb", "failed")+ assert "\n" not in line++ def test_failure_statuses_frozen(self):+ assert SUBAGENT_FAILURE_STATUSES == {"failed", "error", "timeout"}+++def _make_runner_and_captured(monkeypatch, run_still_current=True):+ """TurnRunner with a stub gateway runner; captures scheduled notices."""+ from gateway import run as run_mod++ captured: list[str] = []++ class _StubGatewayRunner:+ def _adapter_for_source(self, source):+ return None++ async def _deliver_platform_notice(self, source, content):+ captured.append(content)++ def _fake_schedule(coro, loop, logger=None, log_message=None):+ asyncio.run(coro)++ monkeypatch.setattr(run_mod, "safe_schedule_threadsafe", _fake_schedule)++ ctx = TurnContext(+ source=MagicMock(),+ _run_still_current=lambda: run_still_current,+ progress_queue=None,+ _loop_for_step=None,+ )+ return run_mod.TurnRunner(_StubGatewayRunner(), ctx), captured+++class TestGatewayFailureNotice:+ @pytest.mark.parametrize("status", sorted(SUBAGENT_FAILURE_STATUSES))+ def test_failure_statuses_deliver_notice(self, monkeypatch, status):+ runner, captured = _make_runner_and_captured(monkeypatch)+ runner.progress_callback(+ "subagent.complete",+ preview="Error code: 404 - model not found",+ status=status,+ goal="scan the repo",+ duration_seconds=8.0,+ )+ assert len(captured) == 1+ assert "Subagent" in captured[0]+ assert "404" in captured[0]+ assert '"scan the repo"' in captured[0]++ @pytest.mark.parametrize("status", ["completed", "interrupted", None])+ def test_non_failure_statuses_stay_silent(self, monkeypatch, status):+ runner, captured = _make_runner_and_captured(monkeypatch)+ runner.progress_callback(+ "subagent.complete", preview="all done", status=status, goal="g"+ )+ assert captured == []++ def test_stale_run_stays_silent(self, monkeypatch):+ runner, captured = _make_runner_and_captured(+ monkeypatch, run_still_current=False+ )+ runner.progress_callback(+ "subagent.complete", preview="boom", status="failed", goal="g"+ )+ assert captured == []++ def test_fires_without_progress_queue(self, monkeypatch):+ """The notice must not depend on tool_progress being enabled —+ progress_queue=None is exactly the Telegram/Slack default where the+ silent-failure report came from."""+ runner, captured = _make_runner_and_captured(monkeypatch)+ assert runner._ctx.progress_queue is None+ runner.progress_callback(+ "subagent.complete", preview="err", status="error", goal="g"+ )+ assert len(captured) == 1++ def test_summary_preferred_over_preview(self, monkeypatch):+ runner, captured = _make_runner_and_captured(monkeypatch)+ runner.progress_callback(+ "subagent.complete",+ preview="short preview",+ status="failed",+ goal="g",+ summary="the real error detail",+ )+ assert "the real error detail" in captured[0]diff --git a/tests/tools/test_delegate.py b/tests/tools/test_delegate.pyindex f7c07316ee3..230e4ced40f 100644--- a/tests/tools/test_delegate.py+++ b/tests/tools/test_delegate.py@@ -675,6 +675,35 @@ class TestDelegateObservability(unittest.TestCase):result = json.loads(delegate_task(goal="Test empty sentinel", parent_agent=parent))self.assertEqual(result["results"][0]["status"], "failed")+ def test_failed_flag_marks_status_failed(self):+ """Regression (Aug 2026 community report): a child whose conversation+ loop aborts on a non-retryable HTTP error (404/400, billing wall)+ returns failed=True with the ERROR SUMMARY in final_response. That+ summary is not usable output — without checking `failed`, the entry+ was classified 'completed' and no surface ever showed a failure."""+ parent = _make_mock_parent(depth=0)++ with patch("run_agent.AIAgent") as MockAgent:+ mock_child = MagicMock()+ mock_child.model = "totally/nonexistent-model"+ mock_child.session_prompt_tokens = 0+ mock_child.session_completion_tokens = 0+ mock_child.run_conversation.return_value = {+ "final_response": "HTTP 404: model not found",+ "completed": False,+ "failed": True,+ "error": "HTTP 404: model not found",+ "interrupted": False,+ "api_calls": 1,+ "messages": [],+ }+ MockAgent.return_value = mock_child++ result = json.loads(delegate_task(goal="Test failed flag", parent_agent=parent))+ entry = result["results"][0]+ self.assertEqual(entry["status"], "failed")+ self.assertIn("404", entry["error"])+class TestSubagentCostRollup(unittest.TestCase):"""Port of Kilo-Org/kilocode#9448 — parent's session_estimated_cost_usddiff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 342cf628475..6cd04d5ccb5 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -162,6 +162,63 @@ _RECENT_SUBAGENTS_CAP = 200_recent_subagents: Dict[str, Dict[str, Any]] = {}+# 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.+SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"})+++def _clean_error_text(error: Any, max_chars: int = 200) -> str:+ """Reduce an arbitrary error payload to one clean human-readable line.++ 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()]+ 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+++def format_subagent_failure_line(+ goal: Optional[str],+ status: Optional[str],+ 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)+ """+ 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}"+ if goal_label:+ line += f' — "{goal_label}"'+ err = _clean_error_text(error)+ if err:+ line += f": {err}"+ if isinstance(duration_seconds, (int, float)) and duration_seconds > 0:+ line += f" (after {round(duration_seconds)}s)"+ return line++def get_subagent_attribution(task_id: Optional[str]) -> Optional[Dict[str, Any]]:"""Resolve a process task_id to its originating delegation, if any.@@ -1460,6 +1517,21 @@ def _build_child_progress_callback(returnif event_type == "subagent.complete":+ # 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 below.+ if spinner and kwargs.get("status") in SUBAGENT_FAILURE_STATUSES:+ _fail_line = format_subagent_failure_line(+ goal_label,+ kwargs.get("status"),+ error=kwargs.get("summary") or preview,+ duration_seconds=kwargs.get("duration_seconds"),+ )+ try:+ spinner.print_above(f" {prefix}├─ {_fail_line}")+ except Exception as e:+ logger.debug("Spinner print_above failed: %s", e)_relay("subagent.complete", preview=preview, **kwargs)return@@ -3092,6 +3164,14 @@ def _run_single_child(if interrupted:status = "interrupted"+ elif result.get("failed"):+ # The child's conversation loop aborted (non-retryable HTTP+ # error, retries exhausted, billing wall). final_response holds+ # the error summary in this shape, NOT usable output — without+ # this branch a provider 404/400 was classified "completed" with+ # the error text as its summary, so no surface ever saw a+ # failure (community report, Aug 2026).+ status = "failed"elif summary and not _empty_sentinel:# A summary means the subagent produced usable output.# exit_reason ("completed" vs "max_iterations") already@@ -4106,6 +4186,15 @@ def delegate_task(icon = "✓" if status == "completed" else "✗"remaining = n_tasks - completed_countcompletion_line = f"{icon} [{idx+1}/{n_tasks}] {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}"if spinner_ref:try:spinner_ref.print_above(completion_line)diff --git a/website/docs/guides/delegation-patterns.md b/website/docs/guides/delegation-patterns.mdindex 9f16bb34999..d0f5bffb27d 100644--- a/website/docs/guides/delegation-patterns.md+++ b/website/docs/guides/delegation-patterns.md@@ -235,6 +235,8 @@ delegation:**Check results.** Subagent summaries are just that — summaries. If a subagent says "fixed the bug and tests pass," verify by running the tests yourself or reading the diff.+**Failures are surfaced.** A subagent that dies (provider error, timeout, crash) is reported with a clean one-line notice — `⚠️ Subagent failed — "your goal": <reason>` — in the CLI delegation tree and as a chat notice on gateway platforms, even when tool progress is turned off. The parent agent also receives the full error in the tool result.+---*For the complete delegation reference — all parameters, ACP integration, and advanced configuration — see [Subagent Delegation](/user-guide/features/delegation).*diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex 52db42d8950..95c7f949854 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -274,6 +274,16 @@ stopwatch kill from other failures without parsing text: `timeout_seconds`first request, `after_llm_calls` otherwise). All three are `null` onnon-timeout errors.+## Failure Visibility++A subagent that fails — non-retryable provider error (404/400), timeout, crash, or no usable output — is never silent:++- **CLI**: the delegation tree prints a one-line reason: `⚠️ Subagent failed — "your goal": HTTP 404: model not found (after 12s)`. Batch runs append the reason to the per-task `✗` completion line.+- **Gateway platforms** (Telegram, Discord, Slack, ...): the same clean line is delivered as a standalone chat notice, **even when `tool_progress` is off** for that platform.+- **Parent agent**: the tool result entry carries `status: "failed"` plus the full `error` text, so the model can react (retry, re-route, report).++Error text is reduced to the single most informative line (the exception message, not a traceback wall) and capped in length.+:::tip Diagnostic dump on zero-call timeoutWith a hard cap configured, if a subagent times out having made **zero** API calls (usually: provider unreachable, auth failure, or tool-schema rejection), `delegate_task` writes a structured diagnostic to `~/.hermes/logs/subagent-timeout-<session>-<timestamp>.log` containing the subagent's config snapshot, credential-resolution trace, any early error messages, and stack traces for **all** live threads (not just the child's own) — a child parked waiting on a nested helper thread is indistinguishable from a slow provider without the full picture.:::