The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): allow plugins to inject session messages
GodsBoyf46c600a547c
diff --git a/gateway/run.py b/gateway/run.pyindex 56fb67f23af..91c007b230b 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -11777,6 +11777,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._wire_teams_pipeline_runtime()self._running = True+ self._install_plugin_message_injector()self._update_runtime_status("running")# Loop-liveness heartbeat (#66892): an asyncio task so a frozen loop@@ -13249,6 +13250,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreturn time.monotonic() - _stop_started_atself._running = False+ self._clear_plugin_message_injector()self._draining = Truestop_watchdog = getattr(self, "_stop_systemd_watchdog", None)@@ -17060,6 +17062,119 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewexcept AttributeError:pass+ def _install_plugin_message_injector(self) -> None:+ """Publish this live gateway's plugin message scheduler."""+ from hermes_cli.plugins import get_plugin_manager++ get_plugin_manager().set_gateway_message_injector(+ self,+ self._schedule_plugin_message_injection,+ )++ def _clear_plugin_message_injector(self) -> None:+ """Remove this runner's scheduler without clobbering a newer owner."""+ from hermes_cli.plugins import get_plugin_manager++ get_plugin_manager().clear_gateway_message_injector(self)++ def _schedule_plugin_message_injection(+ self,+ *,+ session_key: str,+ content: str,+ plugin_id: str,+ ) -> bool:+ """Schedule a plugin-triggered turn on the live gateway loop."""+ loop = getattr(self, "_gateway_loop", None)+ if not getattr(self, "_running", False) or loop is None or loop.is_closed():+ return False++ coro = self._dispatch_plugin_message_injection(+ session_key=session_key,+ content=content,+ plugin_id=plugin_id,+ )+ try:+ current_loop = asyncio.get_running_loop()+ except RuntimeError:+ current_loop = None++ if current_loop is loop:+ try:+ future = loop.create_task(coro)+ except Exception:+ coro.close()+ logger.warning(+ "Plugin message injection scheduling failed",+ exc_info=True,+ )+ return False+ self._background_tasks.add(future)+ future.add_done_callback(self._background_tasks.discard)+ else:+ future = safe_schedule_threadsafe(+ coro,+ loop,+ logger=logger,+ log_message="Plugin message injection scheduling failed",+ log_level=logging.WARNING,+ )+ if future is None:+ return False++ def _log_result(completed) -> None:+ try:+ accepted = completed.result()+ except (asyncio.CancelledError, concurrent.futures.CancelledError):+ return+ except Exception:+ logger.warning(+ "Plugin message injection failed: plugin=%s session=%s",+ plugin_id,+ session_key,+ exc_info=True,+ )+ return+ if not accepted:+ logger.warning(+ "Plugin message injection was not routed: plugin=%s session=%s",+ plugin_id,+ session_key,+ )++ future.add_done_callback(_log_result)+ return True++ async def _dispatch_plugin_message_injection(+ self,+ *,+ session_key: str,+ content: str,+ plugin_id: str,+ ) -> bool:+ """Route a plugin-triggered turn through the session's live adapter."""+ entry = await self.async_session_store.lookup_by_session_key(session_key)+ if entry is None or entry.origin is None:+ return False++ source = dataclasses.replace(entry.origin)+ adapter = self._adapter_for_source(source)+ if adapter is None:+ return False++ event = MessageEvent(+ text=content,+ message_type=MessageType.TEXT,+ source=source,+ internal=True,+ metadata={+ "hermes_plugin_id": plugin_id,+ "hermes_plugin_injection": True,+ },+ )+ await adapter.handle_message(event)+ return True+def _get_cached_session_source(self, session_key: str):if not session_key:return Nonediff --git a/gateway/session.py b/gateway/session.pyindex d2c63aefdc4..d03348acb60 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -3423,6 +3423,14 @@ class SessionStore:return entryreturn None+ def lookup_by_session_key(self, session_key: str) -> Optional[SessionEntry]:+ """Return the persisted routing entry for an exact session key."""+ if not session_key:+ return None+ with self._lock:+ self._ensure_loaded_locked()+ return self._entries.get(session_key)+def peek_session_id(self, session_key: str) -> Optional[str]:"""Return the persisted session_id currently bound to a session key.diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 2c0bc429421..6a1dc9f1105 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -53,7 +53,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Unionfrom hermes_constants import get_hermes_homefrom utils import env_var_enabled, fast_safe_load-from hermes_cli.config import cfg_get+from hermes_cli.config import cfg_get, load_config_readonlyfrom hermes_cli.middleware import OBSERVER_SCHEMA_VERSION, VALID_MIDDLEWAREfrom hermes_cli.plugin_capabilities import ( # noqa: F401 — re-exportedCAPABILITY_REGISTRY,@@ -917,8 +917,14 @@ class PluginContext:# -- message injection --------------------------------------------------- def inject_message(self, content: str, role: str = "user") -> bool:- """Inject a message into the active conversation.+ def inject_message(+ self,+ content: str,+ role: str = "user",+ *,+ session_key: str | None = None,+ ) -> bool:+ """Inject a message into a CLI or gateway conversation.If the agent is idle (waiting for user input), this starts a new turn.If the agent is running, this interrupts and injects the message.@@ -926,22 +932,80 @@ class PluginContext:This enables plugins (e.g. remote control viewers, messaging bridges)to send messages into the conversation from external sources.+ Gateway injection requires an existing ``session_key`` and an explicit+ ``plugins.entries.<plugin_id>.allow_gateway_injection`` config grant.+ A ``True`` return means the live gateway accepted the request for+ asynchronous dispatch, not that platform delivery has completed.+Returns True if the message was queued successfully."""cli = self._manager._cli_ref- if cli is None:- logger.warning("inject_message: no CLI reference (not available in gateway mode)")+ msg = content if role == "user" else f"[{role}] {content}"++ if cli is not None:+ if getattr(cli, "_agent_running", False):+ # Agent is mid-turn - interrupt with the message+ cli._interrupt_queue.put(msg)+ else:+ # Agent is idle - queue as next input+ cli._pending_input.put(msg)+ return True++ if not session_key:+ logger.warning(+ "inject_message: gateway mode requires an existing session_key"+ )+ return False+ if not self._gateway_injection_allowed():+ plugin_id = self.manifest.key or self.manifest.name+ logger.warning(+ "inject_message: gateway injection denied for plugin %s; set "+ "plugins.entries.%s.allow_gateway_injection: true to allow it",+ plugin_id,+ plugin_id,+ )return False- msg = content if role == "user" else f"[{role}] {content}"+ if not self._manager.has_gateway_message_injector:+ logger.warning("inject_message: no live gateway is available")+ return False- if getattr(cli, "_agent_running", False):- # Agent is mid-turn — interrupt with the message- cli._interrupt_queue.put(msg)- else:- # Agent is idle — queue as next input- cli._pending_input.put(msg)- return True+ plugin_id = self.manifest.key or self.manifest.name+ try:+ return bool(+ self._manager.inject_gateway_message(+ session_key=session_key,+ content=msg,+ plugin_id=plugin_id,+ )+ )+ except Exception:+ logger.warning(+ "inject_message: gateway scheduling failed for plugin %s",+ plugin_id,+ exc_info=True,+ )+ return False++ def _gateway_injection_allowed(self) -> bool:+ """Return whether this plugin may trigger gateway session turns."""+ try:+ cfg = load_config_readonly() or {}+ except Exception:+ return False++ plugin_id = self.manifest.key or self.manifest.name+ return (+ cfg_get(+ cfg,+ "plugins",+ "entries",+ plugin_id,+ "allow_gateway_injection",+ default=False,+ )+ is True+ )# -- CLI command registration --------------------------------------------@@ -1770,6 +1834,7 @@ class PluginManager:self._system_prompt_sections: Dict[str, PluginSystemPromptSection] = {}self._discovered: bool = Falseself._cli_ref = None # Set by CLI after plugin discovery+ self._gateway_message_injector: tuple[object, Callable] | None = None# Plugin skill registry: qualified name → metadata dict.self._plugin_skills: Dict[str, Dict[str, Any]] = {}self._portable_mcp_servers: Dict[str, Dict[str, Any]] = {}@@ -1790,6 +1855,32 @@ class PluginManager:# Public# -----------------------------------------------------------------------+ @property+ def has_gateway_message_injector(self) -> bool:+ """Return whether a live gateway can accept plugin-triggered turns."""+ return self._gateway_message_injector is not None++ def set_gateway_message_injector(+ self,+ owner: object,+ injector: Callable[..., bool],+ ) -> None:+ """Publish a live gateway injector and its lifecycle owner."""+ self._gateway_message_injector = (owner, injector)++ def clear_gateway_message_injector(self, owner: object) -> None:+ """Clear the injector only when it still belongs to ``owner``."""+ registered = self._gateway_message_injector+ if registered is not None and registered[0] is owner:+ self._gateway_message_injector = None++ def inject_gateway_message(self, **kwargs: Any) -> bool:+ """Submit a plugin-triggered turn to the live gateway."""+ registered = self._gateway_message_injector+ if registered is None:+ return False+ return bool(registered[1](**kwargs))+def discover_and_load(self, force: bool = False) -> None:"""Scan all plugin sources and load each plugin found.diff --git a/tests/gateway/test_plugin_message_injection.py b/tests/gateway/test_plugin_message_injection.pynew file mode 100644index 00000000000..95a7c635202--- /dev/null+++ b/tests/gateway/test_plugin_message_injection.py@@ -0,0 +1,259 @@+"""Tests for plugin-triggered turns in existing gateway sessions."""++import asyncio+import concurrent.futures+from datetime import datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from gateway.config import Platform+from gateway.run import GatewayRunner+from gateway.session import SessionEntry, SessionSource+from hermes_cli.plugins import PluginManager+++def _entry(*, origin=True) -> SessionEntry:+ source = None+ if origin:+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="42",+ chat_type="dm",+ user_id="42",+ user_name="tester",+ )+ now = datetime.now()+ return SessionEntry(+ session_key="agent:main:telegram:dm:42",+ session_id="session-42",+ created_at=now,+ updated_at=now,+ origin=source,+ platform=Platform.TELEGRAM,+ )+++def _runner(entry: SessionEntry | None, adapter=None) -> GatewayRunner:+ runner = object.__new__(GatewayRunner)+ runner.session_store = SimpleNamespace()+ runner._async_session_store = SimpleNamespace(+ _store=runner.session_store,+ lookup_by_session_key=AsyncMock(return_value=entry)+ )+ runner.adapters = {Platform.TELEGRAM: adapter} if adapter else {}+ runner._profile_adapters = {}+ runner._running = True+ runner._background_tasks = set()+ return runner+++async def test_dispatch_uses_stored_origin_and_adapter_message_path():+ adapter = SimpleNamespace(handle_message=AsyncMock())+ entry = _entry()+ runner = _runner(entry, adapter)++ accepted = await runner._dispatch_plugin_message_injection(+ session_key=entry.session_key,+ content="check the deployment",+ plugin_id="notify-plugin",+ )++ assert accepted is True+ adapter.handle_message.assert_awaited_once()+ event = adapter.handle_message.await_args.args[0]+ assert event.text == "check the deployment"+ assert event.internal is True+ assert event.source == entry.origin+ assert event.source is not entry.origin+ assert event.metadata == {+ "hermes_plugin_id": "notify-plugin",+ "hermes_plugin_injection": True,+ }+++ ("entry", "with_adapter"),+ [+ (None, True),+ (_entry(origin=False), True),+ (_entry(), False),+ ],+)+async def test_dispatch_rejects_unroutable_session(entry, with_adapter):+ adapter = SimpleNamespace(handle_message=AsyncMock())+ runner = _runner(entry, adapter if with_adapter else None)++ accepted = await runner._dispatch_plugin_message_injection(+ session_key="agent:main:telegram:dm:42",+ content="wake up",+ plugin_id="notify-plugin",+ )++ assert accepted is False+ adapter.handle_message.assert_not_awaited()+++async def test_scheduler_submits_dispatch_on_live_gateway_loop():+ runner = _runner(_entry())+ runner._gateway_loop = asyncio.get_running_loop()+ runner._dispatch_plugin_message_injection = AsyncMock(return_value=True)++ assert runner._schedule_plugin_message_injection(+ session_key="agent:main:telegram:dm:42",+ content="wake up",+ plugin_id="notify-plugin",+ ) is True++ await asyncio.sleep(0)+ runner._dispatch_plugin_message_injection.assert_awaited_once_with(+ session_key="agent:main:telegram:dm:42",+ content="wake up",+ plugin_id="notify-plugin",+ )+++async def test_scheduler_ignores_same_loop_task_cancellation():+ runner = _runner(_entry())+ loop = asyncio.get_running_loop()+ runner._gateway_loop = loop+ callback_errors = []+ previous_handler = loop.get_exception_handler()+ loop.set_exception_handler(lambda _loop, context: callback_errors.append(context))++ blocker = asyncio.Event()++ async def _wait_for_cancellation(**_kwargs):+ await blocker.wait()++ runner._dispatch_plugin_message_injection = _wait_for_cancellation++ try:+ assert runner._schedule_plugin_message_injection(+ session_key="key",+ content="wake up",+ plugin_id="notify-plugin",+ ) is True++ task = next(iter(runner._background_tasks))+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ await asyncio.sleep(0)+ finally:+ loop.set_exception_handler(previous_handler)++ assert callback_errors == []+++def test_scheduler_uses_threadsafe_bridge_outside_gateway_loop():+ runner = _runner(_entry())+ loop = MagicMock()+ loop.is_closed.return_value = False+ runner._gateway_loop = loop++ def _submit(coro, target_loop, **_kwargs):+ assert target_loop is loop+ coro.close()+ future = concurrent.futures.Future()+ future.set_result(True)+ return future++ with patch("gateway.run.safe_schedule_threadsafe", side_effect=_submit) as submit:+ assert runner._schedule_plugin_message_injection(+ session_key="key",+ content="wake up",+ plugin_id="notify-plugin",+ ) is True++ submit.assert_called_once()+++def test_scheduler_ignores_threadsafe_future_cancellation():+ runner = _runner(_entry())+ loop = MagicMock()+ loop.is_closed.return_value = False+ runner._gateway_loop = loop++ def _submit(coro, _target_loop, **_kwargs):+ coro.close()+ future = concurrent.futures.Future()+ future.cancel()+ return future++ with (+ patch("gateway.run.safe_schedule_threadsafe", side_effect=_submit),+ patch("gateway.run.logger.warning") as warning,+ ):+ assert runner._schedule_plugin_message_injection(+ session_key="key",+ content="wake up",+ plugin_id="notify-plugin",+ ) is True++ warning.assert_not_called()+++def test_scheduler_rejects_stopped_or_closed_gateway():+ runner = _runner(_entry())+ loop = MagicMock()+ loop.is_closed.return_value = False+ runner._gateway_loop = loop+ runner._running = False++ assert runner._schedule_plugin_message_injection(+ session_key="key",+ content="wake up",+ plugin_id="notify-plugin",+ ) is False+ loop.call_soon_threadsafe.assert_not_called()++ runner._running = True+ loop.is_closed.return_value = True+ assert runner._schedule_plugin_message_injection(+ session_key="key",+ content="wake up",+ plugin_id="notify-plugin",+ ) is False+ loop.call_soon_threadsafe.assert_not_called()+++def test_scheduler_rejects_submission_failure():+ runner = _runner(_entry())+ loop = MagicMock()+ loop.is_closed.return_value = False+ runner._gateway_loop = loop++ with patch("gateway.run.safe_schedule_threadsafe", return_value=None):+ assert runner._schedule_plugin_message_injection(+ session_key="key",+ content="wake up",+ plugin_id="notify-plugin",+ ) is False+++def test_install_and_clear_gateway_injector_preserves_newer_owner():+ runner = _runner(_entry())+ manager = PluginManager()++ with patch("hermes_cli.plugins.get_plugin_manager", return_value=manager):+ runner._install_plugin_message_injector()+ assert manager.has_gateway_message_injector is True++ runner._clear_plugin_message_injector()+ assert manager.has_gateway_message_injector is False++ runner._install_plugin_message_injector()++ newer_owner = MagicMock()+ newer_injector = MagicMock(return_value=True)+ manager.set_gateway_message_injector(newer_owner, newer_injector)+ runner._clear_plugin_message_injector()++ assert manager.has_gateway_message_injector is True+ assert manager.inject_gateway_message(value="kept") is True+ newer_injector.assert_called_once_with(value="kept")diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.pyindex 9b68bbc352b..d8e535eeb77 100644--- a/tests/gateway/test_session.py+++ b/tests/gateway/test_session.py@@ -543,7 +543,7 @@ class TestSessionStoreSwitchSession:db.close()-class TestSessionStoreLookupBySessionId:+class TestSessionStoreLookup:@pytest.fixture()def store(self, tmp_path):config = GatewayConfig()@@ -566,6 +566,19 @@ class TestSessionStoreLookupBySessionId:assert store.lookup_by_session_id("missing") is Noneassert store.lookup_by_session_id("") is None+ def test_returns_exact_existing_route(self, store):+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="42",+ chat_type="dm",+ user_id="42",+ )+ entry = store.get_or_create_session(source)++ assert store.lookup_by_session_key(entry.session_key) is entry+ assert store.lookup_by_session_key("agent:main:telegram:dm:missing") is None+ assert store.lookup_by_session_key("") is None+class TestSlackWorkspaceSessionIsolation:@pytest.fixture()diff --git a/tests/hermes_cli/test_plugin_message_injection.py b/tests/hermes_cli/test_plugin_message_injection.pynew file mode 100644index 00000000000..784ac174ccb--- /dev/null+++ b/tests/hermes_cli/test_plugin_message_injection.py@@ -0,0 +1,170 @@+"""Tests for plugin message injection across CLI and gateway hosts."""++from queue import SimpleQueue+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import yaml++from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+++def _context(name: str = "notify-plugin") -> tuple[PluginContext, PluginManager]:+ manager = PluginManager()+ manifest = PluginManifest(name=name, key=name, source="user")+ return PluginContext(manifest, manager), manager+++def _write_plugin_config(tmp_path, monkeypatch, entry: dict) -> None:+ hermes_home = tmp_path / "hermes"+ hermes_home.mkdir()+ (hermes_home / "config.yaml").write_text(+ yaml.safe_dump({"plugins": {"entries": {"notify-plugin": entry}}})+ )+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+++def test_cli_idle_injection_keeps_existing_queue_behaviour():+ context, manager = _context()+ cli = SimpleNamespace(+ _agent_running=False,+ _pending_input=SimpleQueue(),+ _interrupt_queue=SimpleQueue(),+ )+ manager._cli_ref = cli++ assert context.inject_message("new input") is True+ assert cli._pending_input.get_nowait() == "new input"+ assert cli._interrupt_queue.empty()+++def test_cli_running_injection_keeps_existing_interrupt_behaviour():+ context, manager = _context()+ cli = SimpleNamespace(+ _agent_running=True,+ _pending_input=SimpleQueue(),+ _interrupt_queue=SimpleQueue(),+ )+ manager._cli_ref = cli++ assert context.inject_message("status", role="system") is True+ assert cli._interrupt_queue.get_nowait() == "[system] status"+ assert cli._pending_input.empty()+++def test_gateway_injection_requires_session_key(tmp_path, monkeypatch):+ _write_plugin_config(+ tmp_path,+ monkeypatch,+ {"allow_gateway_injection": True},+ )+ context, manager = _context()+ injector = MagicMock(return_value=True)+ manager.set_gateway_message_injector(object(), injector)++ assert context.inject_message("wake up") is False+ injector.assert_not_called()+++def test_gateway_injection_requires_explicit_permission(tmp_path, monkeypatch):+ _write_plugin_config(tmp_path, monkeypatch, {})+ context, manager = _context()+ injector = MagicMock(return_value=True)+ manager.set_gateway_message_injector(object(), injector)++ assert context.inject_message(+ "wake up",+ session_key="agent:main:telegram:dm:42",+ ) is False+ injector.assert_not_called()+++def test_gateway_injection_does_not_treat_string_as_permission(tmp_path, monkeypatch):+ _write_plugin_config(+ tmp_path,+ monkeypatch,+ {"allow_gateway_injection": "false"},+ )+ context, manager = _context()+ injector = MagicMock(return_value=True)+ manager.set_gateway_message_injector(object(), injector)++ assert context.inject_message(+ "wake up",+ session_key="agent:main:telegram:dm:42",+ ) is False+ injector.assert_not_called()+++def test_gateway_injection_fails_closed_when_config_cannot_be_read():+ context, manager = _context()+ injector = MagicMock(return_value=True)+ manager.set_gateway_message_injector(object(), injector)++ with patch(+ "hermes_cli.plugins.load_config_readonly",+ side_effect=OSError("config unavailable"),+ ):+ assert context.inject_message(+ "wake up",+ session_key="agent:main:telegram:dm:42",+ ) is False++ injector.assert_not_called()+++def test_gateway_injection_requires_live_host(tmp_path, monkeypatch):+ _write_plugin_config(+ tmp_path,+ monkeypatch,+ {"allow_gateway_injection": True},+ )+ context, manager = _context()++ assert manager.has_gateway_message_injector is False+ assert context.inject_message(+ "wake up",+ session_key="agent:main:telegram:dm:42",+ ) is False+++def test_gateway_injection_passes_host_owned_plugin_identity(tmp_path, monkeypatch):+ _write_plugin_config(+ tmp_path,+ monkeypatch,+ {"allow_gateway_injection": True},+ )+ context, manager = _context()+ injector = MagicMock(return_value=True)+ manager.set_gateway_message_injector(object(), injector)++ result = context.inject_message(+ "wake up",+ role="system",+ session_key="agent:main:telegram:dm:42",+ )++ assert result is True+ injector.assert_called_once_with(+ session_key="agent:main:telegram:dm:42",+ content="[system] wake up",+ plugin_id="notify-plugin",+ )+++def test_gateway_injection_returns_host_rejection(tmp_path, monkeypatch):+ _write_plugin_config(+ tmp_path,+ monkeypatch,+ {"allow_gateway_injection": True},+ )+ context, manager = _context()+ manager.set_gateway_message_injector(+ object(),+ MagicMock(return_value=False),+ )++ assert context.inject_message(+ "wake up",+ session_key="agent:main:telegram:dm:42",+ ) is Falsediff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex bdb790cb2a0..89f0eded33b 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -103,7 +103,7 @@ Every `ctx.*` API below is available inside a plugin's `register(ctx)` function.| Add slash commands | `ctx.register_command(name, handler, description)` — adds `/name` in CLI and gateway sessions || Dispatch tools from commands | `ctx.dispatch_tool(name, args)` — invokes a registered tool with parent-agent context auto-wired || Add CLI commands | `ctx.register_cli_command(name, help, setup_fn, handler_fn)` — adds `hermes <plugin> <subcommand>` |-| Inject messages | `ctx.inject_message(content, role="user")` — see [Injecting Messages](#injecting-messages) |+| Inject messages | `ctx.inject_message(content, role="user", session_key=...)` - see [Injecting Messages](#injecting-messages) || Ship data files | `Path(__file__).parent / "data" / "file.yaml"` || Bundle skills | `ctx.register_skill(name, path)` — namespaced as `plugin:skill`, loaded via `skill_view("plugin:skill")` || Gate on env vars | `requires_env: [API_KEY]` in plugin.yaml — prompted during `hermes plugins install` |@@ -448,25 +448,54 @@ In a running session, `/plugins` shows which plugins are currently loaded.## Injecting Messages-Plugins can inject messages into the active conversation using `ctx.inject_message()`:+Plugins can inject messages into a CLI conversation or a known gateway session using `ctx.inject_message()`:```python+# Active CLI conversationctx.inject_message("New data arrived from the webhook", role="user")++# Existing gateway conversation+ctx.inject_message(+ "New data arrived from the webhook",+ role="user",+ session_key="agent:main:telegram:dm:123456789",+)```-**Signature:** `ctx.inject_message(content: str, role: str = "user") -> bool`+**Signature:** `ctx.inject_message(content: str, role: str = "user", *, session_key: str | None = None) -> bool`-How it works:+In CLI mode:- If the agent is **idle** (waiting for user input), the message is queued as the next input and starts a new turn.- If the agent is **mid-turn** (actively running), the message interrupts the current operation — the same as a user typing a new message and pressing Enter.- For non-`"user"` roles, the content is prefixed with `[role]` (e.g. `[system] ...`).-- Returns `True` if the message was queued successfully, `False` if no CLI reference is available (e.g. in gateway mode).+- Returns `True` if the message was queued successfully.++In gateway mode:++- `session_key` is required and must identify an existing gateway session. It is the stable routing key, not the CLI session ID.+- Hermes reuses that session's stored platform, chat, thread, profile, and conversation history. Plugins cannot supply a new chat route through this API.+- The request enters the platform adapter's normal message path. Active sessions use the existing busy-session queue rather than starting a competing turn.+- Returns `True` when the live gateway accepts the request for asynchronous dispatch. This does not confirm that the agent turn or platform delivery has completed.+- Returns `False` when `session_key` is omitted, the permission is not granted, or no live gateway can accept the request. Unknown or unroutable session keys discovered after asynchronous acceptance are written to the gateway log.This enables plugins like remote control viewers, messaging bridges, or webhook receivers to feed messages into the conversation from external sources.+Gateway injection can send an agent response to an external messaging platform. It is disabled by default for every plugin. Grant it per plugin in `config.yaml`:++```yaml+plugins:+ entries:+ my-plugin:+ allow_gateway_injection: true+```++:::warning+Only grant gateway injection to plugins you trust. Hermes checks this host API permission and restricts it to existing session routes, but Python plugins run in-process and this setting is not a sandbox.+:::+:::note-`inject_message` is only available in CLI mode. In gateway mode, there is no CLI reference and the method returns `False`.+This plugin API does not expose a public HTTP endpoint or CLI command for external processes. The plugin must already know the target gateway `session_key`, for example from its own trusted configuration or previously retained session state.:::See the **[full guide](/developer-guide/plugins)** for handler contracts, schema format, hook behavior, error handling, and common mistakes.