Skip to content

The agent that grows with you

fix(api_server): keep one memory provider per session across requests (#120116)

teknium1eb8960fead33
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 4d2bb6c993f..918b9fe2313 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1256,7 +1256,7 @@ def _memory_provider_init_kwargs(agent, platform) -> Dict[str, Any]:
return kwargs
-def _init_memory(agent, _agent_cfg, skip_memory, platform):
+def _init_memory(agent, _agent_cfg, skip_memory, platform, memory_manager=None):
# Persistent memory (MEMORY.md + USER.md) — loaded from disk
agent._memory_store = None
agent._memory_enabled = False
@@ -1297,7 +1297,12 @@ def _init_memory(agent, _agent_cfg, skip_memory, platform):
# External memory provider plugin (one at a time, alongside built-in): memory.provider.
agent._memory_manager = None
- if not skip_memory:
+ if memory_manager is not None and not skip_memory:
+ # A caller that rebuilds the agent per turn (gateway api_server) hands back the session's
+ # already-initialized manager: providers keep their prefetch/retain state across turns instead
+ # of being re-initialized (#120116). No initialize_all — the providers are already bound.
+ agent._memory_manager = memory_manager
+ elif not skip_memory:
try:
_mem_provider_name = mem_config.get("provider", "") if mem_config else ""
if not is_core_memory_provider(_mem_provider_name):
@@ -2345,7 +2350,7 @@ def init_agent(
checkpoint_max_snapshots: int = 20, checkpoint_max_total_size_mb: int = 500,
checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,
requested_provider: str = None, capabilities: Optional[Dict[str, bool]] = None, cwd: Optional[str] = None,
- side_agent: bool = False,
+ side_agent: bool = False, memory_manager=None,
):
_install_safe_stdio()
@@ -2424,7 +2429,7 @@ def init_agent(
_agent_cfg = {}
_apply_display_config(agent, _agent_cfg, platform)
- _init_memory(agent, _agent_cfg, skip_memory, platform)
+ _init_memory(agent, _agent_cfg, skip_memory, platform, memory_manager=memory_manager)
_apply_agent_section(agent, _agent_cfg)
cs = _parse_compression_config(agent, _agent_cfg)
_config_context_length, _custom_providers, _effective_context_length, _model_cfg = _resolve_context_length(
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.md
index 075c6ae2159..a5552a47c96 100644
--- a/gateway/AGENTS.md
+++ b/gateway/AGENTS.md
@@ -210,6 +210,13 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki
Resolve the owning home from the session record (`profile_home`, `agent:<profile>:` key), never
from `os.environ`, which holds the launch profile. Why: eviction that flushed under the launch scope
wrote a secondary profile's memories into the default profile's store, silently.
+- **`api_server` rebuilds the agent per request but not the memory provider.** The adapter bypasses
+ `TurnRunner` and the agent cache (per-request callbacks, model route, ephemeral prompt), so
+ `platforms/api_server_memory_sessions.py` parks each session's initialised `MemoryManager` between
+ requests (exclusive check-out in `_create_agent`, check-in in the turn's `finally`, keyed by profile
+ home + `agent.session_id`; idle/LRU eviction shuts down under the owning home) and
+ `AIAgent(memory_manager=...)` adopts it without a second provider init. Without it the previous
+ turn's queued recall never reaches the next request (#120116).
- **`multiplex_profiles: false` is not "no scope ever".** A native hosted room serving a second
profile flips the process-wide guard (`tui_gateway/launch_profile_policy.py::
activate_multi_profile_hosting`) inside the gateway process, after the adapters were wired; every
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 4ea5a6eef73..fee6782a27b 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -122,6 +122,7 @@ from gateway.platforms import api_server_room_dispatch as _room_dispatch
from gateway.platforms import api_server_room_grants as _room_grants
from gateway.platforms import api_server_runs as _api_runs
from gateway.platforms.api_server_openai_routes import OpenAICompatRoutesMixin
+from gateway.platforms.api_server_memory_sessions import ApiServerMemorySessions
from gateway.platforms.base import (
MEDIA_TAG_CLEANUP_RE, BasePlatformAdapter, SendResult, _terminal_sentinel_start, is_network_accessible,
validate_media_delivery_path)
@@ -1214,6 +1215,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
# Every agent inside _run_agent() for shutdown interrupt, keyed by id() (the strong ref
# keeps the id() from recycling); distinct from the run_id-keyed _active_run_agents.
self._shutdown_interruptible_agents: Dict[int, Any] = {}
+ # One memory provider per session across requests (this surface rebuilds the agent per turn).
+ self._memory_sessions = ApiServerMemorySessions()
self.gateway_runner: Optional[Any] = None # set by gateway/run.py
# Admitted requests not yet in agent bookkeeping, so shutdown drain counts them.
self._pending_agent_requests: int = 0
@@ -2236,7 +2239,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
# Same fallback provider chain as Telegram/Discord/Slack.
"fallback_model": None if confirmed_runtime_lock else GatewayRunner._load_fallback_model(),
"reasoning_config": request_reasoning_config,
- "gateway_session_key": gateway_session_key}
+ "gateway_session_key": gateway_session_key,
+ # The session's provider from the previous request, so its queued recall reaches this turn
+ # (#120116); checked back in by the turn's finally.
+ "memory_manager": self._memory_sessions.checkout(session_id)}
if request_service_tier is not _REQUEST_OPTION_MISSING:
agent_kwargs["service_tier"] = request_service_tier
agent = AIAgent(**agent_kwargs)
@@ -4034,6 +4040,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
if agent is not None:
_clear_turn_process_ownership(agent)
self._shutdown_interruptible_agents.pop(id(agent), None)
+ self._memory_sessions.checkin(agent)
# Bind the declared key to the row the turn actually ended on
# (agent.session_id carries a mid-turn rotation). Opt-in per route.
# Record the declared conversation on the row the turn actually ended on —
@@ -4288,6 +4295,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
except Exception:
logger.debug("Failed to close response store for %s", self.name, exc_info=True)
_api_runs._close_run_state(self)
+ with suppress(Exception):
+ await asyncio.to_thread(self._memory_sessions.close_all)
try:
if self._site:
await self._site.stop()
diff --git a/gateway/platforms/api_server_memory_sessions.py b/gateway/platforms/api_server_memory_sessions.py
new file mode 100644
index 00000000000..3f25ce501c9
--- /dev/null
+++ b/gateway/platforms/api_server_memory_sessions.py
@@ -0,0 +1,136 @@
+"""Memory-provider continuity across api_server requests (#120116).
+
+The api_server adapter builds a fresh ``AIAgent`` per request (per-request callbacks, model
+route, ephemeral prompt), unlike the messaging platforms, whose cached agent — and with it the
+memory provider — lives for the whole session. External providers deliver recall as the
+PREVIOUS turn's background prefetch held on the provider instance, so a provider that is
+re-initialised per request never has anything to inject, and each init re-runs the provider's
+startup (for an embedded daemon: a restart that also kills the retain still in flight).
+
+This registry keeps one initialised ``MemoryManager`` per (profile home, session id): a request
+checks the session's manager out before building its agent (``AIAgent(memory_manager=...)``
+skips provider init) and checks it back in when the turn ends. Check-out is exclusive, so two
+concurrent requests on one session never share a manager; the loser's fresh manager is shut down
+when it checks in behind the winner. Idle entries and LRU overflow are shut down under the owning
+profile's scope, like the gateway agent cache's eviction.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from collections import OrderedDict
+from contextlib import nullcontext, suppress
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+logger = logging.getLogger(__name__)
+
+
+class ApiServerMemorySessions:
+ """Session-keyed ``MemoryManager`` registry with exclusive check-out/check-in."""
+
+ def __init__(self, *, max_size: Optional[int] = None, idle_ttl_secs: Optional[float] = None) -> None:
+ self._entries: "OrderedDict[Tuple[str, str], Tuple[Any, Optional[Path], float]]" = OrderedDict()
+ self._lock = threading.Lock()
+ self._max_size = max_size
+ self._idle_ttl_secs = idle_ttl_secs
+
+ # -- bounds (same knobs as the gateway agent cache, resolved lazily) -------------------------
+
+ def _bounds(self) -> Tuple[int, float]:
+ if self._max_size is None or self._idle_ttl_secs is None:
+ from gateway.run import _AGENT_CACHE_IDLE_TTL_SECS, _AGENT_CACHE_MAX_SIZE, _load_gateway_config
+ from gateway.agent_cache_pressure import resolve_agent_cache_bounds
+ configured = None
+ with suppress(Exception):
+ configured = resolve_agent_cache_bounds(_load_gateway_config())
+ if self._max_size is None:
+ self._max_size = getattr(configured, "max_size", None) or _AGENT_CACHE_MAX_SIZE
+ if self._idle_ttl_secs is None:
+ self._idle_ttl_secs = getattr(configured, "idle_ttl_secs", None) or _AGENT_CACHE_IDLE_TTL_SECS
+ return self._max_size, self._idle_ttl_secs
+
+ @staticmethod
+ def _owner_home() -> Tuple[str, Optional[Path]]:
+ """(registry key, profile home to re-enter on eviction) for the CURRENT scope. Callers run
+ inside ``_profile_scope`` (or a single-profile gateway), so the ambient home is the owner's."""
+ from hermes_constants import get_hermes_home, hermes_home_key
+ home = Path(get_hermes_home())
+ return hermes_home_key(home), home
+
+ # -- check-out / check-in ----------------------------------------------------------------
+
+ def checkout(self, session_id: Optional[str]) -> Optional[Any]:
+ """The manager a previous request on ``session_id`` checked in, or None (build a new one)."""
+ if not session_id:
+ return None
+ home_key, _home = self._owner_home()
+ with self._lock:
+ entry = self._entries.pop((home_key, session_id), None)
+ return entry[0] if entry else None
+
+ def checkin(self, agent: Any) -> None:
+ """Park ``agent``'s manager under the session the turn ended on (``agent.session_id`` carries a
+ mid-turn compression rotation) and shut down whatever this displaces or has gone idle."""
+ manager = getattr(agent, "_memory_manager", None)
+ session_id = str(getattr(agent, "session_id", "") or "")
+ if manager is None or not session_id:
+ return
+ home_key, home = self._owner_home()
+ max_size, idle_ttl = self._bounds()
+ now = time.monotonic()
+ doomed: List[Tuple[Any, Optional[Path]]] = []
+ with self._lock:
+ displaced = self._entries.pop((home_key, session_id), None)
+ if displaced is not None and displaced[0] is not manager:
+ doomed.append((displaced[0], displaced[1]))
+ self._entries[(home_key, session_id)] = (manager, home, now)
+ for key, (mgr, owner, last_used) in list(self._entries.items()):
+ if mgr is manager:
+ continue
+ if now - last_used > idle_ttl or len(self._entries) > max_size:
+ del self._entries[key]
+ doomed.append((mgr, owner))
+ for mgr, owner in doomed:
+ self._shutdown_async(mgr, owner)
+
+ def close_all(self) -> None:
+ """Adapter shutdown: drain and shut down every parked manager (inline: the process is ending)."""
+ with self._lock:
+ entries = list(self._entries.values())
+ self._entries.clear()
+ for mgr, owner, _ in entries:
+ self._shutdown(mgr, owner)
+
+ # -- teardown -------------------------------------------------------------------------------
+
+ def _shutdown_async(self, manager: Any, owner: Optional[Path]) -> None:
+ """Eviction runs inside a request's own turn: never make that reply wait on a provider drain."""
+ from agent.memory_provider import spawn_context_thread
+ spawn_context_thread(self._shutdown, args=(manager, owner), name="api-server-memory-evict").start()
+
+ @staticmethod
+ def _shutdown(manager: Any, owner: Optional[Path]) -> None:
+ """Bounded drain then provider shutdown, under the OWNING profile's scope: eviction runs inside
+ whichever request happened to trigger it, and a provider reads its home/credentials at call time."""
+ scope: Any = nullcontext()
+ with suppress(Exception):
+ from agent.secret_scope import is_multiplex_active
+ if owner is not None and is_multiplex_active():
+ from gateway.run import _profile_runtime_scope
+ scope = _profile_runtime_scope(owner)
+ try:
+ with scope:
+ with suppress(Exception):
+ manager.flush_pending(timeout=10)
+ manager.shutdown_all()
+ except Exception:
+ logger.debug("api_server memory manager shutdown failed", exc_info=True)
+
+ # -- introspection (tests) --------------------------------------------------------------------
+
+ def parked(self) -> Dict[Tuple[str, str], Any]:
+ with self._lock:
+ return {key: entry[0] for key, entry in self._entries.items()}
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index f018926c39c..70a9479731a 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -780,6 +780,7 @@ def _run_agent_sync(self, run: _RunLaunch, agent, approval_notify, *, _api_serve
finally:
# Clear ownership now so a later stop can't reap work this run left running.
_api_server._clear_turn_process_ownership(agent)
+ self._memory_sessions.checkin(agent)
# Declared-conversation binding, same precedence gate as _run_agent.
if run.declared_selected:
self._bind_declared_conversation(
diff --git a/run_agent.py b/run_agent.py
index 1e6fb74ee6e..64e60e4d964 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -289,7 +289,7 @@ class AIAgent(
checkpoint_max_total_size_mb: int = 500, checkpoint_max_file_size_mb: int = 10,
pass_session_id: bool = False, requested_provider: str = None,
capabilities: Dict[str, bool] | None = None, cwd: str | None = None,
- side_agent: bool = False,
+ side_agent: bool = False, memory_manager=None,
):
"""Forwarder — see ``agent.agent_init.init_agent`` (same keyword parameters, minus ``tool_delay``)."""
init_kwargs = {k: v for k, v in locals().items() if k not in ("self", "tool_delay")}
diff --git a/tests/agent/test_memory_provider_init.py b/tests/agent/test_memory_provider_init.py
index 9063efae918..8faeb0b5492 100644
--- a/tests/agent/test_memory_provider_init.py
+++ b/tests/agent/test_memory_provider_init.py
@@ -170,3 +170,34 @@ def test_core_tool_names_rejected_from_memory_routing_table():
assert "honcho_search" in schema_names
+
+
+def test_aiagent_reuses_handed_in_memory_manager_without_reinitializing():
+ """A caller that rebuilds the agent per turn (gateway api_server) hands back the session's manager:
+ the provider keeps its state — no second load, no second initialize (#120116)."""
+ provider = RecordingMemoryProvider()
+ cfg = {"memory": {"provider": "recording"}, "agent": {}}
+ common = dict(
+ api_key="test-key-1234567890", base_url="https://openrouter.ai/api/v1", quiet_mode=True,
+ skip_context_files=True, skip_memory=False, session_id="sess-api", platform="api_server",
+ )
+ with (
+ patch("hermes_cli.config.load_config", return_value=cfg), patch("hermes_cli.config.load_config_readonly", return_value=cfg),
+ patch("plugins.memory.load_memory_provider", return_value=provider) as load_memory_provider,
+ patch("agent.model_metadata.get_model_context_length", return_value=204_800),
+ patch("model_tools.get_tool_definitions", return_value=[]),
+ patch("model_tools.check_toolset_requirements", return_value={}),
+ patch("agent.process_bootstrap.OpenAI"),
+ ):
+ from run_agent import AIAgent
+
+ first = AIAgent(**common)
+ manager = first._memory_manager
+ assert manager is not None and load_memory_provider.call_count == 1
+ provider.init_session_id = None # a re-initialize would set it again
+
+ second = AIAgent(memory_manager=manager, **common)
+
+ assert second._memory_manager is manager
+ assert load_memory_provider.call_count == 1
+ assert provider.init_session_id is None
diff --git a/tests/gateway/test_api_server_memory_sessions.py b/tests/gateway/test_api_server_memory_sessions.py
new file mode 100644
index 00000000000..f97bddcb206
--- /dev/null
+++ b/tests/gateway/test_api_server_memory_sessions.py
@@ -0,0 +1,43 @@
+"""api_server keeps one memory provider per session across requests (#120116)."""
+
+from types import SimpleNamespace
+
+from gateway.platforms.api_server_memory_sessions import ApiServerMemorySessions
+
+
+class _Manager:
+ def __init__(self):
+ self.shut_down = False
+
+ def flush_pending(self, timeout=None):
+ return True
+
+ def shutdown_all(self):
+ self.shut_down = True
+
+
+def _agent(manager, session_id="sess-1"):
+ return SimpleNamespace(_memory_manager=manager, session_id=session_id)
+
+
+def test_manager_survives_across_requests_and_is_exclusive_per_home(monkeypatch):
+ registry = ApiServerMemorySessions(max_size=8, idle_ttl_secs=3600.0)
+ home = ["home-a"]
+ monkeypatch.setattr(ApiServerMemorySessions, "_owner_home", staticmethod(lambda: (home[0], None)))
+ # Shutdowns run inline so the assertion below does not race a daemon thread.
+ monkeypatch.setattr(registry, "_shutdown_async", registry._shutdown)
+
+ assert registry.checkout("sess-1") is None # first request builds its own
+ manager = _Manager()
+ registry.checkin(_agent(manager))
+ assert registry.checkout("sess-1") is manager # next request on the session gets it back
+ assert registry.checkout("sess-1") is None # ...exclusively: a concurrent request builds a new one
+ loser = _Manager()
+ registry.checkin(_agent(manager))
+ registry.checkin(_agent(loser)) # the concurrent request checks in behind the winner
+ assert manager.shut_down and not loser.shut_down
+ # Same session id under another profile home is a different key (#120116 x multiplex).
+ home[0] = "home-b"
+ assert registry.checkout("sess-1") is None
+ home[0] = "home-a"
+ assert registry.checkout("sess-1") is loser
diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md
index 32d586ffb99..5db0303f4fe 100644
--- a/website/docs/user-guide/features/api-server.md
+++ b/website/docs/user-guide/features/api-server.md
@@ -660,6 +660,8 @@ X-Hermes-Session-Key: agent:main:webui:dm:user-42
Rules: max 256 chars, control characters (`\r`, `\n`, `\x00`) are rejected, and the value is echoed back on responses (JSON + SSE). `/v1/capabilities` advertises support via `"session_key_header": "X-Hermes-Session-Key"`. Without the key, Honcho's `per-session` strategy produces a different scope per `session_id` — exactly the behavior Hermes had before.
+Automatic recall follows the **transcript**: the memory provider is initialised once per session and kept across requests, so a continued session (`X-Hermes-Session-Id`, `previous_response_id`, or a declared `X-Hermes-Session-Key` conversation) receives the recall the provider prepared after the previous turn, exactly like a Telegram or Discord chat does. A request without any continuation starts a fresh session and, like the first turn of any new CLI session, has nothing queued yet. Idle sessions release their provider after the same idle TTL as the gateway agent cache (`agent.agent_cache.idle_ttl_secs`, default one hour).
+
## System Prompt Handling
When a frontend sends a `system` message (Chat Completions) or `instructions` field (Responses API), hermes-agent **layers it on top** of its core system prompt. Your agent keeps all its tools, memory, and skills — the frontend's system prompt adds extra instructions.