Skip to content

The agent that grows with you

fix(gateway): bind the turn's session id in the task context

Teknium057078f5f538
diff --git a/gateway/run.py b/gateway/run.py
index 010cc71cf96..11e887f89e2 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4070,6 +4070,9 @@ class GatewayRunner(
scope_id=str(getattr(context.source, "scope_id", "") or ""),
parent_chat_id=str(getattr(context.source, "parent_chat_id", "") or ""),
session_key=context.session_key,
+ # A cached agent binds HERMES_SESSION_ID only on the turn that built it; every later turn
+ # (and a command it yields to the background) must still see its own session.
+ session_id=context.session_id or "",
message_id=str(context.source.message_id) if context.source.message_id else "",
profile=getattr(context.source, "profile", "") or "",
async_delivery=_async_delivery,
diff --git a/tests/gateway/test_session_env.py b/tests/gateway/test_session_env.py
index 8206d85f537..4ece2085238 100644
--- a/tests/gateway/test_session_env.py
+++ b/tests/gateway/test_session_env.py
@@ -316,3 +316,17 @@ async def test_plugin_slash_command_sees_session_env(monkeypatch):
# Bound only for the handler call, not leaked past dispatch
assert get_session_env("HERMES_SESSION_KEY") == ""
+
+
+def test_set_session_env_binds_the_turn_session_id(monkeypatch):
+ """A cached agent sets HERMES_SESSION_ID only on the turn that built it. Every later turn's
+ task context must still carry the session id, or a command yielded to the background
+ records no parent session and its completion is refused by the owner (admission_conflict)."""
+ runner = object.__new__(GatewayRunner)
+ source = SessionSource(platform=Platform.LOCAL, chat_id="local-abc", chat_type="dm", user_id="uid:1")
+ context = SessionContext(source=source, connected_platforms=[], home_channels={},
+ session_key="agent:main:local:dm:local-abc", session_id="20261006_x")
+ monkeypatch.setenv("HERMES_SESSION_ID", "stale-process-env")
+ tokens = runner._set_session_env(context)
+ assert get_session_env("HERMES_SESSION_ID") == "20261006_x"
+ runner._clear_session_env(tokens)