Skip to content
Open
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
94 changes: 76 additions & 18 deletions agent/conversation_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,55 @@ def _ra():
return run_agent


def _stored_system_prompt_stale_for_soul(agent: Any, stored_prompt: str) -> bool:
"""Return True when a persisted prompt no longer matches current identity.

Gateway profiles often create a fresh AIAgent for each incoming message and
restore the frozen prompt from the session DB for cache stability. That is
correct for normal turns, but profile identity edits such as SOUL.md changes
must take effect without forcing users to abandon the current chat session.
"""
if not stored_prompt:
return False

should_load_soul = (
getattr(agent, "load_soul_identity", False)
or not getattr(agent, "skip_context_files", False)
)
if not should_load_soul:
return False

try:
run_agent = _ra()
current_soul = run_agent.load_soul_md()
default_identity = getattr(run_agent, "DEFAULT_AGENT_IDENTITY", "")
guidance = getattr(run_agent, "HERMES_AGENT_HELP_GUIDANCE", "")
if not guidance:
from agent.prompt_builder import HERMES_AGENT_HELP_GUIDANCE

guidance = HERMES_AGENT_HELP_GUIDANCE
except Exception as exc:
logger.debug(
"Could not load SOUL.md while validating stored system prompt: %s",
exc,
)
return False

expected_identity = current_soul or default_identity
if not expected_identity:
return False

marker = f"\n\n{guidance}" if guidance else None
if not marker:
return True

identity_block, sep, _ = stored_prompt.partition(marker)
if not sep:
return True

return identity_block.strip() != expected_identity.strip()


def _nous_entitlement_message(capability: str) -> str:
try:
from hermes_cli.nous_account import (
Expand Down Expand Up @@ -250,7 +299,6 @@ def _try_refresh_nous_paid_entitlement_credentials(agent) -> bool:
except Exception:
return False


def _restore_or_build_system_prompt(agent, system_message, conversation_history):
"""Restore the cached system prompt from the session DB or build it fresh.

Expand Down Expand Up @@ -280,6 +328,7 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)
"""
stored_prompt = None
stored_state = "missing"
stored_prompt_stale = False
if conversation_history and agent._session_db:
try:
session_row = agent._session_db.get_session(agent.session_id)
Expand All @@ -301,10 +350,18 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebuilding here changes the system prompt inside an existing conversation. Current main treats that prompt as byte-stable for the session (agent/system_prompt.py:157-161) and documents SOUL.md changes as cleanly taking effect in new sessions (website/docs/user-guide/profiles.md:148); this needs maintainer approval as an explicit cache-invalidation exception.


if stored_prompt:
# Continuing session β€” reuse the exact system prompt from the
# previous turn so the Anthropic cache prefix matches.
agent._cached_system_prompt = stored_prompt
return
if _stored_system_prompt_stale_for_soul(agent, stored_prompt):
stored_prompt_stale = True
logger.info(
"Stored system prompt for session %s is stale relative to "
"SOUL.md/default identity; rebuilding.",
agent.session_id,
)
else:
# Continuing session β€” reuse the exact system prompt from the
# previous turn so the Anthropic cache prefix matches.
agent._cached_system_prompt = stored_prompt
return

if conversation_history and stored_state in ("null", "empty"):
# Continuing session whose stored prompt is unusable. The
Expand All @@ -323,19 +380,20 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)
# prompt) β€” build from scratch.
agent._cached_system_prompt = agent._build_system_prompt(system_message)

# Plugin hook: on_session_start β€” fired once when a brand-new
# session is created (not on continuation). Plugins can use this
# to initialise session-scoped state (e.g. warm a memory cache).
try:
from hermes_cli.plugins import invoke_hook as _invoke_hook
_invoke_hook(
"on_session_start",
session_id=agent.session_id,
model=agent.model,
platform=getattr(agent, "platform", None) or "",
)
except Exception as exc:
logger.warning("on_session_start hook failed: %s", exc)
if not stored_prompt_stale:
# Plugin hook: on_session_start β€” fired once when a brand-new
# session is created (not on continuation). Plugins can use this
# to initialise session-scoped state (e.g. warm a memory cache).
try:
from hermes_cli.plugins import invoke_hook as _invoke_hook
_invoke_hook(
"on_session_start",
session_id=agent.session_id,
model=agent.model,
platform=getattr(agent, "platform", None) or "",
)
except Exception as exc:
logger.warning("on_session_start hook failed: %s", exc)

