Skip to content

The agent that grows with you

fix(serve): off-turn system-prompt rebuilds run under the session's profile scope

teknium180ab36e4a908
diff --git a/tests/tui_gateway/test_multi_profile_hosting_fail_closed.py b/tests/tui_gateway/test_multi_profile_hosting_fail_closed.py
index 39f9eee01ac..b0803927aa6 100644
--- a/tests/tui_gateway/test_multi_profile_hosting_fail_closed.py
+++ b/tests/tui_gateway/test_multi_profile_hosting_fail_closed.py
@@ -175,3 +175,48 @@ def test_launch_profile_agent_build_is_scoped_once_multiplexing(two_homes, monke
finally:
server._release_build_profile_scopes(scopes)
assert current_secret_scope() is None
+
+
+class _MemoryManager:
+ """Stands in for an external memory provider: ``system_prompt_block()`` reads its credential via get_secret."""
+ def build_system_prompt(self):
+ from agent.secret_scope import get_secret
+ from hermes_constants import get_hermes_home
+ return f"{get_hermes_home()}|{get_secret('MEM_PROVIDER_KEY')}"
+
+
+def _prompt_building_session(profile_home, key):
+ import threading
+ from types import SimpleNamespace
+ agent = SimpleNamespace(
+ _memory_manager=_MemoryManager(), _cached_system_prompt="", session_id=key, model="m", tools=[],
+ _session_db=SimpleNamespace(update_system_prompt=lambda sid, prompt: None))
+ agent._build_system_prompt = lambda system_message=None: agent._memory_manager.build_system_prompt()
+ return {"agent": agent, "history": [], "history_lock": threading.Lock(), "history_version": 0,
+ "running": False, "session_key": key, "profile_home": profile_home, "cwd": os.getcwd()}
+
+
+def test_off_turn_prompt_rebuilds_run_under_the_sessions_profile_scope(two_homes, monkeypatch):
+ """Regression for #112927: ``session.context_breakdown`` (Desktop refetches it after every turn) and the
+ model-switch prompt re-persist rebuilt the system prompt with no secret scope, so the external memory
+ provider's ``system_prompt_block()`` hit ``UnscopedSecretError`` on the LAUNCH profile once the process
+ hosted a second home — and for a secondary they resolved the launch profile's credential/home."""
+ import agent.system_prompt as system_prompt
+
+ root, b = two_homes
+ (root / ".env").write_text((root / ".env").read_text() + "MEM_PROVIDER_KEY=launch-mem-key\n")
+ (b / ".env").write_text((b / ".env").read_text() + "MEM_PROVIDER_KEY=b-mem-key\n")
+ monkeypatch.setattr(system_prompt, "build_system_prompt_parts",
+ lambda agent, system_message=None: {"stable": "", "context": "",
+ "volatile": agent._memory_manager.build_system_prompt()})
+ monkeypatch.setattr("agent.context_file_sources.context_file_sources_for_agent", lambda agent: [])
+ sessions = {"sa": _prompt_building_session(None, "sess-a"), "sb": _prompt_building_session(str(b), "sess-b")}
+ monkeypatch.setattr(server, "_sessions", sessions)
+ assert _probe("b")["b_ref"] == B_VAL # flips the process to fail-closed multi-profile hosting
+
+ for sid, home, key in (("sa", root, "launch-mem-key"), ("sb", b, "b-mem-key"), ("sa", root, "launch-mem-key")):
+ resp = server._methods["session.context_breakdown"]("rid", {"session_id": sid})
+ assert "error" not in resp, resp
+ server._persist_live_session_system_prompt(sessions[sid])
+ assert sessions[sid]["agent"]._cached_system_prompt == f"{home}|{key}"
+ assert os.environ.get("MEM_PROVIDER_KEY") is None
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index c0692aae042..652697b7dc4 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1217,15 +1217,18 @@ def _(rid, params: dict, session: dict) -> dict:
"model": _metadata_mirror(session).get("model", "")})
with session["history_lock"]:
history = list(session.get("history", []))
- # Bind the session context: on the RPC thread the session cwd is unset, so the prompt build
- # inside would key its workspace pin on the backend's cwd and overwrite the session's pin.
+ # Bind the session context (on the RPC thread the session cwd is unset, so the prompt build inside
+ # would key its workspace pin on the backend's cwd and overwrite the session's pin) and the session's
+ # profile runtime scope: the build reaches the external memory provider's system_prompt_block(),
+ # whose get_secret read fails closed once this process multiplexes (#112927).
tokens = _set_session_context(session["session_key"])
try:
from agent.context_breakdown import compute_session_context_breakdown
from agent.context_file_sources import context_file_sources_for_agent
- payload = compute_session_context_breakdown(agent, history)
- # Structured per-file rows so the Desktop popover can explain "why is my CLAUDE.md ignored?".
- payload["context_files"] = context_file_sources_for_agent(agent)
+ with _session_profile_runtime_scope(session):
+ payload = compute_session_context_breakdown(agent, history)
+ # Structured per-file rows so the Desktop popover can explain "why is my CLAUDE.md ignored?".
+ payload["context_files"] = context_file_sources_for_agent(agent)
return _ok(rid, payload)
except Exception as exc:
return _err(rid, 5000, f"Could not compute context breakdown: {exc}")
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 102bcf3d1a0..92d11d92513 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1639,22 +1639,19 @@ def _persist_live_session_system_prompt(session: dict | None) -> None:
if live is None or not hasattr(live[0], "_build_system_prompt") or not hasattr(live[2], "update_system_prompt"):
return
agent, session_key, db = live
- # Re-bind the session's profile HERMES_HOME (the build's finally reset it → root profile's SOUL.md/skills)
- # and session context (on the RPC thread _SESSION_CWD is unset → the process TERMINAL_CWD would persist).
- # Without this, _start_agent_build's finally block has already reset the override and the rebuilt prompt
- # silently uses the root profile's SOUL.md and skills. See issue #50233.
- profile_home = session.get("profile_home")
- home_token = set_hermes_home_override(profile_home) if profile_home else None
+ # Re-bind the session's profile runtime scope (the build's finally reset it → root profile's SOUL.md/skills,
+ # #50233) and session context (on the RPC thread _SESSION_CWD is unset → the process TERMINAL_CWD would
+ # persist). The full scope, not HERMES_HOME alone: the external memory provider's system_prompt_block()
+ # reads its credential through get_secret, which fails closed once this process multiplexes (#112927).
session_tokens = _set_session_context(session_key, cwd=_session_cwd(session))
try:
- prompt = agent._cached_system_prompt = agent._build_system_prompt(None)
+ with _session_profile_runtime_scope(session):
+ prompt = agent._cached_system_prompt = agent._build_system_prompt(None)
db.update_system_prompt(getattr(agent, "session_id", None) or session_key, prompt)
except Exception:
logger.warning("failed to persist live session system prompt for session %s", session_key, exc_info=True)
finally:
_clear_session_context(session_tokens)
- if home_token is not None:
- reset_hermes_home_override(home_token)
# Stable leading text of the model-switch marker (builder + dedup); only the newest marker is meaningful.