The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): pass the calling session to plugin slash commands on every surface
Teknium09759375939f
diff --git a/cli.py b/cli.pyindex 44d80205755..7c7d80058a0 100644--- a/cli.py+++ b/cli.py@@ -1281,12 +1281,16 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,answered = gateway_plugin_commands.run(self, base_cmd.lstrip("/"), user_args)if answered:return answered # ran beside the plugin's hooks, tools and MCP servers in the gateway, or GONE+ from hermes_cli.plugin_command_dispatch import invoke_plugin_commandfrom hermes_cli.plugins import get_plugin_command_handler, resolve_plugin_command_resultplugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))if not plugin_handler:return+ session_id = getattr(self, "session_id", None) or ""try:- result = resolve_plugin_command_result(plugin_handler(user_args))+ result = resolve_plugin_command_result(invoke_plugin_command(+ plugin_handler, user_args, source=None, session_id=session_id, session_key=session_id,+ platform="cli"))if result:_cprint(str(result))except Exception as e:diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.pyindex 557f76ec732..e6bdf44b575 100644--- a/gateway/run_inbound_hooks.py+++ b/gateway/run_inbound_hooks.py@@ -273,17 +273,25 @@ class GatewayInboundHooksMixin:# message has none yet, so session_key is derived from source. Sync handlers run on the# gateway pool (contextvars carried), never the loop thread: blocking I/O there starves# the liveness watchdog and the process exits 75 mid-handler (#105279).+ if session_entry is None and getattr(self, "session_store", None) is not None:+ # The chat's current session, if it has one (lookup only: a command never creates one), so+ # HERMES_SESSION_ID / session_id name what a later /new reports as old_session_id (#123245).+ session_entry = await self.async_session_store.lookup_by_session_key(+ self._session_key_for_source(source))_plugin_context = build_session_context(source, self.config, session_entry)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 argsfrom hermes_cli.plugin_command_dispatch import invoke_plugin_command+ call = functools.partial(+ invoke_plugin_command, plugin_handler, user_args, source=source,+ session_id=_plugin_context.session_id or "", session_key=_plugin_context.session_key or "",+ platform=source.platform.value)with self._session_env_scope(_plugin_context):if inspect.iscoroutinefunction(plugin_handler):- result = await invoke_plugin_command(plugin_handler, user_args, source=source)+ result = await call()else:- result = await self._run_in_executor_with_context(- functools.partial(invoke_plugin_command, plugin_handler, user_args, source=source))+ result = await self._run_in_executor_with_context(call)if inspect.isawaitable(result):result = await resultreturn str(result) if result else Nonediff --git a/hermes_cli/plugin_command_dispatch.py b/hermes_cli/plugin_command_dispatch.pyindex 2e70bb8ff47..d0be9362520 100644--- a/hermes_cli/plugin_command_dispatch.py+++ b/hermes_cli/plugin_command_dispatch.py@@ -5,23 +5,25 @@ from __future__ import annotationsimport inspectfrom typing import Any, Callable+_KEYWORD_KINDS = (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)-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.+def invoke_plugin_command(handler: Callable, raw_args: str, **context: Any) -> Any:+ """Call *handler* once with *raw_args* plus the *context* keywords it declares.++ Every surface passes the same context (``source``, ``session_id``, ``session_key``,+ ``platform``); a handler opts in by naming any of them as keyword-capable parameters, or+ takes them all with ``**kwargs``. Legacy ``fn(raw_args)`` handlers and opaque signatures keep+ the one-argument call. Handler exceptions propagate; they are never retried as a legacy call."""try:- parameters = inspect.signature(handler).parameters.values()+ parameters = list(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)+ return handler(raw_args)+ if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters):+ return handler(raw_args, **context)+ # The first positional parameter receives raw_args whatever its name.+ if parameters and parameters[0].kind is not inspect.Parameter.KEYWORD_ONLY:+ parameters = parameters[1:]+ accepted = {p.name for p in parameters if p.kind in _KEYWORD_KINDS}+ return handler(raw_args, **{k: v for k, v in context.items() if k in accepted})diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex a97bc1ef686..c7fad5e387d 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -647,7 +647,7 @@ class PluginContext:argument_mode: str | None = None,) -> Optional[PluginRegistration]:"""Register an in-session slash command (``/name``); handler ``fn(raw_args: str) -> str | None``- (sync or async). ``args_hint`` (e.g. ``"<file>"``) lets adapters like Discord surface an argument+ (sync or async), plus the session-context keywords it declares (``plugin_command_dispatch``). ``args_hint`` (e.g. ``"<file>"``) lets adapters like Discord surface an argumentfield; without it the command registers parameterless there but still accepts trailing text."""clean = name.lower().strip().lstrip("/").replace(" ", "-")if not clean:diff --git a/tests/gateway/test_session_env.py b/tests/gateway/test_session_env.pyindex 7f4812294fd..8d7693c3d94 100644--- a/tests/gateway/test_session_env.py+++ b/tests/gateway/test_session_env.py@@ -330,49 +330,40 @@ 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)++@pytest.mark.asyncio[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."""+async def test_plugin_slash_command_receives_calling_session(monkeypatch):+ """A gateway plugin command handler that opts in receives the calling chat's source and its+ current session id (the one a later /new reports as old_session_id, #123245); the bound+ HERMES_SESSION_ID agrees with it."""+ from datetime import datetime+ from unittest.mock import MagicMock+from gateway.config import GatewayConfig, PlatformConfigfrom gateway.platforms.event import MessageEvent+ from gateway.session import SessionEntryrunner = 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")+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="c1", user_id="u1", chat_type="dm")+ key = runner._session_key_for_source(source)+ runner.session_store = MagicMock()+ runner.session_store.lookup_by_session_key.side_effect = lambda k: SessionEntry(+ session_key=k, session_id="20261018_live", created_at=datetime.now(), updated_at=datetime.now(),+ ) if k == key else Noneseen = []- 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+ def _handler(raw_args, *, source, session_id, session_key, platform):+ seen.append((raw_args, source, session_id, session_key, platform, get_session_env("HERMES_SESSION_ID")))+ return "ok"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"- )+ monkeypatch.setattr(_plugins_mod, "get_plugin_command_handler", lambda name: _handler)- assert handled is True- assert result == "source delivered"- assert seen == [("details", source)]+ event = MessageEvent(text="/who details", source=source, message_id="m1")+ handled, result, _command = await runner._hm_dispatch_quick_and_plugin_commands(event, source, "who")+ assert (handled, result) == (True, "ok")+ assert seen == [("details", source, "20261018_live", key, "telegram", "20261018_live")]diff --git a/tests/hermes_cli/test_plugin_command_source.py b/tests/hermes_cli/test_plugin_command_source.pyindex 8a48934b520..f266db25106 100644--- a/tests/hermes_cli/test_plugin_command_source.py+++ b/tests/hermes_cli/test_plugin_command_source.py@@ -1,57 +1,24 @@-"""Compatibility behavior for gateway source delivery to plugin slash handlers."""--import pytest+"""Plugin slash-command handlers receive only the calling-session context they declare."""from hermes_cli.plugin_command_dispatch import invoke_plugin_command+CONTEXT = {"source": "src", "session_id": "sid", "session_key": "key", "platform": "telegram"}-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 test_handlers_get_only_the_context_they_declare():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"]+ return (raw_args,)+ def named(raw_args, *, session_id, platform):+ return raw_args, session_id, platform-def test_invoke_plugin_command_does_not_retry_handler_type_error():- calls = []+ def catch_all(args, **kwargs):+ return args, kwargs- def failing(raw_args, *, source):- calls.append((raw_args, source))- raise TypeError("handler body failed")+ def positional_only(raw_args, session_id=None, /): # cannot be passed by keyword: no opt-in+ return raw_args, session_id- source = object()- with pytest.raises(TypeError, match="handler body failed"):- invoke_plugin_command(failing, "args", source=source)- assert calls == [("args", source)]+ assert invoke_plugin_command(legacy, "a", **CONTEXT) == ("a",)+ assert invoke_plugin_command(named, "a", **CONTEXT) == ("a", "sid", "telegram")+ assert invoke_plugin_command(catch_all, "a", **CONTEXT) == ("a", CONTEXT)+ assert invoke_plugin_command(positional_only, "a", **CONTEXT) == ("a", None)diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 0666d6555ad..a5cd314117c 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -504,9 +504,13 @@ def _run_plugin_command(handler, arg: str, session=None) -> str:saw ``""`` or the launch process's inherited values. Same class as the messaging gateway's#108698; ``_set_session_context`` is the turn path's own seam."""plugins = _tools_mod("hermes_cli.plugins")- tokens = _set_session_context(session.get("session_key", "") or "", cwd=str(session.get("cwd") or "")) if session else []+ invoke = _tools_mod("hermes_cli.plugin_command_dispatch").invoke_plugin_command+ key = str(session.get("session_key") or "") if session else ""+ tokens = _set_session_context(key, cwd=str(session.get("cwd") or "")) if session else []+ context = {"source": None, "session_key": key, "platform": _session_source(session),+ "session_id": getattr(session.get("agent"), "session_id", None) or key if session else ""}try:- return str(plugins.resolve_plugin_command_result(handler(arg)) or "")+ return str(plugins.resolve_plugin_command_result(invoke(handler, arg, **context)) or "")finally:_clear_session_context(tokens)diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex d4bf03e299a..7e2fc1ccd63 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -1578,7 +1578,7 @@ After registration, users can type `/mystatus` in any session. The command appea| Parameter | Type | Description ||-----------|------|-------------|| `name` | `str` | Command name without the leading slash (e.g. `"lcm"`, `"mystatus"`) |-| `handler` | `Callable[[str], str \| None]` | Called with the raw argument string. May also be `async`. |+| `handler` | `Callable[[str], str \| None]` | Called with the raw argument string, plus any calling-session keywords it declares (see below). May also be `async`. || `description` | `str` | Shown in `/help`, autocomplete, and Telegram bot menu |**Key differences from `register_cli_command()`:**@@ -1587,28 +1587,33 @@ After registration, users can type `/mystatus` in any session. The command appea|---|---|---|| Invoked as | `/name` in a session | `hermes name` in a terminal || Where it works | CLI sessions, Telegram, Discord, etc. | Terminal only |-| Handler receives | Raw args string | argparse `Namespace` |+| Handler receives | Raw args string (+ opt-in session context) | argparse `Namespace` || Use case | Diagnostics, status, quick actions | Complex subcommand trees, setup wizards |**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.-**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:+**Calling-session context:** a handler can learn which chat and session invoked it by declaring any of these keyword parameters (or `**kwargs` for all of them). Handlers that declare none keep the one-argument `handler(raw_args)` call, so existing plugins are unaffected:-```python-from gateway.session import SessionSource+| Keyword | Value |+|---|---|+| `session_id` | The calling session's id (the one `on_session_reset` later reports as `old_session_id`). Empty when the chat has no session yet. |+| `session_key` | The routing key of the calling chat. |+| `platform` | Where the command came from: `telegram`, `discord`, …, `local` (CLI/Desktop sessions owned by the gateway), `cli`, `tui`, `desktop`. |+| `source` | The adapter-derived `gateway.session.SessionSource` (`user_id`, `chat_id`, `chat_type`, `thread_id`, …) when the gateway dispatched the command, else `None`. |++Every surface passes them: messaging platforms, the classic CLI, the TUI and Desktop. Sync handlers run in the gateway executor and async handlers are awaited, as before.+```python+def _handle_whoami(raw_args: str, *, session_id: str = "", platform: str = "", source=None) -> str:+ user = source.user_id if source is not None else "local user"+ return f"{user} on {platform}, session {session_id or '(none yet)'}"-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)+def register(ctx):+ ctx.register_command("whoami", handler=_handle_whoami, description="Show the calling session")```+`source` is transport identity, not an authorization grant: authorize from stable ids (`source.user_id`, `source.chat_id`), never from display names or the command text, and fail closed when a sensitive command gets `source=None`. Handler exceptions propagate; Hermes never retries the call with fewer arguments.+**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:- Return the text to show. `print()` writes to the gateway's stdout, and the user never sees it.@@ -1622,7 +1627,6 @@ def _handle_todo(raw_args: str) -> str:todo = resolve_agent_cwd() / "TODO.md" # the session's folder, not the gateway'sreturn 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 commandsdiff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 7f7d7e9317f..734cabf237d 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -129,7 +129,7 @@ A `/command` registered with `ctx.register_command()` runs in the gateway proces- **Return its text** instead of calling `print()`. Printed output goes to the gateway's stdout, not to the user's chat.- **Read the session's working directory with `agent.runtime_cwd.resolve_agent_cwd()`**, not `os.getcwd()`, which is the gateway's own directory. The gateway pins the session's directory while the handler runs.-- **Read session identity with `gateway.session_context.get_session_env("HERMES_SESSION_PLATFORM")`** (and the other `HERMES_SESSION_*` names, such as `HERMES_SESSION_ID` and `HERMES_SESSION_KEY`), not `os.environ`. These values are bound per session around the handler, so a background job the handler starts records the session as its parent.+- **Take the calling session as handler keywords**: declare `session_id`, `session_key`, `platform` or `source` (the sender's `SessionSource`) and Hermes passes them; one-argument handlers keep working unchanged. The same values are bound as `HERMES_SESSION_*` around the handler (`gateway.session_context.get_session_env`, never `os.environ`), so a background job the handler starts records the session as its parent.The classic CLI waits for the reply for as long as the handler runs. Ctrl+C stops the wait, not the handler: the handler finishes in the gateway and its reply is not shown. The command runs over its own connection to the gateway, so the session's prompts, interrupts and other commands are not held up while it runs.