Files
hermes-agent/agent/agent_init_session.py
yoniebans 8fd1fcbe0c docs(agent): an agent built on a SessionDB borrows its handle
An agent given hermes_state.SessionDB as session_db writes through the handle that SessionDB holds when the agent is built. The stand_in_interface docstring and the plugin guide's SessionDB() row now say the caller keeps that SessionDB open for the agent's life: its close() releases the handle, and its reopen after close() gives the agent no new one.
2026-11-17 19:10:58 +01:00

49 lines
2.3 KiB
Python

"""Session plumbing an agent sets up at construction: publishing its session id, and naming the storage
interface handle it writes its own store through."""
import os
import sys
def _publish_session_id(session_id: str) -> None:
"""Expose the session ID to tools via ContextVar (+ legacy os.environ fallback).
If the ContextVar bridge fails to import, keep the root-agent env fallback but never let
delegated construction publish a child ID process-wide.
"""
try:
from gateway.session_context import set_current_session_id
set_current_session_id(session_id)
except Exception:
try:
from agent.delegation_context import is_delegated_child_context
delegated_child = is_delegated_child_context()
except Exception:
delegated_child = False
if not delegated_child:
os.environ["HERMES_SESSION_ID"] = session_id
def writer_interface(persistence, store):
"""``persistence`` when it is a writer's handle beside ``store``, else None: no store, no handle, or a reader
beside a store that is a client of the file's owner (a managed worker's, the classic CLI's), whose calls stay
on that store."""
return persistence if store is not None and persistence is not None and not persistence.read_only else None
def stand_in_interface(session_db):
"""The storage interface handle a writable ``hermes_state.SessionDB`` forwards to, when ``session_db`` is one, else
None. The stand-in carries only the plugin guide's methods, so an agent given it alone writes through the handle;
no stand-in exists before ``hermes_state`` is imported. The agent borrows the handle the SessionDB holds when the
agent is built, so the caller keeps that SessionDB open for the agent's life: its close() releases the handle, and
its reopen after close() gives the agent no new one."""
stand_in = sys.modules.get("hermes_state")
if stand_in is None or not isinstance(session_db, stand_in._SessionDB) or session_db.read_only:
return None
return session_db._store
def agent_interface(agent):
"""The agent's storage interface handle for its own store (:func:`writer_interface`), or None."""
return writer_interface(getattr(agent, "persistence", None), getattr(agent, "_session_db", None))