Skip to content

The agent that grows with you

fix(terminal,api-server): trim profile qualification of session-derived sandbox keys (#123989, salvage #124057 + #123991)

teknium124b1c32bd26a
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 9db30feba89..1f8b1fd3aed 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -1061,11 +1061,12 @@ def _derive_chat_session_id(system_prompt: Optional[str], first_user_message: st
profile: Optional[str] = None) -> str:
"""Stable session id from the system prompt + first user message (constant across all
turns of an Open WebUI-style conversation), so one Hermes session/sandbox is reused.
- ``profile`` namespaces the fingerprint: the id keys process-global resources (the session
- store; the persistent Docker sandbox labeled ``hermes-task-id``), so under
- ``gateway.multiplex_profiles`` two header-less conversations that open with identical text
- on different profiles must not land on one session/container (#123989)."""
- seed = f"{profile or 'default'}\0{system_prompt or ''}\n{first_user_message}"
+ A routed ``/p/<profile>/`` prefix namespaces the seed: the id keys process-wide state
+ (session store, per-session sandbox), so two profiles opening with identical text must not
+ collide (#123989). Default/standalone ids are unchanged so live conversations survive."""
+ seed = f"{system_prompt or ''}\n{first_user_message}"
+ if profile and profile != "default":
+ seed = f"{profile}\0{seed}"
digest = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:16]
return f"api-{digest}"
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index a050759d893..f9b50ec91f8 100644
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@ -712,10 +712,7 @@ class OpenAICompatRoutesMixin:
history = []
else:
# Stable id from the conversation fingerprint so Open WebUI-style clients map onto
- # one Hermes session. Namespaced by the routed profile: under multiplexing the id
- # keys process-global session stores and persistent sandboxes, and two header-less
- # conversations opening with identical text on different profiles must not share
- # one (#123989).
+ # one Hermes session; namespaced by the routed profile (#123989).
first_user = next(
(cm.get("content", "") for cm in conversation_messages if cm.get("role") == "user"), "")
session_id = _derive_chat_session_id(system_prompt, first_user, _api_request_profile.get())
diff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.py
index ae38c5b460e..80c7729b84d 100644
--- a/tests/gateway/test_api_server.py
+++ b/tests/gateway/test_api_server.py
@@ -13,6 +13,7 @@ Tests cover:
"""
import asyncio
+import hashlib
import json
import time
import types
@@ -1403,20 +1404,16 @@ class TestDeriveChatSessionId:
b = _derive_chat_session_id("You are a robot.", "Hello")
assert a != b
- def test_identical_text_on_different_profiles_yields_different_ids(self):
- """Under multiplexing the id keys process-global session stores and persistent Docker
- sandboxes (``hermes-task-id``): two header-less conversations opening with the same text
- on different profiles must not share one session/container (#123989)."""
- a = _derive_chat_session_id("sys", "hello", "default")
- b = _derive_chat_session_id("sys", "hello", "research")
- assert a != b
-
- def test_profile_none_matches_default_and_is_stable(self):
- """A standalone listener (no profile-prefix middleware, ContextVar default None) lands on
- the same namespace as an explicit ``default`` profile, and stays stable across turns."""
- assert _derive_chat_session_id("sys", "hello") == _derive_chat_session_id("sys", "hello", "default")
- assert _derive_chat_session_id("sys", "hello", "research") == _derive_chat_session_id(
- "sys", "hello", "research")
+ def test_routed_profile_namespaces_the_id_without_moving_default(self):
+ """Two header-less conversations opening with identical text on different profiles must
+ not share one session/sandbox key (#123989); default/standalone ids stay byte-identical
+ so live conversations survive the upgrade."""
+ legacy = "api-" + hashlib.sha256(b"sys\nhello").hexdigest()[:16]
+ assert _derive_chat_session_id("sys", "hello") == legacy
+ assert _derive_chat_session_id("sys", "hello", "default") == legacy
+ research = _derive_chat_session_id("sys", "hello", "research")
+ assert research != legacy
+ assert research == _derive_chat_session_id("sys", "hello", "research")
# ---------------------------------------------------------------------------
diff --git a/tests/tools/test_docker_session_isolation.py b/tests/tools/test_docker_session_isolation.py
index e45b62ce68d..237ce6c0c09 100644
--- a/tests/tools/test_docker_session_isolation.py
+++ b/tests/tools/test_docker_session_isolation.py
@@ -131,101 +131,51 @@ class TestSessionIsolationKeying:
class TestRoutedScopeQualification:
- """A routed profile scope must qualify raw per-session container keys (#123989).
-
- A multiplexed host serves every profile in one process, and header-less
- API-server clients derive the same fingerprint session id from identical
- opening messages. Under per-session isolation (container_persistent: false)
- the raw key was profile-blind: the second profile's turn attached to the
- first profile's sandbox. A ``HERMES_HOME`` override (multiplex turns —
- named AND default —, per-profile TUI/desktop RPC, cron ticks) now qualifies
- the key; CLI and single-profile gateways keep the historical raw key.
- """
-
- def test_no_override_keeps_raw_key(self, monkeypatch):
- _enable_isolation(monkeypatch)
- from hermes_constants import get_hermes_home_override
- assert get_hermes_home_override() is None
- assert terminal_tool._resolve_container_task_id("api-abc123") == "api-abc123"
+ """A routed profile must qualify session-derived keys (#123989): one multiplexed process,
+ two profiles, one colliding session id (header-less API fingerprint, shared DM chat id)
+ → distinct sandboxes and cwd records. No routed home → historical raw key."""
- def test_routed_profile_qualifies_the_key(self, monkeypatch, tmp_path):
- _enable_isolation(monkeypatch)
- home = tmp_path / "profiles" / "research"
- home.mkdir(parents=True)
- from hermes_constants import set_hermes_home_override, reset_hermes_home_override
- token = set_hermes_home_override(str(home))
- try:
- assert terminal_tool._resolve_container_task_id("api-abc123") == (
- f"profile:research:api-abc123")
- finally:
- reset_hermes_home_override(token)
+ def test_colliding_session_id_is_isolated_per_routed_profile(self, monkeypatch, tmp_path):
+ from agent import secret_scope
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
- def test_fingerprint_collision_isolated_across_profiles(self, monkeypatch, tmp_path):
- """The reported bug: same opening message, two profiles, one process."""
_enable_isolation(monkeypatch)
- from hermes_constants import set_hermes_home_override, reset_hermes_home_override
raw = "api-9a5f7809eec0aac1"
- keys = {}
+ assert terminal_tool._resolve_container_task_id(raw) == raw # CLI / standalone: unchanged
+ homes = {}
for name in ("research", "default"):
- home = tmp_path / "profiles" / name
- home.mkdir(parents=True)
- token = set_hermes_home_override(str(home))
+ homes[name] = tmp_path / "profiles" / name
+ homes[name].mkdir(parents=True)
+ secret_scope.set_multiplex_active(True)
+ try:
+ keys, cwds = {}, {}
+ for name in ("research", "default", "research"): # A → B → A
+ token = set_hermes_home_override(str(homes[name]))
+ try:
+ keys[name] = terminal_tool._resolve_container_task_id(raw)
+ terminal_tool.register_container_alias(f"child-{name}", raw)
+ assert terminal_tool._resolve_container_task_id(f"child-{name}") == keys[name]
+ if name not in cwds:
+ assert terminal_tool.get_session_cwd(raw) is None
+ terminal_tool.record_session_cwd(raw, f"/workspace/{name}")
+ cwds[name] = terminal_tool.get_session_cwd(raw)
+ finally:
+ reset_hermes_home_override(token)
+ assert keys["research"] == f"profile:research:{raw}"
+ assert keys["default"] == f"default:{raw}"
+ assert cwds == {"research": "/workspace/research", "default": "/workspace/default"}
+ token = set_hermes_home_override(str(homes["default"]))
try:
- keys[name] = terminal_tool._resolve_container_task_id(raw)
+ terminal_tool.clear_session_cwd(raw)
+ finally:
+ reset_hermes_home_override(token)
+ token = set_hermes_home_override(str(homes["research"]))
+ try:
+ assert terminal_tool.get_session_cwd(raw) == "/workspace/research"
finally:
reset_hermes_home_override(token)
- assert keys["research"] != keys["default"]
- assert keys["research"].endswith(f":{raw}")
- assert keys["default"].endswith(f":{raw}")
-
- def test_routed_subagent_alias_resolves_qualified_parent(self, monkeypatch, tmp_path):
- _enable_isolation(monkeypatch)
- home = tmp_path / "profiles" / "research"
- home.mkdir(parents=True)
- from hermes_constants import set_hermes_home_override, reset_hermes_home_override
- token = set_hermes_home_override(str(home))
- try:
- terminal_tool.register_container_alias("subagent-1", "api-abc123")
- assert terminal_tool._resolve_container_task_id("subagent-1") == (
- "profile:research:api-abc123")
- finally:
- reset_hermes_home_override(token)
-
- def test_cwd_records_qualified_symmetric(self, monkeypatch, tmp_path):
- _enable_isolation(monkeypatch)
- from hermes_constants import set_hermes_home_override, reset_hermes_home_override
- raw = "api-abc123"
- home_a = tmp_path / "profiles" / "research"
- home_a.mkdir(parents=True)
- token = set_hermes_home_override(str(home_a))
- try:
- terminal_tool.record_session_cwd(raw, "/workspace/a")
- assert terminal_tool.get_session_cwd(raw) == "/workspace/a"
- finally:
- reset_hermes_home_override(token)
- # A different profile's scope reads a different slot for the same raw id.
- home_b = tmp_path / "profiles" / "default"
- home_b.mkdir(parents=True)
- token = set_hermes_home_override(str(home_b))
- try:
- assert terminal_tool.get_session_cwd(raw) is None
- terminal_tool.record_session_cwd(raw, "/workspace/b")
- assert terminal_tool.get_session_cwd(raw) == "/workspace/b"
- terminal_tool.clear_session_cwd(raw)
- assert terminal_tool.get_session_cwd(raw) is None
- finally:
- reset_hermes_home_override(token)
- # Profile A's record is untouched by B's clear.
- token = set_hermes_home_override(str(home_a))
- try:
- assert terminal_tool.get_session_cwd(raw) == "/workspace/a"
finally:
- reset_hermes_home_override(token)
-
- def test_cwd_records_unqualified_without_override(self, monkeypatch, tmp_path):
- _enable_isolation(monkeypatch)
- terminal_tool.record_session_cwd("task-1", "/tmp/x")
- assert terminal_tool._session_cwd.get("task-1") == "/tmp/x"
+ secret_scope.set_multiplex_active(False)
class TestSessionScopedMountResolution:
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index a945515e795..fb72f8972a6 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -253,16 +253,8 @@ _container_alias_lock = threading.Lock()
def record_session_cwd(session_key: Optional[str], cwd: Optional[str]) -> None:
"""Record *cwd* as *session_key*'s working directory (after a completed
command, or on workspace-override registration). None/empty keys collapse
- to ``"default"``; non-string / empty cwds are ignored.
-
- Keys are qualified under a routed scope (``HERMES_HOME`` override): a
- multiplexed host serves every profile in one process, and header-less
- API-server clients derive the same fingerprint session id from identical
- opening messages, so a raw key would let profile B's ``cd`` land in
- profile A's session record (#123989). Read side qualifies identically,
- so all callers (terminal results, file-ops rescue, delegation cwd copy,
- code-execution lookup) stay consistent without per-site edits.
- """
+ to ``"default"``; non-string / empty cwds are ignored. Keys are routed-profile
+ qualified (:func:`_qualify_task_key`); the read/clear side qualifies identically."""
if not isinstance(cwd, str) or not cwd.strip():
return
key = _qualify_task_key(str(session_key or "default"))
@@ -273,8 +265,7 @@ def record_session_cwd(session_key: Optional[str], cwd: Optional[str]) -> None:
def get_session_cwd(session_key: Optional[str]) -> Optional[str]:
"""Recorded cwd for *session_key*, or None. No fallback chain on purpose:
- callers decide what an absent record means. None/empty keys read
- ``"default"``. Qualified the same way as :func:`record_session_cwd`."""
+ callers decide what an absent record means. None/empty keys read ``"default"``."""
with _session_cwd_lock:
return _session_cwd.get(_qualify_task_key(str(session_key or "default")))
@@ -472,36 +463,18 @@ def _routed_home_task_key(profile_scoped: bool) -> Optional[str]:
return f"home:{override}"
-def _home_scope_qualifier() -> str:
- """Profile/home qualifier prefix for task-keyed env records, or "" when none applies.
-
- A routed (``HERMES_HOME`` override) scope — every multiplexed gateway turn, default profile
- included — must not share *-keyed state with another profile just because the raw keys
- match. Under persistent Docker the container key already carries the profile (branches 3/4);
- this qualifier covers the remaining raw-id keys (session-isolated backends, cwd records).
- Mirrors :func:`_routed_home_task_key`'s naming: ``profile:<name>`` when the override resolves
- to a profile directory, else ``home:<realpath>``.
- """
- from hermes_constants import get_hermes_home_override, profile_name_for_home
-
- override = get_hermes_home_override()
- if not override:
- return ""
- profile = profile_name_for_home(override)
- if profile == "default":
- return "profile:default"
- if profile:
- return f"profile:{profile}"
- try:
- return f"home:{os.path.realpath(override)}"
- except OSError:
- return f"home:{override}"
-
-
def _qualify_task_key(key: str) -> str:
- """Prefix *key* with the active home qualifier when one is active, else return it."""
- qualifier = _home_scope_qualifier()
- return f"{qualifier}:{key}" if qualifier else key
+ """Prefix a session-derived key with the routed profile/home, or return it unchanged.
+
+ A multiplexed host serves every profile in one process, and session ids are not
+ profile-unique (a header-less API client's ``api-<digest>`` fingerprint, a DM chat id
+ shared by two bots), so raw session keys in ``_active_environments`` / ``_session_cwd``
+ would hand profile B the sandbox and cwd profile A created (#123989). Persistent Docker
+ already keys the profile (branches 3/4); this covers the per-session keys. CLI and
+ single-profile gateways (no routed home) keep the historical raw key.
+ """
+ scope = _routed_home_task_key(profile_scoped=True)
+ return f"{scope}:{key}" if scope else key
def _resolve_container_task_id(task_id: Optional[str]) -> str:
@@ -513,9 +486,7 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:
2. Per-session isolation (docker + ``container_persistent: false``): each
session's task_id is its own key (a fresh chat gets a fresh sandbox with only
ITS mounts); delegate_task children follow the alias registry to the parent.
- Under a routed scope the key is qualified with the profile/home
- (:func:`_qualify_task_key`) so two multiplex profiles whose fingerprint-derived
- session ids collide cannot share one sandbox (#123989).
+ Routed profiles qualify the key (:func:`_qualify_task_key`, #123989).
3. Session key present (WebUI per-session, gateway per-message): persistent
Docker is PROFILE-scoped — ``shared:<key>`` opt-in, else ``profile:<name>``,
with the default profile staying literally ``"default"`` so CLI and
@@ -531,14 +502,6 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:
return task_id
scope = _session_scope()
if task_id and scope.session_isolated:
- # Session-isolated backends (docker + container_persistent: false, plugin equivalents)
- # key the raw per-session id — which for header-less API-server clients is the
- # fingerprint-derived ``api-<digest>`` (#123989). A multiplexed host serves every profile
- # in ONE process, so two profiles whose conversations open with the same text share the
- # digest and, unqualified, would attach to each other's sandbox. A routed scope
- # (HERMES_HOME override — multiplex turns named AND default, per-profile TUI/desktop RPC,
- # cron ticks) therefore qualifies the key; plain CLI/single-profile gateways keep the
- # historical raw key.
return _qualify_task_key(_resolve_container_alias(task_id))
# Per-session isolation: when a session key is present (the WebUI streaming layer sets it per-session,
# the gateway per-message via contextvars), scope the container to it so switching profiles can't reuse
@@ -558,7 +521,7 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:
if not session_key:
return _routed_home_task_key(scope.docker_profile_scoped) or "default"
if not scope.docker_profile_scoped:
- return f"session:{session_key}"
+ return _qualify_task_key(f"session:{session_key}")
profile = _current_session_profile() or "default"
return "default" if profile == "default" else f"profile:{profile}"
@@ -1437,8 +1400,7 @@ def terminal_tool(
# Session key for cwd records: the contextvar doesn't cross tool-worker
# threads, so fall back to the raw task_id (the top-level agent's
- # session_key) as a stable anchor. Record/read functions qualify the
- # key under a routed scope (#123989), so every caller stays symmetric.
+ # session_key) as a stable anchor.
from tools.approval import get_current_session_key
session_key = get_current_session_key(default="") or (task_id or "")