Skip to content

The agent that grows with you

fix(gateway): run sync plugin command handlers off the event loop

Konstantin Khlopkove794bb31cb75
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index b7e26d99cc5..614434de50b 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -1059,17 +1059,22 @@ class GatewayInboundMixin:
from hermes_cli.plugins import get_plugin_command_handler
plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
if plugin_handler:
- # 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.
+ # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
+ # sits before it, so a handler reading get_session_env() would see an empty or a
+ # foreign (cron agent's os.environ) session (#108698). No session_entry exists 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).
_plugin_context = build_session_context(source, self.config)
_plugin_context.session_key = self._session_key_for_source(source)
+ user_args = event.get_command_args().strip()
with self._session_env_scope(_plugin_context):
- result = plugin_handler(event.get_command_args().strip())
- if asyncio.iscoroutine(result):
- result = await result
+ if asyncio.iscoroutinefunction(plugin_handler):
+ result = await plugin_handler(user_args)
+ else:
+ result = await self._run_in_executor_with_context(plugin_handler, user_args)
+ if asyncio.iscoroutine(result):
+ result = await result
return True, str(result) if result else None, command
except Exception as e:
logger.warning("Plugin command dispatch failed: %s", e)
diff --git a/tests/gateway/test_unknown_command.py b/tests/gateway/test_unknown_command.py
index abe23da48c6..e232e7a3c91 100644
--- a/tests/gateway/test_unknown_command.py
+++ b/tests/gateway/test_unknown_command.py
@@ -225,3 +225,38 @@ async def test_command_hook_rewrite_routes_to_plugin(monkeypatch):
# First emit_collect fires on the original command; after rewrite the
# dispatcher does NOT re-fire for the new command (one decision per turn).
assert call_log == ["command:status"]
+
+
+async def test_sync_plugin_command_runs_off_loop_thread(monkeypatch):
+ """A sync plugin handler doing blocking I/O must run off the gateway loop thread,
+ else the loop stops answering shutdown_watchdog probes and is killed with exit 75."""
+ import threading
+ import time
+
+ import gateway.run as gateway_run
+ from hermes_cli import plugins as _plugins_mod
+
+ runner = _make_runner()
+ seen_threads = []
+
+ def _blocking_handler(args: str) -> str:
+ seen_threads.append(threading.current_thread().name)
+ time.sleep(0.15)
+ return f"sync {args}"
+
+ monkeypatch.setattr(
+ _plugins_mod,
+ "get_plugin_command_handler",
+ lambda name: _blocking_handler if name == "slow-api" else None,
+ )
+ monkeypatch.setattr(
+ gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "***"}
+ )
+
+ result = await runner._handle_message(_make_event("/slow-api arg"))
+
+ assert result == "sync arg"
+ assert seen_threads, "handler must have run"
+ # pytest-asyncio runs the loop on the main thread; the blocking handler must not.
+ assert seen_threads[0] != threading.main_thread().name