The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): qualify session-isolated container keys and cwd records under a routed profile scope (#123989)
Nabil Ahmed Ameenaa6706b5c1b53
diff --git a/tests/tools/test_docker_session_isolation.py b/tests/tools/test_docker_session_isolation.pyindex fa104ae9612..e45b62ce68d 100644--- a/tests/tools/test_docker_session_isolation.py+++ b/tests/tools/test_docker_session_isolation.py@@ -130,6 +130,104 @@ class TestSessionIsolationKeying:assert terminal_tool._resolve_container_task_id("x") in {"x", "y"}+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"++ 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_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 = {}+ for name in ("research", "default"):+ home = tmp_path / "profiles" / name+ home.mkdir(parents=True)+ token = set_hermes_home_override(str(home))+ try:+ keys[name] = terminal_tool._resolve_container_task_id(raw)+ 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"++class TestSessionScopedMountResolution:"""_resolve_task_host_cwd: the single owner of the cwd→/workspace mount policy."""diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 859bc2e6c4e..a945515e795 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -253,10 +253,19 @@ _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 completedcommand, or on workspace-override registration). None/empty keys collapse- to ``"default"``; non-string / empty cwds are ignored."""+ 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.+ """if not isinstance(cwd, str) or not cwd.strip():return- key = str(session_key or "default")+ key = _qualify_task_key(str(session_key or "default"))with _session_cwd_lock:if _session_cwd.get(key) != cwd:_session_cwd[key] = cwd@@ -264,15 +273,16 @@ 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"``."""+ callers decide what an absent record means. None/empty keys read+ ``"default"``. Qualified the same way as :func:`record_session_cwd`."""with _session_cwd_lock:- return _session_cwd.get(str(session_key or "default"))+ return _session_cwd.get(_qualify_task_key(str(session_key or "default")))def clear_session_cwd(session_key: str) -> None:"""Drop a session's cwd record (session teardown)."""with _session_cwd_lock:- _session_cwd.pop(session_key, None)+ _session_cwd.pop(_qualify_task_key(session_key), None)def _sanitize_cwd_for_live_env(env: Any, new_cwd: str) -> Optional[str]:@@ -462,6 +472,38 @@ 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++def _resolve_container_task_id(task_id: Optional[str]) -> str:"""Map a tool-call ``task_id`` to the ``_active_environments`` key. Order matters —earlier branches are authoritative where they apply:@@ -471,6 +513,9 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:2. Per-session isolation (docker + ``container_persistent: false``): eachsession's task_id is its own key (a fresh chat gets a fresh sandbox with onlyITS 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).3. Session key present (WebUI per-session, gateway per-message): persistentDocker is PROFILE-scoped — ``shared:<key>`` opt-in, else ``profile:<name>``,with the default profile staying literally ``"default"`` so CLI and@@ -486,7 +531,15 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:return task_idscope = _session_scope()if task_id and scope.session_isolated:- return _resolve_container_alias(task_id)+ # 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# a previous profile's SSHEnvironment and silently run commands on the wrong remote host. Subagents@@ -1384,7 +1437,8 @@ 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.+ # session_key) as a stable anchor. Record/read functions qualify the+ # key under a routed scope (#123989), so every caller stays symmetric.from tools.approval import get_current_session_keysession_key = get_current_session_key(default="") or (task_id or "")