Skip to content

The agent that grows with you

refactor(terminal): extract _current_session_key() helper for session-key lookups

kshitijk4poor8e475ed27b11
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 9f4c2375416..b0ec8ff39e6 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"