The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): mount each gateway session's own workspace into its Docker container
Tekniumd8835ab3a8b7
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex ffd0f69d90e..4b8f1874211 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1149,8 +1149,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):from gateway.session_policy import policy_for_source, policy_scopefrom gateway.session_api_turn import api_policy_scopefrom gateway.session_authorities import active_authority- with policy_scope(policy_for_source(self._runner, self._ctx.source),- authority=active_authority(self._runner)), api_policy_scope():+ from gateway.session_policy import bind_turn_workspace+ policy = policy_for_source(self._runner, self._ctx.source)+ with policy_scope(policy, authority=active_authority(self._runner)), api_policy_scope():+ bind_turn_workspace(policy, self._ctx.session_id)result = self._run_sync_scoped()from gateway.session_results import execution_resultcaptured = execution_result.get()diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex bdd170b5403..185608e753a 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -927,6 +927,29 @@ def policy_scope(policy, *, authority=None):_TURN_PROFILE.reset(profile_token)+def bind_turn_workspace(policy, task_id):+ """Make the session's frozen workspace its terminal cwd override for this turn's tools (#140665).++ The client's cwd (or ``--in DIR``) is frozen into the policy at admission, but the terminal tool+ mounts ``resolve_task_overrides(task_id)['cwd']`` into a per-session Docker container. Before the+ one-gateway runtime each ``hermes chat`` was its own process with its own ``TERMINAL_CWD``; now the+ turn runs here, so register it under the turn's own task id (inside the turn's routed scope, which+ qualifies the key). Docker mounting the host cwd only: the local backend already runs in the+ policy's ``TERMINAL_CWD``, and ssh and the other sandboxes keep their own cwd. Re-registered only+ when the workspace changed, so an agent's ``cd`` inside the session survives later turns.+ """+ if policy is None or not task_id:+ return+ terminal = json.loads(policy.terminal_json)+ if str(terminal.get('TERMINAL_ENV') or '').strip().lower() != 'docker' or not terminal_uses_host_cwd(terminal):+ return+ from tools.terminal_tool import register_task_env_overrides, resolve_task_overrides+ current = resolve_task_overrides(task_id)+ if current.get('cwd') == policy.cwd and current.get('cwd_source') == 'session':+ return+ register_task_env_overrides(task_id, {**current, 'cwd': policy.cwd, 'cwd_source': 'session'})++@contextmanagerdef profile_read_scope(policy, authority):"""Hold ONE read of a following session's profile for every resolution inside, as a turn'sdiff --git a/tests/gateway/test_docker_session_workspace.py b/tests/gateway/test_docker_session_workspace.pynew file mode 100644index 00000000000..5b51f3899ce--- /dev/null+++ b/tests/gateway/test_docker_session_workspace.py@@ -0,0 +1,107 @@+"""#140665 (#134889 CLI-39): a gateway-owned session's client cwd reaches the Docker terminal backend.++Before #106742 every ``hermes chat`` was its own process with its own ``TERMINAL_CWD`` and its own+container. Now the turn runs in the gateway: the client's cwd (or ``--in DIR``) is frozen into the+session's policy, but never reached ``resolve_task_overrides(task_id)['cwd']``, the per-session mount+source. So ``container_persistent: false`` mounted no ``/workspace`` at all, and ``true`` shared ONE+``profile:<name>`` container bound to whichever session's cwd created it first.+"""+import json+from dataclasses import asdict++import pytest+++def home(tmp_path, monkeypatch):+ from tools import terminal_tool+ home = tmp_path / 'home'+ home.mkdir()+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.delenv('TERMINAL_ENV', raising=False)+ monkeypatch.delenv('TERMINAL_CWD', raising=False)+ monkeypatch.delenv('TERMINAL_CONTAINER_PERSISTENT', raising=False)+ monkeypatch.delenv('TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE', raising=False)+ saved = dict(terminal_tool._task_env_overrides), dict(terminal_tool._session_cwd)+ yield home+ terminal_tool._task_env_overrides.clear()+ terminal_tool._task_env_overrides.update(saved[0])+ terminal_tool._session_cwd.clear()+ terminal_tool._session_cwd.update(saved[1])+++def _policy(home, cwd, persistent, mount=True):+ from gateway.session_policy import build_policy, restore_policy+ (home / 'config.yaml').write_text(json.dumps({'terminal': {+ 'backend': 'docker', 'docker_mount_cwd_to_workspace': mount,+ 'container_persistent': persistent}}), encoding='utf-8')+ return restore_policy(asdict(build_policy({'source': 'cli', 'cwd': str(cwd), 'model': 'm'}, {})))+++def _turn(policy, session_id):+ """The gateway turn's own scope: frozen policy, session key, and the turn's workspace binding."""+ from contextlib import ExitStack+ from gateway.session_context import clear_session_vars, set_session_vars+ from gateway.session_policy import bind_turn_workspace, policy_scope+ stack = ExitStack()+ stack.enter_context(policy_scope(policy))+ tokens = set_session_vars(session_key=f'agent:main:local:dm:{session_id}')+ stack.callback(clear_session_vars, tokens)+ bind_turn_workspace(policy, session_id)+ return stack+++def _plan(session_id):+ from tools.terminal_tool import _get_env_config, _resolve_container_task_id, _resolve_task_host_cwd+ return _resolve_container_task_id(session_id), _resolve_task_host_cwd(_get_env_config(), session_id)+++def test_per_session_container_mounts_each_sessions_own_client_cwd(home, tmp_path):+ ws1, ws2 = tmp_path / 'ws1', tmp_path / 'ws2'+ ws1.mkdir(), ws2.mkdir()+ plans = {}+ for sid, ws in (('local-a', ws1), ('local-b', ws2)):+ with _turn(_policy(home, ws, persistent=False), sid):+ plans[sid] = _plan(sid)+ # Each session: its own container, mounting its own client cwd at /workspace (None on main).+ assert plans == {'local-a': ('local-a', str(ws1)), 'local-b': ('local-b', str(ws2))}+++def test_persistent_container_is_keyed_per_workspace_not_per_profile(home, tmp_path):+ ws1, ws2 = tmp_path / 'ws1', tmp_path / 'ws2'+ ws1.mkdir(), ws2.mkdir()+ plans = {}+ for sid, ws in (('local-a', ws1), ('local-b', ws2), ('local-c', ws1)):+ with _turn(_policy(home, ws, persistent=True), sid):+ plans[sid] = _plan(sid)+ # Two workspaces: two containers, each bound to its own folder (main: one "default" for all).+ assert plans['local-a'][0] != plans['local-b'][0]+ assert (plans['local-a'][1], plans['local-b'][1]) == (str(ws1), str(ws2))+ # Same workspace: still ONE persistent container, shared across sessions as before.+ assert plans['local-c'] == plans['local-a']+++def test_binding_keeps_a_cd_and_follows_a_workspace_move(home, tmp_path):+ from tools.terminal_tool import get_session_cwd, record_session_cwd+ ws1, ws2 = tmp_path / 'ws1', tmp_path / 'ws2'+ ws1.mkdir(), ws2.mkdir()+ policy = _policy(home, ws1, persistent=False)+ with _turn(policy, 'local-a'):+ assert get_session_cwd('local-a') == str(ws1)+ record_session_cwd('local-a', '/workspace/sub') # the agent's own `cd`+ with _turn(policy, 'local-a'): # the next turn re-binds nothing that is already bound+ assert get_session_cwd('local-a') == '/workspace/sub'+ with _turn(_policy(home, ws2, persistent=False), 'local-a'): # moved to another project+ assert _plan('local-a') == ('local-a', str(ws2))++[email protected]('terminal', [{'backend': 'local'}, {'backend': 'ssh', 'cwd': '/srv'},+ {'backend': 'docker', 'docker_mount_cwd_to_workspace': False}])+def test_backends_that_do_not_mount_the_host_cwd_register_nothing(home, tmp_path, terminal):+ from gateway.session_policy import bind_turn_workspace, build_policy, policy_scope, restore_policy+ from tools import terminal_tool+ (home / 'config.yaml').write_text(json.dumps({'terminal': terminal}), encoding='utf-8')+ policy = restore_policy(asdict(build_policy({'source': 'cli', 'cwd': str(tmp_path), 'model': 'm'}, {})))+ with policy_scope(policy):+ bind_turn_workspace(policy, 'local-x')+ assert terminal_tool.resolve_task_overrides('local-x') == {}diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 0b0eacedd7b..bdfd2679110 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -522,7 +522,30 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:if not scope.docker_profile_scoped:return _qualify_task_key(f"session:{session_key}")profile = _current_session_profile() or "default"- return "default" if profile == "default" else f"profile:{profile}"+ base = "default" if profile == "default" else f"profile:{profile}"+ return _workspace_container_key(base, task_id)+++def _workspace_container_key(base: str, task_id: Optional[str]) -> str:+ """Persistent Docker key for a session that registered a workspace: one container per+ (profile, workspace), not per profile (#140665).++ A gateway-owned CLI/Desktop session registers its client cwd as a ``cwd_source: "session"``+ override (``gateway.session_policy.bind_turn_workspace``). Keyed by profile alone, every+ concurrent session shared the container bound to whichever workspace created it first; sessions+ in the same folder still share one. Sessions with no registered workspace keep the profile key.+ Reads the raw table (not :func:`resolve_task_overrides`, which calls back into key resolution).+ """+ overrides = _task_env_overrides.get(_qualify_task_key(task_id)) if task_id else None+ cwd = overrides.get("cwd") if overrides and overrides.get("cwd_source") == "session" else None+ if not isinstance(cwd, str) or not cwd.strip():+ return base+ import hashlib+ try:+ resolved = os.path.realpath(os.path.expanduser(cwd))+ except OSError:+ resolved = cwd+ return f"{base}:ws:{hashlib.sha256(resolved.encode('utf-8')).hexdigest()[:16]}"def resolve_task_overrides(task_id: Optional[str]) -> dict[str, Any]: