The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): on_room_member_activity hook projects Group Chat member runtime events to plugins
Tekniumfafb27ee5c5b
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex bc45188e488..0e639fe60f6 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -135,6 +135,12 @@ VALID_HOOKS: Set[str] = {# surface: "cli"|"gateway"|"smart"; post_approval_response adds choice ("once"|"session"|# "always"|"deny"|"timeout"|"smart_approve"|"smart_deny") and decided_by."pre_approval_request", "post_approval_response",+ # on_room_member_activity: a hosted Group Chat member's live runtime events (tool.started/completed,+ # request.opened, message.delta, reasoning.delta, turn.error, ...) stamped with room_id, thread_id,+ # member_id, turn_id, task_id, execution_generation. Observer, queued per consumer off the token+ # path (agent.plugin_stream_hooks); never written to the durable room log. Kwargs: those+ # coordinates + kind, seq, payload (the client-safe session event payload, approvals redacted).+ "on_room_member_activity",# pre_transcription: after provider resolution, BEFORE any backend runs. Kwargs: file_path,# provider, model, language, prompt, source. Return None or a dict mutating prompt/language/# model (registration order, last-writer-wins; file_path is read-only).diff --git a/tests/tui_gateway/test_hosted_room_driver_runtime.py b/tests/tui_gateway/test_hosted_room_driver_runtime.pyindex 9b226701515..bdf5fe77981 100644--- a/tests/tui_gateway/test_hosted_room_driver_runtime.py+++ b/tests/tui_gateway/test_hosted_room_driver_runtime.py@@ -177,6 +177,7 @@ class FakeSessionRPC:task: state.TaskIdentity,execution_generation: int,on_terminal,+ member_id="",):self._assert_lock(profile)params = {diff --git a/tests/tui_gateway/test_hosted_room_member_activity_hook.py b/tests/tui_gateway/test_hosted_room_member_activity_hook.pynew file mode 100644index 00000000000..af73a6cbec6--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_member_activity_hook.py@@ -0,0 +1,89 @@+"""on_room_member_activity: a room member's hidden-session runtime events reach plugins with room+coordinates; an ordinary session's identical events never do."""++from __future__ import annotations++import threading+import time++import pytest++from tui_gateway import server+from tui_gateway.hosted_room_member_activity import HOOK_NAME+++def _wait_for(predicate, timeout: float = 2.0) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.01)+ assert predicate()+++def observer(monkeypatch):+ from agent.plugin_stream_hooks import shutdown_plugin_stream_hook_dispatcher++ shutdown_plugin_stream_hook_dispatcher()+ seen: list[dict] = []+ lock = threading.Lock()++ def on_activity(**kwargs):+ with lock:+ seen.append(kwargs)++ monkeypatch.setattr(+ "hermes_cli.plugins.iter_hook_callbacks", lambda name: (on_activity,) if name == HOOK_NAME else ())+ monkeypatch.setattr(server, "_stdio_transport", type("Sink", (), {"write": staticmethod(lambda _o: True)})())+ yield seen+ shutdown_plugin_stream_hook_dispatcher()+++HOSTED_TASK = {+ "room_id": "room-a", "task_id": "task-1", "thread_id": "thread-1", "turn_id": "turn-1",+ "execution_generation": 2, "member_id": "reviewer"}+++def _session(sid: str, hosted: bool):+ entry = {"session_key": sid, "transport": None, "agent": None, "created_at": time.time()}+ if hosted:+ entry["_hosted_room_task"] = dict(HOSTED_TASK)+ with server._sessions_lock:+ server._sessions[sid] = entry+++def test_room_member_session_events_reach_plugins_with_room_coordinates(observer):+ _session("room-sid", hosted=True)+ try:+ server._emit("tool.start", "room-sid", {"tool_id": "call-1", "name": "terminal", "args": {"command": "ls"}})+ server._emit("approval.request", "room-sid", {"request_id": "req-1", "command": "rm -rf build"})+ server._emit("session.info", "room-sid", {"title": "chrome, not member activity"})+ server._emit("tool.complete", "room-sid", {"tool_id": "call-1", "name": "terminal", "result": "ok"})+ finally:+ with server._sessions_lock:+ server._sessions.pop("room-sid", None)++ _wait_for(lambda: len(observer) == 3)+ kinds = [event["kind"] for event in observer]+ assert kinds == ["tool.started", "request.opened", "tool.completed"]+ started = observer[0]+ assert {k: started[k] for k in HOSTED_TASK} == HOSTED_TASK+ assert started["payload"]["tool_id"] == "call-1" and started["payload"]["args"] == {"command": "ls"}+ assert observer[1]["payload"]["request_id"] == "req-1"+ # Per-session replay seq travels with the event so consumers can order/dedupe.+ assert [event["seq"] for event in observer] == sorted(event["seq"] for event in observer)+++def test_ordinary_session_events_never_fire_the_room_hook(observer):+ _session("plain-sid", hosted=False)+ try:+ server._emit("tool.start", "plain-sid", {"tool_id": "call-1", "name": "terminal"})+ server._emit("approval.request", "plain-sid", {"request_id": "req-1", "command": "ls"})+ server._emit("message.delta", "plain-sid", {"text": "hi"})+ finally:+ with server._sessions_lock:+ server._sessions.pop("plain-sid", None)++ time.sleep(0.2)+ assert observer == []diff --git a/tests/tui_gateway/test_hosted_room_server_rpc.py b/tests/tui_gateway/test_hosted_room_server_rpc.pyindex 10577bda0cf..5ffb5aa6552 100644--- a/tests/tui_gateway/test_hosted_room_server_rpc.py+++ b/tests/tui_gateway/test_hosted_room_server_rpc.py@@ -63,6 +63,7 @@ def test_routes_exact_hidden_session_and_internal_task_proof():task=task,execution_generation=2,on_terminal=callback,+ member_id="ops-member",)create = next(params for method, params in calls if method == "session.create")@@ -77,6 +78,7 @@ def test_routes_exact_hidden_session_and_internal_task_proof():"thread_id": "thread","turn_id": "turn","execution_generation": 2,+ "member_id": "ops-member",}assert submit["_hosted_terminal_callback"] is callback@@ -171,6 +173,7 @@ def test_prompt_rejection_is_proven_not_admitted():task=TaskIdentity("room", "task", "thread", "turn"),execution_generation=1,on_terminal=lambda _receipt: None,+ member_id="ops",)assert exc.value.code == 4121diff --git a/tests/tui_gateway/test_hosted_room_service.py b/tests/tui_gateway/test_hosted_room_service.pyindex 80596b14a0a..9eb7fcad375 100644--- a/tests/tui_gateway/test_hosted_room_service.py+++ b/tests/tui_gateway/test_hosted_room_service.py@@ -68,6 +68,7 @@ class _FakeRPC:task,execution_generation,on_terminal,+ member_id="",):on_terminal({"status": "settled", "text": f"reply from {profile}"})return {"accepted": True}@@ -279,6 +280,7 @@ class _PromptRecordingRPC(_FakeRPC):task,execution_generation,on_terminal,+ member_id="",):self.prompts.append((profile, prompt))on_terminal({"status": "settled", "text": f"reply from {profile}"})diff --git a/tui_gateway/hosted_room_driver.py b/tui_gateway/hosted_room_driver.pyindex 5e4f5eab464..34a1dde0f07 100644--- a/tui_gateway/hosted_room_driver.py+++ b/tui_gateway/hosted_room_driver.py@@ -43,7 +43,7 @@ class InternalSessionRPC(Protocol):def resume(self, *, profile: str, session_id: str, source: str) -> Mapping[str, Any]: ...def submit(self, *, profile: str, session_id: str, prompt: str, source: str, task: state.TaskIdentity,- execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None],+ execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None], member_id: str,) -> Mapping[str, Any]: ...def history(self, *, profile: str, session_id: str, source: str) -> Sequence[Mapping[str, Any]]: ...@@ -593,7 +593,8 @@ class HostedRoomRuntime:transport.submit(**_session_kw(profile, session_id), prompt=task["payload"]["prompt"],task=attempt.identity, execution_generation=attempt.execution_generation,- on_terminal=lambda receipt: self._on_terminal(binding, attempt, receipt))+ on_terminal=lambda receipt: self._on_terminal(binding, attempt, receipt),+ member_id=_member_id(task))self._unavailable_route_retries.pop((task["identity"].room_id, _member_id(task)), None)receipt = self._wait_for_terminal(diff --git a/tui_gateway/hosted_room_member_activity.py b/tui_gateway/hosted_room_member_activity.pynew file mode 100644index 00000000000..51fe2e0a64b--- /dev/null+++ b/tui_gateway/hosted_room_member_activity.py@@ -0,0 +1,61 @@+"""Project a hosted room member's live runtime events to the ``on_room_member_activity`` plugin hook.++A member turn runs on a hidden ``room_plumbing`` session with no client transport, so the tool /+approval / streaming frames the turn loop already emits bottom out at stdio and are lost. Between+``turn.started`` and ``turn.settled`` in the durable room log a client sees nothing. This module+re-routes those frames, stamped with the room coordinates the session carries in+``_hosted_room_task``, to plugins — off the token path, through the same bounded per-consumer+queues the ``on_stream_*`` observers use. Nothing is written to the room log: deltas at room-log+byte budgets would exhaust a room in minutes, and checkpoint replay must stay a pure function of+the durable events.+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++HOOK_NAME = "on_room_member_activity"++# Session event frame ``type`` -> room activity ``kind``. Frames not listed (session.info,+# status.update, message.start/complete, ...) are session chrome, not member activity.+KIND_BY_FRAME_TYPE: Mapping[str, str] = {+ "tool.start": "tool.started",+ "tool.complete": "tool.completed",+ "tool.output_risk": "tool.output_risk",+ "approval.request": "request.opened",+ "message.delta": "message.delta",+ "message.interim": "message.interim",+ "reasoning.delta": "reasoning.delta",+ "error": "turn.error",+}++_COORDINATE_FIELDS = ("room_id", "thread_id", "member_id", "turn_id", "task_id", "execution_generation")+++def emit_room_member_activity(hosted_task: Mapping[str, Any], *, kind: str, payload: Mapping[str, Any] | None,+ seq: int | None = None) -> bool:+ """Queue one activity event for every registered consumer; False when nobody listens."""+ from agent.plugin_stream_hooks import enqueue_plugin_stream_hook++ coordinates = {field: hosted_task.get(field) for field in _COORDINATE_FIELDS}+ return enqueue_plugin_stream_hook(HOOK_NAME, **coordinates, kind=kind, seq=seq, payload=dict(payload or {}))+++def project_room_member_activity(frame: Mapping[str, Any], sessions: Mapping[str, Mapping[str, Any]]) -> bool:+ """Fire the hook for an outgoing session event frame when its session is running a room turn."""+ if frame.get("method") != "event":+ return False+ params = frame.get("params")+ if not isinstance(params, Mapping):+ return False+ kind = KIND_BY_FRAME_TYPE.get(str(params.get("type") or ""))+ if kind is None:+ return False+ session = sessions.get(str(params.get("session_id") or ""))+ hosted_task = session.get("_hosted_room_task") if isinstance(session, Mapping) else None+ if not isinstance(hosted_task, Mapping):+ return False+ payload = params.get("payload")+ return emit_room_member_activity(+ hosted_task, kind=kind, payload=payload if isinstance(payload, Mapping) else None, seq=params.get("seq"))diff --git a/tui_gateway/hosted_room_peer_transport.py b/tui_gateway/hosted_room_peer_transport.pyindex 0bda289022e..e49594c5f9c 100644--- a/tui_gateway/hosted_room_peer_transport.py+++ b/tui_gateway/hosted_room_peer_transport.py@@ -193,8 +193,9 @@ class PeerHostedRoomTransport(InternalSessionRPC):def submit(self, *, profile: str, session_id: str, prompt: str, source: str, task: TaskIdentity,- execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None],+ execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None], member_id: str = "",) -> Mapping[str, Any]:+ del member_id # the signed route already names the memberself._validate_coordinates(profile=profile, source=source)if self._session_id not in {None, session_id}:raise ValueError("peer room session changed during admission")diff --git a/tui_gateway/hosted_room_server_rpc.py b/tui_gateway/hosted_room_server_rpc.pyindex e470c91a09d..38578592a36 100644--- a/tui_gateway/hosted_room_server_rpc.py+++ b/tui_gateway/hosted_room_server_rpc.py@@ -67,14 +67,15 @@ class HostedRoomServerRPC:def submit(self, *, profile: str, session_id: str, prompt: str, source: str, task: state.TaskIdentity,- execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None],+ execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None], member_id: str,) -> Mapping[str, Any]:try:return self._call("prompt.submit", {"profile": profile, "session_id": session_id, "text": prompt, "source": source,"_hosted_task": {"room_id": task.room_id, "task_id": task.task_id, "thread_id": task.thread_id,- "turn_id": task.turn_id, "execution_generation": execution_generation},+ "turn_id": task.turn_id, "execution_generation": execution_generation,+ "member_id": member_id},"_hosted_terminal_callback": on_terminal})except HostedRoomSessionError as exc:# In-process prompt.submit error envelopes come back before the background turn isdiff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 07ad5fda8f6..0ff67007c27 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -187,7 +187,7 @@ def _typed_stop_phrase_response(rid, text):return _ok(rid, {"voice_stopped": True})-_HOSTED_TASK_FIELDS = {"room_id", "task_id", "thread_id", "turn_id", "execution_generation"}+_HOSTED_TASK_FIELDS = {"room_id", "task_id", "thread_id", "turn_id", "execution_generation", "member_id"}def _hosted_submit_error(rid, session, hosted_task, hosted_terminal_callback):diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 8175d2d0c3e..cbfe41572db 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -576,8 +576,11 @@ def write_json(obj: dict) -> bool:(2) the context-bound transport (:func:`dispatch`); (3) module stdio (tests monkey-patch ``_real_stdout``).Every event frame gets a per-session monotonic ``seq`` + replay-ring entry so ``session.events.since`` can resume."""from tui_gateway.event_replay import _stamp_event+ from tui_gateway.hosted_room_member_activity import project_room_member_activity_stamp_event(obj)if obj.get("method") == "event":+ # A room member's hidden session has no transport: its frames would die at stdio below.+ project_room_member_activity(obj, _sessions)params = obj.get("params")sid = ((params or {}).get("session_id")) if isinstance(params, dict) else ""if sid and (t := (_sessions.get(sid) or {}).get("transport")) is not None:diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.pyindex c3803fe97db..bab6c68f98e 100644--- a/tui_gateway/tool_progress.py+++ b/tui_gateway/tool_progress.py@@ -224,6 +224,8 @@ def _emit_tool_lifecycle(event, sid, name, args, payload):transport = current_transport() or _stdio_transportframe = _event_frame(event, sid, payload)_stamp_event(frame)+ from tui_gateway.hosted_room_member_activity import project_room_member_activity+ project_room_member_activity(frame, _sessions)transport.write(frame)diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex 007d2da2f22..8db271d9d7a 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -104,6 +104,7 @@ Use the **Move up** and **Move down** arrows beside a room to choose its positio- **Not every Bot replies to every message.** Speaking is each member's own choice — a Bot replies only when it has something new to add and passes otherwise, and @-mentioning specific members scopes the round to them. Expect the members you addressed (or whoever has something to say) to speak, and the rest to stay quiet.- **Rooms keep running when you close the Desktop.** When every member of a room lives on the same gateway, that gateway owns turn scheduling through a durable driver: closing Hermes Desktop (or losing its connection) does not stop a room mid-discussion, and the Desktop simply catches up from the room's log when it reconnects. `groups.capabilities` on the gateway reports `driver: true` when this applies. Rooms whose members span several machines are different: each member's turns run on its own gateway, and the cross-connection courier described under *Bot-to-bot messaging* still applies to them.- **Rooms can span machines.** The New Group Chat picker seats Bots from any registered connection; each member's turns run on its own machine, in its own `Group: <name>` session there. Cross-machine members carry a device badge (`dixie · Mac Mini`) in the room and in other members' transcripts, and the disambiguated `@name-device` handle works in room mentions — so same-named agents on two machines never blur together.+- **Plugins can watch members work.** The durable room log records `turn.started` and `turn.settled`; what a member does in between (tools, approvals, streamed text) is projected to plugins through the [`on_room_member_activity`](/user-guide/features/hooks#on_room_member_activity) hook with room, member and turn coordinates, so community clients can build tool cards and live member status on top of Group Chat without reading Hermes internals.## Bot-to-bot messagingdiff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 182b045920a..e5562398080 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -467,6 +467,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. || `pre_approval_request` | Observer | Before prompted or smart approval; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id` | Command may contain secrets; smart observer preparation force-redacts, but surfaces do not all have identical redaction. || `post_approval_response` | Observer | After a decision, timeout, or gateway notification failure; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id`, `choice`; smart path may add `decided_by` | Same command sensitivity plus decision metadata. |+| `on_room_member_activity` | Observer | While a hosted Group Chat member turn runs on the Bot Mode gateway, once per runtime event the member session emits (tool start/complete, approval request, message/reasoning deltas, errors); queued per consumer off the token path; return ignored. | `room_id`, `thread_id`, `member_id`, `turn_id`, `task_id`, `execution_generation`, `kind`, `seq`, `payload` | `payload` is the client-safe session event body: tool args and results, redacted approval commands, streamed member text. || `kanban_task_claimed` | Observer | After claim commit, in dispatcher process before worker spawn; return ignored. | `task_id`, `profile_name`, `board`, `assignee`, `run_id` | Board/task/profile/assignee identifiers. || `kanban_task_completed` | Observer | After completion and cleanup, usually in worker process; return ignored. | `task_id`, `profile_name`, `board`, `assignee`, `run_id`, `summary` | Summary may contain project/user content. || `kanban_task_blocked` | Observer | After a blocked transition; the dependency-wait path fires before its transaction exits. Return ignored. | `task_id`, `profile_name`, `board`, `assignee`, `run_id`, `reason` | Reason may contain project/user content. |@@ -1360,6 +1361,51 @@ def register(ctx):---+### `on_room_member_activity`++Fires while a hosted [Group Chat](/user-guide/bot-mode#groups-and-group-chats) member turn runs. A member executes on a hidden `Group: <room>` session that no client is attached to, so between the room log's `turn.started` and `turn.settled` the turn is a black box. This hook projects the runtime events that session already produces — tool start/complete, approval requests, streamed text and reasoning, errors — stamped with the room coordinates, so a client (Hermes Crew, a dashboard, an audit log) can render tool cards, approval prompts and live member status without inferring anything from text. The Group Chat runtime keeps ownership of execution, scheduling and the durable log; plugins only observe.++**Callback signature:**++```python+def my_callback(+ room_id: str,+ thread_id: str,+ member_id: str,+ turn_id: str,+ task_id: str,+ execution_generation: int,+ kind: str,+ seq: int | None,+ payload: dict,+ **kwargs,+):+```++| Parameter | Type | Description |+|-----------|------|-------------|+| `room_id`, `thread_id`, `turn_id`, `task_id` | `str` | The same coordinates the room log's `turn.*` and `message.member` events carry; join on them. |+| `member_id` | `str` | The seated member (`members[].member_id` from `groups.state`). |+| `execution_generation` | `int` | Increments on every retry of the same task; events from a superseded attempt carry the older value. |+| `kind` | `str` | `tool.started`, `tool.completed`, `tool.output_risk`, `request.opened` (approval), `message.delta`, `message.interim`, `reasoning.delta`, `turn.error`. New kinds are additive. |+| `seq` | `int \| None` | The member session's per-process event sequence (same numbering as `session.events.since`); monotonic within one gateway process, resets on restart. |+| `payload` | `dict` | The client-safe body of the underlying session event (`tool_id`, `name`, `args`, `result`, `request_id`, `choices`, `text`, ...). Approval commands are already credential-redacted. |++**Delivery:** each registered callback gets its own bounded queue and worker thread (the `on_stream_*` mechanism); a slow callback drops its oldest pending event and never delays the member's turn. Nothing is written to the room log — deltas are not durable and do not replay; clients that need durability persist what they receive. Local members only: a member seated from another machine runs on that machine's gateway, whose plugins see it.++**Return value:** ignored.++```python+def on_member_activity(room_id, member_id, turn_id, kind, payload, **kwargs):+ if kind == "request.opened":+ notify(f"{member_id} in {room_id} needs approval: {payload['command']}")++def register(ctx):+ ctx.register_hook("on_room_member_activity", on_member_activity)+```++---+### `pre_transcription`Fires inside the STT dispatcher (`tools.transcription_tools.transcribe_audio`) **after** the provider has been resolved and **before** any backend is invoked, whether that backend is built-in, a `type: command` provider, or a plugin-registered provider. Lets a plugin steer the transcription request itself instead of only observing the transcript afterwards.