Skip to content
Merged
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
9 changes: 9 additions & 0 deletions examples/hermes-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,12 @@ client commits do not use the server scheduler's interval or retention settings.
The plugin retains the existing `keep_recent_count: 0` commit behavior.
The threshold is not a hard limit on extraction input: one turn can
exceed it, and the server may include other context during extraction.

### Non-primary contexts

Hermes passes an `agent_context` to `initialize()`. Sessions started for scheduled
cron jobs, delegated subagents, or flush forks (`cron`, `subagent`, `flush`) are
non-primary: recall and profile reads keep working, but the provider skips turn
uploads, session commits, and memory mirroring, so fixed-prompt job output neither
lands in the memory bank nor spends server-side extraction budget. Interactive
sessions (and hosts that predate `agent_context`) keep the previous write behavior.
24 changes: 24 additions & 0 deletions examples/hermes-plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ def _cfg_field(key: str, description: str, **extra) -> dict:
_SESSION_START_LIST_PARAMS = {"output": "agent", "recursive": True, "abs_limit": 512, "node_limit": 512}
# Built-in memory tool `target` -> mirror subdir (user facts -> preferences, agent notes -> patterns).
_MEMORY_WRITE_TARGET_SUBDIR_MAP = {"user": "preferences", "memory": "patterns"}
# Host contexts that must not write into OpenViking. Fixed-prompt output from scheduled
# jobs, delegated subagents, and flush forks has no memory value and would spend server-side
# extraction budget. Hermes delivers the context to initialize(); recall/read paths are unchanged.
_NON_PRIMARY_AGENT_CONTEXTS = frozenset({"cron", "subagent", "flush"})
# OpenViking-generated summaries; non-.md sidecars are already rejected by the .md check.
_GENERATED_MEMORY_SUMMARY_FILENAMES = {".abstract.md", ".overview.md"}
_LOCAL_OPENVIKING_HOSTS = {"localhost", "127.0.0.1", "::1"}
Expand Down Expand Up @@ -1312,6 +1316,10 @@ def __init__(self):
self._runtime_start_thread: Optional[threading.Thread] = None
self._runtime_start_pending = False
self._shutting_down = False # finalizers stop issuing network writes
# Non-primary contexts (cron/subagent/flush) skip OpenViking writes; resolved in
# initialize() from the host's agent_context.
self._agent_context = "primary"
self._writes_enabled = True

@property
def name(self) -> str:
Expand Down Expand Up @@ -1506,6 +1514,14 @@ def initialize(self, session_id: str, **kwargs) -> None:
self._user_id = _gateway_peer_id(self._gateway_platform, self._gateway_user_id_alt or self._gateway_user_id)
self._turn_peer.set(None)
self._hermes_home = str(kwargs.get("hermes_home") or "").strip() or str(get_hermes_home())
self._agent_context = str(kwargs.get("agent_context") or "primary")
self._writes_enabled = self._agent_context not in _NON_PRIMARY_AGENT_CONTEXTS
if not self._writes_enabled:
logger.debug(
"OpenViking writes disabled for %s context (session %s)",
self._agent_context,
session_id,
)
self._acquire_run_lock()
self._profile_prefetched_sessions.clear()

Expand Down Expand Up @@ -2236,6 +2252,8 @@ def sync_turn(self, user_content: str, assistant_content: str, *, session_id: st
messages: Optional[List[Dict[str, Any]]] = None,
turn_author: Optional[Dict[str, Any]] = None) -> None:
"""Record the conversation turn in OpenViking's session (non-blocking)."""
if not self._writes_enabled:
return
if not self._ensure_client():
return
user_content = _derive_openviking_user_text(user_content)
Expand Down Expand Up @@ -2624,6 +2642,8 @@ def _finalize() -> None:
def on_session_end(self, messages: List[Dict[str, Any]]) -> None:
"""Commit the session (synchronously — it must land before process exit) to
trigger extraction of profile/preferences/entities/events/cases/patterns."""
if not self._writes_enabled:
return
if not self._ensure_client():
return
with self._session_state_lock:
Expand All @@ -2650,6 +2670,8 @@ def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "",
The new session never accumulates messages, and memory extraction never fires for it. See
hermes-agent#28296.
"""
if not self._writes_enabled:
return
new_id = str(new_session_id or "").strip()
if not new_id or not self._ensure_client():
return
Expand Down Expand Up @@ -2732,6 +2754,8 @@ def on_memory_write(
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Mirror successful built-in memory mutations to OpenViking."""
if not self._writes_enabled:
return
if action not in {"add", "replace", "remove"} or not self._ensure_client():
return
if action in {"add", "replace"} and not content:
Expand Down
29 changes: 29 additions & 0 deletions examples/hermes-plugin/tests/test_standalone.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,35 @@ def test_session_switch_commits_below_live_threshold(external_provider, monkeypa
assert provider._session_id == "new-sid"


@pytest.mark.parametrize("agent_context", ["cron", "subagent", "flush"])
def test_non_primary_contexts_skip_writes(external_provider, monkeypatch, agent_context):
"""cron/subagent/flush contexts stay read-only: no turn uploads, commits, or mirroring."""
from unittest.mock import Mock

home, provider, module, _ = external_provider(f"non-primary-{agent_context}")
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setenv("OPENVIKING_ENDPOINT", "http://127.0.0.1:19531")
monkeypatch.setattr(module, "_classify_runtime_openviking_health", lambda *_: ("healthy", ""))
provider.initialize("live-sid", hermes_home=str(home))
assert (provider._agent_context, provider._writes_enabled) == ("primary", True)
provider.initialize("live-sid", hermes_home=str(home), agent_context=agent_context)
assert (provider._agent_context, provider._writes_enabled) == (agent_context, False)

provider._client = Mock()
provider._client.get.return_value = {"pending_tokens": 20000}
provider._ensure_client = lambda: True
provider._new_client = lambda: provider._client
provider._acquire_run_lock()
_finish_turn(provider)
provider.on_session_switch("new-sid")
provider.on_session_end([])
provider.on_memory_write("add", "user", f"not mirrored ({agent_context})")
assert provider._drain_finalizers(timeout=5)

assert provider._client.method_calls == []
assert provider._pending_sessions() == []


def test_live_commit_does_not_block_next_turn_or_lose_its_pending_marker(external_provider, monkeypatch):
from concurrent.futures import ThreadPoolExecutor

Expand Down