The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hermes_cli): scope hook timeouts and fail closed on pre_tool_call
fangliquanflq091cc0e8be62
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex cc24a10ec56..c9bf9ad6e2a 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2535,6 +2535,16 @@ DEFAULT_CONFIG = {# table_formatting skill instead of emitting a Markdown table."platform_hints": {},+ # Plugin system settings. ``enabled`` / ``disabled`` are written by+ # ``hermes plugins enable|disable`` and intentionally omitted here so an+ # empty default does not clobber a user's allow-list on merge.+ "plugins": {+ # Wall-clock cap (seconds) for a single in-process Python plugin hook+ # callback. Shell hooks keep their own per-entry ``timeout``. Set to 0+ # to disable the cap (sync call on the agent thread). Capped at 600.+ "hook_callback_timeout": 30,+ },+# Shell-script hooks — declarative bridge that invokes shell scripts# on plugin-hook events (pre_tool_call, post_tool_call, pre_llm_call,# subagent_stop, etc.). Each entry maps an event name to a list ofdiff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex d02ee62fb96..0d6dc6a38aa 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -34,6 +34,7 @@ so plugin-defined tools appear alongside the built-in tools.from __future__ import annotationsimport asyncio+import contextvarsimport copyimport hashlibimport importlib.metadata@@ -46,6 +47,7 @@ import queueimport reimport sysimport threading+import timeimport typesfrom contextlib import contextmanagerfrom dataclasses import dataclass, field@@ -396,6 +398,62 @@ SHELL_UNSUPPORTED_HOOKS: Set[str] = {"transform_api_error_classification",}+# Timeout coverage is an allowlist for the agent-turn hot path, not every+# entry in VALID_HOOKS. The goal is to stop a hung Python plugin callback from+# wedging the conversation loop (#76821) without joining the worker (avoids+# the #6622 ThreadPoolExecutor shutdown hang). Hooks not listed below run+# synchronously to completion.+#+# Intentionally unbounded (no hook_callback_timeout wrapper):+# - on_session_finalize / on_session_reset — infrequent teardown / session+# swap; finalize is a last-chance flush where fail-open abandon can lose+# state. (on_session_start/end stay bounded — they sit on the common+# session-boundary path.)+# - subagent_start — observer only; blocking delegation belongs in+# pre_tool_call. Lower frequency than tool/LLM hooks.+# - pre_gateway_dispatch — policy gate (skip/rewrite/allow). Abandoning is+# unsafe either way (fail-open skips auth-like checks; fail-closed can+# drop legitimate messages). Prefer finish-or-exception fallthrough.+# - pre_approval_request / post_approval_response — observers only (cannot+# veto); the approval UX already has its own timeout; not on the tool+# loop hot path.+# - kanban_task_* — fire after the board DB commit, observers only, in+# dispatcher/worker processes; kanban has its own heartbeat/stale reclaim.+# Abandon-without-join also leaves a daemon thread that may still mutate+# shared state — safer for value-returning observers than for gates/flushes.+#+# Bounded hooks: timeout is fail-open (abandon/skip, agent continues).+_HOOK_TIMEOUT_BOUNDED_HOOKS: Set[str] = {+ "post_tool_call",+ "transform_terminal_output",+ "transform_tool_result",+ "transform_llm_output",+ "pre_llm_call",+ "post_llm_call",+ "pre_api_request",+ "post_api_request",+ "api_request_error",+ "pre_verify",+ "on_session_start",+ "on_session_end",+}++# Policy hooks: timeout / still-running must fail closed (block the tool).+# Skipping would let the tool run without a completed policy decision.+_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS: Set[str] = {"pre_tool_call"}++# Documented parent-thread serialization contract — never move the callback+# body onto a timeout worker (see website/docs/user-guide/features/hooks.md).+_HOOK_CALLER_THREAD_HOOKS: Set[str] = {"subagent_stop"}++# After a timeout, suppress re-firing the same callback for this long so a+# repeatedly invoked hung hook cannot accumulate abandoned daemon threads.+_HOOK_TIMEOUT_SUPPRESSION_SECONDS = 60.0++_PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE = (+ "pre_tool_call plugin callback timed out or is still running"+)+ENTRY_POINTS_GROUP = "hermes_agent.plugins"ENTRY_POINT_CAPABILITIES_GROUP = "hermes_agent.plugin_capabilities"@@ -3467,6 +3525,78 @@ class PluginContext:return handle+# ---------------------------------------------------------------------------+# Hook callback timeout (non-blocking abandon)+# ---------------------------------------------------------------------------++# Default wall-clock cap for a single Python plugin hook callback. Overridden+# by ``plugins.hook_callback_timeout`` in config.yaml (see DEFAULT_CONFIG).+# Shell hooks already enforce their own subprocess timeout.+_HOOK_CALLBACK_TIMEOUT_SECS = 30.0+_MAX_HOOK_CALLBACK_TIMEOUT_SECS = 600.0+++def _resolve_hook_callback_timeout() -> float:+ """Return the effective hook-callback timeout in seconds.++ Reads ``plugins.hook_callback_timeout`` via the cached readonly config+ loader. Falls back to ``_HOOK_CALLBACK_TIMEOUT_SECS``. Values ``<= 0``+ disable the threaded timeout (sync call). Values above+ ``_MAX_HOOK_CALLBACK_TIMEOUT_SECS`` are clamped.+ """+ timeout = _HOOK_CALLBACK_TIMEOUT_SECS+ try:+ from hermes_cli.config import load_config_readonly++ plugins_cfg = (load_config_readonly() or {}).get("plugins")+ if isinstance(plugins_cfg, dict) and "hook_callback_timeout" in plugins_cfg:+ raw = plugins_cfg.get("hook_callback_timeout")+ if raw is not None:+ timeout = float(raw)+ except (TypeError, ValueError):+ logger.warning(+ "plugins.hook_callback_timeout is not a number; using default %gs",+ _HOOK_CALLBACK_TIMEOUT_SECS,+ )+ timeout = _HOOK_CALLBACK_TIMEOUT_SECS+ except Exception:+ timeout = _HOOK_CALLBACK_TIMEOUT_SECS++ if timeout < 0:+ logger.warning(+ "plugins.hook_callback_timeout=%g is negative; using default %gs",+ timeout,+ _HOOK_CALLBACK_TIMEOUT_SECS,+ )+ return _HOOK_CALLBACK_TIMEOUT_SECS+ if timeout > _MAX_HOOK_CALLBACK_TIMEOUT_SECS:+ logger.warning(+ "plugins.hook_callback_timeout=%g exceeds max %gs; clamping",+ timeout,+ _MAX_HOOK_CALLBACK_TIMEOUT_SECS,+ )+ return _MAX_HOOK_CALLBACK_TIMEOUT_SECS+ return timeout+++def _hook_uses_callback_timeout(hook_name: str, timeout: float) -> bool:+ """Whether *hook_name* should run under the non-blocking timeout path."""+ if timeout <= 0 or hook_name in _HOOK_CALLER_THREAD_HOOKS:+ return False+ return (+ hook_name in _HOOK_TIMEOUT_BOUNDED_HOOKS+ or hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS+ )+++def _pre_tool_call_timeout_block() -> Dict[str, str]:+ """Fail-closed directive when a policy callback times out or is still running."""+ return {+ "action": "block",+ "message": _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE,+ }++# ---------------------------------------------------------------------------# PluginManager# ---------------------------------------------------------------------------@@ -3523,6 +3653,13 @@ class PluginManager:# ``re.Pattern``, or a constraint dict); ``callback`` is an async# function with the slack_bolt signature ``(ack, body, action)``.self._slack_action_handlers: List[tuple] = []+ # In-flight / recently-timed-out hook callbacks. Keyed by+ # (hook_name, id(cb)) so a stuck policy hook cannot spawn a new+ # abandoned daemon thread on every subsequent fire.+ self._hook_running_callbacks: Dict[tuple, object] = {}+ self._hook_timeout_suppressed_until: Dict[tuple, float] = {}+ self._hook_timeout_lock = threading.Lock()+ self._hook_timeout_suppression_seconds = _HOOK_TIMEOUT_SUPPRESSION_SECONDS# Registration handles are kept both per plugin (ownership lookup) and# globally (reverse-order teardown for overrides spanning plugins).#@@ -3902,6 +4039,9 @@ class PluginManager:self._predeclared_modules.clear()self._predeclared_tools.clear()self._context_engine = None+ with self._hook_timeout_lock:+ self._hook_running_callbacks.clear()+ self._hook_timeout_suppressed_until.clear()self._discovered = Falseelse:for key in target_keys:@@ -5286,6 +5426,17 @@ class PluginManager:wrapped in its own try/except so a misbehaving plugin cannot break thecore agent loop.+ Hot-path / observer hooks in ``_HOOK_TIMEOUT_BOUNDED_HOOKS`` and the+ policy hook ``pre_tool_call`` are bounded by+ ``plugins.hook_callback_timeout`` (default 30s). On timeout the worker+ is abandoned (not joined) so we do not reintroduce the #6622 hang.+ Timed-out or still-running ``pre_tool_call`` callbacks fail closed+ with a block directive; other bounded hooks fail open (skip).++ ``subagent_stop`` (and any hook in ``_HOOK_CALLER_THREAD_HOOKS``)+ always runs on the caller thread to preserve the documented parent-+ thread serialization contract.+Returns a list of non-``None`` return values from callbacks.For ``pre_llm_call``, callbacks may return a dict describing@@ -5308,16 +5459,97 @@ class PluginManager:kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION)callbacks = self._hooks.get(hook_name, [])results: List[Any] = []+ timeout = _resolve_hook_callback_timeout()+ use_timeout = _hook_uses_callback_timeout(hook_name, timeout)+ fail_closed = hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS+for cb in callbacks:+ callback_name = getattr(cb, "__name__", repr(cb))+ callback_key = (hook_name, id(cb))try:- ret = self._invoke_hook_callback(cb, kwargs)+ if use_timeout:+ token = object()+ now = time.monotonic()+ with self._hook_timeout_lock:+ suppressed_until = self._hook_timeout_suppressed_until.get(+ callback_key+ )+ running = callback_key in self._hook_running_callbacks+ if (+ suppressed_until is not None and suppressed_until > now+ ) or running:+ logger.warning(+ "Hook '%s' callback %s skipped after previous "+ "timeout or while still running",+ hook_name,+ callback_name,+ )+ if fail_closed:+ results.append(_pre_tool_call_timeout_block())+ continue+ if suppressed_until is not None:+ self._hook_timeout_suppressed_until.pop(callback_key, None)+ self._hook_running_callbacks[callback_key] = token++ context = contextvars.copy_context()+ done = threading.Event()+ outcome: Dict[str, Any] = {}+ failure: Dict[str, Exception] = {}++ def _runner(+ _cb: Callable[..., Any] = cb,+ _key: tuple = callback_key,+ _token: object = token,+ ) -> None:+ try:+ # Route through _invoke_hook_callback so the+ # additive-payload signature filtering (narrow+ # legacy callbacks) applies on the worker too.+ outcome["value"] = context.run(+ self._invoke_hook_callback, _cb, kwargs+ )+ except Exception as exc:+ failure["exc"] = exc+ finally:+ with self._hook_timeout_lock:+ if self._hook_running_callbacks.get(_key) is _token:+ self._hook_running_callbacks.pop(_key, None)+ done.set()++ thread = threading.Thread(+ target=_runner,+ name=f"hermes-hook-{callback_name}"[:40],+ daemon=True,+ )+ thread.start()+ if not done.wait(timeout=timeout):+ # Do not join — that would reintroduce the #6622 hang.+ with self._hook_timeout_lock:+ self._hook_timeout_suppressed_until[callback_key] = (+ time.monotonic()+ + self._hook_timeout_suppression_seconds+ )+ logger.warning(+ "Hook '%s' callback %s timed out after %gs — skipping",+ hook_name,+ callback_name,+ timeout,+ )+ if fail_closed:+ results.append(_pre_tool_call_timeout_block())+ continue+ if "exc" in failure:+ raise failure["exc"]+ ret = outcome.get("value")+ else:+ ret = self._invoke_hook_callback(cb, kwargs)if ret is not None:results.append(ret)except Exception as exc:logger.warning("Hook '%s' callback %s raised: %s",hook_name,- getattr(cb, "__name__", repr(cb)),+ callback_name,exc,)return resultsdiff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 1ca811f35af..2d27c5da980 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -1344,6 +1344,16 @@ _SCHEMA_OVERRIDES: Dict[str, Dict[str, Any]] = {"type": "boolean","description": "Run the local browser in headed mode (visible window). Also keeps the window open between turns; idle sessions are still reaped after browser.inactivity_timeout.",},+ "plugins.hook_callback_timeout": {+ "type": "number",+ "description": (+ "Wall-clock cap (seconds) for timeout-bounded in-process Python "+ "plugin hook callbacks (hot-path observers + pre_tool_call). "+ "Timed-out pre_tool_call fails closed. 0 disables the cap; "+ "values above 600 are clamped. Caller-thread hooks such as "+ "subagent_stop are never moved onto a timeout worker."+ ),+ },}# Categories with fewer fields get merged into "general" to avoid tab sprawl.@@ -1388,6 +1398,10 @@ _CATEGORY_MERGE: Dict[str, str] = {# `telemetry.shared_metrics.enabled` is the only schema-surfaced telemetry# field — fold it into security alongside the other privacy-posture toggles."telemetry": "security",+ # `plugins.hook_callback_timeout` is the only schema-surfaced plugins field+ # (`enabled`/`disabled` are list allow-lists omitted from DEFAULT_CONFIG) —+ # fold it into the agent tab rather than spawning a one-field orphan category.+ "plugins": "agent",# `doctor.live_probe_timeout` is the only schema-surfaced doctor field —# fold it into general rather than spawning a one-field orphan category."doctor": "general",diff --git a/tests/agent/test_subagent_stop_hook.py b/tests/agent/test_subagent_stop_hook.pyindex 6aa30bc5169..b38c765280b 100644--- a/tests/agent/test_subagent_stop_hook.py+++ b/tests/agent/test_subagent_stop_hook.py@@ -2,7 +2,8 @@Covers wire-up from tools.delegate_tool.delegate_task:* fires once per child in both single-task and batch modes- * runs on the parent thread (no re-entrancy for hook authors)+ * is dispatched from the parent thread (no child-pool re-entrancy)+ and callback bodies stay on that caller thread* carries child_role when the agent exposes _delegate_role* carries child_role=None when _delegate_role is not set (pre-M3)* exposes a detached, metadata-only tool_call_history@@ -108,10 +109,19 @@ class TestSingleTask:assert payload["duration_ms"] == 5000def test_fires_on_parent_thread(self):+ """Dispatch and callback body stay on the parent/caller thread."""captured = _register_capturing_hook()main_thread = threading.current_thread()+ dispatch_threads = []+ real_invoke = plugins.invoke_hook- with patch("tools.delegate_tool._run_single_child") as mock_run:+ def _tracking_invoke(hook_name, **kwargs):+ if hook_name == "subagent_stop":+ dispatch_threads.append(threading.current_thread())+ return real_invoke(hook_name, **kwargs)++ with patch("tools.delegate_tool._run_single_child") as mock_run, \+ patch("hermes_cli.plugins.invoke_hook", side_effect=_tracking_invoke):mock_run.return_value = {"task_index": 0, "status": "completed","summary": "x", "api_calls": 1, "duration_seconds": 0.1,@@ -119,7 +129,9 @@ class TestSingleTask:}delegate_task(goal="go", parent_agent=_make_parent())- assert captured[0]["_thread"] is main_thread+ assert dispatch_threads and all(t is main_thread for t in dispatch_threads)+ cb_thread = captured[0]["_thread"]+ assert cb_thread is main_threaddef test_payload_includes_parent_session_id(self):captured = _register_capturing_hook()@@ -171,10 +183,19 @@ class TestBatchMode:assert roles == ["role-a", "role-b", "role-c"]def test_all_fires_on_parent_thread(self):+ """Batch stop hooks are dispatched from the parent, not child workers."""captured = _register_capturing_hook()main_thread = threading.current_thread()+ dispatch_threads = []+ real_invoke = plugins.invoke_hook- with patch("tools.delegate_tool._run_single_child") as mock_run:+ def _tracking_invoke(hook_name, **kwargs):+ if hook_name == "subagent_stop":+ dispatch_threads.append(threading.current_thread())+ return real_invoke(hook_name, **kwargs)++ with patch("tools.delegate_tool._run_single_child") as mock_run, \+ patch("hermes_cli.plugins.invoke_hook", side_effect=_tracking_invoke):mock_run.side_effect = [{"task_index": 0, "status": "completed","summary": "A", "api_calls": 1, "duration_seconds": 1.0,diff --git a/tests/hermes_cli/test_plugins.py b/tests/hermes_cli/test_plugins.pyindex b533cd7d4d0..998dcfed1c2 100644--- a/tests/hermes_cli/test_plugins.py+++ b/tests/hermes_cli/test_plugins.py@@ -3,6 +3,7 @@import loggingimport jsonimport sys+import threadingimport typesfrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -1010,6 +1011,214 @@ class TestForceReloadSymmetry:assert not shell_hooks_mod._registeredassert recorded["cfg"] == {"hooks": {}}+ def test_hook_timeout_does_not_block_caller(self, monkeypatch):+ """A hung callback must be abandoned without joining the worker.++ Regression for the #6622 approach: ThreadPoolExecutor + result(timeout)+ inside a ``with`` still waits on shutdown after TimeoutError.+ """+ import time++ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 0.15+ )++ hold = threading.Event()+ started = threading.Event()++ def blocker(**_kwargs):+ started.set()+ hold.wait(timeout=10.0)+ return "late"++ def fast(**_kwargs):+ return {"ok": True}++ mgr = PluginManager()+ mgr._hooks["post_tool_call"] = [blocker, fast]++ t0 = time.monotonic()+ results = mgr.invoke_hook(+ "post_tool_call",+ tool_name="terminal",+ args={},+ result="{}",+ )+ elapsed = time.monotonic() - t0++ assert started.wait(timeout=1.0)+ assert results == [{"ok": True}]+ assert elapsed < 1.0, f"caller blocked for {elapsed:.2f}s after timeout"+ hold.set()++ def test_hook_callback_within_timeout_returns_value(self, monkeypatch):+ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 1.0+ )+ mgr = PluginManager()+ mgr._hooks["pre_llm_call"] = [lambda **_kw: {"context": "hi"}]+ assert mgr.invoke_hook("pre_llm_call", session_id="s1") == [+ {"context": "hi"}+ ]++ def test_hook_exception_still_isolated_under_timeout_path(self, monkeypatch):+ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 1.0+ )++ def boom(**_kwargs):+ raise RuntimeError("plugin blew up")++ mgr = PluginManager()+ mgr._hooks["post_tool_call"] = [boom, lambda **_kw: "survived"]+ assert mgr.invoke_hook("post_tool_call") == ["survived"]++ def test_hook_callback_timeout_reads_config(self, tmp_path, monkeypatch):+ hermes_home = tmp_path / "hermes_test"+ hermes_home.mkdir(parents=True, exist_ok=True)+ (hermes_home / "config.yaml").write_text(+ yaml.safe_dump({"plugins": {"hook_callback_timeout": 0.12}})+ )+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))++ import hermes_cli.config as config_mod++ config_mod._LOAD_CONFIG_CACHE.clear()+ config_mod._RAW_CONFIG_CACHE.clear()++ import hermes_cli.plugins as plugins_mod++ assert plugins_mod._resolve_hook_callback_timeout() == 0.12++ def test_subagent_stop_stays_on_caller_thread(self, monkeypatch):+ """Caller-thread hooks must not move the body onto a timeout worker."""+ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 1.0+ )+ seen = {}++ def capture(**_kwargs):+ seen["thread"] = threading.current_thread()+ return "ok"++ mgr = PluginManager()+ mgr._hooks["subagent_stop"] = [capture]+ caller = threading.current_thread()+ assert mgr.invoke_hook("subagent_stop", parent_session_id="p1") == ["ok"]+ assert seen["thread"] is caller++ def test_hung_callback_suppresses_repeat_fires(self, monkeypatch):+ """A still-running timed-out callback must not spawn another worker."""+ import time++ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 0.1+ )++ hold = threading.Event()+ starts = []++ def blocker(**_kwargs):+ starts.append(1)+ hold.wait(timeout=10.0)+ return "late"++ mgr = PluginManager()+ mgr._hooks["post_tool_call"] = [blocker]++ t0 = time.monotonic()+ assert mgr.invoke_hook("post_tool_call") == []+ assert mgr.invoke_hook("post_tool_call") == []+ elapsed = time.monotonic() - t0++ assert len(starts) == 1+ assert elapsed < 1.0+ hold.set()++ def test_pre_tool_call_timeout_fail_closed(self, monkeypatch):+ """Timed-out pre_tool_call must return a block directive, not allow."""+ import time++ from hermes_cli.plugins import (+ _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE,+ resolve_pre_tool_block,+ )++ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 0.1+ )++ hold = threading.Event()++ def hung_policy(**_kwargs):+ hold.wait(timeout=10.0)+ return None++ mgr = PluginManager()+ mgr._hooks["pre_tool_call"] = [hung_policy]++ import hermes_cli.plugins as plugins_mod++ monkeypatch.setattr(plugins_mod, "_plugin_manager", mgr)++ t0 = time.monotonic()+ msg = resolve_pre_tool_block("web_search", {"query": "x"})+ elapsed = time.monotonic() - t0++ assert msg == _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE+ assert elapsed < 1.0++ # Still-running / suppression window must also fail closed.+ msg2 = resolve_pre_tool_block("web_search", {"query": "y"})+ assert msg2 == _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE+ hold.set()++ def test_pre_tool_call_timeout_does_not_reach_tool_handler(self, monkeypatch):+ """E2E: timed-out pre_tool_call blocks handle_function_call before dispatch."""+ import json++ from hermes_cli.plugins import _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE++ monkeypatch.setattr(+ "hermes_cli.plugins._resolve_hook_callback_timeout", lambda: 0.1+ )++ hold = threading.Event()++ def hung_policy(**_kwargs):+ hold.wait(timeout=10.0)+ return None++ mgr = PluginManager()+ mgr._hooks["pre_tool_call"] = [hung_policy]++ import hermes_cli.plugins as plugins_mod++ monkeypatch.setattr(plugins_mod, "_plugin_manager", mgr)++ dispatch_calls = []++ def _dispatch(name, args, **kwargs):+ dispatch_calls.append((name, args))+ return json.dumps({"ok": True})++ mock_registry = MagicMock()+ mock_registry.dispatch.side_effect = _dispatch++ with patch("model_tools.registry", mock_registry):+ from model_tools import handle_function_call++ result = handle_function_call(+ "web_search",+ {"query": "test"},+ task_id="t1",+ session_id="s1",+ )++ assert dispatch_calls == []+ assert _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE in result+ hold.set()+class TestPreToolCallBlocking:"""Tests for the pre_tool_call block directive helper."""diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex ace2d2998c7..8ef9e7b180c 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -383,6 +383,7 @@ def register(ctx):- Callbacks receive **keyword arguments**. Always accept `**kwargs` for forward compatibility.- Callback exceptions are logged and skipped; later callbacks continue.+- If a Python plugin callback on a **timeout-bounded** hook (hot-path observers such as `post_tool_call` / `pre_llm_call`, plus the policy hook `pre_tool_call`) **blocks** longer than `plugins.hook_callback_timeout` (default 30s, set `0` to disable, max 600), it is abandoned without joining the worker so the agent loop continues. Timed-out or still-running `pre_tool_call` callbacks **fail closed** (block the tool); other bounded hooks fail open (skip). Hooks with a documented caller-thread contract (`subagent_stop`) are never moved onto a timeout worker. Shell hooks keep their own per-entry `timeout`.- The catalog below is descriptive: **observers** ignore returns, **transforms** accept the first valid string replacement, and **directive/control** hooks consume documented return shapes. Plugin middleware is a separate registry and surface, not another hook category.- Correlation fields such as `turn_id`, `api_request_id`, `task_id`, `session_id`, and `api_call_count` are hook-specific and may be absent. Treat IDs as opaque.- Runtime event-name validity comes from `hermes_cli.plugins.VALID_HOOKS`. `hermes hooks list` lists configured shell/outbound hooks, not every available event; `hermes hooks test <event>` reports the valid set only when an invalid event is supplied.@@ -569,6 +570,8 @@ Shell hooks also accept the Claude Code-compatible format:Both formats are normalized internally to `{"action": "modify", "args": {...}}`.+If a `pre_tool_call` callback exceeds `plugins.hook_callback_timeout` (or is still running from a previous timed-out fire), Hermes **fails closed**: the tool is blocked with a timeout message rather than proceeding without a policy decision.+**Use cases:** Logging, audit trails, tool call counters, blocking dangerous operations, rate limiting, per-user policy enforcement, argument sanitization, path rewriting, injecting default parameters.**Example — tool call audit log:**@@ -1115,7 +1118,7 @@ def register(ctx):### `subagent_stop`-Fires **once per child agent** after `delegate_task` finishes. Whether you delegated a single task or a batch of three, this hook fires once for each child, serialised on the parent thread.+Fires **once per child agent** after `delegate_task` finishes. Whether you delegated a single task or a batch of three, this hook fires once for each child. Dispatch is serialised on the parent thread after child futures drain, and each Python callback body runs on that same caller thread (not on a timeout worker).**Callback signature:**@@ -1134,7 +1137,7 @@ def my_callback(parent_session_id: str, child_role: str | None,| `tool_call_history` | `list[dict]` | Ordered metadata-only tool calls: `tool_name`, bounded `tool_input`, `input_bytes`, `output_bytes`, and `status`; raw inputs and outputs are excluded || `duration_ms` | `int` | Wall-clock time spent running the child, in milliseconds |-**Fires:** In `tools/delegate_tool.py`, after `ThreadPoolExecutor.as_completed()` drains all child futures. Firing is marshalled to the parent thread so hook authors don't have to reason about concurrent callback execution.+**Fires:** In `tools/delegate_tool.py`, after `ThreadPoolExecutor.as_completed()` drains all child futures. `invoke_hook("subagent_stop", ...)` is marshalled to the parent thread so authors don't see child-pool re-entrancy, and callbacks stay on that caller thread.**Return value:** Ignored.diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex d487f2c5fa5..417850c1c7b 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -157,6 +157,13 @@ plugins:- disk-cleanupdisabled: # optional deny-list — always wins if a name appears in both- noisy-plugin+ # Optional: wall-clock cap (seconds) for timeout-bounded in-process Python+ # plugin hook callbacks (hot-path observers + pre_tool_call). Default 30;+ # set 0 to disable; values above 600 are clamped. Timed-out pre_tool_call+ # callbacks fail closed (block the tool). Caller-thread hooks such as+ # subagent_stop are never moved onto a timeout worker.+ # Shell hooks keep their own per-entry timeout under the top-level hooks: key.+ hook_callback_timeout: 30```Three ways to flip state: