Skip to content

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

Refuse same-line rewrites, drop web search, and tighten the copy budget

Elevatormusic2a43a5b18123
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.json
index a420301..a50d1ff 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-06T11:09:43Z",
+ "started_utc": "2026-10-06T11:27:57Z",
"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": "f33e5f76683e379e164e71d8a68fcdb750811463f5fdb4b73bc71c8077b32263",
+ "warm_compaction/engine.py": "3021157e4bfabcd9dbfc48e42d2702d084a3cf6690ec207a7e87fe9b70137720",
"warm_compaction/fallback.py": "45dffdab8983292f4d6b7e5b7f60b7578078c8b1abb436c0e47acef3b2f77960",
"warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",
"warm_compaction/layout.py": "5e730211647eed0beec1e6819dfc008b0855a0866dc920bb0cf8d6d8ab2dfa92",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
"warm_compaction/rows.py": "cc2a8a3d0561559f24fc40881453441d938ea9d7803e1df81a107a5e05e5f00a",
- "warm_compaction/warm.py": "c651392ce7f01937ebe284bb9d44eacf11c877961b405834b2fe1829a02f673e"
+ "warm_compaction/warm.py": "ff83b4681f52afa9eb82cbdb5893e7165c2f93b2c644c7424aa57ec95ddd9260"
},
"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.114,
+ "compress_seconds": 0.253,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.023,
+ "elapsed_s": 0.139,
"prompt_tokens": 33883,
"cached_tokens": 16941
},
@@ -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.218
+ "process_seconds": 66.713
},
{
"scenario": "manual_fallback",
@@ -246,11 +248,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.214,
+ "compress_seconds": 0.518,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
- "elapsed_s": 0.11,
+ "elapsed_s": 0.328,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -359,7 +361,7 @@
"install",
"run"
],
- "process_seconds": 35.991
+ "process_seconds": 41.703
},
{
"scenario": "manual_fixed",
@@ -417,11 +419,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.269,
+ "compress_seconds": 0.542,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.141,
+ "elapsed_s": 0.312,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -530,7 +532,7 @@
"install",
"run"
],
- "process_seconds": 32.246
+ "process_seconds": 40.152
},
{
"scenario": "auto_tool_loop",
@@ -618,14 +620,14 @@
"warm_last_1": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.031,
+ "elapsed_s": 0.141,
"prompt_tokens": 35201,
"cached_tokens": 17600
},
"warm_last_2": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.015,
+ "elapsed_s": 0.156,
"prompt_tokens": 18427,
"cached_tokens": 9213
},
@@ -735,7 +737,7 @@
"install",
"run"
],
- "process_seconds": 34.006
+ "process_seconds": 46.077
},
{
"scenario": "rollback",
@@ -785,11 +787,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.184,
+ "compress_seconds": 0.269,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.016,
+ "elapsed_s": 0.125,
"prompt_tokens": 33873,
"cached_tokens": 16936
},
@@ -948,8 +950,7 @@
"stored": 30
},
"fence_denied": {
- "child_process_blocked": 5,
- "network_host_blocked": 1
+ "child_process_blocked": 4
},
"fence_blocked_programs": [
"git",
@@ -957,9 +958,7 @@
"python",
"python3"
],
- "fence_blocked_hosts": [
- "hermes-assets.nousresearch.com"
- ]
+ "fence_blocked_hosts": []
},
"exit": [
0,
@@ -971,10 +970,10 @@
"run",
"rollback"
],
- "process_seconds": 44.422
+ "process_seconds": 47.662
}
],
- "finished_utc": "2026-10-06T11:13:08Z",
+ "finished_utc": "2026-10-06T11:31:59Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 6983807..e5e42ad 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -399,6 +399,43 @@ class EngineTest(unittest.TestCase):
self.assertIsNone(request_overhead(None, rows, 10))
self.assertIsNone(request_overhead(None, rows, estimate_tokens(rows)))
+ def test_request_overhead_counts_text_that_a_middleware_added_to_a_captured_row(self):
+ from warm_compaction.engine import request_overhead
+ from warm_compaction.rows import estimate_tokens
+ rows = [user("hi"), assistant("ok")]
+ added = "hi\n\n" + "[recalled] " * 400
+ capture = {"digests": [None, None], "body": {"messages": [SYSTEM, {"role": "user", "content": added},
+ {"role": "assistant", "content": "ok"}]}}
+ base = estimate_tokens({"messages": [SYSTEM], "tools": None})
+ self.assertEqual(request_overhead(capture, rows), base + estimate_tokens(added) - estimate_tokens("hi"))
+ self.assertEqual(request_overhead(capture), base)
+
+ def test_request_reserve_is_the_larger_limit(self):
+ from warm_compaction.engine import request_reserve
+ self.assertEqual(request_reserve({"body": {"messages": [], "max_tokens": 100,
+ "max_completion_tokens": 5_000}}), 5_000)
+
+ def test_a_capture_of_another_route_is_not_used_for_the_copy_budget(self):
+ # After a model change, the old capture says nothing about the system prompt and tools of the new route.
+ from warm_compaction.rows import estimate_tokens
+ rows = old_turns(20)
+ engine = self.make(threshold=0.95, tail_tokens=2_000)
+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",
+ provider="custom", api_mode=ROUTE[2])
+ large = {"role": "system", "content": "s " * 120_000}
+ self.store.on_pre_api_request(api_request_id="r1", session_id="s1", conversation_history=list(rows[:-1]),
+ model=ROUTE[0], base_url=ROUTE[1], api_mode=ROUTE[2])
+ self.store.on_llm_execution(request={"model": ROUTE[0], "messages": [large, *wire(rows[:-1])]},
+ next_call=lambda: None, api_request_id="r1")
+ self.store.on_post_api_request(api_request_id="r1", session_id="s1", finish_reason="stop",
+ assistant_message=reply_object(rows[-1]))
+ engine.update_model(model="another-model", context_length=64_000, base_url=ROUTE[1], api_key="k",
+ provider="custom", api_mode=ROUTE[2])
+ new = engine.compress(rows, current_tokens=estimate_tokens(rows) + 1_000)
+ self.assertEqual(engine.warm_last["reason"], "route_changed")
+ summary = next(row["content"] for row in new if "## Copied user messages" in str(row["content"]))
+ self.assertFalse(summary.split("## Copied user messages", 1)[1].strip().startswith("(none)"))
+
def test_without_a_capture_the_copies_leave_room_for_the_system_prompt_and_tools(self):
# After a restart there is no capture. The system prompt and the tool schemas still take their space.
from warm_compaction.rows import estimate_tokens
diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.py
index 342b0c2..23eecf2 100644
--- a/tests/test_wc_warm.py
+++ b/tests/test_wc_warm.py
@@ -115,6 +115,12 @@ class SettingsTest(unittest.TestCase):
self.assertTrue(fits(body, 300))
self.assertFalse(fits(body, 200))
+ def test_fits_reserves_the_larger_of_the_two_reply_limits(self):
+ body = {"messages": [{"role": "user", "content": "x" * 400}], "max_tokens": 100,
+ "max_completion_tokens": 5_000}
+ self.assertFalse(fits(body, 1_000))
+ self.assertTrue(fits(body, 6_000))
+
def test_fits_uses_the_measured_count_for_the_captured_rows(self):
# The byte estimate of the two captured rows is above 2,000 tokens. The server measured 900.
captured = [{"role": "user", "content": "x" * 4_000}, {"role": "assistant", "content": "y" * 4_000}]
@@ -187,6 +193,11 @@ class BuildRequestTest(unittest.TestCase):
self.assertNotIn("stop", body)
self.assertEqual(body["temperature"], 0.2)
+ def test_web_search_is_not_sent(self):
+ # A web search in the handoff request costs a search and can bring text that is not in the conversation.
+ body = self.build(capture_for(self.rows, self.reply, body_extra={"web_search_options": {}}))
+ self.assertNotIn("web_search_options", body)
+
def test_the_handoff_has_its_own_reply_limit(self):
# The reply limit of the main request is for another task: a small one cuts the handoff, a large one
# reserves space that the handoff does not need.
@@ -272,9 +283,9 @@ class BuildRequestTest(unittest.TestCase):
with self.assertRaises(WarmRefusal) as caught:
self.build(capture)
self.assertEqual(caught.exception.code, "source_transform_unsupported")
- # Text that Hermes adds inside a text run is not a move.
+ # Lines that Hermes adds inside a text run are not a move.
capture = capture_for(self.rows, self.reply)
- capture["body"]["messages"][1]["content"][0]["text"] = "[context] first"
+ capture["body"]["messages"][1]["content"][0]["text"] = "[context]\n\nfirst"
self.build(capture)
def test_the_stored_api_content_is_the_sent_text(self):
@@ -361,6 +372,23 @@ class BuildRequestTest(unittest.TestCase):
sent[-3]["tool_calls"][0]["function"]["arguments"] = "{ \"path\": \"a\" }"
self.assertEqual(self.build(capture)["messages"][: len(sent)], sent)
+ def test_refuses_text_added_on_the_same_line_as_the_stored_text(self):
+ # Hermes adds request-time context as separate lines ("\n\n" + context). Text on the same line can
+ # change the meaning of the stored text ("Delete A" to "Do not Delete A").
+ self.rows = [user("Delete A"), assistant("a1"), user("u2")]
+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]
+ for sent, accepted in (("Do not Delete A", False), ("Delete A now", False), ("Delete A\n\n[context]", True),
+ ("[context]\nDelete A", True), ("[a]\n\nDelete A \n\n[b]", True)):
+ capture = capture_for(self.rows, self.reply)
+ capture["body"]["messages"][1]["content"] = sent
+ with self.subTest(sent=sent):
+ if accepted:
+ self.build(capture)
+ continue
+ with self.assertRaises(WarmRefusal) as caught:
+ self.build(capture)
+ self.assertEqual(caught.exception.code, "source_transform_unsupported")
+
def test_refuses_changed_whitespace_inside_the_text(self):
self.rows = [user("def f():\n return 1"), assistant("a1"), user("u2")]
self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index be70e75..f00a1a5 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -11,7 +11,7 @@ from agent.context_engine import ContextEngine
from . import fallback, handoff, layout, warm
from .capture import CaptureStore
-from .rows import estimate_tokens, hermes_value
+from .rows import api_content, attr, estimate_tokens, hermes_value
logger = logging.getLogger(__name__)
@@ -90,14 +90,18 @@ def request_overhead(capture: dict[str, Any] | None, messages: list | None = Non
overhead = current_tokens - estimate_tokens(messages)
return overhead if overhead > 0 else None
count = max(len(body["messages"]) - len(capture.get("digests") or ()), 0)
- return estimate_tokens({"messages": body["messages"][:count], "tools": body.get("tools")})
+ overhead = estimate_tokens({"messages": body["messages"][:count], "tools": body.get("tools")})
+ if messages is not None:
+ # Request-time text in the captured rows (context that Hermes or a middleware added) comes again with
+ # the next request, so it is overhead too.
+ for wire, row in zip(body["messages"][count:], messages):
+ overhead += max(0, estimate_tokens(attr(wire, "content")) - estimate_tokens(api_content(row)))
+ return overhead
def request_reserve(capture: dict[str, Any] | None) -> int:
- """The reply reserve of the captured request: max_tokens or max_completion_tokens, else the default."""
- body = (capture or {}).get("body")
- value = (body.get("max_tokens") or body.get("max_completion_tokens")) if isinstance(body, dict) else None
- return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else warm.DEFAULT_RESERVE
+ """The reply reserve of the captured request (warm.reply_reserve), else the default."""
+ return warm.reply_reserve((capture or {}).get("body"))
def _int(value: Any) -> int:
@@ -207,10 +211,12 @@ class WarmCompactionEngine(ContextEngine):
if summary is None:
summary = fallback.fixed_summary(messages[:start])
record["path"] = "fixed"
- # An unknown overhead can be most of the window: then no copies.
- overhead = request_overhead(capture, messages, current_tokens)
+ # An unknown overhead can be most of the window: then no copies. A capture of another route says
+ # nothing about the system prompt, the tools, and the reply limit of this one.
+ budget = capture if capture is not None and tuple(capture.get("route") or ()) == tuple(self._wc_route) else None
+ overhead = request_overhead(budget, messages, current_tokens)
copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead,
- request_reserve(capture))
+ request_reserve(budget))
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),
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index 4702b1c..6d4243a 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import collections
import copy
import json
+import re
import time
import urllib.error
import urllib.parse
@@ -126,11 +127,20 @@ def _arguments(value: Any) -> tuple[str, str]:
return "json", json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
+def _in_whole_lines(stored: str, sent: str) -> bool:
+ """True when the stored text is in the sent text as whole lines. Hermes adds request-time context as
+ separate lines ("\n\n" + context); text on the same line can change the meaning ("Delete A" to
+ "Do not Delete A")."""
+ if not stored:
+ return True
+ return re.search(r"(?:^|\n)[ \t]*" + re.escape(stored) + r"[ \t]*(?:\n|$)", sent) is not None
+
+
def _same_row(wire: Any, row: Any) -> bool:
"""True when the sent row carries the stored row: the same shape; the same name (the Hermes transport
removes the name from tool rows only); the same image, audio, and file parts in the same order; each stored
- text run inside the sent text run at the same place (Hermes can add request-time context to a row); and the
- same tool-call arguments. The stored text is the api_content sidecar when the row has one."""
+ text run inside the sent text run at the same place, as whole lines (Hermes can add request-time context to a
+ row); and the same tool-call arguments. The stored text is the api_content sidecar when the row has one."""
if _shape(wire) != _shape(row):
return False
name = attr(wire, "name")
@@ -139,7 +149,7 @@ def _same_row(wire: Any, row: Any) -> bool:
sent_runs, sent_media = _parts(attr(wire, "content"))
stored_runs, stored_media = _parts(api_content(row))
if sent_media != stored_media or not all(
- stored.strip() in sent for stored, sent in zip(stored_runs, sent_runs)):
+ _in_whole_lines(stored.strip(), sent) for stored, sent in zip(stored_runs, sent_runs)):
return False
return [_arguments(arguments) for _id, _name, arguments in tool_calls_of(wire)] == [
_arguments(arguments) for _id, _name, arguments in tool_calls_of(row)]
@@ -273,6 +283,14 @@ def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_url
return wire
+def reply_reserve(body: Any) -> int:
+ """The reply reserve of a request: the larger positive max_tokens or max_completion_tokens (a server can
+ honor either), else DEFAULT_RESERVE."""
+ values = [body.get(key) for key in ("max_tokens", "max_completion_tokens")] if isinstance(body, dict) else []
+ values = [value for value in values if type(value) is int and value > 0]
+ return max(values) if values else DEFAULT_RESERVE
+
+
def fits(body: dict[str, Any], context_length: int, measured_tokens: int | None = None,
measured_rows: int = 0) -> bool:
"""Return True when the request size plus the reply reserve fits in the context window.
@@ -282,7 +300,7 @@ def fits(body: dict[str, Any], context_length: int, measured_tokens: int | None
"""
if context_length <= 0:
return True
- reserve = body.get("max_tokens") or body.get("max_completion_tokens") or DEFAULT_RESERVE
+ reserve = reply_reserve(body)
messages = body.get("messages") or []
if type(measured_tokens) is int and measured_tokens > 0 and 0 < measured_rows <= len(messages):
size = measured_tokens + estimate_tokens({"messages": messages[measured_rows:]}) * SAFETY
@@ -313,6 +331,8 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, context
request.pop("stream_options", None)
# A stop sequence of the main request could cut the handoff after the five headings.
request.pop("stop", None)
+ # A web search costs a search and can bring text that is not in the conversation into the handoff.
+ request.pop("web_search_options", None)
# The reply limit of the main request is for another task: a small one cuts the handoff, a large one reserves
# space that the handoff does not need. Keep the field that the route uses.
for key in ("max_tokens", "max_completion_tokens"):