The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hooks): a blocked prompt is stored only as the withheld placeholder
Teknium792330dc918b
diff --git a/agent/memory_manager.py b/agent/memory_manager.pyindex c6525e0c1c1..ad5f8202414 100644--- a/agent/memory_manager.py+++ b/agent/memory_manager.py@@ -136,7 +136,10 @@ def _redact_for_provider(*values: Any) -> Any:def _redact_messages_for_egress(messages: Optional[list[Any]]) -> Optional[list[Any]]:- return None if messages is None else list(_redact_for_provider(messages))+ """Scrubbed copies of whole transcript rows for a provider; a ``pre_llm_call`` veto's typed text+ (display-only metadata) never leaves the host."""+ from agent.message_metadata import without_withheld_prompts+ return None if messages is None else list(_redact_for_provider(without_withheld_prompts(messages)))class _StuckCallGate:@@ -705,7 +708,9 @@ class MemoryManager:return ""parts = []checkpoint_succeeded = False- messages, evidence_messages = _redact_for_provider(messages or [], evidence_messages)+ from agent.message_metadata import without_withheld_prompts+ messages, evidence_messages = _redact_for_provider(+ without_withheld_prompts(messages or []), without_withheld_prompts(evidence_messages))for provider in self._providers:version = self._checkpoint_api_version(provider)if version is None:diff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex 52c0c126dd8..de075f09879 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -73,6 +73,32 @@ def stamp_data_use(message: MutableMapping[str, Any], requires: list[str]) -> Nomessage["display_metadata"] = {**(metadata if isinstance(metadata, dict) else {}), DATA_USE: list(requires)}+# What the user typed on a turn a ``pre_llm_call`` hook vetoed, kept inside ``display_metadata``. The row's+# ``content`` is the withheld placeholder, so every reader that hands transcript text to a model (wire+# replay, compaction, session_search, memory providers, background review) only ever sees that; transcript+# views render this key instead (agent/turn_context.py::_withhold_blocked_prompt).+WITHHELD_PROMPT = "withheld_prompt"+++def withheld_prompt_text(message: Any) -> Optional[str]:+ """The typed text a transcript view shows for a vetoed user row, else None."""+ metadata = message.get("display_metadata") if isinstance(message, Mapping) else None+ text = metadata.get(WITHHELD_PROMPT) if isinstance(metadata, Mapping) else None+ return text if isinstance(text, str) else None+++def without_withheld_prompts(messages: Any) -> Any:+ """*messages* with the vetoed text dropped from each row's ``display_metadata`` (copies only where+ one is present), for hand-offs that leave the host with whole row dicts (memory providers)."""+ if not isinstance(messages, list) or not any(withheld_prompt_text(m) is not None for m in messages):+ return messages+ return [+ {**m, "display_metadata": {k: v for k, v in m["display_metadata"].items() if k != WITHHELD_PROMPT}}+ if withheld_prompt_text(m) is not None else m+ for m in messages+ ]++def lift_data_use(message: MutableMapping[str, Any]) -> None:"""Restore a replayed row's ``data_use`` key from its durable ``display_metadata`` copy."""metadata = message.get("display_metadata")diff --git a/agent/runtime_session_lifecycle.py b/agent/runtime_session_lifecycle.pyindex 1a201b21acb..94fa76c3d8e 100644--- a/agent/runtime_session_lifecycle.py+++ b/agent/runtime_session_lifecycle.py@@ -73,9 +73,12 @@ class RuntimeSessionLifecycleMixin:return self._apply('session.message_api_content',{'row_id': row_id, 'content': content, 'api_content': api_content})['value']- def set_user_message_content(self, session_id, row_id, content):+ def set_user_message_content(self, session_id, row_id, content, display_metadata=None):self._session(session_id)- return self._apply('session.user_content', {'row_id': row_id, 'content': content})['value']+ payload = {'row_id': row_id, 'content': content}+ if display_metadata is not None:+ payload['display_metadata'] = display_metadata+ return self._apply('session.user_content', payload)['value']def end_session(self, session_id, end_reason):self._session(session_id)diff --git a/agent/turn_context.py b/agent/turn_context.pyindex f59f9ad30aa..12011287f1d 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -802,11 +802,49 @@ def _ensure_session_row(agent: Any, pending_cli_message: Any) -> None:# ``turn_exit_reason`` of a turn a ``pre_llm_call`` hook vetoed before any inference request, and-# the ``api_content`` later turns replay in place of the vetoed prompt (the transcript keeps it).+# the stored ``content`` of the vetoed user row (what the user typed is display-only metadata).PRE_LLM_BLOCK_EXIT_REASON = "blocked_by_plugin_pre_llm_call"PRE_LLM_BLOCK_WITHHELD_PROMPT = "[Message withheld: a pre_llm_call policy hook blocked it.]"+def _withhold_blocked_prompt(agent: Any, turn_user_msg: dict[str, Any], typed: Any) -> None:+ """Store a vetoed prompt as the withheld placeholder. ``content`` is what compaction,+ session_search, memory providers and background review read, so the placeholder is the row's+ content (and the persist override, so no flush restores the typed text); what the user typed is+ kept only in ``display_metadata`` for transcript views. A row another writer materialized first+ (the TUI/Desktop submit-time row) is rewritten in place under the persist lock. A row merged with+ an earlier compaction handoff keeps the handoff and an unanswered earlier message merged into the+ row keeps its text; only this turn's ask becomes the placeholder."""+ from agent.context_compressor import COMPRESSED_SUMMARY_METADATA_KEY, _handoff_only_content+ from agent.message_metadata import WITHHELD_PROMPT+ from agent.session_persistence import _content_with_turn_override, _durable_content, _persist_lock++ content = turn_user_msg.get("content")+ if turn_user_msg.get(COMPRESSED_SUMMARY_METADATA_KEY):+ handoff = flatten_message_text(_handoff_only_content(content)).strip()+ withheld = f"{handoff}\n\n{PRE_LLM_BLOCK_WITHHELD_PROMPT}" if handoff else PRE_LLM_BLOCK_WITHHELD_PROMPT+ else:+ typed = _content_with_turn_override(turn_user_msg, content, typed)+ withheld = _content_with_turn_override(turn_user_msg, content, PRE_LLM_BLOCK_WITHHELD_PROMPT)+ metadata = turn_user_msg.get("display_metadata")+ metadata = {**(metadata if isinstance(metadata, dict) else {}), WITHHELD_PROMPT: str(_durable_content(typed) or "")}+ agent._persist_user_message_override = PRE_LLM_BLOCK_WITHHELD_PROMPT+ with _persist_lock(agent):+ turn_user_msg["content"] = withheld+ turn_user_msg.pop("api_content", None)+ turn_user_msg["display_metadata"] = metadata+ _db = getattr(agent, "_session_db", None)+ _row_id = turn_user_msg.get("_row_id")+ if _db is None or not isinstance(_row_id, int):+ return+ try:+ # A submit-time row is addressed under the session that wrote it (a rotation may follow).+ _db.set_user_message_content(turn_user_msg.get("_submit_row_session_id") or agent.session_id,+ _row_id, withheld, metadata)+ except Exception:+ logger.warning("withheld-prompt rewrite failed for session=%s", agent.session_id or "none", exc_info=True)++def _collect_pre_llm_call_context(agent: Any, *, effective_task_id: str, turn_id: str, original_user_message: Any,messages: list[Any], conversation_history: Optional[list[Any]], blocks: Optional[list[str]] = None,@@ -1068,7 +1106,7 @@ def build_turn_context(Order matters: the DB session row is created only AFTER the system prompt is built(else it persists system_prompt=NULL and costs a cache miss) and BEFORE preflightcompression."""- from agent.turn_context_compaction import run_turn_start_compaction+ from agent.turn_context_compaction import CompactionOutcome, run_turn_start_compaction# Guard stdio against OSError from broken pipes (systemd/headless/daemon).install_safe_stdio()@@ -1188,7 +1226,19 @@ def build_turn_context():agent._flush_messages_to_session_db(conversation_history, conversation_history)- compaction = run_turn_start_compaction(+ # Before turn-start compaction: its summary request quotes recent user turns, this one included,+ # so a vetoed prompt skips it (the turn makes no model call at all).+ _blocks: list[str] = []+ plugin_user_context = _collect_pre_llm_call_context(+ agent, effective_task_id=effective_task_id, turn_id=turn_id,+ original_user_message=original_user_message, messages=messages,+ conversation_history=conversation_history, blocks=_blocks,+ )+ plugin_block_message = _blocks[0] if _blocks else "" # first veto wins+ compaction = CompactionOutcome(+ messages=messages, active_system_prompt=active_system_prompt,+ conversation_history=conversation_history, current_turn_user_idx=current_turn_user_idx,+ ) if plugin_block_message else run_turn_start_compaction(agent, messages=messages, system_message=system_message,active_system_prompt=active_system_prompt, conversation_history=conversation_history,current_turn_user_idx=current_turn_user_idx, user_message=user_message,@@ -1198,14 +1248,6 @@ def build_turn_context(active_system_prompt = compaction.active_system_promptconversation_history = compaction.conversation_historycurrent_turn_user_idx = compaction.current_turn_user_idx-- _blocks: list[str] = []- plugin_user_context = _collect_pre_llm_call_context(- agent, effective_task_id=effective_task_id, turn_id=turn_id,- original_user_message=original_user_message, messages=messages,- conversation_history=conversation_history, blocks=_blocks,- )- plugin_block_message = _blocks[0] if _blocks else "" # first veto wins# Every turn, not only on a prompt restore: a long-lived agent (CLI, TUI, Desktop) keeps its# prompt in memory for the whole conversation and would never re-check its skills index.stage_skills_index_note(agent, active_system_prompt, messages)@@ -1227,7 +1269,7 @@ def build_turn_context(# Sidecar skipped for codex_app_server/MoA; list content carries its context as a part in every mode.if 0 <= current_turn_user_idx < len(messages) and messages[current_turn_user_idx].get("role") == "user":if plugin_block_message:- messages[current_turn_user_idx]["api_content"] = PRE_LLM_BLOCK_WITHHELD_PROMPT+ _withhold_blocked_prompt(agent, messages[current_turn_user_idx], original_user_message)elif isinstance(messages[current_turn_user_idx].get("content"), list):_append_multimodal_context(agent, messages[current_turn_user_idx], ext_prefetch_cache, plugin_user_context,diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex f17ecfd0e9c..3a595fad8d6 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -179,6 +179,7 @@ def _collect_resume_entries(display_history, disp: dict, clean_assistant):screen, retitle the window or restyle the panel. Pure-reasoning assistant rows with novisible output are skipped, as are tool-call-only rows when ``resume_skip_tool_only``."""+ from agent.message_metadata import withheld_prompt_textfrom tools.ansi_strip import sanitize_display_text as _sanitize_display_textmax_user_len = int(disp.get("resume_max_user_chars", 300))max_asst_len = int(disp.get("resume_max_assistant_chars", 200))@@ -200,7 +201,7 @@ def _collect_resume_entries(display_history, disp: dict, clean_assistant):entries.append(("event", _sanitize_display_text(label or t(_RESUME_EVENT_KEYS[display_kind]))))continueif role == "user":- text = _sanitize_display_text(_user_display_text(content))+ text = _sanitize_display_text(withheld_prompt_text(msg) or _user_display_text(content))if len(text) > max_user_len:text = text[:max_user_len] + "..."entries.append(("user", text))diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex d6a5cb947a1..df2fe808454 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -684,6 +684,7 @@ def _project_for_display(messages: list, *, home=None, inline_images: bool = Trufrom agent.context_compressor import is_compaction_summary_messagefrom agent.conversation_compression import _extract_steer_text_from_messagefrom agent.history_commentary import project_history_commentary+ from agent.message_metadata import withheld_prompt_textfrom agent.prompt_builder import STEER_DISPLAY_KINDfrom agent.turn_failure_copy import untyped_failed_turn_display_kind@@ -718,6 +719,9 @@ def _project_for_display(messages: list, *, home=None, inline_images: bool = Truif message.get("role") == "user" and message.get("display_kind") == STEER_DISPLAY_KIND and (steer_text := _extract_steer_text_from_message(message)):message = {**message, "display_content": steer_text}+ # A pre_llm_call veto stores a placeholder; the transcript shows what the user typed.+ if message.get("role") == "user" and (typed := withheld_prompt_text(message)) is not None:+ message = {**message, "display_content": typed}if not is_compaction_summary_message(message):projected_messages.append(message)continuediff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex b014f2503e5..ef725c17ac1 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -1040,16 +1040,23 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):self._message_columns_cache = [r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()]return self._message_columns_cache- def set_user_message_content(self, session_id: str, row_id: int, content: Any) -> int:+ def set_user_message_content(self, session_id: str, row_id: int, content: Any,+ display_metadata: Optional[dict[str, Any]] = None) -> int:"""Rewrite the content of ONE known active user row. Used when a user turn was written at submittime (before the agent ran) and the turn prologue then rewrote the prompt it persists (@-file- expansion, native image parts): the early row must show what the transcript will replay, not the- raw keystrokes, and the turn must not append a second row for the same input."""+ expansion, native image parts, a ``pre_llm_call`` veto's placeholder): the early row must show what+ the transcript will replay, not the raw keystrokes, and the turn must not append a second row for+ the same input. ``display_metadata``, when given, replaces the row's (and clears ``api_content``)."""if not session_id or isinstance(row_id, bool) or not isinstance(row_id, int) or row_id <= 0:return 0+ if display_metadata is None:+ return self._write_rowcount(+ "UPDATE messages SET content = ? WHERE id = ? AND session_id = ? AND role = 'user' AND active = 1",+ (self._encode_content(content), row_id, session_id))return self._write_rowcount(- "UPDATE messages SET content = ? WHERE id = ? AND session_id = ? AND role = 'user' AND active = 1",- (self._encode_content(content), row_id, session_id))+ "UPDATE messages SET content = ?, api_content = NULL, display_metadata = ? "+ "WHERE id = ? AND session_id = ? AND role = 'user' AND active = 1",+ (self._encode_content(content), self._encode_display_metadata(display_metadata), row_id, session_id))def deactivate_message(self, session_id: str, row_id: int) -> int:"""Deactivate ONE known row (id-addressed, idempotent; returns the affected row count). Used bydiff --git a/hermes_state_worker_lifecycle.py b/hermes_state_worker_lifecycle.pyindex 420408b8a66..a1fa46fdbfe 100644--- a/hermes_state_worker_lifecycle.py+++ b/hermes_state_worker_lifecycle.py@@ -176,11 +176,17 @@ def worker_message_api_content(db, conn, session_id, payload):def worker_user_content(db, conn, session_id, payload):"""Rewrite ONE active user row of this session, same guards as ``SessionDB.set_user_message_content``."""- if set(payload) != {'row_id', 'content'}:+ if set(payload) - {'display_metadata'} != {'row_id', 'content'}:raise RuntimeStoreError('invalid_params')+ if 'display_metadata' not in payload:+ return {'value': conn.execute(+ "UPDATE messages SET content=? WHERE id=? AND session_id=? AND role='user' AND active=1",+ (db._encode_content(payload['content']), _row_id(payload), session_id)).rowcount}return {'value': conn.execute(- "UPDATE messages SET content=? WHERE id=? AND session_id=? AND role='user' AND active=1",- (db._encode_content(payload['content']), _row_id(payload), session_id)).rowcount}+ "UPDATE messages SET content=?, api_content=NULL, display_metadata=? "+ "WHERE id=? AND session_id=? AND role='user' AND active=1",+ (db._encode_content(payload['content']), db._encode_display_metadata(payload['display_metadata']),+ _row_id(payload), session_id)).rowcount}WORKER_LIFECYCLE_HANDLERS = {diff --git a/tests/agent/test_pre_llm_block_hook.py b/tests/agent/test_pre_llm_block_hook.pyindex 8dff5b3a38b..876a71f4514 100644--- a/tests/agent/test_pre_llm_block_hook.py+++ b/tests/agent/test_pre_llm_block_hook.py@@ -56,36 +56,49 @@ def provider_url():srv.shutdown()-def test_blocked_turn_never_reaches_the_provider_and_is_never_replayed(provider_url, tmp_path, monkeypatch):- """Turn 1 is vetoed: zero chat requests, the block message is the reply and closes the- transcript pair. Turn 2 (a fresh agent reloading the session) reaches the model with the- withheld placeholder in place of the vetoed prompt, while the transcript keeps the original."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+def _agent(provider_url, db):from run_agent import AIAgent- db = SessionDB(db_path=tmp_path / "state.db")- verdicts = {"pre_llm_call": [{"context": "IGNORED-ON-BLOCK"}, {"action": "block", "message": BLOCK_MSG}]}+ return AIAgent(+ api_key="test-key", base_url=provider_url, provider="openai-compat", model="test-model",+ max_iterations=4, enabled_toolsets=[], quiet_mode=True, skip_context_files=True,+ skip_memory=True, save_trajectories=False, platform="cli", session_db=db, session_id="s-block",+ )+- def make_agent():- return AIAgent(- api_key="test-key", base_url=provider_url, provider="openai-compat", model="test-model",- max_iterations=4, enabled_toolsets=[], quiet_mode=True, skip_context_files=True,- skip_memory=True, save_trajectories=False, platform="cli", session_db=db, session_id="s-block",- )+def _blocked_session(provider_url, db):+ """Run one vetoed turn on ``s-block``; return its result."""+ verdicts = [{"context": "IGNORED-ON-BLOCK"}, {"action": "block", "message": BLOCK_MSG}]+ with patch("hermes_cli.plugins.invoke_hook",+ side_effect=lambda hook, **kw: list(verdicts) if hook == "pre_llm_call" else []):+ return _agent(provider_url, db).run_conversation(f"look up {SECRET}", conversation_history=[], task_id="t")+++def test_blocked_turn_never_reaches_the_provider_and_stores_only_the_placeholder(provider_url, tmp_path, monkeypatch):+ """Turn 1 is vetoed: zero chat requests, the block message is the reply and closes the+ transcript pair. The stored row's content is the placeholder (what session_search and every+ other content reader sees); the typed text is display-only metadata the transcript renders.+ Turn 2 (a fresh agent reloading the session) replays the placeholder, never the prompt."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ from agent.message_metadata import withheld_prompt_text+ from tools.session_search_tool import session_search+ db = SessionDB(db_path=tmp_path / "state.db")try:- with patch("hermes_cli.plugins.invoke_hook", side_effect=lambda hook, **kw: list(verdicts.get(hook, []))):- result = make_agent().run_conversation(f"look up {SECRET}", conversation_history=[], task_id="t")- assert _Provider.chat_requests == []- assert result["final_response"] == BLOCK_MSG- assert result["turn_exit_reason"] == PRE_LLM_BLOCK_EXIT_REASON- assert result["api_calls"] == 0 and result["failed"] is False-- verdicts.clear()- history = db.get_messages_as_conversation("s-block")- assert [(m["role"], m["content"]) for m in history] == [- ("user", f"look up {SECRET}"), ("assistant", BLOCK_MSG)]- follow_up = make_agent().run_conversation("next question", conversation_history=history, task_id="t")+ result = _blocked_session(provider_url, db)+ assert _Provider.chat_requests == []+ assert result["final_response"] == BLOCK_MSG+ assert result["turn_exit_reason"] == PRE_LLM_BLOCK_EXIT_REASON+ assert result["api_calls"] == 0 and result["failed"] is False++ history = db.get_messages_as_conversation("s-block")+ assert [(m["role"], m["content"]) for m in history] == [+ ("user", PRE_LLM_BLOCK_WITHHELD_PROMPT), ("assistant", BLOCK_MSG)]+ assert withheld_prompt_text(history[0]) == f"look up {SECRET}"+ assert SECRET not in session_search(query="CUSTOMER", db=db, current_session_id="other")++ follow_up = _agent(provider_url, db).run_conversation("next question", conversation_history=history,+ task_id="t")assert follow_up["final_response"] == "MODEL-ANSWER"(sent,) = _Provider.chat_requestswire = json.dumps(sent["messages"])@@ -94,6 +107,32 @@ def test_blocked_turn_never_reaches_the_provider_and_is_never_replayed(provider_db.close()+def test_compaction_of_a_blocked_turn_never_sends_the_prompt(provider_url, tmp_path, monkeypatch):+ """A later compaction serializes the stored rows for the summarizer and quotes user turns in its+ handoff: neither the summary request nor the compacted history may carry the vetoed prompt."""+ home = tmp_path / "home"+ home.mkdir()+ (home / "config.yaml").write_text(+ f"auxiliary:\n compression: {{provider: custom, base_url: '{provider_url}', api_key: k, model: m}}\n")+ monkeypatch.setenv("HERMES_HOME", str(home))+ from agent.conversation_compression import compress_context++ db = SessionDB(db_path=tmp_path / "state.db")+ try:+ _blocked_session(provider_url, db)+ blocked_pair = db.get_messages_as_conversation("s-block")+ filler = [{"role": role, "content": f"{role} {i} " + "x" * 400}+ for i in range(8) for role in ("user", "assistant")]+ agent = _agent(provider_url, db)+ compressed, _ = compress_context(agent, filler[:12] + blocked_pair + filler, "sys",+ approx_tokens=150000, force=True)+ assert _Provider.chat_requests, "the summarizer was never called"+ assert SECRET not in json.dumps(_Provider.chat_requests)+ assert SECRET not in json.dumps([{k: m.get(k) for k in ("content", "api_content")} for m in compressed])+ finally:+ db.close()++@pytest.mark.parametrize(("stdout", "expected"), [('{"action": "block", "message": "no"}', {"action": "block", "message": "no"}),('{"decision": "block", "reason": "no"}', {"action": "block", "message": "no"}),diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.pyindex 22ced4df50d..b0227d29c4c 100644--- a/tui_gateway/session_history.py+++ b/tui_gateway/session_history.py@@ -298,6 +298,7 @@ def _history_to_messages(history: list[dict], *, profile_home=None, image_urls:"""``image_urls=False`` is the ``inline_images=false`` projection (#116511): image parts render ``[image]``so a remote client's history read stays kilobytes instead of re-transmitting every stored attachment."""from agent.history_commentary import project_history_commentary+ from agent.message_metadata import withheld_prompt_textmessages = []tool_call_args = {}@@ -323,6 +324,8 @@ def _history_to_messages(history: list[dict], *, profile_home=None, image_urls:continueif role == "user":content_text = _DISCORD_TRIGGERING_NOTE_RE.sub(r"\1", content_text)+ # A pre_llm_call veto stores a placeholder; the transcript shows what the user typed.+ content_text = withheld_prompt_text(m) or content_textif role == "user" and m.get("display_kind") == STEER_DISPLAY_KIND:# Mid-turn /steer: show the user's own words, not the model-facing marker wrapper.from agent.conversation_compression import _extract_steer_text_from_message