Skip to content

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

Keep the route query, check the attempt at the send, count the overhead in preflight, and refuse a preamble

Elevatormusic72859dfc8f43
diff --git a/README.md b/README.md
index a2ec07b..86f38a0 100644
--- a/README.md
+++ b/README.md
@@ -196,6 +196,9 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
## Limits
- The warm path needs a captured main-model request in the current Hermes process. After a restart or a resume, the first compaction uses the fallback summary if no main-model request completed before it (`no_capture`).
+- The warm request uses its own HTTP connection. It sends the route URL (with its query, for example an Azure `api-version`), the route headers, and the TLS settings, but not the cookies of the Hermes client. A gateway that needs a cookie from an earlier response refuses the warm request, and the fallback summary runs (`provider_error`).
+- A model or session switch, or a host timeout, during the attempt stops the warm request before it is sent (`route_changed` or `cancelled`).
+- 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). 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, 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 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`).
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.json
index f73c818..2328f51 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-06T13:29:33Z",
+ "started_utc": "2026-10-06T13:55:14Z",
"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": "4364e59bc2f896a5ea138de88895c127e0a3d41e44586cdcac983905af2b194a",
- "warm_compaction/fallback.py": "8d03c6a86a975c1f7c0d13d53e14b6561ab46be705b2ff813c69cec4ce747974",
- "warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",
+ "warm_compaction/engine.py": "d48df1522b0155236fb1018373608ff179aa606e5a30157c5f1f759b8b7c4054",
+ "warm_compaction/fallback.py": "f4cf08186f38fc9a46f47af2bedf22584b6ede4f11de1c3abd0fd598aec2f8a4",
+ "warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",
"warm_compaction/layout.py": "2ade107c1b6fc4f4d1bc35e0118c17184d8fe241484aad4b36d03800acb965c7",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
"warm_compaction/rows.py": "689c0619df6a7f8b89ef05ae87ec81b62c812ce34f81bfe557eb653158effac4",
- "warm_compaction/warm.py": "8122ac98d000a964fde02f9b1f7fa2e4d5379cedaf75641b80a7582d3deed8cc"
+ "warm_compaction/warm.py": "6ef65b128412838f70bd8d66f6fe98db87c48aacd81e21df8b7d48f8e411353a"
},
"privacy": "metadata only: names, counts, codes, booleans, and times; no message text",
"scenarios": [
@@ -76,23 +76,22 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.109,
+ "compress_seconds": 0.106,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.026,
- "prompt_tokens": 33883,
- "cached_tokens": 16941
+ "elapsed_s": 0.023,
+ "prompt_tokens": 33892,
+ "cached_tokens": 16946
},
"session_rotated": false,
"final_session_id": "wc-enable_manual_warm",
"continuation_keeps_custom_system_text": false,
"fence_denied": {
- "child_process_blocked": 4,
- "network_host_blocked": 1
+ "network_host_blocked": 1,
+ "child_process_blocked": 3
},
"fence_blocked_programs": [
- "git",
"pip",
"python",
"python3"
@@ -101,7 +100,6 @@
"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"
@@ -189,7 +187,7 @@
"install",
"run"
],
- "process_seconds": 57.387
+ "process_seconds": 57.073
},
{
"scenario": "manual_fallback",
@@ -248,7 +246,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.245,
+ "compress_seconds": 0.228,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
@@ -260,7 +258,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 +359,7 @@
"install",
"run"
],
- "process_seconds": 34.627
+ "process_seconds": 34.653
},
{
"scenario": "manual_fixed",
@@ -419,11 +417,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.279,
+ "compress_seconds": 0.276,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.125,
+ "elapsed_s": 0.14,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -431,7 +429,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 +530,7 @@
"install",
"run"
],
- "process_seconds": 32.876
+ "process_seconds": 31.374
},
{
"scenario": "auto_tool_loop",
@@ -620,16 +618,16 @@
"warm_last_1": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.016,
- "prompt_tokens": 35201,
- "cached_tokens": 17600
+ "elapsed_s": 0.015,
+ "prompt_tokens": 35209,
+ "cached_tokens": 17604
},
"warm_last_2": {
"path": "warm",
"reason": "accepted",
"elapsed_s": 0.016,
- "prompt_tokens": 18427,
- "cached_tokens": 9213
+ "prompt_tokens": 18436,
+ "cached_tokens": 9218
},
"compression_count": 2,
"fence_denied": {
@@ -737,7 +735,7 @@
"install",
"run"
],
- "process_seconds": 35.944
+ "process_seconds": 36.624
},
{
"scenario": "rollback",
@@ -787,13 +785,13 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.162,
+ "compress_seconds": 0.159,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.015,
- "prompt_tokens": 33873,
- "cached_tokens": 16936
+ "elapsed_s": 0.016,
+ "prompt_tokens": 33882,
+ "cached_tokens": 16941
},
"session_rotated": false,
"final_session_id": "wc-rollback",
@@ -950,7 +948,7 @@
"stored": 30
},
"fence_denied": {
- "child_process_blocked": 5,
+ "child_process_blocked": 6,
"network_host_blocked": 1
},
"fence_blocked_programs": [
@@ -973,10 +971,10 @@
"run",
"rollback"
],
- "process_seconds": 40.669
+ "process_seconds": 41.056
}
],
- "finished_utc": "2026-10-06T13:32:55Z",
+ "finished_utc": "2026-10-06T13:58:35Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 4923ab7..0024d9e 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -209,6 +209,52 @@ class EngineTest(unittest.TestCase):
self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),
("fallback", "middleware_changed_reply"))
+ def test_a_timed_out_attempt_does_not_send(self):
+ # The host can give up on the attempt while an execution middleware still runs.
+ def slow(request=None, next_call=None, **context):
+ self.engine._compression_cancelled_check = lambda: True
+ return next_call()
+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(slow)
+ rows = old_turns()
+ reply = assistant("final")
+ self.seed(rows, reply)
+ self.engine.compress([*rows, reply])
+ self.assertEqual(self.post.calls, [])
+ self.assertEqual(self.engine.warm_last["path"], "cancelled")
+
+ def test_a_route_change_during_the_attempt_does_not_send_to_the_new_route(self):
+ def switch(request=None, next_call=None, **context):
+ self.engine.update_model(model="other-model", context_length=200_000, base_url="https://other/v1",
+ api_key="other-key", provider="custom", api_mode=ROUTE[2])
+ return next_call()
+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(switch)
+ rows = old_turns()
+ reply = assistant("final")
+ self.seed(rows, reply)
+ self.engine.compress([*rows, reply])
+ self.assertEqual(self.post.calls, [])
+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),
+ ("fallback", "route_changed"))
+
+ def test_preflight_counts_the_captured_overhead_and_reply_reserve(self):
+ # A large system prompt and tool schemas take space that the history estimate does not show.
+ from warm_compaction.rows import estimate_tokens
+ rows = old_turns(4)
+ 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])
+ 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]))
+ messages = [*rows, user("next")]
+ self.assertLess(estimate_tokens(messages), engine.threshold_tokens)
+ self.assertTrue(engine.should_compress_preflight(messages))
+ self.assertFalse(self.make(threshold=0.95).should_compress_preflight([user("hi")]))
+
def test_a_second_send_is_refused_before_it_sends(self):
def twice(request=None, next_call=None, **context):
first = next_call()
diff --git a/tests/test_wc_handoff.py b/tests/test_wc_handoff.py
index 78be2d5..de952e1 100644
--- a/tests/test_wc_handoff.py
+++ b/tests/test_wc_handoff.py
@@ -39,6 +39,8 @@ class HandoffTest(unittest.TestCase):
"heading_order": reply("## Next step\nx\n## Goal\ng\n## User instructions\n## Current state\n- s\n"
"## Key facts\n"),
"section_empty": reply("## Goal\n## User instructions\n## Current state\n## Key facts\n## Next step"),
+ # Text before the first heading can be an answer or an action that did not occur, not a summary.
+ "heading_preamble": reply("I ran the tests and they pass.\n\n" + HEADINGS_TEXT),
"heading_repeated": reply("## Goal\n## Goal\n## User instructions\n## Current state\n## Current state\n"
"## Key facts\n## Next step\n## Next step"),
}
@@ -46,6 +48,11 @@ class HandoffTest(unittest.TestCase):
with self.subTest(expected=expected):
self.assertEqual(gate(value), (None, expected))
+ def test_a_leading_think_block_is_not_a_preamble(self):
+ text, reason = gate(reply("<think>plan</think>\n\n" + HEADINGS_TEXT))
+ self.assertIsNone(reason)
+ self.assertTrue(text.startswith("## Goal"))
+
def test_gate_needs_text_in_goal_state_and_next_step(self):
sections = {"## Goal": "g", "## User instructions": "- u", "## Current state": "- [OPEN] s",
"## Key facts": "- k", "## Next step": "n"}
diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.py
index 605d9b6..07e8e8d 100644
--- a/tests/test_wc_warm.py
+++ b/tests/test_wc_warm.py
@@ -539,6 +539,11 @@ class SendTest(unittest.TestCase):
"prompt_tokens_details": {"cached_tokens": 96}}}
reply = send({"messages": []}, "http://h/v1/", "k", post=fake_post(200, payload, calls))
self.assertEqual(calls[0][0], "http://h/v1/chat/completions")
+ # Hermes sends the query of the route URL (Azure api-version) as the client's default_query.
+ send({"messages": []}, "https://x.openai.azure.com/openai/deployments/d?api-version=2024-10-21", "k",
+ post=fake_post(200, payload, calls))
+ self.assertEqual(calls[1][0],
+ "https://x.openai.azure.com/openai/deployments/d/chat/completions?api-version=2024-10-21")
self.assertEqual(calls[0][2]["Authorization"], "Bearer k")
self.assertEqual((reply["content"], reply["finish_reason"], reply["tool_calls"], reply["refusal"]),
("text", "stop", False, False))
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index a97d0db..8459045 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -176,7 +176,18 @@ class WarmCompactionEngine(ContextEngine):
return self.threshold_tokens > 0 and _int(tokens) >= self.threshold_tokens
def should_compress_preflight(self, messages: list) -> bool:
- return self.threshold_tokens > 0 and estimate_tokens(messages) >= self.threshold_tokens
+ """The history estimate, with the system rows and tool schemas of a usable capture, reaches the threshold;
+ or with the reply reserve it does not fit in the window."""
+ if self.threshold_tokens <= 0:
+ return False
+ tokens = estimate_tokens(messages)
+ budget = self._budget_capture(self._store.latest(self._wc_session_id), messages)
+ if budget is not None:
+ tokens += request_overhead(budget, messages) or 0
+ window = int(self.context_length or 0)
+ if window > 0 and tokens + request_reserve(budget, window) > window:
+ return True
+ return tokens >= self.threshold_tokens
def has_content_to_compress(self, messages: list) -> bool:
start, _prepend = layout.tail_start(messages, self._tail_tokens(), self._prefixes())
@@ -202,13 +213,16 @@ class WarmCompactionEngine(ContextEngine):
memory = sanitize_memory(memory_context)
record: dict[str, Any] = {"path": None, "reason": None, "elapsed_s": None, "prompt_tokens": None,
"cached_tokens": None}
- capture = self._store.latest(self._wc_session_id)
+ # 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()
+ capture = self._store.latest(attempt[3])
# 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 = self._budget_capture(capture, messages)
overhead = request_overhead(budget, messages)
reserve = request_reserve(budget, int(self.context_length or 0))
- summary = self._warm_summary(messages, capture, focus_topic, memory, prefixes, record)
+ 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():
@@ -247,18 +261,22 @@ class WarmCompactionEngine(ContextEngine):
self._finish(record, started)
return new
+ def _attempt(self) -> tuple:
+ """(route, api key, provider, session id) now."""
+ return tuple(self._wc_route), self._wc_api_key, self._wc_provider, self._wc_session_id
+
def _warm_summary(self, messages: list, capture: dict[str, Any] | None, focus_topic: str | None, memory: str,
- prefixes: tuple[str, ...], record: dict[str, Any]) -> str | None:
+ prefixes: tuple[str, ...], record: dict[str, Any], attempt: tuple) -> str | None:
try:
if not self._settings["warm"]:
raise warm.WarmRefusal("disabled")
if capture is None:
raise warm.WarmRefusal("no_capture")
instruction = handoff.build_instruction(focus_topic, memory)
- body = warm.build_request(capture, messages, self._wc_route, self.context_length, instruction)
+ body = warm.build_request(capture, messages, attempt[0], self.context_length, instruction)
if self._cancelled():
raise warm.WarmRefusal("cancelled")
- reply = self._execute(body, instruction, len(capture["body"]["messages"]),
+ reply = self._execute(body, instruction, len(capture["body"]["messages"]), attempt,
capture.get("prompt_tokens"))
record.update(prompt_tokens=reply["prompt_tokens"], cached_tokens=reply["cached_tokens"])
text, reason = handoff.gate(reply, prefixes)
@@ -273,7 +291,7 @@ class WarmCompactionEngine(ContextEngine):
record.update(path="warm", reason="accepted")
return text
- def _execute(self, body: dict[str, Any], instruction: str, captured: int,
+ def _execute(self, body: dict[str, Any], instruction: str, captured: int, attempt: tuple,
measured: int | None = None) -> dict[str, Any]:
"""Send the warm request through the Hermes llm_request and llm_execution middleware, as Hermes sends a
main request. A request middleware can change the request, for example to redact the new rows. An
@@ -285,10 +303,11 @@ class WarmCompactionEngine(ContextEngine):
except Exception as error:
raise warm.WarmRefusal("middleware_unavailable") from error
# Before any middleware sees the request: a route without its headers does not send it.
- headers = warm.route_headers(self._wc_api_key, self._wc_route[1], self._wc_provider)
- tls = warm.route_tls(self._wc_route[1])
- context = {"purpose": NAME, "api_request_id": None, "session_id": self._wc_session_id,
- "model": self._wc_route[0], "base_url": self._wc_route[1], "api_mode": self._wc_route[2]}
+ route, api_key, provider, session_id = attempt
+ headers = warm.route_headers(api_key, route[1], provider)
+ tls = warm.route_tls(route[1])
+ context = {"purpose": NAME, "api_request_id": None, "session_id": session_id,
+ "model": route[0], "base_url": route[1], "api_mode": route[2]}
try:
# A copy: a host chain that passes the request itself to a middleware that changes it in place
# would change the body that the checks below compare with (and the stored capture).
@@ -324,8 +343,13 @@ class WarmCompactionEngine(ContextEngine):
# attempt stops even when the middleware catches this refusal.
repeated.append(True)
raise warm.WarmRefusal("middleware_repeated")
- result = warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post, extra_headers=headers,
- ssl_context=tls)
+ # The last check before the provider: an execution middleware can run after the host gave up on the
+ # attempt, or after a model or session switch.
+ if self._cancelled():
+ raise warm.WarmRefusal("cancelled")
+ if self._attempt() != attempt:
+ raise warm.WarmRefusal("route_changed")
+ result = warm.send(base, route[1], api_key, post=self._post, extra_headers=headers, ssl_context=tls)
sent.append((result, dict(result)))
return result
try:
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index ee15a94..27eab51 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -56,7 +56,7 @@ Rules:
- The transcript can be shortened. "[earlier summary]" marks the summary of older turns. "[first user message]" \
marks the first message of the user.
-Use these five headings, in this order, each on its own line:
+Use these five headings, in this order, each on its own line. Start the reply with "## Goal":
## Goal
The current goal of the user, in one or two sentences.
diff --git a/warm_compaction/handoff.py b/warm_compaction/handoff.py
index b576ef4..9b1c536 100644
--- a/warm_compaction/handoff.py
+++ b/warm_compaction/handoff.py
@@ -24,7 +24,7 @@ Rules:
- Write in the language of the conversation. Use short bullets. Use at most 600 words.
- Leave out data that the task does not need, for example unrelated records or logs.
-Use these five headings, in this order, each on its own line:
+Use these five headings, in this order, each on its own line. Start the reply with "## Goal":
## Goal
The current goal of the user, in one or two sentences.
@@ -93,6 +93,9 @@ def gate(reply: dict[str, Any], summary_prefixes: Iterable[str] = ()) -> tuple[s
starts = [lines.index(heading) for heading in HEADINGS]
if starts != sorted(starts):
return None, "heading_order"
+ # Text before the first heading can be an answer, or an action that did not occur: not a summary.
+ if next((line for line in lines if line), "") != HEADINGS[0]:
+ return None, "heading_preamble"
# The goal, the state, and the next step are necessary to continue the task. The user instructions and
# the key facts can be empty: there can be none.
for heading, start, end in zip(HEADINGS, starts, [*starts[1:], len(lines)]):
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index 60b36c1..f04073d 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -531,7 +531,10 @@ def send(body: dict[str, Any], base_url: str, api_key: Any, timeout_s: float = T
data = json.dumps(body).encode("utf-8")
started = time.monotonic()
try:
- url = str(base_url).rstrip("/") + "/chat/completions"
+ # The query of the route URL stays after the path: Hermes sends it as the client's default_query (the
+ # api-version of an Azure route, for example).
+ parts = urllib.parse.urlsplit(str(base_url))
+ url = urllib.parse.urlunsplit(parts._replace(path=parts.path.rstrip("/") + "/chat/completions"))
if ssl_context is None:
status, raw = (post or urllib_post)(url, data, headers, timeout_s)
else: