The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): fire post_compaction on every committed compaction path
Tekniumed9fb3cf56d9
diff --git a/agent/compaction_events.py b/agent/compaction_events.pyindex a2a88170d79..f4206f20764 100644--- a/agent/compaction_events.py+++ b/agent/compaction_events.py@@ -6,7 +6,8 @@ compaction Hermes observes. A persistence-detached fork (background review) sharbut rewrites only its own throwaway transcript, so it publishes nothing. The payload is flat because OpenTelemetry exporters flatten only top-levelkeys; every categorical field except the free-form ``summarizer_provider`` / ``summarizer_model`` identifierscomes from a closed set with an ``other`` fallback; no field carries message, summary, focus-topic, error or-path text. Publishing never raises into compaction.+path text. Publishing never raises into compaction. A committed record also fires the ``post_compaction`` plugin+hook, so plugins learn about every compaction the model will see without inferring it from history shrinkage."""from __future__ import annotations@@ -235,23 +236,59 @@ def provider_native_payload(*, session_id: str, compression_count: Any = None) -)+def fire_post_compaction(+ *, session_id: str, old_session_id: str = "", kind: str | None, reason: str | None,+ before_tokens: int | None, after_tokens: int | None, messages_removed: int | None,+) -> None:+ """The ``post_compaction`` plugin hook, gated on a listener. Callbacks are isolated by the dispatcher."""+ from hermes_cli.lifecycle import has_hook, invoke_hook++ if has_hook("post_compaction"):+ invoke_hook(+ "post_compaction", session_id=session_id, old_session_id=old_session_id, kind=kind, reason=reason,+ before_tokens=before_tokens, after_tokens=after_tokens, messages_removed=messages_removed,+ )+++def _fire_for(payload: dict[str, Any], session_id: str) -> None:+ before, after = payload["messages_before"], payload["messages_after"]+ fire_post_compaction(+ session_id=session_id, old_session_id=payload["session_id"] if payload["session_id"] != session_id else "",+ kind=payload["kind"], reason=payload["trigger"], before_tokens=payload["tokens_before"],+ after_tokens=payload["tokens_after"],+ messages_removed=before - after if before is not None and after is not None else None,+ )++def _publish(build: Any, *args: Any, turn_session_id: str | None = None, require_target_session_id: str | None = None,- **kwargs: Any,+ live_session_id: str | None = None, **kwargs: Any,) -> None:- """Build one record and fan it out to the built-in Relay integration. Never raises into compaction: the- first failure logs at WARNING with its traceback, later ones at DEBUG."""+ """Build one record, fire ``post_compaction`` for a committed one, and fan it out to the built-in Relay+ integration. ``live_session_id`` is the session holding the compacted transcript now (a rotating commit+ moved it off the record's session). Never raises into compaction: the first failure logs at WARNING with+ its traceback, later ones at DEBUG."""global _warnedtry:+ relay = Trueif require_target_session_id is not None:from agent.relay_compaction import compaction_target_available- if not compaction_target_available(require_target_session_id, turn_session_id=turn_session_id):- return+ relay = compaction_target_available(require_target_session_id, turn_session_id=turn_session_id)+ from hermes_cli.lifecycle import has_hook++ hook = has_hook("post_compaction")+ if not (relay or hook):+ returnpayload = build(*args, **kwargs)+ name = event_name(payload)+ if hook and name == COMPACTION_MARK:+ _fire_for(payload, live_session_id or payload["session_id"])+ if not relay:+ returnfrom agent.relay_compaction import emit_compaction_mark- emit_compaction_mark(payload["session_id"], event_name(payload), payload, turn_session_id=turn_session_id)+ emit_compaction_mark(payload["session_id"], name, payload, turn_session_id=turn_session_id)except Exception:with _warned_lock:first, _warned = not _warned, True@@ -275,7 +312,7 @@ def publish_attempt(agent: Any, record: dict[str, Any]) -> None:if _publishes_for(agent):_publish(lambda: attempt_payload(record, compression_count=getattr(getattr(agent, "context_compressor", None), "compression_count", None),- ), turn_session_id=_turn_session_id(agent))+ ), turn_session_id=_turn_session_id(agent), live_session_id=getattr(agent, "session_id", None))def publish_micro(record: dict[str, Any], *, turn_session_id: str | None = None) -> None:diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 3b449417e6a..d8d01fa9dcd 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -3332,30 +3332,6 @@ class ContextCompressor(self._proactive_prune_rearm_tokens = 0self._last_reclaim_block_warn = None- def _fire_post_compaction_hook(self, messages_before: List[Dict[str, Any]], messages_after: List[Dict[str, Any]]) -> None:- """Fire the post_compaction plugin hook (observer-only, returns ignored).-- Runs after a successful compaction so plugins/providers can react- (re-inject context, update indices, etc.). Gated on has_hook so- the hook dispatch cost is zero when no plugin is listening (#118382).- """- try:- from hermes_cli.lifecycle import has_hook, invoke_hook- if has_hook("post_compaction"):- before_tokens = estimate_messages_tokens_rough(messages_before)- after_tokens = estimate_messages_tokens_rough(messages_after)- messages_removed = len(messages_before) - len(messages_after)- invoke_hook(- "post_compaction",- session_id=getattr(self, "_session_id", ""),- before_tokens=before_tokens,- after_tokens=after_tokens,- messages_removed=messages_removed,- reason="compaction",- )- except Exception as exc:- logger.debug("post_compaction hook dispatch failed (non-fatal): %s", exc)-def _billed_basis_over_threshold(self, current_tokens: int | None) -> bool:"""Whether a provider-billed reading says the session is over threshold.@@ -5657,10 +5633,7 @@ Write only the summary body. Do not include any preamble or prefix.""")# Phase 4: Assemble compressed message listcompressed = self._assemble_compressed(messages, compress_start, compress_end, scan, summary)- result = self._finalize_compressed(compressed, canonical_messages, n_messages, spare_pending_images, pruned_count)- if self._last_compression_made_progress:- self._fire_post_compaction_hook(messages, result)- return result+ return self._finalize_compressed(compressed, canonical_messages, n_messages, spare_pending_images, pruned_count)def _assemble_compressed(self, messages: list[dict[str, Any]], compress_start: int, compress_end: int, scan: _HandoffScan, summary: str,diff --git a/gateway/session_mutation_compress.py b/gateway/session_mutation_compress.pyindex 227c664fb06..84b028abb4c 100644--- a/gateway/session_mutation_compress.py+++ b/gateway/session_mutation_compress.py@@ -1,9 +1,13 @@"""Summary preparation has no canonical store; publication owns the only write."""import asyncioimport json+import logging+from pathlib import Pathfrom hermes_state_runtime import RuntimeStoreError+logger = logging.getLogger(__name__)+def compress_request(payload):"""``session.mutate(compress)`` payload → the shared ``CompressRequest``.@@ -87,10 +91,29 @@ async def prepare_compress(authority, live, payload, prepared):messages, messages, tokens, tokens, compression_state=compressor)}summary = summarize_manual_compression(messages, compressed, estimate_request_tokens_rough(messages),estimate_request_tokens_rough(compressed), compression_state=compressor)- return dict(prepared, messages=compressed, summary=summary,+ from agent.model_metadata import estimate_messages_tokens_rough+ hook = None if policy.safe_mode else { # same rough basis as the agent path's compaction record+ 'before_tokens': estimate_messages_tokens_rough(messages),+ 'after_tokens': estimate_messages_tokens_rough(compressed), 'messages_removed': len(messages) - len(compressed)}+ return dict(prepared, messages=compressed, summary=summary, post_compaction=hook,in_place=is_truthy_value(options.get('in_place'), default=True))+async def fire_post_compaction_hook(authority, prepared, result):+ """``post_compaction`` for a committed ``/compress``: this path summarizes outside the agent's+ ``compress_context``, so it fires here, after the commit, in the session's profile."""+ from agent.compaction_events import fire_post_compaction+ from gateway.run import _async_profile_runtime_scope+ target, previous = result['target_session_id'], result['previous_target_session_id']+ try:+ async with _async_profile_runtime_scope(Path(authority.profile_id)):+ await asyncio.to_thread(+ fire_post_compaction, session_id=target, old_session_id='' if previous == target else previous,+ kind='summarize', reason='manual', **prepared['post_compaction'])+ except Exception: # the compaction is committed; a plugin-side failure must not fail the reply+ logger.warning('post_compaction hook delivery failed', exc_info=True)++def _request_tokens(agent, messages):"""Main's /compress request estimate: the agent's system prompt and tool schemas plus the messages."""from agent.model_metadata import estimate_request_tokens_roughdiff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 0ab17714d57..8a84bf0dbb4 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -225,6 +225,9 @@ async def write_mutation(authority, ref, params, editor_servers, *, principal_idresult = await asyncio.to_thread(mutate_runtime_session, authority.db, **fields,_prepared=prepared, _authorize_write=authorize_write)await _project_result(authority, ref, live, params, result, editor_servers, applied=applied)+ if operation == 'compress' and applied and (prepared or {}).get('post_compaction'):+ from gateway.session_mutation_compress import fire_post_compaction_hook+ await fire_post_compaction_hook(authority, prepared, result)if operation == 'delete':# After the synchronous projections (no yield before retirement), off the loop: the# retired-media owner check is a messages-table pass (exact retries repeat it too).diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 37887818b04..7e2a87b7b4f 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -195,15 +195,10 @@ VALID_HOOKS: set[str] = {# returns IGNORED in v1. Deliberately NOT fired for the gateway's running-agent intercept path# (/stop, /approve, busy_policy) — a slow/hostile plugin must not touch the operator's escape# hatches. Kwargs: surface, command (canonical), alias_used, args_raw, session_key, platform.- # Slash-command dispatch observer (#64204, observer-first per #64182 ground rule 3). Return values are- # IGNORED in v1 — a plugin returning a directive-shaped dict gets a debug log so future block/rewrite- # adopters are discoverable once the middleware variant ships against the #64231 taxonomy.+ # Observer-first (#64204, #64182 rule 3); a directive-shaped return gets a debug log so future+ # block/rewrite adopters are discoverable once the middleware variant ships (#64231 taxonomy)."pre_command",- # post_compaction: after a successful context compaction. Fires once per compress() call that- # made progress. Observer-only (returns ignored). Kwargs: session_id, before_tokens, after_tokens,- # messages_removed, reason. Lets plugins/providers re-inject context that compaction summarized- # away (#118382).- "post_compaction",+ "post_compaction", # once per committed compaction on every path; observer (hooks.md, #118382)}# Hooks whose directive the shell-hook response parser has no channel for. VALID_HOOKS doubles asdiff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex 17c1a59bd0f..e8cd9282249 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -47,6 +47,8 @@ _HOOK_TIMEOUT_BOUNDED_HOOKS: set[str] = {"post_gateway_admission",# Observer on every local session's commands, fired by the gateway (gateway/session_commands.py)."pre_command",+ # Fires inside the compression commit window (lease held): a hung plugin must not wedge the session.+ "post_compaction",}# Hooks whose calls are told apart by another payload field: one session's commands are one# sequence, so a still-running callback skips that session's next command, not another session's.diff --git a/tests/agent/test_post_compaction_hook.py b/tests/agent/test_post_compaction_hook.pyindex 34371902249..c11a38b360b 100644--- a/tests/agent/test_post_compaction_hook.py+++ b/tests/agent/test_post_compaction_hook.py@@ -1,141 +1,46 @@-"""Tests for the post_compaction plugin hook (#118382).--The post_compaction hook fires once after a successful context compaction,-so plugins/providers can react (re-inject context, update indices, etc.).-"""--from __future__ import annotations+"""``post_compaction`` fires once per committed compaction, never for an attempt that changed nothing,+and a raising plugin never changes what the compaction returns (#118382)."""from unittest.mock import patchimport pytest-from agent.context_compressor import ContextCompressor---class _RecordingCompressor(ContextCompressor):- """A compressor whose _generate_summary returns a fixed string."""-- def __init__(self) -> None:- super().__init__(- model="test-model", protect_first_n=2, protect_last_n=2,- quiet_mode=True, config_context_length=40_960,- )- self.summary_calls: list = []-- def _generate_summary(self, turns_to_summarize, focus_topic=None, memory_context="", bypass_cooldown=False):- self.summary_calls.append((focus_topic, memory_context, {}))- return "## Goal\nTest summary for hook."---def _messages(n: int = 14) -> list[dict]:- """Build a small synthetic conversation."""- return [{"role": "system", "content": "system"}] + [- {"role": "user" if i % 2 == 0 else "assistant", "content": f"turn-{i} " + "context " * 50}- for i in range(n)- ]---class TestPostCompactionHook:- """post_compaction hook fires once per successful compaction, observer-only."""-- def test_hook_fired_when_has_hook_true(self) -> None:- compressor = _RecordingCompressor()- compressor.bind_session_state(session_id="sess-1")-- messages = _messages()- before_tokens = len(str(messages)) # rough estimate, exact value not checked- after_tokens_before = len(str(messages))-- with patch("hermes_cli.lifecycle.has_hook", return_value=True) as mock_has, \- patch("hermes_cli.lifecycle.invoke_hook") as mock_invoke:- compressed = compressor.compress(messages, current_tokens=30_000)-- mock_has.assert_called_once_with("post_compaction")- mock_invoke.assert_called_once()- call_kwargs = mock_invoke.call_args.kwargs-- assert call_kwargs["session_id"] == "sess-1"- assert call_kwargs["before_tokens"] > 0- assert call_kwargs["after_tokens"] > 0- assert call_kwargs["messages_removed"] > 0- assert call_kwargs["reason"] == "compaction"-- def test_hook_not_fired_when_has_hook_false(self) -> None:- compressor = _RecordingCompressor()- compressor.bind_session_state(session_id="sess-2")-- messages = _messages()-- with patch("hermes_cli.lifecycle.has_hook", return_value=False) as mock_has, \- patch("hermes_cli.lifecycle.invoke_hook") as mock_invoke:- compressed = compressor.compress(messages, current_tokens=30_000)-- mock_has.assert_called_once_with("post_compaction")- mock_invoke.assert_not_called()-- def test_hook_not_fired_on_structural_no_op(self) -> None:- """Compaction that does nothing (too few messages) does NOT fire the hook."""- compressor = _RecordingCompressor()- compressor.bind_session_state(session_id="sess-3")-- messages = [{"role": "system", "content": "system"}, {"role": "user", "content": "hi"}]-- with patch("hermes_cli.lifecycle.has_hook", return_value=True) as mock_has, \- patch("hermes_cli.lifecycle.invoke_hook") as mock_invoke:- result = compressor.compress(messages, current_tokens=100)-- # Hook is not fired when no compaction made progress- mock_has.assert_not_called()- mock_invoke.assert_not_called()-- def test_hook_payload_values_correct(self) -> None:- compressor = _RecordingCompressor()- compressor.bind_session_state(session_id="sess-4")-- messages = _messages()-- with patch("hermes_cli.lifecycle.has_hook", return_value=True), \- patch("hermes_cli.lifecycle.invoke_hook") as mock_invoke:- compressed = compressor.compress(messages, current_tokens=30_000)-- kwargs = mock_invoke.call_args.kwargs- assert kwargs["session_id"] == "sess-4"- assert kwargs["before_tokens"] > kwargs["after_tokens"] # compression shrinks- assert kwargs["messages_removed"] == len(messages) - len(compressed)- assert kwargs["reason"] == "compaction"-- def test_hook_dispatch_failure_does_not_raise(self) -> None:- """Hook dispatch failure is caught (non-fatal debug log)."""- compressor = _RecordingCompressor()- compressor.bind_session_state(session_id="sess-5")-- messages = _messages()-- with patch("hermes_cli.lifecycle.has_hook", return_value=True), \- patch("hermes_cli.lifecycle.invoke_hook", side_effect=RuntimeError("boom")):- # Should not raise- compressed = compressor.compress(messages, current_tokens=30_000)-- assert len(compressed) < len(messages) # compression still succeeded-- def test_hook_called_once_per_compress(self) -> None:- compressor = _RecordingCompressor()- compressor.bind_session_state(session_id="sess-6")-- messages = _messages()-- with patch("hermes_cli.lifecycle.has_hook", return_value=True), \- patch("hermes_cli.lifecycle.invoke_hook") as mock_invoke:- compressed = compressor.compress(messages, current_tokens=30_000)-- mock_invoke.assert_called_once()---class TestPostCompactionHookRegistration:- """post_compaction appears in VALID_HOOKS."""-- def test_post_compaction_in_valid_hooks(self) -> None:- from hermes_cli.plugins import VALID_HOOKS-- assert "post_compaction" in VALID_HOOKS+from hermes_cli import plugins as plugins_mod+from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+from tests.agent.test_compaction_events import _Agent, _compressor, _messages+from agent.conversation_compression import compress_context+++def ctx(monkeypatch):+ mgr = PluginManager()+ mgr._discovered = True+ monkeypatch.setattr(plugins_mod, "_plugin_manager", mgr)+ monkeypatch.setattr(plugins_mod, "_plugin_managers_by_home", {})+ return PluginContext(PluginManifest(name="compaction-observer", source="user"), mgr)++[email protected]("summary, committed", [("SANITIZED SUMMARY", True), (None, False)])+def test_post_compaction_fires_once_per_committed_compaction(ctx, summary, committed):+ fired = []++ def boom(**_kw):+ raise RuntimeError("plugin bug")++ ctx.register_hook("post_compaction", lambda **kw: fired.append(kw))+ ctx.register_hook("post_compaction", boom)+ agent = _Agent(_compressor(abort_on_summary_failure=True))++ with patch.object(agent.context_compressor, "_generate_summary", return_value=summary):+ compressed, _ = compress_context(agent, _messages(), "system prompt", approx_tokens=80_000, trigger="pre_api")++ assert (len(compressed) < len(_messages())) is committed+ if not committed:+ assert fired == []+ return+ [kw] = fired+ assert (kw["session_id"], kw["old_session_id"], kw["kind"], kw["reason"]) == (+ "session-events-test", "", "summarize", "pre_api",+ )+ assert kw["messages_removed"] == len(_messages()) - len(compressed) > 0+ assert kw["before_tokens"] > kw["after_tokens"] > 0diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex 8e945593191..b5c2cd8ab78 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -1353,6 +1353,7 @@ Each hook is documented in full on the **[Event Hooks reference](../../user-guid| [`on_session_finalize`](../../user-guide/features/hooks.md#on_session_finalize) | CLI/gateway tears down an active session | `session_id: str \| None, platform: str` | ignored || [`on_session_reset`](../../user-guide/features/hooks.md#on_session_reset) | Gateway swaps in a new session key (`/new`, `/reset`) | `session_id: str, platform: str` | ignored || [`on_session_delete`](../../user-guide/features/hooks.md#on_session_delete) | A session delete or deliberate archive commits (every surface, sweeps, prune) | `session_id: str, reason: str, profile: str \| None`, optional `deleted_ids: list[str]`, `sessions_dir: str` | ignored |+| [`post_compaction`](../../user-guide/features/hooks.md#post_compaction) | A compaction committed (any path: auto, `/compress`, gateway, Codex, micro, prune) | `session_id: str, old_session_id: str, kind: str, reason: str, before_tokens: int \| None, after_tokens: int \| None, messages_removed: int \| None` | ignored || [`gateway_platform_event`](../../user-guide/features/hooks.md#gateway_platform_event) | An authorized platform-native event is normalized at the gateway boundary (Telegram reactions currently) | `platform: str, event_type: str, payload: dict` | ignored || `kanban_task_claimed` | A kanban task is claimed (dispatcher process, before the worker spawns) | `task_id: str, board: str \| None, assignee: str \| None, run_id: int \| None, profile_name: str` | ignored || `kanban_task_completed` | A kanban task completes (worker process) | `task_id, board, assignee, run_id, profile_name, summary: str \| None` | ignored |diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex ed30ffec051..cc9b3034e0e 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -472,6 +472,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `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. || `on_session_delete` | Observer | After a session delete or deliberate archive commits (CLI, TUI, Desktop/dashboard, gateway API, sweeps, prune); return ignored. | `session_id`, `reason`, `profile`, optional `deleted_ids` (full set when more than one row went), `sessions_dir` | Session identifiers only; no message content. |+| `post_compaction` | Observer | Once per committed compaction, on every path: automatic and manual compaction in the agent loop (CLI, TUI, Desktop, gateway hygiene, overflow recovery), the gateway's `/compress` (`session.mutate compress`), Codex app-server compactions, micro-compaction and proactive tool-result pruning. Not fired for attempts that changed nothing (aborted, blocked, refused). Timeout-bounded; return ignored. | `session_id`, `old_session_id`, `kind`, `reason`, `before_tokens`, `after_tokens`, `messages_removed` | Identifiers and counts only. || `agent_loop_stopped` | Observer | Immediately after a real running agent is interrupted — gateway `_interrupt_and_clear_session` or TUI/desktop `session.interrupt`; 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. |@@ -1114,6 +1115,31 @@ See the **[Build a Plugin guide](../../developer-guide/plugins/index.md)** for t---+### `post_compaction`++Fires once after a compaction **committed**, so plugins (memory providers, context engines, external knowledge stores) can tell that detail they injected earlier was just summarized away and re-inject it, typically from their next `pre_llm_call`.++**Callback signature:**++```python+def my_callback(session_id: str, kind: str, reason: str, **kwargs):+```++| Parameter | Type | Description |+|-----------|------|-------------|+| `session_id` | `str` | The session that holds the compacted transcript now. |+| `old_session_id` | `str` | The session the compaction started in when it rotated to a new one; `""` when compacted in place. |+| `kind` | `str` | `"summarize"` (full compaction), `"micro_summarize"`, `"prune_tool_results"` or `"provider_native"` (Codex app-server). |+| `reason` | `str` | What triggered it: `"manual"` (`/compress`), `"pre_api"`, `"post_tool"`, `"overflow"`, `"gateway_hygiene"`, `"between_turns"`, `"proactive_prune"`, `"provider"`, or `"unknown"`. |+| `before_tokens` / `after_tokens` | `int \| None` | Rough token estimates of the transcript before and after; `None` when unknown (Codex owns the thread). |+| `messages_removed` | `int \| None` | Messages before minus after; `None` when unknown. |++**Fires:** in the agent loop, in the process that compacted (CLI, TUI and Desktop backends, gateway agents, cron); for the gateway's `/compress`, in the gateway after the commit. Attempts that changed nothing (summary aborted, blocked by a cooldown, refused because it would grow) and background-review forks fire nothing.++**Return value:** Ignored. A callback that raises is logged and skipped; the compaction is already committed and is unaffected. Callbacks are bounded by `plugins.hook_callback_timeout`.++**Use cases:** Re-inject session context after compaction, refresh an external index, count compactions.+### `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).diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 3b540374230..a1eb0fa23c0 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -349,7 +349,7 @@ Plugins can register the 27 lifecycle events currently accepted by `hermes_cli.p|---|---|| **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`, `pre_auxiliary_call`, `post_auxiliary_call`, `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_session_delete`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `on_human_input_request`, `on_human_input_resolved`, `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`, `pre_auxiliary_call`, `post_auxiliary_call`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `post_compaction`, `on_session_delete`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `on_human_input_request`, `on_human_input_resolved`, `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