session_context.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. """Session-scoped context variables for the Hermes gateway.
  2. Replaces the old ``os.environ``-based ``HERMES_SESSION_*`` state with task-local ``ContextVar``s
  3. (inherited by ``run_in_executor`` threads), so concurrently handled messages no longer clobber each
  4. other's routing ids. ``get_session_env`` is a drop-in for ``os.getenv``.
  5. """
  6. import os
  7. from contextlib import contextmanager
  8. from contextvars import ContextVar
  9. from typing import Any, Iterator
  10. # "Never set here" (falls back to os.environ for CLI/cron) vs "" = explicitly cleared (no fallback).
  11. _UNSET: Any = object()
  12. # Process-level latch: has set_session_vars() ever bound a session? When engaged, the subprocess
  13. # env bridge treats ContextVars as authoritative and an _UNSET var as "no session in THIS task".
  14. _session_context_engaged: bool = False
  15. def session_context_engaged() -> bool:
  16. """True if any session has been bound via set_session_vars in this process."""
  17. return _session_context_engaged
  18. # --- Per-task session variables: bound by set_session_vars / cleared to "" by clear_session_vars;
  19. # tuple ORDER is the positional order of ``values`` in set_session_vars (zipped).
  20. # * SCOPE_ID: platform-neutral scope (guild / workspace / Matrix server) so async producers can
  21. # persist a completion's full routing origin (relay egress guards need it).
  22. # * UI_SESSION_ID: in-process UI tab id, separate from the durable SESSION_ID, so a stale/rotated
  23. # durable key is not consumed by the wrong poller.
  24. # * MESSAGE_ID: reply anchor keeping notifications inside the originating Telegram topic.
  25. # * CRON_SESSION: tri-state — _UNSET = legacy env fallback; "1" = cron; "" = non-cron, masks env.
  26. _SESSION_VARS = (
  27. _SESSION_PLATFORM, _SESSION_SOURCE, _SESSION_CHAT_ID, _SESSION_CHAT_TYPE,
  28. _SESSION_CHAT_NAME, _SESSION_THREAD_ID, _SESSION_USER_ID, _SESSION_USER_ID_ALT,
  29. _SESSION_USER_NAME, _SESSION_SCOPE_ID, _SESSION_KEY, _SESSION_ID,
  30. _SESSION_UI_SESSION_ID, _SESSION_MESSAGE_ID, _SESSION_PROFILE, _CRON_SESSION, _SESSION_PARENT_CHAT_ID,
  31. ) = tuple(ContextVar(name, default=_UNSET) for name in (
  32. "HERMES_SESSION_PLATFORM", "HERMES_SESSION_SOURCE", "HERMES_SESSION_CHAT_ID",
  33. "HERMES_SESSION_CHAT_TYPE", "HERMES_SESSION_CHAT_NAME", "HERMES_SESSION_THREAD_ID",
  34. "HERMES_SESSION_USER_ID", "HERMES_SESSION_USER_ID_ALT", "HERMES_SESSION_USER_NAME",
  35. "HERMES_SESSION_SCOPE_ID", "HERMES_SESSION_KEY", "HERMES_SESSION_ID",
  36. "HERMES_UI_SESSION_ID", "HERMES_SESSION_MESSAGE_ID", "HERMES_SESSION_PROFILE",
  37. "HERMES_CRON_SESSION", "HERMES_SESSION_PARENT_CHAT_ID",
  38. ))
  39. # Whether this channel can route an ASYNC completion back AFTER the turn ends (see
  40. # ``async_delivery_supported()``). _UNSET => supported (CLI, contextvar-unaware paths); stateless
  41. # adapters (API server, Kanban workers) opt OUT via ``supports_async_delivery = False`` at bind.
  42. _SESSION_ASYNC_DELIVERY = ContextVar("HERMES_SESSION_ASYNC_DELIVERY", default=_UNSET)
  43. # Request-local proof that the client resumes SessionDB history. No env fallback
  44. # or child-process export: a bound id alone cannot authorize detached delivery.
  45. _SESSION_HISTORY_DELIVERY = ContextVar("HERMES_SESSION_HISTORY_DELIVERY", default=_UNSET)
  46. # Cron auto-delivery vars, set per-job in run_job() so concurrent jobs don't clobber.
  47. _CRON_AUTO_DELIVER_PLATFORM = ContextVar("HERMES_CRON_AUTO_DELIVER_PLATFORM", default=_UNSET)
  48. _CRON_AUTO_DELIVER_CHAT_ID = ContextVar("HERMES_CRON_AUTO_DELIVER_CHAT_ID", default=_UNSET)
  49. _CRON_AUTO_DELIVER_THREAD_ID = ContextVar("HERMES_CRON_AUTO_DELIVER_THREAD_ID", default=_UNSET)
  50. # Legacy env-var name -> ContextVar for get_session_env (_SESSION_ASYNC_DELIVERY deliberately
  51. # absent: it is a bool capability, read via async_delivery_supported).
  52. _VAR_MAP = {var.name: var for var in (
  53. *_SESSION_VARS, _CRON_AUTO_DELIVER_PLATFORM, _CRON_AUTO_DELIVER_CHAT_ID,
  54. _CRON_AUTO_DELIVER_THREAD_ID,
  55. )}
  56. def _runtime_cwd(func: str, *args: Any) -> None:
  57. """Best-effort call of ``agent.runtime_cwd.<func>``; import/runtime failures are ignored."""
  58. try:
  59. from agent import runtime_cwd
  60. getattr(runtime_cwd, func)(*args)
  61. except Exception:
  62. pass
  63. def set_current_session_id(session_id: str) -> None:
  64. """Synchronize ``HERMES_SESSION_ID`` across ContextVar and ``os.environ`` (tools read it
  65. with an os.environ fallback). Delegated subagent children (built in the parent process)
  66. get ONLY the task-local write, or they would clobber the parent's id."""
  67. _SESSION_ID.set(session_id)
  68. try:
  69. from agent.delegation_context import is_delegated_child_context
  70. if is_delegated_child_context():
  71. return
  72. except Exception:
  73. pass
  74. os.environ["HERMES_SESSION_ID"] = session_id
  75. @contextmanager
  76. def scoped_current_session_id(session_id: str | None = None) -> Iterator[None]:
  77. """Bind a task-local session id and restore the prior value on exit; never touches
  78. ``os.environ``. ``session_id=None`` is a pure save/restore boundary."""
  79. previous = _SESSION_ID.get()
  80. if session_id is not None:
  81. _SESSION_ID.set(session_id)
  82. try:
  83. yield
  84. finally:
  85. _SESSION_ID.set(previous)
  86. @contextmanager
  87. def scoped_session_key(session_key: str) -> Iterator[None]:
  88. """Bind only the route key of the session a call works for (a hook fired for it outside its
  89. turn) and restore the prior value on exit; never touches ``os.environ``."""
  90. token = _SESSION_KEY.set(session_key)
  91. try:
  92. yield
  93. finally:
  94. _SESSION_KEY.reset(token)
  95. def bound_session_key() -> str:
  96. """The route key bound in THIS context, ``""`` when none is: no ``os.environ`` fallback, so a
  97. thread that inherited no context never borrows another session's key."""
  98. value = _SESSION_KEY.get()
  99. return "" if value is _UNSET else value
  100. def source_route_metadata(source: Any, metadata: dict | None) -> dict | None:
  101. """Keep inbound route anchors for durable deliveries after the source is gone."""
  102. anchors = {key: str(value) for key in ("scope_id", "parent_chat_id")
  103. if (value := getattr(source, key, None))}
  104. return {**(metadata or {}), **anchors} if anchors else metadata
  105. def set_session_vars(
  106. platform: str = "", source: str = "", chat_id: str = "", chat_type: str = "",
  107. chat_name: str = "", thread_id: str = "", user_id: str = "", user_id_alt: str = "",
  108. user_name: str = "", scope_id: str = "", session_key: str = "", session_id: str = "",
  109. message_id: str = "", profile: str = "", cwd: str = "", async_delivery: bool = True,
  110. ui_session_id: str = "", cron_session: Any = _UNSET, parent_chat_id: str = "",
  111. session_history_delivery: str | None = None,
  112. ) -> list:
  113. """Set all session context variables and return reset tokens. Call
  114. ``clear_session_vars(tokens)`` in a ``finally``; not nestable, clearing resets every var
  115. to ``""`` rather than restoring prior values (tokens are accepted only for API compat).
  116. ``session_history_delivery`` declares whether the bound chat id is one the client can address again:
  117. ``"1"`` (audited producers — explicit session-id header, native API sessions, /v1/runs) or
  118. ``""`` / omitted (default-deny, #98619). ``None`` leaves the var at ``_UNSET`` ("never
  119. declared"), which ``session_history_delivery_supported()`` treats as NOT capable — an omitted declaration
  120. cannot grant wake authority."""
  121. global _session_context_engaged
  122. _session_context_engaged = True
  123. values = (
  124. platform, source, chat_id, chat_type, chat_name, thread_id, user_id, user_id_alt,
  125. user_name, scope_id, session_key, session_id, ui_session_id, message_id, profile,
  126. cron_session, parent_chat_id,
  127. )
  128. tokens = [var.set(value) for var, value in zip(_SESSION_VARS, values)]
  129. tokens.append(_SESSION_ASYNC_DELIVERY.set(bool(async_delivery)))
  130. tokens.append(_SESSION_HISTORY_DELIVERY.set(_UNSET if session_history_delivery is None else session_history_delivery))
  131. _runtime_cwd("set_session_cwd", cwd)
  132. return tokens
  133. def clear_session_vars(tokens: list) -> None:
  134. """Mark session context variables as explicitly cleared (``""``, not ``_UNSET``), so
  135. ``get_session_env`` returns empty instead of stale ``os.environ`` values. Async-delivery
  136. goes back to ``_UNSET``: a cleared context is default-supported, not opted-out. Wake
  137. capability goes back to ``_UNSET`` too — but for the opposite reason: a cleared context has
  138. declared nothing, and an undeclared capability FAILS CLOSED (#98619)."""
  139. for var in _SESSION_VARS:
  140. var.set("")
  141. _SESSION_ASYNC_DELIVERY.set(_UNSET)
  142. _SESSION_HISTORY_DELIVERY.set(_UNSET)
  143. _runtime_cwd("clear_session_cwd")
  144. def reset_session_vars() -> None:
  145. """Reset every session var to ``_UNSET`` ("never bound here") for THIS context. Call at
  146. the top of a fresh task *before* it binds: ``create_task`` snapshots the context, so B's
  147. task inherits A's already-set vars and a subprocess spawned before B binds would read A's
  148. identity. ``_SESSION_ASYNC_DELIVERY`` and ``_SESSION_HISTORY_DELIVERY`` (outside ``_VAR_MAP``)
  149. are reset explicitly too."""
  150. for var in _VAR_MAP.values():
  151. var.set(_UNSET)
  152. _SESSION_ASYNC_DELIVERY.set(_UNSET)
  153. _SESSION_HISTORY_DELIVERY.set(_UNSET)
  154. _runtime_cwd("clear_session_cwd")
  155. def get_session_env(name: str, default: str = "") -> str:
  156. """Read a session var by legacy ``HERMES_SESSION_*`` name; drop-in for os.getenv. The
  157. ContextVar wins if ever set here (even to ``""``); else ``os.environ``; else *default*."""
  158. var = _VAR_MAP.get(name)
  159. if var is not None and (value := var.get()) is not _UNSET:
  160. return value
  161. return os.getenv(name, default)
  162. # Surfaces that are not a human chat channel (gateway binds HERMES_SESSION_PLATFORM, CLI/TUI/
  163. # desktop bind HERMES_SESSION_SOURCE, so both are consulted). Default-deny: an unrecognized
  164. # identity counts as messaging. Mirrors LOCAL_SESSION_SOURCE_IDS in apps/desktop session-source.ts.
  165. NON_MESSAGING_SESSION_SURFACES = frozenset({
  166. "", "api_server", "cli", "codex", "desktop", "gateway", "kanban", "local",
  167. "msgraph_webhook", "tool", "tui", "webhook",
  168. })
  169. def session_is_messaging_surface() -> bool:
  170. """Whether this turn is delivered over a human messaging channel (checks
  171. ``HERMES_PLATFORM``, then the session platform, then the session source)."""
  172. platform = os.getenv("HERMES_PLATFORM") or get_session_env("HERMES_SESSION_PLATFORM", "")
  173. idents = (platform, get_session_env("HERMES_SESSION_SOURCE", ""))
  174. idents = (str(v or "").strip().lower() for v in idents)
  175. return any(ident and ident not in NON_MESSAGING_SESSION_SURFACES for ident in idents)
  176. def declare_stateless_channel() -> None:
  177. """Declare that this session cannot receive an async background completion. Unlike
  178. ``set_session_vars(async_delivery=False)`` this does NOT latch ``_session_context_engaged``
  179. (flipping the subprocess env bridge), which a one-shot CLI must not do as a side effect.
  180. See NousResearch/hermes-agent#53027 and #63142.
  181. """
  182. _SESSION_ASYNC_DELIVERY.set(False)
  183. def async_delivery_supported() -> bool:
  184. """Whether the current session can deliver a background completion later. False for
  185. stateless channels (:func:`declare_stateless_channel`), Kanban workers
  186. (``HERMES_KANBAN_TASK``: one-shot subprocesses whose parent disappears after the turn) and
  187. registered worker processes: a managed worker exits at its turn boundary, so detached work
  188. it scheduled would be lost (recovered ``unknown``) and its completion queue has no reader."""
  189. from agent.runtime_session_store import is_worker_process
  190. if os.environ.get("HERMES_KANBAN_TASK") or is_worker_process():
  191. return False
  192. value = _SESSION_ASYNC_DELIVERY.get()
  193. return True if value is _UNSET else bool(value)
  194. def session_history_delivery_supported() -> bool:
  195. """Whether this request declares a server-history consumer for detached results.
  196. Fail closed on omitted bindings; never borrow authority from the environment."""
  197. return _SESSION_HISTORY_DELIVERY.get() == "1"