From 8e475ed27b1199b8d0bbf094cf2e15fcd555f8cf Mon Sep 17 00:00:00 2001 From: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> Date: Sat, 22 Aug 2026 14:55:41 +0530 Subject: [PATCH] refactor(terminal): extract _current_session_key() helper for session-key lookups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the session-scoping fix: _get_sudo_password_cache_scope() and _resolve_container_task_id() carried byte-identical copies of the HERMES_SESSION_KEY lookup (contextvar + os.environ fallback). Collapse both onto one helper adopting the bare-import convention approval.py already uses — get_session_env() implements the fallback internally, so the old try/except could only fire on import failure, where silently degrading to process-global semantics would reintroduce exactly the cross-session contamination the fix prevents. --- tools/terminal_tool.py | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index 9f4c237541..b0ec8ff39e 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -272,6 +272,19 @@ def _get_sudo_password_callback(): return getattr(_callback_tls, "sudo_password", None) +def _current_session_key() -> str: + """Return the active gateway/WebUI session key, or "" outside sessions. + + Single lookup point for the ``HERMES_SESSION_KEY`` ContextVar with the + os.environ fallback that ``get_session_env()`` applies for CLI, cron, and + test processes. Callers scope per-session caches by prefixing the value + with ``"session:"`` so two sessions never share a cache slot. + """ + from gateway.session_context import get_session_env + + return get_session_env("HERMES_SESSION_KEY", "") + + def _get_approval_callback(): return getattr(_callback_tls, "approval", None) @@ -297,12 +310,7 @@ def set_approval_callback(cb): def _get_sudo_password_cache_scope() -> str: """Return the cache scope for interactive sudo passwords.""" - try: - from gateway.session_context import get_session_env - - session_key = get_session_env("HERMES_SESSION_KEY", "") - except Exception: - session_key = os.getenv("HERMES_SESSION_KEY", "") + session_key = _current_session_key() if session_key: return f"session:{session_key}" @@ -1398,12 +1406,7 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str: # branches above: those paths already key containers per task_id, so they # stay authoritative where they apply and this only covers the cases that # would otherwise collapse to the shared "default" key (notably SSH). - try: - from gateway.session_context import get_session_env - - session_key = get_session_env("HERMES_SESSION_KEY", "") - except Exception: - session_key = os.getenv("HERMES_SESSION_KEY", "") + session_key = _current_session_key() if session_key: return f"session:{session_key}" return "default"