Skip to content

The agent that grows with you

feat(gateway): reshape post_gateway_admission into a fail-open consume hook

Tekniumbe5481690d43
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index c724214dd5f..94615f39537 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -1397,25 +1397,9 @@ class GatewayInboundMixin:
_run_generation = self._begin_session_run_generation(_quick_key)
try:
- # Post-admission consuming extension (#129958): only idle, non-internal
- # business messages reach it. All admission, pause/drain, pending-reply,
- # running-session and slash-command lanes were selected above; the FIFO
- # orphan rescue already chose the event (with its own anchor) for this
- # turn, and the session slot + sentinel are held so a concurrent arrival
- # queues on the busy path instead of invoking the consumer twice.
- if not is_internal:
- try:
- from gateway.run_inbound_consumer import invoke_post_admission_hook as _invoke_post
- _consumed, _consumer_reply, event, source = await _invoke_post(
- self, event, source, _quick_key
- )
- except asyncio.CancelledError:
- raise
- except Exception as _consumer_exc:
- logger.warning("post_gateway_admission failed closed: %s", _consumer_exc)
- return (
- "⚠️ A gateway plugin failed to handle this message, so it was not processed."
- )
+ if not is_internal: # fail-open plugin consume, inside the claimed slot (#129958)
+ from gateway.run_inbound_consumer import run_post_admission_hook
+ _consumed, _consumer_reply = await run_post_admission_hook(self, event, source, _quick_key)
if _consumed:
return _consumer_reply
try:
diff --git a/gateway/run_inbound_consumer.py b/gateway/run_inbound_consumer.py
index f305153e529..691e956599b 100644
--- a/gateway/run_inbound_consumer.py
+++ b/gateway/run_inbound_consumer.py
@@ -1,312 +1,58 @@
-"""Post-admission consuming gateway plugin extension (issue #129958).
-
-Minimal, profile-scoped, fail-closed consuming hook for new business messages.
-
-Placement (owned by ``GatewayInboundMixin._handle_message`` in
-``gateway/run_inbound.py``) is AFTER all core-owned gates:
-
-- admission (profile routing, ignored channels, unserved profiles,
- authorization, bot admission),
-- pause / maintenance-drain gates,
-- pending-reply intercepts (update prompt, clarify, slash-confirm),
-- running-session fast-path (steering, busy commands),
-- idle slash-command dispatch (built-in, quick, plugin, skill),
-
-and AFTER FIFO orphan rescue, INSIDE the claimed session slot (sentinel
-held) so concurrent arrivals serialize through the busy path instead of
-invoking the consumer twice.
-
-Only idle, non-internal business messages reach the hook. Rejected,
-ignored-channel, unserved-profile, bot-loop, internal/system, paused,
-draining and control traffic never invoke it.
-
-Outcomes (first decisive result wins, registration order):
-
-- ``None`` / ``{"action": "pass"}`` (also ``"allow"``) → PASS, ordinary
- agent flow runs once.
-- ``{"action": "consumed", "receipt": "<id>", "reply": "<optional>"}``
- → CONSUMED, agent flow suppressed, ``reply`` (when a non-empty string)
- returned through the normal core-owned delivery route. ``receipt`` is
- a required, non-empty plugin receipt identifier; a missing/invalid
- receipt is malformed → FAILED.
-- ``{"action": "failed", "reply": "<optional>"}`` (also ``"fail"``,
- ``"error"``, ``"block"``, ``"deny"``) → FAILED, agent flow suppressed,
- short user-failure notice returned, sanitized operator diagnostic
- logged.
-
-Fail-closed: unknown/malformed outcomes, callback exceptions and
-timeouts suppress the agent turn (FAILED), never silently permit inline
-execution. Plugin absence (no callbacks registered) is distinct — it is
-PASS (ordinary flow). Cancellation propagates without starting an agent
-turn.
-
-Scope: invoked inside the routed profile's ``_async_profile_runtime_scope``
-(the ``_handle_message`` call path already binds it), so
-``get_plugin_manager()`` resolves the routed profile's own consumers.
-Scope is restored by the ambient context manager, including on
-exceptions. The hook receives no runner/adapter authority beyond the
-documented kwargs.
-
-Context: a versioned, immutable snapshot (``MappingProxyType``) with
-canonical profile/platform/conversation, stable event identity, sender
-identity and reply anchor. Inbound text is untrusted data. Direct
-mutation of ``event.source`` routing fields is restored and logged —
-destinations are never taken from plugin-returned fields.
-
-Durable acceptance is a plugin responsibility (commit before CONSUMED,
-reconcile by receipt on replay). Core records no cross-store
-transaction and claims no exactly-once external delivery.
+"""``post_gateway_admission``: let a plugin consume an admitted inbound message (#129958).
+
+``GatewayInboundMixin._handle_message`` fires it once per non-internal message that survived
+authorization, bot admission, pause/drain, pending-reply intercepts, the running-session lane and
+idle slash-command dispatch, inside the claimed session slot. It runs under the message's ROUTED
+profile scope: the receiving bot's handler binds the transport home (auth reads its ``.env``), which
+differs from the runtime home when that bot serves a chat for another profile.
+
+Fail-open: a callback that raises, times out or returns anything other than
+``{"action": "handled"}`` is logged/ignored and the message proceeds to the agent, so one buggy
+plugin can never blackhole a profile's traffic. The payload is a plain snapshot, never live
+runner/session-store handles.
"""
from __future__ import annotations
import asyncio
-import dataclasses
+import contextlib
import logging
-from types import MappingProxyType
-from typing import Any, Dict, Mapping, Optional, Tuple
+from typing import Any, Optional, Tuple
-logger = logging.getLogger("gateway.run")
+logger = logging.getLogger(__name__)
POST_ADMISSION_HOOK = "post_gateway_admission"
-POST_ADMISSION_VERSION = 1
-
-# Short, sanitized user-facing notice for FAILED consumption. Deliberately
-# not i18n-keyed in v1 to avoid locale-parity churn; plugins may supply
-# their own short ``reply`` for the failed turn instead.
-POST_ADMISSION_FAILURE_NOTICE = (
- "⚠️ A gateway plugin failed to handle this message, so it was not processed."
-)
-
-_MAX_REPLY_CHARS = 2000
-_MAX_RECEIPT_CHARS = 256
-
-
-def build_post_admission_context(
- event: Any,
- source: Any,
- session_key: str,
- *,
- reply_anchor: Optional[str],
-) -> Mapping[str, Any]:
- """Versioned immutable snapshot presented to ``post_gateway_admission`` consumers."""
- platform = getattr(getattr(source, "platform", None), "value", None)
- platform = platform if isinstance(platform, str) else str(getattr(source, "platform", "") or "")
- ctx = {
- "version": POST_ADMISSION_VERSION,
- "profile": getattr(source, "profile", None),
- "platform": platform,
- "session_key": session_key,
- "conversation": MappingProxyType(
- {
- "chat_id": getattr(source, "chat_id", ""),
- "thread_id": getattr(source, "thread_id", None),
- "chat_type": getattr(source, "chat_type", "") or "",
- }
- ),
- "event_id": getattr(event, "message_id", None),
- "event_revision": getattr(event, "platform_update_id", None),
- "sender": MappingProxyType(
- {
- "user_id": getattr(source, "user_id", None),
- "user_name": getattr(source, "user_name", None),
- }
- ),
- "reply_anchor": reply_anchor,
- # Untrusted inbound data; never trusted for authorization or routing.
- "text": getattr(event, "text", "") or "",
- "reply_to_text": getattr(event, "reply_to_text", None),
- }
- return MappingProxyType(ctx)
-def _action_of(result: Any) -> str:
- if not isinstance(result, dict):
- return ""
- action = result.get("action", result.get("decision", ""))
- return str(action or "").strip().lower()
-
-
-def decide_post_admission(results: Any) -> Tuple[str, Optional[str], Optional[str], Optional[str]]:
- """Interpret raw hook results → ``(decision, reply, receipt, diagnostic)``.
-
- ``decision`` is ``"pass"``, ``"consumed"`` or ``"failed"``. ``reply`` is
- the optional user-facing string (truncated), ``receipt`` the validated
- plugin receipt for CONSUMED, ``diagnostic`` a sanitized operator string.
- Empty/missing results → PASS. Any malformed entry with at least one
- registered consumer present → FAILED (fail-closed).
- """
- if not results:
- return "pass", None, None, None
- decisive: Optional[Tuple[str, Optional[str], Optional[str], Optional[str]]] = None
- decisive_count = 0
- for result in results:
- if result is None:
- continue
- if not isinstance(result, dict):
- decisive_count += 1
- if decisive is None:
- decisive = ("failed", None, None, "malformed non-dict result")
- continue
- action = _action_of(result)
- if action in ("", "pass", "allow", "continue"):
- continue
- if action in ("consumed", "consume", "consumes", "handled"):
- receipt = result.get("receipt", result.get("receipt_id", ""))
- reply = result.get("reply", result.get("response", result.get("message")))
- if not isinstance(receipt, str) or not receipt.strip():
- decisive_count += 1
- if decisive is None:
- decisive = ("failed", None, None, "consumed without valid receipt")
- continue
- receipt = receipt.strip()[:_MAX_RECEIPT_CHARS]
- if reply is not None and not isinstance(reply, str):
- decisive_count += 1
- if decisive is None:
- decisive = ("failed", None, receipt, "consumed with non-string reply")
- continue
- reply = (reply[:_MAX_REPLY_CHARS] if isinstance(reply, str) else None) or None
- decisive_count += 1
- if decisive is None:
- decisive = ("consumed", reply, receipt, None)
- continue
- if action in ("failed", "fail", "error", "block", "deny", "blocked"):
- reply = result.get("reply", result.get("response", result.get("message")))
- if reply is not None and not isinstance(reply, str):
- reply = None
- reply = (reply[:_MAX_REPLY_CHARS] if isinstance(reply, str) else None) or None
- reason = result.get("reason", result.get("error", ""))
- diagnostic = str(reason)[:200] if reason else "consumer reported failure"
- decisive_count += 1
- if decisive is None:
- decisive = ("failed", reply, None, diagnostic)
- continue
- # Unknown action → fail closed.
- decisive_count += 1
- if decisive is None:
- decisive = ("failed", None, None, f"unknown action {action!r}")
- if decisive is None:
- return "pass", None, None, None
- if decisive_count > 1:
- logger.warning(
- "post_gateway_admission: %d decisive consumer results; first wins", decisive_count
- )
- return decisive
+def _routed_scope(runner: Any, source: Any):
+ if not getattr(getattr(runner, "config", None), "multiplex_profiles", False):
+ return contextlib.nullcontext()
+ from gateway.run import _async_profile_runtime_scope
+ return _async_profile_runtime_scope(runner._resolve_profile_home_for_source(source))
-def _snapshot_destination(source: Any) -> Dict[str, Any]:
- return {
- "platform": getattr(getattr(source, "platform", None), "value", None)
- if hasattr(getattr(source, "platform", None), "value")
- else getattr(source, "platform", None),
- "chat_id": getattr(source, "chat_id", None),
- "thread_id": getattr(source, "thread_id", None),
- "chat_type": getattr(source, "chat_type", None),
- "profile": getattr(source, "profile", None),
- "user_id": getattr(source, "user_id", None),
- }
-
-
-def _restore_destination_if_mutated(event: Any, source: Any, snapshot: Dict[str, Any]) -> None:
- """Restore routing fields mutated by a consumer; destinations never come from plugins."""
- current = _snapshot_destination(source)
- if current == snapshot:
- return
- logger.warning(
- "post_gateway_admission consumer attempted to mutate destination metadata; restored"
- )
- try:
- for key, value in snapshot.items():
- if key == "platform":
- # The snapshot stores the enum's .value; coerce back so the
- # attribute lands on the enum, not a bare string.
- from gateway.config import Platform
-
- try:
- setattr(source, key, Platform(value))
- except ValueError:
- setattr(source, key, value)
- continue
- setattr(source, key, value)
- # Restore the event's source reference when it was swapped wholesale.
- if getattr(event, "source", None) is not source:
- event.source = source
- except Exception:
- logger.debug("post_gateway_admission destination restore failed", exc_info=True)
-
-
-async def invoke_post_admission_hook(
+async def run_post_admission_hook(
runner: Any, event: Any, source: Any, session_key: str
-) -> Tuple[bool, Optional[str], Any, Any]:
- """Invoke the ``post_gateway_admission`` hook → ``(handled, reply, event, source)``.
-
- ``handled=False`` means PASS (run the ordinary agent flow). ``handled=True``
- means CONSUMED/FAILED (suppress the agent flow, return ``reply`` which may
- be ``None`` for a silent consume). ``event``/``source`` are returned with
- any destination mutation restored.
- """
- try:
- from hermes_cli.lifecycle import ainvoke_hook as _ainvoke_hook
- except Exception:
- return False, None, event, source
-
- snapshot = _snapshot_destination(source)
- try:
- reply_anchor = None
- try:
- from gateway.platforms.base import _reply_anchor_for_event as _anchor
- reply_anchor = _anchor(event)
- except Exception:
- reply_anchor = getattr(event, "message_id", None)
- context = build_post_admission_context(
- event, source, session_key, reply_anchor=reply_anchor
- )
- except Exception:
- logger.warning("post_gateway_admission context build failed; failing closed", exc_info=True)
- return True, POST_ADMISSION_FAILURE_NOTICE, event, source
-
+) -> Tuple[bool, Optional[str]]:
+ """Return ``(handled, reply)``; ``handled=False`` means run the ordinary agent turn."""
try:
- results = await _ainvoke_hook(
- POST_ADMISSION_HOOK,
- event=event,
- gateway=runner,
- session_store=getattr(runner, "session_store", None),
- source=source,
- session_key=session_key,
- context=context,
- )
+ async with _routed_scope(runner, source):
+ from hermes_cli.lifecycle import ainvoke_hook, has_hook
+ if not has_hook(POST_ADMISSION_HOOK):
+ return False, None
+ results = await ainvoke_hook(
+ POST_ADMISSION_HOOK, session_key=session_key,
+ platform=source.platform.value if source.platform else "",
+ source=source.to_dict(), message_id=event.message_id, text=event.text or "",
+ )
except asyncio.CancelledError:
- # Cancellation after a commit needs receipt lookup, not a new agent
- # turn. Propagate without starting inline execution.
- _restore_destination_if_mutated(event, source, snapshot)
raise
- except Exception as exc:
- logger.warning("post_gateway_admission invocation failed: %s", exc)
- _restore_destination_if_mutated(event, source, snapshot)
- return True, POST_ADMISSION_FAILURE_NOTICE, event, source
-
- _restore_destination_if_mutated(event, source, snapshot)
-
- # The fail-closed timeout path contributes {"action": "block"}; decide maps it to FAILED.
- decision, reply, receipt, diagnostic = decide_post_admission(results)
- if decision == "pass":
- return False, None, event, source
- if decision == "consumed":
- logger.info(
- "post_gateway_admission consumed message (receipt=%s session=%s)",
- receipt or "unknown",
- session_key,
- )
- return True, reply, event, source
- # FAILED: sanitized operator diagnostic (identifiers only, never message text).
- try:
- platform = getattr(getattr(source, "platform", None), "value", "unknown")
except Exception:
- platform = "unknown"
- logger.warning(
- "post_gateway_admission consumer failed (session=%s platform=%s diagnostic=%s)",
- session_key,
- platform,
- (diagnostic or "unknown")[:200],
- )
- return True, (reply or POST_ADMISSION_FAILURE_NOTICE), event, source
+ logger.warning("%s failed; continuing with the agent turn", POST_ADMISSION_HOOK, exc_info=True)
+ return False, None
+ for result in results:
+ if isinstance(result, dict) and result.get("action") == "handled":
+ reply = result.get("reply")
+ logger.info("%s: a plugin handled the message for session %s", POST_ADMISSION_HOOK, session_key)
+ return True, reply if isinstance(reply, str) and reply.strip() else None
+ return False, None
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 69b5d524d39..49fc0c20982 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -136,17 +136,7 @@ VALID_HOOKS: Set[str] = {
# pre_gateway_dispatch: once per incoming MessageEvent, after the internal-event guard, BEFORE
# 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",
- # post_gateway_admission: once per admitted idle business message, AFTER auth/bot-admission,
- # pause/drain, pending-reply intercepts, running-session routing and idle slash-command dispatch
- # (commands, approvals, clarification and steering never reach it), inside the claimed session
- # slot after FIFO orphan rescue. Kwargs: event, gateway, session_store, source, session_key,
- # context (versioned immutable snapshot). Return None/{"action": "pass"} -> ordinary agent flow;
- # {"action": "consumed", "receipt": <id>, "reply": <optional>} -> suppress agent, deliver reply
- # via the normal route; {"action": "failed", "reply": <optional>} -> suppress agent with a short
- # failure notice. Unknown/malformed/exception/timeout fail closed (suppress). No callbacks ->
- # ordinary flow. See gateway/run_inbound_consumer.py.
- "post_gateway_admission",
+ "pre_gateway_dispatch", "post_gateway_admission", # post_*: fail-open consume, gateway/run_inbound_consumer.py
# 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.
diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.py
index e8d40f9d48b..9c303f12f03 100644
--- a/hermes_cli/plugins_dispatch.py
+++ b/hermes_cli/plugins_dispatch.py
@@ -43,11 +43,12 @@ _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_auxiliary_call", "post_auxiliary_call", "pre_verify", "on_session_start", "on_session_end",
+ # Fail-open consumer on every inbound gateway message: a hung plugin must not stall the profile.
+ "post_gateway_admission",
}
-# Policy hooks: timeout / still-running must fail closed (pre_tool_call blocks the tool;
-# post_gateway_admission suppresses the agent turn with a short failure notice).
-_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS: Set[str] = {"pre_tool_call", "post_gateway_admission"}
+# Policy hooks: timeout / still-running must fail closed (block the tool).
+_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS: Set[str] = {"pre_tool_call"}
# Documented parent-thread serialization contract — never run on a timeout worker (hooks.md).
_HOOK_CALLER_THREAD_HOOKS: Set[str] = {"subagent_stop"}
# After a timeout, suppress the same callback this long so a hung hook cannot pile up threads.
diff --git a/tests/gateway/test_post_gateway_admission.py b/tests/gateway/test_post_gateway_admission.py
index af39d8a4896..fe945e5ed15 100644
--- a/tests/gateway/test_post_gateway_admission.py
+++ b/tests/gateway/test_post_gateway_admission.py
@@ -1,546 +1,124 @@
-"""Regression tests for the post-admission consuming gateway extension (#129958).
+"""``post_gateway_admission``: a fail-open plugin hook that may consume an admitted message (#129958).
-Exercises the real ``GatewayRunner._handle_message`` pipeline (not a
-reference model) plus the pure ``decide_post_admission`` / context helpers.
-Covers: rejected/negative admission, pause/drain, control priority, FIFO
-and rescue anchor, multiplex isolation, PASS/CONSUMED/FAILED agent counts,
-fail-closed malformed/exception/timeout/cancellation, receipt requirement,
-destination binding and session-ownership lifecycle.
+Drives the real ``GatewayRunner._handle_message`` pipeline and the real plugin dispatch: callbacks
+are registered on the per-home ``PluginManager`` exactly as ``ctx.register_hook`` stores them.
"""
-import asyncio
-from types import MappingProxyType, SimpleNamespace
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.platforms.event import MessageEvent
-from gateway.session import SessionSource, build_session_key
+from gateway.run import _profile_runtime_scope
+from gateway.session import SessionSource
+from hermes_constants import get_hermes_home
-POST_HOOK = "post_gateway_admission"
-PRE_HOOK = "pre_gateway_dispatch"
+HOOK = "post_gateway_admission"
-def _clear_auth_env(monkeypatch) -> None:
- for key in (
- "TELEGRAM_ALLOWED_USERS",
- "WHATSAPP_ALLOWED_USERS",
- "GATEWAY_ALLOWED_USERS",
- "TELEGRAM_ALLOW_ALL_USERS",
- "WHATSAPP_ALLOW_ALL_USERS",
- "GATEWAY_ALLOW_ALL_USERS",
- ):
- monkeypatch.delenv(key, raising=False)
-
-
-def _make_source(**over) -> SessionSource:
- base = dict(
- platform=Platform.WHATSAPP,
- user_id="[email protected]",
- chat_id="[email protected]",
- user_name="tester",
- chat_type="dm",
- )
- base.update(over)
- return SessionSource(**base)
+def _register(callback) -> None:
+ """Register *callback* on the ACTIVE home's plugin manager (what a loaded plugin does)."""
+ from hermes_cli.plugins import get_plugin_manager
+ manager = get_plugin_manager()
+ manager._discovered = True # no on-disk plugins in the test home; skip discovery
+ manager._hooks.setdefault(HOOK, []).append(callback)
-def _make_event(text="hello", **over) -> MessageEvent:
- src = over.pop("source", None) or _make_source()
- return MessageEvent(text=text, message_id="m1", source=src, **over)
-
-def _make_runner():
+def _runner(*, multiplex=False):
from gateway.run import GatewayRunner
- config = GatewayConfig(platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)})
runner = object.__new__(GatewayRunner)
- runner.config = config
+ runner.config = GatewayConfig(
+ platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)}, multiplex_profiles=multiplex,
+ )
adapter = SimpleNamespace(send=AsyncMock())
runner.adapters = {Platform.WHATSAPP: adapter}
runner.pairing_store = MagicMock()
- runner.pairing_store.is_approved.return_value = False
- runner.pairing_store._is_rate_limited.return_value = False
runner.session_store = MagicMock()
- # Authorize + admit by default; individual tests override to deny.
- runner._is_user_authorized_for_source = lambda _s: True # noqa: SLF001
- runner._admit_bot_message_for_source = lambda _s: True # noqa: SLF001
- runner._delivery_adapter_for = lambda _s: adapter # noqa: SLF001
- runner._intake_adapter_for = lambda _s: adapter # noqa: SLF001
- runner._rescue_orphaned_overflow = lambda _k, _a: None # noqa: SLF001
- runner._enqueue_fifo = MagicMock() # noqa: SLF001
- runner._handle_message_with_agent = AsyncMock(return_value="agent-ok") # noqa: SLF001
- runner._run_post_turn_hooks = AsyncMock() # noqa: SLF001
- return runner, adapter
+ runner._is_user_authorized_for_source = lambda _s: True
+ runner._admit_bot_message_for_source = lambda _s: True
+ runner._delivery_adapter_for = lambda _s: adapter
+ runner._intake_adapter_for = lambda _s: adapter
+ runner._rescue_orphaned_overflow = lambda _k, _a: None
+ runner._enqueue_fifo = MagicMock()
+ runner._handle_message_with_agent = AsyncMock(return_value="agent-ok")
+ runner._run_post_turn_hooks = AsyncMock()
+ return runner
+
+
+def _event(text="queue my report", profile=None):
+ source = SessionSource(
+ platform=Platform.WHATSAPP, user_id="[email protected]",
+ chat_id="[email protected]", user_name="tester", chat_type="dm", profile=profile,
+ )
+ return MessageEvent(text=text, message_id="m1", source=source)
[email protected](autouse=True)
def _allow_all(monkeypatch):
- _clear_auth_env(monkeypatch)
+ for key in ("WHATSAPP_ALLOWED_USERS", "GATEWAY_ALLOWED_USERS", "GATEWAY_ALLOW_ALL_USERS"):
+ monkeypatch.delenv(key, raising=False)
monkeypatch.setenv("WHATSAPP_ALLOWED_USERS", "*")
-def _post_only(monkeypatch, post_fn, calls=None):
- """Patch the plugin hook seam: pre hook allows, post hook delegates to *post_fn*.
-
- Both ``pre_gateway_dispatch`` and ``post_gateway_admission`` flow through
- the same ``ainvoke_hook`` seam; counting every call would conflate the
- pre-auth policy gate with the business consumer. This helper makes the
- pre hook a no-op allow and only counts/invokes for the post hook.
- """
-
- async def _hook(name, **kwargs):
- if name == PRE_HOOK:
- return []
- if name == POST_HOOK:
- if calls is not None:
- calls["n"] += 1
- return await post_fn(name, **kwargs) if asyncio.iscoroutinefunction(post_fn) else post_fn(name, **kwargs)
- return []
-
- monkeypatch.setattr("hermes_cli.plugins.ainvoke_hook", _hook)
- return _hook
-
-
-# ── pure helpers ──────────────────────────────────────────────────────────
-
-def test_decide_pass_consumed_failed():
- from gateway.run_inbound_consumer import decide_post_admission
-
- assert decide_post_admission([])[0] == "pass"
- assert decide_post_admission([None])[0] == "pass"
- assert decide_post_admission([{"action": "pass"}])[0] == "pass"
- assert decide_post_admission([{"action": "allow"}])[0] == "pass"
-
- d, reply, receipt, _ = decide_post_admission(
- [{"action": "consumed", "receipt": "r1", "reply": "ack"}]
- )
- assert (d, reply, receipt) == ("consumed", "ack", "r1")
-
- d, reply, _, _ = decide_post_admission([{"action": "failed", "reply": "oops"}])
- assert d == "failed" and reply == "oops"
-
- # First decisive wins; ambiguous config warns but stays deterministic.
- d, reply, receipt, _ = decide_post_admission(
- [
- {"action": "consumed", "receipt": "first", "reply": "one"},
- {"action": "consumed", "receipt": "second", "reply": "two"},
- ]
- )
- assert (d, receipt) == ("consumed", "first")
-
-
-def test_decide_fail_closed_on_malformed():
- from gateway.run_inbound_consumer import decide_post_admission
-
- assert decide_post_admission([{"action": "weird"}])[0] == "failed"
- assert decide_post_admission(["oops"])[0] == "failed"
- assert decide_post_admission([{"action": "consumed"}])[0] == "failed"
- assert decide_post_admission([{"action": "consumed", "receipt": " "}])[0] == "failed"
- assert decide_post_admission([{"action": "consumed", "receipt": "r", "reply": 123}])[0] == "failed"
- # Timeout path contributes {"action": "block"} → FAILED.
- assert decide_post_admission([{"action": "block", "message": "timeout"}])[0] == "failed"
-
-
-def test_context_is_versioned_and_immutable():
- from gateway.run_inbound_consumer import (
- POST_ADMISSION_VERSION,
- build_post_admission_context,
- )
-
- event = _make_event("hi")
- ctx = build_post_admission_context(event, event.source, "k1", reply_anchor="m1")
- assert ctx["version"] == POST_ADMISSION_VERSION
- assert ctx["platform"] == "whatsapp"
- assert ctx["session_key"] == "k1"
- assert ctx["reply_anchor"] == "m1"
- assert isinstance(ctx, MappingProxyType)
- with pytest.raises(TypeError):
- ctx["platform"] = "evil"
- with pytest.raises(TypeError):
- ctx["conversation"]["chat_id"] = "evil"
-
-
-# ── admission gates: zero consumers, zero business writes ─────────────────
-
@pytest.mark.asyncio
-async def test_rejected_source_invokes_zero_consumers(monkeypatch):
- """RED from the issue: rejected source → zero consumers, zero business writes."""
- _clear_auth_env(monkeypatch)
- calls = {"n": 0}
+async def test_handled_consumes_the_turn_and_its_reply_is_delivered():
+ seen = []
- async def _post(name, **kwargs):
- return [{"action": "consumed", "receipt": "r", "reply": "ack"}]
+ def consume(**kwargs):
+ seen.append(kwargs)
+ return {"action": "handled", "reply": "Queued - I'll follow up."}
- _post_only(monkeypatch, _post, calls)
- runner, _ = _make_runner()
- runner._is_user_authorized_for_source = lambda _s: False # noqa: SLF001
+ _register(consume)
+ runner = _runner()
- result = await runner._handle_message(_make_event("hello"))
-
- assert result is None
- assert calls["n"] == 0
+ assert await runner._handle_message(_event()) == "Queued - I'll follow up."
+ # The session slot is released on the consume path: the next message is admitted, not queued.
+ assert await runner._handle_message(_event("another")) == "Queued - I'll follow up."
runner._handle_message_with_agent.assert_not_awaited()
+ # Snapshot-only payload: message + routing facts, never live runner/store handles.
+ first = seen[0]
+ assert first["text"] == "queue my report" and first["message_id"] == "m1"
+ assert first["platform"] == "whatsapp"
+ assert first["source"]["chat_id"] == "[email protected]" and first["session_key"]
+ assert "gateway" not in first and "session_store" not in first
@pytest.mark.asyncio
-async def test_negative_admission_each_invokes_zero_consumers(monkeypatch):
- _allow_all(monkeypatch)
- from gateway.config import Platform as _P
-
- async def _post(name, **kwargs):
- raise AssertionError("business consumer must not run")
-
- _post_only(monkeypatch, _post)
-
- # Internal / system event still runs the agent but never the consumer.
- runner, _ = _make_runner()
- internal = _make_event("sys")
- internal.internal = True
- await runner._handle_message(internal)
- runner._handle_message_with_agent.assert_awaited()
+async def test_a_raising_consumer_fails_open_and_the_message_reaches_the_agent():
+ def broken(**_kwargs):
+ raise RuntimeError("plugin bug")
- # Bot-loop rejection.
- runner2, _ = _make_runner()
- runner2._admit_bot_message_for_source = lambda _s: False # noqa: SLF001
- assert await runner2._handle_message(_make_event("hi")) is None
- runner2._handle_message_with_agent.assert_not_awaited()
+ _register(broken)
+ runner = _runner()
- # Unserved profile route.
- runner3, _ = _make_runner()
- ev = _make_event("hi")
- ev.source.profile_route_rejected = True
- assert await runner3._handle_message(ev) is None
- runner3._handle_message_with_agent.assert_not_awaited()
-
- # Ignored Slack channel.
- runner4 = _make_runner()[0]
- import gateway.config as _cfg
-
- runner4.config = _cfg.GatewayConfig(
- platforms={_P.SLACK: _cfg.PlatformConfig(enabled=True, extra={"ignored_channels": ["C123"]})},
- )
- runner4.adapters = {_P.SLACK: SimpleNamespace(send=AsyncMock(), config=SimpleNamespace(extra={"ignored_channels": ["C123"]}))}
- runner4._delivery_adapter_for = lambda _s: runner4.adapters[_P.SLACK] # noqa: SLF001
- runner4._intake_adapter_for = lambda _s: runner4.adapters[_P.SLACK] # noqa: SLF001
- slack_src = SessionSource(
- platform=_P.SLACK, user_id="U1", chat_id="C123", chat_type="group",
- )
- assert await runner4._handle_message(MessageEvent(text="hi", message_id="m9", source=slack_src)) is None
- runner4._handle_message_with_agent.assert_not_awaited()
+ assert await runner._handle_message(_event()) == "agent-ok"
+ # Every following message on the profile keeps flowing too.
+ assert await runner._handle_message(_event("second")) == "agent-ok"
+ assert runner._handle_message_with_agent.await_count == 2
-# ── pause / drain ─────────────────────────────────────────────────────────
-
@pytest.mark.asyncio
-async def test_pause_and_drain_suppress_consumer_but_commands_still_route(monkeypatch):
- _allow_all(monkeypatch)
- calls = {"n": 0}
-
- async def _post(name, **kwargs):
- return [{"action": "consumed", "receipt": "r", "reply": "ack"}]
-
- _post_only(monkeypatch, _post, calls)
- runner, _ = _make_runner()
- runner._hm_estop_gate = lambda _e, _s, _i: "paused-notice" # noqa: SLF001
-
- assert await runner._handle_message(_make_event("business")) == "paused-notice"
- assert calls["n"] == 0
+async def test_consumer_fires_in_the_routed_profile_scope_only(tmp_path):
+ launch, routed = tmp_path / "launch", tmp_path / "profiles" / "beta"
+ launch.mkdir()
+ routed.mkdir(parents=True)
+ fired = []
+
+ with _profile_runtime_scope(launch):
+ _register(lambda **_k: fired.append(("launch", get_hermes_home())))
+ with _profile_runtime_scope(routed):
+ _register(lambda **_k: fired.append(("beta", get_hermes_home())) or {"action": "handled"})
+
+ runner = _runner(multiplex=True)
+ runner._resolve_profile_home_for_source = lambda _source: routed
+ # The receiving bot's handler binds ITS home (auth reads its .env); this chat routes to beta.
+ with _profile_runtime_scope(launch):
+ assert await runner._handle_message(_event(profile="beta")) is None
+ assert get_hermes_home() == launch # scope restored after the hook
+
+ assert fired == [("beta", routed)]
runner._handle_message_with_agent.assert_not_awaited()
-
- # Recognized control traffic still reaches its owner under pause.
- # /start is DB-free (unlike /status) so the bare test runner can route it.
- runner2, _ = _make_runner()
- runner2._hm_estop_gate = lambda _e, _s, _i: None # noqa: SLF001
- result = await runner2._handle_message(_make_event("/start"))
- assert calls["n"] == 0 # commands never reach the business consumer
- runner2._handle_message_with_agent.assert_not_awaited()
- assert result is not None
-
- # External drain refuses new business without invoking the consumer.
- runner3, _ = _make_runner()
- runner3._external_drain_active = True
- assert "drain" in (await runner3._handle_message(_make_event("work")) or "").lower()
- assert calls["n"] == 0
- runner3._handle_message_with_agent.assert_not_awaited()
-
-
-# ── control priority ──────────────────────────────────────────────────────
-
-async def test_control_traffic_never_reaches_consumer(monkeypatch):
- _allow_all(monkeypatch)
- calls = {"n": 0}
-
- async def _post(name, **kwargs):
- return [{"action": "consumed", "receipt": "r", "reply": "ack"}]
-
- _post_only(monkeypatch, _post, calls)
-
- # Slash command (/start is DB-free for the bare runner).
- runner, _ = _make_runner()
- await runner._handle_message(_make_event("/start"))
- assert calls["n"] == 0
-
- # Pending-reply intercept owns the message.
- runner2, _ = _make_runner()
- runner2._hm_pending_reply_intercepts = AsyncMock(return_value="") # noqa: SLF001
- await runner2._handle_message(_make_event("answer"))
- assert calls["n"] == 0
- runner2._handle_message_with_agent.assert_not_awaited()
-
- # Running session steers/queues; busy ownership is core-decided.
- runner3, _ = _make_runner()
- key = build_session_key(_make_source())
- runner3._session_state(key).turn.agent = MagicMock()
- runner3._session_state(key).turn.agent._supports_active_turn_redirect = False
- runner3._effective_busy_input_mode = lambda _s: "interrupt" # noqa: SLF001
- runner3._steer_running_agent = lambda *_a: False # noqa: SLF001
- await runner3._handle_message(_make_event("steer me"))
- assert calls["n"] == 0
- runner3._handle_message_with_agent.assert_not_awaited()
-
-
-# ── FIFO / rescue anchor ──────────────────────────────────────────────────
-
-async def test_busy_messages_defer_and_rescue_presents_selected_anchor(monkeypatch):
- _allow_all(monkeypatch)
- seen = {}
-
- async def _post(name, **kwargs):
- ctx = kwargs.get("context", {})
- seen["event_id"] = ctx.get("event_id")
- seen["anchor"] = ctx.get("reply_anchor")
- return [{"action": "consumed", "receipt": "r1", "reply": "ack"}]
-
- _post_only(monkeypatch, _post)
- runner, _ = _make_runner()
-
- rescued_src = _make_source()
- rescued = MessageEvent(text="oldest orphan", message_id="old-1", source=rescued_src)
- incoming = _make_event("new arrival")
- runner._hm_rescue_orphaned_fifo = lambda e, s, i, k: (rescued, rescued_src, False) # noqa: SLF001
-
- result = await runner._handle_message(incoming)
- assert result == "ack"
- assert seen["event_id"] == "old-1"
- runner._handle_message_with_agent.assert_not_awaited()
-
-
-# ── PASS / CONSUMED / FAILED ──────────────────────────────────────────────
-
-async def test_pass_runs_agent_once_consumed_and_failed_suppress(monkeypatch):
- _allow_all(monkeypatch)
-
- async def _pass(name, **kwargs):
- return [{"action": "pass"}]
-
- _post_only(monkeypatch, _pass)
- runner, _ = _make_runner()
- assert await runner._handle_message(_make_event("work")) == "agent-ok"
- runner._handle_message_with_agent.assert_awaited_once()
-
- async def _consumed(name, **kwargs):
- return [{"action": "consumed", "receipt": "req-1", "reply": "queued ✓"}]
-
- _post_only(monkeypatch, _consumed)
- runner2, _ = _make_runner()
- assert await runner2._handle_message(_make_event("follow up")) == "queued ✓"
- runner2._handle_message_with_agent.assert_not_awaited()
-
- async def _failed(name, **kwargs):
- return [{"action": "failed", "reply": "cannot queue right now"}]
-
- _post_only(monkeypatch, _failed)
- runner3, _ = _make_runner()
- assert await runner3._handle_message(_make_event("follow up")) == "cannot queue right now"
- runner3._handle_message_with_agent.assert_not_awaited()
-
-
-async def test_fail_closed_variants_suppress_agent(monkeypatch):
- _allow_all(monkeypatch)
-
- async def _malformed(name, **kwargs):
- return [{"action": "definitely-not-real"}]
-
- _post_only(monkeypatch, _malformed)
- runner, _ = _make_runner()
- result = await runner._handle_message(_make_event("hi"))
- assert "failed" in result.lower()
- runner._handle_message_with_agent.assert_not_awaited()
-
- async def _boom(name, **kwargs):
- raise RuntimeError("consumer exploded")
-
- _post_only(monkeypatch, _boom)
- runner2, _ = _make_runner()
- result2 = await runner2._handle_message(_make_event("hi"))
- assert "failed" in result2.lower()
- assert "exploded" not in result2
- runner2._handle_message_with_agent.assert_not_awaited()
-
- # Timeout path surfaces {"action": "block"} from the bounded dispatcher.
- # Fail-closed means the agent is suppressed; the dispatcher-provided
- # message becomes the short user notice.
- async def _timeout(name, **kwargs):
- return [{"action": "block", "message": "timed out"}]
-
- _post_only(monkeypatch, _timeout)
- runner3, _ = _make_runner()
- result3 = await runner3._handle_message(_make_event("hi"))
- assert result3 == "timed out"
- runner3._handle_message_with_agent.assert_not_awaited()
-
- # Cancellation never starts inline execution.
- async def _cancel(name, **kwargs):
- raise asyncio.CancelledError()
-
- _post_only(monkeypatch, _cancel)
- runner4, _ = _make_runner()
- with pytest.raises(asyncio.CancelledError):
- await runner4._handle_message(_make_event("hi"))
- runner4._handle_message_with_agent.assert_not_awaited()
-
-
-async def test_consumed_without_receipt_fails_closed(monkeypatch):
- _allow_all(monkeypatch)
-
- async def _hook(name, **kwargs):
- return [{"action": "consumed", "reply": "ack without commit"}]
-
- _post_only(monkeypatch, _hook)
- runner, _ = _make_runner()
- result = await runner._handle_message(_make_event("do work"))
- assert "failed" in result.lower()
- assert "without commit" not in result
- runner._handle_message_with_agent.assert_not_awaited()
-
-
-# ── destination binding + lifecycle ───────────────────────────────────────
-
-async def test_destination_mutation_is_restored(monkeypatch):
- _allow_all(monkeypatch)
- from gateway.run_inbound_consumer import invoke_post_admission_hook
-
- async def _hook(name, **kwargs):
- event = kwargs.get("event")
- if name == POST_HOOK:
- event.source.chat_id = "EVIL-CHAT"
- event.source.platform = Platform.TELEGRAM
- event.text = "mutated text is allowed"
- return [{"action": "pass"}]
- return []
-
- monkeypatch.setattr("hermes_cli.lifecycle.ainvoke_hook", _hook)
- runner, _ = _make_runner()
- event = _make_event("original")
- handled, reply, out_event, out_source = await invoke_post_admission_hook(
- runner, event, event.source, "k"
- )
- assert handled is False and reply is None
- assert out_source.chat_id == "[email protected]"
- assert out_source.platform is Platform.WHATSAPP
- assert out_event.source.chat_id == "[email protected]"
- assert out_event.source.platform is Platform.WHATSAPP
-
-
-async def test_failure_does_not_leak_session_ownership(monkeypatch):
- _allow_all(monkeypatch)
- calls = {"n": 0}
-
- async def _flaky(name, **kwargs):
- # Wrapper already counted this post-hook invocation in calls["n"].
- if calls["n"] == 1:
- raise RuntimeError("first turn fails")
- return [{"action": "pass"}]
-
- _post_only(monkeypatch, _flaky, calls)
- runner, _ = _make_runner()
- first = await runner._handle_message(_make_event("one"))
- assert "failed" in first.lower()
- second = await runner._handle_message(_make_event("two"))
- assert second == "agent-ok"
- assert runner._handle_message_with_agent.await_count == 1
-
-
-async def test_context_carries_routed_profile_and_anchor(monkeypatch):
- _allow_all(monkeypatch)
- seen = {}
-
- async def _hook(name, **kwargs):
- seen.update(kwargs.get("context", {}))
- return [{"action": "pass"}]
-
- _post_only(monkeypatch, _hook)
- runner, _ = _make_runner()
- src = _make_source(profile="satellite")
- await runner._handle_message(MessageEvent(text="hi", message_id="mid-7", source=src))
- assert seen["profile"] == "satellite"
- assert seen["event_id"] == "mid-7"
- assert seen["reply_anchor"] == "mid-7"
- runner._handle_message_with_agent.assert_awaited_once()
-
-
-def test_hook_registered_in_valid_hooks_and_fail_closed():
- """The hook is a valid registration and times out fail-closed."""
- from hermes_cli.plugins import VALID_HOOKS
- from hermes_cli.plugins_dispatch import _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS
-
- assert "post_gateway_admission" in VALID_HOOKS
- assert "post_gateway_admission" in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS
-
-
-def test_profile_scoped_managers_isolate_consumers(tmp_path, monkeypatch):
- """Two homes with real discovery never cross consumers (A→B→A)."""
- import textwrap
-
- import hermes_yaml as yaml
- from hermes_cli import plugins as plugins_mod
-
- def _home(name, marker):
- home = tmp_path / name
- plugindir = home / "plugins" / "consumer"
- plugindir.mkdir(parents=True)
- (plugindir / "plugin.yaml").write_text(
- yaml.safe_dump({"name": "consumer", "version": "0.1.0", "description": "test"}),
- encoding="utf-8",
- )
- (plugindir / "__init__.py").write_text(
- "def register(ctx):\n"
- f" ctx.register_hook('post_gateway_admission', lambda **kw: {{'action': 'consumed', 'receipt': '{marker}', 'reply': '{marker}'}})\n",
- encoding="utf-8",
- )
- cfg = {"plugins": {"enabled": ["consumer"]}}
- (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")
- return home
-
- home_a, home_b = _home("homeA", "A"), _home("homeB", "B")
- plugins_mod._reset_plugin_managers_for_tests()
- try:
- monkeypatch.setenv("HERMES_HOME", str(home_a))
- mgr_a = plugins_mod.get_plugin_manager()
- mgr_a.discover_and_load(force=True)
- res_a = mgr_a.invoke_hook("post_gateway_admission", event="e")
- assert res_a == [{"action": "consumed", "receipt": "A", "reply": "A"}]
-
- monkeypatch.setenv("HERMES_HOME", str(home_b))
- mgr_b = plugins_mod.get_plugin_manager()
- assert mgr_b is not mgr_a
- mgr_b.discover_and_load(force=True)
- res_b = mgr_b.invoke_hook("post_gateway_admission", event="e")
- assert res_b == [{"action": "consumed", "receipt": "B", "reply": "B"}]
-
- monkeypatch.setenv("HERMES_HOME", str(home_a))
- assert plugins_mod.get_plugin_manager() is mgr_a
- assert mgr_a.invoke_hook("post_gateway_admission", event="e") == [
- {"action": "consumed", "receipt": "A", "reply": "A"}
- ]
- finally:
- plugins_mod._reset_plugin_managers_for_tests()
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index d76ef5316fa..b1c31b3339f 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -476,7 +476,7 @@ Payload fields below are the exact event-specific fields supplied by each call s
| `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. |
| `pre_gateway_dispatch` | Directive/control | Incoming non-internal message before auth/pairing/dispatch; first valid `skip`, `rewrite`, or `allow` controls flow. | `event`, `gateway`, `session_store` | Extremely privileged in-process objects expose inbound user/routing data and host handles. |
-| `post_gateway_admission` | Directive/control | Admitted idle business message after auth, pause/drain, pending-reply, running-session and slash-command lanes, inside the claimed slot after FIFO rescue; first decisive `consumed`/`failed` wins, `pass` runs the agent. | `event`, `gateway`, `session_store`, `source`, `session_key`, `context` (v1 immutable snapshot) | Trusted in-process consumer; `context.text` is untrusted inbound data, destinations never come from plugin fields. |
+| `post_gateway_admission` | Directive/control (fail-open) | Admitted non-internal message after auth, pause/drain, pending-reply, running-session and slash-command lanes, inside the claimed session slot and the routed profile's scope; first `handled` result skips the agent turn, anything else (including a raise or timeout) runs it. | `session_key`, `platform`, `source` (dict snapshot), `message_id`, `text` | Inbound text is untrusted user data; no runner or session-store handles are passed. |
| `gateway_platform_event` | Observer | After the gateway's profile-scoped authorization succeeds, when a supported platform-native event is normalized at the gateway boundary (Telegram: reactions, message edits; Discord: message edits/deletes, thread created/renamed); return ignored. | `platform`, `event_type`, `payload` (event-type-specific dict — see the per-event contracts below) | Normalized plain-dict envelope only; raw SDK objects, adapter handles, and bot clients are never exposed. |
| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. |
| `pre_approval_request` | Observer | Before prompted or smart approval; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id` | Command may contain secrets; smart observer preparation force-redacts, but surfaces do not all have identical redaction. |
@@ -1277,28 +1277,22 @@ def register(ctx):
### `post_gateway_admission`
-Fires **once per admitted idle business message** in the gateway, after core owns routing, authorization, bot admission, pause/drain, pending-reply ownership, running-session steering and slash-command dispatch. Commands, approvals, clarification replies and busy steering never reach it; rejected, ignored-channel, unserved-profile, bot-loop and internal/system events never invoke it. The consumer runs inside the claimed session slot after FIFO orphan rescue, so the selected event (with its own reply anchor) is presented and concurrent arrivals serialize through the busy path.
+Fires **once per admitted, non-internal message** in the gateway, after authorization, bot admission, pause/drain, pending-reply intercepts (clarify, confirmations), the running-session lane (steering, busy commands) and idle slash-command dispatch. Rejected, ignored, internal and control traffic never reaches it. It runs inside the claimed session slot, so concurrent messages for the same chat queue behind it, and under the message's **routed profile** scope: only that profile's plugins run.
+
+Return `{"action": "handled", "reply": "..."}` to consume the message: the agent turn is skipped and `reply` (when a non-empty string) is delivered through the normal route. Omit `reply` to consume silently. Any other return value runs the ordinary agent turn.
```python
-def consume(event, source, session_key, context, **kwargs):
- # context is v1 and immutable: version, profile, platform, session_key,
- # conversation {chat_id, thread_id, chat_type}, event_id, sender, reply_anchor, text.
- if not _is_follow_up(context["text"]):
- return None # or {"action": "pass"}: ordinary agent flow runs once
- receipt = _commit_request(context) # durable commit BEFORE consumed
- return {"action": "consumed", "receipt": receipt, "reply": "Got it — queued."}
+def consume(session_key, platform, source, message_id, text, **kwargs):
+ if not text.startswith("follow up:"):
+ return None # ordinary agent turn
+ enqueue_follow_up(source, text) # commit your own durable state first
+ return {"action": "handled", "reply": "Got it - queued."}
def register(ctx):
ctx.register_hook("post_gateway_admission", consume)
```
-| Return | Effect |
-|--------|--------|
-| `None` / `{"action": "pass"}` (also `"allow"`) | Ordinary agent flow runs once. |
-| `{"action": "consumed", "receipt": "<id>", "reply": "<optional>"}` | Agent flow suppressed; `reply` (when a non-empty string) is delivered through the normal core-owned route. `receipt` is required — a missing/invalid receipt fails closed. Commit durable state before returning consumed; reconcile replays by receipt. |
-| `{"action": "failed", "reply": "<optional>"}` (also `"fail"`, `"error"`, `"block"`, `"deny"`) | Agent flow suppressed with a short failure notice (`reply` when a string, else a generic notice); a sanitized operator diagnostic is logged. |
-
-Fail-closed: unknown/malformed results, exceptions and timeouts suppress the agent turn, never silently permit inline execution. No registered consumer means ordinary flow (deliberately disabled is distinct from failing). The hook is bounded by `plugins.hook_callback_timeout` (default 30s); a timeout suppresses the turn. Do not do slow build/model work in the callback; do not send via adapters directly — return `reply` and let core deliver it. Destination metadata is snapshot before invocation and restored when mutated. Durable acceptance, dedupe and response reconciliation are plugin responsibilities; core claims no exactly-once external delivery. Only the routed profile's consumers run.
+**Fail-open.** A callback that raises, times out (`plugins.hook_callback_timeout`) or returns something else is logged and the message proceeds to the agent, so one buggy plugin cannot block a profile's traffic. A plugin that needs fail-closed behaviour catches its own errors and returns `handled` with its own failure reply. The payload is a snapshot (`source` is `SessionSource.to_dict()`); do not send through adapters directly, return `reply` instead. Dedupe and durable acceptance are the plugin's responsibility.
---