# Cold-start credits seed (L3) β€” fallback for the first-turn path. The TUI/
# desktop build seeds at session OPEN (see seed_credits_at_session_start in
Expand Down
26 changes: 26 additions & 0 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -12535,8 +12535,34 @@ def _extract_cache_busting_config(cls, user_config: dict | None) -> dict:
else:
out.update(cls._empty_honcho_cache_busting_config())

out["identity.soul_md"] = cls._soul_md_cache_key()
return out

@staticmethod
def _soul_md_cache_key() -> dict:
"""Return a compact fingerprint for the active profile's SOUL.md.

Gateway agents freeze their system prompt for prompt-cache reuse. That
is great for latency, but it means editing a profile's SOUL.md would
otherwise keep using the old identity/rules until a manual reset or
unrelated cache eviction. Include cheap filesystem metadata in the
agent signature so persona/rule edits take effect on the next message.
"""
soul_path = _hermes_home / "SOUL.md"
try:
stat = soul_path.stat()
except OSError:
return {"exists": False}
return {
"exists": True,
"mtime_ns": getattr(
stat,
"st_mtime_ns",
int(stat.st_mtime * 1_000_000_000),
),
"size": stat.st_size,
}

@staticmethod
def _agent_config_signature(
model: str,
Expand Down
1 change: 1 addition & 0 deletions scripts/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@
"zhekinmaksim@gmail.com": "Zhekinmaksim",
"obafemiferanmi1999@gmail.com": "KvnGz",
"159539633+MottledShadow@users.noreply.github.com": "MottledShadow",
"18210507492@126.com": "qindongliang",
"aludwin+gh@gmail.com": "adamludwin",
"ngusev@astralinux.ru": "NikolayGusev-astra",
"liuguangyong201@hellobike.com": "liuguangyong93",
Expand Down
43 changes: 42 additions & 1 deletion tests/gateway/test_agent_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,6 @@ def test_extract_includes_live_tool_registry_generation(self, monkeypatch):

assert out["tools.registry_generation"] == 12345


def test_skips_honcho_config_read_when_provider_is_not_honcho(self, monkeypatch):
"""Non-Honcho gateways must not read/parse honcho.json on every message."""
from gateway.run import GatewayRunner
Expand Down Expand Up @@ -381,6 +380,48 @@ def from_global_config(cls, config_path=None):
assert third == first
assert parse_calls == [config_path, config_path]

def test_extract_includes_soul_md_fingerprint(self, tmp_path, monkeypatch):
import gateway.run as gateway_run
from gateway.run import GatewayRunner

monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)

before = GatewayRunner._extract_cache_busting_config({})
(tmp_path / "SOUL.md").write_text("updated gateway persona", encoding="utf-8")
after = GatewayRunner._extract_cache_busting_config({})

assert before["identity.soul_md"] == {"exists": False}
assert after["identity.soul_md"]["exists"] is True
assert after["identity.soul_md"]["size"] == len("updated gateway persona")
assert before["identity.soul_md"] != after["identity.soul_md"]

def test_soul_md_fingerprint_change_busts_signature(self):
from gateway.run import GatewayRunner

runtime = {"api_key": "k", "base_url": "u", "provider": "p"}
sig_before = GatewayRunner._agent_config_signature(
"m",
runtime,
["telegram"],
"",
cache_keys={"identity.soul_md": {"exists": False}},
)
sig_after = GatewayRunner._agent_config_signature(
"m",
runtime,
["telegram"],
"",
cache_keys={
"identity.soul_md": {
"exists": True,
"mtime_ns": 123,
"size": 22,
}
},
)

assert sig_before != sig_after

