The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(review): key cwd/override records by the session's own profile home; keep /p/<launch>/ ids stable
teknium1124b5c7d451a
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 1f8b1fd3aed..83d7410eb60 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1057,15 +1057,27 @@ def _make_request_fingerprint(body: Dict[str, Any], keys: List[str]) -> str:return hashlib.sha256(repr(subset).encode("utf-8")).hexdigest()+def _names_launch_profile(profile: str) -> bool:+ """True when a /p/<profile>/ prefix names the profile this process was LAUNCHED as: its+ un-prefixed and prefixed requests are one profile and must key one session."""+ try:+ from hermes_cli.profiles import profile_matches_home+ from hermes_constants import get_routing_process_hermes_home+ return profile_matches_home(profile, home=get_routing_process_hermes_home())+ except Exception:+ return False++def _derive_chat_session_id(system_prompt: Optional[str], first_user_message: str,profile: Optional[str] = None) -> str:"""Stable session id from the system prompt + first user message (constant across allturns of an Open WebUI-style conversation), so one Hermes session/sandbox is reused.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."""+ collide (#123989). Default/standalone ids are unchanged so live conversations survive, and+ the launch profile addressed through its own ``/p/<launch>/`` prefix keeps the un-prefixed id."""seed = f"{system_prompt or ''}\n{first_user_message}"- if profile and profile != "default":+ if profile and profile != "default" and not _names_launch_profile(profile):seed = f"{profile}\0{seed}"digest = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:16]return f"api-{digest}"diff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.pyindex 80c7729b84d..15fa8a5225e 100644--- a/tests/gateway/test_api_server.py+++ b/tests/gateway/test_api_server.py@@ -1415,6 +1415,19 @@ class TestDeriveChatSessionId:assert research != legacyassert research == _derive_chat_session_id("sys", "hello", "research")+ def test_launch_profile_prefix_keeps_the_unprefixed_id(self, monkeypatch, tmp_path):+ """A gateway launched as ``work`` serves ``/p/work/`` and the bare route as ONE profile:+ both must derive one id, or the same conversation forks by URL."""+ import hermes_constants+ from hermes_cli import profiles++ work = tmp_path / "profiles" / "work"+ work.mkdir(parents=True)+ monkeypatch.setattr(hermes_constants, "get_routing_process_hermes_home", lambda: work)+ monkeypatch.setattr(profiles, "get_profile_dir", lambda name: tmp_path / "profiles" / name)+ assert _derive_chat_session_id("sys", "hello", "work") == _derive_chat_session_id("sys", "hello")+ assert _derive_chat_session_id("sys", "hello", "research") != _derive_chat_session_id("sys", "hello")+# ---------------------------------------------------------------------------# /v1/responses endpointdiff --git a/tests/tui_gateway/test_session_cwd_profile_key.py b/tests/tui_gateway/test_session_cwd_profile_key.pynew file mode 100644index 00000000000..4b796349145--- /dev/null+++ b/tests/tui_gateway/test_session_cwd_profile_key.py@@ -0,0 +1,39 @@+"""A secondary profile's session.create cwd record is readable inside that profile's turn scope.++``session.create`` is a plain ``@method`` (no profile scope bound), while the turn that reads the+record runs under the session's profile home. Since the terminal keys its cwd/override records by+the routed home (#123989), the writer must bind the same home or the record lands under the raw+key and ``get_session_cwd`` misses until the first ``cd``.+"""++from __future__ import annotations++import tools.terminal_tool as terminal_tool+import tui_gateway.server as server+++def test_secondary_profile_session_cwd_is_found_inside_its_scope(monkeypatch, tmp_path):+ from agent import secret_scope+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})+ monkeypatch.setattr(terminal_tool, "_session_cwd", {})+ monkeypatch.setattr(server, "_effective_terminal_backend", lambda: "local")+ home = tmp_path / "profiles" / "research"+ home.mkdir(parents=True)+ workspace = tmp_path / "ws"+ workspace.mkdir()+ session = {"session_key": "sess-b", "cwd": str(workspace), "explicit_cwd": True,+ "source": "desktop", "profile_home": str(home)}+ secret_scope.set_multiplex_active(True)+ try:+ server._register_session_cwd(session) # session.create path: no scope bound by the caller+ token = set_hermes_home_override(str(home))+ try:+ assert terminal_tool.get_session_cwd("sess-b") == str(workspace)+ assert terminal_tool.resolve_task_overrides("sess-b")["cwd"] == str(workspace)+ finally:+ reset_hermes_home_override(token)+ assert terminal_tool.get_session_cwd("sess-b") is None # not leaked onto the launch profile's key+ finally:+ secret_scope.set_multiplex_active(False)diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex fb72f8972a6..a699d4a5bb3 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -322,8 +322,11 @@ def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):mid-session via ``session/load``). The session record keeps the RAW path(host workspaces are tracked there on purpose); only the live-env write issanitized, since a host cwd can never be a container workdir.++ Keyed like ``_session_cwd`` — routed-profile qualified (:func:`_qualify_task_key`) — so two+ profiles registering the same task id never read each other's image/cwd (#123989)."""- _task_env_overrides[task_id] = overrides+ _task_env_overrides[_qualify_task_key(task_id)] = overridesnew_cwd = overrides.get("cwd")if isinstance(new_cwd, str) and new_cwd.strip():@@ -342,7 +345,7 @@ def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):def clear_task_env_overrides(task_id: str):"""Drop a task's overrides, cwd record and container alias (rollout cleanup)."""- _task_env_overrides.pop(task_id, None)+ _task_env_overrides.pop(_qualify_task_key(task_id), None)clear_session_cwd(task_id)with _container_alias_lock:_container_aliases.pop(task_id, None)@@ -378,9 +381,8 @@ def _has_isolation_overrides(task_id: Optional[str]) -> bool:"""True when *task_id* registered image/env_type overrides — the single"isolated RL/benchmark rollout" predicate shared by key resolution andcontainer 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)+ overrides = _task_env_overrides.get(_qualify_task_key(task_id)) if task_id else None+ return bool(overrides and set(overrides) & _ISOLATION_OVERRIDE_KEYS)@dataclass(frozen=True)@@ -499,7 +501,7 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:else ``"default"``, which subagent ids collapse onto to share the parent's container."""if task_id and _has_isolation_overrides(task_id):- return task_id+ return _qualify_task_key(task_id)scope = _session_scope()if task_id and scope.session_isolated:return _qualify_task_key(_resolve_container_alias(task_id))@@ -538,7 +540,7 @@ def resolve_task_overrides(task_id: Optional[str]) -> Dict[str, Any]:"""raw = task_id or "default"return (- _task_env_overrides.get(raw)+ _task_env_overrides.get(_qualify_task_key(raw))or _task_env_overrides.get(_resolve_container_task_id(raw))or {})diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 65f9f4c4ed9..314a75b6037 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -313,7 +313,13 @@ def _register_session_cwd(session: dict | None) -> None:with contextlib.suppress(Exception):from tools.terminal_tool import register_task_env_overridescwd, cwd_source = _terminal_task_cwd_with_source(session)- register_task_env_overrides(session["session_key"], {"cwd": cwd, "cwd_source": cwd_source})+ # The cwd/override record is keyed by the ROUTED home (#123989). session.create is a plain+ # @method, so bind the session's own profile home here or the record lands under the raw key+ # and the scoped turn (`profile:<p>:<key>`) misses it until the first `cd`.+ with contextlib.ExitStack() as stack:+ if profile_home := session.get("profile_home"):+ stack.callback(reset_hermes_home_override, set_hermes_home_override(str(profile_home)))+ register_task_env_overrides(session["session_key"], {"cwd": cwd, "cwd_source": cwd_source})def _workdir_row_model_config(session: dict) -> tuple[str, dict]: