The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): fire agent_loop_stopped plugin hook on interrupt
Franci Penovf361971eedd2
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.pyindex d503c82b8bf..be24d79f3d0 100644--- a/gateway/run_agent_cache.py+++ b/gateway/run_agent_cache.py@@ -465,9 +465,28 @@ class GatewayAgentCacheMixin:if not session_key:returnstate = self._peek_session_state(session_key)+ running_agent = state.turn.agent if state else None_generation_at_interrupt = self._interrupt_running_turn(session_key, interrupt_reason=interrupt_reason, invalidation_reason=invalidation_reason,)+ from gateway.run import _AGENT_PENDING_SENTINEL+ if running_agent and running_agent is not _AGENT_PENDING_SENTINEL:+ # Plugins holding a per-turn external resource (an outbound RPC blocked on a tool result+ # the loop will never consume) learn the turn is gone. Fires for /stop and the /new+ # running-agent fast path; the pending-sentinel /stop has no in-flight work, so it stays+ # silent. Dispatch failures are swallowed so a misbehaving plugin cannot break an interrupt.+ try:+ from hermes_cli.plugins import invoke_hook as _invoke_hook++ _invoke_hook(+ "agent_loop_stopped",+ session_key=session_key,+ platform=source.platform.value if source.platform else "",+ reason=interrupt_reason,+ invalidation_reason=invalidation_reason,+ )+ except Exception:+ logger.debug("agent_loop_stopped hook dispatch failed", exc_info=True)adapter = self._adapter_for_source(source)interrupt_session_activity = getattr(type(adapter), "interrupt_session_activity", None)if adapter and callable(interrupt_session_activity):diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex fb894d40796..fef322e691e 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -131,6 +131,10 @@ VALID_HOOKS: Set[str] = {# auth/pairing and dispatch. Kwargs: event, gateway, session_store. Return {"action": "skip",# "reason"} -> drop; {"action": "rewrite", "text"} -> replace event.text; "allow"/None -> normal."pre_gateway_dispatch",+ # agent_loop_stopped: an agent turn was interrupted mid-run (/stop, or the running-agent+ # fast-path of /new; see gateway/run.py::_interrupt_and_clear_session). Kwargs: session_key,+ # platform, reason, invalidation_reason. Return values are ignored.+ "agent_loop_stopped",# Approval observers (tools/approval.py); returns ignored — plugins cannot veto or pre-answer# (use pre_tool_call). Kwargs: command, description, pattern_key, pattern_keys, session_key,# surface: "cli"|"gateway"|"smart"; post_approval_response adds choice ("once"|"session"|diff --git a/tests/gateway/test_agent_loop_stopped_hook.py b/tests/gateway/test_agent_loop_stopped_hook.pynew file mode 100644index 00000000000..e8d2c14f9c4--- /dev/null+++ b/tests/gateway/test_agent_loop_stopped_hook.py@@ -0,0 +1,165 @@+"""Tests that the ``agent_loop_stopped`` plugin hook fires when the gateway+interrupts a running agent turn — both via ``/stop`` and via the running-agent+fast-path inside ``/new``.++Mirrors ``test_session_boundary_hooks.py``: we bypass ``GatewayRunner.__init__``+and stub just enough attributes to drive ``_interrupt_and_clear_session``.+"""++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.session import SessionSource, build_session_key+from hermes_cli.plugins import VALID_HOOKS+++def _make_source() -> SessionSource:+ return SessionSource(+ platform=Platform.TELEGRAM,+ user_id="u1",+ chat_id="c1",+ user_name="tester",+ chat_type="dm",+ )+++def _make_runner():+ from gateway.run import GatewayRunner++ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")}+ )+ # SimpleNamespace, not MagicMock — _interrupt_and_clear_session calls+ # adapter.interrupt_session_activity() only when hasattr(...) is true,+ # and MagicMock fakes every attribute, which would push us into an+ # await on a non-awaitable.+ adapter = SimpleNamespace(send=AsyncMock())+ runner.adapters = {Platform.TELEGRAM: adapter}+ runner.hooks = SimpleNamespace(emit=AsyncMock(), loaded_hooks=False)+ runner._running_agents = {}+ runner._pending_messages = {}++ # _invalidate_session_run_generation + _release_running_agent_state are+ # called downstream; stub to no-op so we exercise the hook emit only.+ runner._invalidate_session_run_generation = lambda *a, **kw: None+ runner._release_running_agent_state = lambda *a, **kw: None+ return runner+++def test_agent_loop_stopped_in_valid_hooks():+ """Plugins must be able to subscribe to the new hook without warnings."""+ assert "agent_loop_stopped" in VALID_HOOKS+++@patch("hermes_cli.plugins.invoke_hook")+async def test_interrupt_fires_agent_loop_stopped_hook(mock_invoke_hook):+ """Calling ``_interrupt_and_clear_session`` with a real running agent+ must interrupt it AND dispatch the hook with the session, platform,+ and reasons attached."""+ runner = _make_runner()+ source = _make_source()+ session_key = build_session_key(source)++ running_agent = MagicMock()+ runner._running_agents[session_key] = running_agent++ await runner._interrupt_and_clear_session(+ session_key,+ source,+ interrupt_reason="user_stop",+ invalidation_reason="stop_command",+ )++ running_agent.interrupt.assert_called_once_with("user_stop")+ mock_invoke_hook.assert_any_call(+ "agent_loop_stopped",+ session_key=session_key,+ platform="telegram",+ reason="user_stop",+ invalidation_reason="stop_command",+ )+++@patch("hermes_cli.plugins.invoke_hook")+async def test_hook_not_fired_for_pending_sentinel_stop(mock_invoke_hook):+ """The pending-sentinel /stop path (slash_commands.py) has no in-flight+ work to cancel — the agent loop never started. The hook is gated on a+ real running agent and must not fire in this case."""+ from gateway.run import _AGENT_PENDING_SENTINEL++ runner = _make_runner()+ source = _make_source()+ session_key = build_session_key(source)++ runner._running_agents[session_key] = _AGENT_PENDING_SENTINEL++ await runner._interrupt_and_clear_session(+ session_key,+ source,+ interrupt_reason="user_stop",+ invalidation_reason="stop_command_pending",+ )++ agent_loop_stopped_calls = [+ call for call in mock_invoke_hook.call_args_list+ if call.args and call.args[0] == "agent_loop_stopped"+ ]+ assert agent_loop_stopped_calls == [], (+ f"agent_loop_stopped must not fire on the pending-sentinel path "+ f"(saw {len(agent_loop_stopped_calls)} call(s))"+ )+++@patch("hermes_cli.plugins.invoke_hook")+async def test_hook_not_fired_when_no_running_agent(mock_invoke_hook):+ """If there is no agent at all for the session key (already cleared),+ there is nothing to interrupt and the hook must not fire."""+ runner = _make_runner()+ source = _make_source()+ session_key = build_session_key(source)++ # _running_agents stays empty — no entry for this session_key.+ await runner._interrupt_and_clear_session(+ session_key,+ source,+ interrupt_reason="user_stop",+ invalidation_reason="stop_command_no_agent",+ )++ agent_loop_stopped_calls = [+ call for call in mock_invoke_hook.call_args_list+ if call.args and call.args[0] == "agent_loop_stopped"+ ]+ assert agent_loop_stopped_calls == []+++@patch("hermes_cli.plugins.invoke_hook")+async def test_hook_dispatch_failure_does_not_break_interrupt(mock_invoke_hook):+ """A misbehaving plugin must not prevent the interrupt from completing."""+ mock_invoke_hook.side_effect = RuntimeError("plugin exploded")++ runner = _make_runner()+ source = _make_source()+ session_key = build_session_key(source)++ running_agent = MagicMock()+ runner._running_agents[session_key] = running_agent++ # Should not raise — the hook block has try/except for exactly this.+ await runner._interrupt_and_clear_session(+ session_key,+ source,+ interrupt_reason="user_stop",+ invalidation_reason="stop_command",+ )++ # The interrupt itself still happened despite the hook blowing up.+ running_agent.interrupt.assert_called_once_with("user_stop")diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex e5562398080..054a3bb75e9 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -459,6 +459,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `on_session_end` | Observer | Canonically at each turn finalization; CLI/TUI exits have additional reduced legacy shapes. Return ignored. | Canonical: `session_id`, `task_id`, `turn_id`, `completed`, `failed`, `interrupted`, `turn_exit_reason`, `model`, `platform`; exit paths may add `reason`/`api_request_id` and omit fields. | IDs, model/platform, and outcome; canonical payload has no message body. || `on_session_finalize` | Observer | CLI/TUI/gateway teardown through `finalize_session`; gateway shutdown may finalize without a reset. Return ignored. | Surface-dependent `session_id`, `platform`, optionally `reason`, `old_session_id`, `new_session_id` | Session and routing identifiers. || `on_session_reset` | Observer | CLI/TUI session boundary and gateway after the replacement session exists; return ignored. | CLI: `session_id`, `platform`, `reason`; TUI: `session_id`, `platform`; gateway: those plus `reason`, `old_session_id`, `new_session_id` | Session and routing identifiers. |+| `agent_loop_stopped` | Observer | Immediately after a real gateway agent is interrupted in `_interrupt_and_clear_session`; return ignored. | `session_key`, `platform`, `reason`, `invalidation_reason` | Session/routing identifiers and interruption reasons; no message body. || `on_skill_lifecycle` | Observer | After an authoritative skill-usage state change; return ignored. | `action`, `skill_name`, `provenance`, `task_id`, `session_id`, `use_count`, `reused`, `reuse_after_patch` | Exposes the local skill name and provenance. || `subagent_start` | Observer | Child constructed and about to run; return ignored. | `parent_session_id`, `parent_turn_id`, `parent_subagent_id`, `child_session_id`, `child_subagent_id`, `child_role`, `child_goal` | Child goal may contain user/project content. || `subagent_stop` | Observer | Child exit; return ignored. | `parent_session_id`, `parent_turn_id`, `child_session_id`, `child_role`, `child_summary`, `child_status`, `tool_call_history`, `duration_ms` | Summary and redacted tool-history metadata may reveal project structure. |@@ -1046,6 +1047,33 @@ See the **[Build a Plugin guide](/developer-guide/plugins)** for the full walkth---+### `agent_loop_stopped`++Fires when the gateway **interrupts a running agent turn** — the user ran `/stop` while the loop was working, or the running-agent fast-path inside `/new` cleared the in-flight run before swapping the session. Unlike `on_session_finalize`, this fires earlier, while a turn is mid-flight, so plugins can drop per-turn external resources the agent loop will never consume (e.g. an outbound RPC that was waiting for a tool result).++**Gateway only.** Does not fire in the CLI; there is no equivalent interruption surface there.++**Callback signature:**++```python+def my_callback(session_key: str, platform: str, reason: str, invalidation_reason: str, **kwargs):+```++| Parameter | Type | Description |+|-----------|------|-------------|+| `session_key` | `str` | The session whose run was interrupted. |+| `platform` | `str` | The messaging platform name (`"telegram"`, `"discord"`, etc.); empty string if unknown. |+| `reason` | `str` | Why the agent was interrupted (e.g. `"user_stop"`, the reset/new reason). |+| `invalidation_reason` | `str` | Why queued session state was invalidated (e.g. `"stop_command"`, `"stop_command_thread_sibling"`, `"reset_command"`). |++**Fires:** In `gateway/run.py::_interrupt_and_clear_session`, immediately after `request_hard_interrupt()` interrupts the running agent. Only when a real agent was running — the pending-sentinel `/stop` path (no agent loop yet started) does **not** fire this hook, since there is no in-flight work to drop. On the slow `/new` reset path, `on_session_finalize` fires later in `_handle_reset_command` instead.++**Return value:** Ignored.++**Use cases:** Cancel external requests blocked on a tool result the loop will never consume, notify a connected voice/realtime client that a tool call was abandoned, release per-turn credentials or locks held only for the duration of an active turn.++---+### `subagent_start`Fires **once per child agent** after `delegate_task` has constructed the child `AIAgent` and before that child is run. Whether you delegate a single task or a batch of three, this hook fires once for each child.diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 7e828943467..01006ccb765 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -292,13 +292,13 @@ When you upgrade to a version of Hermes that has opt-in plugins (config schema v## Available hooks-Plugins can register the 26 lifecycle events currently accepted by `hermes_cli.plugins.VALID_HOOKS`. The **[Event Hooks catalog](/user-guide/features/hooks#shipped-plugin-hook-catalog)** is canonical for exact timing, return handling, payload fields, and privacy notes.+Plugins can register the 27 lifecycle events currently accepted by `hermes_cli.plugins.VALID_HOOKS`. The **[Event Hooks catalog](/user-guide/features/hooks#shipped-plugin-hook-catalog)** is canonical for exact timing, return handling, payload fields, and privacy notes.| Descriptive category | Shipped hooks ||---|---|| **Directive/control** | `pre_tool_call`, `pre_llm_call`, `pre_verify`, `pre_gateway_dispatch` || **Transform** | `transform_tool_result`, `transform_terminal_output`, `transform_llm_output`, `pre_transcription` |-| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `pre_command`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |+| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `pre_command`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |These categories describe current behavior rather than defining future naming rules. Plugin middleware remains a separate registry/surface.## Plugin types