def test_full_round_trip_busts_cache_on_real_edit(self):
"""End-to-end: simulate a config edit on main and verify the
extracted cache_keys change produces a new signature."""
Expand Down
88 changes: 88 additions & 0 deletions tests/run_agent/test_run_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -5215,6 +5215,94 @@ def test_is_azure_openai_url_detection(self, agent):
class TestSystemPromptStability:
"""Verify that the system prompt stays stable across turns for cache hits."""

def test_stored_prompt_marked_stale_when_soul_changed(self):
from agent.conversation_loop import _stored_system_prompt_stale_for_soul
from agent.prompt_builder import HERMES_AGENT_HELP_GUIDANCE

agent = SimpleNamespace(load_soul_identity=False, skip_context_files=False)
stored = f"old SOUL without mapping\n\n{HERMES_AGENT_HELP_GUIDANCE}"

with patch(
"run_agent.load_soul_md",
return_value="current SOUL with Feishu bot open_ids",
):
assert (
_stored_system_prompt_stale_for_soul(agent, stored)
is True
)

def test_stored_prompt_not_stale_when_current_soul_present(self):
from agent.conversation_loop import _stored_system_prompt_stale_for_soul
from agent.prompt_builder import HERMES_AGENT_HELP_GUIDANCE

agent = SimpleNamespace(load_soul_identity=False, skip_context_files=False)
stored = f"current SOUL with Feishu bot open_ids\n\n{HERMES_AGENT_HELP_GUIDANCE}"

with patch(
"run_agent.load_soul_md",
return_value="current SOUL with Feishu bot open_ids",
):
assert _stored_system_prompt_stale_for_soul(agent, stored) is False

def test_stored_prompt_marked_stale_when_soul_removed(self):
from agent.conversation_loop import _stored_system_prompt_stale_for_soul

agent = SimpleNamespace(load_soul_identity=False, skip_context_files=False)

with patch("run_agent.load_soul_md", return_value=None):
assert (
_stored_system_prompt_stale_for_soul(
agent,
"custom SOUL that used to be loaded\n\nOther system prompt sections",
)
is True
)

def test_stored_prompt_marked_stale_when_soul_shortened(self):
from agent.conversation_loop import _stored_system_prompt_stale_for_soul
from agent.prompt_builder import HERMES_AGENT_HELP_GUIDANCE

agent = SimpleNamespace(load_soul_identity=False, skip_context_files=False)
stored = f"You are Jasper. Be helpful.\n\n{HERMES_AGENT_HELP_GUIDANCE}"

with patch("run_agent.load_soul_md", return_value="Be helpful."):
assert _stored_system_prompt_stale_for_soul(agent, stored) is True

def test_stored_prompt_soul_check_respects_skip_context_files(self):
from agent.conversation_loop import _stored_system_prompt_stale_for_soul

agent = SimpleNamespace(load_soul_identity=False, skip_context_files=True)

with patch("run_agent.load_soul_md", return_value="current SOUL") as load_soul:
assert _stored_system_prompt_stale_for_soul(agent, "old SOUL") is False

load_soul.assert_not_called()

def test_stale_soul_prompt_rebuilds_without_session_start_hook(self, agent):
from agent.conversation_loop import _restore_or_build_system_prompt

mock_db = MagicMock()
mock_db.get_session.return_value = {"system_prompt": "old SOUL rules"}
agent._session_db = mock_db
agent._cached_system_prompt = None
agent.load_soul_identity = True
agent._build_system_prompt = MagicMock(return_value="current SOUL rules")
history = [
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "hi"},
]

with patch("run_agent.load_soul_md", return_value="current SOUL rules"):
with patch("hermes_cli.plugins.invoke_hook") as invoke_hook:
_restore_or_build_system_prompt(agent, None, history)

assert agent._cached_system_prompt == "current SOUL rules"
mock_db.update_system_prompt.assert_called_once_with(
agent.session_id,
"current SOUL rules",
)
invoke_hook.assert_not_called()

def test_stored_prompt_reused_for_continuing_session(self, agent):
"""When conversation_history is non-empty and session DB has a stored
prompt, it should be reused instead of rebuilding from disk."""
Expand Down