Skip to content

The agent that grows with you

feat(plugins): expose gateway source to slash handlers

ewtillman06e8c5bc7017
diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.py
index b97d084d404..557f76ec732 100644
--- a/gateway/run_inbound_hooks.py
+++ b/gateway/run_inbound_hooks.py
@@ -10,6 +10,8 @@ from __future__ import annotations
import asyncio
import contextlib
import dataclasses
+import functools
+import inspect
import logging
import os
import signal
@@ -275,11 +277,13 @@ class GatewayInboundHooksMixin:
if session_entry is None:
_plugin_context.session_key = self._session_key_for_source(source)
user_args = event.get_command_args().strip() if args is None else args
+ from hermes_cli.plugin_command_dispatch import invoke_plugin_command
with self._session_env_scope(_plugin_context):
- if asyncio.iscoroutinefunction(plugin_handler):
- result = await plugin_handler(user_args)
+ if inspect.iscoroutinefunction(plugin_handler):
+ result = await invoke_plugin_command(plugin_handler, user_args, source=source)
else:
- result = await self._run_in_executor_with_context(plugin_handler, user_args)
- if asyncio.iscoroutine(result):
+ result = await self._run_in_executor_with_context(
+ functools.partial(invoke_plugin_command, plugin_handler, user_args, source=source))
+ if inspect.isawaitable(result):
result = await result
return str(result) if result else None
diff --git a/hermes_cli/plugin_command_dispatch.py b/hermes_cli/plugin_command_dispatch.py
new file mode 100644
index 00000000000..2e70bb8ff47
--- /dev/null
+++ b/hermes_cli/plugin_command_dispatch.py
@@ -0,0 +1,27 @@
+"""Compatibility-aware call boundary for plugin slash-command handlers."""
+
+from __future__ import annotations
+
+import inspect
+from typing import Any, Callable
+
+
+def invoke_plugin_command(handler: Callable, raw_args: str, *, source: Any = None) -> Any:
+ """Call a handler once, passing gateway ``source`` only when its signature supports the keyword.
+
+ Opaque callables retain the legacy one-argument contract. Exceptions raised by the handler
+ propagate; they must not be mistaken for signature incompatibility and retried.
+ """
+ try:
+ parameters = inspect.signature(handler).parameters.values()
+ except (TypeError, ValueError):
+ parameters = ()
+ accepts_source = any(
+ (parameter.name == "source" and parameter.kind in {
+ inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY,
+ }) or parameter.kind == inspect.Parameter.VAR_KEYWORD
+ for parameter in parameters
+ )
+ if accepts_source:
+ return handler(raw_args, source=source)
+ return handler(raw_args)
diff --git a/tests/gateway/test_session_env.py b/tests/gateway/test_session_env.py
index ee41418d602..7f4812294fd 100644
--- a/tests/gateway/test_session_env.py
+++ b/tests/gateway/test_session_env.py
@@ -330,3 +330,49 @@ def test_set_session_env_binds_the_turn_session_id(monkeypatch):
tokens = runner._set_session_env(context)
assert get_session_env("HERMES_SESSION_ID") == "20261006_x"
runner._clear_session_env(tokens)
[email protected]("handler_kind", ["sync", "async", "returned_awaitable"])
+async def test_plugin_slash_command_receives_explicit_source(monkeypatch, handler_kind):
+ """Gateway opt-in passes the exact transport source across sync/async execution paths."""
+ from gateway.config import GatewayConfig, PlatformConfig
+ from gateway.platforms.event import MessageEvent
+
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")})
+ runner._draining = False
+ source = SessionSource(
+ platform=Platform.TELEGRAM, chat_id="synthetic-chat", user_id="synthetic-user",
+ user_name="untrusted display label", chat_type="dm",
+ )
+ event = MessageEvent(text="/source-check details", source=source, message_id="synthetic-message")
+ seen = []
+
+ async def _resolve(raw_args, received_source):
+ seen.append((raw_args, received_source))
+ return "source delivered"
+
+ if handler_kind == "async":
+ async def _async_handler(raw_args, *, source):
+ return await _resolve(raw_args, source)
+ handler = _async_handler
+ elif handler_kind == "returned_awaitable":
+ def _awaitable_handler(raw_args, *, source):
+ return _resolve(raw_args, source)
+ handler = _awaitable_handler
+ else:
+ def _sync_handler(raw_args, *, source):
+ seen.append((raw_args, source))
+ return "source delivered"
+ handler = _sync_handler
+
+ from hermes_cli import plugins as _plugins_mod
+ monkeypatch.setattr(_plugins_mod, "get_plugin_command_handler", lambda name: handler)
+
+ handled, result, _command = await runner._hm_dispatch_quick_and_plugin_commands(
+ event, source, "source-check"
+ )
+
+ assert handled is True
+ assert result == "source delivered"
+ assert seen == [("details", source)]
+
diff --git a/tests/hermes_cli/test_plugin_command_source.py b/tests/hermes_cli/test_plugin_command_source.py
new file mode 100644
index 00000000000..8a48934b520
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_command_source.py
@@ -0,0 +1,57 @@
+"""Compatibility behavior for gateway source delivery to plugin slash handlers."""
+
+import pytest
+
+from hermes_cli.plugin_command_dispatch import invoke_plugin_command
+
+
+def test_invoke_plugin_command_delivers_source_only_to_keyword_capable_parameters():
+ source = object()
+ seen = []
+
+ def keyword_only(raw_args, *, source):
+ seen.append((raw_args, source))
+ return "ok"
+
+ def keyword_capture(raw_args, **kwargs):
+ seen.append((raw_args, kwargs["source"]))
+ return "ok"
+
+ def positional_only(raw_args, source=None, /):
+ return raw_args, source
+
+ def positional_only_with_kwargs(raw_args, source=None, /, **kwargs):
+ seen.append((raw_args, kwargs["source"]))
+ return "ok"
+
+ assert invoke_plugin_command(keyword_only, "args", source=source) == "ok"
+ assert invoke_plugin_command(keyword_capture, "args", source=source) == "ok"
+ assert invoke_plugin_command(positional_only, "args", source=source) == ("args", None)
+ assert invoke_plugin_command(positional_only_with_kwargs, "args", source=source) == "ok"
+ assert seen == [("args", source)] * 3
+
+
+def test_invoke_plugin_command_keeps_legacy_contract_when_signature_is_opaque(monkeypatch):
+ calls = []
+
+ def legacy(raw_args):
+ calls.append(raw_args)
+ return "legacy"
+
+ monkeypatch.setattr("hermes_cli.plugin_command_dispatch.inspect.signature", lambda _handler: (_ for _ in ()).throw(ValueError()))
+
+ assert invoke_plugin_command(legacy, "args", source=object()) == "legacy"
+ assert calls == ["args"]
+
+
+def test_invoke_plugin_command_does_not_retry_handler_type_error():
+ calls = []
+
+ def failing(raw_args, *, source):
+ calls.append((raw_args, source))
+ raise TypeError("handler body failed")
+
+ source = object()
+ with pytest.raises(TypeError, match="handler body failed"):
+ invoke_plugin_command(failing, "args", source=source)
+ assert calls == [("args", source)]
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index 9e3e78dfd91..d4bf03e299a 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -1592,15 +1592,21 @@ After registration, users can type `/mystatus` in any session. The command appea
**Conflict protection:** If a plugin tries to register a name that conflicts with a built-in command (`help`, `model`, `new`, etc.), the registration is silently rejected with a log warning. Built-in commands always take precedence.
-**Async handlers:** The gateway dispatch automatically detects and awaits async handlers, so you can use either sync or async functions:
+**Gateway source context:** A gateway handler may opt into the adapter-derived `gateway.session.SessionSource` as a keyword-only `source` argument (or accept it through `**kwargs`). Sync handlers keep running in the gateway executor, and coroutine or returned-awaitable handlers are awaited as before:
```python
-async def _handle_check(raw_args: str) -> str:
- result = await some_async_operation()
- return f"Check result: {result}"
+from gateway.session import SessionSource
-def register(ctx):
- ctx.register_command("check", handler=_handle_check, description="Run async check")
+
+def _handle_admin(raw_args: str, *, source: SessionSource | None = None) -> str:
+ # Non-gateway invocation does not supply a source. Sensitive work must fail closed.
+ if source is None or source.user_id is None:
+ return "This command requires gateway identity context."
+ # Apply plugin-owned policy using stable transport identifiers; do not authorize
+ # from user_name/chat_name or command arguments.
+ if not plugin_policy.allows(source.platform, source.user_id, source.chat_id):
+ return "Not authorized."
+ return perform_allowed_action(raw_args)
```
**Where handlers run:** a slash command handler runs in the gateway process that owns the session, also when the user types the command in the classic `hermes chat` CLI. The handler is not running in the user's terminal or directory, so:
@@ -1616,6 +1622,7 @@ def _handle_todo(raw_args: str) -> str:
todo = resolve_agent_cwd() / "TODO.md" # the session's folder, not the gateway's
return todo.read_text() if todo.exists() else "No TODO.md here."
```
+The example's `plugin_policy` and action function are illustrative plugin-owned code, not Hermes APIs. The gateway preserves the existing session-context binding and sync-handler executor behavior. Legacy `handler(raw_args)` callbacks continue receiving only the raw argument string; CLI/non-gateway invocation also retains its existing one-argument contract. Hermes supplies `source=` only when the handler signature accepts that keyword (including `**kwargs`). A parameter named `source` that is positional-only does not opt in. The source describes transport/routing identity and is not an authorization grant: plugin policy remains responsible for each action, and display names are untrusted labels, not authorization evidence. If a sensitive operation requires gateway identity, reject a missing source rather than treating the non-gateway call as authorized. Exceptions raised inside a handler propagate through normal dispatch error handling; Hermes does not retry the callback as a legacy call.
### Dispatch tools from slash commands