Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Keep Gemini thought signatures, send once, and keep the captured part out of a second middleware pass
Elevatormusicd1a2c94da32d
diff --git a/README.md b/README.mdindex 16b4e1d..e532dcb 100644--- a/README.md+++ b/README.md@@ -100,7 +100,7 @@ The settings are in `plugins.entries.warm_compaction.settings`. An invalid value| Key | Type and range | Default | Use || --- | --- | --- | --- || `threshold` | float, 0.10 to 0.95 | 0.50 | Fraction of the context window at which automatic compaction starts |-| `tail_tokens` | int, 0 or more | 0: 2.5% of the context window, from 10,000 to 25,000 | Size of the verbatim tail |+| `tail_tokens` | int, 0 or more | 0: 2.5% of the context window, from 10,000 to 25,000 | Size of the verbatim tail, at most half of the compaction threshold || `user_copy_chars` | int, 0 or more | 24,000 | Total characters of user messages that the summary copies || `warm` | bool | true | Set false to use only the fallback summary, for comparison runs |@@ -138,7 +138,7 @@ warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021```- `path` is `warm`, `fallback`, or `fixed`.-- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.+- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.- `cached_tokens` is `None` when the server does not report it. Then the cache reuse is unknown.The engine status (`get_status()`) has the same values in `warm_last`. The log never contains message text, request bodies, or keys.diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex 9b87532..0eedba0 100644--- a/evidence/plugin-integration.json+++ b/evidence/plugin-integration.json@@ -1,6 +1,6 @@{"check": "standalone warm_compaction plugin on unpatched Hermes Agent",- "started_utc": "2026-10-06T08:09:55Z",+ "started_utc": "2026-10-06T08:32:14Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,13 +10,13 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "3ee60f35ae4e8fc0376ab6634c721ae1ca429593d10730f19addc3be545fe682",- "warm_compaction/engine.py": "60f78d788eb7abb2e76a86fe2148837b233758e2ce7c05eccec9fb5c27001149",+ "warm_compaction/engine.py": "95ae73286225c664512f567584e99ce07ff409a9071789ddc2a1d29eb24ec2a3","warm_compaction/fallback.py": "f2551f0cf957b07fa6ba79dd92c8c5e211d70810d675e492ca509063b92de5a1","warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2","warm_compaction/layout.py": "fd4d260380ce2cc44aa846758762a05bb4737c10677bceec0b17fd3c59c943f5","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "a8943216049ef95742466c5628108154e239b96672726c732c508e30c95ac914",- "warm_compaction/warm.py": "595ab834836c6605480df8a6b9decadde19f6d114e7781b04e6d0cfddb3b1b18"+ "warm_compaction/warm.py": "7e1df5fb42e962567baf0644943ab260680af42273a65e017d8cddaa0c978d40"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text","scenarios": [@@ -75,11 +75,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.118,+ "compress_seconds": 0.13,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.023,+ "elapsed_s": 0.032,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -188,7 +188,7 @@"install","run"],- "process_seconds": 61.681+ "process_seconds": 59.565},{"scenario": "manual_fallback",@@ -247,11 +247,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.36,+ "compress_seconds": 0.259,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.172,+ "elapsed_s": 0.125,"prompt_tokens": null,"cached_tokens": null},@@ -360,7 +360,7 @@"install","run"],- "process_seconds": 36.723+ "process_seconds": 35.611},{"scenario": "manual_fixed",@@ -418,11 +418,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.255,+ "compress_seconds": 0.271,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.11,+ "elapsed_s": 0.125,"prompt_tokens": null,"cached_tokens": null},@@ -430,7 +430,7 @@"final_session_id": "wc-manual_fixed","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -531,7 +531,7 @@"install","run"],- "process_seconds": 35.632+ "process_seconds": 32.453},{"scenario": "auto_tool_loop",@@ -617,7 +617,7 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.0,"prompt_tokens": 35205,"cached_tokens": 17602},@@ -630,8 +630,8 @@},"compression_count": 2,"fence_denied": {- "child_process_blocked": 8,- "network_host_blocked": 1+ "network_host_blocked": 1,+ "child_process_blocked": 7},"fence_blocked_programs": ["git",@@ -645,7 +645,6 @@"fence_blocked_callers": ["child_process_blocked from hermes_cli/local_runtime/processes.py:spawn_server < hermes_cli/_subprocess_compat.py:bounded_probe_run < hermes_cli/_subprocess_compat.py:bounded_git_probe","child_process_blocked from hermes_cli/local_runtime/processes.py:spawn_server < hermes_cli/_subprocess_compat.py:bounded_probe_run < hermes_cli/_subprocess_compat.py:noninteractive_repo_git_env",- "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout","child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version","child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of","network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"@@ -734,7 +733,7 @@"install","run"],- "process_seconds": 37.074+ "process_seconds": 34.825},{"scenario": "rollback",@@ -784,7 +783,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.132,+ "compress_seconds": 0.142,"warm_last": {"path": "warm","reason": "accepted",@@ -796,7 +795,7 @@"final_session_id": "wc-rollback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -947,7 +946,8 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -955,7 +955,9 @@"python","python3"],- "fence_blocked_hosts": []+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ]},"exit": [0,@@ -967,10 +969,10 @@"run","rollback"],- "process_seconds": 40.907+ "process_seconds": 41.308}],- "finished_utc": "2026-10-06T08:13:27Z",+ "finished_utc": "2026-10-06T08:35:38Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 35ef278..13dcd36 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -206,6 +206,37 @@ class EngineTest(unittest.TestCase):self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),("fallback", "middleware_changed_reply"))+ def test_a_second_send_is_refused_before_it_sends(self):+ def twice(request=None, next_call=None, **context):+ first = next_call()+ try:+ next_call()+ except Exception:+ pass+ return first+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(twice)+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ self.engine.compress([*rows, reply])+ self.assertEqual(len(self.post.calls), 1)+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),+ ("fallback", "middleware_repeated"))++ def test_a_request_middleware_that_changes_the_captured_part_stops_the_warm_request(self):+ # The captured body already went through the request middleware. A second pass would apply it twice.+ def prepend(request=None, **context):+ return {"request": {**request, "messages": [{"role": "system", "content": "policy"},+ *request["messages"]]}}+ wc_hermes_stub.REQUEST_MIDDLEWARE.append(prepend)+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ self.engine.compress([*rows, reply])+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),+ ("fallback", "middleware_rewrite"))+ self.assertEqual(self.post.calls, [])+def test_a_rewriting_middleware_stops_the_warm_request(self):# The capture keeps the body before later middleware. A middleware that rewrites requests can have# rewritten the captured request too, so the warm request is not sent.@@ -366,7 +397,9 @@ class SettingsTest(unittest.TestCase):# The automatic tail stays at or below half of the compaction threshold, so a small window can compact.self.assertEqual(self.module.tail_budget(0, 20_000, 10_000), 5_000)self.assertEqual(self.module.tail_budget(0, 200_000, 100_000), 10_000)- self.assertEqual(self.module.tail_budget(7, 20_000, 10), 7)+ self.assertEqual(self.module.tail_budget(7, 20_000, 10), 5)+ self.assertEqual(self.module.tail_budget(100_000, 128_000, 64_000), 32_000)+ self.assertEqual(self.module.tail_budget(7, 20_000, 10_000), 7)def test_hermes_value_uses_the_replacement(self):read = self.module.hermes_valuediff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 9eba35f..fbcb2d2 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -133,6 +133,25 @@ class BuildRequestTest(unittest.TestCase):self.messages = [*self.rows, assistant("", [("c1", "read", "{}")], reasoning="look"), tool("c1", "r1")]self.assertNotIn("reasoning_content", self.build(capture_for(self.rows, self.reply))["messages"][-3])+ def test_appended_tool_calls_keep_the_gemini_thought_signature(self):+ signed = {"google": {"thought_signature": "sig-1"}}+ reply = assistant("", [("c1", "read", "{}")])+ reply["tool_calls"][0]["extra_content"] = signed+ reply["tool_calls"][0]["call_id"] = "c1"+ self.messages = [*self.rows, reply, tool("c1", "r1")]+ gemini = capture_for(self.rows, self.reply, route=("gemini-3-pro", ROUTE[1], ROUTE[2]))+ sent = build_request(gemini, self.messages, ("gemini-3-pro", ROUTE[1], ROUTE[2]), 100_000,+ INSTRUCTION)["messages"][-3]+ self.assertEqual(sent["tool_calls"][0], {"id": "c1", "type": "function", "extra_content": signed,+ "function": {"name": "read", "arguments": "{}"}})+ # Other models reject the field; an empty signature is not sent.+ other = self.build(capture_for(self.rows, self.reply))["messages"][-3]+ self.assertNotIn("extra_content", other["tool_calls"][0])+ reply["tool_calls"][0]["extra_content"] = {"google": {"thought_signature": " "}}+ sent = build_request(gemini, self.messages, ("gemini-3-pro", ROUTE[1], ROUTE[2]), 100_000,+ INSTRUCTION)["messages"][-3]+ self.assertNotIn("extra_content", sent["tool_calls"][0])+def test_sends_every_trailing_user_row(self):# The tail can keep only the newest of several user rows. The handoff must see the older ones too.self.messages = [*self.messages, user("u4 " + "x" * 5_000)]diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex ba346b4..9f85770 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -59,11 +59,9 @@ def read_settings(get_config: Callable[..., Any] | None) -> dict[str, Any]:def tail_budget(setting: int, context_length: int, threshold_tokens: int = 0) -> int:"""Return the tail size: the setting, or 2.5% of the context window kept between 10,000 and 25,000.- The automatic size is also at most half of the compaction threshold. Otherwise the tail can hold the- whole history when compaction starts, and nothing comes before the tail."""- if setting > 0:- return setting- budget = max(TAIL_MIN, min(TAIL_MAX, int(context_length * TAIL_SHARE)))+ The size is also at most half of the compaction threshold, for a set value too. Otherwise the tail can hold+ the whole history when compaction starts, and nothing comes before the tail."""+ budget = setting if setting > 0 else max(TAIL_MIN, min(TAIL_MAX, int(context_length * TAIL_SHARE)))return min(budget, threshold_tokens // 2) if threshold_tokens > 0 else budget@@ -215,7 +213,7 @@ class WarmCompactionEngine(ContextEngine):handoff.build_instruction(focus_topic, memory))if self._cancelled():raise warm.WarmRefusal("cancelled")- reply = self._execute(body)+ reply = self._execute(body, len(capture["body"]["messages"]))record.update(prompt_tokens=reply["prompt_tokens"], cached_tokens=reply["cached_tokens"])text, reason = handoff.gate(reply, prefixes)if text is None:@@ -229,11 +227,12 @@ class WarmCompactionEngine(ContextEngine):record.update(path="warm", reason="accepted")return text- def _execute(self, body: dict[str, Any]) -> dict[str, Any]:+ def _execute(self, body: dict[str, Any], captured: int) -> dict[str, Any]:"""Send the warm request through the Hermes llm_request and llm_execution middleware, as Hermes sends amain request. A request middleware can change the request, for example to redact the new rows. Anexecution middleware can audit, block, or replace the request. A block, a rewrite, or a replaced reply- stops the warm request; the fallback summary then runs."""+ stops the warm request; the fallback summary then runs. The first captured messages of the body are+ the captured request, which already went through the request middleware."""try:from hermes_cli.middleware import apply_llm_request_middleware, run_llm_execution_middlewareexcept Exception as error:@@ -241,20 +240,32 @@ class WarmCompactionEngine(ContextEngine):context = {"purpose": NAME, "api_request_id": None, "session_id": self._wc_session_id,"model": self._wc_route[0], "base_url": self._wc_route[1], "api_mode": self._wc_route[2]}try:- body = apply_llm_request_middleware(body, **context).payload+ changed = apply_llm_request_middleware(body, **context).payloadexcept Exception as error:raise warm.WarmRefusal("middleware_refused") from error- if not isinstance(body, dict):+ if not isinstance(changed, dict) or not isinstance(changed.get("messages"), list):raise warm.WarmRefusal("middleware_refused")+ # The captured part went through the request middleware already. A middleware that changes it again (for+ # example, adds a system row) would apply twice and change the cached prefix. It can change the new rows.+ if ({k: v for k, v in changed.items() if k != "messages"} != {k: v for k, v in body.items() if k != "messages"}+ or changed["messages"][:captured] != body["messages"][:captured]):+ raise warm.WarmRefusal("middleware_rewrite")+ body = changed# A copy that no middleware can change in place.base = copy.deepcopy(body)sent: list[tuple[dict[str, Any], dict[str, Any]]] = []+ repeated: list[bool] = []def terminal(request: Any) -> dict[str, Any]:# The capture keeps the body before the execution middleware. An execution middleware that rewrites# this request can also have rewritten the captured request, so the warm request is not sent.if request != base:raise warm.WarmRefusal("middleware_rewrite")+ if sent:+ # One request only: a middleware that calls next_call again does not send it again, and the+ # attempt stops even when the middleware catches this refusal.+ repeated.append(True)+ raise warm.WarmRefusal("middleware_repeated")result = warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post)sent.append((result, dict(result)))return result@@ -264,6 +275,8 @@ class WarmCompactionEngine(ContextEngine):raiseexcept Exception as error:raise warm.WarmRefusal("middleware_refused") from error+ if repeated:+ raise warm.WarmRefusal("middleware_repeated")# Only the reply of this request: a middleware that skipped the request or changed its reply stops it.if not sent or reply is not sent[0][0] or reply != sent[0][1]:raise warm.WarmRefusal("middleware_changed_reply")diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 40a5643..929db15 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -170,10 +170,28 @@ def needs_reasoning_echo(body: dict[str, Any], rows: list) -> bool:attr(row, "role") == "assistant" and isinstance(attr(row, "reasoning_content"), str) for row in rows)-def wire_row(row: Any, reasoning_echo: bool = False) -> dict[str, Any]:+def _model_consumes_thought_signature(model: Any) -> bool:+ """Hermes 45871e10 (agent.transports.chat_completions): Gemini and Gemma models need the tool-call+ extra_content replayed; other providers reject it."""+ name = str(model or "").lower()+ return "gemini" in name or "gemma" in name+++def _signature(extra: Any) -> Any:+ """Return the tool-call extra_content when it has a usable thought signature, else None."""+ if not isinstance(extra, dict):+ return None+ candidate = extra.get("thought_signature")+ google = extra.get("google")+ if candidate is None and isinstance(google, dict):+ candidate = google.get("thought_signature")+ return copy.deepcopy(extra) if isinstance(candidate, str) and candidate.strip() else None+++def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None) -> dict[str, Any]:"""Return the wire form of a stored row, as Hermes sends it: only the fields that the API reads, the- api_content sidecar of a user or assistant row in place of its content, and reasoning_content on an assistant- row when the route needs it."""+ api_content sidecar of a user or assistant row in place of its content, reasoning_content on an assistant+ row when the route needs it, and the thought signature (extra_content) of a tool call for a Gemini model."""wire: dict[str, Any] = {"role": attr(row, "role"), "content": copy.deepcopy(api_content(row))}for key in ("tool_call_id", "name"):value = attr(row, key)@@ -189,6 +207,13 @@ def wire_row(row: Any, reasoning_echo: bool = False) -> dict[str, Any]:}}for call_id, name, arguments in calls]+ consumes = hermes_value("agent.transports.chat_completions", "_model_consumes_thought_signature",+ _model_consumes_thought_signature)(model)+ stored = attr(row, "tool_calls") or []+ for call, source in zip(wire["tool_calls"], stored):+ extra = _signature(attr(source, "extra_content")) if consumes else None+ if extra is not None:+ call["extra_content"] = extraif isinstance(row, dict):policy = hermes_value("agent.message_sanitization", "apply_reasoning_content_policy", _reasoning_policy)policy(row, wire, reasoning_echo)@@ -229,8 +254,8 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, contextrequest = dict(body)# Send the trailing user rows too: the tail can keep only the newest of them, and compaction removes the others.echo = needs_reasoning_echo(body, new_rows)- request["messages"] = [*body["messages"], *(wire_row(row, echo) for row in (*new_rows, *trailing)),- {"role": "user", "content": instruction}]+ added = [wire_row(row, echo, body.get("model")) for row in (*new_rows, *trailing)]+ request["messages"] = [*body["messages"], *added, {"role": "user", "content": instruction}]request["stream"] = Falserequest.pop("stream_options", None)if not fits(request, context_length, capture.get("prompt_tokens"), len(body["messages"])):