Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Keep unsent reasoning out of cuts, and estimate rows by the wire_row rules
Elevatormusicb9d89af4612d
diff --git a/README.md b/README.mdindex 9a9497b..1663289 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 a short text. 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: a stored `reasoning` field and row metadata do not count, `reasoning_details` counts only on a route that replays it, a tool call counts only its id, type, name, and arguments, and its thought signature counts only for a Gemini or Gemma model. 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. Reasoning that the route does not send is not cut: it does not go to the fallback model or into the fixed summary. 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 dd78752..b83c13c 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-06T15:38:58Z",+ "started_utc": "2026-10-06T16:12:49Z","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": "b88091a5581a15b1ae034a22e62d468767f0cf8641e22b1c6fb398554a571794",+ "warm_compaction/engine.py": "aa7d4abc93dad256a14ccca91cc4f9498940a8c99149b3d6c5f3ed4c6a41ade5","warm_compaction/fallback.py": "f4cf08186f38fc9a46f47af2bedf22584b6ede4f11de1c3abd0fd598aec2f8a4","warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",- "warm_compaction/layout.py": "e99ccddff875a2e7a093eb4f75c7d3418b93376e39adea76e2974b81fbdabf7d",+ "warm_compaction/layout.py": "21a280ec25c581e732e8d0c528f19b72102d685bd0da91bc622b6e01cd0fbb06","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",- "warm_compaction/rows.py": "d282fb4d40a0e7050183f350f13a0e8b127a5c42d6ccd29fe79975809d466b84",- "warm_compaction/warm.py": "f76aa64c739f8db7e228c25f9f3ee0c7d890c48eea8215f75577a2d6e5f4736b"+ "warm_compaction/rows.py": "1eb0a043c060322769ad0e2533b3f1b30d5258f125502752d18b8a94c1006347",+ "warm_compaction/warm.py": "fe1f1b2e065f7198586979455ab54ed7dfd20d144b3751c3451d3cf6a70480e4"},"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.118,+ "compress_seconds": 0.097,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.031,+ "elapsed_s": 0.025,"prompt_tokens": 33892,"cached_tokens": 16946},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 56.42+ "process_seconds": 56.281},{"scenario": "manual_fallback",@@ -248,11 +248,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.249,+ "compress_seconds": 0.264,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.141,"prompt_tokens": null,"cached_tokens": null},@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 35.621+ "process_seconds": 33.064},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.244,+ "compress_seconds": 0.271,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.141,"prompt_tokens": null,"cached_tokens": null},@@ -431,7 +431,7 @@"final_session_id": "wc-manual_fixed","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 6,"network_host_blocked": 1},"fence_blocked_programs": [@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 31.615+ "process_seconds": 30.49},{"scenario": "auto_tool_loop",@@ -620,14 +620,14 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.015,"prompt_tokens": 35209,"cached_tokens": 17604},"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 19504,"cached_tokens": 9752},@@ -737,7 +737,7 @@"install","run"],- "process_seconds": 34.583+ "process_seconds": 33.176},{"scenario": "rollback",@@ -787,11 +787,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.155,+ "compress_seconds": 0.158,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.015,"prompt_tokens": 33882,"cached_tokens": 16941},@@ -799,7 +799,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": [@@ -950,7 +950,8 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -958,7 +959,9 @@"python","python3"],- "fence_blocked_hosts": []+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ]},"exit": [0,@@ -970,10 +973,10 @@"run","rollback"],- "process_seconds": 38.012+ "process_seconds": 40.153}],- "finished_utc": "2026-10-06T15:42:14Z",+ "finished_utc": "2026-10-06T16:16:02Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex b19bd05..0e53a62 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -723,6 +723,31 @@ class EngineTest(unittest.TestCase):self.assertIsNot(new, history)self.assertLess(len(new), len(history))+ def test_the_copied_messages_are_sized_after_the_tail_cut(self):+ # A huge newest unit fills the room before the cut; after the cut there is room for the copies, which the+ # fixed summary needs (it does not keep the earlier user text).+ self.llm.error = RuntimeError("down")+ rows = [*old_turns(4), user("go")]+ reply = assistant("", [("c1", "read", "{}")])+ self.seed(rows, reply)+ engine = self.make(threshold=0.95, warm=False)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ new = engine.compress([*rows, reply, tool("c1", "t" * 400_000)])+ self.assertEqual(engine.warm_last["path"], "fixed")+ summary = "\n".join(str(row["content"]) for row in new if row.get("_compressed_summary"))+ self.assertIn("ask 0 ", summary)++ def test_unsent_reasoning_does_not_reach_the_fallback_model(self):+ # The route does not send reasoning: the auxiliary model must not get the private reasoning of a cut row.+ rows = [*old_turns(4), user("go"), assistant("c" * 40_000, reasoning="r" * 40_000 + " SECRET " + "r" * 40_000)]+ engine = self.make(threshold=0.95, tail_tokens=2_000, warm=False)+ engine.compress(rows)+ self.assertEqual(engine.warm_last["path"], "fallback")+ sent = json.dumps([call[0] for call in self.llm.calls])+ self.assertNotIn("SECRET", sent)+ self.assertNotIn("r" * 100, sent)+def test_clone_keeps_the_model_thresholds(self):self.engine.model_thresholds = {"fake": 0.25}clone = self.engine.clone_for_agent()diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex 8cb35f0..15392e0 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -195,8 +195,28 @@ class BoundTailTest(unittest.TestCase):self.assertIs(bound_tail(rows[2:], 1_500)[0], rows[2])def test_unsent_reasoning_does_not_move_the_tail(self):+ from warm_compaction.rows import SendPolicyrows = [user("o" * 4_000), assistant("a"), user("q"), assistant("b", reasoning="r" * 40_000)]- self.assertEqual(tail_start(rows, 900, PREFIXES), (2, None))+ self.assertEqual(tail_start(rows, 900, PREFIXES, SendPolicy(echo=False)), (2, None))++ def test_unsent_reasoning_is_not_cut_or_given_back(self):+ # A route that does not send reasoning: the private reasoning must not go to the fallback model or into+ # the fixed summary.+ from warm_compaction.layout import bound_tail+ from warm_compaction.rows import SendPolicy+ for key in ("reasoning", "reasoning_content"):+ with self.subTest(key=key):+ rows = [user("go"), assistant("c" * 20_000, **{key: "r" * 30_000 + " SECRET " + "r" * 30_000})]+ removed = []+ bounded = bound_tail(rows, 2_000, removed, SendPolicy(echo=False))+ self.assertEqual(bounded[1][key], rows[1][key])+ self.assertNotIn("SECRET", str(removed))+ # A route that needs reasoning back sends a stored reasoning field as reasoning_content: it is cut.+ rows = [user("go"), assistant("ok", reasoning="r" * 30_000 + " SENT " + "r" * 30_000)]+ removed = []+ bounded = bound_tail(rows, 2_000, removed, SendPolicy(echo=True))+ self.assertLess(len(bounded[1]["reasoning"]), 60_000)+ self.assertIn("SENT", str(removed))def test_a_large_assistant_row_is_cut_and_keeps_its_tool_calls(self):from warm_compaction.layout import bound_tail@@ -243,9 +263,23 @@ class BoundTailTest(unittest.TestCase):self.assertLessEqual(sum(estimate_tokens(row) for row in bounded), 2_000)text, note = bounded[0]["content"]self.assertTrue(text["text"].startswith("look ") and text["text"].endswith(" end"))- self.assertEqual(note, {"type": "text", "text": "[image_url removed]"})+ self.assertEqual(note, {"type": "text", "text": "[image attachment] (removed)"})self.assertIs(rows[0]["content"][1], image)+ def test_a_removed_media_part_keeps_its_reference(self):+ # A web URL or a file name stays in the tail and in the removed note; a data URL does not.+ from warm_compaction.layout import bound_tail+ url = "https://example.invalid/photo.png?" + "q" * 40_000+ image = {"type": "image_url", "image_url": {"url": url}}+ rows = [user([{"type": "text", "text": "see"}, image]), assistant("ok")]+ removed = []+ bounded = bound_tail(rows, 2_000, removed)+ note = bounded[0]["content"][1]["text"]+ self.assertTrue(note.startswith("[image attachment: https://example.invalid/photo.png?"))+ self.assertLess(len(note), 400)+ self.assertIn("https://example.invalid/photo.png?", removed[0]["content"])+ self.assertLess(len(removed[0]["content"]), 600)+def test_raw_string_parts_and_untyped_text_parts_are_cut_as_text(self):# visible_text reads both shapes as text: the bound cuts them, and does not replace them with a note.from warm_compaction.layout import CUT_NOTE, bound_taildiff --git a/tests/test_wc_rows.py b/tests/test_wc_rows.pyindex 4f7c826..6f8ae38 100644--- a/tests/test_wc_rows.py+++ b/tests/test_wc_rows.py@@ -68,15 +68,23 @@ if __name__ == "__main__":class SentRowsTest(unittest.TestCase):def test_the_estimate_uses_the_fields_that_hermes_sends(self):# wire_row: no stored reasoning field, no metadata, reasoning_details only on a route that replays it.- from warm_compaction.rows import sent_tokens+ from warm_compaction.rows import SendPolicy, sent_tokensbase = {"role": "assistant", "content": "ok"}- small = sent_tokens(base)- self.assertEqual(sent_tokens({**base, "reasoning": "r" * 40_000, "timestamp": "t" * 4_000}), small)+ small = sent_tokens(base, SendPolicy(echo=False))+ quiet = SendPolicy(echo=False)+ self.assertEqual(sent_tokens({**base, "reasoning": "r" * 40_000, "timestamp": "t" * 4_000}, quiet), small)+ # reasoning_content only on a route that needs it back (apply_reasoning_content_policy); there a stored+ # reasoning field without tool calls goes as reasoning_content.+ self.assertEqual(sent_tokens({**base, "reasoning_content": "r" * 4_000}, quiet), small)self.assertGreater(sent_tokens({**base, "reasoning_content": "r" * 4_000}), small + 900)+ self.assertGreater(sent_tokens({**base, "reasoning": "r" * 4_000}), small + 900)details = {**base, "reasoning_details": [{"type": "reasoning.text", "text": "d" * 4_000}]}self.assertGreater(sent_tokens(details), small + 900)from warm_compaction.rows import SendPolicy- self.assertEqual(sent_tokens(details, SendPolicy(details=False)), small)+ self.assertEqual(sent_tokens(details, SendPolicy(details=False, echo=False)), small)+ # The private native-assistant carriers are not replayed (warm._replay_details).+ native = {**base, "reasoning_details": [{"type": "anthropic.native_assistant", "text": "n" * 8_000}]}+ self.assertEqual(sent_tokens(native, SendPolicy(echo=False)), small)def test_the_estimate_uses_the_tool_call_fields_that_hermes_sends(self):# wire_row: id, type, and function name and arguments; the thought signature only for a model that reads it.@@ -91,4 +99,9 @@ class SentRowsTest(unittest.TestCase):self.assertEqual(sent_tokens(noisy, SendPolicy(signatures=False)), small)self.assertGreater(sent_tokens(noisy, SendPolicy(signatures=True)), small + 1_900)self.assertLess(sent_tokens(noisy, SendPolicy(signatures=True)), small + 2_100)+ # extra_content without a usable thought signature is not sent (warm._signature).+ for unsigned in ({"meta": "m" * 8_000}, {"google": {"thought_signature": " "}, "meta": "m" * 8_000}):+ with self.subTest(extra=unsigned):+ row = {**base, "tool_calls": [{**call, "extra_content": unsigned}]}+ self.assertEqual(sent_tokens(row, SendPolicy(signatures=True)), small)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 200876f..9db1896 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -196,7 +196,7 @@ class WarmCompactionEngine(ContextEngine):if self.threshold_tokens <= 0:return False# As Hermes sends the rows: the stored display text of a row with api_content is not in the request.- tokens = estimate_tokens(sent_rows(messages, self._policy()))+ tokens = estimate_tokens(sent_rows(messages, self._policy(messages)))window = int(self.context_length or 0)budget = self._budget_capture(self._store.latest(self._wc_session_id), messages)if budget is not None:@@ -209,7 +209,7 @@ class WarmCompactionEngine(ContextEngine):def has_content_to_compress(self, messages: list) -> bool:start, _prepend = layout.tail_start(messages, self._start_tail(messages, self._store.latest(- self._wc_session_id)), self._prefixes(), self._policy())+ self._wc_session_id)), self._prefixes(), self._policy(messages))return start > 0def on_session_reset(self) -> None:@@ -229,7 +229,7 @@ class WarmCompactionEngine(ContextEngine):"""Replace the rows before the tail with a summary. Keep the history when no row comes before the tail."""started = self._clock()prefixes = self._prefixes()- policy = self._policy()+ policy = self._policy(messages)# The route, key, and session of this attempt. Hermes can switch them while the attempt still runs (it# runs on a pooled thread and can outlive a host timeout); the warm request goes only to this route.attempt = self._attempt()@@ -277,7 +277,7 @@ class WarmCompactionEngine(ContextEngine):record["path"] = "fixed"# The prepended user row must be in the tail: when it does not fit in the room, keep its start and end.# With an unknown overhead, the room is unknown too: the row keeps only its minimum.- room = self._room(messages[start:], summary, overhead or 0, reserve)+ room = self._room(messages[start:], summary, overhead or 0, reserve, policy)cut: list = []if prepend is not None and room is not None:allowed = room if overhead is not None else 0@@ -290,7 +290,6 @@ class WarmCompactionEngine(ContextEngine):# summary as a quote. The room keeps space for that quote.prepend = layout.fit_user_row(prepend, allowed - fallback.CUT_QUOTE_CHARS // 4, cut)summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)- copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead, reserve)prepend_tokens = estimate_tokens(prepend) if prepend is not None else 0tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)if record["path"] == "fixed":@@ -307,6 +306,9 @@ class WarmCompactionEngine(ContextEngine):if lower >= tail_tokens or _round == FIXED_ROUNDS - 1:breaktail_tokens = lower+ # The copies get the room after the tail as build cuts it: the uncut tail can be much larger.+ copy_tokens = 0 if overhead is None else self._copy_tokens(+ layout.bound_tail(messages[start:], tail_tokens, policy=policy), summary, overhead, reserve, policy)new = layout.build(messages, summary, start=start, prepend=prepend, copy_chars=int(self._settings["user_copy_chars"]),header_prefix=hermes_value("agent.context_compressor", "SUMMARY_PREFIX", handoff.LEGACY_PREFIX),@@ -318,11 +320,20 @@ class WarmCompactionEngine(ContextEngine):self._finish(record, started)return new- def _policy(self) -> SendPolicy:+ def _policy(self, messages: list) -> SendPolicy:"""The route-dependent fields that warm.wire_row sends: reasoning_details on a route that replays them,- and the tool-call thought signature for a model that reads it."""+ the tool-call thought signature for a model that reads it, and reasoning_content on a route that needs it+ back. Hermes does not give that last rule to a context engine: a capture of this route shows it (Hermes+ sends 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+ sent = [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+ else warm.needs_reasoning_echo({}, messages))module = "agent.transports.chat_completions"return SendPolicy(+ echo=echo,details=bool(hermes_value(module, "_route_replays_reasoning_details",warm._route_replays_reasoning_details)(self._wc_route[1])),signatures=bool(hermes_value(module, "_model_consumes_thought_signature",@@ -453,7 +464,8 @@ class WarmCompactionEngine(ContextEngine):return tail_budget(int(self._settings["tail_tokens"]), int(self.context_length or 0),int(self.threshold_tokens or 0))- def _room(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0) -> int | None:+ def _room(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0,+ policy: SendPolicy = SendPolicy()) -> int | None:"""Tokens that stay free below the compaction threshold, and below the context window less the replyreserve, after the request overhead (system rows and tool schemas), the tail rows, the summary, and thesummary row headings. None without a threshold."""@@ -462,7 +474,7 @@ class WarmCompactionEngine(ContextEngine):return Nonewindow = int(self.context_length or 0)limit = min(threshold, window - reserve) if window > 0 else threshold- return limit - (overhead + estimate_tokens(sent_rows(tail_rows, self._policy())) + estimate_tokens(summary)+ return limit - (overhead + estimate_tokens(sent_rows(tail_rows, policy)) + estimate_tokens(summary)+ CARRIER_TOKENS)def _tail_cap(self, summary_tokens: int, overhead: int | None, reserve: int, prepend_tokens: int = 0) -> int:@@ -494,11 +506,12 @@ class WarmCompactionEngine(ContextEngine):return Nonereturn capture- def _copy_tokens(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0) -> int:+ def _copy_tokens(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0,+ policy: SendPolicy = SendPolicy()) -> int:"""Token allowance for the copied user messages and the prepended user row: at most the tail size, andthe free room (_room)."""tail = self._tail_tokens()- room = self._room(tail_rows, summary, overhead, reserve)+ room = self._room(tail_rows, summary, overhead, reserve, policy)return tail if room is None else max(0, min(tail, room))def _cancelled(self) -> bool:diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex cdf3c0a..579c5fd 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -8,7 +8,7 @@ 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, sent_tokens, visible_text)+ SendPolicy, attachment_mark, sent_reasoning_key, sent_tokens, visible_text)HEADER_TEXT = "The summary of the earlier turns follows."COPY_HEADING = "## Copied user messages"@@ -240,13 +240,11 @@ def _tail_row(row: Any, marker: str) -> Any:return clean-# The sent text fields of an assistant row that a model can make large: its reasoning.-REASONING_KEYS = ("reasoning_content", "reasoning")---def _tail_parts(row: Any) -> list[tuple[tuple, Any]]:+def _tail_parts(row: Any, policy: SendPolicy = SendPolicy()) -> list[tuple[tuple, Any]]:"""Return the sent payloads of a tail row that a cut can make smaller, as (key, value): the content (text, or- each part of a list), the arguments of each tool call, and the reasoning text of an assistant row."""+ each part of a list), the arguments of each tool call, and the reasoning text that the route sends for an+ assistant row (sent_reasoning_key). Reasoning that the route does not send is not a payload: a cut would give+ it to the fallback model and the fixed summary."""if not isinstance(row, dict):return []role = row.get("role")@@ -269,7 +267,9 @@ def _tail_parts(row: Any) -> list[tuple[tuple, Any]]:if 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)))- parts.extend(((key,), row[key]) for key in REASONING_KEYS if isinstance(row.get(key), str))+ key = sent_reasoning_key(row, policy)+ if key is not None:+ parts.append(((key,), row[key]))return parts@@ -306,7 +306,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, policy: Senbe larger than the tail budget (a large user message, assistant reply, tool call, or tool result). Then thelargest sent payloads (_tail_parts) are cut to their start and end, until the rows fit or no payload has morethan MIN_COPY_CHARS characters. A tool call keeps its id and name, and its arguments stay a JSON object. A- media part (an image, for example) is replaced by a short text. Other rows and fields stay as they are; signed+ media part (an image, for example) is replaced by its attachment mark. Other rows and fields stay as they are; signedreasoning_details stay, because a cut breaks the signature. When the minimum cuts are not enough (a small cap,or many small payloads), the payloads are dropped (DROPPED), largest first. Only the row structure (roles, toolcall ids and names) can then stay above the cap.@@ -322,7 +322,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, policy: Senwhile sum(sent_tokens(row, policy) for row in rows) > tokens:cuttable = []for index, row in enumerate(rows):- for key, value in _tail_parts(row):+ for key, value in _tail_parts(row, policy):value = current.get((index, key), value)if (isinstance(value, str) and len(value) > max(floor, len(DROPPED))) or (key[0] == "media" and (index, key) not in current@@ -336,7 +336,8 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, policy: Sencost, index, key, value = max(cuttable, key=lambda item: (item[0], -item[1]))originals.setdefault((index, key), value)if key[0] == "media":- new_value: Any = {"type": "text", "text": f"[{value.get('type') or 'media'} removed]"}+ # The mark keeps a web URL or a file name (short), not a data URL.+ new_value: Any = {"type": "text", "text": attachment_mark(value) + " (removed)"}elif not floor:limits[(index, key)] = 0new_value = DROPPED@@ -352,7 +353,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, policy: Senfor index, key in sorted(originals, key=lambda item: (item[0], repr(item[1]))):original = originals[(index, key)]if key[0] == "media":- text = f"(a {original.get('type') or 'media'} part was removed)"+ text = f"(removed from the tail: {attachment_mark(original)})"else:first, second = cut_bounds(original, limits[(index, key)])label = {"arguments": "tool call arguments: ", "reasoning_content": "reasoning: ",diff --git a/warm_compaction/rows.py b/warm_compaction/rows.pyindex fe08899..967f7ec 100644--- a/warm_compaction/rows.py+++ b/warm_compaction/rows.py@@ -70,7 +70,9 @@ ATTACHMENT_KINDS = {"image_url": "image", "input_audio": "audio", "file": "file"REFERENCE_CHARS = 200-def _attachment_mark(part: dict) -> str:+def attachment_mark(part: dict) -> str:+ """One short mark for an image, audio, or file part: a web URL or a file name (at most REFERENCE_CHARS+ characters) stays, a data URL does not."""kind = str(part.get("type") or "unknown")label = ATTACHMENT_KINDS.get(kind, kind)body = part.get(kind) if isinstance(part.get(kind), dict) else {}@@ -92,7 +94,7 @@ def visible_text(content: Any) -> str:elif isinstance(part, dict) and isinstance(part.get("text"), str) and part.get("type", "text") == "text":lines.append(part["text"])elif isinstance(part, dict):- lines.append(_attachment_mark(part))+ lines.append(attachment_mark(part))return "\n".join(lines)@@ -104,20 +106,74 @@ SENT_FIELDS = ("role", "content", "name", "tool_call_id", "reasoning_content")class SendPolicy(NamedTuple):- """The route-dependent fields of warm.wire_row: reasoning_details (a route that replays them) and the- tool-call thought signature, extra_content (a model that reads it). The default counts both."""+ """The route-dependent fields of warm.wire_row: reasoning_details (a route that replays them), the tool-call+ thought signature, extra_content (a model that reads it), and reasoning_content (a route that needs it back,+ apply_reasoning_content_policy). The default counts all of them."""details: bool = Truesignatures: bool = True+ echo: bool = True+++def reasoning_policy(source: dict, wire: dict, needs_pad: bool) -> None:+ """The reasoning_content rule of Hermes 45871e10 (agent.message_sanitization.apply_reasoning_content_policy):+ a thinking-mode route (DeepSeek, Kimi, MiMo) needs the field on every assistant row; other routes reject it."""+ if source.get("role") != "assistant":+ return+ if not needs_pad:+ wire.pop("reasoning_content", None)+ return+ existing, reasoning = source.get("reasoning_content"), source.get("reasoning")+ if isinstance(existing, str):+ wire["reasoning_content"] = existing or " "+ elif isinstance(reasoning, str) and reasoning and not source.get("tool_calls"):+ wire["reasoning_content"] = reasoning+ else:+ wire["reasoning_content"] = " "+++def sent_reasoning_key(row: Any, policy: SendPolicy) -> str | None:+ """The stored field that Hermes sends as reasoning_content (reasoning_policy), or None: then the row sends no+ reasoning of its own."""+ if not policy.echo or not isinstance(row, dict) or row.get("role") != "assistant":+ return None+ if isinstance(row.get("reasoning_content"), str):+ return "reasoning_content"+ reasoning = row.get("reasoning")+ return "reasoning" if isinstance(reasoning, str) and reasoning and not row.get("tool_calls") else None+++def has_thought_signature(extra: Any) -> bool:+ """True when a tool-call extra_content has a usable thought signature (Hermes sends only such a value)."""+ if not isinstance(extra, dict):+ return False+ candidate = extra.get("thought_signature")+ google = extra.get("google")+ if candidate is None and isinstance(google, dict):+ candidate = google.get("thought_signature")+ return isinstance(candidate, str) and bool(candidate.strip())+++def replay_details(details: Any) -> list | None:+ """Return reasoning_details without private native-assistant carriers (the profile that reads them is not+ known here), or None when nothing is left. The items are not copied."""+ if not isinstance(details, list):+ return None+ kept = [item for item in details if not (+ isinstance(item, dict) and isinstance(item.get("type"), str) and item["type"].endswith(".native_assistant"))]+ return kept or Nonedef sent_rows(messages: list, policy: SendPolicy = SendPolicy()) -> list:- """Return the rows as Hermes sends them, for an estimate: the fields of warm.wire_row, with the api_content- sidecar in place of the content, and each tool call as id, type, and function name and arguments."""- fields = (*SENT_FIELDS, "reasoning_details") if policy.details else SENT_FIELDS+ """Return the rows as Hermes sends them, for an estimate, by the rules of warm.wire_row: the api_content+ sidecar in place of the content, no name on a tool row, each tool call as id, type, and function name and+ arguments (with a usable thought signature when the model reads it), replayed reasoning_details, and+ reasoning_content by the reasoning policy."""+ reasoning = hermes_value("agent.message_sanitization", "apply_reasoning_content_policy", reasoning_policy)out = []for row in messages:if isinstance(row, dict):- sent = {key: row[key] for key in fields if key in row}+ role = row.get("role")+ sent = {key: row[key] for key in SENT_FIELDS if key in row and not (key == "name" and role == "tool")}sent["content"] = api_content(row)calls = []for (call_id, name, arguments), source in zip(tool_calls_of(row), row.get("tool_calls") or ()):@@ -125,11 +181,16 @@ def sent_rows(messages: list, policy: SendPolicy = SendPolicy()) -> list:arguments if isinstance(arguments, str) else compact_json(arguments if arguments is not None else {}))}}extra = attr(source, "extra_content")- if policy.signatures and isinstance(extra, dict):+ if policy.signatures and has_thought_signature(extra):call["extra_content"] = extracalls.append(call)if calls:sent["tool_calls"] = calls+ if policy.details and role == "assistant":+ details = replay_details(row.get("reasoning_details"))+ if details is not None:+ sent["reasoning_details"] = details+ reasoning(row, sent, policy.echo)out.append(sent)else:out.append(row)diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex eab588c..f226cee 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -13,8 +13,8 @@ import urllib.requestfrom typing import Any, Callablefrom .rows import (- api_content, attr, compact_json, estimate_tokens, hermes_value, plain_text, reply_text, row_digest,- tool_calls_of,+ api_content, attr, compact_json, estimate_tokens, has_thought_signature, hermes_value, plain_text,+ reasoning_policy as _reasoning_policy, replay_details, reply_text, row_digest, tool_calls_of,)DEFAULT_RESERVE = 4096@@ -191,23 +191,6 @@ def check_source(body: dict[str, Any], history_rows: list, base_url: Any = None)raise WarmRefusal("source_transform_unsupported")-def _reasoning_policy(source: dict, wire: dict, needs_pad: bool) -> None:- """The reasoning_content rule of Hermes 45871e10 (agent.message_sanitization.apply_reasoning_content_policy):- a thinking-mode route (DeepSeek, Kimi, MiMo) needs the field on every assistant row; other routes reject it."""- if source.get("role") != "assistant":- return- if not needs_pad:- wire.pop("reasoning_content", None)- return- existing, reasoning = source.get("reasoning_content"), source.get("reasoning")- if isinstance(existing, str):- wire["reasoning_content"] = existing or " "- elif isinstance(reasoning, str) and reasoning and not source.get("tool_calls"):- wire["reasoning_content"] = reasoning- else:- wire["reasoning_content"] = " "--def needs_reasoning_echo(body: dict[str, Any], rows: list) -> bool:"""True when the route needs reasoning_content on assistant rows: Hermes sent it on a captured assistant row,or a new assistant row has it from the provider."""@@ -224,14 +207,8 @@ def _model_consumes_thought_signature(model: Any) -> bool: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+ """Return a copy of the tool-call extra_content when it has a usable thought signature, else None."""+ return copy.deepcopy(extra) if has_thought_signature(extra) else NoneREPLAY_DETAILS_HOSTS = ("openrouter.ai", "nousresearch.com")@@ -264,13 +241,9 @@ def _route_replays_reasoning_details(base_url: Any) -> bool:def _replay_details(details: Any) -> list | None:- """Return reasoning_details without private native-assistant carriers (the profile that reads them is not- known here), or None when nothing is left."""- if not isinstance(details, list):- return None- kept = [copy.deepcopy(item) for item in details if not (- isinstance(item, dict) and isinstance(item.get("type"), str) and item["type"].endswith(".native_assistant"))]- return kept or None+ """A copy of rows.replay_details: reasoning_details without private native-assistant carriers, or None."""+ kept = replay_details(details)+ return copy.deepcopy(kept) if kept is not None else Nonedef wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_url: Any = None) -> dict[str, Any]: