Skip to content

Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix

Bound the tool inventory, keep the fixed budget in the room, and quote the cut request on the fallback path

Elevatormusic4a9188100b70
diff --git a/README.md b/README.md
index 9d7a34a..ceb7148 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 they stay in one budget (4,096 tokens, and at most the free room). 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: 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 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.json
index dd45d26..b7fcc2d 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-06T17:31:33Z",
+ "started_utc": "2026-10-06T17:53:15Z",
"hermes": {
"commit": "45871e100feceb89769536c88e5e6e265226a409",
"clean": true
@@ -10,8 +10,8 @@
"plugin_files_sha256": {
"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",
"warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",
- "warm_compaction/engine.py": "45d15e75267d9dc51d251502181ffaacf0432d0043c6130477324d35780655ee",
- "warm_compaction/fallback.py": "c697a9476018aacf76e21430c4e6c818fed88339a079e5989137391845d91676",
+ "warm_compaction/engine.py": "3e57c909033e7771eab5ca2a56d9632f0148c9bf1534df5ba04e0721d8fd8fce",
+ "warm_compaction/fallback.py": "da48630977e42366090a203ca80937dfd83c617720b4dcba36ef2bf1fff44976",
"warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",
"warm_compaction/layout.py": "88a8b50e59c2f9468e238aea6a6f3dedccd62175c303e5df1a11de43b6d94bd4",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
@@ -76,7 +76,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.104,
+ "compress_seconds": 0.106,
"warm_last": {
"path": "warm",
"reason": "accepted",
@@ -88,10 +88,11 @@
"final_session_id": "wc-enable_manual_warm",
"continuation_keeps_custom_system_text": false,
"fence_denied": {
- "network_host_blocked": 1,
- "child_process_blocked": 3
+ "child_process_blocked": 4,
+ "network_host_blocked": 1
},
"fence_blocked_programs": [
+ "git",
"pip",
"python",
"python3"
@@ -100,6 +101,7 @@
"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"
@@ -187,7 +189,7 @@
"install",
"run"
],
- "process_seconds": 58.623
+ "process_seconds": 56.235
},
{
"scenario": "manual_fallback",
@@ -246,7 +248,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.232,
+ "compress_seconds": 0.254,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
@@ -359,7 +361,7 @@
"install",
"run"
],
- "process_seconds": 32.922
+ "process_seconds": 35.008
},
{
"scenario": "manual_fixed",
@@ -417,11 +419,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.241,
+ "compress_seconds": 0.229,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.109,
+ "elapsed_s": 0.11,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -429,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": [
@@ -530,7 +532,7 @@
"install",
"run"
],
- "process_seconds": 30.203
+ "process_seconds": 32.142
},
{
"scenario": "auto_tool_loop",
@@ -625,14 +627,14 @@
"warm_last_2": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.016,
+ "elapsed_s": 0.0,
"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",
@@ -646,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"
@@ -734,7 +737,7 @@
"install",
"run"
],
- "process_seconds": 33.468
+ "process_seconds": 33.21
},
{
"scenario": "rollback",
@@ -784,7 +787,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.145,
+ "compress_seconds": 0.168,
"warm_last": {
"path": "warm",
"reason": "accepted",
@@ -947,7 +950,8 @@
"stored": 30
},
"fence_denied": {
- "child_process_blocked": 4
+ "child_process_blocked": 5,
+ "network_host_blocked": 1
},
"fence_blocked_programs": [
"git",
@@ -955,7 +959,9 @@
"python",
"python3"
],
- "fence_blocked_hosts": []
+ "fence_blocked_hosts": [
+ "hermes-assets.nousresearch.com"
+ ]
},
"exit": [
0,
@@ -967,10 +973,10 @@
"run",
"rollback"
],
- "process_seconds": 37.858
+ "process_seconds": 38.681
}
],
- "finished_utc": "2026-10-06T17:34:47Z",
+ "finished_utc": "2026-10-06T17:56:31Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 9c46320..5b96d3e 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -423,6 +423,27 @@ class EngineTest(unittest.TestCase):
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("cancelled", "route_changed"))
self.assertEqual(engine.compression_count, 0)
+ def test_the_fixed_budget_is_not_above_a_small_room(self):
+ self.engine._room = lambda *args, **kwargs: 100
+ self.assertEqual(self.engine._fixed_budget(0, 0), 100)
+ self.engine._room = lambda *args, **kwargs: -5
+ self.assertEqual(self.engine._fixed_budget(0, 0), 0)
+
+ def test_the_fallback_summary_gets_the_cut_middle_of_the_prepended_row(self):
+ # The fallback transcript has only the start and end of a long row: the middle that the tail cuts from
+ # the prepended request must stay in the summary (a bounded quote: its start and end).
+ rows = [*old_turns(4), user("BIG start " + "q" * 3_000 + " MID-REQ " + "q" * 37_000 + " big end"),
+ assistant("", [("c1", "read", "{}")]), tool("c1", "r1"), assistant("done")]
+ engine = self.make(threshold=0.95, tail_tokens=2_000, 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)
+ self.assertEqual(engine.warm_last["path"], "fallback")
+ self.assertNotIn("MID-REQ", json.dumps([call[0] for call in self.llm.calls]))
+ prepended = next(row for row in new if str(row.get("content")).startswith("BIG start"))
+ self.assertNotIn("MID-REQ", prepended["content"])
+ self.assertTrue(any("MID-REQ" in str(row.get("content")) for row in new if row.get("_compressed_summary")))
+
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.py
index 75a7604..f79338b 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -247,6 +247,16 @@ class FixedSummaryTest(unittest.TestCase):
for mark in ("OLD-GOAL", "FOCUS-START", "MEMORY-START", "CUT-START"):
self.assertIn(mark, text)
+ def test_many_tool_names_stay_in_the_budget(self):
+ # The tool inventory is in the budget too: the most used names stay, the others become one count.
+ from warm_compaction.rows import estimate_tokens
+ rows = [assistant("", [(f"c{index}", f"synthetic_tool_name_{index:04d}", "{}")]) for index in range(500)]
+ rows.append(assistant("", [("x1", "read", "{}"), ("x2", "read", "{}")]))
+ text = fixed_summary(rows, max_tokens=1_000)
+ self.assertLessEqual(estimate_tokens(text), 1_000)
+ self.assertIn("- Tool calls: read x2", text)
+ self.assertIn("- Other tool calls:", text)
+
def test_no_tool_calls(self):
self.assertIn("- No tool calls.", fixed_summary([user("x")]))
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index aaeb0cf..615345c 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -29,8 +29,6 @@ CARRIER_TOKENS = 500
# Rounds of the fixed path: cut the tail, quote the cut, and size the cap again.
FIXED_ROUNDS = 10
SUMMARY_RESERVE = 2 * fallback.MAX_TOKENS
-# The smallest fixed summary: the headings and short quotes.
-FIXED_MIN_TOKENS = 256
# The largest reply reserve for an unknown reply limit: the Hermes output reserve of a native Gemini route.
UNKNOWN_RESERVE_MAX = 65_536
HERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"
@@ -301,9 +299,16 @@ class WarmCompactionEngine(ContextEngine):
if prepend is not None and room is not None:
allowed = room if overhead is not None else 0
if sent_tokens(prepend, policy) > allowed:
- if record["path"] != "fixed":
- # A model summary had the whole row (in the warm request, or in the fallback transcript).
+ if record["path"] == "warm":
+ # The warm request had the whole row.
prepend = layout.fit_user_row(prepend, allowed)
+ elif record["path"] == "fallback":
+ # The fallback transcript had only the start and end of a long row: the middle that this cut
+ # removes goes after the summary as a quote. The room keeps space for that quote.
+ prepend = layout.fit_user_row(prepend, allowed - fallback.CUT_QUOTE_CHARS // 4, cut)
+ block = fallback.cut_quote(cut, fallback.CUT_QUOTE_CHARS // 4)
+ if block:
+ summary = summary.rstrip() + "\n\n" + block
else:
# The row is not copied and the fixed summary does not have it: its cut middle goes into the
# summary as a quote. The room keeps space for that quote.
@@ -515,13 +520,14 @@ class WarmCompactionEngine(ContextEngine):
def _fixed_budget(self, overhead: int | None, reserve: int) -> int:
"""The token budget of the fixed summary: the summary reserve, and at most the free room (half of it with
- an unknown overhead), but enough for the headings."""
+ an unknown overhead)."""
free = self._room([], "", overhead or 0, reserve)
if free is None:
return SUMMARY_RESERVE
if overhead is None:
free //= 2
- return max(FIXED_MIN_TOKENS, min(SUMMARY_RESERVE, free))
+ # Not above a small room: the headings take less, and the quotes then have no share.
+ return max(0, min(SUMMARY_RESERVE, free))
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)."""
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index 478abe3..f99b6b3 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -87,12 +87,15 @@ def _cut(text: str, limit: int) -> str:
def _bound(text: str, chars: int, tokens: int, middle: bool = False) -> str:
- """Cut the text to at most chars characters and about tokens estimated tokens. A character is at most
- one estimated token, so a cut to tokens characters meets the token limit."""
+ """Cut the text to at most chars characters and at most tokens estimated tokens. The length goes down by
+ the ratio of the estimate to the limit until the text fits (ASCII text has about four characters for each
+ estimated token, CJK text about one)."""
cut = _cut_middle if middle else _cut
- text = cut(text, chars)
- if estimate_tokens(text) > tokens:
- text = cut(text, max(tokens - MARK_TOKENS, 0))
+ text = base = cut(text, chars)
+ limit = len(base)
+ while limit > 0 and estimate_tokens(text) > tokens:
+ limit = min(limit - 1, limit * max(tokens - MARK_TOKENS, 0) // estimate_tokens(text))
+ text = cut(base, max(limit, 0))
return text
@@ -218,6 +221,36 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
return text, tokens if isinstance(tokens, int) and tokens > 0 else None
+def _tool_lines(counts: collections.Counter, max_tokens: int) -> list[str]:
+ """One line for each tool name, in about half of max_tokens: when they do not fit, the most used names stay
+ and one line counts the others."""
+ if not counts:
+ return ["- No tool calls."]
+ ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
+ keep = len(ranked)
+ while True:
+ lines = [f"- Tool calls: {name} x{count}" for name, count in sorted(ranked[:keep])]
+ rest = ranked[keep:]
+ if rest:
+ lines.append(f"- Other tool calls: {len(rest)} names, {sum(count for _name, count in rest)} calls.")
+ if keep == 0 or estimate_tokens("\n".join(lines)) <= max_tokens // 2:
+ return lines
+ keep //= 2
+
+
+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."""
+ 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]])
+
+
def fixed_summary(messages: list, prefixes: Iterable[str] = (), focus_topic: str | None = None,
memory_context: str = "", max_tokens: int = FIXED_TOKENS) -> str:
"""Return a five-heading summary without a model request, in about max_tokens estimated tokens. Its quotes
@@ -227,7 +260,7 @@ def fixed_summary(messages: list, prefixes: Iterable[str] = (), focus_topic: str
prefixes = tuple(prefixes)
counts = collections.Counter(
name for row in messages for _call_id, name, _arguments in tool_calls_of(row) if name)
- tools = [f"- Tool calls: {name} x{count}" for name, count in sorted(counts.items())] or ["- No tool calls."]
+ tools = _tool_lines(counts, max_tokens)
# (label, texts, character limit): in the order of the summary.
items: list[tuple[str, list[str], int]] = []
summaries = [row for row in messages if is_summary(row, prefixes)]