Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Fit the whole quote block, check the window in the attempt, and keep signed Gemini calls whole
Elevatormusic9205d3d75f1a
diff --git a/README.md b/README.mdindex 29c1640..7cb02fa 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. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. A model or session switch at any time during the compaction discards its result (reason `route_changed`). A change of the provider or the key forgets the capture, also from an empty provider and key. 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 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. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. 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 fb8cf59..68dbfd9 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-06T18:07:55Z",+ "started_utc": "2026-10-06T18:22:56Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,10 +10,10 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "381dde42592b0e0f5a37c1a18ac9d19053eb0efda0901b984a3923f9bcfec14f",- "warm_compaction/fallback.py": "da48630977e42366090a203ca80937dfd83c617720b4dcba36ef2bf1fff44976",+ "warm_compaction/engine.py": "250f54624a6ca983c38221ce22acb223b5f3ba906081aa0ca17d59c149a24cc2",+ "warm_compaction/fallback.py": "f62143b7576fdaeb1ffda9d871fc0bf062b536a817f89841f6722d9a7ce9db07","warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",- "warm_compaction/layout.py": "88a8b50e59c2f9468e238aea6a6f3dedccd62175c303e5df1a11de43b6d94bd4",+ "warm_compaction/layout.py": "540526e1ece17675138820572187c956474b53a099f3fc3ddd900118b763be9a","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "acba1ae0bed41c38041d1149f825a5f2c6552d2dd20549266bd2c11f1da4ba50","warm_compaction/warm.py": "657dd7d496e7cf64190a21a920c202a3aea2ab3cf06eb045c05b22ae25969d10"@@ -76,11 +76,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.121,+ "compress_seconds": 0.12,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.032,+ "elapsed_s": 0.027,"prompt_tokens": 33892,"cached_tokens": 16946},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 63.904+ "process_seconds": 54.14},{"scenario": "manual_fallback",@@ -248,11 +248,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.279,+ "compress_seconds": 0.24,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.125,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 40.224+ "process_seconds": 33.142},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.298,+ "compress_seconds": 0.237,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.141,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 36.662+ "process_seconds": 30.59},{"scenario": "auto_tool_loop",@@ -620,14 +620,14 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.031,+ "elapsed_s": 0.015,"prompt_tokens": 35209,"cached_tokens": 17604},"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.0,"prompt_tokens": 19504,"cached_tokens": 9752},@@ -737,7 +737,7 @@"install","run"],- "process_seconds": 39.658+ "process_seconds": 33.527},{"scenario": "rollback",@@ -787,11 +787,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.191,+ "compress_seconds": 0.146,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.032,+ "elapsed_s": 0.015,"prompt_tokens": 33882,"cached_tokens": 16941},@@ -973,10 +973,10 @@"run","rollback"],- "process_seconds": 45.41+ "process_seconds": 37.468}],- "finished_utc": "2026-10-06T18:11:41Z",+ "finished_utc": "2026-10-06T18:26:05Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 296a797..09eca88 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -460,6 +460,24 @@ class EngineTest(unittest.TestCase):summary = next(row["content"] for row in new if row.get("_compressed_summary") and row["role"] == "assistant")self.assertLessEqual(estimate_tokens(summary), SUMMARY_RESERVE + 100)+ def test_a_window_change_before_the_result_is_used_discards_it(self):+ # The same route with a smaller window: the result was sized for the old window and threshold.+ from warm_compaction import layout+ engine = self.make(warm=False)+ real = layout.build++ def build(*args, **kwargs):+ engine.update_model(model=ROUTE[0], context_length=32_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ return real(*args, **kwargs)+ layout.build = build+ try:+ history = [*old_turns(), assistant("done")]+ self.assertIs(engine.compress(history), history)+ finally:+ layout.build = real+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("cancelled", "route_changed"))+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.diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex f79338b..57667c7 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -257,6 +257,17 @@ class FixedSummaryTest(unittest.TestCase):self.assertIn("- Tool calls: read x2", text)self.assertIn("- Other tool calls:", text)+ def test_the_cut_quote_block_fits_its_budget_with_its_label(self):+ from warm_compaction.fallback import cut_quote+ from warm_compaction.layout import CUT_NOTE+ from warm_compaction.rows import estimate_tokens+ rows = [user(CUT_NOTE + "m" * 40_000), tool("c1", CUT_NOTE + "t" * 40_000)]+ for budget in (16, 40, 200, 2_000):+ with self.subTest(budget=budget):+ block = cut_quote(rows, budget)+ self.assertLessEqual(estimate_tokens(block), budget)+ self.assertIn("m" * 50, cut_quote(rows, 2_000))+def test_no_tool_calls(self):self.assertIn("- No tool calls.", fixed_summary([user("x")]))diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex 3302d75..af01c2c 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -295,6 +295,20 @@ class BoundTailTest(unittest.TestCase):self.assertLess(len(bounded[1]["reasoning"]), 60_000)self.assertIn("SENT", str(removed))+ def test_a_signed_gemini_tool_call_stays_whole(self):+ # Gemini needs a function call with a thought signature back as it was: its arguments are not cut on a+ # route that sends the signature. On another route the signature is not sent, and the cut is safe.+ from warm_compaction.layout import bound_tail+ from warm_compaction.rows import SendPolicy+ arguments = '{"text": "' + "a" * 40_000 + '"}'+ call = {"id": "c1", "type": "function", "function": {"name": "write", "arguments": arguments},+ "extra_content": {"google": {"thought_signature": "sig"}}}+ rows = [user("go"), {"role": "assistant", "content": "", "tool_calls": [call]}, tool("c1", "ok")]+ kept = bound_tail(rows, 2_000, policy=SendPolicy(signatures=True))+ self.assertEqual(kept[1]["tool_calls"][0], call)+ cut = bound_tail(rows, 2_000, policy=SendPolicy(signatures=False))+ self.assertNotEqual(cut[1]["tool_calls"][0]["function"]["arguments"], arguments)+def test_a_large_assistant_row_is_cut_and_keeps_its_tool_calls(self):from warm_compaction.layout import bound_tailfrom warm_compaction.rows import MIDDLE_MARK, estimate_tokensdiff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 3b1ad76..35ea4bd 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -390,8 +390,10 @@ class WarmCompactionEngine(ContextEngine):request_reserve(budget, int(self.context_length or 0)))def _attempt(self) -> tuple:- """(route, api key, provider, session id) now."""- return tuple(self._wc_route), self._wc_api_key, self._wc_provider, self._wc_session_id+ """(route, api key, provider, session id, window, threshold) now. The result of an attempt is sized for+ the window and threshold: a change of them also stops it."""+ return (tuple(self._wc_route), self._wc_api_key, self._wc_provider, self._wc_session_id,+ int(self.context_length or 0), int(self.threshold_tokens or 0))def _warm_summary(self, messages: list, capture: dict[str, Any] | None, focus_topic: str | None, memory: str,prefixes: tuple[str, ...], record: dict[str, Any], attempt: tuple) -> str | None:@@ -431,7 +433,7 @@ class WarmCompactionEngine(ContextEngine):except Exception as error:raise warm.WarmRefusal("middleware_unavailable") from error# Before any middleware sees the request: a route without its headers does not send it.- route, api_key, provider, session_id = attempt+ route, api_key, provider, session_id = attempt[:4]headers = warm.route_headers(api_key, route[1], provider)tls = warm.route_tls(route[1])context = {"purpose": NAME, "api_request_id": None, "session_id": session_id,diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex f99b6b3..4d78b8b 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -239,16 +239,22 @@ def _tool_lines(counts: collections.Counter, max_tokens: int) -> list[str]:def cut_quote(rows: list, max_tokens: int) -> str:- """The cut middles of rows (after CUT_NOTE) as one labeled block quote in about max_tokens estimated tokens,- each with its start and end. Empty without cut middles or room."""+ """The cut middles of rows (after CUT_NOTE) as one labeled block quote in at most max_tokens estimated+ tokens with its label and quote marks, each with its start and end. Empty without cut middles or room."""texts = [text[len(CUT_NOTE):] for text in (attr(row, "content") for row in rows)if isinstance(text, str) and text.startswith(CUT_NOTE)]- if not texts or max_tokens < MIN_QUOTE_TOKENS:- return ""- each = max_tokens // len(texts)- return "\n".join(["- Parts that the tail cut from the newest rows (their start and end):",- *[quote(_bound(text, max(MIN_PART_CHARS, CUT_QUOTE_CHARS // len(texts)), each, middle=True))- for text in texts]])+ label = "- Parts that the tail cut from the newest rows (their start and end):"+ # The text share: the budget less the label and the quote marks, smaller until the whole block fits.+ share = max_tokens - estimate_tokens(label) - 2 * len(texts)+ while texts and share // len(texts) >= MIN_QUOTE_TOKENS:+ each = share // len(texts)+ block = "\n".join([label, *[quote(_bound(text, max(MIN_PART_CHARS, CUT_QUOTE_CHARS // len(texts)), each,+ middle=True)) for text in texts]])+ size = estimate_tokens(block)+ if size <= max_tokens:+ return block+ share -= size - max_tokens+ return ""def fixed_summary(messages: list, prefixes: Iterable[str] = (), focus_topic: str | None = None,diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex a91054b..360c681 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -9,7 +9,8 @@ from typing import Any, Iterablefrom .handoff import END_MARKER, LEGACY_PREFIXfrom .rows import (api_content, attr, compact_json, cut_bounds, cut_middle, estimate_tokens, hermes_value, plain_text,- SendPolicy, attachment_mark, sent_reasoning_key, sent_tokens, visible_text)+ SendPolicy, attachment_mark, has_thought_signature, sent_reasoning_key, sent_tokens,+ visible_text)HEADER_TEXT = "The summary of the earlier turns follows."COPY_HEADING = "## Copied user messages"@@ -302,6 +303,11 @@ def _tail_parts(row: Any, policy: SendPolicy = SendPolicy()) -> list[tuple[tupleif role == "assistant":for index, call in enumerate(row.get("tool_calls") or ()):function = call.get("function") if isinstance(call, dict) else None+ # Gemini needs a function call with a thought signature back as it was: on a route that sends the+ # signature, its arguments are not a payload.+ if policy.signatures and has_thought_signature(call.get("extra_content") if isinstance(call, dict)+ else None):+ continueif isinstance(function, dict) and function.get("arguments") is not None:arguments = function["arguments"]parts.append((("arguments", index), arguments if isinstance(arguments, str) else compact_json(arguments)))