The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): add cache-safe system prompt sections
SeoYeonKim9acf0db88944
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 1a236e6eacc..95d48421c12 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -605,6 +605,12 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)# Continuing session — reuse the exact system prompt from the# previous turn so the Anthropic cache prefix matches.agent._cached_system_prompt = stored_prompt+ # Prompt-section callbacks are new-session-only. Recover their frozen+ # bytes from the persisted full prompt so a later compression rebuild+ # keeps them without evaluating plugin state in this resumed process.+ from agent.system_prompt import restore_plugin_prompt_sections++ restore_plugin_prompt_sections(agent, stored_prompt)# Reconstruct the cross-session-stable prefix for the early cache# breakpoint. The static prefix is not persisted (only the full# prompt is), so gateway surfaces that build a fresh AIAgent perdiff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex 5d405922427..c15989e16e7 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -28,6 +28,7 @@ from __future__ import annotationsimport jsonimport loggingimport os+import refrom typing import Any, Dict, List, Optionalfrom agent.prompt_builder import (@@ -53,6 +54,11 @@ from hermes_constants import get_hermes_homefrom utils import is_truthy_valuelogger = logging.getLogger(__name__)+_PLUGIN_SECTION_FRAME_RE = re.compile(+ r"^## Plugin Context: (?P<id>[a-z0-9][a-z0-9._-]{0,127})\n"+ r"<!-- hermes-plugin-section-chars:(?P<chars>[0-9]{1,4}) -->\n\n",+ re.MULTILINE,+)def _ra():@@ -149,6 +155,113 @@ def _tui_embedded_pane_clarifier(hint: str) -> str:return hint + _TUI_EMBEDDED_PANE_CLARIFIER+def _plugin_session_info(agent: Any) -> Dict[str, str]:+ """Return immutable-at-render-time metadata exposed to prompt sections."""+ try:+ cwd = str(resolve_context_cwd() or "")+ except Exception:+ cwd = ""+ try:+ from hermes_cli.profiles import get_active_profile_name++ profile_name = str(get_active_profile_name() or "default")+ except Exception:+ profile_name = "default"+ return {+ "session_id": str(getattr(agent, "session_id", None) or ""),+ "model": str(getattr(agent, "model", None) or ""),+ "provider": str(getattr(agent, "provider", None) or ""),+ "platform": str(getattr(agent, "platform", None) or ""),+ "profile_name": profile_name,+ "cwd": cwd,+ }+++def _frozen_plugin_prompt_sections(agent: Any) -> tuple:+ """Render once on a new session; never re-evaluate a restored prompt.++ Compression rebuilds reuse the per-agent tuple. A fresh process restores+ ``_cached_system_prompt`` before reconstructing its static cache prefix;+ because plugin sections live after memory in the volatile tail, that+ reconstruction can safely omit them and must not call plugin code again.+ """+ attr = "_plugin_system_prompt_sections_snapshot"+ if hasattr(agent, attr):+ return getattr(agent, attr)+ stored_prompt = getattr(agent, "_cached_system_prompt", None)+ if isinstance(stored_prompt, str) and stored_prompt:+ rendered = _restore_plugin_prompt_sections(stored_prompt)+ setattr(agent, attr, rendered)+ return rendered+ try:+ from hermes_cli.plugins import render_system_prompt_sections++ rendered = tuple(render_system_prompt_sections(_plugin_session_info(agent)))+ except Exception as exc:+ logger.warning("Plugin system prompt sections could not be rendered: %s", exc)+ rendered = ()+ setattr(agent, attr, rendered)+ return rendered+++def _restore_plugin_prompt_sections(prompt: str) -> tuple:+ """Recover frozen section bytes from the already-persisted full prompt."""+ from hermes_cli.plugins import (+ MAX_SYSTEM_PROMPT_SECTION_CHARS,+ PLUGIN_SECTIONS_END,+ PLUGIN_SECTIONS_START,+ RenderedPluginSystemPromptSection,+ format_system_prompt_sections,+ )++ start = prompt.rfind(PLUGIN_SECTIONS_START)+ if start < 0:+ return ()+ end = prompt.find(PLUGIN_SECTIONS_END, start + len(PLUGIN_SECTIONS_START))+ if end < 0:+ return ()+ after_end = end + len(PLUGIN_SECTIONS_END)+ if not prompt[after_end:].startswith("\n\nConversation started:"):+ return ()+ framed = prompt[start:after_end]++ restored = []+ for match in _PLUGIN_SECTION_FRAME_RE.finditer(framed):+ content_len = int(match.group("chars"))+ if content_len > MAX_SYSTEM_PROMPT_SECTION_CHARS:+ continue+ content_start = match.end()+ content = framed[content_start : content_start + content_len]+ if len(content) != content_len:+ continue+ restored.append(+ RenderedPluginSystemPromptSection(+ id=match.group("id"),+ content=content,+ position="after_memory",+ plugin="persisted-prompt",+ )+ )+ # User/project text may resemble a frame. Accept only the exact canonical+ # container emitted by core, never a partial or malformed lookalike.+ if format_system_prompt_sections(restored) != framed:+ return ()+ return tuple(restored)+++def restore_plugin_prompt_sections(agent: Any, prompt: str) -> None:+ """Seed a resumed agent's frozen snapshot from persisted prompt bytes."""+ agent._plugin_system_prompt_sections_snapshot = _restore_plugin_prompt_sections(prompt)+++def _plugin_section_blocks(sections: tuple, position: str) -> List[str]:+ from hermes_cli.plugins import format_system_prompt_sections++ selected = [section for section in sections if section.position == position]+ block = format_system_prompt_sections(selected)+ return [block] if block else []++def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) -> Dict[str, str]:"""Assemble the system prompt as three ordered cache tiers.@@ -540,6 +653,13 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)except Exception:pass+ # Plugin sections are intentionally confined to one coarse anchor in the+ # volatile tail. This preserves deterministic ordering and lets a resumed+ # process reconstruct the stable cache prefix without re-running plugins.+ volatile_parts.extend(+ _plugin_section_blocks(_frozen_plugin_prompt_sections(agent), "after_memory")+ )+from hermes_time import now as _hermes_nownow = _hermes_now()# Date-only (not minute-precision) so the system prompt is byte-stable@@ -689,5 +809,6 @@ __all__ = ["build_system_prompt_parts","build_system_prompt","invalidate_system_prompt",+ "restore_plugin_prompt_sections","format_tools_for_system_message",]diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 6ca0e79e165..09f19f2d338 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -224,6 +224,40 @@ VALID_HOOKS: Set[str] = {ENTRY_POINTS_GROUP = "hermes_agent.plugins"+# System-prompt sections are deliberately more constrained than lifecycle+# hooks. They become high-trust prompt bytes and are charged on every turn.+SYSTEM_PROMPT_SECTION_POSITIONS = frozenset({"after_memory"})+DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS = 4_000+MAX_SYSTEM_PROMPT_SECTION_CHARS = 4_000+MAX_SYSTEM_PROMPT_SECTIONS = 32+MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS = 8_000+_SYSTEM_PROMPT_SECTION_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,127}$")+_SYSTEM_PROMPT_SECTION_HEADING_PREFIX = "## Plugin Context: "+PLUGIN_SECTIONS_START = "<!-- hermes-plugin-sections:start -->"+PLUGIN_SECTIONS_END = "<!-- hermes-plugin-sections:end -->"+++def is_valid_system_prompt_section_id(value: Any) -> bool:+ """Return whether *value* is a stable, heading-safe section identifier."""+ return isinstance(value, str) and bool(_SYSTEM_PROMPT_SECTION_ID_RE.fullmatch(value))+++def format_system_prompt_section(section_id: str, content: str) -> str:+ """Render an auditable, length-framed block recoverable from the full prompt."""+ return (+ f"{_SYSTEM_PROMPT_SECTION_HEADING_PREFIX}{section_id}\n"+ f"<!-- hermes-plugin-section-chars:{len(content)} -->\n\n"+ f"{content}"+ )+++def format_system_prompt_sections(sections: list) -> str:+ """Render the canonical container used for persistence recovery."""+ if not sections:+ return ""+ blocks = [format_system_prompt_section(item.id, item.content) for item in sections]+ return f"{PLUGIN_SECTIONS_START}\n" + "\n\n".join(blocks) + f"\n{PLUGIN_SECTIONS_END}"+_NS_PARENT = "hermes_plugins"@@ -347,6 +381,27 @@ class PluginManifest:skill_namespace: str = ""+@dataclass(frozen=True)+class PluginSystemPromptSection:+ """A plugin-owned section rendered once for each new session."""++ id: str+ content: Union[str, Callable[[Mapping[str, Any]], str]]+ position: str+ max_chars: int+ plugin: str+++@dataclass(frozen=True)+class RenderedPluginSystemPromptSection:+ """Validated prompt bytes frozen on the owning AIAgent."""++ id: str+ content: str+ position: str+ plugin: str++@dataclassclass LoadedPlugin:"""Runtime state for a single loaded plugin."""@@ -1532,6 +1587,56 @@ class PluginContext:self._manager._hooks.setdefault(hook_name, []).append(callback)logger.debug("Plugin %s registered hook: %s", self.manifest.name, hook_name)+ def register_system_prompt_section(+ self,+ id: str,+ content: Union[str, Callable[[Mapping[str, Any]], str]],+ *,+ position: str = "after_memory",+ max_chars: int = DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS,+ ) -> None:+ """Register bounded context that is frozen into each new session prompt.++ Callables receive a read-only session-info mapping. The rendered full+ system prompt is already persisted by core and restored verbatim, so no+ parallel plugin-section state is needed for process restarts.+ """+ if not is_valid_system_prompt_section_id(id):+ raise ValueError(+ "system prompt section id must be 1-128 lowercase characters "+ "using letters, numbers, '.', '_', or '-'"+ )+ if not isinstance(content, str) and not callable(content):+ raise TypeError("system prompt section content must be a string or callable")+ if position not in SYSTEM_PROMPT_SECTION_POSITIONS:+ raise ValueError(+ "system prompt section position must be one of: "+ + ", ".join(sorted(SYSTEM_PROMPT_SECTION_POSITIONS))+ )+ if (+ isinstance(max_chars, bool)+ or not isinstance(max_chars, int)+ or not 0 < max_chars <= MAX_SYSTEM_PROMPT_SECTION_CHARS+ ):+ raise ValueError(+ "system prompt section max_chars must be between 1 and "+ f"{MAX_SYSTEM_PROMPT_SECTION_CHARS}"+ )+ existing = self._manager._system_prompt_sections.get(id)+ if existing is not None:+ raise ValueError(+ f"system prompt section {id!r} is already registered by "+ f"plugin {existing.plugin!r}"+ )+ plugin_id = self.manifest.key or self.manifest.name+ self._manager._system_prompt_sections[id] = PluginSystemPromptSection(+ id=id,+ content=content,+ position=position,+ max_chars=max_chars,+ plugin=plugin_id,+ )+# -- middleware registration -------------------------------------------def register_middleware(self, kind: str, callback: Callable) -> None:@@ -1622,6 +1727,7 @@ class PluginManager:self._cli_commands: Dict[str, dict] = {}self._context_engine = None # Set by a plugin via register_context_engine()self._plugin_commands: Dict[str, dict] = {} # Slash commands registered by plugins+ self._system_prompt_sections: Dict[str, PluginSystemPromptSection] = {}self._discovered: bool = Falseself._cli_ref = None # Set by CLI after plugin discovery# Plugin skill registry: qualified name → metadata dict.@@ -1673,6 +1779,7 @@ class PluginManager:self._plugin_platform_names.clear()self._cli_commands.clear()self._plugin_commands.clear()+ self._system_prompt_sections.clear()self._plugin_skills.clear()self._portable_mcp_servers.clear()self._aux_tasks.clear()@@ -2589,6 +2696,96 @@ class PluginManager:"""Return True when at least one callback is registered for a hook."""return bool(self._hooks.get(hook_name))+ def render_system_prompt_sections(+ self, session_info: Mapping[str, Any]+ ) -> List[RenderedPluginSystemPromptSection]:+ """Render all registered sections deterministically and fail open."""+ frozen_info = types.MappingProxyType(dict(session_info))+ rendered: List[RenderedPluginSystemPromptSection] = []+ total_chars = len(PLUGIN_SECTIONS_START) + len(PLUGIN_SECTIONS_END) + 2+ for section_id in sorted(self._system_prompt_sections):+ section = self._system_prompt_sections[section_id]+ if len(rendered) >= MAX_SYSTEM_PROMPT_SECTIONS:+ logger.warning(+ "Plugin system prompt section %s exceeded the section-count "+ "budget (%d) and was skipped",+ section.id,+ MAX_SYSTEM_PROMPT_SECTIONS,+ )+ continue+ try:+ value = (+ section.content(frozen_info)+ if callable(section.content)+ else section.content+ )+ except Exception as exc:+ logger.warning(+ "Plugin system prompt section %s (%s) raised and was skipped: %s",+ section.id,+ section.plugin,+ exc,+ )+ continue+ if not isinstance(value, str):+ logger.warning(+ "Plugin system prompt section %s (%s) returned %s, not str; skipped",+ section.id,+ section.plugin,+ type(value).__name__,+ )+ continue+ text = value.strip()+ if not text:+ continue+ if PLUGIN_SECTIONS_START in text or PLUGIN_SECTIONS_END in text:+ logger.warning(+ "Plugin system prompt section %s (%s) contained a reserved "+ "persistence marker and was skipped",+ section.id,+ section.plugin,+ )+ continue+ if len(text) > section.max_chars:+ logger.warning(+ "Plugin system prompt section %s (%s) exceeded max_chars "+ "(%d > %d) and was skipped",+ section.id,+ section.plugin,+ len(text),+ section.max_chars,+ )+ continue+ rendered_chars = len(format_system_prompt_section(section.id, text))+ if rendered:+ rendered_chars += 2 # canonical ``\n\n`` separator+ if total_chars + rendered_chars > MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS:+ logger.warning(+ "Plugin system prompt section %s (%s) exceeded the aggregate "+ "session budget (%d chars) and was skipped",+ section.id,+ section.plugin,+ MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS,+ )+ continue+ rendered.append(+ RenderedPluginSystemPromptSection(+ id=section.id,+ content=text,+ position=section.position,+ plugin=section.plugin,+ )+ )+ total_chars += rendered_chars+ logger.info(+ "Session plugin prompt section: id=%s plugin=%s position=%s chars=%d",+ section.id,+ section.plugin,+ section.position,+ len(text),+ )+ return rendered+def has_middleware(self, kind: str) -> bool:"""Return True when at least one callback is registered for middleware."""return bool(self._middleware.get(kind))@@ -2880,6 +3077,13 @@ def invoke_hook(hook_name: str, **kwargs: Any) -> List[Any]:return get_plugin_manager().invoke_hook(hook_name, **kwargs)+def render_system_prompt_sections(+ session_info: Mapping[str, Any],+) -> List[RenderedPluginSystemPromptSection]:+ """Render plugin prompt sections after idempotent plugin discovery."""+ return _ensure_plugins_discovered().render_system_prompt_sections(session_info)++def invoke_middleware(kind: str, **kwargs: Any) -> List[Any]:"""Invoke registered middleware callbacks.diff --git a/tests/agent/test_plugin_prompt_sections.py b/tests/agent/test_plugin_prompt_sections.pynew file mode 100644index 00000000000..ff4aea89253--- /dev/null+++ b/tests/agent/test_plugin_prompt_sections.py@@ -0,0 +1,174 @@+from __future__ import annotations++import base64+import json+import os+import subprocess+import sys+import textwrap++from agent.system_prompt import build_system_prompt, invalidate_system_prompt+from hermes_cli import plugins+from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+from run_agent import AIAgent+++def _real_agent(*, session_id: str = "plugin-section-test") -> AIAgent:+ return AIAgent(+ api_key="test-key",+ base_url="https://openrouter.ai/api/v1",+ model="test/model",+ provider="openrouter",+ platform="cli",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ session_id=session_id,+ )+++def _install_test_section(manager: PluginManager, content) -> None:+ manager._discovered = True+ ctx = PluginContext(+ PluginManifest(name="example-plugin", key="example-plugin", source="user"),+ manager,+ )+ ctx.register_system_prompt_section(+ "example.rules",+ content,+ position="after_memory",+ max_chars=1000,+ )+++def test_real_aiagent_builds_section_once_and_keeps_it_out_of_static_prefix(monkeypatch):+ calls = []++ def section(session_info):+ calls.append(dict(session_info))+ return f"rules render {len(calls)}"++ manager = PluginManager()+ _install_test_section(manager, section)+ monkeypatch.setattr(plugins, "_plugin_manager", manager)+ agent = _real_agent()++ first = build_system_prompt(agent)+ invalidate_system_prompt(agent)+ rebuilt = build_system_prompt(agent)++ assert first == rebuilt+ assert len(calls) == 1+ assert calls[0]["session_id"] == agent.session_id+ assert "## Plugin Context: example.rules" in first+ assert "rules render 1" in first+ assert first.index("## Plugin Context: example.rules") < first.index("Conversation started:")+ assert "example.rules" not in agent._cached_system_prompt_static+++def test_fresh_process_resume_restores_identical_full_prompt_without_callback(tmp_path):+ """The existing persisted full prompt is the only resume state required."""+ db_path = tmp_path / "state.db"+ calls_path = tmp_path / "calls.txt"+ child = textwrap.dedent(+ """+ import base64+ import json+ import os+ from pathlib import Path++ from agent.conversation_loop import _restore_or_build_system_prompt+ from agent.system_prompt import build_system_prompt, invalidate_system_prompt+ from hermes_cli import plugins+ from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest+ from hermes_state import SessionDB+ from run_agent import AIAgent++ db = SessionDB(db_path=Path(os.environ["TEST_DB"]))+ session_id = "resume-plugin-section"+ db.ensure_session(session_id, source="cli", model="test/model")+ agent = AIAgent(+ api_key="test-key",+ base_url="https://openrouter.ai/api/v1",+ model="test/model",+ provider="openrouter",+ platform="cli",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ session_id=session_id,+ session_db=db,+ )++ manager = PluginManager()+ manager._discovered = True+ ctx = PluginContext(+ PluginManifest(name="example-plugin", key="example-plugin", source="user"),+ manager,+ )+ calls_path = Path(os.environ["TEST_CALLS"])+ def render(_session_info):+ count = int(calls_path.read_text() or "0") if calls_path.exists() else 0+ calls_path.write_text(str(count + 1))+ return "original bytes" if os.environ["TEST_PHASE"] == "first" else "CHANGED"+ ctx.register_system_prompt_section("example.rules", render, position="after_memory")+ plugins._plugin_manager = manager++ history = [] if os.environ["TEST_PHASE"] == "first" else [+ {"role": "user", "content": "already persisted"}+ ]+ _restore_or_build_system_prompt(agent, None, history)+ restored = agent._cached_system_prompt+ rebuilt_equal = None+ if os.environ["TEST_PHASE"] != "first":+ invalidate_system_prompt(agent)+ rebuilt = build_system_prompt(agent)+ rebuilt_equal = rebuilt == restored+ agent._cached_system_prompt = rebuilt+ print(json.dumps({+ "prompt_b64": base64.b64encode(+ agent._cached_system_prompt.encode("utf-8")+ ).decode("ascii"),+ "calls": int(calls_path.read_text()),+ "rebuilt_equal": rebuilt_equal,+ }))+ db.close()+ """+ )++ outputs = []+ for phase in ("first", "resume"):+ env = os.environ.copy()+ env.update(+ HERMES_HOME=str(tmp_path / "hermes-home"),+ TEST_DB=str(db_path),+ TEST_CALLS=str(calls_path),+ TEST_PHASE=phase,+ )+ proc = subprocess.run(+ [sys.executable, "-c", child],+ cwd=os.getcwd(),+ env=env,+ text=True,+ capture_output=True,+ timeout=90,+ check=True,+ )+ outputs.append(json.loads(proc.stdout.strip().splitlines()[-1]))++ first_prompt = base64.b64decode(outputs[0]["prompt_b64"])+ resumed_prompt = base64.b64decode(outputs[1]["prompt_b64"])+ if first_prompt != resumed_prompt:+ diff_at = next(+ i for i, (left, right) in enumerate(zip(first_prompt, resumed_prompt))+ if left != right+ )+ raise AssertionError(+ f"prompt bytes differ at {diff_at}: "+ f"first={first_prompt[diff_at - 100:diff_at + 100]!r} "+ f"resumed={resumed_prompt[diff_at - 100:diff_at + 100]!r}"+ )+ assert b"original bytes" in first_prompt+ assert b"CHANGED" not in resumed_prompt+ assert outputs[0]["calls"] == outputs[1]["calls"] == 1+ assert outputs[1]["rebuilt_equal"] is Truediff --git a/tests/hermes_cli/test_plugin_prompt_sections.py b/tests/hermes_cli/test_plugin_prompt_sections.pynew file mode 100644index 00000000000..cebfaa2fbbc--- /dev/null+++ b/tests/hermes_cli/test_plugin_prompt_sections.py@@ -0,0 +1,90 @@+from __future__ import annotations++import logging+from types import MappingProxyType++import pytest++from hermes_cli.plugins import (+ MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS,+ PluginContext,+ PluginManager,+ PluginManifest,+)+++def _context(manager: PluginManager, name: str = "example-plugin") -> PluginContext:+ return PluginContext(+ PluginManifest(name=name, key=name, source="user"),+ manager,+ )+++def test_registration_validates_stable_id_position_budget_and_duplicates():+ manager = PluginManager()+ ctx = _context(manager)++ for invalid_id in ("", "UPPER.case", "has space", "line\nbreak", "x" * 129):+ with pytest.raises(ValueError):+ ctx.register_system_prompt_section(invalid_id, "content")++ with pytest.raises(ValueError):+ ctx.register_system_prompt_section("example.rules", "content", position="priority-17")+ with pytest.raises(ValueError):+ ctx.register_system_prompt_section("example.rules", "content", max_chars=0)++ ctx.register_system_prompt_section("example.rules", "content")+ with pytest.raises(ValueError, match="already registered"):+ _context(manager, "other-plugin").register_system_prompt_section(+ "example.rules", "other content"+ )+++def test_render_is_deterministic_bounded_and_session_info_is_read_only(caplog):+ manager = PluginManager()+ ctx = _context(manager)+ observed = []++ def render_b(info):+ observed.append(info)+ with pytest.raises(TypeError):+ info["session_id"] = "changed"+ return "B"++ ctx.register_system_prompt_section("example.z", render_b, max_chars=4)+ ctx.register_system_prompt_section("example.a", "A", max_chars=4)+ ctx.register_system_prompt_section("example.too-large", "12345", max_chars=4)++ with caplog.at_level(logging.WARNING, logger="hermes_cli.plugins"):+ rendered = manager.render_system_prompt_sections({"session_id": "session-1"})++ assert [(item.id, item.content) for item in rendered] == [+ ("example.a", "A"),+ ("example.z", "B"),+ ]+ assert isinstance(observed[0], MappingProxyType)+ assert observed[0]["session_id"] == "session-1"+ assert "exceeded max_chars" in caplog.text+++def test_render_fails_open_for_callback_failure_wrong_type_and_aggregate_budget(caplog):+ manager = PluginManager()+ ctx = _context(manager)++ def boom(_info):+ raise RuntimeError("plugin exploded")++ ctx.register_system_prompt_section("example.boom", boom)+ ctx.register_system_prompt_section("example.wrong", lambda _info: {"not": "text"})+ chunk = (MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS // 2) - 200+ ctx.register_system_prompt_section("example.first", "a" * chunk, max_chars=chunk)+ ctx.register_system_prompt_section("example.second", "b" * chunk, max_chars=chunk)+ ctx.register_system_prompt_section("example.zzlast", "c" * 500, max_chars=500)++ with caplog.at_level(logging.WARNING, logger="hermes_cli.plugins"):+ rendered = manager.render_system_prompt_sections({})++ assert [item.id for item in rendered] == ["example.first", "example.second"]+ assert "plugin exploded" in caplog.text+ assert "returned dict, not str" in caplog.text+ assert "aggregate" in caplog.textdiff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex bb543896319..6ea344db6ce 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -387,6 +387,50 @@ def register(ctx):- Correlation fields such as `turn_id`, `api_request_id`, `task_id`, `session_id`, and `api_call_count` are hook-specific and may be absent. Treat IDs as opaque.- Runtime event-name validity comes from `hermes_cli.plugins.VALID_HOOKS`. `hermes hooks list` lists configured shell/outbound hooks, not every available event; `hermes hooks test <event>` reports the valid set only when an invalid event is supplied.+### Cache-safe system prompt sections++Plugins that need durable, always-on guidance can register a bounded system+prompt section instead of injecting the same text through `pre_llm_call` on+every turn:++```python+def board_rules(session_info):+ return f"Apply the worker rules for profile {session_info['profile_name']}."++def register(ctx):+ ctx.register_system_prompt_section(+ "kanban-advanced.worker-rules",+ board_rules, # a string is also accepted+ position="after_memory",+ max_chars=4000,+ )+```++The contract is deliberately narrow:++- IDs are global, stable, 1–128 character lowercase identifiers using only+ letters, numbers, `.`, `_`, and `-`. Duplicate IDs are rejected.+- `after_memory` is the only placement anchor. Sections are sorted by ID,+ rendered after memory/profile context and before session metadata; plugins+ cannot reorder or replace core prompt content.+- A callable receives a read-only mapping with `session_id`, `model`,+ `provider`, `platform`, `profile_name`, and `cwd`. It runs **once for a new+ session**. Its rendered bytes are frozen on compression and recovered from+ the already-persisted full system prompt after a process restart/resume;+ plugin state is not re-read for an existing session.+- `max_chars` is capped at 4,000 characters. All plugin sections together,+ including their audit headings, are capped at 8,000 characters and 32+ sections. Empty, non-string, oversized, aggregate-over-budget, or raising+ sections are skipped with a warning; prompt construction continues.+- Every accepted section is named in the prompt and logged at session start+ with its plugin, position, and character count.++Use `pre_llm_call` for truly dynamic per-turn context. There is intentionally+no plugin environment-hints hook in this contract: changing cwd, branch, or+other environment data must not silently mutate a session's cached prompt.+Such a hook needs a concrete consumer and the same frozen/resume-safe semantics+before it can be added.+### Shipped plugin-hook catalogPayload fields below are the exact event-specific fields supplied by each call site. For backward compatibility, `PluginManager` also adds `telemetry_schema_version="hermes.observer.v1"` to every plugin-hook callback. That legacy envelope marker does not mean all hook payloads share one semantic schema; new versioned contracts belong to their concrete event or capability family.