Skip to content

The agent that grows with you

fix(plugins): broadcast_plugin_event from the turn-isolation child reaches the Desktop

teknium1be59f0411e8f
diff --git a/hermes_cli/plugin_events.py b/hermes_cli/plugin_events.py
index 43ee2e1e059..29f16c5298f 100644
--- a/hermes_cli/plugin_events.py
+++ b/hermes_cli/plugin_events.py
@@ -20,15 +20,21 @@ event 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.
+routers, slash commands and the agent turn's tools/hooks run) that is every
+connected window; a call from the ``dashboard.turn_isolation`` compute-host
+child rides the host pipe to ``hermes serve`` and fans out there. A process
+with no Desktop client at all (``hermes gateway run``, ``hermes chat``, cron)
+has nobody to deliver to: the call is a logged no-op.
"""
from __future__ import annotations
+import logging
import re
from typing import Any, Optional
+logger = logging.getLogger(__name__)
+
#: Every plugin event name starts with this — core owns all other names.
PLUGIN_EVENT_PREFIX = "plugin."
@@ -71,6 +77,12 @@ def broadcast_plugin_event(plugin_id: str, event: str, payload: Optional[dict[st
# 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
+ try:
+ from tui_gateway.server import _broadcast_global_event
+ except ImportError:
+ # A plugin-only process (``hermes plugins validate`` importing the backend, a trimmed
+ # install) has no gateway at all: nobody to deliver to, and the handler must not die for it.
+ logger.warning("plugin event %s dropped: no tui_gateway in this process", name, exc_info=True)
+ return
_broadcast_global_event(name, dict(payload or {}))
diff --git a/tests/hermes_cli/test_plugin_events.py b/tests/hermes_cli/test_plugin_events.py
index a2d922a0f97..5b67931ca98 100644
--- a/tests/hermes_cli/test_plugin_events.py
+++ b/tests/hermes_cli/test_plugin_events.py
@@ -44,6 +44,72 @@ def test_broadcast_reaches_a_registered_client_as_a_namespaced_global_event():
]
+def test_broadcast_from_a_turn_isolation_child_reaches_the_parent_gateways_clients(monkeypatch):
+ """``dashboard.turn_isolation`` runs plugin agent-side code (tools, hooks, slash commands) in the
+ compute-host child, where no client is connected: the frame must ride the host pipe to the parent
+ ``hermes serve`` and fan out there instead of dying at ``logger.debug``."""
+ import io
+ import json
+ import os
+ import threading
+
+ import tui_gateway.server as server
+ from tui_gateway import compute_host
+
+ monkeypatch.setenv("HERMES_COMPUTE_HOST_HEARTBEAT_SECS", "0")
+ monkeypatch.setenv("HERMES_COMPUTE_HOST_CHILD", "0")
+ child_stdout = io.StringIO()
+ stdin_r, stdin_w = os.pipe()
+ child = threading.Thread(
+ target=compute_host.run_host, kwargs={"stdin": os.fdopen(stdin_r), "stdout": child_stdout}, daemon=True)
+ child.start()
+ try:
+ deadline = threading.Event()
+ for _ in range(100): # the child registers its transport right after ``hello``
+ if any(isinstance(t, compute_host._HostTransport) for t in list(server._live_transports)):
+ break
+ deadline.wait(0.05)
+ plugin_events.broadcast_plugin_event("rss-reader", "feed.updated", {"count": 3})
+ finally:
+ os.close(stdin_w)
+ child.join(timeout=10)
+ assert not child.is_alive()
+ assert not any(isinstance(t, compute_host._HostTransport) for t in list(server._live_transports))
+
+ piped = [json.loads(line) for line in child_stdout.getvalue().splitlines()]
+ relayed = [f for f in piped if f.get("type") == "rpc"]
+ assert len(relayed) == 1 and relayed[0]["sid"] == ""
+
+ # Parent side: the supervisor hands the child's frame to the bridge, which must broadcast it.
+ peer = _Peer()
+ server.register_live_transport(peer)
+ try:
+ server._relay_compute_host_rpc(relayed[0]["message"])
+ finally:
+ server.unregister_live_transport(peer)
+ assert [f["params"]["type"] for f in peer.frames] == ["plugin.rss-reader.feed.updated"]
+ assert peer.frames[0]["params"]["payload"] == {"count": 3}
+
+
+def test_broadcast_without_a_gateway_module_is_a_logged_no_op(monkeypatch, caplog):
+ """A plugin-only process (``hermes plugins validate`` importing the backend) has no
+ ``tui_gateway.server``; the documented "safe from any handler" promise must hold there too."""
+ import builtins
+ import logging
+
+ real_import = builtins.__import__
+
+ def _no_gateway(name, *args, **kwargs):
+ if name == "tui_gateway.server":
+ raise ImportError("No module named 'tui_gateway.server'")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_gateway)
+ with caplog.at_level(logging.WARNING, logger="hermes_cli.plugin_events"):
+ plugin_events.broadcast_plugin_event("rss-reader", "feed.updated")
+ assert "plugin.rss-reader.feed.updated" in caplog.text
+
+
@pytest.mark.parametrize(
("plugin_id", "event", "payload", "exc"),
[
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 49a9afb5a0b..6719c2189c1 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -525,6 +525,11 @@ def run_host(stdin: Any = None, stdout: Any = None) -> None:
stdin = stdin or sys.stdin
host = ComputeHost(stdout=stdout or sys.stdout)
shutting_down = threading.Event()
+ # No client is connected to this process: session-less broadcasts (``broadcast_plugin_event``
+ # from a plugin tool/hook running in the isolated turn) ride the host pipe to the parent
+ # gateway, which fans them out to its clients (compute_host_bridge._relay_compute_host_rpc).
+ from tui_gateway import server
+ server.register_live_transport(host._transport)
def _signal_handler(_signum, _frame) -> None:
if shutting_down.is_set():
@@ -564,6 +569,7 @@ def run_host(stdin: Any = None, stdout: Any = None) -> None:
if not reader.is_alive():
break
finally:
+ server.unregister_live_transport(host._transport)
host.shutdown(reason="stdin_closed", wait=2.0)
diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.py
index 48c81a20ba1..41d636bd270 100644
--- a/tui_gateway/compute_host_bridge.py
+++ b/tui_gateway/compute_host_bridge.py
@@ -129,6 +129,12 @@ def _relay_compute_host_rpc(message: dict) -> bool:
and session.get("_compute_host_turn_id") == params["turn_id"]):
session["_compute_host_activity_ns"] = params.get("activity_ns")
return True # Internal observation, not a client event or replay entry.
+ if (isinstance(message, dict) and message.get("method") == "event" and isinstance(params, dict)
+ and not params.get("session_id")):
+ # A session-less (global) event the child could not deliver itself: ``write_json`` would drop it
+ # on this process's stdio; fan it out to every connected client like a local broadcast.
+ _broadcast_global_event(str(params.get("type") or ""), params.get("payload"))
+ return True
if isinstance(message, dict) and isinstance(message.get("id"), str) and message.get("method") not in (None, "event"):
# A server request minted by the child: remember it against its session until it is answered/withdrawn.
session = _sessions.get(str((params or {}).get("session_id") or "")) if isinstance(params, dict) else None
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 9432bd03dec..790b60d946d 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -1403,10 +1403,16 @@ plugin's); `event` is the BARE dotted name (`"feed.updated"`, not
on a name nobody emits. `payload` is a JSON dict (or omitted → `{}`), delivered
as the event's `payload`; the frame carries `session_id: ""` like every global
event. Delivery is fire-and-forget (a wedged client is skipped, never stalling
-your handler) and per process: under `hermes serve` (the Desktop backend, where
-both `plugin_api.py` routers and slash commands run) it reaches every connected
-window; in a process with no connected client it is a logged no-op. Use this
-instead of importing `tui_gateway.server` internals; for plugin-scoped frames
+your handler). Where it lands depends on the process the call runs in:
+
+| Caller runs in | Reaches |
+|---|---|
+| `hermes serve` (the Desktop backend): `plugin_api.py` routers, plugin slash commands, tools and hooks in the agent turn | every connected Desktop window |
+| the `dashboard.turn_isolation` compute-host child (tools/hooks of an isolated turn) | relayed over the host pipe to `hermes serve`, then every window |
+| the stdio TUI (`hermes` in a terminal) | that terminal's client |
+| `hermes gateway run` (messaging platforms), `hermes chat`, cron, `hermes plugins validate` | nobody — no Desktop client is attached to that process; the call is a logged no-op |
+
+Use this instead of importing `tui_gateway.server` internals; for plugin-scoped frames
with a payload tailored per connection, `ctx.socket('/events')` remains the
richer door.