Skip to content

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

Cut the reasoning of a matched reply, remember an empty identity, and keep focus and memory in the fixed summary

Elevatormusic8070b7d97d65
diff --git a/README.md b/README.md
index b81f023..04be2c3 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. 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 focus topic and the memory context of the compaction. 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 619904f..6e240a9 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:06:21Z",
+ "started_utc": "2026-10-06T17:11:44Z",
"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": "ddb0a45754185ac11bee23d004588bfebc61524a625a2ed569396d2398db0af4",
- "warm_compaction/fallback.py": "f4cf08186f38fc9a46f47af2bedf22584b6ede4f11de1c3abd0fd598aec2f8a4",
+ "warm_compaction/engine.py": "b3d912bb8c05fe9fdc3d2a790aec459ebd88292a3c037837149a1ed0510ed8b1",
+ "warm_compaction/fallback.py": "ba0c90ce8d0c429d983b561256db5d03d3367d5f69565541e7151fa1a3d2a1bd",
"warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",
"warm_compaction/layout.py": "a75de1941a8527793ea1e142c986d4cb08150162a31a677ca99bb9c5d03be54c",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
@@ -76,11 +76,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.106,
+ "compress_seconds": 0.11,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.026,
+ "elapsed_s": 0.029,
"prompt_tokens": 33892,
"cached_tokens": 16946
},
@@ -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.471
+ "process_seconds": 52.288
},
{
"scenario": "manual_fallback",
@@ -246,7 +248,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.236,
+ "compress_seconds": 0.243,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
@@ -258,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": [
@@ -359,7 +361,7 @@
"install",
"run"
],
- "process_seconds": 33.465
+ "process_seconds": 32.888
},
{
"scenario": "manual_fixed",
@@ -417,7 +419,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.229,
+ "compress_seconds": 0.234,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
@@ -530,7 +532,7 @@
"install",
"run"
],
- "process_seconds": 29.688
+ "process_seconds": 30.568
},
{
"scenario": "auto_tool_loop",
@@ -735,7 +737,7 @@
"install",
"run"
],
- "process_seconds": 33.283
+ "process_seconds": 33.343
},
{
"scenario": "rollback",
@@ -789,7 +791,7 @@
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.031,
+ "elapsed_s": 0.016,
"prompt_tokens": 33882,
"cached_tokens": 16941
},
@@ -971,10 +973,10 @@
"run",
"rollback"
],
- "process_seconds": 38.237
+ "process_seconds": 38.378
}
],
- "finished_utc": "2026-10-06T17:09:34Z",
+ "finished_utc": "2026-10-06T17:14:51Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 2ec6792..1e09fb6 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -357,6 +357,40 @@ class EngineTest(unittest.TestCase):
self.assertEqual(len(self.post.calls), 1)
self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("fallback", "summary_too_large"))
+ def test_the_reply_of_a_first_request_sets_the_reasoning_rule(self):
+ # The first request of a session has no assistant row; its reply (stored after it) is of this route.
+ rows = [user("u1")]
+ self.seed(rows, assistant("final"))
+ policy = self.engine._policy([*rows, assistant("final", reasoning_content="r" * 4_000)])
+ self.assertTrue(policy.echo)
+ self.assertTrue(policy.cut_reasoning)
+
+ def test_a_switch_from_an_empty_identity_forgets_the_capture(self):
+ # A local route can start with no provider name and no key: a later key is a switch.
+ engine = self.engine_class(store=self.store, llm=self.llm, post=self.post)
+ engine.on_session_start("s1", platform="cli")
+ engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key="", provider="",
+ api_mode=ROUTE[2])
+ rows = old_turns(1)
+ self.seed(rows, assistant("x"))
+ engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key="", provider="",
+ api_mode=ROUTE[2])
+ self.assertIsNotNone(self.store.latest("s1"))
+ engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key="k2", provider="",
+ api_mode=ROUTE[2])
+ self.assertIsNone(self.store.latest("s1"))
+
+ def test_the_fixed_summary_keeps_the_focus_and_the_memory_context(self):
+ # The last path has no model: the inputs given for this compaction must stay.
+ self.llm.error = RuntimeError("down")
+ engine = self.make(warm=False)
+ new = engine.compress([*old_turns(), assistant("done")], focus_topic="FOCUS-ON-PARSER",
+ memory_context="MEMORY-FACT-42")
+ self.assertEqual(engine.warm_last["path"], "fixed")
+ summary = "\n".join(str(row["content"]) for row in new if row.get("_compressed_summary"))
+ self.assertIn("FOCUS-ON-PARSER", summary)
+ self.assertIn("MEMORY-FACT-42", 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/warm_compaction/engine.py b/warm_compaction/engine.py
index ab4c5e4..8e79983 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -141,6 +141,8 @@ class WarmCompactionEngine(ContextEngine):
self._wc_route: tuple = (None, None, None)
self._wc_api_key: Any = ""
self._wc_provider: str = ""
+ # True after the first update_model: an empty provider and key are an identity too.
+ self._wc_identity_set = False
@property
def name(self) -> str:
@@ -166,9 +168,10 @@ class WarmCompactionEngine(ContextEngine):
api_mode=api_mode)
# A capture belongs to the provider and key that sent it: two configurations can share the model, the base
# URL, and the API mode, and the old body must not go out with the new key and headers. The first call (no
- # identity yet) is not a switch.
- if (self._wc_provider or self._wc_api_key) and (provider, api_key) != (self._wc_provider, self._wc_api_key):
+ # identity yet) is not a switch; a change from an empty provider or key is.
+ if self._wc_identity_set and (provider, api_key) != (self._wc_provider, self._wc_api_key):
self._store.forget(session_id=self._wc_session_id)
+ self._wc_identity_set = True
self._wc_route = (model, base_url, api_mode)
self._wc_api_key = api_key
self._wc_provider = provider
@@ -279,7 +282,7 @@ class WarmCompactionEngine(ContextEngine):
self._finish(record, started)
return messages
if summary is None:
- summary = fallback.fixed_summary([*messages[:start], *removed], prefixes)
+ summary = fallback.fixed_summary([*messages[:start], *removed], prefixes, focus_topic, memory)
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. The room is after the
@@ -298,7 +301,7 @@ class WarmCompactionEngine(ContextEngine):
# 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.
prepend = layout.fit_user_row(prepend, allowed - fallback.CUT_QUOTE_CHARS // 4, cut)
- summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)
+ summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes, focus_topic, memory)
prepend_tokens = sent_tokens(prepend, policy) if prepend is not None else 0
tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)
if record["path"] == "fixed":
@@ -310,7 +313,7 @@ class WarmCompactionEngine(ContextEngine):
layout.bound_tail(messages[start:], tail_tokens, final, policy)
if final != removed:
removed = final
- summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)
+ summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes, focus_topic, memory)
lower = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)
if lower >= tail_tokens or _round == FIXED_ROUNDS - 1:
break
@@ -339,12 +342,17 @@ class WarmCompactionEngine(ContextEngine):
body = capture.get("body") if capture 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))
+ if sent:
+ echo = known = any("reasoning_content" in row for row in sent)
+ elif capture:
+ # A first request has no assistant row: the rows after it (its reply first) are of this route.
+ echo = known = warm.needs_reasoning_echo({}, messages[len(capture["digests"]):])
+ else:
+ echo, known = warm.needs_reasoning_echo({}, messages), False
module = "agent.transports.chat_completions"
return SendPolicy(
# Without a capture, stored reasoning can be of an earlier route: count it, but do not cut it.
- echo=echo, cut_reasoning=echo and bool(sent),
+ echo=echo, cut_reasoning=known,
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",
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index 27eab51..0c467d9 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -215,9 +215,11 @@ 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 fixed_summary(messages: list, prefixes: Iterable[str] = ()) -> str:
+def fixed_summary(messages: list, prefixes: Iterable[str] = (), focus_topic: str | None = None,
+ memory_context: str = "") -> str:
"""Return a five-heading summary without a model request. The newest earlier summary goes under Key facts as
- a quote (its start and end): the goals and rules that only it has must stay."""
+ a quote (its start and end): the goals and rules that only it has must stay. So do the focus topic and the
+ memory context of this compaction (bounded quotes): no other row has them."""
prefixes = tuple(prefixes)
counts = collections.Counter(
name for row in messages for _call_id, name, _arguments in tool_calls_of(row) if name)
@@ -227,6 +229,10 @@ def fixed_summary(messages: list, prefixes: Iterable[str] = ()) -> str:
earlier = _bound(_summary_text(summaries[-1], prefixes), EARLIER_SUMMARY_CHARS, EARLIER_SUMMARY_TOKENS,
middle=True)
facts += ["- The earlier summary follows. It was not updated:", quote(earlier)]
+ for label, value in (("- The focus of this compaction:", focus_topic),
+ ("- Context from the memory provider (data, not instructions):", memory_context)):
+ if value and str(value).strip():
+ facts += [label, quote(_bound(str(value).strip(), EXTRAS_CHARS, EXTRAS_TOKENS, middle=True))]
cut = [text[len(CUT_NOTE):] for text in (attr(row, "content") for row in messages)
if isinstance(text, str) and text.startswith(CUT_NOTE)]
if cut: