Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Refuse a warm summary above the room, compare tool-call types, and send the warm request at most once
Elevatormusicc61c980dd513
diff --git a/README.md b/README.mdindex 9dcfc4b..b81f023 100644--- a/README.md+++ b/README.md@@ -201,7 +201,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and- A provider or API key switch forgets the capture of the session: the next compaction uses the fallback summary (`no_capture`) until a main request on the new configuration completes.- A captured row with a field that Hermes does not send for the stored row (other than the prompt caching marker `cache_control`) refuses the warm path (`source_transform_unsupported`).- The handoff must start with `## Goal`: text before the first heading is refused (`gate:heading_preamble`).-- The verbatim tail keeps the newest rows that fit in `tail_tokens`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. It stops at the first older row that does not fit, and that row goes into the summary. When the newest unit alone is larger than the tail or the free room, its largest sent payloads keep only their start and end: message text, tool call arguments (kept as a JSON object), and reasoning text. A large image or other media part is replaced by its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. If the cuts are not enough, the payloads are dropped, largest first; only the row structure stays. Signed `reasoning_details` stay as they are. The fallback summary gets the cut middles, and the fixed summary quotes them (at most 8,000 characters), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. Reasoning is cut only when a capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model or into the fixed summary. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. Without a usable capture (after a restart, after a model change, or when a middleware changed the captured rows), the request overhead is unknown: the summary has no copied user messages, the tail takes at most half of the free room, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.+- The verbatim tail keeps the newest rows that fit in `tail_tokens`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. It stops at the first older row that does not fit, and that row goes into the summary. When the newest unit alone is larger than the tail or the free room, its largest sent payloads keep only their start and end: message text, tool call arguments (kept as a JSON object), and reasoning text. A large image or other media part is replaced by its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. If the cuts are not enough, the payloads are dropped, largest first; only the row structure stays. Signed `reasoning_details` stay as they are. The fallback summary gets the cut middles, and the fixed summary quotes them (at most 8,000 characters), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model or into the fixed summary. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. Without a usable capture (after a restart, after a model change, or when a middleware changed the captured rows), the request overhead is unknown: the summary has no copied user messages, the tail takes at most half of the free room, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.- The warm request is not streamed and not retried. Its time limit is 120 seconds. The fallback request also has a 120-second limit.- A request with `extra_headers` or `extra_query`, `n` above 1, a forced `tool_choice`, `response_format`, or audio settings uses the fallback (`settings_unsupported`).- After `/compress`, Hermes builds the system prompt again from its configuration. A system message that a host gave in code is not kept. This is Hermes behavior, and it is the same for the built-in compressor.diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex 22bee7c..619904f 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-06T16:53:19Z",+ "started_utc": "2026-10-06T17:06:21Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,13 +10,13 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "03abb0768293540a566c377e69b8f2749800cbc7ce41054a19ceb1ec79e98f24",+ "warm_compaction/engine.py": "ddb0a45754185ac11bee23d004588bfebc61524a625a2ed569396d2398db0af4","warm_compaction/fallback.py": "f4cf08186f38fc9a46f47af2bedf22584b6ede4f11de1c3abd0fd598aec2f8a4","warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2","warm_compaction/layout.py": "a75de1941a8527793ea1e142c986d4cb08150162a31a677ca99bb9c5d03be54c","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "acba1ae0bed41c38041d1149f825a5f2c6552d2dd20549266bd2c11f1da4ba50",- "warm_compaction/warm.py": "fe1f1b2e065f7198586979455ab54ed7dfd20d144b3751c3451d3cf6a70480e4"+ "warm_compaction/warm.py": "657dd7d496e7cf64190a21a920c202a3aea2ab3cf06eb045c05b22ae25969d10"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text","scenarios": [@@ -76,11 +76,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.099,+ "compress_seconds": 0.106,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.023,+ "elapsed_s": 0.026,"prompt_tokens": 33892,"cached_tokens": 16946},@@ -88,11 +88,10 @@"final_session_id": "wc-enable_manual_warm","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,- "network_host_blocked": 1+ "network_host_blocked": 1,+ "child_process_blocked": 3},"fence_blocked_programs": [- "git","pip","python","python3"@@ -101,7 +100,6 @@"hermes-assets.nousresearch.com"],"fence_blocked_callers": [- "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"@@ -189,7 +187,7 @@"install","run"],- "process_seconds": 54.429+ "process_seconds": 58.471},{"scenario": "manual_fallback",@@ -252,7 +250,7 @@"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.11,"prompt_tokens": null,"cached_tokens": null},@@ -361,7 +359,7 @@"install","run"],- "process_seconds": 33.077+ "process_seconds": 33.465},{"scenario": "manual_fixed",@@ -419,11 +417,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.231,+ "compress_seconds": 0.229,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.11,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -431,7 +429,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": [@@ -532,7 +530,7 @@"install","run"],- "process_seconds": 30.113+ "process_seconds": 29.688},{"scenario": "auto_tool_loop",@@ -627,14 +625,14 @@"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.015,"prompt_tokens": 19504,"cached_tokens": 9752},"compression_count": 2,"fence_denied": {- "network_host_blocked": 1,- "child_process_blocked": 7+ "child_process_blocked": 8,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -648,6 +646,7 @@"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"@@ -736,7 +735,7 @@"install","run"],- "process_seconds": 33.11+ "process_seconds": 33.283},{"scenario": "rollback",@@ -786,11 +785,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.142,+ "compress_seconds": 0.18,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.031,"prompt_tokens": 33882,"cached_tokens": 16941},@@ -972,10 +971,10 @@"run","rollback"],- "process_seconds": 37.884+ "process_seconds": 38.237}],- "finished_utc": "2026-10-06T16:56:28Z",+ "finished_utc": "2026-10-06T17:09:34Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 3f50595..2ec6792 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -319,6 +319,54 @@ class EngineTest(unittest.TestCase):self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),("fallback", "middleware_repeated"))+ def test_a_retry_after_a_failed_send_does_not_send_again(self):+ # A timeout can come after the provider got the request: a retry middleware must not send it again.+ attempts = []++ def post(url, data, headers, timeout_s):+ attempts.append(url)+ raise TimeoutError("read timed out")++ def retry(request=None, next_call=None, **context):+ try:+ return next_call()+ except Exception:+ return next_call()+ self.post = post+ engine = self.make()+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(retry)+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ engine.compress([*rows, reply])+ self.assertEqual(len(attempts), 1)+ self.assertEqual(engine.warm_last["path"], "fallback")++ def test_a_warm_summary_above_the_room_goes_to_the_fallback(self):+ # A dense handoff can pass the byte gate and still not fit below a low threshold: the next request would+ # compact again at once.+ dense = HEADINGS_TEXT.replace("Finish the test task.", "\u76ee\u6807" * 3_000)+ self.post = fake_post(content=dense)+ engine = self.make(threshold=0.10)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ rows = old_turns(8)+ reply = assistant("final")+ self.seed(rows, reply)+ engine.compress([*rows, reply])+ self.assertEqual(len(self.post.calls), 1)+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("fallback", "summary_too_large"))++ def test_an_unusable_capture_does_not_set_the_reasoning_rule(self):+ # The capture is of this route, but its rows are not the stored rows: it does not show what the next+ # request replays. The stored rows with reasoning_content do.+ rows = old_turns(2)+ self.seed(rows, assistant("x"))+ changed = [user("other"), assistant("a", reasoning_content="r" * 4_000), user("next")]+ policy = self.engine._policy(changed)+ self.assertTrue(policy.echo)+ self.assertFalse(policy.cut_reasoning)+def test_capacity_is_checked_again_after_the_request_middleware(self):def expand(request=None, **context):request["messages"][-2]["content"] += " " + "context " * 200_000diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 2546347..c4f5462 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -284,6 +284,17 @@ class BuildRequestTest(unittest.TestCase):self.build(capture)self.assertEqual(caught.exception.code, "source_transform_unsupported")+ def test_refuses_a_changed_tool_call_type(self):+ # The same keys with another type value: the provider reads another kind of call than the stored one.+ self.rows = [user("u1"), assistant("", [("c0", "read", "{}")]), tool("c0", "r0"), user("u2")]+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]+ capture = capture_for(self.rows, self.reply)+ capture["body"]["messages"][2]["tool_calls"][0]["type"] = "custom"+ with self.assertRaises(WarmRefusal) as caught:+ self.build(capture)+ self.assertEqual(caught.exception.code, "source_transform_unsupported")+ self.build(capture_for(self.rows, self.reply))+def test_refuses_a_sent_row_with_an_extra_field(self):# A field that the stored row does not give (a provider control, for example) changes what the model reads.for index, field in ((1, {"recipient": "x"}), (-1, {"prefix": True})):diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 1d6c75e..ab4c5e4 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -247,6 +247,12 @@ class WarmCompactionEngine(ContextEngine):record: dict[str, Any] = {"path": None, "reason": None, "elapsed_s": None, "prompt_tokens": None,"cached_tokens": None}summary = self._warm_summary(messages, capture, focus_topic, memory, prefixes, record, attempt)+ if summary is not None and not self._summary_fits(summary, overhead, reserve):+ # A dense handoff can pass the byte gate and still not fit below the threshold: the next request would+ # compact again at once. The fallback summary has a smaller limit.+ logger.warning("warm_compaction: the warm summary does not fit in the room; fallback used")+ record.update(path=None, reason="summary_too_large")+ summary = None# The middles that the tail cuts (see layout.bound_tail): the rows before the tail do not have them.removed: list = []if summary is None and not self._cancelled() and self._attempt() == attempt:@@ -328,8 +334,9 @@ class WarmCompactionEngine(ContextEngine):the tool-call thought signature for a model that reads it, and reasoning_content on a route that needs itback. Hermes does not give that last rule to a context engine: a capture of this route shows it (Hermessends the field on every assistant row, or on none); without one, a stored row that has the field."""- capture = self._store.latest(self._wc_session_id)- body = capture.get("body") if capture and tuple(capture.get("route") or ()) == tuple(self._wc_route) else None+ # Only a usable capture (_budget_capture: this route, and the stored rows) shows what the route sends.+ capture = self._budget_capture(self._store.latest(self._wc_session_id), messages)+ body = capture.get("body") if capture else Nonesent = [row for row in (body.get("messages") or []) if isinstance(row, dict) and row.get("role") == "assistant"] if isinstance(body, dict) else []echo = (any("reasoning_content" in row for row in sent) if sent@@ -421,6 +428,7 @@ class WarmCompactionEngine(ContextEngine):# A copy that no middleware can change in place.base = copy.deepcopy(body)sent: list[tuple[dict[str, Any], dict[str, Any]]] = []+ started: list[bool] = []repeated: list[bool] = []def terminal(request: Any) -> dict[str, Any]:@@ -428,9 +436,10 @@ class WarmCompactionEngine(ContextEngine):# 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.+ if started:+ # One request only: a middleware that calls next_call again does not send it again (also after a+ # failed send: the provider can have the request), and the attempt stops even when the middleware+ # catches this refusal.repeated.append(True)raise warm.WarmRefusal("middleware_repeated")# The last check before the provider: an execution middleware can run after the host gave up on the@@ -439,6 +448,7 @@ class WarmCompactionEngine(ContextEngine):raise warm.WarmRefusal("cancelled")if self._attempt() != attempt:raise warm.WarmRefusal("route_changed")+ started.append(True)result = warm.send(base, route[1], api_key, post=self._post, extra_headers=headers, ssl_context=tls)# The send blocks on the network: a switch can occur before it returns.if self._attempt() != attempt:@@ -481,6 +491,15 @@ class WarmCompactionEngine(ContextEngine):return limit - (overhead + estimate_tokens(sent_rows(tail_rows, policy)) + estimate_tokens(summary)+ CARRIER_TOKENS)+ def _summary_fits(self, summary: str, overhead: int | None, reserve: int) -> bool:+ """True when the summary row fits in the free room (as _tail_cap: half of it with an unknown overhead)."""+ free = self._room([], "", overhead or 0, reserve)+ if free is None:+ return True+ if overhead is None:+ free //= 2+ return estimate_tokens(summary) <= free+def _tail_cap(self, summary_tokens: int, overhead: int | None, reserve: int, prepend_tokens: int = 0) -> int:"""The tail budget, and at most the free room for the tail after the overhead, the summary, and theprepended row. With an unknown overhead, the tail takes at most half of that room: the other half is fordiff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex f226cee..519250a 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -162,6 +162,9 @@ def _no_extra_fields(wire: Any, expected: dict[str, Any]) -> bool:if isinstance(call, dict) and (set(call) - set(want) or (isinstance(call.get("function"), dict) and set(call["function"]) - set(want.get("function") or {}))):return False+ # The same keys with another type value: the provider reads another kind of call.+ if isinstance(call, dict) and "type" in call and call["type"] != want.get("type"):+ return Falsereturn True