Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 68 additions & 16 deletions gateway/session_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,36 +36,42 @@
platform = get_session_env("HERMES_SESSION_PLATFORM", "")
"""

from contextvars import ContextVar
from typing import Any
from contextlib import contextmanager
from contextvars import ContextVar, Token
from typing import Iterator, Optional

class _UnsetType:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not carry this sentinel/type migration into the salvage. The requested change is the public session-key wrapper pair, while current main has since expanded and hardened this ContextVar module; preserve its current state representation and add the wrappers only.

def __repr__(self) -> str:
return "<UNSET>"


# Sentinel to distinguish "never set in this context" from "explicitly set to empty".
# When a contextvar holds _UNSET, we fall back to os.environ (CLI/cron compat).
# When it holds "" (after clear_session_vars resets it), we return "" — no fallback.
_UNSET: Any = object()
_UNSET = _UnsetType()

# ---------------------------------------------------------------------------
# Per-task session variables
# ---------------------------------------------------------------------------

_SESSION_PLATFORM: ContextVar = ContextVar("HERMES_SESSION_PLATFORM", default=_UNSET)
_SESSION_CHAT_ID: ContextVar = ContextVar("HERMES_SESSION_CHAT_ID", default=_UNSET)
_SESSION_CHAT_NAME: ContextVar = ContextVar("HERMES_SESSION_CHAT_NAME", default=_UNSET)
_SESSION_THREAD_ID: ContextVar = ContextVar("HERMES_SESSION_THREAD_ID", default=_UNSET)
_SESSION_USER_ID: ContextVar = ContextVar("HERMES_SESSION_USER_ID", default=_UNSET)
_SESSION_USER_NAME: ContextVar = ContextVar("HERMES_SESSION_USER_NAME", default=_UNSET)
_SESSION_KEY: ContextVar = ContextVar("HERMES_SESSION_KEY", default=_UNSET)
_SESSION_ID: ContextVar = ContextVar("HERMES_SESSION_ID", default=_UNSET)
_SESSION_PLATFORM: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_PLATFORM", default=_UNSET)
_SESSION_CHAT_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_CHAT_ID", default=_UNSET)
_SESSION_CHAT_NAME: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_CHAT_NAME", default=_UNSET)
_SESSION_THREAD_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_THREAD_ID", default=_UNSET)
_SESSION_USER_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_USER_ID", default=_UNSET)
_SESSION_USER_NAME: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_USER_NAME", default=_UNSET)
_SESSION_KEY: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_KEY", default=_UNSET)
_SESSION_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_ID", default=_UNSET)
# ID of the message that triggered the current turn. Used as a reply anchor
# so background-process notifications stay inside the originating Telegram
# private-chat topic (those lanes route only with thread id + reply anchor).
_SESSION_MESSAGE_ID: ContextVar = ContextVar("HERMES_SESSION_MESSAGE_ID", default=_UNSET)
_SESSION_MESSAGE_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_SESSION_MESSAGE_ID", default=_UNSET)

# Cron auto-delivery vars — set per-job in run_job() so concurrent jobs
# don't clobber each other's delivery targets.
_CRON_AUTO_DELIVER_PLATFORM: ContextVar = ContextVar("HERMES_CRON_AUTO_DELIVER_PLATFORM", default=_UNSET)
_CRON_AUTO_DELIVER_CHAT_ID: ContextVar = ContextVar("HERMES_CRON_AUTO_DELIVER_CHAT_ID", default=_UNSET)
_CRON_AUTO_DELIVER_THREAD_ID: ContextVar = ContextVar("HERMES_CRON_AUTO_DELIVER_THREAD_ID", default=_UNSET)
_CRON_AUTO_DELIVER_PLATFORM: ContextVar[str | _UnsetType] = ContextVar("HERMES_CRON_AUTO_DELIVER_PLATFORM", default=_UNSET)
_CRON_AUTO_DELIVER_CHAT_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_CRON_AUTO_DELIVER_CHAT_ID", default=_UNSET)
_CRON_AUTO_DELIVER_THREAD_ID: ContextVar[str | _UnsetType] = ContextVar("HERMES_CRON_AUTO_DELIVER_THREAD_ID", default=_UNSET)

_VAR_MAP = {
"HERMES_SESSION_PLATFORM": _SESSION_PLATFORM,
Expand Down Expand Up @@ -98,6 +104,52 @@ def set_current_session_id(session_id: str) -> None:
_SESSION_ID.set(session_id)


def set_current_turn_session_key(session_key: Optional[str]) -> Token[str | _UnsetType]:
"""Bind the per-turn session-identity ContextVar to ``session_key``.

