The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): persistent Docker containers are profile-scoped, not per-session
Teknium15f7b7293cbe
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 00304f30c73..f91a83a5031 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -1531,41 +1531,59 @@ def _parse_docker_volume_mounts() -> List[Tuple[Path, Path]]:return mounts-def _docker_sandbox_dir_name(session_key: str = "") -> str:- """Host sandbox directory name for a session's persistent Docker container.+def _docker_sandbox_dir_candidates(session_key: str = "") -> List[str]:+ """Candidate host sandbox dir names for the delivering session, best first.- Mirrors ``_resolve_container_task_id(None)`` (tools/terminal_tool.py):- gateway sessions key their container ``session:<session_key>`` and- tools/environments/docker.py names the host directory after- :func:`sanitize_task_id_for_path` of that id. Contexts without a session- key share the historical ``default`` sandbox.+ Mirrors ``_resolve_container_task_id`` (tools/terminal_tool.py). Persistent+ Docker containers are PROFILE-scoped: the default profile uses the literal+ ``default`` sandbox (shared with CLI), other profiles use+ ``sanitize_task_id_for_path("profile:<name>")``. Legacy per-session+ sandboxes created while commit a270c4ade's ungated session fallback was+ live (``session:<session_key>``) are kept as a fallback candidate so+ files produced in that window still deliver (self-heal, no migration).Takes the key explicitly because the delivery pipeline runs after``_handle_message_with_agent`` cleared the turn's session contextvars(#93950) — an ambient lookup here would silently collapse onto``default`` and miss the session's real sandbox."""- if not session_key:- return "default"+ candidates: List[str] = []try:from tools.environments.base import sanitize_task_id_for_path-- return sanitize_task_id_for_path(f"session:{session_key}")except Exception:- return "default"-+ return ["default"]+ try:+ from hermes_cli.profiles import get_active_profile_name-def _default_docker_workspace_host_root(session_key: str = "") -> Optional[Path]:- """Host path for this session's persistent ``/workspace`` mount."""+ profile = get_active_profile_name() or "default"+ except Exception:+ profile = "default"+ if profile != "default":+ candidates.append(sanitize_task_id_for_path(f"profile:{profile}"))+ candidates.append("default")+ if session_key:+ # Bug-window legacy layout: per-session sandboxes.+ candidates.append(sanitize_task_id_for_path(f"session:{session_key}"))+ return candidates+++def _default_docker_workspace_host_roots(session_key: str = "") -> List[Path]:+ """Existing host-path candidates for the persistent ``/workspace`` mount.++ Ordered best-first (active profile layout, then the legacy bug-window+ per-session layout). The translator tries each until the requested file+ actually resolves — the profile sandbox dir existing does not mean the+ file lives there when it was produced in a legacy per-session container.+ """if os.getenv("TERMINAL_ENV", "").strip().lower() != "docker":- return None+ return []if os.getenv("TERMINAL_CONTAINER_PERSISTENT", "true").strip().lower() not in {"1","true","yes","on",}:- return None+ return []# Explicit cwd mount takes over /workspace when enabled.if os.getenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in {"1",@@ -1577,46 +1595,51 @@ def _default_docker_workspace_host_root(session_key: str = "") -> Optional[Path]try:host = Path(os.path.expanduser(cwd)).resolve(strict=False)except (OSError, RuntimeError, ValueError):- return None- return host if host.is_dir() else None+ return []+ return [host] if host.is_dir() else []try:from tools.environments.base import get_sandbox_dir- root = (- get_sandbox_dir() / "docker" / _docker_sandbox_dir_name(session_key) / "workspace"- ).resolve(strict=False)+ base = get_sandbox_dir() / "docker"+ roots = []+ for name in _docker_sandbox_dir_candidates(session_key):+ cand = (base / name / "workspace").resolve(strict=False)+ if cand.is_dir():+ roots.append(cand)except Exception:- return None- return root if root.is_dir() else None+ return []+ return roots-def _docker_persistent_home_host_root(session_key: str = "") -> Optional[Path]:- """Host path for this session's persistent ``/root`` home mount.+def _docker_persistent_home_host_roots(session_key: str = "") -> List[Path]:+ """Existing host-path candidates for the persistent ``/root`` home mount.Persistent containers bind ``<sandbox>/docker/<task>/home`` to ``/root``(tools/environments/docker.py), so an agent that writes ``/root/out.png``- produced a real host file the gateway couldn't find. The task directory- is derived from the delivering session's key so session-scoped sandboxes- resolve to the container that produced the file (#93950).+ produced a real host file the gateway couldn't find. Ordered best-first:+ the profile-scoped layout, then the legacy bug-window per-session layout."""if os.getenv("TERMINAL_ENV", "").strip().lower() != "docker":- return None+ return []if os.getenv("TERMINAL_CONTAINER_PERSISTENT", "true").strip().lower() not in {"1","true","yes","on",}:- return None+ return []try:from tools.environments.base import get_sandbox_dir- root = (- get_sandbox_dir() / "docker" / _docker_sandbox_dir_name(session_key) / "home"- ).resolve(strict=False)+ base = get_sandbox_dir() / "docker"+ roots = []+ for name in _docker_sandbox_dir_candidates(session_key):+ cand = (base / name / "home").resolve(strict=False)+ if cand.is_dir():+ roots.append(cand)except Exception:- return None- return root if root.is_dir() else None+ return []+ return rootsdef _cache_dir_container_mounts() -> List[Tuple[Path, Path]]:@@ -1685,15 +1708,16 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = "mounts = list(_parse_docker_volume_mounts())mounts.extend(_cache_dir_container_mounts())- # Synthetic /workspace mount for default persistent sandbox / cwd bind.- default_ws = _default_docker_workspace_host_root(session_key)- if default_ws is not None and not any(c.as_posix() == "/workspace" for _, c in mounts):- mounts.append((default_ws, Path("/workspace")))- # Synthetic /root mount for the persistent home bind. Cache mounts above+ # Synthetic /workspace mounts for the persistent sandbox / cwd bind.+ # Multiple candidates: profile-scoped layout first, then the legacy+ # bug-window per-session layout — the file is tried against each.+ if not any(c.as_posix() == "/workspace" for _, c in mounts):+ for ws_root in _default_docker_workspace_host_roots(session_key):+ mounts.append((ws_root, Path("/workspace")))+ # Synthetic /root mounts for the persistent home bind. Cache mounts above# are longer prefixes, so /root/.hermes/... still translates to the host# cache — this only catches stray home writes like /root/out.png.- default_home = _docker_persistent_home_host_root(session_key)- if default_home is not None and not any(c.as_posix() == "/root" for _, c in mounts):+ if not any(c.as_posix() == "/root" for _, c in mounts):# /root/.hermes/* that did NOT match a cache mount is the container's# credential/secret surface (.env, auth.json, ... are individually# bind-mounted from the real host stores). Translating those through@@ -1701,33 +1725,36 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = "# host-side credential denylist prefixes — refuse instead so the# normal "container path doesn't exist on host" rejection applies.if not candidate.as_posix().startswith("/root/.hermes"):- mounts.append((default_home, Path("/root")))+ for home_root in _docker_persistent_home_host_roots(session_key):+ mounts.append((home_root, Path("/root")))if not mounts:_warn_unresolved_docker_media(candidate, session_key, "no sandbox mounts resolved")return None- # Longest container-prefix match.- best: Optional[Tuple[Path, Path, int]] = None+ # Longest container-prefix match; equal-length prefixes (the candidate+ # sandbox layouts above) are tried in insertion order until one actually+ # holds the file.+ matched: List[Tuple[Path, Path, int]] = []candidate_posix = candidate.as_posix()for host_root, container_root in mounts:container_posix = container_root.as_posix().rstrip("/") or "/"if candidate_posix == container_posix or candidate_posix.startswith(container_posix + "/"):- score = len(container_posix)- if best is None or score > best[2]:- best = (host_root, container_root, score)- if best is None:+ matched.append((host_root, container_root, len(container_posix)))+ if not matched:_warn_unresolved_docker_media(candidate, session_key, "no mounted prefix matches")return None- host_root, container_root, _ = best- try:- relative = candidate.relative_to(container_root)- translated = (host_root / relative).resolve(strict=True)- except (OSError, RuntimeError, ValueError):- _warn_unresolved_docker_media(candidate, session_key, "host file missing from sandbox")- return None- if translated != host_root and not _path_is_within(translated, host_root):- return None- return translated+ matched.sort(key=lambda m: -m[2])+ for host_root, container_root, _score in matched:+ try:+ relative = candidate.relative_to(container_root)+ translated = (host_root / relative).resolve(strict=True)+ except (OSError, RuntimeError, ValueError):+ continue+ if translated != host_root and not _path_is_within(translated, host_root):+ continue+ return translated+ _warn_unresolved_docker_media(candidate, session_key, "host file missing from sandbox")+ return Nonedef validate_media_delivery_path(path: str, session_key: str = "") -> Optional[str]:diff --git a/tests/gateway/test_platform_base.py b/tests/gateway/test_platform_base.pyindex 8d8fe8e0ff2..61392146ced 100644--- a/tests/gateway/test_platform_base.py+++ b/tests/gateway/test_platform_base.py@@ -1254,74 +1254,81 @@ class TestMediaFallbackDoesNotLeakHostPath:assert self.SENSITIVE_PATH not in sent_text-class TestDockerSessionSandboxMediaTranslation:- """MEDIA from a session-scoped persistent Docker sandbox must resolve to- the host directory that container actually bind-mounts (#93950).-- Contract: the gateway resolves the SAME directory- ``tools/environments/docker.py`` created — ``<sandboxes>/docker/<task>``- where ``<task>`` is ``sanitize_task_id_for_path("session:<key>")`` for- gateway sessions and the literal ``default`` otherwise.+class TestDockerProfileSandboxMediaTranslation:+ """MEDIA from persistent Docker sandboxes must resolve to the host+ directory the profile's container actually bind-mounts (#93950).++ Contract: persistent Docker is PROFILE-scoped — the default profile (and+ CLI) uses the literal ``default`` sandbox, other profiles use+ ``sanitize_task_id_for_path("profile:<name>")``. Legacy per-session+ sandboxes (``session:<key>``) created during the a270c4ade bug window+ remain resolvable as a fallback so their files still deliver."""SESSION_KEY = "agent:main:telegram:dm:123456"@staticmethod- def _sandbox_dir(session_key: str):+ def _sandbox_dir(task_id: str = "default"):from tools.environments.base import get_sandbox_dir, sanitize_task_id_for_path- task_id = f"session:{session_key}" if session_key else "default"- return get_sandbox_dir() / "docker" / sanitize_task_id_for_path(task_id)+ name = task_id if task_id == "default" else sanitize_task_id_for_path(task_id)+ return get_sandbox_dir() / "docker" / namedef _enable_docker(self, monkeypatch):monkeypatch.setenv("TERMINAL_ENV", "docker")monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "true")- def test_session_scoped_workspace_media_translates(self, monkeypatch):+ def test_default_profile_workspace_media_translates(self, monkeypatch):"""A MEDIA tag pointing at the container's /workspace resolves to the- session's real host sandbox instead of being dropped."""+ default profile's shared host sandbox — with or without a session+ key, since every session of the profile shares one container."""self._enable_docker(monkeypatch)- workspace = self._sandbox_dir(self.SESSION_KEY) / "workspace"+ workspace = self._sandbox_dir() / "workspace"workspace.mkdir(parents=True, exist_ok=True)produced = workspace / "chart.png"produced.write_bytes(b"png")- resolved = BasePlatformAdapter.validate_media_delivery_path(+ with_key = BasePlatformAdapter.validate_media_delivery_path("/workspace/chart.png", session_key=self.SESSION_KEY)+ without_key = BasePlatformAdapter.validate_media_delivery_path(+ "/workspace/chart.png"+ )- assert resolved == str(produced.resolve())+ assert with_key == without_key == str(produced.resolve())- def test_missing_session_key_reproduces_93950_drop(self, monkeypatch):- """Pre-fix failure mode: with no delivering-session key the- translation collapses onto the (nonexistent) ``default`` sandbox and- the attachment is dropped even though the file exists."""+ def test_legacy_session_sandbox_still_resolves(self, monkeypatch):+ """Self-heal for the a270c4ade bug window: files produced in a legacy+ per-session sandbox still deliver via the fallback candidate."""self._enable_docker(monkeypatch)- workspace = self._sandbox_dir(self.SESSION_KEY) / "workspace"+ workspace = self._sandbox_dir(f"session:{self.SESSION_KEY}") / "workspace"workspace.mkdir(parents=True, exist_ok=True)- (workspace / "out.png").write_bytes(b"png")+ produced = workspace / "out.png"+ produced.write_bytes(b"png")- assert (- BasePlatformAdapter.validate_media_delivery_path("/workspace/out.png")- is None- )+ assert BasePlatformAdapter.validate_media_delivery_path(+ "/workspace/out.png", session_key=self.SESSION_KEY+ ) == str(produced.resolve())- def test_default_sandbox_still_resolves_without_session_key(self, monkeypatch):- """CLI-created default sandboxes keep their historical resolution."""+ def test_profile_and_legacy_sandboxes_both_searched(self, monkeypatch):+ """When the profile sandbox exists but the file was produced in a+ legacy per-session container, translation still finds it — the dir+ existing must not mask the fallback (#93950 follow-up)."""self._enable_docker(monkeypatch)- workspace = self._sandbox_dir("") / "workspace"- workspace.mkdir(parents=True, exist_ok=True)- produced = workspace / "out.png"+ (self._sandbox_dir() / "workspace").mkdir(parents=True, exist_ok=True)+ legacy_ws = self._sandbox_dir(f"session:{self.SESSION_KEY}") / "workspace"+ legacy_ws.mkdir(parents=True, exist_ok=True)+ produced = legacy_ws / "old.png"produced.write_bytes(b"png")assert BasePlatformAdapter.validate_media_delivery_path(- "/workspace/out.png"+ "/workspace/old.png", session_key=self.SESSION_KEY) == str(produced.resolve())- def test_session_home_mount_translates_stray_root_writes(self, monkeypatch):- """/root/<file> lands in the session sandbox's home mount."""+ def test_home_mount_translates_stray_root_writes(self, monkeypatch):+ """/root/<file> lands in the profile sandbox's home mount."""self._enable_docker(monkeypatch)- home = self._sandbox_dir(self.SESSION_KEY) / "home"+ home = self._sandbox_dir() / "home"home.mkdir(parents=True, exist_ok=True)produced = home / "note.txt"produced.write_text("hi")@@ -1330,14 +1337,15 @@ class TestDockerSessionSandboxMediaTranslation:"/root/note.txt", session_key=self.SESSION_KEY) == str(produced.resolve())- def test_session_home_credential_surface_still_refused(self, monkeypatch):- """The /root/.hermes exclusion survives session scoping: translating- the home mount must never expose the container's secret surface."""+ def test_home_credential_surface_still_refused(self, monkeypatch):+ """The /root/.hermes exclusion survives profile scoping: translating+ the home mount must never expose the container's secret surface —+ in the profile layout AND the legacy session layout."""self._enable_docker(monkeypatch)- home = self._sandbox_dir(self.SESSION_KEY) / "home"- secrets = home / ".hermes"- secrets.mkdir(parents=True, exist_ok=True)- (secrets / "auth.json").write_text("{}")+ for task in ("default", f"session:{self.SESSION_KEY}"):+ secrets = self._sandbox_dir(task) / "home" / ".hermes"+ secrets.mkdir(parents=True, exist_ok=True)+ (secrets / "auth.json").write_text("{}")assert (BasePlatformAdapter.validate_media_delivery_path(@@ -1348,9 +1356,9 @@ class TestDockerSessionSandboxMediaTranslation:def test_filter_passes_session_key_through(self, monkeypatch):"""The adapter filter used by _process_message_background forwards the- key, so extracted MEDIA tags survive filtering in one hop."""+ key, so legacy-sandbox MEDIA tags survive filtering in one hop."""self._enable_docker(monkeypatch)- workspace = self._sandbox_dir(self.SESSION_KEY) / "workspace"+ workspace = self._sandbox_dir(f"session:{self.SESSION_KEY}") / "workspace"workspace.mkdir(parents=True, exist_ok=True)produced = workspace / "clip.mp4"produced.write_bytes(b"mp4")@@ -1362,7 +1370,7 @@ class TestDockerSessionSandboxMediaTranslation:assert kept == [(str(produced.resolve()), False)]def test_unresolved_docker_media_names_the_cause(self, monkeypatch, caplog):- """Approach C: a container path whose sandbox never existed must log+ """A container path that resolves in no candidate sandbox must logWHY it was dropped (sandbox mismatch), not just the generic unsafe-path line — the silent-drop mode reported in #93950."""import logging@@ -1375,7 +1383,6 @@ class TestDockerSessionSandboxMediaTranslation:assert resolved is Noneassert any(- "did not resolve to a host sandbox file" in r.message- and f"session_key={self.SESSION_KEY}" in r.message+ "did not resolve" in r.message and f"session_key={self.SESSION_KEY}" in r.messagefor r in caplog.records)diff --git a/tests/tools/test_shared_container_task_id.py b/tests/tools/test_shared_container_task_id.pyindex b4ea3fa4b9b..cb1eeef6445 100644--- a/tests/tools/test_shared_container_task_id.py+++ b/tests/tools/test_shared_container_task_id.py@@ -163,3 +163,93 @@ def test_contextvar_session_key_wins_over_environ(monkeypatch):)finally:clear_session_vars(tokens)+++# --- Persistent Docker is PROFILE-scoped, not session-scoped ------------------+#+# Product contract: TERMINAL_ENV=docker + container_persistent:true means ONE+# long-lived container per Hermes profile, shared by every session of that+# profile (CLI, gateway chats, WebUI). The a270c4ade session-key fallback must+# NOT fragment persistent Docker into per-session containers; it exists for+# backends where cross-session reuse is dangerous (SSH).+++def _persistent_docker(monkeypatch):+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "true")+++def test_persistent_docker_default_profile_shares_default_container(monkeypatch):+ # A gateway session of the default profile lands on the SAME container key+ # CLI mode uses — "default" — not a per-session key.+ from gateway.session_context import clear_session_vars, set_session_vars++ _persistent_docker(monkeypatch)+ tokens = set_session_vars(session_key="agent:main:telegram:dm:123", profile="")+ try:+ assert terminal_tool._resolve_container_task_id(None) == "default"+ finally:+ clear_session_vars(tokens)+++def test_persistent_docker_two_sessions_same_profile_share_container(monkeypatch):+ from gateway.session_context import clear_session_vars, set_session_vars++ _persistent_docker(monkeypatch)+ tokens = set_session_vars(session_key="agent:main:telegram:dm:123", profile="work")+ try:+ a = terminal_tool._resolve_container_task_id(None)+ finally:+ clear_session_vars(tokens)+ tokens = set_session_vars(session_key="agent:main:discord:guild:456", profile="work")+ try:+ b = terminal_tool._resolve_container_task_id(None)+ finally:+ clear_session_vars(tokens)+ assert a == b == "profile:work"+++def test_persistent_docker_distinct_profiles_get_distinct_containers(monkeypatch):+ from gateway.session_context import clear_session_vars, set_session_vars++ _persistent_docker(monkeypatch)+ tokens = set_session_vars(session_key="sess-X", profile="work")+ try:+ a = terminal_tool._resolve_container_task_id(None)+ finally:+ clear_session_vars(tokens)+ tokens = set_session_vars(session_key="sess-X", profile="research")+ try:+ b = terminal_tool._resolve_container_task_id(None)+ finally:+ clear_session_vars(tokens)+ assert a == "profile:work"+ assert b == "profile:research"+ assert a != b+++def test_nonpersistent_docker_keeps_session_scoping(monkeypatch):+ # container_persistent:false is an explicit isolation statement (#82731) —+ # the profile-scope gate must not fire there.+ from gateway.session_context import clear_session_vars, set_session_vars++ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "false")+ tokens = set_session_vars(session_key="sess-A", profile="work")+ try:+ assert terminal_tool._resolve_container_task_id(None) == "session:sess-A"+ finally:+ clear_session_vars(tokens)+++def test_ssh_backend_keeps_session_scoping(monkeypatch):+ # The original a270c4ade leak: SSH environments must stay session-scoped+ # regardless of profile, or profile A's SSHEnvironment leaks into B.+ from gateway.session_context import clear_session_vars, set_session_vars++ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ tokens = set_session_vars(session_key="sess-A", profile="work")+ try:+ assert terminal_tool._resolve_container_task_id(None) == "session:sess-A"+ finally:+ clear_session_vars(tokens)diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 053170ec00e..b7a02448ff5 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -1407,6 +1407,39 @@ def _docker_session_isolation_enabled() -> bool:return _session_isolation_enabled()+def _docker_persistent_profile_scoped() -> bool:+ """True when the persistent Docker container is shared per PROFILE.++ The product contract for ``TERMINAL_ENV=docker`` ++ ``container_persistent: true`` is ONE long-lived container per Hermes+ profile, shared by every session of that profile (CLI, gateway chats,+ WebUI). Commit a270c4ade added a session-key fallback to+ :func:`_resolve_container_task_id` to stop cross-profile SSH environment+ reuse, but the fallback wasn't backend-gated, so persistent Docker+ silently fragmented into one container per gateway session (#93950 was+ downstream damage from that). This predicate gates the resolver back to+ profile scoping for exactly this backend/mode; SSH and other backends+ keep the session-scoped cache key that fixed the original leak.+ """+ _ensure_terminal_env_bridged()+ if os.getenv("TERMINAL_ENV", "local") != "docker":+ return False+ return os.getenv("TERMINAL_CONTAINER_PERSISTENT", "true").lower() in {"true", "1", "yes"}+++def _current_session_profile() -> str:+ """Return the active session's Hermes profile name, or "" when unset.++ Same lookup discipline as :func:`_current_session_key`: the ContextVar+ (bound per message by the gateway, per session by the WebUI streaming+ layer) with the ``get_session_env`` os.environ fallback for CLI, cron,+ and test processes.+ """+ from gateway.session_context import get_session_env++ return get_session_env("HERMES_SESSION_PROFILE", "")++_ISOLATION_OVERRIDE_KEYS = frozenset({"docker_image", "modal_image", "singularity_image","daytona_image", "env_type",@@ -1474,6 +1507,18 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:# would otherwise collapse to the shared "default" key (notably SSH).session_key = _current_session_key()if session_key:+ # Persistent Docker is PROFILE-scoped by contract: one long-lived+ # container shared by every session of the profile. Key it by profile+ # (not session) so gateway chats, CLI, and WebUI all land in the same+ # container and sandbox. The bare "profile:default" key stays literally+ # "default" so CLI mode (no session key at all) and gateway sessions of+ # the default profile share the SAME container — CLI's historical key+ # IS the default profile's container.+ if _docker_persistent_profile_scoped():+ profile = _current_session_profile() or "default"+ if profile == "default":+ return "default"+ return f"profile:{profile}"return f"session:{session_key}"return "default"