run_inbound_consumer.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """``post_gateway_admission``: let a plugin consume an admitted inbound message (#129958).
  2. ``GatewayInboundMixin._handle_message`` fires it once per non-internal message that survived
  3. authorization, bot admission, pause/drain, pending-reply intercepts, the running-session lane and
  4. idle slash-command dispatch, inside the claimed session slot. It runs under the message's ROUTED
  5. profile scope: the receiving bot's handler binds the transport home (auth reads its ``.env``), which
  6. differs from the runtime home when that bot serves a chat for another profile.
  7. Fail-open: a callback that raises, times out or returns anything other than
  8. ``{"action": "handled"}`` is logged/ignored and the message proceeds to the agent, so one buggy
  9. plugin can never blackhole a profile's traffic. The payload is a plain snapshot, never live
  10. runner/session-store handles.
  11. """
  12. from __future__ import annotations
  13. import asyncio
  14. import contextlib
  15. import logging
  16. from typing import Any, Optional, Tuple
  17. logger = logging.getLogger(__name__)
  18. POST_ADMISSION_HOOK = "post_gateway_admission"
  19. def _routed_scope(runner: Any, source: Any):
  20. if not getattr(getattr(runner, "config", None), "multiplex_profiles", False):
  21. return contextlib.nullcontext()
  22. from gateway.run import _async_profile_runtime_scope
  23. return _async_profile_runtime_scope(runner._resolve_profile_home_for_source(source))
  24. async def run_post_admission_hook(
  25. runner: Any, event: Any, source: Any, session_key: str
  26. ) -> tuple[bool, Optional[str]]:
  27. """Return ``(handled, reply)``; ``handled=False`` means run the ordinary agent turn."""
  28. try:
  29. async with _routed_scope(runner, source):
  30. from hermes_cli.lifecycle import ainvoke_hook, has_hook
  31. if not has_hook(POST_ADMISSION_HOOK):
  32. return False, None
  33. results = await ainvoke_hook(
  34. POST_ADMISSION_HOOK, session_key=session_key,
  35. platform=source.platform.value if source.platform else "",
  36. source=source.to_dict(), message_id=event.message_id, text=event.text or "",
  37. )
  38. except asyncio.CancelledError:
  39. raise
  40. except Exception:
  41. logger.warning("%s failed; continuing with the agent turn", POST_ADMISSION_HOOK, exc_info=True)
  42. return False, None
  43. for result in results:
  44. if isinstance(result, dict) and result.get("action") == "handled":
  45. reply = result.get("reply")
  46. logger.info("%s: a plugin handled the message for session %s", POST_ADMISSION_HOOK, session_key)
  47. return True, reply if isinstance(reply, str) and reply.strip() else None
  48. return False, None