Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Keep reasoning_content on echo routes, refuse cut-off fallback replies, and count the request overhead
Elevatormusic73485a5c9cc6
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex ee806b2..f53250e 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-06T07:30:24Z",+ "started_utc": "2026-10-06T07:51:51Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,13 +10,13 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "3ee60f35ae4e8fc0376ab6634c721ae1ca429593d10730f19addc3be545fe682",- "warm_compaction/engine.py": "c7ba706f4f1d0c5707cd62a932bc0f762c7940080f153f2aa44d21db1254a8d3",- "warm_compaction/fallback.py": "ae36f2a37e451d833cb09bbbba3491e06ab84d41612e4496b467cac269260672",+ "warm_compaction/engine.py": "0f989bf6668a6f1b9c37e112a5d4f1fd8df1cb588ee44d3af31aaf0a1e435f1d",+ "warm_compaction/fallback.py": "83c00652f9fc1aeb1673636e1cf33f1793a0c5adb46a613368d27abad80592df","warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2","warm_compaction/layout.py": "e6f6c92c91b8c9da415bff6e430c1eaaddb62d14ed403ff700cf8ed23bb1ecca","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "a8943216049ef95742466c5628108154e239b96672726c732c508e30c95ac914",- "warm_compaction/warm.py": "b46adbd267a52d5f46d4484ac774ab8b4e136fb8ec4a25452f95b7ea4218f5a4"+ "warm_compaction/warm.py": "93401d68420d9e2e99f7f4bc83eed6a530fa38f43c6c27d53fe655b085166747"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text","scenarios": [@@ -75,11 +75,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.099,+ "compress_seconds": 0.109,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.02,+ "elapsed_s": 0.023,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -188,7 +188,7 @@"install","run"],- "process_seconds": 62.675+ "process_seconds": 58.832},{"scenario": "manual_fallback",@@ -247,11 +247,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.302,+ "compress_seconds": 0.242,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.141,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -360,7 +360,7 @@"install","run"],- "process_seconds": 38.397+ "process_seconds": 32.847},{"scenario": "manual_fixed",@@ -418,11 +418,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.236,+ "compress_seconds": 0.254,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.11,+ "elapsed_s": 0.125,"prompt_tokens": null,"cached_tokens": null},@@ -531,7 +531,7 @@"install","run"],- "process_seconds": 34.069+ "process_seconds": 31.429},{"scenario": "auto_tool_loop",@@ -734,7 +734,7 @@"install","run"],- "process_seconds": 37.438+ "process_seconds": 34.844},{"scenario": "rollback",@@ -784,7 +784,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.155,+ "compress_seconds": 0.176,"warm_last": {"path": "warm","reason": "accepted",@@ -947,7 +947,8 @@"stored": 30},"fence_denied": {- "child_process_blocked": 4+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -955,7 +956,9 @@"python","python3"],- "fence_blocked_hosts": []+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ]},"exit": [0,@@ -967,10 +970,10 @@"run","rollback"],- "process_seconds": 43.854+ "process_seconds": 40.93}],- "finished_utc": "2026-10-06T07:34:01Z",+ "finished_utc": "2026-10-06T07:55:10Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex d6d13ba..28f1a64 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -248,6 +248,18 @@ class EngineTest(unittest.TestCase):self.assertLess(self.engine._copy_tokens(tail, summary), 5_000)engine = self.make() # A large window keeps the full allowance.self.assertEqual(engine._copy_tokens(tail, summary), engine._tail_tokens())+ # The system prompt and the tool schemas count too.+ self.assertEqual(self.engine._copy_tokens(tail, "short", 4_000), 10_000 - 4_000 - CARRIER_TOKENS+ - estimate_tokens(tail) - estimate_tokens("short"))++ def test_request_overhead_comes_from_the_capture(self):+ from warm_compaction.engine import request_overhead+ from warm_compaction.rows import estimate_tokens+ rows = old_turns(2)+ self.seed(rows, assistant("final"))+ capture = self.store.latest("s1")+ self.assertEqual(request_overhead(capture), estimate_tokens({"messages": [SYSTEM], "tools": None}))+ self.assertEqual(request_overhead(None), 0)def test_fixed_summary_when_the_fallback_fails(self):self.llm = FakeLlm(error=RuntimeError("down"))diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex a03c2f1..2725fe4 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -18,14 +18,17 @@ SUMMARY = "## Goal\nG\n## User instructions\n- none\n## Current state\n- [OPEN]class FakeLlm:- def __init__(self, text=SUMMARY, error=None):- self.text, self.error, self.calls = text, error, []+ def __init__(self, text=SUMMARY, error=None, output_tokens=None):+ self.text, self.error, self.calls, self.output_tokens = text, error, [], output_tokensdef complete(self, messages, **kwargs):self.calls.append((messages, kwargs))if self.error:raise self.error- return SimpleNamespace(text=self.text, usage=SimpleNamespace(input_tokens=321))+ usage = SimpleNamespace(input_tokens=321)+ if self.output_tokens is not None:+ usage.output_tokens = self.output_tokens+ return SimpleNamespace(text=self.text, usage=usage)class TranscriptTest(unittest.TestCase):@@ -54,6 +57,17 @@ class TranscriptTest(unittest.TestCase):self.assertIn("[user]\n[ctx]\n\nhi", text)self.assertIn("[assistant]\nThe answer is 4.", text)+ def test_the_end_of_a_long_tool_result_is_kept(self):+ text = render_row(tool("c1", "start " + "y" * 3_000 + " exit status 1"))+ self.assertTrue(text.startswith("[tool result c1]\nstart "))+ self.assertTrue(text.endswith(" exit status 1"))+ self.assertLessEqual(len(text.split("\n", 1)[1]), TOOL_CHARS)++ def test_the_first_user_slot_shows_the_sent_api_content(self):+ rows = [user("first", api_content="[ctx]\n\nfirst"), *[assistant("z" * 3_900) for _ in range(12)]]+ text = transcript(rows, PREFIXES)+ self.assertIn("[first user message]\n[ctx]\n\nfirst", text)+def test_names_are_in_the_transcript_labels(self):text = transcript([user("ship it", name="alice"), user("wait", name="bob"), assistant("ok", name="lead")],PREFIXES)@@ -75,7 +89,8 @@ class TranscriptTest(unittest.TestCase):text = transcript(rows, PREFIXES)self.assertTrue(text.startswith("[earlier summary]\nold summary\n\n[first user message]\nfirst ask"))self.assertIn("(tool call c1 read: {\"p\":1})", text)- self.assertIn("[tool result c1 read]\n" + "y" * TOOL_CHARS + " [cut]", text)+ self.assertIn("[tool result c1 read]\n" + "y" * 600, text)+ self.assertIn(MIDDLE_MARK, text.split("[tool result c1 read]\n", 1)[1])self.assertTrue(text.endswith("[assistant]\ndone"))def test_size_is_bounded(self):@@ -120,6 +135,14 @@ class LlmSummaryTest(unittest.TestCase):self.assertIn("Give more detail to this topic: db", messages[0]["content"])self.assertEqual(messages[1]["role"], "user")+ def test_a_reply_that_reached_the_token_limit_is_refused(self):+ # ctx.llm reports no finish reason. A reply at the max_tokens limit can be cut off.+ long_summary = SUMMARY + "\n" + "- fact\n" * 1_000+ for llm in (FakeLlm(output_tokens=MAX_TOKENS), FakeLlm(text=long_summary)):+ with self.subTest(), self.assertLogs("warm_compaction.fallback", level="WARNING"):+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES), (None, None))+ self.assertEqual(llm_summary(FakeLlm(output_tokens=300), [user("hi")], PREFIXES), (SUMMARY, 321))+def test_task_none_uses_the_main_model_route(self):llm = FakeLlm()llm_summary(llm, [user("hi")], PREFIXES, task=None)diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 204e803..e09218b 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -119,6 +119,20 @@ class BuildRequestTest(unittest.TestCase):self.assertEqual((body["stream"], body["temperature"]), (False, 0.2))self.assertNotIn("stream_options", body)+ def test_appended_assistant_rows_keep_reasoning_content_on_an_echo_route(self):+ # A thinking-mode route (DeepSeek, Kimi) needs reasoning_content on every assistant row. The captured+ # rows show that Hermes sends it on this route.+ self.rows = [user("u1"), assistant("a1", reasoning_content=" "), user("u2")]+ self.messages = [*self.rows, assistant("", [("c1", "read", "{}")], reasoning="look"), tool("c1", "r1")]+ sent = self.build(capture_for(self.rows, self.reply))["messages"]+ self.assertEqual(sent[-3]["reasoning_content"], " ")+ self.messages[-2] = assistant("", [("c1", "read", "{}")], reasoning_content="look")+ self.assertEqual(self.build(capture_for(self.rows, self.reply))["messages"][-3]["reasoning_content"], "look")+ # A route without it keeps the field out (strict providers reject it).+ self.rows = history()+ self.messages = [*self.rows, assistant("", [("c1", "read", "{}")], reasoning="look"), tool("c1", "r1")]+ self.assertNotIn("reasoning_content", self.build(capture_for(self.rows, self.reply))["messages"][-3])+def test_sends_every_trailing_user_row(self):# The tail can keep only the newest of several user rows. The handoff must see the older ones too.self.messages = [*self.messages, user("u4 " + "x" * 5_000)]diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 73291ec..75d1db8 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -78,6 +78,16 @@ def sanitize_memory(memory_context: Any) -> str:return ""+def request_overhead(capture: dict[str, Any] | None) -> int:+ """Estimated tokens of the request parts that are not history rows: the system rows and the tool schemas of+ the captured request. 0 without a captured request body."""+ body = (capture or {}).get("body")+ if not isinstance(body, dict) or not isinstance(body.get("messages"), list):+ return 0+ count = max(len(body["messages"]) - len(capture.get("digests") or ()), 0)+ return estimate_tokens({"messages": body["messages"][:count], "tools": body.get("tools")})++def _int(value: Any) -> int:return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0@@ -167,7 +177,8 @@ 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}- summary = self._warm_summary(messages, focus_topic, memory, prefixes, record)+ capture = self._store.latest(self._wc_session_id)+ summary = self._warm_summary(messages, capture, focus_topic, memory, prefixes, record)if summary is None and not self._cancelled():# 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.@@ -188,17 +199,16 @@ class WarmCompactionEngine(ContextEngine):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=self._copy_tokens(messages[start:], summary))+ copy_tokens=self._copy_tokens(messages[start:], summary, request_overhead(capture)))self.compression_count += 1self._finish(record, started)return new- def _warm_summary(self, messages: list, focus_topic: str | None, memory: str, prefixes: tuple[str, ...],- record: dict[str, Any]) -> str | None:+ 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:try:if not self._settings["warm"]:raise warm.WarmRefusal("disabled")- capture = self._store.latest(self._wc_session_id)if capture is None:raise warm.WarmRefusal("no_capture")body = warm.build_request(capture, messages, self._wc_route, self.context_length,@@ -265,14 +275,15 @@ class WarmCompactionEngine(ContextEngine):return tail_budget(int(self._settings["tail_tokens"]), int(self.context_length or 0),int(self.threshold_tokens or 0))- def _copy_tokens(self, tail_rows: list, summary: str) -> int:- """Token allowance for the copied user messages: at most the tail size, and small enough that the tail- rows, the summary, the summary row headings, and the copies fit below the compaction threshold."""+ def _copy_tokens(self, tail_rows: list, summary: str, overhead: int = 0) -> int:+ """Token allowance for the copied user messages: at most the tail size, and small enough that the request+ overhead (system rows and tool schemas), the tail rows, the summary, the summary row headings, and the+ copies fit below the compaction threshold."""tail = self._tail_tokens()threshold = int(self.threshold_tokens or 0)if threshold <= 0:return tail- used = estimate_tokens(tail_rows) + estimate_tokens(summary) + CARRIER_TOKENS+ used = overhead + estimate_tokens(tail_rows) + estimate_tokens(summary) + CARRIER_TOKENSreturn max(0, min(tail, threshold - used))def _cancelled(self) -> bool:diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex a0e0d41..9125546 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -113,7 +113,8 @@ def render_row(row: Any, call_names: dict[str, str] | None = None) -> str:call_id = str(attr(row, "tool_call_id") or "")name = str(attr(row, "name") or (call_names or {}).get(call_id) or "")label = " ".join(part for part in ("tool result", call_id, name) if part)- return f"[{label}]\n" + _cut(text, TOOL_CHARS)+ # The start and the end: the result, an exit status, or an error is often at the end.+ return f"[{label}]\n" + _cut_middle(text, TOOL_CHARS)name = attr(row, "name")lines = [f"[{role} {name}]" if isinstance(name, str) and name else f"[{role}]"]if text:@@ -138,7 +139,7 @@ def transcript(messages: list, prefixes: Iterable[str]) -> str:EARLIER_SUMMARY_TOKENS))first = next((row for row in messages if is_real_user(row, prefixes)), None)if first is not None:- head.append("[first user message]\n" + _bound(visible_text(first.get("content")).strip(), FIRST_USER_CHARS,+ head.append("[first user message]\n" + _bound(visible_text(api_content(first)).strip(), FIRST_USER_CHARS,FIRST_USER_TOKENS))budget = TRANSCRIPT_CHARS - sum(len(part) + 2 for part in head)tokens = TRANSCRIPT_TOKENS - sum(estimate_tokens(part) + 1 for part in head)@@ -167,6 +168,16 @@ def transcript(messages: list, prefixes: Iterable[str]) -> str:return "\n\n".join([*head, *recent])+def _finish_reason(result: Any, text: str) -> str:+ """Return "length" for a reply that can be cut off, else "stop". ctx.llm reports no finish reason. A reply+ at the max_tokens limit can be cut off; the instruction asks for about 1,000 tokens. Without an output count,+ a reply with an estimate above three quarters of the limit counts as cut off."""+ output = getattr(getattr(result, "usage", None), "output_tokens", None)+ if isinstance(output, int) and not isinstance(output, bool) and output > 0:+ return "length" if output >= MAX_TOKENS else "stop"+ return "length" if estimate_tokens(text) >= MAX_TOKENS * 3 // 4 else "stop"++def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topic: str | None = None,memory_context: str = "", task: str | None = TASK,timeout_s: float = TIMEOUT_S) -> tuple[str | None, int | None]:@@ -185,8 +196,8 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topireturn None, None# The same checks as the warm reply: the five headings, the byte limit, and no summary markers. A reply# without them (cut off, or an answer to the conversation) must not replace the history.- text, reason = gate({"content": str(getattr(result, "text", "") or ""),- "finish_reason": getattr(result, "finish_reason", None) or "stop"}, prefixes)+ raw = str(getattr(result, "text", "") or "")+ text, reason = gate({"content": raw, "finish_reason": _finish_reason(result, raw)}, prefixes)if text is None:logger.warning("warm_compaction: the fallback summary was refused (%s)", reason)return None, Nonediff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 09a4e7d..29ade5b 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -10,7 +10,8 @@ import urllib.requestfrom typing import Any, Callablefrom .rows import (- api_content, attr, compact_json, estimate_tokens, plain_text, reply_text, row_digest, tool_calls_of,+ api_content, attr, compact_json, estimate_tokens, hermes_value, plain_text, reply_text, row_digest,+ tool_calls_of,)DEFAULT_RESERVE = 4096@@ -147,9 +148,35 @@ def check_source(body: dict[str, Any], history_rows: list) -> None:raise WarmRefusal("source_transform_unsupported")-def wire_row(row: Any) -> dict[str, Any]:- """Return the wire form of a stored row, as Hermes sends it: only the fields that the API reads, and the- api_content sidecar of a user or assistant row in place of its content."""+def _reasoning_policy(source: dict, wire: dict, needs_pad: bool) -> None:+ """The reasoning_content rule of Hermes 45871e10 (agent.message_sanitization.apply_reasoning_content_policy):+ a thinking-mode route (DeepSeek, Kimi, MiMo) needs the field on every assistant row; other routes reject it."""+ if source.get("role") != "assistant":+ return+ if not needs_pad:+ wire.pop("reasoning_content", None)+ return+ existing, reasoning = source.get("reasoning_content"), source.get("reasoning")+ if isinstance(existing, str):+ wire["reasoning_content"] = existing or " "+ elif isinstance(reasoning, str) and reasoning and not source.get("tool_calls"):+ wire["reasoning_content"] = reasoning+ else:+ wire["reasoning_content"] = " "+++def needs_reasoning_echo(body: dict[str, Any], rows: list) -> bool:+ """True when the route needs reasoning_content on assistant rows: Hermes sent it on a captured assistant row,+ or a new assistant row has it from the provider."""+ return any(isinstance(row, dict) and row.get("role") == "assistant" and "reasoning_content" in row+ for row in body.get("messages") or ()) or any(+ attr(row, "role") == "assistant" and isinstance(attr(row, "reasoning_content"), str) for row in rows)+++def wire_row(row: Any, reasoning_echo: bool = False) -> dict[str, Any]:+ """Return the wire form of a stored row, as Hermes sends it: only the fields that the API reads, the+ api_content sidecar of a user or assistant row in place of its content, and reasoning_content on an assistant+ row when the route needs it."""wire: dict[str, Any] = {"role": attr(row, "role"), "content": copy.deepcopy(api_content(row))}for key in ("tool_call_id", "name"):value = attr(row, key)@@ -165,6 +192,9 @@ def wire_row(row: Any) -> dict[str, Any]:}}for call_id, name, arguments in calls]+ if isinstance(row, dict):+ policy = hermes_value("agent.message_sanitization", "apply_reasoning_content_policy", _reasoning_policy)+ policy(row, wire, reasoning_echo)return wire@@ -201,7 +231,8 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, contextcheck_source(body, messages[: len(capture["digests"])])request = dict(body)# Send the trailing user rows too: the tail can keep only the newest of them, and compaction removes the others.- request["messages"] = [*body["messages"], *(wire_row(row) for row in (*new_rows, *trailing)),+ echo = needs_reasoning_echo(body, new_rows)+ request["messages"] = [*body["messages"], *(wire_row(row, echo) for row in (*new_rows, *trailing)),{"role": "user", "content": instruction}]request["stream"] = Falserequest.pop("stream_options", None)