The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): inter-plugin event bus with declared emits/listens
hans17030939db86
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 393354f8ea9..954117cc8fd 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -283,6 +283,14 @@ def format_system_prompt_sections(sections: list) -> str:return ""blocks = [format_system_prompt_section(item.id, item.content) for item in sections]return f"{PLUGIN_SECTIONS_START}\n" + "\n\n".join(blocks) + f"\n{PLUGIN_SECTIONS_END}"+# Reserved event namespace prefix — only core may publish ``hermes:<event>``.+HERMES_EVENT_NAMESPACE = "hermes"++# Max inter-plugin event dispatch recursion depth. A subscriber may itself+# call ``ctx.emit``; this bound stops mutually-emitting plugins from looping+# forever. When exceeded the over-deep emit is dropped (with a warning), not+# raised, so delivery always terminates cleanly.+_EVENT_EMIT_DEPTH_CAP = 8_NS_PARENT = "hermes_plugins"@@ -713,6 +721,14 @@ class PluginManifest:license: str = ""homepage: str = ""tags: List[str] = field(default_factory=list)+ # Inter-plugin event bus declarations (advisory in v1 — NOT enforced).+ # ``emits`` lists the bare event names this plugin publishes under its own+ # ``<key>:`` namespace (e.g. ``["ping"]`` → publishes ``<key>:ping``).+ # ``listens`` lists the fully-qualified ``<plugin>:<event>`` names this+ # plugin subscribes to. Both are purely for discoverability+ # (``hermes plugins show``); a plugin may emit/subscribe without declaring.+ emits: List[str] = field(default_factory=list)+ listens: List[str] = field(default_factory=list)@dataclass(frozen=True)@@ -2143,6 +2159,74 @@ class PluginContext:plugin=plugin_id,)+ # -- inter-plugin event bus --------------------------------------------++ def emit(self, event: str, payload: Optional[dict] = None) -> int:+ """Publish *event* to all subscribers; return the number invoked.++ The event is delivered as ``<plugin_key>:<event>`` where+ ``plugin_key`` is FORCED to this plugin's own registry key+ (``manifest.key or manifest.name``). Pass only the bare event name —+ a plugin may only publish under its own namespace.++ Passing an already-namespaced name (anything containing ``':'``,+ including ``hermes:x`` or a foreign ``other:x``) is rejected with a+ ``ValueError`` and a logged warning — fail-closed. The ``hermes:``+ prefix is reserved for core.++ Subscribers are invoked in registration order, each isolated in its+ own ``try/except`` (one raising subscriber does not stop delivery to+ the others). ``payload`` is passed to each callback as keyword+ arguments (``cb(**payload)``), mirroring the hook convention.++ Returns the count of subscriber callbacks invoked (0 when there are+ no subscribers, or when the recursion cap dropped the emit).+ """+ plugin_key = self.manifest.key or self.manifest.name+ if not event or not isinstance(event, str):+ logger.warning(+ "Plugin '%s' tried to emit an invalid event name %r",+ plugin_key, event,+ )+ raise ValueError(+ f"Plugin '{plugin_key}' emit() requires a non-empty event name"+ )+ if ":" in event:+ logger.warning(+ "Plugin '%s' tried to emit namespaced/reserved event '%s' — "+ "a plugin may only emit bare event names under its own '%s:' "+ "namespace (the '%s:' prefix is reserved for core, and foreign "+ "namespaces are forbidden)",+ plugin_key, event, plugin_key, HERMES_EVENT_NAMESPACE,+ )+ raise ValueError(+ f"Plugin '{plugin_key}' may not emit '{event}': emit only the "+ f"bare event name; the namespace is forced to '{plugin_key}:' "+ f"and the '{HERMES_EVENT_NAMESPACE}:' prefix is reserved for core"+ )+ full_event = f"{plugin_key}:{event}"+ return self._manager._dispatch_event(full_event, payload or {})++ def subscribe(self, event: str, callback: Callable) -> None:+ """Subscribe *callback* to a fully-qualified event name.++ *event* is the full ``<plugin_key>:<event>`` name (or ``hermes:<event>``+ if core ever emits). Subscribing is unrestricted — any plugin may+ listen to any published event; only *emitting* is namespace-gated.++ Callbacks are stored in registration order and invoked with the+ emitter's payload as keyword arguments.+ """+ if not event or not isinstance(event, str):+ raise ValueError(+ f"Plugin '{self.manifest.name}' subscribe() requires a "+ f"non-empty event name"+ )+ self._manager._subscriptions.setdefault(event, []).append(callback)+ logger.debug(+ "Plugin %s subscribed to event: %s", self.manifest.name, event,+ )+# -- middleware registration -------------------------------------------def register_middleware(self, kind: str, callback: Callable) -> None:@@ -2245,6 +2329,13 @@ class PluginManager:self._aux_tasks: Dict[str, Dict[str, Any]] = {}# Explicitly-selected, profile-scoped human approval transports.self._approval_transports: Dict[str, Any] = {}+ # Inter-plugin event bus: full event name (``<plugin_key>:<event>`` or+ # ``hermes:<event>``) → list of subscriber callbacks in registration+ # order. See PluginContext.subscribe/emit and _dispatch_event.+ self._subscriptions: Dict[str, List[Callable]] = {}+ # Per-thread re-entrancy depth for event dispatch, used to cap+ # mutually-emitting plugins (see _EVENT_EMIT_DEPTH_CAP).+ self._emit_depth = threading.local()# Slack Block Kit action handlers registered by plugins. Each entry# is (matcher, callback, plugin_name); the Slack adapter wires them# into its slack_bolt App at connect() time. ``matcher`` is whatever@@ -2317,6 +2408,7 @@ class PluginManager:self._portable_mcp_servers.clear()self._aux_tasks.clear()self._approval_transports.clear()+ self._subscriptions.clear()self._slack_action_handlers.clear()self._context_engine = None# Set the flag up front as a re-entrancy guard (a plugin's register()@@ -2875,6 +2967,8 @@ class PluginManager:data.get("capabilities"), name),**v2_fields,+ emits=data.get("emits") or [],+ listens=data.get("listens") or [],)except Exception as exc:logger.warning(@@ -3316,6 +3410,48 @@ class PluginManager:)return results+ def _dispatch_event(self, event: str, payload: Dict[str, Any]) -> int:+ """Deliver *event* to its subscribers; return the number invoked.++ Mirrors :meth:`invoke_hook`: iterate subscribers in registration+ order, isolate each in its own ``try/except`` so one raising+ subscriber cannot break delivery to the rest, and pass the payload+ as keyword arguments.++ A subscriber may itself call ``ctx.emit`` (re-entrant dispatch). A+ per-thread depth counter caps recursion at+ :data:`_EVENT_EMIT_DEPTH_CAP`; over-deep emits are dropped with a+ single warning (never raised) so delivery always terminates.+ """+ depth = getattr(self._emit_depth, "value", 0)+ if depth >= _EVENT_EMIT_DEPTH_CAP:+ logger.warning(+ "Event bus recursion cap (%d) exceeded while dispatching '%s' "+ "— dropping this emit to prevent an infinite loop",+ _EVENT_EMIT_DEPTH_CAP, event,+ )+ return 0+ callbacks = list(self._subscriptions.get(event, []))+ if not callbacks:+ return 0+ self._emit_depth.value = depth + 1+ invoked = 0+ try:+ for cb in callbacks:+ invoked += 1+ try:+ cb(**payload)+ except Exception as exc:+ logger.warning(+ "Event '%s' subscriber %s raised: %s",+ event,+ getattr(cb, "__name__", repr(cb)),+ exc,+ )+ finally:+ self._emit_depth.value = depth+ return invoked+def has_hook(self, hook_name: str) -> bool:"""Return True when at least one callback is registered for a hook."""return bool(self._hooks.get(hook_name))@@ -4106,6 +4242,18 @@ def get_plugin_auxiliary_tasks() -> List[Dict[str, Any]]:return [manager._aux_tasks[k] for k in sorted(manager._aux_tasks)]+def get_plugin_subscriptions() -> Dict[str, List[Callable]]:+ """Return the inter-plugin event bus subscription registry.++ Maps each fully-qualified event name (``<plugin_key>:<event>`` or+ ``hermes:<event>``) to its list of subscriber callbacks in registration+ order. Triggers idempotent plugin discovery so callers can read the+ registry before any explicit ``discover_plugins()`` call.+ """+ manager = _ensure_plugins_discovered()+ return manager._subscriptions++def get_plugin_toolsets() -> List[tuple]:"""Return plugin toolsets as ``(key, label, description)`` tuples.diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 370518154cc..aeed0d8d14b 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -2018,6 +2018,55 @@ def _configure_context_engine() -> bool:# ---------------------------------------------------------------------------+def cmd_show(name: str) -> None:+ """Show details for a single plugin, including declared emits/listens.++ Resolves *name* against every discoverable plugin (bundled + user ++ entrypoint) by either its display name or its registry key, then reads+ its ``plugin.yaml`` to surface the advisory event-bus declarations+ (``emits`` / ``listens``) alongside the basic metadata.+ """+ from rich.console import Console++ console = Console()+ entries = _discover_all_plugins()+ match = None+ for entry in entries:+ # entry = (name, version, description, source, dir_path, key)+ if entry[0] == name or entry[5] == name:+ match = entry+ break++ if match is None:+ console.print(f"[red]Plugin '{name}' not found.[/red]")+ console.print("[dim]List installed plugins:[/dim] hermes plugins list")+ sys.exit(1)++ pname, version, description, source, dir_path, key = match+ manifest = _read_manifest(Path(dir_path)) if dir_path else {}+ emits = manifest.get("emits") or []+ listens = manifest.get("listens") or []++ enabled = _get_enabled_set()+ disabled = _get_disabled_set()+ status = _plugin_status(pname, enabled, disabled, key=key)++ console.print()+ console.print(f"[bold]{pname}[/bold]" + (f" [dim]v{version}[/dim]" if version else ""))+ if description:+ console.print(description)+ console.print(f"[dim]Status:[/dim] {status}")+ console.print(f"[dim]Source:[/dim] {source}")+ console.print(f"[dim]Key:[/dim] {key}")+ console.print(+ "[dim]Emits:[/dim] " + (", ".join(emits) if emits else "[dim](none)[/dim]")+ )+ console.print(+ "[dim]Listens:[/dim] " + (", ".join(listens) if listens else "[dim](none)[/dim]")+ )+ console.print()++def cmd_toggle() -> None:"""Interactive composite UI — general plugins + provider plugin categories."""from rich.console import Console@@ -2836,6 +2885,8 @@ def plugins_command(args) -> None:cmd_list(args)elif action == "doctor":cmd_plugin_doctor(args.target, ci=getattr(args, "ci", False))+ elif action in {"show", "info"}:+ cmd_show(args.name)elif action is None:cmd_toggle()else:diff --git a/hermes_cli/subcommands/plugins.py b/hermes_cli/subcommands/plugins.pyindex b5b7831b2f3..68020b5e09a 100644--- a/hermes_cli/subcommands/plugins.py+++ b/hermes_cli/subcommands/plugins.py@@ -173,4 +173,11 @@ def build_plugins_parser(subparsers, *, cmd_plugins: Callable) -> None:help="Exit non-zero when validation reports an error",)+ plugins_show = plugins_subparsers.add_parser(+ "show",+ aliases=["info"],+ help="Show details for a single plugin (including emits/listens)",+ )+ plugins_show.add_argument("name", help="Plugin name or key to show")+plugins_parser.set_defaults(func=cmd_plugins)diff --git a/tests/hermes_cli/test_plugin_event_bus.py b/tests/hermes_cli/test_plugin_event_bus.pynew file mode 100644index 00000000000..6e4396716c3--- /dev/null+++ b/tests/hermes_cli/test_plugin_event_bus.py@@ -0,0 +1,354 @@+"""Tests for the inter-plugin event bus (PluginContext.emit / subscribe).++Covers:+ - Two plugins communicate via emit/subscribe; emit returns listener count+ - Namespace is FORCED to the emitting plugin's own key+ - Namespace spoofing (hermes:, foreign, already-colon'd) is rejected+ - Per-callback isolation: one raising subscriber does not break the rest+ - Recursion cap: mutually-emitting plugins terminate + warn+ - Manifest emits/listens parsed as optional advisory fields+ - `hermes plugins show` output includes emits/listens+"""++from __future__ import annotations++import logging++import pytest++from hermes_cli.plugins import (+ _EVENT_EMIT_DEPTH_CAP,+ PluginContext,+ PluginManager,+ PluginManifest,+ get_plugin_subscriptions,+)+++# ── Fixtures ─────────────────────────────────────────────────────────────────+++def _make_ctx(manager: PluginManager, name: str, key: str = "") -> PluginContext:+ """Build a PluginContext for *name* wired to *manager*."""+ manifest = PluginManifest(name=name, key=key)+ return PluginContext(manifest, manager)+++def _fresh_manager() -> PluginManager:+ manager = PluginManager()+ manager._discovered = True # skip auto-discovery+ return manager+++# ── 1. Two plugins communicate ───────────────────────────────────────────────+++def test_two_plugins_communicate():+ manager = _fresh_manager()+ ctx_a = _make_ctx(manager, "plugin_a", key="a")+ ctx_b = _make_ctx(manager, "plugin_b", key="b")++ received = []++ def on_ping(**payload):+ received.append(payload)++ # A subscribes to b:ping; B emits the bare name "ping".+ ctx_a.subscribe("b:ping", on_ping)+ count = ctx_b.emit("ping", {"n": 42})++ assert count == 1 # one listener invoked+ assert received == [{"n": 42}]+++def test_emit_with_no_subscribers_returns_zero():+ manager = _fresh_manager()+ ctx_b = _make_ctx(manager, "plugin_b", key="b")+ assert ctx_b.emit("ping", {"x": 1}) == 0+++def test_emit_none_payload_delivers_empty_kwargs():+ manager = _fresh_manager()+ ctx_a = _make_ctx(manager, "plugin_a", key="a")+ ctx_b = _make_ctx(manager, "plugin_b", key="b")++ seen = []+ ctx_a.subscribe("b:ping", lambda **p: seen.append(p))+ count = ctx_b.emit("ping") # payload omitted++ assert count == 1+ assert seen == [{}]+++# ── 2. Namespace is forced to the emitter's own key ──────────────────────────+++def test_namespace_forced_to_emitter_key():+ manager = _fresh_manager()+ ctx_a = _make_ctx(manager, "plugin_a", key="a")+ ctx_b = _make_ctx(manager, "plugin_b", key="b")++ delivered_events = []++ # Subscribe to what we expect the fully-qualified name to be.+ ctx_a.subscribe("b:ping", lambda **p: delivered_events.append("b:ping"))+ # A wrong-namespace subscription must NOT fire.+ ctx_a.subscribe("a:ping", lambda **p: delivered_events.append("a:ping"))++ ctx_b.emit("ping")++ # Delivered under the emitter's own key ("b"), never "a".+ assert delivered_events == ["b:ping"]+ # Registry stores it under the forced full name.+ assert "b:ping" in manager._subscriptions+++def test_namespace_falls_back_to_name_when_key_empty():+ manager = _fresh_manager()+ # No key → namespace derives from name.+ ctx = _make_ctx(manager, "plugin_named", key="")+ got = []+ ctx.subscribe("plugin_named:evt", lambda **p: got.append(p))+ count = ctx.emit("evt", {"v": 1})+ assert count == 1+ assert got == [{"v": 1}]+++# ── 3. Namespace spoofing is rejected (fail-closed) ──────────────────────────+++ "bad_event",+ [+ "hermes:x", # reserved core prefix+ "a:x", # foreign namespace+ "b:x", # even the plugin's own colon'd name — must pass bare only+ "other:evt",+ ":x",+ "x:",+ ],+)+def test_emit_rejects_namespaced_names(bad_event):+ manager = _fresh_manager()+ ctx_b = _make_ctx(manager, "plugin_b", key="b")++ fired = []+ # Subscribe to every plausible delivery target so we can prove no delivery.+ for name in (bad_event, f"b:{bad_event}", "hermes:x", "a:x", "b:x"):+ ctx_b.subscribe(name, lambda **p: fired.append(name))++ with pytest.raises(ValueError):+ ctx_b.emit(bad_event)++ assert fired == [] # nothing delivered+++def test_emit_rejects_empty_event():+ manager = _fresh_manager()+ ctx_b = _make_ctx(manager, "plugin_b", key="b")+ with pytest.raises(ValueError):+ ctx_b.emit("")+++def test_subscribe_is_unrestricted():+ """Any plugin may subscribe to any event, including hermes: and foreign."""+ manager = _fresh_manager()+ ctx_a = _make_ctx(manager, "plugin_a", key="a")+ got = []+ # None of these raise — only emit is namespace-gated.+ ctx_a.subscribe("hermes:core_event", lambda **p: got.append("hermes"))+ ctx_a.subscribe("b:ping", lambda **p: got.append("b"))+ assert "hermes:core_event" in manager._subscriptions+ assert "b:ping" in manager._subscriptions+++# ── 4. Per-callback isolation ────────────────────────────────────────────────+++def test_per_callback_isolation(caplog):+ manager = _fresh_manager()+ ctx_a = _make_ctx(manager, "plugin_a", key="a")+ ctx_b = _make_ctx(manager, "plugin_b", key="b")++ received = []++ def boom(**payload):+ raise RuntimeError("subscriber exploded")++ def good(**payload):+ received.append(payload)++ # Registration order: raising subscriber first, healthy one second.+ ctx_a.subscribe("b:ping", boom)+ ctx_a.subscribe("b:ping", good)++ with caplog.at_level(logging.WARNING):+ count = ctx_b.emit("ping", {"ok": True})++ # Both listeners were invoked despite the first raising.+ assert count == 2+ assert received == [{"ok": True}]+ assert any("subscriber exploded" in r.message or "raised" in r.message+ for r in caplog.records)+++# ── 5. Recursion cap ─────────────────────────────────────────────────────────+++def test_recursion_cap_terminates(caplog):+ manager = _fresh_manager()+ ctx_a = _make_ctx(manager, "plugin_a", key="a")+ ctx_b = _make_ctx(manager, "plugin_b", key="b")++ calls = {"a": 0, "b": 0}++ # A hears b:ping and re-emits a:ping; B hears a:ping and re-emits b:ping.+ def a_on_bping(**payload):+ calls["a"] += 1+ ctx_a.emit("ping")++ def b_on_aping(**payload):+ calls["b"] += 1+ ctx_b.emit("ping")++ ctx_a.subscribe("b:ping", a_on_bping)+ ctx_b.subscribe("a:ping", b_on_aping)++ with caplog.at_level(logging.WARNING):+ # Kick off the loop — must terminate, not hang or RecursionError.+ result = ctx_b.emit("ping")++ # Returned cleanly.+ assert result == 1+ # Bounded by the depth cap — nowhere near unbounded.+ assert calls["a"] + calls["b"] <= _EVENT_EMIT_DEPTH_CAP + 1+ # Exactly the recursion-cap warning fired.+ assert any("recursion cap" in r.message.lower() for r in caplog.records)+++# ── 6. Manifest emits/listens parsed as optional ─────────────────────────────+++def test_manifest_emits_listens_default_empty():+ m = PluginManifest(name="plain")+ assert m.emits == []+ assert m.listens == []+++def test_manifest_emits_listens_present():+ m = PluginManifest(+ name="declar",+ key="declar",+ emits=["ping", "pong"],+ listens=["other:ready"],+ )+ assert m.emits == ["ping", "pong"]+ assert m.listens == ["other:ready"]+++def test_manifest_parse_reads_emits_listens(tmp_path):+ """_parse_manifest picks up optional emits/listens from plugin.yaml."""+ import yaml++ plugin_dir = tmp_path / "myplug"+ plugin_dir.mkdir()+ manifest_file = plugin_dir / "plugin.yaml"+ manifest_file.write_text(+ yaml.safe_dump(+ {+ "name": "myplug",+ "emits": ["ping"],+ "listens": ["other:evt"],+ }+ ),+ encoding="utf-8",+ )++ manager = _fresh_manager()+ manifest = manager._parse_manifest(manifest_file, plugin_dir, "user", "")+ assert manifest is not None+ assert manifest.emits == ["ping"]+ assert manifest.listens == ["other:evt"]+++def test_manifest_parse_absent_emits_listens(tmp_path):+ import yaml++ plugin_dir = tmp_path / "bare"+ plugin_dir.mkdir()+ manifest_file = plugin_dir / "plugin.yaml"+ manifest_file.write_text(+ yaml.safe_dump({"name": "bare"}), encoding="utf-8"+ )++ manager = _fresh_manager()+ manifest = manager._parse_manifest(manifest_file, plugin_dir, "user", "")+ assert manifest is not None+ assert manifest.emits == []+ assert manifest.listens == []+++# ── Module-level accessor ────────────────────────────────────────────────────+++def test_get_plugin_subscriptions_accessor(monkeypatch):+ from hermes_cli import plugins as plugins_mod++ fresh = _fresh_manager()+ monkeypatch.setattr(plugins_mod, "_ensure_plugins_discovered", lambda force=False: fresh)++ ctx = _make_ctx(fresh, "plugin_a", key="a")+ ctx.subscribe("b:ping", lambda **p: None)++ subs = get_plugin_subscriptions()+ assert "b:ping" in subs+ assert len(subs["b:ping"]) == 1+++# ── 7. plugins show output includes emits/listens ────────────────────────────+++def test_plugins_show_includes_emits_listens(tmp_path, monkeypatch, capsys):+ import yaml+ from hermes_cli import plugins_cmd++ plugin_dir = tmp_path / "showplug"+ plugin_dir.mkdir()+ (plugin_dir / "plugin.yaml").write_text(+ yaml.safe_dump(+ {+ "name": "showplug",+ "version": "1.2.3",+ "description": "a demo plugin",+ "emits": ["ping", "pong"],+ "listens": ["other:ready"],+ }+ ),+ encoding="utf-8",+ )++ # entry = (name, version, description, source, dir_path, key)+ entry = ("showplug", "1.2.3", "a demo plugin", "user", str(plugin_dir), "showplug")+ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: [entry])+ monkeypatch.setattr(plugins_cmd, "_get_enabled_set", lambda: set())+ monkeypatch.setattr(plugins_cmd, "_get_disabled_set", lambda: set())++ plugins_cmd.cmd_show("showplug")++ out = capsys.readouterr().out+ assert "showplug" in out+ assert "Emits:" in out+ assert "ping" in out+ assert "pong" in out+ assert "Listens:" in out+ assert "other:ready" in out+++def test_plugins_show_not_found_exits(monkeypatch, capsys):+ from hermes_cli import plugins_cmd++ monkeypatch.setattr(plugins_cmd, "_discover_all_plugins", lambda: [])+ with pytest.raises(SystemExit):+ plugins_cmd.cmd_show("nope")+ out = capsys.readouterr().out+ assert "not found" in out.lower()