The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(docker): per-session container isolation and session-scoped workspace mounts
Tekniume95e13783bc4
diff --git a/tests/tools/test_docker_session_isolation.py b/tests/tools/test_docker_session_isolation.pynew file mode 100644index 00000000000..f1d123be77e--- /dev/null+++ b/tests/tools/test_docker_session_isolation.py@@ -0,0 +1,327 @@+"""Per-session docker container isolation (docker + container_persistent: false).++Two user-reported bugs on the docker terminal backend (desktop app, sandboxed+cybersecurity profile):++1. **Stale workspace mount leak** — a NEW chat's container carried the+ PREVIOUS session's workspace bind-mounted rw at /workspace, because the+ mount source was the process-global TERMINAL_CWD env var (written by the+ workspace picker, outliving the session that set it) and because every+ session collapsed onto one shared "default" container.++2. **Broken startup cd (exit 126)** — every command tried to+ ``cd /Users/<user>/...`` (a host path recorded as the session cwd by the+ desktop/TUI gateway) inside the container where it doesn't exist.++These tests pin the fix:++* ``container_persistent: false`` + docker ⇒ each session task_id is its own+ container key (fresh container per session); subagents share the parent's+ container via ``register_container_alias``.+* ``container_persistent: true`` (or any other backend) ⇒ legacy shared+ "default" container, unchanged.+* Mount resolution (``_resolve_task_host_cwd``) refuses process-global cwd+ sources under isolation; only the session's own attached workspace mounts.+* ``_resolve_command_cwd`` discards recorded host-path cwds on container+ backends instead of prefixing commands with an un-cd-able host path.+"""++import os++import pytest++from tools import terminal_tool++[email protected](autouse=True)+def _clean_state(monkeypatch):+ """Isolate override/alias/cwd-record state and pin docker isolation env."""+ before_overrides = dict(terminal_tool._task_env_overrides)+ terminal_tool._task_env_overrides.clear()+ with terminal_tool._container_alias_lock:+ before_aliases = dict(terminal_tool._container_aliases)+ terminal_tool._container_aliases.clear()+ with terminal_tool._session_cwd_lock:+ before_cwd = dict(terminal_tool._session_cwd)+ terminal_tool._session_cwd.clear()+ # The config→env bridge is one-shot; mark it done so tests control env vars.+ monkeypatch.setattr(terminal_tool, "_terminal_config_bridge_attempted", True)+ yield+ terminal_tool._task_env_overrides.clear()+ terminal_tool._task_env_overrides.update(before_overrides)+ with terminal_tool._container_alias_lock:+ terminal_tool._container_aliases.clear()+ terminal_tool._container_aliases.update(before_aliases)+ with terminal_tool._session_cwd_lock:+ terminal_tool._session_cwd.clear()+ terminal_tool._session_cwd.update(before_cwd)+++def _enable_isolation(monkeypatch):+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "false")+++def _disable_isolation(monkeypatch):+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "true")+++class TestSessionIsolationKeying:+ def test_persistent_true_keeps_shared_default(self, monkeypatch):+ _disable_isolation(monkeypatch)+ assert terminal_tool._resolve_container_task_id("tui:sess-1") == "default"++ def test_persistent_false_keys_by_session(self, monkeypatch):+ _enable_isolation(monkeypatch)+ assert terminal_tool._resolve_container_task_id("tui:sess-1") == "tui:sess-1"++ def test_two_sessions_get_distinct_keys(self, monkeypatch):+ """The reported bug: session B must not land in session A's container."""+ _enable_isolation(monkeypatch)+ a = terminal_tool._resolve_container_task_id("tui:sess-a")+ b = terminal_tool._resolve_container_task_id("tui:sess-b")+ assert a != b++ def test_none_task_id_still_default_under_isolation(self, monkeypatch):+ _enable_isolation(monkeypatch)+ assert terminal_tool._resolve_container_task_id(None) == "default"++ def test_local_backend_unaffected(self, monkeypatch):+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "false")+ assert terminal_tool._resolve_container_task_id("tui:sess-1") == "default"++ def test_rl_override_isolation_still_wins(self, monkeypatch):+ """Image/env_type overrides keep their own key in BOTH modes."""+ _enable_isolation(monkeypatch)+ terminal_tool.register_task_env_overrides(+ "bench-env", {"docker_image": "custom:latest"}+ )+ try:+ assert terminal_tool._resolve_container_task_id("bench-env") == "bench-env"+ finally:+ terminal_tool.clear_task_env_overrides("bench-env")++ def test_subagent_alias_resolves_to_parent(self, monkeypatch):+ """delegate_task children share the PARENT session's container."""+ _enable_isolation(monkeypatch)+ terminal_tool.register_container_alias("subagent-1", "tui:sess-a")+ assert terminal_tool._resolve_container_task_id("subagent-1") == "tui:sess-a"++ def test_subagent_alias_without_parent_falls_to_default(self, monkeypatch):+ _enable_isolation(monkeypatch)+ terminal_tool.register_container_alias("subagent-2", None)+ assert terminal_tool._resolve_container_task_id("subagent-2") == "default"++ def test_nested_alias_chain_resolves(self, monkeypatch):+ """Orchestrator child spawning its own worker: chain to the root session."""+ _enable_isolation(monkeypatch)+ terminal_tool.register_container_alias("child", "tui:sess-a")+ terminal_tool.register_container_alias("grandchild", "child")+ assert terminal_tool._resolve_container_task_id("grandchild") == "tui:sess-a"++ def test_alias_cycle_does_not_hang(self, monkeypatch):+ _enable_isolation(monkeypatch)+ terminal_tool.register_container_alias("x", "y")+ terminal_tool.register_container_alias("y", "x")+ # Any terminating answer is fine; the invariant is no infinite loop.+ assert terminal_tool._resolve_container_task_id("x") in {"x", "y"}+++class TestSessionScopedMountResolution:+ """_resolve_task_host_cwd: the single owner of the cwd→/workspace mount policy."""++ def _config(self, host_cwd="/Users/prev/dev/oldrepo", mount=True):+ return {+ "env_type": "docker",+ "docker_mount_cwd_to_workspace": mount,+ "host_cwd": host_cwd,+ }++ def test_shared_mode_keeps_legacy_host_cwd(self, monkeypatch):+ _disable_isolation(monkeypatch)+ cfg = self._config()+ assert (+ terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-1")+ == "/Users/prev/dev/oldrepo"+ )++ def test_isolation_refuses_process_global_mount(self, monkeypatch, tmp_path):+ """The reported leak: a fresh session with NO attached workspace must+ not inherit the process-global TERMINAL_CWD-derived mount."""+ _enable_isolation(monkeypatch)+ cfg = self._config(host_cwd=str(tmp_path))+ assert terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-new") is None++ def test_isolation_refuses_process_tagged_override(self, monkeypatch, tmp_path):+ """A cwd override tagged cwd_source='process' (gateway env-var fallback)+ is a launch artifact, not a session workspace — never a mount source."""+ _enable_isolation(monkeypatch)+ terminal_tool.register_task_env_overrides(+ "tui:sess-new", {"cwd": str(tmp_path), "cwd_source": "process"}+ )+ cfg = self._config(host_cwd=str(tmp_path))+ assert terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-new") is None++ def test_isolation_mounts_session_attached_workspace(self, monkeypatch, tmp_path):+ """A workspace the user attached to THIS session does mount."""+ _enable_isolation(monkeypatch)+ ws = tmp_path / "attached"+ ws.mkdir()+ terminal_tool.register_task_env_overrides(+ "tui:sess-new", {"cwd": str(ws), "cwd_source": "session"}+ )+ cfg = self._config(host_cwd="/Users/prev/dev/oldrepo")+ assert terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-new") == str(ws)++ def test_isolation_rejects_nonexistent_session_dir(self, monkeypatch, tmp_path):+ _enable_isolation(monkeypatch)+ terminal_tool.register_task_env_overrides(+ "tui:sess-new",+ {"cwd": str(tmp_path / "gone"), "cwd_source": "session"},+ )+ cfg = self._config()+ assert terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-new") is None++ def test_isolation_rejects_in_container_path_as_mount(self, monkeypatch):+ _enable_isolation(monkeypatch)+ terminal_tool.register_task_env_overrides(+ "tui:sess-new", {"cwd": "/workspace", "cwd_source": "session"}+ )+ cfg = self._config()+ assert terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-new") is None++ def test_mount_flag_off_means_no_mount(self, monkeypatch, tmp_path):+ _enable_isolation(monkeypatch)+ ws = tmp_path / "attached"+ ws.mkdir()+ terminal_tool.register_task_env_overrides(+ "tui:sess-new", {"cwd": str(ws), "cwd_source": "session"}+ )+ cfg = self._config(mount=False)+ assert terminal_tool._resolve_task_host_cwd(cfg, "tui:sess-new") is None++ def test_default_task_keeps_legacy_behavior_under_isolation(self, monkeypatch):+ """The single-session CLI parent ("default") keeps the legacy mount."""+ _enable_isolation(monkeypatch)+ cfg = self._config()+ assert (+ terminal_tool._resolve_task_host_cwd(cfg, None)+ == "/Users/prev/dev/oldrepo"+ )++ def test_non_docker_backend_never_mounts(self, monkeypatch):+ _disable_isolation(monkeypatch)+ cfg = self._config()+ cfg["env_type"] = "modal"+ assert terminal_tool._resolve_task_host_cwd(cfg, "t") is None+++class TestRecordedHostCwdDiscardedOnContainers:+ """_resolve_command_cwd must not cd to a recorded HOST path in a sandbox.++ The reported exit-126 bug: the desktop gateway records the host launch+ dir as the session cwd; every subsequent command then ran+ ``cd /Users/<user>/dev/<repo> && <cmd>`` inside the container.+ """++ def test_host_record_discarded_for_docker(self):+ terminal_tool.record_session_cwd("sess-1", "/Users/me/dev/repo")+ cwd = terminal_tool._resolve_command_cwd(+ workdir=None, default_cwd="/workspace",+ session_key="sess-1", env_type="docker",+ )+ assert cwd == "/workspace"++ def test_container_record_honored_for_docker(self):+ """A legitimate in-container cd is the session's state — keep it."""+ terminal_tool.record_session_cwd("sess-1", "/workspace/subdir")+ cwd = terminal_tool._resolve_command_cwd(+ workdir=None, default_cwd="/workspace",+ session_key="sess-1", env_type="docker",+ )+ assert cwd == "/workspace/subdir"++ def test_host_record_kept_for_local_backend(self):+ terminal_tool.record_session_cwd("sess-1", "/home/me/project")+ cwd = terminal_tool._resolve_command_cwd(+ workdir=None, default_cwd="/anything",+ session_key="sess-1", env_type="local",+ )+ assert cwd == "/home/me/project"++ def test_explicit_workdir_still_wins(self):+ terminal_tool.record_session_cwd("sess-1", "/workspace/a")+ cwd = terminal_tool._resolve_command_cwd(+ workdir="/workspace/b", default_cwd="/workspace",+ session_key="sess-1", env_type="docker",+ )+ assert cwd == "/workspace/b"++ def test_no_env_type_keeps_previous_behavior(self):+ """Callers that don't pass env_type (legacy sites) are unchanged."""+ terminal_tool.record_session_cwd("sess-1", "/home/me/project")+ cwd = terminal_tool._resolve_command_cwd(+ workdir=None, default_cwd="/fallback", session_key="sess-1",+ )+ assert cwd == "/home/me/project"+++class TestSessionScopedContainerLifecycle:+ def test_session_scoped_env_counts_persistent_for_turn_teardown(self, monkeypatch):+ """Session-scoped containers survive between turns (torn down at+ session close, not per-turn)."""+ _enable_isolation(monkeypatch)++ class _FakeEnv:+ _session_scoped = True+ _persistent = False++ monkeypatch.setitem(+ terminal_tool._active_environments, "tui:sess-1", _FakeEnv()+ )+ try:+ assert terminal_tool.is_persistent_env("tui:sess-1") is True+ finally:+ terminal_tool._active_environments.pop("tui:sess-1", None)++ def test_create_environment_marks_session_scoped(self, monkeypatch):+ """_create_environment disables cross-process persist for session+ containers and stamps the marker the lifecycle paths read."""+ _enable_isolation(monkeypatch)+ captured = {}++ class _FakeDockerEnv:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ monkeypatch.setattr(terminal_tool, "_DockerEnvironment", _FakeDockerEnv)+ monkeypatch.setattr(terminal_tool, "_maybe_reap_docker_orphans", lambda cc: None)++ env = terminal_tool._create_environment(+ env_type="docker", image="img:1", cwd="/workspace", timeout=60,+ container_config={"docker_persist_across_processes": True},+ task_id="tui:sess-1",+ )+ assert captured["persist_across_processes"] is False+ assert getattr(env, "_session_scoped") is True++ def test_create_environment_default_task_not_session_scoped(self, monkeypatch):+ _enable_isolation(monkeypatch)+ captured = {}++ class _FakeDockerEnv:+ def __init__(self, **kwargs):+ captured.update(kwargs)++ monkeypatch.setattr(terminal_tool, "_DockerEnvironment", _FakeDockerEnv)+ monkeypatch.setattr(terminal_tool, "_maybe_reap_docker_orphans", lambda cc: None)++ env = terminal_tool._create_environment(+ env_type="docker", image="img:1", cwd="/workspace", timeout=60,+ container_config={"docker_persist_across_processes": True},+ task_id="default",+ )+ assert captured["persist_across_processes"] is True+ assert getattr(env, "_session_scoped", False) is Falsediff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex 6bead21f18a..b0309be6b93 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -793,7 +793,7 @@ def _get_or_create_env(task_id: str):_active_environments, _env_lock, _create_environment,_get_env_config, _last_activity, _start_cleanup_thread,_creation_locks, _creation_locks_lock, _task_env_overrides,- _resolve_container_task_id,+ _resolve_container_task_id, _resolve_task_host_cwd,)effective_task_id = _resolve_container_task_id(task_id)@@ -873,7 +873,7 @@ def _get_or_create_env(task_id: str):container_config=container_config,local_config=local_config,task_id=effective_task_id,- host_cwd=config.get("host_cwd"),+ host_cwd=_resolve_task_host_cwd(config, task_id),)with _env_lock:diff --git a/tools/delegate_tool.py b/tools/delegate_tool.pyindex 25b8c81d070..e4f4766fca8 100644--- a/tools/delegate_tool.py+++ b/tools/delegate_tool.py@@ -2278,9 +2278,18 @@ def _run_single_child(# isolated in its own record (a child's cd no longer bleeds back into# the parent once readers flip to the record store).try:- from tools.terminal_tool import get_session_cwd, record_session_cwd+ from tools.terminal_tool import (+ get_session_cwd,+ record_session_cwd,+ register_container_alias,+ )record_session_cwd(child_task_id, get_session_cwd(parent_task_id))+ # Per-session container isolation (docker + container_persistent:+ # false) keys containers by session task_id. The child must share+ # the PARENT's container — register the alias so the child's+ # task_id resolves to the parent's container key.+ register_container_alias(child_task_id, parent_task_id)except Exception as e:logger.debug("Child cwd seed failed: %s", e)wall_start = time.time()diff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex dc16c366010..a9bca99b7a2 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -881,7 +881,7 @@ class DockerEnvironment(BaseEnvironment):forward_env: list[str] | None = None,env: dict | None = None,network: bool = True,- host_cwd: str = None,+ host_cwd: Optional[str] = None,auto_mount_cwd: bool = False,run_as_host_user: bool = False,extra_args: list = None,@@ -893,6 +893,10 @@ class DockerEnvironment(BaseEnvironment):super().__init__(cwd=cwd, timeout=timeout)self._persistent = persistent_filesystemself._persist_across_processes = persist_across_processes+ # Set by terminal_tool._create_environment when this container is+ # scoped to a single session (docker + container_persistent: false):+ # survives between turns, removed at session close / idle timeout.+ self._session_scoped = Falseself._task_id = task_idself._forward_env = _normalize_forward_env_names(forward_env)self._env = _normalize_env_dict(env)diff --git a/tools/file_tools.py b/tools/file_tools.pyindex 0a8f08cb9b0..deb55134f54 100644--- a/tools/file_tools.py+++ b/tools/file_tools.py@@ -1353,6 +1353,7 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations:_creation_locks,_creation_locks_lock,_resolve_container_task_id,+ _resolve_task_host_cwd,_is_unusable_container_cwd,_CONTAINER_BACKENDS,)@@ -1488,7 +1489,7 @@ def _get_file_ops(task_id: str = "default") -> ShellFileOperations:container_config=container_config,local_config=local_config,task_id=task_id,- host_cwd=config.get("host_cwd"),+ host_cwd=_resolve_task_host_cwd(config, raw_task_id),)with _env_lock:diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex f9dd09114fc..2f664fbb133 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -1277,6 +1277,76 @@ def clear_task_env_overrides(task_id: str):"""_task_env_overrides.pop(task_id, None)clear_session_cwd(task_id)+ with _container_alias_lock:+ _container_aliases.pop(task_id, None)+++# Subagent → parent container aliasing. delegate_task children get their own+# task_id (file-state tracking, TUI events) but must share the PARENT+# session's container — one bash, one /workspace, one set of installed+# packages. With per-session container isolation active (docker ++# container_persistent: false), the collapse-to-"default" shortcut no longer+# provides that sharing, so the spawn site registers an explicit alias.+_container_aliases: Dict[str, str] = {}+_container_alias_lock = threading.Lock()+++def register_container_alias(child_task_id: str, parent_task_id: Optional[str]) -> None:+ """Make *child_task_id* resolve to *parent_task_id*'s container.++ Called by ``delegate_task`` at child spawn so subagents share the parent+ session's sandbox under per-session container isolation. A missing/empty+ parent id aliases the child to ``"default"`` (top-level CLI parent).+ """+ if not child_task_id:+ return+ with _container_alias_lock:+ _container_aliases[child_task_id] = str(parent_task_id or "default")+++def _resolve_container_alias(task_id: str) -> str:+ """Follow the child→parent alias chain (cycle-safe) for *task_id*."""+ seen = set()+ key = task_id+ with _container_alias_lock:+ while key in _container_aliases and key not in seen:+ seen.add(key)+ key = _container_aliases[key]+ return key+++def _docker_session_isolation_enabled() -> bool:+ """True when docker sessions get their OWN containers (issue: stale+ workspace mounts leaking between desktop sessions).++ Gated on ``terminal.backend: docker`` + ``container_persistent: false``:+ a non-persistent sandbox is a statement that state must not survive the+ session, so sharing one container across sessions contradicts it. With+ ``container_persistent: true`` the documented ONE-long-lived-container+ contract is unchanged.+ """+ _ensure_terminal_env_bridged()+ if os.getenv("TERMINAL_ENV", "local") != "docker":+ return False+ return os.getenv("TERMINAL_CONTAINER_PERSISTENT", "true").lower() not in {"true", "1", "yes"}+++_ISOLATION_OVERRIDE_KEYS = frozenset({+ "docker_image", "modal_image", "singularity_image",+ "daytona_image", "env_type",+})+++def _has_isolation_overrides(task_id: Optional[str]) -> bool:+ """True when *task_id* registered backend-image/env_type overrides.++ The single owner of the "is this an RL/benchmark-style isolated rollout"+ predicate — shared by container-key resolution and container creation so+ the two can't drift.+ """+ if not task_id or task_id not in _task_env_overrides:+ return False+ return bool(set(_task_env_overrides[task_id].keys()) & _ISOLATION_OVERRIDE_KEYS)def _resolve_container_task_id(task_id: Optional[str]) -> str:@@ -1302,15 +1372,18 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:tracking) are *not* isolation signals — they should not cause eachsession to spin up its own container. Only overrides containingbackend-specific image keys or ``env_type`` trigger isolation.++ Per-session container isolation (docker + ``container_persistent:+ false``): each session's task_id is its own container key, so a fresh+ chat gets a fresh sandbox with only ITS mounts — a previous session's+ workspace can no longer appear in a new session's container.+ ``delegate_task`` children keep sharing the parent's container via the+ alias registry (``register_container_alias``)."""- _ISOLATION_KEYS = frozenset({- "docker_image", "modal_image", "singularity_image",- "daytona_image", "env_type",- })- if task_id and task_id in _task_env_overrides:- overrides = _task_env_overrides[task_id]- if set(overrides.keys()) & _ISOLATION_KEYS:- return task_id+ if task_id and _has_isolation_overrides(task_id):+ return task_id+ if task_id and _docker_session_isolation_enabled():+ return _resolve_container_alias(task_id)return "default"@@ -1334,6 +1407,50 @@ def resolve_task_overrides(task_id: Optional[str]) -> Dict[str, Any]:)+def _resolve_task_host_cwd(config: Dict[str, Any], task_id: Optional[str]) -> Optional[str]:+ """Host directory to bind-mount at ``/workspace`` for *task_id*'s container.++ The single owner of the cwd-mount policy, shared by every environment+ creation site (terminal tool, file tools, execute_code, lazy bring-up):++ * Shared-container mode (the default): the process-global+ ``TERMINAL_CWD``-derived ``config["host_cwd"]`` — unchanged legacy+ behavior, ONE container whose mount tracks the configured workspace.+ * Per-session isolation mode (docker + ``container_persistent: false``):+ only the SESSION's own registered workspace may mount. The process+ env var is a launch artifact — the TUI/desktop workspace picker writes+ ``os.environ["TERMINAL_CWD"]`` and it outlives the session that set it,+ so deriving a fresh session's mount from it leaks the previous+ session's directory into a chat that never attached one. Overrides+ tagged ``cwd_source: "process"`` (gateway fallback to the global env+ var) are likewise refused as mount sources; only a workspace the user+ actually attached to THIS session (``cwd_source: "session"`` or an+ untagged override from ACP/RL surfaces) mounts.+ """+ if config.get("env_type") != "docker":+ return None+ if not config.get("docker_mount_cwd_to_workspace"):+ return None+ if not _docker_session_isolation_enabled():+ return config.get("host_cwd")+ if _resolve_container_task_id(task_id) == "default":+ # Top-level CLI parent — single-session process, legacy behavior.+ return config.get("host_cwd")+ overrides = resolve_task_overrides(task_id)+ if overrides.get("cwd_source") == "process":+ return None+ candidate = overrides.get("cwd")+ if not isinstance(candidate, str) or not candidate.strip():+ return None+ candidate = os.path.abspath(os.path.expanduser(candidate))+ if not os.path.isdir(candidate):+ return None+ if candidate.startswith(("/workspace", "/root")):+ # Already an in-container path, not a host workspace.+ return None+ return candidate++# Configuration from environment variablesdef _parse_env_var(name: str, default: str, converter: Any = int, type_label: str = "integer"):@@ -1638,7 +1755,7 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int,ssh_config: dict = None, container_config: dict = None,local_config: dict = None,task_id: str = "default",- host_cwd: str = None):+ host_cwd: Optional[str] = None):"""Create an execution environment for sandboxed command execution.@@ -1678,7 +1795,18 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int,# subagents, RL benchmarks) don't run the reaper N times.# Disable via ``terminal.docker_orphan_reaper: false`` (issue #20561)._maybe_reap_docker_orphans(cc)- return _DockerEnvironment(+ # Per-session container isolation: a session-keyed container must not+ # outlive its session, so cross-process reuse/persist is disabled for+ # it — cleanup_vm()/the idle reaper stop+rm it instead of leaving a+ # running container behind for every chat ever opened. The shared+ # "default" container and RL/benchmark override sandboxes keep their+ # existing lifecycle.+ session_scoped = (+ _docker_session_isolation_enabled()+ and task_id != "default"+ and not _has_isolation_overrides(task_id)+ )+ docker_env_obj = _DockerEnvironment(image=image, cwd=cwd, timeout=timeout,cpu=cpu, memory=memory, disk=disk,persistent_filesystem=persistent, task_id=task_id,@@ -1690,9 +1818,22 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int,run_as_host_user=cc.get("docker_run_as_host_user", False),network=docker_network,extra_args=docker_extra_args,- persist_across_processes=cc.get("docker_persist_across_processes", True),+ persist_across_processes=(+ False if session_scoped+ else cc.get("docker_persist_across_processes", True)+ ),shm_size=cc.get("docker_shm_size", "1g"),)+ # Marker read by is_persistent_env(): a session-scoped container+ # survives BETWEEN turns (skip per-turn teardown) but is removed at+ # session close / idle timeout. Guarded setattr: test doubles for+ # _DockerEnvironment may not accept attributes.+ if session_scoped:+ try:+ docker_env_obj._session_scoped = True+ except AttributeError:+ pass+ return docker_env_objelif env_type == "singularity":return _SingularityEnvironment(@@ -1973,7 +2114,7 @@ def ensure_task_env(task_id: Optional[str] = None):),local_config=None,task_id=effective_task_id,- host_cwd=config.get("host_cwd"),+ host_cwd=_resolve_task_host_cwd(config, task_id),)except Exception as exc: # noqa: BLE001 — best-effort bring-uplogger.warning(@@ -2002,10 +2143,17 @@ def is_persistent_env(task_id: str) -> bool:down at end-of-turn to prevent leakage. The idle reaper(``_cleanup_inactive_envs``) handles persistent envs once they exceed``terminal.lifetime_seconds``.++ Session-scoped docker containers (per-session isolation mode) also count+ as persistent HERE: their lifetime is the SESSION, not the turn — they+ are removed by ``AIAgent.close()`` → ``cleanup_vm`` at session teardown+ and by the idle reaper, not per-turn."""env = get_active_env(task_id)if env is None:return False+ if getattr(env, "_session_scoped", False):+ return Truereturn bool(getattr(env, "_persistent", False))@@ -2337,6 +2485,7 @@ def _resolve_command_cwd(workdir: Optional[str],default_cwd: str,session_key: Optional[str] = None,+ env_type: Optional[str] = None,) -> str:"""Return the cwd for a command. Explicit ``workdir=`` overrides everything.@@ -2346,10 +2495,29 @@ def _resolve_command_cwd(``cd`` lands in another record and can't affect us. A session with norecord yet (first command) runs in ``default_cwd`` (config/override cwd),which is also what seeds a fresh environment.++ ``env_type`` makes the record container-aware: on container backends a+ recorded HOST path (a desktop/TUI surface registering its host workspace+ via ``register_task_env_overrides`` → ``record_session_cwd``) is unusable+ inside the sandbox — the shell prefixes every command with ``cd <host+ path>`` and fails with exit 126. Same guard class as the env-creation+ sanitizers (#50636, #54447); this is the per-command sibling site."""if workdir:return workdir- return get_session_cwd(session_key) or default_cwd+ recorded = get_session_cwd(session_key)+ if (+ recorded+ and env_type in _CONTAINER_BACKENDS+ and _is_unusable_container_cwd(recorded)+ ):+ logger.info(+ "Ignoring recorded session cwd %r for %s backend "+ "(host/relative path won't work in sandbox). Using %r instead.",+ recorded, env_type, default_cwd,+ )+ return default_cwd+ return recorded or default_cwddef terminal_tool(@@ -2439,6 +2607,10 @@ def terminal_tool(image = ""cwd = overrides.get("cwd") or get_session_cwd(task_id) or config["cwd"]+ # Session-scoped mount resolution (single owner: _resolve_task_host_cwd).+ # Under per-session isolation a fresh session must not inherit the+ # process-global TERMINAL_CWD mount left behind by a previous session.+ host_cwd = _resolve_task_host_cwd(config, task_id)# A per-task cwd override (registered by the gateway/TUI for workspace# tracking, or by RL/benchmark envs) wins over config["cwd"] — but# config["cwd"] was already sanitized for container backends in@@ -2447,17 +2619,20 @@ def terminal_tool(# POSIX /home/<user>) reaches `docker run -w <host-path>` and the# container fails to start (exit 125). Re-apply the same host/relative# path guard to the *resolved* cwd so the override can't bypass it.+ # When the host path IS this session's mounted workspace, remap it to+ # /workspace (where the mount lands) instead of discarding it.# Valid in-container override paths (RL/benchmark sandboxes that set# cwd to /workspace, /root, etc.) are absolute non-host paths and pass# through untouched.if env_type in _CONTAINER_BACKENDS and _is_unusable_container_cwd(cwd):- if cwd != config["cwd"]:+ remapped = "/workspace" if host_cwd else config["cwd"]+ if cwd != remapped:logger.info(- "Ignoring host/relative cwd override %r for %s backend "+ "Remapping host/relative cwd override %r for %s backend ""(won't exist in sandbox). Using %r instead.",- cwd, env_type, config["cwd"],+ cwd, env_type, remapped,)- cwd = config["cwd"]+ cwd = remappeddefault_timeout = config["timeout"]# Validate an explicit timeout before it flows into deadline math.@@ -2562,7 +2737,7 @@ def terminal_tool(container_config=container_config,local_config=local_config,task_id=effective_task_id,- host_cwd=config.get("host_cwd"),+ host_cwd=host_cwd,)except ImportError as e:return json.dumps({@@ -2622,6 +2797,7 @@ def terminal_tool(workdir=workdir,default_cwd=guard_cwd_base,session_key=session_key,+ env_type=env_type,)def _read_script_in_env(script_path: str) -> Optional[str]:@@ -2807,6 +2983,7 @@ def terminal_tool(workdir=workdir,default_cwd=cwd,session_key=session_key,+ env_type=env_type,)try:if env_type == "local":@@ -3069,6 +3246,7 @@ def terminal_tool(workdir=workdir,default_cwd=cwd,session_key=session_key,+ env_type=env_type,)execute_kwargs = {"timeout": effective_timeout,diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 21966445e17..e44707c3f6e 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2415,6 +2415,23 @@ def _terminal_task_cwd(session: dict | None) -> str:resolution path is taken even when the dashboard entrypoint did not call``apply_terminal_config_to_env`` on its own ``os.environ``."""+ return _terminal_task_cwd_with_source(session)[0]+++def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:+ """Like :func:`_terminal_task_cwd` but also names the value's ORIGIN.++ Returns ``(cwd, source)`` where source is:++ * ``"session"`` — the workspace the user attached to THIS session+ (``explicit_cwd``), or this session's own tracked directory.+ * ``"process"`` — the process-global ``TERMINAL_CWD`` env var / config+ ``terminal.cwd`` fallback. On a shared-container backend this is the+ normal seed; under per-session docker isolation it is a launch+ artifact from a PREVIOUS session (the workspace picker persists it+ process-wide) and must never become a fresh session's bind mount —+ terminal_tool refuses ``cwd_source: "process"`` as a mount source.+ """backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()if not backend or backend == "local":# Fall back to config when TERMINAL_ENV is unset (dashboard/TUI process@@ -2429,6 +2446,11 @@ def _terminal_task_cwd(session: dict | None) -> str:passif backend and backend != "local":+ # A workspace the user explicitly attached to THIS session wins over+ # the process-global env var — the env var is whatever the LAST+ # session's picker wrote, not this session's choice.+ if session and session.get("explicit_cwd") and session.get("cwd"):+ return str(session["cwd"]), "session"raw = os.environ.get("TERMINAL_CWD", "").strip()if not raw:try:@@ -2438,11 +2460,13 @@ def _terminal_task_cwd(session: dict | None) -> str:except Exception:raw = ""if raw and raw not in {".", "auto", "cwd"}:- return raw+ return raw, "process"if backend == "ssh":- return "~"+ return "~", "process"- return _session_cwd(session)+ if session and session.get("cwd"):+ return str(session["cwd"]), "session"+ return _completion_cwd(), "process"# Git working-tree probing (run git, resolve roots, fold worktrees) lives in a@@ -2692,8 +2716,9 @@ def _register_session_cwd(session: dict | None) -> None:try:from tools.terminal_tool import register_task_env_overrides+ cwd, cwd_source = _terminal_task_cwd_with_source(session)register_task_env_overrides(- session["session_key"], {"cwd": _terminal_task_cwd(session)}+ session["session_key"], {"cwd": cwd, "cwd_source": cwd_source})except Exception:passdiff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 4a97edca682..3fa977b4a7e 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -214,6 +214,8 @@ Runs commands inside a Docker container with security hardening (all capabilitie**Single persistent container, shared across Hermes processes.** Hermes starts ONE long-lived container on first use and routes every terminal, file, and `execute_code` call through `docker exec` into that same container — across sessions, `/new`, `/reset`, and `delegate_task` subagents. Working-directory changes, installed packages, files in `/workspace`, and **background processes** all carry over from one tool call to the next, and from one Hermes process to the next. When you close a TUI session, run `/quit`, or start a new `hermes` invocation, the container keeps running and the next Hermes process reuses it via a labeled lookup. See **Container lifecycle** below for the exact teardown rules.+**Per-session isolation mode (`container_persistent: false`).** Setting `container_persistent: false` on the Docker backend switches to one container **per session**: every chat (desktop app session, gateway conversation, TUI session) gets its own fresh sandbox, created on its first terminal/file call and removed when the session closes or goes idle past `lifetime_seconds`. Nothing carries over between sessions — no filesystem state, no mounts, no background processes. With `docker_mount_cwd_to_workspace: true`, only the workspace **attached to that session** is mounted at `/workspace`; a fresh session with no attached directory gets an empty workspace instead of inheriting the previous session's mount. `delegate_task` subagents still share their parent session's container. Use this mode when the sandbox is a security boundary between conversations; keep the default `true` when you want the long-lived shared container described above.+```yamlterminal:backend: docker@@ -237,7 +239,7 @@ terminal:container_cpu: 1 # CPU cores (0 = unlimited)container_memory: 5120 # MB (0 = unlimited)container_disk: 51200 # MB (requires overlay2 on XFS+pquota)- container_persistent: true # Persist /workspace and /root bind-mount dirs+ container_persistent: true # true = persist /workspace + /root, shared container; false = fresh container per session (see below)# Cross-process container reuse (defaults match the "one long-lived# container shared across sessions" contract — see Container lifecycle).