The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(hooks): pre_llm_call can block a turn before any inference request
Tekniumad9229c8431f
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 8583670f91b..dc47cd72189 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -35,7 +35,7 @@ from agent.runtime_cwd import resolve_agent_cwdfrom agent.surface_switch import (identity_line_value, note_inert_pinned_tools, runtime_host_value, stage_surface_switch_note,)-from agent.turn_context import PreflightCompressionTimedOut, build_turn_context+from agent.turn_context import PRE_LLM_BLOCK_EXIT_REASON, PreflightCompressionTimedOut, build_turn_contextfrom hermes_cli.observability.shared_metrics_efficiency import record_cache_break, record_prompt_rebuildfrom hermes_cli.plugins_dispatch import held_stream_transformsfrom agent.turn_retry_state import TurnRetryState@@ -1600,6 +1600,25 @@ def _run_api_retry_loop(agent, s: _LoopState) -> Optional[dict[str, Any]]:return None+def _finalize_from_state(agent: Any, s: _LoopState) -> dict[str, Any]:+ """Post-loop finalization (agent/turn_finalizer.finalize_turn) fed from the loop state."""+ return finalize_turn(agent, **{+ name: getattr(s, name)+ for name in inspect.signature(finalize_turn).parameters if name != "agent"+ })+++def _turn_without_loop(agent: Any, s: _LoopState, block_message: str) -> Optional[dict[str, Any]]:+ """The turn's result when it never enters the generic loop, else None. A ``pre_llm_call``+ veto finalizes with no inference request (the block message closes the transcript pair);+ the opt-in codex app-server runtime runs the whole turn in its subprocess+ (agent/transports/codex_app_server_session.py)."""+ if block_message:+ s.final_response, s._turn_exit_reason = block_message, PRE_LLM_BLOCK_EXIT_REASON+ return _finalize_from_state(agent, s)+ return _codex_app_server_turn(agent, s) if agent.api_mode == "codex_app_server" else None++def _codex_app_server_turn(agent: Any, s: Any) -> Optional[dict[str, Any]]:"""The codex app-server's result for this turn, or None when its failure activated a fallback and thegeneric loop retries the same user turn."""@@ -1717,10 +1736,8 @@ def _run_conversation_turn(max_compression_attempts=getattr(agent, "max_compression_attempts", 3),**{f.name: getattr(_ctx, f.name.lstrip("_")) for f in fields(_LoopState) if f.name in _CTX_FIELDS},)- # Opt-in runtime: api_mode == codex_app_server hands the whole turn to the codex- # app-server subprocess (see agent/transports/codex_app_server_session.py).- if agent.api_mode == "codex_app_server" and (codex_result := _codex_app_server_turn(agent, s)) is not None:- return codex_result+ if (early_result := _turn_without_loop(agent, s, _ctx.plugin_block_message)) is not None:+ return early_result_prelude_action, _prelude_result = play_prelude(agent, s, prelude)if _prelude_action == "return":@@ -1774,11 +1791,7 @@ def _run_conversation_turn(if _run_phase(handle_outer_loop_error, agent, s, e=e).action == "break":break- # Post-loop finalization lives in agent/turn_finalizer.finalize_turn.- result = finalize_turn(agent, **{- name: getattr(s, name)- for name in inspect.signature(finalize_turn).parameters if name != "agent"- })+ result = _finalize_from_state(agent, s)if s._compression_timeout_exhausted:# Reuse the gateway's context-recovery contract: transcript stays intact while# future input can move to a clean session (#98722).diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex 967d53e7370..acb846e15af 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -667,7 +667,17 @@ def _parse_context(data: dict[str, Any]) -> Optional[dict[str, Any]]:return {"context": context} if isinstance(context, str) and context.strip() else None-_RESPONSE_PARSERS: dict[str, Callable[[dict[str, Any]], Optional[dict[str, Any]]]] = {"pre_tool_call": _parse_pre_tool_call, "pre_verify": _parse_pre_verify}+def _parse_pre_llm_call(data: dict[str, Any]) -> Optional[dict[str, Any]]:+ # A turn veto before any inference request, in either dialect (as for pre_tool_call); else context.+ for verb, primary, secondary, _ in _PRE_TOOL_DIALECTS:+ if data.get(verb) == "block":+ return {"action": "block", "message": _block_message(data.get(primary), data.get(secondary))}+ return _parse_context(data)+++_RESPONSE_PARSERS: dict[str, Callable[[dict[str, Any]], Optional[dict[str, Any]]]] = {+ "pre_tool_call": _parse_pre_tool_call, "pre_verify": _parse_pre_verify, "pre_llm_call": _parse_pre_llm_call,+}def _parse_response(event: str, stdout: str) -> Optional[dict[str, Any]]:diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 94268d605e7..f59f9ad30aa 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -503,6 +503,7 @@ class TurnContext:current_turn_user_idx: int # index of the current user turn within ``messages``should_review_memory: bool = False # post-turn memory review should fireplugin_user_context: str = "" # ``pre_llm_call`` context (appended to user message)+ plugin_block_message: str = "" # ``pre_llm_call`` veto: the turn ends with this, no inferenceext_prefetch_cache: str = "" # external-memory prefetch, reused across iterationspreflight_compression_blocked: bool = False # immediate retry proved ineffective@@ -800,13 +801,21 @@ 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).+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 _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]],+ messages: list[Any], conversation_history: Optional[list[Any]], blocks: Optional[list[str]] = None,) -> str:"""Run ``pre_llm_call`` plugins; their context is injected into the user message(never the system prompt). Oversized per-hook context is spilled to disk so a- runaway plugin can't inflate every subsequent turn's prompt."""+ runaway plugin can't inflate every subsequent turn's prompt. Each+ ``{"action": "block", "message": ...}`` veto is appended to ``blocks`` (#57364); one+ without a message is ignored, as for ``pre_tool_call``."""if getattr(agent, "_persist_disabled", False):return ""try:@@ -836,6 +845,11 @@ def _collect_pre_llm_call_context(_spill_config_cached = None_ctx_parts: list[str] = []for r in _pre_results:+ if isinstance(r, dict) and r.get("action") == "block":+ _msg = r.get("message")+ if blocks is not None and isinstance(_msg, str) and _msg.strip():+ blocks.append(_msg.strip())+ continueif isinstance(r, dict) and r.get("context"):_piece = str(r["context"])elif isinstance(r, str) and r.strip():@@ -1185,11 +1199,13 @@ def build_turn_context(conversation_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,+ 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)@@ -1198,16 +1214,21 @@ def build_turn_context()_bind_interrupt_scope(agent, ra)- ext_prefetch_cache = _memory_turn_start_and_prefetch(agent, original_user_message, turn_author)+ # A vetoed prompt never leaves the host: no external-memory prefetch, no titling call.+ ext_prefetch_cache = "" if plugin_block_message else _memory_turn_start_and_prefetch(+ agent, original_user_message, turn_author)# Title the session now: titling depends only on the user's ask (before any injected# context lands on list content), so it runs concurrently with the turn. Daemon thread,# no-op once titled; it ensures the session row itself.- _maybe_title_session_at_turn_start(agent, messages, title_user_message)+ if not plugin_block_message:+ _maybe_title_session_at_turn_start(agent, messages, title_user_message)# 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 isinstance(messages[current_turn_user_idx].get("content"), list):+ if plugin_block_message:+ messages[current_turn_user_idx]["api_content"] = PRE_LLM_BLOCK_WITHHELD_PROMPT+ 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,preflight_compressed=compaction.compressed,@@ -1225,8 +1246,8 @@ def build_turn_context(conversation_history=conversation_history, active_system_prompt=active_system_prompt,effective_task_id=effective_task_id, turn_id=turn_id,current_turn_user_idx=current_turn_user_idx, should_review_memory=should_review_memory,- plugin_user_context=plugin_user_context, ext_prefetch_cache=ext_prefetch_cache,- preflight_compression_blocked=compaction.blocked,+ plugin_user_context=plugin_user_context, plugin_block_message=plugin_block_message,+ ext_prefetch_cache=ext_prefetch_cache, preflight_compression_blocked=compaction.blocked,)diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 591a3b86a97..898e34a6ea9 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -588,6 +588,34 @@ def public_pre_transform(agent, pre_transform: Optional[Any]) -> Optional[Any]:return None if getattr(agent, "_hold_stream", False) else pre_transform+def _mirror_turn_to_memory(+ agent, *, original_user_message, final_response, interrupted, messages, review_memory, review_skills, vetoed,+) -> None:+ """External-memory sync (+ next prefetch), then the background memory/skill review. A prompt a+ ``pre_llm_call`` hook vetoed never leaves the host, so neither runs for that turn."""+ if vetoed:+ return+ agent._sync_external_memory_for_turn(+ original_user_message=original_user_message, final_response=final_response,+ interrupted=interrupted, messages=messages,+ )+ # Background memory/skill review runs AFTER delivery so it never competes with the+ # user's task. Suppressed by skip_background_review (e.g. cron): the fork costs+ # ~30K tokens / event with no human-in-the-loop benefit. Best-effort; the review+ # clones the snapshot structurally so its sanitizers can't reach the live transcript.+ if (+ final_response+ and not interrupted+ and not getattr(agent, "skip_background_review", False)+ and (review_memory or review_skills)+ ):+ with suppress(Exception):+ agent._spawn_background_review(+ messages_snapshot=list(messages), review_memory=review_memory,+ review_skills=review_skills,+ )++def finalize_turn(agent, *, final_response, api_call_count, interrupted, failed, messages, conversation_history,effective_task_id, turn_id, user_message, original_user_message, _should_review_memory,@@ -837,28 +865,13 @@ def finalize_turn(if _should_review_skills:agent._iters_since_skill = 0- # External memory provider: sync the completed turn + queue next prefetch.- agent._sync_external_memory_for_turn(- original_user_message=original_user_message, final_response=final_response,- interrupted=interrupted, messages=messages,+ from agent.turn_context import PRE_LLM_BLOCK_EXIT_REASON+ _mirror_turn_to_memory(+ agent, original_user_message=original_user_message, final_response=final_response,+ interrupted=interrupted, messages=messages, review_memory=_should_review_memory,+ review_skills=_should_review_skills, vetoed=_turn_exit_reason == PRE_LLM_BLOCK_EXIT_REASON,)- # Background memory/skill review runs AFTER delivery so it never competes with the- # user's task. Suppressed by skip_background_review (e.g. cron): the fork costs- # ~30K tokens / event with no human-in-the-loop benefit. Best-effort; the review- # clones the snapshot structurally so its sanitizers can't reach the live transcript.- if (- final_response- and not interrupted- and not getattr(agent, "skip_background_review", False)- and (_should_review_memory or _should_review_skills)- ):- with suppress(Exception):- agent._spawn_background_review(- messages_snapshot=list(messages), review_memory=_should_review_memory,- review_skills=_should_review_skills,- )-# Opt-in (compression.prepare_ahead): near the trigger, write the next compaction summary# between turns. No-op otherwise; never raises.from agent.prepared_compaction import maybe_preparediff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex 1c1d68c2a56..a2ee443b553 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -279,7 +279,8 @@ class PluginDispatchMixin:what they declare. Each callback is isolated. Bounded hooks and ``pre_tool_call`` run under``plugins.hook_callback_timeout`` (worker abandoned, never joined); ``pre_tool_call`` failsclosed with a block directive, others skip. ``_HOOK_CALLER_THREAD_HOOKS`` always run on the- caller thread. ``pre_llm_call`` may return ``{"context": "..."}`` (or a str) to inject.+ caller thread. ``pre_llm_call`` may return ``{"context": "..."}`` (or a str) to inject, or+ ``{"action": "block", "message": "..."}`` to end the turn before any inference request."""from agent.safe_worker_policy import safe_worker_enableddiff --git a/tests/agent/test_pre_llm_block_hook.py b/tests/agent/test_pre_llm_block_hook.pynew file mode 100644index 00000000000..8dff5b3a38b--- /dev/null+++ b/tests/agent/test_pre_llm_block_hook.py@@ -0,0 +1,103 @@+"""``pre_llm_call`` block directive: a policy hook vetoes a turn before any inference request (#57364)."""++from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer+from unittest.mock import patch++import pytest++from agent import shell_hooks+from agent.turn_context import PRE_LLM_BLOCK_EXIT_REASON, PRE_LLM_BLOCK_WITHHELD_PROMPT+from hermes_state import SessionDB++BLOCK_MSG = "Blocked by policy: prompt contains a customer ID."+SECRET = "CUSTOMER-ID-4242"+++class _Provider(BaseHTTPRequestHandler):+ chat_requests: list = []++ def do_POST(self):+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))).decode())+ if "messages" in req:+ type(self).chat_requests.append(req)+ if req.get("stream") is True:+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.end_headers()+ for delta, finish in (({"role": "assistant", "content": "MODEL-ANSWER"}, None), ({}, "stop")):+ chunk = {"id": "m", "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}+ self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())+ self.wfile.write(b"data: [DONE]\n\n")+ return+ body = json.dumps({+ "id": "m", "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "MODEL-ANSWER"}, "finish_reason": "stop"}],+ }).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *a, **kw):+ pass+++def provider_url():+ _Provider.chat_requests = []+ srv = HTTPServer(("127.0.0.1", 0), _Provider)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ yield f"http://127.0.0.1:{srv.server_address[1]}/v1"+ 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"))+ 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}]}++ 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",+ )++ 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")+ assert follow_up["final_response"] == "MODEL-ANSWER"+ (sent,) = _Provider.chat_requests+ wire = json.dumps(sent["messages"])+ assert SECRET not in wire and PRE_LLM_BLOCK_WITHHELD_PROMPT in wire+ finally:+ db.close()++[email protected](("stdout", "expected"), [+ ('{"action": "block", "message": "no"}', {"action": "block", "message": "no"}),+ ('{"decision": "block", "reason": "no"}', {"action": "block", "message": "no"}),+ ('{"context": "today is Friday"}', {"context": "today is Friday"}),+])+def test_shell_hook_pre_llm_call_block_in_both_dialects(stdout, expected):+ assert shell_hooks._parse_response("pre_llm_call", stdout) == expecteddiff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex ffa5f10f8c0..5caa8436784 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -1549,7 +1549,7 @@ Each hook is documented in full on the **[Event Hooks reference](../../user-guid| `kanban_task_completed` | A kanban task completes (worker process) | `task_id, board, assignee, run_id, profile_name, summary: str \| None` | ignored || `kanban_task_blocked` | A kanban task is blocked (worker process) | `task_id, board, assignee, run_id, profile_name, reason: str \| None` | ignored |-Most hooks are fire-and-forget observers — their return values are ignored. The exceptions are `pre_llm_call`, which can inject context into the conversation, and `pre_tool_call`, which can return a block/approve directive.+Most hooks are fire-and-forget observers — their return values are ignored. The exceptions are `pre_llm_call`, which can inject context into the conversation or block the turn before it reaches the model, and `pre_tool_call`, which can return a block/approve directive.All callbacks should accept `**kwargs` for forward compatibility. If a hook callback crashes, it's logged and skipped. Other hooks and the agent continue normally.@@ -1559,7 +1559,7 @@ The **API request hooks** are observers for the raw provider request, one level### `pre_llm_call` context injection-This is the only hook whose return value matters. When a `pre_llm_call` callback returns a dict with a `"context"` key (or a plain string), Hermes injects that text into the **current turn's user message**. This is the mechanism for memory plugins, RAG integrations, guardrails, and any plugin that needs to provide the model with additional context.+When a `pre_llm_call` callback returns a dict with a `"context"` key (or a plain string), Hermes injects that text into the **current turn's user message**. This is the mechanism for memory plugins, RAG integrations, guardrails, and any plugin that needs to provide the model with additional context.#### Return format@@ -1570,12 +1570,17 @@ return {"context": "Recalled memories:\n- User prefers dark mode\n- Last project# Plain string (equivalent to the dict form above)return "Recalled memories:\n- User prefers dark mode"+# Block the turn before it reaches the model (DLP / policy plugins)+return {"action": "block", "message": "Blocked by policy: prompt contains a customer ID."}+# Return None or don't return → no injection (observer-only)return None```Any non-None, non-empty return with a `"context"` key (or a plain non-empty string) is collected and appended to the user message for the current turn.+A `{"action": "block", "message": "..."}` return vetoes the turn **before any inference request**: the message is shown to the user in place of a model reply and saved as the assistant reply (so the transcript keeps a normal `user → assistant` pair and `--resume` works), the turn makes zero model calls, and the result carries `turn_exit_reason: "blocked_by_plugin_pre_llm_call"`. The blocked prompt is also kept out of session titling, external-memory prefetch/sync and the background memory review for that turn. The first block wins; a block without a message is ignored. Model metadata lookups (such as a `/models` context-length probe on a fresh session) can still run before the hook; they carry no message content.+#### Oversized-context spillPer-hook context is capped at `10,000` characters by default. Anything above the cap is written to `$HERMES_HOME/hook_outputs/<session_id>/<uuid>.txt` and replaced with a head/tail preview plus the saved path. The model can read the full content via `read_file` or `terminal` if it genuinely needs it. This keeps a runaway plugin from inflating every subsequent turn's prompt and blowing out the prompt cache prefix. Tune in `config.yaml`:diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 99eff53702f..8c3c6683250 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -453,7 +453,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `transform_tool_result` | Transform | After `post_tool_call`, before conversation append; first string replaces the result. | `tool_name`, `args`, `result`, `task_id`, `session_id`, `tool_call_id`, `turn_id`, `api_request_id`, `duration_ms`, `status`, `error_type`, `error_message` | Exposes the full model-bound result and arguments. || `transform_terminal_output` | Transform | After bounded foreground process capture, before final output limiting; first string replaces output. | `command`, `output`, `returncode`, `task_id`, `env_type` | Command/output may contain credentials. || `pre_transcription` | Transform | Fired by the STT dispatcher after provider resolution and before any backend (built-in, command-type, or plugin-registered) is invoked; dict results are applied in registration order, last-writer-wins per field (`prompt`, `language`, `model`; `file_path` is read-only). | `file_path`, `provider`, `model`, `language`, `prompt`, `source` | The final prompt is uploaded to the configured STT provider with the audio — keep secrets out of hook returns. |-| `pre_llm_call` | Directive/control | Once per turn before the loop; all valid string/`{"context": ...}` returns are joined and injected into the user message. | `session_id`, `task_id`, `turn_id`, `user_message`, `conversation_history`, `is_first_turn`, `model`, `platform`, `parent_session_id`, `sender_id` | Full user message and conversation history. |+| `pre_llm_call` | Directive/control | Once per turn before the loop; all valid string/`{"context": ...}` returns are joined and injected into the user message; the first valid `{"action": "block", "message": ...}` ends the turn before any inference request. | `session_id`, `task_id`, `turn_id`, `user_message`, `conversation_history`, `is_first_turn`, `model`, `platform`, `parent_session_id`, `sender_id` | Full user message and conversation history. || `post_llm_call` | Observer | Successful, non-interrupted turn finalization; return ignored. | `session_id`, `task_id`, `turn_id`, `user_message`, `assistant_response`, `conversation_history`, `model`, `platform`, `side_question_token` | Full prompt, response, and history. || `transform_llm_output` | Transform | Before `post_llm_call` and final delivery; first non-empty string replaces the response. | `response_text`, `session_id`, `model`, `platform` | Full final assistant text. || `pre_verify` | Directive/control | At the bounded edited-code verify gate; first valid continue/block-stop directive keeps the turn going. | `session_id`, `platform`, `model`, `coding`, `attempt`, `final_response`, `changed_paths` | Draft response and changed paths. |@@ -699,6 +699,8 @@ def my_callback(session_id: str, user_message: str, conversation_history: list,**Return value:** If the callback returns a dict with a `"context"` key, or a plain non-empty string, the text is appended to the current turn's user message. Return `None` for no injection.+A `{"action": "block", "message": "..."}` return vetoes the turn **before any inference request**: the message is shown to the user in place of a model reply and saved as the assistant reply (so the transcript keeps a normal `user → assistant` pair and `--resume` works), the turn makes zero model calls, and the result carries `turn_exit_reason: "blocked_by_plugin_pre_llm_call"`. The blocked prompt is also kept out of session titling, external-memory prefetch/sync and the background memory review for that turn. The first block wins; a block without a message is ignored. Model metadata lookups (such as a `/models` context-length probe on a fresh session) can still run before the hook; they carry no message content.+```python# Inject contextreturn {"context": "Recalled memories:\n- User likes Python\n- Working on hermes-agent"}@@ -1963,6 +1965,10 @@ profile's `HERMES_HOME`. `tool_name` and `tool_input` are `null` for non-tool ev// Inject context for pre_llm_call:{"context": "Today is Friday, 2026-04-17"}+// Block the turn before any inference request (pre_llm_call); both shapes accepted:+{"action": "block", "message": "Blocked by policy: prompt contains a customer ID"}+{"decision": "block", "reason": "Blocked by policy: prompt contains a customer ID"}+// Keep the agent going at the verify gate (pre_verify); both shapes accepted:{"action": "continue", "message": "Run the formatter, then finish."}{"decision": "block", "reason": "Run the formatter, then finish."}