Accepts ``None`` (treated as empty string) so server-initiated turns can
pass through whatever they have without a pre-check; returns the
:class:`contextvars.Token` that callers MUST pass to
:func:`reset_current_turn_session_key` in a ``finally`` clause.

Public wrapper for the per-turn session-identity binding used by
server-initiated agent turns (e.g. completion-time wakeups) so
callers do not need to import ``_SESSION_KEY`` directly.

Mirror of the pattern at ``tools/approval.py`` for the
approval-session ContextVar; the public API here is intentionally
named with the ``turn_session_key`` suffix (and binds the
``_SESSION_KEY`` ContextVar) because the two ContextVars
carry different concerns:

* approval-session: identifies the human/policy session that
approves tool calls (``tools/approval.py:_approval_session_key``).
* per-turn session (``_SESSION_KEY`` in this module): identifies the
agent turn / chat session for downstream model-resolve, stream
routing, and persistence.
"""
return _SESSION_KEY.set(session_key or "")


def reset_current_turn_session_key(token: Token[str | _UnsetType]) -> None:
"""Reset the per-turn session-identity ContextVar.

Pair with :func:`set_current_turn_session_key` in a ``finally``
clause.
"""
_SESSION_KEY.reset(token)
Comment thread
Isla-Liu marked this conversation as resolved.
Resolved


@contextmanager

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The downstream contract described by this PR uses the explicit setter/resetter pair. Please omit this additional public context-manager API unless a concrete consumer needs it.

def turn_session_key(session_key: Optional[str]) -> Iterator[None]:
"""Context manager wrapper around the public per-turn session-key setters."""
token = set_current_turn_session_key(session_key)
try:
yield
finally:
reset_current_turn_session_key(token)


def set_session_vars(
platform: str = "",
chat_id: str = "",
Expand Down Expand Up @@ -173,7 +225,7 @@ def get_session_env(name: str, default: str = "") -> str:
var = _VAR_MAP.get(name)
if var is not None:
value = var.get()
if value is not _UNSET:
if isinstance(value, str):
return value
# Fall back to os.environ for CLI, cron, and test compatibility
return os.getenv(name, default)
71 changes: 71 additions & 0 deletions tests/test_session_context_public_turn_setters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Tests for public per-turn session-key setters in gateway.session_context.

These wrappers mirror tools/approval.py's set_current_session_key /
reset_current_session_key pattern but are deliberately named distinctly
(``turn_session_key``) because they target a different ContextVar
(``_SESSION_KEY`` in gateway.session_context) than the approval-session
ContextVar (``_approval_session_key`` in tools.approval).
"""

from gateway.session_context import (
get_session_env,
reset_current_turn_session_key,
set_current_turn_session_key,
turn_session_key,
)


def test_set_and_reset_round_trip(monkeypatch):
monkeypatch.setenv("HERMES_SESSION_KEY", "env-session")
previous = get_session_env("HERMES_SESSION_KEY")
token = set_current_turn_session_key("session-abc")
try:
assert get_session_env("HERMES_SESSION_KEY") == "session-abc"
finally:
reset_current_turn_session_key(token)
assert get_session_env("HERMES_SESSION_KEY") == previous
Comment thread
Isla-Liu marked this conversation as resolved.
Resolved


def test_nested_set_reset():
outer = set_current_turn_session_key("outer")
try:
assert get_session_env("HERMES_SESSION_KEY") == "outer"
inner = set_current_turn_session_key("inner")
try:
assert get_session_env("HERMES_SESSION_KEY") == "inner"
finally:
reset_current_turn_session_key(inner)
assert get_session_env("HERMES_SESSION_KEY") == "outer"
finally:
reset_current_turn_session_key(outer)


def test_empty_string_round_trip():
token = set_current_turn_session_key("")
try:
assert get_session_env("HERMES_SESSION_KEY") == ""
finally:
reset_current_turn_session_key(token)


def test_none_coerced_to_empty_string():
# set_current_turn_session_key(None) should not raise; treat as "".
token = set_current_turn_session_key(None)
try:
assert get_session_env("HERMES_SESSION_KEY") == ""
finally:
reset_current_turn_session_key(token)
Comment thread
Isla-Liu marked this conversation as resolved.
Resolved


def test_turn_session_key_context_manager_restores_previous_value(monkeypatch):
monkeypatch.setenv("HERMES_SESSION_KEY", "env-session")

with turn_session_key("session-xyz"):
assert get_session_env("HERMES_SESSION_KEY") == "session-xyz"

assert get_session_env("HERMES_SESSION_KEY") == "env-session"


def test_turn_session_key_context_manager_none_coerces_to_empty_string():
with turn_session_key(None):
assert get_session_env("HERMES_SESSION_KEY") == ""