The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): bind session context for plugin slash command handlers
chelsealong5943347a2aa9
diff --git a/gateway/run.py b/gateway/run.pyindex 0c752565654..62f69cf98d0 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4281,6 +4281,17 @@ class GatewayRunner(from gateway.session_context import clear_session_varsclear_session_vars(tokens)+ @_contextmanager+ def _session_env_scope(self, context: SessionContext):+ """Bind session context variables for the duration of the block, e.g. a plugin command+ handler invoked outside the normal agent-turn path (``_set_session_env`` is otherwise only+ reached there). Always cleared on exit, including on exception."""+ tokens = self._set_session_env(context)+ try:+ yield+ finally:+ self._clear_session_env(tokens)+async def _run_in_executor_with_context(self, func, *args):"""Run blocking work in the thread pool while preserving session contextvars."""loop = asyncio.get_running_loop()diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 72e126098c8..b7e26d99cc5 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -26,7 +26,8 @@ from gateway.run_inbound_unauthorized import (unauthorized_owner_hint,)from gateway.session import (- SessionSource, is_shared_multi_user_session, neutralize_untrusted_inline_text+ SessionSource, build_session_context, is_shared_multi_user_session,+ neutralize_untrusted_inline_text,)from gateway.turn_lease import TurnLeaseTimeoutErrorfrom typing import Any, Dict, List, Optional, Tuple@@ -1058,9 +1059,17 @@ class GatewayInboundMixin:from hermes_cli.plugins import get_plugin_command_handlerplugin_handler = get_plugin_command_handler(command.replace("_", "-"))if plugin_handler:- result = plugin_handler(event.get_command_args().strip())- if asyncio.iscoroutine(result):- result = await result+ # The agent-turn path binds HERMES_SESSION_* via _set_session_env before running;+ # this dispatch sits outside that path, so a handler reading get_session_env()+ # (directly, or through code it calls: message delivery, cron, kanban, approvals)+ # would otherwise see an empty/stale session (#108698). No session_entry exists+ # yet here, so session_key is resolved from source instead of a persisted one.+ _plugin_context = build_session_context(source, self.config)+ _plugin_context.session_key = self._session_key_for_source(source)+ with self._session_env_scope(_plugin_context):+ result = plugin_handler(event.get_command_args().strip())+ if asyncio.iscoroutine(result):+ result = await resultreturn True, str(result) if result else None, commandexcept Exception as e:logger.warning("Plugin command dispatch failed: %s", e)diff --git a/tests/gateway/test_session_env.py b/tests/gateway/test_session_env.pyindex e40a5266e50..8206d85f537 100644--- a/tests/gateway/test_session_env.py+++ b/tests/gateway/test_session_env.py@@ -273,3 +273,46 @@ def test_cron_session_set_clear_and_reset_tristate(monkeypatch):reset_session_vars()assert get_session_env("HERMES_CRON_SESSION") == "1"++async def test_plugin_slash_command_sees_session_env(monkeypatch):+ """A plugin-registered slash command handler must see the same HERMES_SESSION_*+ contextvars an agent turn would for that event (#108698): the agent-turn path binds+ them via _set_session_env before running, but plugin command dispatch is a separate,+ earlier path that previously called the handler with nothing bound."""+ from gateway.config import GatewayConfig, PlatformConfig+ from gateway.platforms.event import MessageEvent++ monkeypatch.delenv("HERMES_SESSION_KEY", raising=False)+ monkeypatch.delenv("HERMES_SESSION_CHAT_ID", raising=False)++ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")})+ runner._draining = False++ source = SessionSource(+ platform=Platform.TELEGRAM, chat_id="c1", user_id="u1", user_name="tester", chat_type="dm",+ )+ event = MessageEvent(text="/gsd bind", source=source, message_id="m1")++ seen = {}++ def _handler(raw_args):+ seen["session_key"] = get_session_env("HERMES_SESSION_KEY")+ seen["chat_id"] = get_session_env("HERMES_SESSION_CHAT_ID")+ return f"Bound: {raw_args}"++ from hermes_cli import plugins as _plugins_mod+ monkeypatch.setattr(_plugins_mod, "get_plugin_command_handler",+ lambda name: _handler if name == "gsd-bind" else None)++ handled, result, command = await runner._hm_dispatch_quick_and_plugin_commands(event, source, "gsd_bind")++ assert handled is True+ assert result == "Bound: bind"+ assert seen["session_key"] == runner._session_key_for_source(source)+ assert seen["session_key"] != ""+ assert seen["chat_id"] == "c1"+ # Bound only for the handler call, not leaked past dispatch+ assert get_session_env("HERMES_SESSION_KEY") == ""+