Repository navigation
feat(session_context): add set/reset_current_turn_session_key public wrappers #32927
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Isla-Liu
wants to merge
4
commits into
NousResearch:main
Choose a base branch
from
Isla-Liu:feat/session-context-public-turn-setters
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9ab519c
feat(session_context): add set/reset_current_turn_session_key
Isla-Liu 0b13947
fix(32927 round-2): address Copilot inline comments
Isla-Liu 6f7db19
fix(32927 round-3): address Copilot session context comments
Isla-Liu f8ffb2c
fix: address Copilot review on session context setters
Isla-Liu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
| 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, | ||
|
|
@@ -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) | ||
|
Isla-Liu marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| @contextmanager | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 = "", | ||
|
|
@@ -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) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
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) | ||
|
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") == "" | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.