The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): enforce post-auth normalized reaction observer
Teknium9994bc9ec9f6
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..5ca4dc852b7--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+paoloantinori+# PR #68431 gateway_platform_event observer salvagediff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 475d8f8386d..80651176d49 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3005,6 +3005,12 @@ class BasePlatformAdapter(ABC):self._reaction_handler: Optional[Callable[[Dict[str, Any]], Awaitable[None]]] = None+ # Normalized platform events cross this runner-owned boundary before+ # plugin dispatch so authorization/profile state never lives in an SDK+ # adapter. The second argument is an internal SessionSource.+ self._platform_event_handler: Optional[+ Callable[[Dict[str, Any], Any], Awaitable[None]]+ ] = None# Optional hook (e.g. Telegram DM topic recovery) that rewrites# ``event.source.thread_id`` before session keying. Returns the# corrected thread_id or None to leave the source untouched.@@ -3583,24 +3589,6 @@ class BasePlatformAdapter(ABC):"""Check if adapter is currently connected."""return self._running- def _fire_gateway_hook(self, name: str, **kwargs: Any) -> None:- """Fire a ``gateway_*`` platform-boundary observer hook (see VALID_HOOKS).-- Observer-only: ``invoke_hook`` isolates each callback and this wrapper- swallows any plugin-layer error so a misbehaving plugin can't break the- adapter. A ``has_hook`` guard skips all dispatch when nothing subscribes- (the common case). Callers pass the hook's documented kwargs (e.g. the- normalized ``gateway_platform_event`` envelope) — never raw SDK objects.- """- try:- from hermes_cli.plugins import get_plugin_manager- mgr = get_plugin_manager()- if not mgr.has_hook(name):- return- mgr.invoke_hook(name, **kwargs)- except Exception as exc:- logger.debug("[%s] %s hook fire error: %s", self.name, name, exc)-def set_message_handler(self, handler: MessageHandler) -> None:"""Set the handler for incoming messages.@@ -3610,6 +3598,19 @@ class BasePlatformAdapter(ABC):"""self._message_handler = handler+ def set_platform_event_handler(+ self,+ handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]],+ ) -> None:+ """Install the gateway-owned normalized platform-event boundary.++ Adapters normalize SDK updates and pass only stable dictionaries plus an+ internal ``SessionSource`` to this callback. The runner owns the final+ authorization decision and plugin dispatch; an adapter with no callback+ therefore fails closed instead of exposing pre-auth events.+ """+ self._platform_event_handler = handler+def set_topic_recovery_fn(self,fn: Optional[Callable[[Any], Optional[str]]],diff --git a/gateway/run.py b/gateway/run.pyindex d6ee2991f85..6fa588cdf0e 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -11526,6 +11526,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_set_reaction(self._handle_reaction_event)adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))+ adapter.set_platform_event_handler(self._primary_platform_event_handler())adapter._busy_text_mode = self._busy_text_mode# Try to connect@@ -12919,6 +12920,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_set_reaction(self._handle_reaction_event)adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))+ adapter.set_platform_event_handler(self._primary_platform_event_handler())adapter._busy_text_mode = self._busy_text_mode# Reconnect after an outage: preserve the platform's@@ -13900,6 +13902,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewadapter.set_authorization_check(self._make_adapter_auth_check(platform, profile_name=profile_name))+ adapter.set_platform_event_handler(+ self._make_profile_platform_event_handler(profile_name)+ )text_modes = getattr(self, "_busy_text_modes_by_profile", None)adapter._busy_text_mode = (text_modes.get(profile_name, self._busy_text_mode)@@ -14133,6 +14138,55 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreturn self._make_default_profile_message_handler()return self._handle_message+ async def _handle_gateway_platform_event(self, event: dict, source) -> None:+ """Authorize and publish one normalized adapter event to plugin hooks."""+ try:+ if not self._is_user_authorized(source):+ return+ from hermes_cli.plugins import get_plugin_manager++ manager = get_plugin_manager()+ if not manager.has_hook("gateway_platform_event"):+ return+ manager.invoke_hook("gateway_platform_event", **event)+ except Exception:+ # Observer failures must never break the adapter's update loop.+ logger.debug("gateway_platform_event hook dispatch failed", exc_info=True)++ def _make_profile_platform_event_handler(self, profile_name: str):+ """Bind platform-event auth and hook dispatch to one multiplex profile."""+ from hermes_cli.profiles import get_profile_dir++ try:+ profile_home = get_profile_dir(profile_name)+ except Exception:+ profile_home = None++ async def _handler(event, source):+ if getattr(source, "profile", None) is None:+ source.profile = profile_name+ if profile_home is not None:+ with _profile_runtime_scope(profile_home):+ return await self._handle_gateway_platform_event(event, source)+ return await self._handle_gateway_platform_event(event, source)++ return _handler++ def _make_default_profile_platform_event_handler(self):+ """Scope default-profile event auth under multiplexing from ingress."""+ profile_home = Path(get_hermes_home())++ async def _handler(event, source):+ with _profile_runtime_scope(profile_home):+ return await self._handle_gateway_platform_event(event, source)++ return _handler++ def _primary_platform_event_handler(self):+ if getattr(self.config, "multiplex_profiles", False):+ return self._make_default_profile_platform_event_handler()+ return self._handle_gateway_platform_event+@staticmethoddef _adapter_credential_claim(platform: Platform, adapter: Anydiff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex c113da30380..9459dda9ce1 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -222,15 +222,15 @@ VALID_HOOKS: Set[str] = {"kanban_task_blocked",# Gateway platform-boundary observer hooks (#64176). Observer-only; each# callback isolated by invoke_hook. Payloads are normalized envelopes only,- # never raw platform SDK objects (per #64176 / #64182 ground rule); raw- # access is a separate capability-gated action API, not a hook.+ # never raw platform SDK objects (per #64176 / #64182 ground rule). This+ # surface grants no adapter handles or platform actions.## gateway_platform_event: inbound platform event as a normalized envelope.# Kwargs: platform, event_type, payload (event_type-specific dict).# Telegram reactions fire today. Other event types and their hook- # names land here together with their real fire-sites and payload- # contracts when #64176's taxonomy is finalized (#64231); no inert- # VALID_HOOKS surface is registered ahead of implementation.+ # names land here only together with real fire-sites and payload+ # contracts; no inert VALID_HOOKS surface is registered ahead of+ # implementation."gateway_platform_event",}@@ -2687,7 +2687,12 @@ class PluginManager:are reused. All injected context is ephemeral — neverpersisted to session DB."""- kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION)+ # Most legacy observer hooks carry the shared telemetry marker. Gateway+ # platform events define event-local additive envelopes instead: injecting+ # a bus-wide version here would turn unrelated adapter payloads into one+ # monolithic compatibility contract (#64176).+ if hook_name != "gateway_platform_event":+ kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION)callbacks = self._hooks.get(hook_name, [])results: List[Any] = []for cb in callbacks:diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 252f024414e..c0b0445251c 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -20,7 +20,7 @@ import threadingimport timefrom contextvars import ContextVarfrom datetime import datetime, timezone-from typing import Dict, List, Optional, Set, Any+from typing import Any, Awaitable, Callable, Dict, List, Optional, Setlogger = logging.getLogger(__name__)@@ -1061,18 +1061,13 @@ class TelegramAdapter(BasePlatformAdapter):Mirrors ``_source_from_message_for_auth`` but for reactions, whichcarry the reactor (``user``, or ``actor_chat`` for an anonymous admin)- and ``chat`` but no ``Message``. Chat type is resolved as far as the- reaction shape allows so the shared authorization decision- (``_is_source_authorized``) matches the message intake outcome (the- runner treats group and forum identically, so the lack of a thread id- on reactions does not change the decision). Reactions expose no thread- id, so ``thread_id`` is None.-- Raises ``ValueError`` for a non-reaction update (no ``message_reaction``)- so the post-auth gate in ``_on_platform_update`` fails closed (drops the- event via its try/except) rather than resolving an empty identity and- authorizing it. This keeps a future event type from silently bypassing- auth before its own source extraction is wired.+ and ``chat`` but no ``Message``. The gateway runner uses this internal+ source for its normal profile-scoped authorization decision. Reactions+ expose no thread id, so ``thread_id`` is None.++ Raises ``ValueError`` when the reaction, actor, chat, or message identity+ is absent so the post-auth boundary fails closed rather than authorizing+ an incomplete source. A future event type must wire its own extraction."""from gateway.session import SessionSource@@ -1094,7 +1089,12 @@ class TelegramAdapter(BasePlatformAdapter):or None)- chat_id = str(getattr(chat, "id", "")).strip() or user_id+ chat_id = str(getattr(chat, "id", "")).strip() or None+ message_id = getattr(mr, "message_id", None)+ if not user_id or not chat_id or message_id is None or not str(message_id).strip():+ raise ValueError(+ "gateway_platform_event reaction requires actor, chat, and message identities"+ )chat_type = str(getattr(chat, "type", "dm")).strip().lower() or "dm"if chat_type == "private":chat_type = "dm"@@ -1105,7 +1105,7 @@ class TelegramAdapter(BasePlatformAdapter):return SessionSource(platform=Platform.TELEGRAM,- chat_id=chat_id or "",+ chat_id=chat_id,chat_type=chat_type,user_id=user_id,user_name=user_name,@@ -1170,19 +1170,7 @@ class TelegramAdapter(BasePlatformAdapter):Unknown DMs with an allowlist still pass through when pairing is theeffective unauthorized-DM behavior (explicit platform override)."""- return self._is_source_authorized(self._source_from_message_for_auth(message))-- def _is_source_authorized(self, source) -> bool:- """Authorization decision shared by message intake and the- ``gateway_platform_event`` observer (#64176 post-auth requirement).-- Same logic the message intake prefilter applies once a SessionSource is- resolved: adapter ``allow_from`` is the sole authority when set, then a- test-only callback override, then the runner's context-aware auth (only- when an allowlist is configured), then the env allowlist. Returns True- for an empty identity or an unconfigured allowlist so the cold path and- pairing flow still run, matching intake exactly.- """+ source = self._source_from_message_for_auth(message)user_id = source.user_id# No identity at all → genuine group service message (pin, delete,# new_chat_members, etc.). Defer to the cold path. Channel posts@@ -1207,7 +1195,7 @@ class TelegramAdapter(BasePlatformAdapter):# Test/custom injection only. The class method named# _is_callback_user_authorized is for inline button callbacks and must- # not be treated as a user-id-only shortcut for real messages; only+ # not be treated as a user-id-only shortcut for real messages — only# honor an instance-level override (set in tests).if authorized is None:callback_auth = self.__dict__.get("_is_callback_user_authorized")@@ -3753,12 +3741,10 @@ class TelegramAdapter(BasePlatformAdapter):"""Catch-all PTB handler firing ``gateway_platform_event`` per inbound update.Normalizes the update into a stable envelope (no raw SDK objects; see- #64176), authorizes the actor on the same decision as inbound gateway- traffic, then fires the observer hook. Registered in a dedicated high- group so it observes alongside, never displaces, the core handlers.- Normalization and authorization are each wrapped so a malformed update- or a missing auth context can't raise into PTB dispatch: the observer- can't break the adapter.+ #64176), then forwards it with an internal source to the gateway-owned+ post-auth boundary. Registered in a dedicated high group so it observes+ alongside, never displaces, the core handlers. Malformed updates and+ dispatch errors cannot raise into PTB's update loop."""try:event = self._normalize_platform_event(update)@@ -3767,20 +3753,21 @@ class TelegramAdapter(BasePlatformAdapter):returnif event is None:return- # Post-auth gate (#64176): the catch-all sees every inbound update, so a- # reaction from a sender the message intake would reject must not reach- # plugins. Reuse the intake's authorization decision verbatim. Fail- # closed (drop the event) if the decision itself raises.+ # The catch-all sees every inbound update. Hand the normalized envelope+ # and its internal source to the gateway-owned boundary, where the full+ # profile-scoped authorization chain runs before plugin dispatch. No+ # callback means no trusted auth boundary, so fail closed.+ handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]] = getattr(+ self, "_platform_event_handler", None+ )+ if handler is None:+ returntry:- authorized = self._is_source_authorized(- self._source_from_reaction_for_auth(update)- )+ source = self._source_from_reaction_for_auth(update)+ await handler(event, source)except Exception:- logger.debug("[%s] gateway_platform_event auth error", self.name, exc_info=True)- return- if not authorized:+ logger.debug("[%s] gateway_platform_event dispatch error", self.name, exc_info=True)return- self._fire_gateway_hook("gateway_platform_event", **event)def _normalize_platform_event(self, update) -> Optional[Dict[str, Any]]:"""Map an inbound PTB update to a normalized ``gateway_platform_event``@@ -3791,8 +3778,8 @@ class TelegramAdapter(BasePlatformAdapter):plugin consumes: ``emojis`` (standard unicode), ``custom_emoji_ids``(custom reaction emojis — PTB exposes ``custom_emoji_id`` with no``.emoji``), ``chat_id``, ``message_id``, ``thread_id``. Other update- types (forward, edit, chat-member) return ``None`` for now; their- payload contracts land with #64176's taxonomy (#64231).+ types (forward, edit, chat-member) return ``None`` unless and until+ they gain a concrete contract and current fire-site consumer."""mr = getattr(update, "message_reaction", None)if mr is None:@@ -3816,8 +3803,8 @@ class TelegramAdapter(BasePlatformAdapter):"custom_emoji_ids": custom_emoji_ids,"chat_id": str(getattr(chat, "id", "")) if chat is not None else None,"message_id": str(getattr(mr, "message_id", "")),- # Reactions don't carry thread_id; plugins route the reply via- # their own send/edit cache or the future action API (#64176).+ # Reactions don't carry thread_id; do not guess it or expose an+ # adapter object as a routing escape hatch."thread_id": None,},}@@ -3825,14 +3812,10 @@ class TelegramAdapter(BasePlatformAdapter):def _register_handlers(self, app) -> None:"""Register every PTB handler on ``app``.- Single source of truth for handler registration. ``connect`` calls this,- and any future rebuild path that re-creates the Application would call- it too, keeping the ``gateway_platform_event`` observer (group 99) in- lockstep with the core handlers. Today reconnect reuses the existing- Application, so handlers already persist; this method exists so there is- one place to add a handler and one re-registration point if a rebuild is- ever introduced. This is the #64176 review's "share registration between- initial and rebuild paths" ask.+ Single source of truth for handler registration. Both initial connect+ and the transient-initialization rebuild path call this method, keeping+ the ``gateway_platform_event`` observer (group 99) in lockstep with the+ core handlers."""app.add_handler(TelegramMessageHandler(filters.TEXT & ~filters.COMMAND,@@ -4183,24 +4166,9 @@ class TelegramAdapter(BasePlatformAdapter):old_app = self._appself._app = builder.build()self._bot = self._app.bot- # Re-register handlers on the new app- self._app.add_handler(TelegramMessageHandler(- filters.TEXT & ~filters.COMMAND,- self._handle_text_message- ))- self._app.add_handler(TelegramMessageHandler(- filters.COMMAND,- self._handle_command- ))- self._app.add_handler(TelegramMessageHandler(- filters.LOCATION | getattr(filters, "VENUE", filters.LOCATION),- self._handle_location_message- ))- self._app.add_handler(TelegramMessageHandler(- filters.PHOTO | filters.VIDEO | filters.AUDIO | filters.VOICE | filters.Document.ALL | filters.Sticker.ALL,- self._handle_media_message- ))- self._app.add_handler(CallbackQueryHandler(self._handle_callback_query))+ # Keep core and observer handlers in lockstep after a+ # transient-init rebuild (#64176).+ self._register_handlers(self._app)# Best-effort discard the old app's resourcestry:await _shutdown_abandoned_app(old_app)diff --git a/tests/gateway/test_gateway_platform_event_hook.py b/tests/gateway/test_gateway_platform_event_hook.pyindex a9d0e4338cd..1f609707553 100644--- a/tests/gateway/test_gateway_platform_event_hook.py+++ b/tests/gateway/test_gateway_platform_event_hook.py@@ -2,9 +2,9 @@Covers the normalized-envelope pattern that replaces raw-SDK handler args:* only ``gateway_platform_event`` is registered in ``VALID_HOOKS`` (no inert- hook surface pending #64231)-* ``BasePlatformAdapter._fire_gateway_hook`` routes to ``invoke_hook`` with a- ``has_hook`` no-subscriber fast-path and per-call error isolation+ hook surface without a concrete fire site)+* the adapter forwards normalized events to a runner-owned callback; the runner+ performs the authoritative post-auth check before invoking plugins* ``TelegramAdapter._normalize_platform_event`` maps an inbound PTB update to astable ``{platform, event_type, payload}`` envelope (no raw SDK objects),including custom-emoji reactions@@ -26,6 +26,8 @@ from unittest.mock import MagicMock, patchimport pytest+from gateway.config import PlatformConfig+_repo = str(Path(__file__).resolve().parents[2])if _repo not in sys.path:@@ -53,7 +55,13 @@ def _ensure_telegram_mock() -> None:_ensure_telegram_mock()from plugins.platforms.telegram.adapter import TelegramAdapter # noqa: E402-from hermes_cli.plugins import VALID_HOOKS # noqa: E402+from gateway.run import GatewayRunner # noqa: E402+from hermes_cli.plugins import ( # noqa: E402+ VALID_HOOKS,+ PluginContext,+ PluginManager,+ PluginManifest,+)def _adapter(extra=None) -> TelegramAdapter:@@ -115,7 +123,7 @@ class TestHookRegistration:def test_gateway_platform_event_registered_reserved_absent(self):"""register_hook rejects names not in VALID_HOOKS, so the implementedhook must be present. The reserved gateway_* names are deliberately- absent (no inert surface pending #64231); lock that in."""+ absent (no inert surface without a concrete fire site); lock that in."""assert "gateway_platform_event" in VALID_HOOKSassert "gateway_session_titled" not in VALID_HOOKSassert "gateway_message_delivered" not in VALID_HOOKS@@ -123,54 +131,79 @@ class TestHookRegistration:# ----------------------------------------------------------------------------# BasePlatformAdapter._fire_gateway_hook — routing + isolation+# Runner-owned dispatch — authoritative post-auth gate + isolation# ----------------------------------------------------------------------------class TestFireGatewayHook:- def test_routes_to_invoke_hook_with_kwargs(self):- a = _adapter()- captured: dict = {}+class TestRunnerDispatch:+ def test_authorized_event_routes_normalized_envelope(self):+ runner = object.__new__(GatewayRunner)+ runner._is_user_authorized = lambda source: source.user_id == "777"+ mgr = MagicMock()+ mgr.has_hook.return_value = True+ source = _adapter()._source_from_reaction_for_auth(+ _auth_reaction_update(user_id=777)+ )+ event = {+ "platform": "telegram",+ "event_type": "reaction",+ "payload": {"chat_id": "123", "message_id": "456", "emojis": ["x"]},+ }- def fake_invoke(name, **kwargs):- captured["name"] = name- captured["kwargs"] = kwargs+ with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):+ asyncio.run(runner._handle_gateway_platform_event(event, source))+ mgr.invoke_hook.assert_called_once_with("gateway_platform_event", **event)++ def test_unauthorized_event_never_reaches_hooks(self):+ runner = object.__new__(GatewayRunner)+ runner._is_user_authorized = lambda source: Falsemgr = MagicMock()- mgr.has_hook.return_value = True- mgr.invoke_hook.side_effect = fake_invoke+ source = _adapter()._source_from_reaction_for_auth(+ _auth_reaction_update(user_id=777)+ )with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):- a._fire_gateway_hook(- "gateway_platform_event",- platform="telegram", event_type="reaction", payload={"emojis": ["x"]},- )-- assert captured["name"] == "gateway_platform_event"- assert captured["kwargs"] == {- "platform": "telegram", "event_type": "reaction", "payload": {"emojis": ["x"]},- }+ asyncio.run(runner._handle_gateway_platform_event(+ {"platform": "telegram", "event_type": "reaction", "payload": {}},+ source,+ ))++ mgr.has_hook.assert_not_called()+ mgr.invoke_hook.assert_not_called()def test_skips_dispatch_when_no_subscriber(self):- """has_hook False -> invoke_hook never called."""- a = _adapter()+ runner = object.__new__(GatewayRunner)+ runner._is_user_authorized = lambda source: Truemgr = MagicMock()mgr.has_hook.return_value = False+ source = _adapter()._source_from_reaction_for_auth(+ _auth_reaction_update(user_id=777)+ )with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):- a._fire_gateway_hook("gateway_platform_event", platform="telegram")+ asyncio.run(runner._handle_gateway_platform_event(+ {"platform": "telegram", "event_type": "reaction", "payload": {}},+ source,+ ))mgr.has_hook.assert_called_once_with("gateway_platform_event")mgr.invoke_hook.assert_not_called()def test_plugin_layer_error_is_isolated(self):- """A raising invoke_hook OR get_plugin_manager must not propagate."""- a = _adapter()+ runner = object.__new__(GatewayRunner)+ runner._is_user_authorized = lambda source: Truemgr = MagicMock()mgr.has_hook.return_value = Truemgr.invoke_hook.side_effect = RuntimeError("plugin boom")+ source = _adapter()._source_from_reaction_for_auth(+ _auth_reaction_update(user_id=777)+ )with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):- a._fire_gateway_hook("gateway_platform_event", platform="telegram") # no raise+ asyncio.run(runner._handle_gateway_platform_event(+ {"platform": "telegram", "event_type": "reaction", "payload": {}},+ source,+ )) # no raise# ---------------------------------------------------------------------------@@ -220,7 +253,7 @@ class TestNormalizePlatformEvent:assert event["payload"]["custom_emoji_ids"] == ["555"]def test_non_reaction_update_returns_none(self):- """Unsupported update types return None (payload contracts pending #64231)."""+ """Unsupported update types return None until a concrete contract exists."""a = _adapter()update = MagicMock()update.message_reaction = None # e.g. an edited_message or chat_member update@@ -236,24 +269,28 @@ class TestOnPlatformUpdate:def test_fires_gateway_platform_event_with_envelope(self):a = _adapter()seen: list = []- a._fire_gateway_hook = lambda name, **kw: seen.append((name, kw)) # type: ignore[assignment]+ async def observe(event, source):+ seen.append((event, source))+ a.set_platform_event_handler(observe)asyncio.run(a._on_platform_update(_reaction_update([_reaction(emoji="\U0001F44E")], 123, 456), context=MagicMock(),))assert len(seen) == 1- name, kwargs = seen[0]- assert name == "gateway_platform_event"- assert kwargs["platform"] == "telegram"- assert kwargs["event_type"] == "reaction"- assert kwargs["payload"]["emojis"] == ["\U0001F44E"]- assert kwargs["payload"]["chat_id"] == "123"+ event, source = seen[0]+ assert event["platform"] == "telegram"+ assert event["event_type"] == "reaction"+ assert event["payload"]["emojis"] == ["\U0001F44E"]+ assert event["payload"]["chat_id"] == "123"+ assert source.chat_id == "123"def test_unsupported_update_does_not_fire(self):a = _adapter()seen: list = []- a._fire_gateway_hook = lambda name, **kw: seen.append((name, kw)) # type: ignore[assignment]+ async def observe(event, source):+ seen.append((event, source))+ a.set_platform_event_handler(observe)update = MagicMock()update.message_reaction = None@@ -265,7 +302,9 @@ class TestOnPlatformUpdate:"""A malformed update that makes normalize raise must be swallowed — theobserver can't break the adapter (regression guard for the try/except)."""a = _adapter()- a._fire_gateway_hook = lambda *a_, **kw: pytest.fail("must not fire on normalize error") # type: ignore[assignment]+ async def observe(event, source):+ pytest.fail("must not fire on normalize error")+ a.set_platform_event_handler(observe)def boom(update):raise RuntimeError("malformed update")@@ -278,53 +317,20 @@ class TestOnPlatformUpdate:# TelegramAdapter._on_platform_update post-auth gate (#64176)# ----------------------------------------------------------------------------class TestOnPlatformUpdateAuthGate:- """The catch-all sees every inbound update. A reaction from a sender the- message intake would reject must NOT reach plugins, using the same- authorization decision as inbound gateway traffic."""-- def test_unauthorized_reaction_does_not_fire(self):- a = _adapter(extra={"allow_from": ["999"]}) # reactor 777 not allowed+class TestOnPlatformUpdateAuthBoundary:+ def test_without_runner_callback_fails_closed(self):+ """A catch-all PTB handler must not expose pre-auth updates merely because+ adapter-local intake would defer an unknown DM to the pairing flow."""+ a = _adapter(extra={})seen: list = []- a._fire_gateway_hook = lambda name, **kw: seen.append((name, kw)) # type: ignore[assignment]-+ # No set_platform_event_handler: the authoritative gateway boundary has+ # not been installed, so even a syntactically valid reaction is dropped.asyncio.run(a._on_platform_update(_auth_reaction_update(user_id=777), context=MagicMock(),))assert seen == []- def test_authorized_reaction_fires(self):- a = _adapter(extra={"allow_from": ["777"]}) # reactor 777 allowed- seen: list = []- a._fire_gateway_hook = lambda name, **kw: seen.append((name, kw)) # type: ignore[assignment]-- asyncio.run(a._on_platform_update(- _auth_reaction_update(user_id=777), context=MagicMock(),- ))-- assert len(seen) == 1- assert seen[0][0] == "gateway_platform_event"-- def test_open_config_defers_to_pairing_flow(self):- """With no allow_from and no env allowlist, intake defers (open) and the- event fires, matching the message intake pairing flow."""- a = _adapter(extra={})- seen: list = []- a._fire_gateway_hook = lambda name, **kw: seen.append((name, kw)) # type: ignore[assignment]- cleared = {k: "" for k in (- "TELEGRAM_ALLOWED_USERS", "TELEGRAM_GROUP_ALLOWED_USERS",- "TELEGRAM_ALLOW_ALL_USERS", "GATEWAY_ALLOWED_USERS",- "GATEWAY_ALLOW_ALL_USERS",- )}-- with patch.dict("os.environ", cleared, clear=False):- asyncio.run(a._on_platform_update(- _auth_reaction_update(user_id=777), context=MagicMock(),- ))-- assert len(seen) == 1-def test_non_reaction_update_fails_closed(self):"""A future event type whose update carries no message_reaction mustNOT fire. _source_from_reaction_for_auth raises and the gate drops it@@ -332,7 +338,9 @@ class TestOnPlatformUpdateAuthGate:and fire it despite the restrictive allow_from."""a = _adapter(extra={"allow_from": ["999"]})seen: list = []- a._fire_gateway_hook = lambda name, **kw: seen.append((name, kw)) # type: ignore[assignment]+ async def observe(event, source):+ seen.append((event, source))+ a.set_platform_event_handler(observe)update = MagicMock()update.message_reaction = None # a future, not-yet-wired event type@@ -345,6 +353,86 @@ class TestOnPlatformUpdateAuthGate:assert seen == [] # fail closed: never fires without a real auth decision+ @pytest.mark.parametrize("missing", ["actor", "chat", "message_id"])+ def test_malformed_reaction_identity_fails_closed(self, missing):+ a = _adapter()+ seen = []++ async def observe(event, source):+ seen.append((event, source))++ a.set_platform_event_handler(observe)+ update = _auth_reaction_update(user_id=777)+ if missing == "actor":+ update.message_reaction.user = None+ update.message_reaction.actor_chat = None+ elif missing == "chat":+ update.message_reaction.chat = None+ else:+ update.message_reaction.message_id = None++ asyncio.run(a._on_platform_update(update, context=MagicMock()))++ assert seen == []+++class TestProfileScopedPlatformEventHandler:+ def test_secondary_handler_stamps_profile_before_dispatch(self, monkeypatch):+ runner = object.__new__(GatewayRunner)+ captured = {}++ async def dispatch(event, source):+ captured["event"] = event+ captured["profile"] = source.profile++ runner._handle_gateway_platform_event = dispatch+ monkeypatch.setattr(+ "hermes_cli.profiles.get_profile_dir", lambda name: None,+ )+ handler = runner._make_profile_platform_event_handler("work")+ source = _adapter()._source_from_reaction_for_auth(+ _auth_reaction_update(user_id=777)+ )++ asyncio.run(handler({"platform": "telegram", "event_type": "reaction", "payload": {}}, source))++ assert captured["profile"] == "work"+++class TestFixturePluginObservationPath:+ def test_reaction_reaches_real_registered_plugin_callback(self):+ """Adapter -> normalized source/envelope -> runner auth -> real plugin bus."""+ manager = PluginManager()+ context = PluginContext(+ PluginManifest(name="reaction-fixture", source="user"), manager,+ )+ seen = []+ context.register_hook(+ "gateway_platform_event", lambda **event: seen.append(event),+ )++ runner = object.__new__(GatewayRunner)+ runner._is_user_authorized = lambda source: source.user_id == "777"+ adapter = _adapter()+ adapter.set_platform_event_handler(runner._handle_gateway_platform_event)++ with patch("hermes_cli.plugins.get_plugin_manager", return_value=manager):+ asyncio.run(adapter._on_platform_update(+ _auth_reaction_update(user_id=777), context=MagicMock(),+ ))++ assert seen == [{+ "platform": "telegram",+ "event_type": "reaction",+ "payload": {+ "emojis": ["\U0001F44D"],+ "custom_emoji_ids": [],+ "chat_id": "123",+ "message_id": "456",+ "thread_id": None,+ },+ }]+# ---------------------------------------------------------------------------# TelegramAdapter._register_handlers single registration site (#64176)@@ -399,3 +487,49 @@ class TestRegisterHandlers:assert rebuilt_app.add_handler.call_count == 6assert len(self._observer_calls(rebuilt_app)) == 1++ def test_transient_init_rebuild_uses_shared_registration(self, monkeypatch):+ """The real connect retry path must call the shared registration method+ for the rebuilt PTB Application, not duplicate only the core handlers."""+ a = TelegramAdapter(PlatformConfig(enabled=True, token="test-token"))+ first_app = MagicMock()+ first_app.bot = MagicMock()+ first_app.initialize = MagicMock(side_effect=OSError("transient"))+ rebuilt_app = MagicMock()+ rebuilt_app.bot = MagicMock()+ rebuilt_app.initialize = MagicMock(side_effect=RuntimeError("stop after rebuild"))++ builder = MagicMock()+ builder.token.return_value = builder+ builder.request.return_value = builder+ builder.get_updates_request.return_value = builder+ builder.build.side_effect = [first_app, rebuilt_app]+ monkeypatch.setattr(+ "plugins.platforms.telegram.adapter.Application",+ SimpleNamespace(builder=MagicMock(return_value=builder)),+ )+ monkeypatch.setattr(+ "plugins.platforms.telegram.adapter.HTTPXRequest", lambda **kwargs: MagicMock(),+ )+ monkeypatch.setattr(+ "plugins.platforms.telegram.adapter.discover_fallback_ips",+ lambda: _async_value([]),+ )+ monkeypatch.setattr("asyncio.sleep", MagicMock(return_value=_async_value(None)))+ monkeypatch.setattr(+ "gateway.status.acquire_scoped_lock",+ lambda scope, identity, metadata=None: (True, None),+ )+ a._register_handlers = MagicMock()++ result = asyncio.run(a.connect())++ assert result is False+ assert a._register_handlers.call_args_list == [+ ((first_app,), {}),+ ((rebuilt_app,), {}),+ ]+++async def _async_value(value):+ return valuediff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.pyindex 8cf090fb6ce..bcb2c29dfa0 100644--- a/tests/gateway/test_multiplex_adapter_registry.py+++ b/tests/gateway/test_multiplex_adapter_registry.py@@ -127,6 +127,9 @@ class _SecondaryRecoveryAdapter:def set_authorization_check(self, handler):self.authorization_check = handler+ def set_platform_event_handler(self, handler):+ self.platform_event_handler = handler+def _secondary_recovery_runner(*, running=True):runner = GatewayRunner.__new__(GatewayRunner)diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex 5715b9e71d4..b86eeece4c7 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -816,6 +816,7 @@ Each hook is documented in full on the **[Event Hooks reference](/user-guide/fea| [`on_session_end`](/user-guide/features/hooks#on_session_end) | End of every `run_conversation` call + CLI exit | `session_id: str, completed: bool, interrupted: bool, model: str, platform: str` | ignored || [`on_session_finalize`](/user-guide/features/hooks#on_session_finalize) | CLI/gateway tears down an active session | `session_id: str \| None, platform: str` | ignored || [`on_session_reset`](/user-guide/features/hooks#on_session_reset) | Gateway swaps in a new session key (`/new`, `/reset`) | `session_id: str, platform: str` | ignored |+| [`gateway_platform_event`](/user-guide/features/hooks#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 || `kanban_task_blocked` | A kanban task is blocked (worker process) | `task_id, board, assignee, run_id, profile_name, reason: str \| None` | ignored |diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 6ea344db6ce..9da9ebbebca 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -456,6 +456,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. |+| `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 currently); return ignored. | `platform`, `event_type`, `payload` (reactions: `emojis`, `custom_emoji_ids`, `chat_id`, `message_id`, `thread_id`) | Normalized plain-dict envelope only; raw SDK objects, adapter handles, and bot clients are never exposed. || `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. || `post_approval_response` | Observer | After a decision, timeout, or gateway notification failure; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id`, `choice`; smart path may add `decided_by` | Same command sensitivity plus decision metadata. || `kanban_task_claimed` | Observer | After claim commit, in dispatcher process before worker spawn; return ignored. | `task_id`, `profile_name`, `board`, `assignee`, `run_id` | Board/task/profile/assignee identifiers. |@@ -1130,6 +1131,33 @@ def register(ctx):---+### `gateway_platform_event`++Fires for supported platform-native events only **after** the gateway's normal, profile-scoped authorization check succeeds. The callback receives plain dictionaries; raw SDK objects, adapter handles, bot clients, and callback contexts are never part of this stable contract.++Telegram message reactions are the first supported event:++```python+def on_platform_event(platform, event_type, payload, **kwargs):+ if platform == "telegram" and event_type == "reaction":+ print(payload["chat_id"], payload["message_id"], payload["emojis"])++def register(ctx):+ ctx.register_hook("gateway_platform_event", on_platform_event)+```++| Parameter | Type | Description |+|-----------|------|-------------|+| `platform` | `str` | Stable platform id (`"telegram"`). |+| `event_type` | `str` | Event-local contract id (`"reaction"`). |+| `payload` | `dict` | For reactions: `emojis: list[str]`, `custom_emoji_ids: list[str]`, `chat_id: str \| None`, `message_id: str`, and `thread_id: str \| None`. |++The reaction payload is additive and event-specific; there is no monolithic gateway payload version. Telegram reaction updates do not carry a topic id, so `thread_id` is currently `None` rather than guessed. Malformed events and events whose source cannot be authorized are dropped. A transient Telegram Application rebuild re-registers the observer together with the core handlers.++This hook is observer-only. It does **not** add raw-event access, adapter access, cross-chat actions, or a platform-action facade. `PluginContext.dispatch_tool()` can only call tools registered in the tool registry; `send_message` is intentionally not registered there (its transport is reserved for explicit CLI, cron, kanban, and MCP delivery paths). Consequently a hook callback cannot currently call `ctx.dispatch_tool("send_message", ...)` for a media fallback. A future outbound-delivery contract must first provide stable delivered content/handles across all adapters; this slice does not pre-register an inert `gateway_message_delivered` hook.++---+### `pre_approval_request`Fires before an approval decision is requested. It covers prompted surfaces—interactive CLI, Ink TUI, gateway platforms, and ACP clients—and `approvals.mode=smart` decisions made without a human prompt (`surface="smart"`). In smart mode, the hook runs before the auxiliary LLM is called.