Skip to content

The agent that grows with you

fix(gateway): bind the calling session's id around a CLI plugin command

unsupportedpastels6c296165e49f
diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.py
index 5614ba5a124..40bb54cdee0 100644
--- a/gateway/run_inbound_hooks.py
+++ b/gateway/run_inbound_hooks.py
@@ -249,18 +249,20 @@ class GatewayInboundHooksMixin:
return False, None, command
async def _hm_run_plugin_handler(
- self, plugin_handler, event: MessageEvent, source: SessionSource
+ self, plugin_handler, event: MessageEvent, source: SessionSource, session_entry=None
) -> Optional[str]:
"""Run a resolved plugin command handler for *source* → its reply text or None; raises what
the handler raises (``gateway/session_commands.py`` resolves the exact registered name)."""
# 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)
+ # foreign (cron agent's os.environ) session (#108698). A local session's command
+ # passes its live *session_entry* (key and id, as its turns bind them); a messaging
+ # 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).
+ _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()
with self._session_env_scope(_plugin_context):
if asyncio.iscoroutinefunction(plugin_handler):
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index d1a3277b21b..d95d36ca644 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -165,8 +165,11 @@ async def _run_runner_command(runner, live, name, arg, kind, shell):
if handler is None:
raise RuntimeStoreError('unsupported_command')
event = MessageEvent(text='/' + name + (' ' + arg if arg else ''), source=live.source)
+ # The session's own entry, so HERMES_SESSION_ID is bound as on its turns: a background job
+ # the handler starts records this session as its parent.
+ entry = await asyncio.to_thread(runner.session_store.lookup_by_session_key, live.route)
try:
- return await runner._hm_run_plugin_handler(handler, event, live.source)
+ return await runner._hm_run_plugin_handler(handler, event, live.source, entry)
except Exception as e: # main's CLI printed it; messaging (run_inbound_hooks) still only logs it
logger.warning("Plugin command dispatch failed: %s", e, exc_info=True)
return t('cli.plugin.command_error', error=str(e) or type(e).__name__)
diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.py
index b14be2e60b5..3a0de1fcf15 100644
--- a/tests/gateway/test_cli_plugin_command_in_gateway.py
+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py
@@ -45,6 +45,16 @@ def register(ctx):
"platform": get_session_env("HERMES_SESSION_PLATFORM"),
"key": get_session_env("HERMES_SESSION_KEY")})
ctx.register_command("probe-cwd", where, description="Where the handler runs")
+
+ def sid(arg): # the session a background job started from the handler records as its parent
+ from gateway.session_context import get_session_env
+ from tools.process_registry import process_registry
+ started = json.loads(ctx.dispatch_tool("terminal", {"command": "true", "background": True}))
+ job = process_registry.get(started.get("session_id") or "")
+ return "SID=" + json.dumps({"id": get_session_env("HERMES_SESSION_ID"),
+ "key": get_session_env("HERMES_SESSION_KEY"),
+ "parent": getattr(job, "parent_session_id", None), "started": started})
+ ctx.register_command("probe-sid", sid, description="The calling session")
'''
# One command per gateway life: A serves /alpha, the restarted B only /beta.
_LIFE = '''import os
@@ -159,7 +169,7 @@ def test_cli_plugin_command_runs_in_the_gateway_and_reaches_its_mcp_registry(tmp
out = capsys.readouterr().out
calls = list(wire.calls)
typed_outs = {}
- for typed in ('/probe_under', '/probe_only', '/probe-boom', '/probe-cwd'):
+ for typed in ('/probe_under', '/probe_only', '/probe-boom', '/probe-cwd', '/probe-sid'):
assert c._process_unregistered_slash(typed, typed) is True
typed_outs[typed] = capsys.readouterr().out
finally:
@@ -175,6 +185,10 @@ def test_cli_plugin_command_runs_in_the_gateway_and_reaches_its_mcp_registry(tmp
# the session's folder and session vars are bound around the handler; the process cwd is the gateway's
assert where['cwd'] == str(work) and where['getcwd'] != str(work), where
assert where['platform'] == 'local' and where['key'], where
+ # the calling session's identity, as a turn binds it: a background job records it as its parent
+ ident = json.loads(typed_outs['/probe-sid'].split('SID=', 1)[1].strip())
+ assert ident['id'] == sid and ident['key'] == where['key'], ident
+ assert ident['parent'] == sid, ident
assert proc.pid != os.getpid()
assert f'PLUGIN_PID={proc.pid} ' in out, out # the handler ran in the gateway process
mcp = json.loads(json.loads(out.split('MCP=', 1)[1].strip())['result'])