Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Size the tail from the free room, and count only the sent tool-call fields
Elevatormusic2312ebfd1e79
diff --git a/README.md b/README.mdindex 55d94b2..9a9497b 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`. 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. The sizes come from the fields that Hermes sends: a stored `reasoning` field and row metadata do not count, and `reasoning_details` counts only on a route that replays it. 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 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 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 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 14f5d11..dd78752 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:16:24Z",+ "started_utc": "2026-10-06T15:38:58Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,12 +10,12 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "290d49c5c8307703033414475fe6cf0101c5c8581c23d77cd6ba46f5995a2328",+ "warm_compaction/engine.py": "b88091a5581a15b1ae034a22e62d468767f0cf8641e22b1c6fb398554a571794","warm_compaction/fallback.py": "f4cf08186f38fc9a46f47af2bedf22584b6ede4f11de1c3abd0fd598aec2f8a4","warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",- "warm_compaction/layout.py": "6fe5feace2962f1d8af8a4a0dfcd75366aae0bc991e1422b1e0b32951b45ad98",+ "warm_compaction/layout.py": "e99ccddff875a2e7a093eb4f75c7d3418b93376e39adea76e2974b81fbdabf7d","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",- "warm_compaction/rows.py": "8a20a325f18e7cf49f38358c61529fafbae102c1350833ae1033d0274487fc5a",+ "warm_compaction/rows.py": "d282fb4d40a0e7050183f350f13a0e8b127a5c42d6ccd29fe79975809d466b84","warm_compaction/warm.py": "f76aa64c739f8db7e228c25f9f3ee0c7d890c48eea8215f75577a2d6e5f4736b"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text",@@ -76,11 +76,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.105,+ "compress_seconds": 0.118,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.025,+ "elapsed_s": 0.031,"prompt_tokens": 33892,"cached_tokens": 16946},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 55.212+ "process_seconds": 56.42},{"scenario": "manual_fallback",@@ -252,7 +252,7 @@"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.094,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -260,7 +260,7 @@"final_session_id": "wc-manual_fallback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 34.293+ "process_seconds": 35.621},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.245,+ "compress_seconds": 0.244,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.11,+ "elapsed_s": 0.109,"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": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 31.541+ "process_seconds": 31.615},{"scenario": "auto_tool_loop",@@ -627,14 +627,14 @@"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.0,+ "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 +648,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 +737,7 @@"install","run"],- "process_seconds": 38.027+ "process_seconds": 34.583},{"scenario": "rollback",@@ -786,7 +787,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.144,+ "compress_seconds": 0.155,"warm_last": {"path": "warm","reason": "accepted",@@ -969,10 +970,10 @@"run","rollback"],- "process_seconds": 38.51+ "process_seconds": 38.012}],- "finished_utc": "2026-10-06T15:19:41Z",+ "finished_utc": "2026-10-06T15:42:14Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 46f1336..b19bd05 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -64,11 +64,11 @@ class EngineTest(unittest.TestCase):provider="custom", api_mode=ROUTE[2])return engine- def seed(self, rows, reply, session="s1"):+ def seed(self, rows, reply, session="s1", system=SYSTEM, extra=None):"""Run one main-model request through the capture store, in the Hermes order."""self.store.on_pre_api_request(api_request_id="r1", session_id=session, conversation_history=list(rows),model=ROUTE[0], base_url=ROUTE[1], api_mode=ROUTE[2])- self.store.on_llm_execution(request={"model": ROUTE[0], "messages": [SYSTEM, *wire(rows)]},+ self.store.on_llm_execution(request={"model": ROUTE[0], "messages": [system, *wire(rows)], **(extra or {})},next_call=lambda: None, api_request_id="r1")self.store.on_post_api_request(api_request_id="r1", session_id=session,finish_reason="tool_calls" if reply.get("tool_calls") else "stop",@@ -482,6 +482,10 @@ class EngineTest(unittest.TestCase):self.assertEqual(request_reserve({"body": {"messages": [], "max_tokens": 1_000}}, 200_000), 1_000)self.assertEqual(request_reserve({"body": {"messages": [], "max_tokens": 1_000}}), 1_000)self.assertEqual(request_reserve({"body": {"messages": [], "max_completion_tokens": 2_000}}), 2_000)+ # A captured request without a positive limit: the provider default of the next request is unknown too.+ for body in ({"messages": []}, {"messages": [], "max_tokens": 0}, {"messages": [], "max_tokens": None}):+ with self.subTest(body=body):+ self.assertEqual(request_reserve({"body": body}, 200_000), 50_000)def test_request_overhead_comes_from_the_capture(self):from warm_compaction.engine import request_overhead@@ -674,6 +678,51 @@ class EngineTest(unittest.TestCase):api_mode=ROUTE[2], **change)self.assertIsNone(self.store.latest("s1"))+ def test_the_fixed_path_builds_the_tail_at_the_cap_that_the_summary_quotes(self):+ # Each quote makes the summary larger and the cap smaller. When the rounds stop before the cap is stable,+ # the tail must be cut at the cap whose cut the summary quotes, not at a smaller one.+ from warm_compaction import layout+ self.llm.error = RuntimeError("down")+ text = "".join(f"{index:07d}" for index in range(30_000))+ rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]), tool("c1", text)]+ engine = self.make(threshold=0.95, tail_tokens=30_000, warm=False)+ caps = iter(range(30_000, 0, -1_500))+ engine._tail_cap = lambda *args, **kwargs: next(caps)+ cuts, built = [], {}+ real_bound, real_build = layout.bound_tail, layout.build++ def bound(rows, tokens, removed=None, *args, **kwargs):+ if removed is not None:+ cuts.append(tokens)+ return real_bound(rows, tokens, removed, *args, **kwargs)++ def build(*args, **kwargs):+ built.update(kwargs)+ return real_build(*args, **kwargs)+ layout.bound_tail, layout.build = bound, build+ try:+ engine.compress(rows)+ finally:+ layout.bound_tail, layout.build = real_bound, real_build+ self.assertEqual(engine.warm_last["path"], "fixed")+ self.assertEqual(built["tail_tokens"], cuts[-1])++ def test_a_large_captured_overhead_makes_a_short_history_compact(self):+ # The history fits the nominal tail, but the system rows and tool schemas of the captured request leave no+ # room for it and the reply reserve.+ rows = old_turns(4)+ reply = assistant("final")+ engine = self.make(threshold=0.95)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ self.seed(rows, reply, system={"role": "system", "content": "s " * 112_000}, extra={"max_tokens": 4_096})+ history = [*rows, reply]+ self.assertTrue(engine.should_compress_preflight(history))+ self.assertTrue(engine.has_content_to_compress(history))+ new = engine.compress(history)+ self.assertIsNot(new, history)+ self.assertLess(len(new), len(history))+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_rows.py b/tests/test_wc_rows.pyindex 24ed918..4f7c826 100644--- a/tests/test_wc_rows.py+++ b/tests/test_wc_rows.py@@ -75,5 +75,20 @@ class SentRowsTest(unittest.TestCase):self.assertGreater(sent_tokens({**base, "reasoning_content": "r" * 4_000}), small + 900)details = {**base, "reasoning_details": [{"type": "reasoning.text", "text": "d" * 4_000}]}self.assertGreater(sent_tokens(details), small + 900)- self.assertEqual(sent_tokens(details, details=False), small)+ from warm_compaction.rows import SendPolicy+ self.assertEqual(sent_tokens(details, SendPolicy(details=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.+ from warm_compaction.rows import SendPolicy, sent_tokens+ call = {"id": "c1", "type": "function", "function": {"name": "read", "arguments": "{}"}}+ base = {"role": "assistant", "content": "", "tool_calls": [call]}+ small = sent_tokens(base)+ extra = {"google": {"thought_signature": "s" * 8_000}}+ noisy = {**base, "tool_calls": [{**call, "index": 0, "response_meta": "m" * 8_000,+ "function": {**call["function"], "trace": "t" * 8_000},+ "extra_content": extra}]}+ 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)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 8b5f706..200876f 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -11,7 +11,7 @@ from agent.context_engine import ContextEnginefrom . import fallback, handoff, layout, warmfrom .capture import CaptureStore-from .rows import api_content, attr, estimate_tokens, hermes_value, sent_rows+from .rows import SendPolicy, api_content, attr, estimate_tokens, hermes_value, sent_rowslogger = logging.getLogger(__name__)@@ -26,6 +26,8 @@ TAIL_MAX = 25_000CARRIER_TOKENS = 500# The summary size that the tail cap keeps free before the fallback summary is known: two times its reply# limit, because the estimate and the server count do not use the same tokenizer.+# Rounds of the fixed path: cut the tail, quote the cut, and size the cap again.+FIXED_ROUNDS = 10SUMMARY_RESERVE = 2 * fallback.MAX_TOKENS# The largest reply reserve for an unknown reply limit: the Hermes output reserve of a native Gemini route.UNKNOWN_RESERVE_MAX = 65_536@@ -102,12 +104,14 @@ def request_overhead(capture: dict[str, Any] | None, messages: list | None = Nondef request_reserve(capture: dict[str, Any] | None, context_length: int = 0) -> int:- """The reply reserve of the captured request (warm.reply_reserve). Without a captured body, the reply limit- of the next request is unknown (Hermes does not give it to a context engine): a quarter of the window, at most+ """The reply reserve of the captured request (warm.reply_reserve). Without a captured body or a positive+ captured limit, the reply limit of the next request is unknown (Hermes does not give it to a context engine): a quarter of the window, at mostUNKNOWN_RESERVE_MAX, and at least the default."""body = (capture or {}).get("body")- if isinstance(body, dict) and isinstance(body.get("messages"), list):+ if isinstance(body, dict) and isinstance(body.get("messages"), list) and any(+ type(body.get(key)) is int and body[key] > 0 for key in warm.LIMIT_KEYS):return warm.reply_reserve(body)+ # Without a positive captured limit, the provider default applies to the next request: it is unknown too.return max(warm.DEFAULT_RESERVE, min(context_length // 4, UNKNOWN_RESERVE_MAX))@@ -192,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._details()))+ tokens = estimate_tokens(sent_rows(messages, self._policy()))window = int(self.context_length or 0)budget = self._budget_capture(self._store.latest(self._wc_session_id), messages)if budget is not None:@@ -204,7 +208,8 @@ class WarmCompactionEngine(ContextEngine):return tokens >= self.threshold_tokensdef has_content_to_compress(self, messages: list) -> bool:- start, _prepend = layout.tail_start(messages, self._tail_tokens(), self._prefixes(), self._details())+ start, _prepend = layout.tail_start(messages, self._start_tail(messages, self._store.latest(+ self._wc_session_id)), self._prefixes(), self._policy())return start > 0def on_session_reset(self) -> None:@@ -224,13 +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()- details = self._details()- start, prepend = layout.tail_start(messages, self._tail_tokens(), prefixes, details)- if start <= 0:- return messages- memory = sanitize_memory(memory_context)- record: dict[str, Any] = {"path": None, "reason": None, "elapsed_s": None, "prompt_tokens": None,- "cached_tokens": None}+ policy = self._policy()# 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()@@ -240,11 +239,18 @@ class WarmCompactionEngine(ContextEngine):budget = self._budget_capture(capture, messages)overhead = request_overhead(budget, messages)reserve = request_reserve(budget, int(self.context_length or 0))+ start, prepend = layout.tail_start(messages, self._tail_cap(SUMMARY_RESERVE, overhead, reserve), prefixes,+ policy)+ if start <= 0:+ return messages+ memory = sanitize_memory(memory_context)+ 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)# 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:- layout.bound_tail(messages[start:], self._tail_cap(SUMMARY_RESERVE, overhead, reserve), removed, details)+ layout.bound_tail(messages[start:], self._tail_cap(SUMMARY_RESERVE, overhead, reserve), removed, policy)# Only the rows before the tail: the tail stays as it is, and a transcript of the whole history# can spend its budget on the tail.summary, _tokens = fallback.llm_summary(self._llm, [*messages[:start], *removed], prefixes,@@ -288,31 +294,47 @@ class WarmCompactionEngine(ContextEngine):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":- # The fixed summary quotes what the tail cuts: cut and quote at the same (final) cap. A larger summary- # makes a smaller cap; a few rounds reach it.- for _round in range(3):+ # The fixed summary quotes what the tail cuts: cut and quote at the same cap. A larger summary makes a+ # smaller cap, and the cap only goes down. When the rounds stop before the cap is stable, the tail is+ # cut at the cap that the summary quotes: a little above the room, but no cut text is lost.+ for _round in range(FIXED_ROUNDS):final: list = []- layout.bound_tail(messages[start:], tail_tokens, final, details)- if final == removed:+ layout.bound_tail(messages[start:], tail_tokens, final, policy)+ if final != removed:+ removed = final+ summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)+ lower = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)+ if lower >= tail_tokens or _round == FIXED_ROUNDS - 1:break- removed = final- summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)- tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)+ tail_tokens = lowernew = 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),prefixes=prefixes,end_marker=hermes_value("agent.context_compressor", "_SUMMARY_END_MARKER", HERMES_END_MARKER),marker=hermes_value("agent.context_compressor", "_DB_PERSISTED_MARKER", HERMES_DB_MARKER),- copy_tokens=copy_tokens, tail_tokens=tail_tokens, details=details)+ copy_tokens=copy_tokens, tail_tokens=tail_tokens, policy=policy)self.compression_count += 1self._finish(record, started)return new- def _details(self) -> bool:- """True when the route replays reasoning_details (warm.wire_row sends them)."""- return bool(hermes_value("agent.transports.chat_completions", "_route_replays_reasoning_details",- warm._route_replays_reasoning_details)(self._wc_route[1]))+ def _policy(self) -> 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."""+ module = "agent.transports.chat_completions"+ return SendPolicy(+ 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",+ warm._model_consumes_thought_signature)(self._wc_route[0])))++ def _start_tail(self, messages: list, capture: dict[str, Any] | None) -> int:+ """The tail budget for the tail start: the tail setting, and at most the room after the overhead of a+ usable capture, the reply reserve, and a summary (_tail_cap). A large system prompt or tool schema can+ leave no room for a history that fits the tail setting."""+ budget = self._budget_capture(capture, messages)+ return self._tail_cap(SUMMARY_RESERVE, request_overhead(budget, messages),+ request_reserve(budget, int(self.context_length or 0)))def _attempt(self) -> tuple:"""(route, api key, provider, session id) now."""@@ -440,7 +462,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._details())) + estimate_tokens(summary)+ return limit - (overhead + estimate_tokens(sent_rows(tail_rows, self._policy())) + estimate_tokens(summary)+ CARRIER_TOKENS)def _tail_cap(self, summary_tokens: int, overhead: int | None, reserve: int, prepend_tokens: int = 0) -> int:diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex 22999cb..cdf3c0a 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,- sent_tokens, visible_text)+ SendPolicy, sent_tokens, visible_text)HEADER_TEXT = "The summary of the earlier turns follows."COPY_HEADING = "## Copied user messages"@@ -126,7 +126,7 @@ def units(messages: list) -> list[tuple[int, int]]:def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str],- details: bool = True) -> tuple[int, dict[str, Any] | None]:+ policy: SendPolicy = SendPolicy()) -> tuple[int, dict[str, Any] | None]:"""Return the first tail index and, in the middle of a task, a copy of the latest real user row."""prefixes = tuple(prefixes)spans = units(messages)@@ -134,9 +134,9 @@ def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str],return 0, Nonestart = spans[-1][0]# As Hermes sends the rows: the stored display text of a row with api_content is not in the request.- size = sum(sent_tokens(row, details) for row in messages[start:])+ size = sum(sent_tokens(row, policy) for row in messages[start:])for span_start, span_end in reversed(spans[:-1]):- cost = sum(sent_tokens(row, details) for row in messages[span_start:span_end])+ cost = sum(sent_tokens(row, policy) for row in messages[span_start:span_end])if size + cost > tail_tokens:breaksize += cost@@ -301,7 +301,7 @@ def _set_part(row: dict[str, Any], key: tuple, value: Any) -> dict[str, Any]:return new-def bound_tail(rows: list, tokens: int, removed: list | None = None, details: bool = True) -> list:+def bound_tail(rows: list, tokens: int, removed: list | None = None, policy: SendPolicy = SendPolicy()) -> list:"""Return the tail rows in about tokens estimated tokens. The tail keeps whole units, so the newest unit canbe 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 more@@ -319,7 +319,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, details: bolimits: dict[tuple, int] = {}# First the cuts to start and end (at least MIN_COPY_CHARS), then, when they are not enough, the drops.floor = MIN_COPY_CHARS- while sum(sent_tokens(row, details) for row in rows) > tokens:+ while sum(sent_tokens(row, policy) for row in rows) > tokens:cuttable = []for index, row in enumerate(rows):for key, value in _tail_parts(row):@@ -341,7 +341,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, details: bolimits[(index, key)] = 0new_value = DROPPEDelse:- target = cost - (sum(sent_tokens(row, details) for row in rows) - tokens)+ target = cost - (sum(sent_tokens(row, policy) for row in rows) - tokens)limit = max(MIN_COPY_CHARS, min(len(value) - 1, len(value) * max(target, 0) // max(cost, 1)))# Cut the original text again: the kept start and end are then parts of the original text.limits[(index, key)] = limit@@ -367,7 +367,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None, details: bodef build(messages: list, summary_text: str, *, start: int, prepend: dict[str, Any] | None, copy_chars: int,header_prefix: str, prefixes: Iterable[str], end_marker: str,marker: str = "_db_persisted", copy_tokens: int | None = None, tail_tokens: int | None = None,- details: bool = True) -> list | None:+ policy: SendPolicy = SendPolicy()) -> list | None:"""Return the new history, or None when no row comes before the tail. With tail_tokens, a tail above itis cut to it (bound_tail)."""if start <= 0:@@ -386,7 +386,7 @@ def build(messages: list, summary_text: str, *, start: int, prepend: dict[str, Abody = summary_body(summary_text, copies, end_marker)tail = [_tail_row(row, marker) for row in messages[start:]]if tail_tokens is not None:- tail = bound_tail(tail, tail_tokens, details=details)+ tail = bound_tail(tail, tail_tokens, policy=policy)rest = ([copy.deepcopy(prepend)] if prepend else []) + tailif attr(rest[0], "role") != "user":return [{"role": "user", "content": f"{header}\n\n{body}", "_compressed_summary": True}, *rest]diff --git a/warm_compaction/rows.py b/warm_compaction/rows.pyindex 97ba2b2..fe08899 100644--- a/warm_compaction/rows.py+++ b/warm_compaction/rows.py@@ -7,7 +7,7 @@ import importlibimport jsonimport mathimport re-from typing import Any+from typing import Any, NamedTupleTHINK_BLOCK = re.compile(r"\A\s*<think>.*?</think>\s*", re.DOTALL)@@ -100,27 +100,45 @@ MIDDLE_MARK = " [cut] "# The fields of a row that Hermes sends (warm.wire_row): a stored reasoning field and metadata are not sent.-SENT_FIELDS = ("role", "content", "name", "tool_call_id", "tool_calls", "reasoning_content")+SENT_FIELDS = ("role", "content", "name", "tool_call_id", "reasoning_content")-def sent_rows(messages: list, details: bool = True) -> list:+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."""+ details: bool = True+ signatures: bool = True+++def 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. reasoning_details only with details (a route that replays it)."""- fields = (*SENT_FIELDS, "reasoning_details") if details else SENT_FIELDS+ 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_FIELDSout = []for row in messages:if isinstance(row, dict):sent = {key: row[key] for key in fields if key in row}sent["content"] = api_content(row)+ calls = []+ for (call_id, name, arguments), source in zip(tool_calls_of(row), row.get("tool_calls") or ()):+ call = {"id": call_id, "type": "function", "function": {"name": name, "arguments": (+ 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):+ call["extra_content"] = extra+ calls.append(call)+ if calls:+ sent["tool_calls"] = callsout.append(sent)else:out.append(row)return out-def sent_tokens(row: Any, details: bool = True) -> int:+def sent_tokens(row: Any, policy: SendPolicy = SendPolicy()) -> int:"""Estimated tokens of one row as Hermes sends it (sent_rows)."""- return estimate_tokens(sent_rows([row], details)[0])+ return estimate_tokens(sent_rows([row], policy)[0])def cut_bounds(text: str, limit: int) -> tuple[int, int]: