The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): plugin event names take a dotted hierarchy; ids are catalog names
teknium15fa140281905
diff --git a/hermes_cli/plugin_events.py b/hermes_cli/plugin_events.pyindex 1fc593ed072..43ee2e1e059 100644--- a/hermes_cli/plugin_events.py+++ b/hermes_cli/plugin_events.py@@ -1,4 +1,4 @@-"""Public event bridge for plugin backends (``plugin_api.py``).+"""Public event bridge for plugin backends (``plugin_api.py``, slash commands).A plugin's backend runs inside the gateway process. To push an update to itsOWN desktop half it emits on the app's global event stream — the same stream@@ -6,17 +6,22 @@ OWN desktop half it emits on the app's global event stream — the same streamfrom hermes_cli.plugin_events import broadcast_plugin_event- broadcast_plugin_event("rss-reader", "items", {"count": 3})- # event "plugin.rss-reader.items" reaches every connected desktop client+ broadcast_plugin_event("rss-reader", "feed.updated", {"count": 3})+ # event "plugin.rss-reader.feed.updated" reaches every connected desktop clientThe desktop half filters for its own name::- host.onEvent('plugin.rss-reader.items', payload => …)+ host.onEvent('plugin.rss-reader.feed.updated', ({ payload }) => …)This module is the sanctioned door for that: plugin backends must never import``tui_gateway.server`` privates (``_broadcast_global_event``), whose signatureis core-internal. The ``plugin.`` prefix keeps plugin traffic out of core's ownevent names (``skin.changed``, ``session.reclaimed``, …).++Delivery is per process: the frame goes to the clients of the gateway the+caller runs in. Under ``hermes serve`` (the Desktop backend, where plugin+routers and slash commands both run) that is every connected window; in a+process with no connected client the call is a logged no-op."""from __future__ import annotations@@ -27,10 +32,13 @@ from typing import Any, Optional#: Every plugin event name starts with this — core owns all other names.PLUGIN_EVENT_PREFIX = "plugin."-# Plugin ids are the manifest names (lowercase, dashes): ``rss-reader``.-_PLUGIN_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")-# One event segment: no whitespace, no dots (the dot is the name separator).-_EVENT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")+# Plugin ids are the catalog names (``plugin_catalog._NAME_RE``): lowercase, digits, ``_``/``-``.+# No dot: ``plugin.<id>.`` must be an unambiguous prefix, so an id can never spell a neighbour's+# namespace (``other.x`` would read as plugin ``other``).+_PLUGIN_ID_RE = re.compile(r"^[a-z0-9_-]{1,64}$")+# Dotted hierarchy like core's own names (``display.install.done``): non-empty segments of+# [A-Za-z0-9_-], so ``../x``, ``a..b``, a leading/trailing dot, slashes and whitespace are refused.+_EVENT_RE = re.compile(r"^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$")def plugin_event_name(plugin_id: str, event: str) -> str:@@ -40,10 +48,10 @@ def plugin_event_name(plugin_id: str, event: str) -> str:mangled name would strand the desktop half waiting on a name nobody emits."""if not isinstance(plugin_id, str) or not _PLUGIN_ID_RE.match(plugin_id):- raise ValueError(f"invalid plugin id {plugin_id!r}: expected [a-z0-9][a-z0-9._-]{{0,63}}")- if not isinstance(event, str) or not _EVENT_RE.match(event):+ raise ValueError(f"invalid plugin id {plugin_id!r}: expected [a-z0-9_-]{{1,64}}")+ if not isinstance(event, str) or len(event) > 128 or not _EVENT_RE.match(event):raise ValueError(- f"invalid plugin event {event!r}: expected one segment of [A-Za-z0-9_-] "+ f"invalid plugin event {event!r}: expected dot-separated segments of [A-Za-z0-9_-] ""(the plugin id already namespaces the name)")return f"{PLUGIN_EVENT_PREFIX}{plugin_id}.{event}"@@ -58,10 +66,11 @@ def broadcast_plugin_event(plugin_id: str, event: str, payload: Optional[dict[st"""if payload is not None and not isinstance(payload, dict):raise TypeError(f"plugin event payload must be a dict or None, got {type(payload).__name__}")+ name = plugin_event_name(plugin_id, event)# Late import: plugin backends load before the gateway server is up in some# hosts (CLI tooling imports plugin_api modules for route inspection), and# tui_gateway.server pulls in the transport stack.from tui_gateway.server import _broadcast_global_event- _broadcast_global_event(plugin_event_name(plugin_id, event), dict(payload or {}))+ _broadcast_global_event(name, dict(payload or {}))diff --git a/tests/hermes_cli/test_plugin_events.py b/tests/hermes_cli/test_plugin_events.pyindex 68e803114a9..a2d922a0f97 100644--- a/tests/hermes_cli/test_plugin_events.py+++ b/tests/hermes_cli/test_plugin_events.py@@ -1,7 +1,7 @@-"""Public event bridge for plugin backends (``plugin_api.py``).+"""Public event bridge for plugin backends (#116305 item 8, salvage of #116419).-Regression for #116305 item 8: a plugin backend pushes events to its own-desktop half through ``hermes_cli.plugin_events`` instead of importing+A plugin backend pushes events to its own desktop half through+``hermes_cli.plugin_events`` instead of importing``tui_gateway.server._broadcast_global_event``."""from __future__ import annotations@@ -11,51 +11,57 @@ import pytestfrom hermes_cli import plugin_events-def test_event_name_namespaces_under_the_plugin():- assert plugin_events.plugin_event_name("rss-reader", "items") == "plugin.rss-reader.items"+class _Peer:+ """A connected client as the gateway sees it (``tui_gateway.transport.Transport``)."""+ def __init__(self):+ self.frames: list[dict] = []-def test_broadcast_reaches_the_global_stream_with_the_namespaced_name(monkeypatch):- seen: list[tuple[str, object]] = []+ def write(self, obj: dict) -> bool:+ self.frames.append(obj)+ return True- import tui_gateway.server as server-- monkeypatch.setattr(server, "_broadcast_global_event", lambda event, payload=None: seen.append((event, payload)))-- plugin_events.broadcast_plugin_event("rss-reader", "items", {"count": 3})-- assert seen == [("plugin.rss-reader.items", {"count": 3})]+ def close(self) -> None:+ pass-def test_broadcast_defaults_the_payload_to_an_empty_dict(monkeypatch):- seen: list[tuple[str, object]] = []-+def test_broadcast_reaches_a_registered_client_as_a_namespaced_global_event():import tui_gateway.server as server- monkeypatch.setattr(server, "_broadcast_global_event", lambda event, payload=None: seen.append((event, payload)))-- plugin_events.broadcast_plugin_event("kanban", "changed")+ peer = _Peer()+ server.register_live_transport(peer)+ try:+ plugin_events.broadcast_plugin_event("rss-reader", "feed.updated", {"count": 3})+ plugin_events.broadcast_plugin_event("kanban", "changed")+ finally:+ server.unregister_live_transport(peer)- assert seen == [("plugin.kanban.changed", {})]+ assert peer.frames == [+ {"jsonrpc": "2.0", "method": "event",+ "params": {"type": "plugin.rss-reader.feed.updated", "session_id": "", "payload": {"count": 3}}},+ {"jsonrpc": "2.0", "method": "event",+ "params": {"type": "plugin.kanban.changed", "session_id": "", "payload": {}}},+ ]@pytest.mark.parametrize(- ("plugin_id", "event"),+ ("plugin_id", "event", "payload", "exc"),[- ("", "items"),- ("Bad Id", "items"),- ("has/slash", "items"),- ("ok", ""),- ("ok", "bad name"),- ("ok", "with.dot"),- ("ok", "plugin.other.items"),+ ("", "items", None, ValueError),+ ("Bad Id", "items", None, ValueError),+ ("has/slash", "items", None, ValueError),+ ("other.x", "items", None, ValueError), # a dotted id would spell plugin ``other``'s namespace+ ("ok", "", None, ValueError),+ ("ok", "bad name", None, ValueError),+ ("ok", "../x", None, ValueError),+ ("ok", ".leading", None, ValueError),+ ("ok", "a..b", None, ValueError),+ ("ok", "items", ["not", "a", "dict"], TypeError),],)-def test_invalid_names_raise(plugin_id, event):- with pytest.raises(ValueError):- plugin_events.plugin_event_name(plugin_id, event)-+def test_names_that_cannot_form_a_namespaced_event_are_refused_before_emit(monkeypatch, plugin_id, event, payload, exc):+ import tui_gateway.server as server-def test_payload_must_be_a_dict():- with pytest.raises(TypeError):- plugin_events.broadcast_plugin_event("ok", "items", ["not", "a", "dict"]) # type: ignore[arg-type]+ monkeypatch.setattr(server, "_broadcast_global_event", lambda *_a, **_k: pytest.fail("must not emit"))+ with pytest.raises(exc):+ plugin_events.broadcast_plugin_event(plugin_id, event, payload) # type: ignore[arg-type]