plugin_events.py 4.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Public event bridge for plugin backends (``plugin_api.py``, slash commands).
  2. A plugin's backend runs inside the gateway process. To push an update to its
  3. OWN desktop half it emits on the app's global event stream — the same stream
  4. ``host.onEvent`` subscribes to in the renderer::
  5. from hermes_cli.plugin_events import broadcast_plugin_event
  6. broadcast_plugin_event("rss-reader", "feed.updated", {"count": 3})
  7. # event "plugin.rss-reader.feed.updated" reaches every connected desktop client
  8. The desktop half filters for its own name::
  9. host.onEvent('plugin.rss-reader.feed.updated', ({ payload }) => …)
  10. This module is the sanctioned door for that: plugin backends must never import
  11. ``tui_gateway.server`` privates (``_broadcast_global_event``), whose signature
  12. is core-internal. The ``plugin.`` prefix keeps plugin traffic out of core's own
  13. event names (``skin.changed``, ``session.reclaimed``, …).
  14. Delivery is per process: the frame goes to the clients of the gateway the
  15. caller runs in. Under ``hermes serve`` (the Desktop backend, where plugin
  16. routers, slash commands and the agent turn's tools/hooks run) that is every
  17. connected window; a call from the ``dashboard.turn_isolation`` compute-host
  18. child rides the host pipe to ``hermes serve`` and fans out there. A process
  19. with no Desktop client at all (``hermes gateway run``, ``hermes chat``, cron)
  20. has nobody to deliver to: the call is a logged no-op.
  21. """
  22. from __future__ import annotations
  23. import logging
  24. import re
  25. from typing import Any, Optional
  26. logger = logging.getLogger(__name__)
  27. #: Every plugin event name starts with this — core owns all other names.
  28. PLUGIN_EVENT_PREFIX = "plugin."
  29. # Plugin ids are the catalog names (``plugin_catalog._NAME_RE``): lowercase, digits, ``_``/``-``.
  30. # No dot: ``plugin.<id>.`` must be an unambiguous prefix, so an id can never spell a neighbour's
  31. # namespace (``other.x`` would read as plugin ``other``).
  32. _PLUGIN_ID_RE = re.compile(r"^[a-z0-9_-]{1,64}$")
  33. # Dotted hierarchy like core's own names (``display.install.done``): non-empty segments of
  34. # [A-Za-z0-9_-], so ``../x``, ``a..b``, a leading/trailing dot, slashes and whitespace are refused.
  35. _EVENT_RE = re.compile(r"^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$")
  36. def plugin_event_name(plugin_id: str, event: str) -> str:
  37. """The wire name for one plugin event: ``plugin.<plugin_id>.<event>``.
  38. Raises ``ValueError`` for an id or event that cannot form one — a silently
  39. mangled name would strand the desktop half waiting on a name nobody emits.
  40. """
  41. if not isinstance(plugin_id, str) or not _PLUGIN_ID_RE.match(plugin_id):
  42. raise ValueError(f"invalid plugin id {plugin_id!r}: expected [a-z0-9_-]{{1,64}}")
  43. if not isinstance(event, str) or len(event) > 128 or not _EVENT_RE.match(event):
  44. raise ValueError(
  45. f"invalid plugin event {event!r}: expected dot-separated segments of [A-Za-z0-9_-] "
  46. "(the plugin id already namespaces the name)"
  47. )
  48. return f"{PLUGIN_EVENT_PREFIX}{plugin_id}.{event}"
  49. def broadcast_plugin_event(plugin_id: str, event: str, payload: Optional[dict[str, Any]] = None) -> None:
  50. """Emit ``plugin.<plugin_id>.<event>`` to every connected client.
  51. Fire-and-forget and safe to call from any request handler: delivery fans out
  52. over the gateway's live transports, and a wedged peer is skipped rather than
  53. stalling the caller. ``payload`` must be a dict (or ``None`` for ``{}``).
  54. """
  55. if payload is not None and not isinstance(payload, dict):
  56. raise TypeError(f"plugin event payload must be a dict or None, got {type(payload).__name__}")
  57. name = plugin_event_name(plugin_id, event)
  58. # Late import: plugin backends load before the gateway server is up in some
  59. # hosts (CLI tooling imports plugin_api modules for route inspection), and
  60. # tui_gateway.server pulls in the transport stack.
  61. try:
  62. from tui_gateway.server import _broadcast_global_event
  63. except ImportError:
  64. # A plugin-only process (``hermes plugins validate`` importing the backend, a trimmed
  65. # install) has no gateway at all: nobody to deliver to, and the handler must not die for it.
  66. logger.warning("plugin event %s dropped: no tui_gateway in this process", name, exc_info=True)
  67. return
  68. _broadcast_global_event(name, dict(payload or {}))