The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegate): child_timeout_seconds bounds inactivity, not total runtime
finn76303973bd02b87
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 6bfcd5d5fbd..c6adde7d7e2 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1325,8 +1325,9 @@ DEFAULT_CONFIG = {# ~/.hermes/cache/delegation/ with a head+tail window + read_file offset footer, nothing# lost). 0 disables the ceiling; the dynamic budget still applies."max_summary_chars": 24000,- # Wall-clock cap per child (seconds, floor 30). 0 = no timeout: children fail only from real- # errors (API, tools, iteration budget).+ # Inactivity cap per child (seconds, floor 30) — time with NO progress, not total runtime. 0 = no cap:+ # children fail only from real errors (API, tools, iteration budget). A progressing child (including one+ # waiting on a multi-minute completion) restarts the window; a frozen one is caught."child_timeout_seconds": 0,# Subagent effort: "ultra" | "max" | "xhigh" | "high" | "medium" | "low" | "minimal" |# "none" (empty = inherit)diff --git a/tests/tools/test_delegate_liveness_timeout.py b/tests/tools/test_delegate_liveness_timeout.pynew file mode 100644index 00000000000..f998a5bc77b--- /dev/null+++ b/tests/tools/test_delegate_liveness_timeout.py@@ -0,0 +1,107 @@+"""``delegation.child_timeout_seconds`` bounds INACTIVITY, not total runtime (#116001).++A configured cap used to be a dispatch-to-death stopwatch: every child that ran longer than the budget was+abandoned even while the provider was actively serving it. Measured over 219 tasks / 75 deaths, 0 of 75 deaths+happened mid-tool — all of them were waiting on an in-flight LLM completion, so the cap converted transient+provider slowness into lost work (a nearly-finished context discarded every time).++These tests pin both directions of the fix:+- a child whose activity signals keep advancing outlives a cap far shorter than its runtime;+- a child with no progress at all is still abandoned when the cap elapses (the knob keeps its teeth).+"""++from __future__ import annotations++import threading+import time+from types import SimpleNamespace++from tools import delegate_tool++_CAP_SECONDS = 0.4+++class _SlowButLiveChild:+ """A provider serving multi-minute completions: the runtime outlasts the cap, but progress never stops.++ ``advance=False`` models the opposite case — a genuinely frozen child (no completed call, no tool change,+ no activity-clock tick).+ """++ def __init__(self, *, total_seconds: float = 1.2, advance: bool = True, initial_calls: int = 0) -> None:+ self.tool_progress_callback = None+ self._credential_pool = None+ self._delegate_saved_tool_names = []+ self._delegate_role = "leaf"+ self._delegate_depth = 1+ self._subagent_id = None+ self.session_id = "live-child"+ self.model = "test/model"+ self._total_seconds = total_seconds+ self._advance = advance+ self._calls = initial_calls+ self._activity_ts = time.time()+ self.interrupted = threading.Event()++ def run_conversation(self, **_kwargs):+ deadline = time.monotonic() + self._total_seconds+ while time.monotonic() < deadline:+ time.sleep(0.05)+ if self._advance:+ self._calls += 1+ self._activity_ts = time.time()+ return {+ "final_response": "FINISHED AFTER OUTLIVING THE CAP",+ "completed": True,+ "api_calls": self._calls,+ "messages": [],+ }++ def get_activity_summary(self):+ return {+ "api_call_count": self._calls,+ "current_tool": None,+ "last_activity_ts": self._activity_ts,+ "max_iterations": 50,+ }++ def hard_interrupt(self, *_args, **_kwargs):+ self.interrupted.set()++ def close(self):+ pass+++def _run(child, monkeypatch, cap=_CAP_SECONDS):+ parent = SimpleNamespace(+ session_id="parent", _current_task_id=None, _active_children=[child],+ _active_children_lock=threading.Lock(), _touch_activity=lambda _d: None, _interrupt_requested=False,+ )+ monkeypatch.setattr(delegate_tool, "_get_child_timeout", lambda: cap)+ monkeypatch.setattr(delegate_tool, "_get_worktree_isolation", lambda: False)+ return delegate_tool._run_single_child(0, "watch the slow provider", child=child, parent_agent=parent)+++def test_progressing_child_outlives_a_cap_shorter_than_its_runtime(monkeypatch):+ child = _SlowButLiveChild(total_seconds=1.2, advance=True)++ entry = _run(child, monkeypatch)++ assert entry["status"] == "completed", entry+ assert entry["summary"] == "FINISHED AFTER OUTLIVING THE CAP", entry+ # The cap really was armed and the child really did run past it: the budget reset on progress.+ assert entry["duration_seconds"] > _CAP_SECONDS, entry+ assert not child.interrupted.is_set()+++def test_frozen_child_is_still_abandoned_when_the_cap_elapses(monkeypatch):+ """The reported death shape: calls completed earlier, then the child stops moving entirely."""+ child = _SlowButLiveChild(total_seconds=1.2, advance=False, initial_calls=49)++ entry = _run(child, monkeypatch)++ assert entry["status"] == "timeout", entry+ assert "no progress in that window" in entry["error"], entry["error"]+ assert entry["timeout_seconds"] == _CAP_SECONDS+ assert entry["last_event_age"] is not None and entry["last_event_age"] > 0.3, entry+ assert child.interrupted.is_set()diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.pyindex 5cad59da6f0..ed7b50d6924 100644--- a/tools/delegate_tool_child_run.py+++ b/tools/delegate_tool_child_run.py@@ -221,6 +221,30 @@ def _dump_subagent_timeout_diagnostic(# ── Per-run helpers ──────────────────────────────────────────────────────────+# Granularity for re-checking a child's progress while a configured ``child_timeout_seconds`` budget runs.+# Five seconds is finer than the 30s heartbeat and cheap (one activity-summary read per slice).+_LIVENESS_POLL_SECONDS = 5.0++def _child_activity_fingerprint(child: Any) -> tuple:+ """``(completed calls, current tool, activity clock)`` — the progress signals the heartbeat's stale verdict+ already watches. A child waiting on an in-flight LLM completion is ALIVE: its activity clock ticks while the+ provider works (``direct_api_call``'s 15s heartbeat) and the call itself is bounded by the per-call stale+ watchdog, so at the delegation layer it must not read as stuck (#116001)."""+ try:+ summary = child.get_activity_summary() or {}+ except Exception:+ return (None, None, None)+ return (summary.get("api_call_count"), summary.get("current_tool"), summary.get("last_activity_ts"))++def _child_last_event_age(child: Any) -> Optional[float]:+ """Seconds since the child's activity clock last ticked, or None when the child exposes no clock. Reported on a+ timeout so an operator can tell a slow-but-live provider from a runaway without transcript forensics."""+ try:+ ts = (child.get_activity_summary() or {}).get("last_activity_ts")+ return round(max(0.0, time.time() - float(ts)), 2) if ts is not None else None+ except Exception:+ return None+class _Heartbeat:"""One child's parent-activity heartbeat via the shared periodic scheduler(``agent.periodic_scheduler``) — not one daemon thread per child. NOT started at construction:@@ -743,6 +767,33 @@ class _ChildRun:"""Close steer acceptance (see ``_merge_late_steer``); returns late steer text, if any."""return _close_subagent_steering(self.subagent_id, self.child) if self.subagent_id else None+ def wait_liveness_aware(self, settled: threading.Event, child_future: Any, child_timeout: Optional[float]) -> None:+ """Wait for the worker or the stale verdict, where ``child_timeout`` bounds INACTIVITY, not total runtime.++ A configured cap used to be a dispatch-to-death stopwatch, so it only ever killed children the runtime had+ already judged healthy: all 75 reported deaths happened while waiting on an in-flight LLM completion, none+ mid-tool (#116001). A provider serving multi-minute completions is progress — the child's activity clock+ ticks during the wait and the request is bounded by the per-call stale watchdog — so the budget restarts on+ every sign of progress, exactly the signals the heartbeat's stale verdict reads. Genuinely frozen children+ keep two authorities: this budget (when configured) and the heartbeat's stale threshold.+ """+ if child_timeout is None:+ settled.wait()+ return+ deadline = time.monotonic() + child_timeout+ fingerprint = _child_activity_fingerprint(self.child)+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return # no progress for the whole budget+ settled.wait(timeout=min(_LIVENESS_POLL_SECONDS, remaining))+ if settled.is_set():+ return # the worker finished, or the heartbeat declared the child stale+ current = _child_activity_fingerprint(self.child)+ if current != fingerprint:+ fingerprint = current+ deadline = time.monotonic() + child_timeout+def await_child(self) -> tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]], bool]:"""Run the child's conversation on a daemon worker: ``(result, None, False)`` or ``(None, error_entry,close_deferred)`` on timeout/exception.@@ -781,13 +832,13 @@ class _ChildRun:# One wait covers both ways out: the worker finishing, or the heartbeat's stale verdict.# Without the second, a worker wedged after its final answer holds a finite (-Q / Bot Chat# one-shot) turn — and its session lease — forever, since that runtime has no gateway- # inactivity watchdog (#109749).+ # inactivity watchdog (#109749). The configured cap bounds INACTIVITY (see wait_liveness_aware).settled = self.heartbeat.settled if self.heartbeat is not None else threading.Event()future.add_done_callback(lambda _f: settled.set())# Set when the stale verdict — not the configured cap — ended the wait; the entry must name that cause.stale_after: Optional[float] = Nonetry:- settled.wait(timeout=child_timeout)+ self.wait_liveness_aware(settled, future, child_timeout)if not future.done():stale_after = getattr(self.heartbeat, "stale_threshold_seconds", None)raise FuturesTimeoutError()@@ -834,8 +885,9 @@ class _ChildRun:)else:_err = (- f"Subagent timed out after {child_timeout}s with {child_api_calls} API call(s) completed — likely "- f"stuck on a slow API call, tool call, or unresponsive network request."+ f"Subagent timed out after {child_timeout}s with {child_api_calls} API call(s) completed — no "+ f"progress in that window (no completed call, tool change, or activity-clock tick): a stalled "+ f"provider request or an unresponsive network request.")if diagnostic_path:_err += f" Diagnostic: {diagnostic_path}"@@ -846,6 +898,9 @@ class _ChildRun:"timeout_seconds": timeout_cause if is_timeout else None,"timed_out_after_seconds": duration if is_timeout else None,"timeout_phase": "before_first_llm_call" if before_first_call else "after_llm_calls" if is_timeout else None,+ # How long the child had been silent when the wait ended: distinguishes a slow provider from a runaway+ # without transcript forensics (#116001).+ "last_event_age": _child_last_event_age(child) if is_timeout else None,"_child_role": getattr(child, "_delegate_role", None),"diagnostic_path": diagnostic_path,}diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.pyindex d85a04db040..10b5e069250 100644--- a/tools/delegate_tool_config.py+++ b/tools/delegate_tool_config.py@@ -137,10 +137,12 @@ def _parse_timeout(raw: Any) -> Optional[float]: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). Failures should come from what the child does- (API/tool errors, iteration budget), not a stopwatch; stuck children are caught by the heartbeat staleness- monitor. delegation.child_timeout_seconds > 0 opts in (floor 30 s); 0 or negative disables. Env fallback:- DELEGATION_CHILD_TIMEOUT_SECONDS."""+ """Inactivity cap for one child (seconds of NO progress), or None (default: no cap). Failures should come from+ what the child does (API/tool errors, iteration budget), not a stopwatch: the cap restarts on every sign of+ progress — a completed call, a tool change, an activity-clock tick — so a slow provider serving multi-minute+ completions never loses a live child, and a child frozen for the whole window is still caught. A configured+ value pre-empts nothing the heartbeat staleness monitor would not also catch. delegation.child_timeout_seconds+ > 0 opts in (floor 30 s); 0 or negative disables. Env fallback: DELEGATION_CHILD_TIMEOUT_SECONDS."""return _knob("child_timeout_seconds", "DELEGATION_CHILD_TIMEOUT_SECONDS", _parse_timeout, DEFAULT_CHILD_TIMEOUT,"delegation.child_timeout_seconds=%r is not a valid number; using default (no timeout)",diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.mdindex a503bd41e60..f7470ce0e1a 100644--- a/website/docs/user-guide/features/delegation.md+++ b/website/docs/user-guide/features/delegation.md@@ -357,24 +357,26 @@ By default there is **no wall-clock timeout** on subagents. Children fail only fGenuinely stuck children are still detected on every runtime, with or without a configured cap: the heartbeat staleness monitor watches each child's progress signals (API calls, tool starts, activity-timestamp ticks). A child whose progress is completely frozen past the stale threshold — 450s idle between turns, 1200s while inside a tool — is interrupted and its wait is **abandoned**: the parent gets a `status: "timeout"` entry whose error reads `Subagent stopped making progress after N API call(s) — no activity for 450s (heartbeat stale threshold); the pending worker was abandoned.` The wait ends even in one-shot runs (`hermes chat -Q`, Bot Chat one-shot, cron) that have no gateway inactivity watchdog behind them, so a wedged child can no longer hold the turn or its session lease forever. An in-flight model wait still counts as progress — subagents refresh the activity clock while waiting on the provider, so a slow local / long-prefill completion is not treated as stalled.-If you want a hard cap anyway (e.g. cost control on unattended cron-driven delegation), opt in per-install:+If you want a cap anyway (e.g. cost control on unattended cron-driven delegation), opt in per-install:```yamldelegation:child_timeout_seconds: 0 # default: 0 = no timeout- # child_timeout_seconds: 1800 # opt-in hard cap (floor 30s)+ # child_timeout_seconds: 1800 # opt-in inactivity cap (floor 30s)```-A positive value enforces a hard wall-clock limit on each child; `0` or a negative value disables it.+A positive value bounds **inactivity, not total runtime**: it is the longest a child may go with *no* progress (no completed API call, no tool change, no activity-clock tick) before it is abandoned. Every sign of progress restarts the window, so a child waiting on a multi-minute completion — the case that used to lose finished work — is never killed for taking long, while a child that has genuinely stopped moving is still caught (and an in-flight request is bounded independently by the per-call stale watchdog). `0` or a negative value disables the cap; the heartbeat staleness monitor below stays active either way.When a configured cap or the stale threshold fires, the child's result carriesstructured timeout metadata alongside the error message so parents and hookscan distinguish a stopwatch kill from other failures without parsing text:`timeout_seconds` (whichever limit actually ended the wait — the stalethreshold when it pre-empts a longer configured cap, otherwise the cap),-`timed_out_after_seconds` (actual wall clock), and `timeout_phase`+`timed_out_after_seconds` (actual wall clock), `last_event_age` (how long+the child had been silent when the wait ended — the fast way to tell a slow+provider from a runaway), and `timeout_phase`(`before_first_llm_call` when the child never reached its first request,-`after_llm_calls` otherwise). All three are `null` on non-timeout errors.+`after_llm_calls` otherwise). All four are `null` on non-timeout errors.## Failure Visibilitydiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.mdindex 571053d513f..e74cb5ea715 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/delegation.md@@ -231,15 +231,15 @@ delegate_task(真正卡死的子智能体仍会被检测到:当子智能体没有任何进展(无 API 调用、无工具启动)时,心跳陈旧度监控会停止刷新父智能体的活动状态,从而让网关的不活动超时机制对真正卡死的工作进程生效。-如果仍需要硬性上限(例如对无人值守的 cron 驱动委派进行成本控制),可按安装实例选择启用:+如果仍需要上限(例如对无人值守的 cron 驱动委派进行成本控制),可按安装实例选择启用:```yamldelegation:child_timeout_seconds: 0 # 默认:0 = 无超时- # child_timeout_seconds: 1800 # 选择启用的硬性上限(下限 30 秒)+ # child_timeout_seconds: 1800 # 选择启用的「无进展」上限(下限 30 秒)```-正值会对每个子智能体强制执行挂钟时间硬限制;`0` 或负值表示禁用。+正值限制的是**无进展时间,而不是总运行时长**:它是子智能体在完全没有进展(没有完成的 API 调用、没有工具切换、活动时钟没有跳动)的情况下可以持续的最长时间,超过后才被放弃。任何进展迹象都会重新开始计时,因此正在等待耗时数分钟的补全任务的子智能体不会因为「耗时长」被终止(过去正是这种情况丢掉了已完成的工作);而真正停止推进的子智能体仍会被捕获(且进行中的请求本身还受单次调用 stale 看门狗约束)。`0` 或负值表示禁用;无论是否配置,下述心跳陈旧度监控始终生效。:::tip 零调用超时时的诊断转储在配置了硬性上限的情况下,如果子智能体在**零次** API 调用的情况下超时(通常原因:provider 不可达、认证失败或工具 schema 被拒绝),`delegate_task` 会将结构化诊断信息写入 `~/.hermes/logs/subagent-timeout-<session>-<timestamp>.log`,其中包含子智能体的配置快照、凭据解析追踪以及早期错误消息。比之前的静默超时行为更易于定位根因。