Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Run the request middleware, compare part order, and send api_content
Elevatormusic41d19ab9877d
diff --git a/README.md b/README.mdindex aec3fb3..16b4e1d 100644--- a/README.md+++ b/README.md@@ -138,7 +138,7 @@ warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021```- `path` is `warm`, `fallback`, or `fixed`.-- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_execution` middleware, as a main request does.+- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.- `cached_tokens` is `None` when the server does not report it. Then the cache reuse is unknown.The engine status (`get_status()`) has the same values in `warm_last`. The log never contains message text, request bodies, or keys.diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex e2d59e0..7050675 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-06T06:43:48Z",+ "started_utc": "2026-10-06T07:12:41Z","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": "4b097105b17e0daf0de09452ba6634d396166db69c1cd7f71495fdc5617a6c78",- "warm_compaction/fallback.py": "77094a68fb91fbb0c1cf1acb4fd5f8ab555e0943422264bf585cf17541b7b267",+ "warm_compaction/engine.py": "7b8244e5465662b30a933bbccd0a4b23f6dfa2af01e1dd23fdf28daf351a1727",+ "warm_compaction/fallback.py": "572eab9cecc0e012dc77aa22455037d8c9d5dd4672274d5b5493d6dc1b947329","warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2",- "warm_compaction/layout.py": "b3d9ffbf60fb6ee890615ed2f18d427aaba4fdd8f886bd93459bd7e40474b190",+ "warm_compaction/layout.py": "10e2a9e8be609757253dcfcab30b0c72e552bc21c90e711624db613f69760529","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",- "warm_compaction/rows.py": "482c62b87fb42f1aa26473d474d6a3c70c85307632675b02a4a9861b80b6b4bf",- "warm_compaction/warm.py": "26d5605e804784ea357d3d6165a69243a527352bd6dde135b77dbc5fb5eb66b5"+ "warm_compaction/rows.py": "a8943216049ef95742466c5628108154e239b96672726c732c508e30c95ac914",+ "warm_compaction/warm.py": "b46adbd267a52d5f46d4484ac774ab8b4e136fb8ec4a25452f95b7ea4218f5a4"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text","scenarios": [@@ -79,7 +79,7 @@"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.019,+ "elapsed_s": 0.02,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -87,7 +87,7 @@"final_session_id": "wc-enable_manual_warm","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -188,7 +188,7 @@"install","run"],- "process_seconds": 61.544+ "process_seconds": 57.485},{"scenario": "manual_fallback",@@ -247,7 +247,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.251,+ "compress_seconds": 0.259,"warm_last": {"path": "fallback","reason": "provider_error",@@ -259,7 +259,7 @@"final_session_id": "wc-manual_fallback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 5,"network_host_blocked": 1},"fence_blocked_programs": [@@ -360,7 +360,7 @@"install","run"],- "process_seconds": 39.128+ "process_seconds": 35.791},{"scenario": "manual_fixed",@@ -418,11 +418,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.255,+ "compress_seconds": 0.253,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.125,"prompt_tokens": null,"cached_tokens": null},@@ -430,7 +430,7 @@"final_session_id": "wc-manual_fixed","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 5,"network_host_blocked": 1},"fence_blocked_programs": [@@ -531,7 +531,7 @@"install","run"],- "process_seconds": 34.569+ "process_seconds": 32.659},{"scenario": "auto_tool_loop",@@ -734,7 +734,7 @@"install","run"],- "process_seconds": 43.865+ "process_seconds": 35.676},{"scenario": "rollback",@@ -784,11 +784,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.143,+ "compress_seconds": 0.159,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.0,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -796,7 +796,7 @@"final_session_id": "wc-rollback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 5,"network_host_blocked": 1},"fence_blocked_programs": [@@ -947,8 +947,7 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5,- "network_host_blocked": 1+ "child_process_blocked": 5},"fence_blocked_programs": ["git",@@ -956,9 +955,7 @@"python","python3"],- "fence_blocked_hosts": [- "hermes-assets.nousresearch.com"- ]+ "fence_blocked_hosts": []},"exit": [0,@@ -970,10 +967,10 @@"run","rollback"],- "process_seconds": 43.277+ "process_seconds": 39.086}],- "finished_utc": "2026-10-06T06:47:31Z",+ "finished_utc": "2026-10-06T07:16:02Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 9ec2b56..6206ee5 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -191,16 +191,53 @@ class EngineTest(unittest.TestCase):("fallback", "middleware_rewrite"))self.assertEqual(self.post.calls, [])- def test_copy_allowance_leaves_room_for_the_summary(self):- from warm_compaction.engine import SUMMARY_RESERVE_TOKENS+ def test_an_in_place_rewrite_stops_the_warm_request(self):+ # The request and the comparison base must not be the same object.+ def rewrite(request=None, next_call=None, **context):+ request["messages"][-1]["content"] = "Continue the task."+ return next_call()+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(rewrite)+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ self.engine.compress([*rows, reply])+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),+ ("fallback", "middleware_rewrite"))+ self.assertEqual(self.post.calls, [])++ def test_the_warm_request_goes_through_the_request_middleware(self):+ def redact(request=None, **context):+ seen.append(context.get("purpose"))+ text = json.dumps(request).replace("SECRET", "[redacted]")+ return {"request": json.loads(text)}+ seen = []+ wc_hermes_stub.REQUEST_MIDDLEWARE.append(redact)+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ self.engine.compress([*rows, reply, user("the key is SECRET")])+ self.assertEqual(self.engine.warm_last["path"], "warm")+ self.assertEqual(seen, ["warm_compaction"])+ sent = json.dumps(self.post.calls[0]["body"])+ self.assertNotIn("SECRET", sent)+ self.assertIn("the key is [redacted]", sent)++ def test_copy_allowance_leaves_room_for_the_actual_summary(self):+ from warm_compaction.engine import CARRIER_TOKENS+ from warm_compaction.rows import estimate_tokensself.engine.update_model(model=ROUTE[0], context_length=20_000, base_url=ROUTE[1], api_key="k",provider="custom", api_mode=ROUTE[2])- tail = self.engine._tail_tokens()- allowance = self.engine._copy_tokens()- self.assertEqual((self.engine.threshold_tokens, tail), (10_000, 5_000))- self.assertLessEqual(tail + allowance + SUMMARY_RESERVE_TOKENS, self.engine.threshold_tokens)+ self.assertEqual((self.engine.threshold_tokens, self.engine._tail_tokens()), (10_000, 5_000))+ tail = [user("t " + "x" * 16_000)]+ for summary in ("short", "## Key facts\n" + "- /very/long/path/name_" * 600):+ with self.subTest(summary=len(summary)):+ allowance = self.engine._copy_tokens(tail, summary)+ self.assertLessEqual(estimate_tokens(tail) + estimate_tokens(summary) + CARRIER_TOKENS + allowance,+ self.engine.threshold_tokens)+ self.assertEqual(self.engine._copy_tokens(tail, "short"), 5_000)+ 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(), engine._tail_tokens())+ self.assertEqual(engine._copy_tokens(tail, summary), engine._tail_tokens())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 df6818d..ae180b5 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -38,6 +38,13 @@ class TranscriptTest(unittest.TestCase):self.assertIn("[first user message]", text)self.assertTrue(text.endswith("\u597d"))+ def test_a_reused_call_id_takes_the_name_of_its_own_turn(self):+ rows = [user("go"), assistant("", [("call_0", "read", "{}")]), tool("call_0", "old"),+ assistant("", [("call_0", "write", "{}")]), tool("call_0", "new")]+ text = transcript(rows, PREFIXES)+ self.assertIn("[tool result call_0 read]\nold", text)+ self.assertIn("[tool result call_0 write]\nnew", text)+def test_think_blocks_are_removed_only_from_assistant_rows(self):text = "<think>keep me</think> body"self.assertNotIn("keep me", render_row(assistant(text)))diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex 33d049e..141b5cb 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -27,6 +27,21 @@ class PredicateTest(unittest.TestCase):with self.subTest(row=row):self.assertFalse(is_real_user(row, PREFIXES))+ def test_hermes_recovery_nudges_are_not_real_user_rows(self):+ for text in (+ "You've reached the maximum number of tool-calling iterations allowed. Please provide a final "+ "response summarizing what you've found and accomplished so far, without calling any more tools.",+ "You just executed tool calls but returned an empty response. Please process the tool results above "+ "and continue with the task.",+ "[System: Continue now. Execute the required tool calls and only send your final answer after "+ "completing the task.]",+ "Continue from the compressed conversation context above. This marker exists because no human user "+ "turn was available."):+ with self.subTest(text=text[:30]):+ self.assertFalse(is_real_user(user(text), PREFIXES))+ self.assertFalse(is_real_user(user(" " + text + "\n"), PREFIXES))+ self.assertTrue(is_real_user(user("Continue now."), PREFIXES))+def test_summary_detection(self):self.assertTrue(is_summary(assistant("[CONTEXT SUMMARY]: s"), PREFIXES))self.assertTrue(is_summary(user("plain", _compressed_summary=True), PREFIXES))diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 8138042..204e803 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -61,6 +61,13 @@ class WireRowTest(unittest.TestCase):self.assertEqual(wire_row(tool("c1", "out", name="read")),{"role": "tool", "content": "out", "tool_call_id": "c1", "name": "read"})+ def test_sends_the_api_content_of_user_and_assistant_rows(self):+ self.assertEqual(wire_row(user("hi", api_content="ctx\n\nhi")), {"role": "user", "content": "ctx\n\nhi"})+ self.assertEqual(wire_row(assistant("", api_content="answer")), {"role": "assistant", "content": "answer"})+ self.assertEqual(wire_row(assistant("shown", api_content="")), {"role": "assistant", "content": "shown"})+ row = dict(tool("c1", "out"), api_content="other")+ self.assertEqual(wire_row(row), {"role": "tool", "content": "out", "tool_call_id": "c1"})+class SettingsTest(unittest.TestCase):def test_refuses_settings_that_change_the_reply_form(self):@@ -153,19 +160,50 @@ class BuildRequestTest(unittest.TestCase):self.build(capture)self.assertEqual(caught.exception.code, "source_transform_unsupported")- def test_refuses_a_renamed_row_and_accepts_a_removed_name(self):- self.rows = [user("u1", name="alice"), assistant("a1"), user("u2")]+ def test_refuses_a_renamed_or_unnamed_user_row_and_accepts_an_unnamed_tool_row(self):+ self.rows = [user("u1", name="alice"), assistant("", [("c0", "read", "{}")]), tool("c0", "r0", name="read"),+ user("u2")]self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]- renamed = capture_for(self.rows, self.reply)- renamed["body"]["messages"][1]["name"] = "bob"- with self.assertRaises(WarmRefusal) as caught:- self.build(renamed)- self.assertEqual(caught.exception.code, "source_transform_unsupported")- # The Hermes transport removes the name from some rows. That is not a rewrite.+ for change in (lambda sent: sent[1].update(name="bob"), lambda sent: sent[1].pop("name")):+ capture = capture_for(self.rows, self.reply)+ change(capture["body"]["messages"])+ with self.subTest(), self.assertRaises(WarmRefusal) as caught:+ self.build(capture)+ self.assertEqual(caught.exception.code, "source_transform_unsupported")+ # The Hermes transport removes the name from tool rows only. That is not a rewrite.stripped = capture_for(self.rows, self.reply)- stripped["body"]["messages"][1].pop("name")+ stripped["body"]["messages"][3].pop("name")self.build(stripped)+ def test_refuses_moved_media_parts(self):+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ self.rows = [user([{"type": "text", "text": "first"}, image, {"type": "text", "text": "caption"}]),+ assistant("a1"), user("u2")]+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]+ capture = capture_for(self.rows, self.reply)+ capture["body"]["messages"][1]["content"] = [image, {"type": "text", "text": "first"},+ {"type": "text", "text": "caption"}]+ 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.+ capture = capture_for(self.rows, self.reply)+ capture["body"]["messages"][1]["content"][0]["text"] = "[context] first"+ self.build(capture)++ def test_the_stored_api_content_is_the_sent_text(self):+ self.rows = [user("hi", api_content="[recalled: short answers]\n\nhi"),+ assistant("", api_content="The answer is 4."), user("u2")]+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]+ capture = capture_for(self.rows, self.reply)+ for row in capture["body"]["messages"][1:3]:+ row["content"] = row.pop("api_content")+ self.build(capture)+ capture["body"]["messages"][2]["content"] = "The answer is 5."+ with self.assertRaises(WarmRefusal) as caught:+ self.build(capture)+ self.assertEqual(caught.exception.code, "source_transform_unsupported")+def test_refuses_changed_media_parts(self):image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}other = {"type": "image_url", "image_url": {"url": "data:image/png;base64,BBBB"}}diff --git a/tests/wc_hermes_stub.py b/tests/wc_hermes_stub.pyindex dad1a65..12bba35 100644--- a/tests/wc_hermes_stub.py+++ b/tests/wc_hermes_stub.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport abcimport copyimport sys-from types import ModuleType+from types import ModuleType, SimpleNamespacefrom unittest.mock import patchSUMMARY_PREFIX = "[HERMES PREFIX] Earlier turns were compacted."@@ -102,6 +102,20 @@ PLUGINS = _module("hermes_cli.plugins", VALID_HOOKS={"pre_api_request", "post_api_request", "on_session_start", "on_session_end", "on_session_finalize","on_session_reset"})EXECUTION_MIDDLEWARE = []+REQUEST_MIDDLEWARE = []+++def apply_llm_request_middleware(request, **context):+ """The llm_request chain of Hermes 45871e10: a middleware can return {"request": {...}} to replace it."""+ current = copy.deepcopy(request)+ trace = []+ for middleware in REQUEST_MIDDLEWARE:+ result = middleware(request=copy.deepcopy(current), original_request=request, **context)+ if isinstance(result, dict) and isinstance(result.get("request"), dict):+ current = copy.deepcopy(result["request"])+ trace.append({"source": "plugin"})+ return SimpleNamespace(payload=current if trace else request, original_payload=request, changed=bool(trace),+ trace=trace)def run_llm_execution_middleware(request, next_call, **context):@@ -125,7 +139,8 @@ def run_llm_execution_middleware(request, next_call, **context):MIDDLEWARE = _module("hermes_cli.middleware", VALID_MIDDLEWARE={"tool_request", "tool_execution", "llm_request", "llm_execution"},- run_llm_execution_middleware=run_llm_execution_middleware)+ run_llm_execution_middleware=run_llm_execution_middleware,+ apply_llm_request_middleware=apply_llm_request_middleware)HERMES_CLI.plugins = PLUGINSHERMES_CLI.middleware = MIDDLEWAREMODULES = {@@ -140,3 +155,4 @@ def install(test_case):patcher.start()test_case.addCleanup(patcher.stop)test_case.addCleanup(EXECUTION_MIDDLEWARE.clear)+ test_case.addCleanup(REQUEST_MIDDLEWARE.clear)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex f9995c8..637281a 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -2,7 +2,7 @@from __future__ import annotations-import importlib+import copyimport loggingimport timefrom typing import Any, Callable@@ -11,7 +11,7 @@ from agent.context_engine import ContextEnginefrom . import fallback, handoff, layout, warmfrom .capture import CaptureStore-from .rows import estimate_tokens+from .rows import estimate_tokens, hermes_valuelogger = logging.getLogger(__name__)@@ -21,9 +21,9 @@ THRESHOLD_RANGE = (0.10, 0.95)TAIL_SHARE = 0.025TAIL_MIN = 10_000TAIL_MAX = 25_000-# The summary row in tokens: the handoff (the instruction asks for at most 600 words, about 1,000 tokens) and-# the carrier headings.-SUMMARY_RESERVE_TOKENS = 2_000+# The summary row without the summary text and the copies: the header, the headings, the end marker, and the+# quote marks, with a margin for the estimate.+CARRIER_TOKENS = 500HERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"HERMES_DB_MARKER = "_db_persisted"@@ -67,15 +67,6 @@ def tail_budget(setting: int, context_length: int, threshold_tokens: int = 0) ->return min(budget, threshold_tokens // 2) if threshold_tokens > 0 else budget-def hermes_value(module: str, name: str, default: Any) -> Any:- """Read one Hermes value. Return the default when the read fails or the type is not the default type."""- try:- value = getattr(importlib.import_module(module), name)- except Exception:- return default- return value if isinstance(value, type(default)) else default--def sanitize_memory(memory_context: Any) -> str:"""Return memory provider text after the Hermes redaction. Return an empty text when that fails."""if not memory_context:@@ -195,7 +186,7 @@ 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())+ copy_tokens=self._copy_tokens(messages[start:], summary))self.compression_count += 1self._finish(record, started)return new@@ -227,25 +218,33 @@ class WarmCompactionEngine(ContextEngine):return textdef _execute(self, body: dict[str, Any]) -> dict[str, Any]:- """Send the warm request through the Hermes llm_execution middleware, as Hermes sends a main request.- A middleware can audit, change, block, or replace the request. A block or a replaced reply stops the- warm request; the fallback summary then runs."""+ """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+ execution middleware can audit, block, or replace the request. A block, a rewrite, or a replaced reply+ stops the warm request; the fallback summary then runs."""try:- from hermes_cli.middleware import run_llm_execution_middleware+ from hermes_cli.middleware import apply_llm_request_middleware, run_llm_execution_middlewareexcept Exception as error:raise warm.WarmRefusal("middleware_unavailable") from error+ 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]}+ try:+ body = apply_llm_request_middleware(body, **context).payload+ except Exception as error:+ raise warm.WarmRefusal("middleware_refused") from error+ if not isinstance(body, dict):+ raise warm.WarmRefusal("middleware_refused")+ # A copy that no middleware can change in place.+ base = copy.deepcopy(body)def terminal(request: Any) -> dict[str, Any]:- # The capture keeps the body before later middleware. A middleware that rewrites this request can- # also have rewritten the captured request, so the warm request is not sent.- if request != body:+ # The capture keeps the body before the execution middleware. An execution middleware that rewrites+ # this request can also have rewritten the captured request, so the warm request is not sent.+ if request != base:raise warm.WarmRefusal("middleware_rewrite")- return warm.send(request, self._wc_route[1], self._wc_api_key, post=self._post)+ return warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post)try:- reply = run_llm_execution_middleware(- body, terminal, original_request=body, 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])+ reply = run_llm_execution_middleware(body, terminal, original_request=base, **context)except warm.WarmRefusal:raiseexcept Exception as error:@@ -264,14 +263,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) -> int:- """Token allowance for the copied user messages: at most the tail size, and small enough that the tail,- the copies, and the summary row fit below the compaction threshold."""+ 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."""tail = self._tail_tokens()threshold = int(self.threshold_tokens or 0)if threshold <= 0:return tail- return max(0, min(tail, threshold - tail - SUMMARY_RESERVE_TOKENS))+ used = estimate_tokens(tail_rows) + estimate_tokens(summary) + CARRIER_TOKENS+ return max(0, min(tail, threshold - used))def _cancelled(self) -> bool:check = getattr(self, "_compression_cancelled_check", None)diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex 34a89e4..3cf9eba 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -138,12 +138,20 @@ def transcript(messages: list, prefixes: Iterable[str]) -> str: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)- call_names = {call_id: name for row in messages for call_id, name, _arguments in tool_calls_of(row) if call_id}+ # A tool row takes the names of the nearest earlier tool calls. Providers can use the same call id again+ # in a later turn.+ turn_names: list[dict[str, str]] = []+ names: dict[str, str] = {}+ for row in messages:+ if attr(row, "role") == "assistant" and tool_calls_of(row):+ names = {call_id: name for call_id, name, _arguments in tool_calls_of(row) if call_id}+ turn_names.append(names)recent: collections.deque = collections.deque()- for row in reversed(messages):+ for index in range(len(messages) - 1, -1, -1):+ row = messages[index]if is_summary(row, prefixes):continue- part = _bound(render_row(row, call_names), ROW_CHARS, ROW_TOKENS, middle=True)+ part = _bound(render_row(row, turn_names[index]), ROW_CHARS, ROW_TOKENS, middle=True)cost = estimate_tokens(part) + 1if len(part) + 2 > budget or cost > tokens:if budget - 2 >= MIN_PART_CHARS and tokens - 1 >= MIN_PART_CHARS // 4:diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex 5957638..4d69584 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -3,10 +3,11 @@from __future__ import annotationsimport copy+import functoolsfrom typing import Any, Iterablefrom .handoff import LEGACY_PREFIX-from .rows import attr, estimate_tokens, plain_text, visible_text+from .rows import attr, estimate_tokens, hermes_value, plain_text, visible_textHEADER_TEXT = "The summary of the earlier turns follows."COPY_HEADING = "## Copied user messages"@@ -21,6 +22,56 @@ SYNTHETIC_PREFIXES = ("[Your active task list was preserved across context compression]","[IMPORTANT: Background process ",)+# Hermes recovery nudges and continuation markers. The Hermes compressor matches them by exact text+# (ContextCompressor._is_synthetic_compression_user_turn). The Hermes value applies when Hermes has it; the+# text here is the value of Hermes 45871e10.+_COMPRESSOR = "agent.context_compressor"+_LOOP = "agent.conversation_loop"+HOST_NUDGES = (+ (_COMPRESSOR, "COMPRESSION_CONTINUATION_USER_CONTENT",+ "Continue from the compressed conversation context above. This marker exists because no human user turn "+ "was available."),+ (_COMPRESSOR, "_LEGACY_COMPRESSION_CONTINUATION_USER_CONTENT",+ "Continue from the compressed conversation context above. This marker exists because the compacted "+ "transcript contained no preserved user turn."),+ (_COMPRESSOR, "MAX_ITERATIONS_SUMMARY_REQUEST",+ "You've reached the maximum number of tool-calling iterations allowed. Please provide a final response "+ "summarizing what you've found and accomplished so far, without calling any more tools."),+ (_LOOP, "_CODEX_INCOMPLETE_NUDGE",+ "[System: Your previous response contained only internal reasoning and never produced a visible answer or "+ "tool call. Do not keep thinking. Produce your final answer as plain text now (or make the tool call you "+ "were planning).]"),+ (_LOOP, "_CODEX_ACK_CONTINUATION_NUDGE",+ "[System: Continue now. Execute the required tool calls and only send your final answer after completing "+ "the task.]"),+ (_LOOP, "_DEGENERATE_FINAL_NUDGE",+ "[System: Your previous message ended the turn with a fragment that is not a usable answer. If the task is "+ "unfinished, continue it and then give the complete answer. If that fragment WAS your complete answer, send "+ "it again exactly as before.]"),+ (_LOOP, "_DROPPED_TOOLCALL_NUDGE_CONTENT",+ "Your previous turn indicated a tool call but none was included. Do not narrate a plan or restate intent — "+ "issue the actual tool call now to continue the task."),+ (_LOOP, "_EMPTY_TOOL_RESPONSE_NUDGE",+ "You just executed tool calls but returned an empty response. Please process the tool results above and "+ "continue with the task."),+ (_LOOP, "_LENGTH_CONTINUATION_NETWORK_STUB",+ "[System: The previous response was cut off by a network error mid-stream — a transport interruption, NOT a "+ "change in your capabilities. Your tools are still fully available; call them as normal and ignore any "+ "earlier claim that you lack tool access. Continue the task from where you left off. Do not restart or "+ "repeat prior text.]"),+ (_LOOP, "_LEGACY_LENGTH_CONTINUATION_NETWORK_STUB",+ "[System: The previous response was cut off by a network error mid-stream. Continue exactly where you left "+ "off. Do not restart or repeat prior text. Finish the answer directly.]"),+ (_LOOP, "_LENGTH_CONTINUATION_OUTPUT_LIMIT",+ "[System: Your previous response was truncated by the output length limit. Continue exactly where you left "+ "off. Do not restart or repeat prior text. Finish the answer directly.]"),+)++[email protected]_cache(maxsize=1)+def nudge_texts() -> frozenset[str]:+ """Return the exact texts of the Hermes recovery nudges. Read one time: the values do not change."""+ return frozenset(hermes_value(module, name, default).strip() for module, name, default in HOST_NUDGES)def is_summary(row: Any, prefixes: Iterable[str]) -> bool:@@ -43,7 +94,7 @@ def is_real_user(row: Any, prefixes: Iterable[str]) -> bool:if row.get("display_kind") and row.get("display_kind") != STEER_KIND:return Falsetext = visible_text(row.get("content")).strip()- if not text or text.startswith(SYNTHETIC_PREFIXES):+ if not text or text.startswith(SYNTHETIC_PREFIXES) or text in nudge_texts():return Falsereturn not is_summary(row, prefixes)diff --git a/warm_compaction/rows.py b/warm_compaction/rows.pyindex 65d5c0f..00c210d 100644--- a/warm_compaction/rows.py+++ b/warm_compaction/rows.py@@ -3,6 +3,7 @@from __future__ import annotationsimport hashlib+import importlibimport jsonimport mathimport re@@ -18,6 +19,27 @@ def attr(obj: Any, name: str, default: Any = None) -> Any:return getattr(obj, name, default)+def hermes_value(module: str, name: str, default: Any) -> Any:+ """Read one Hermes value. Return the default when the read fails or the type is not the default type."""+ try:+ value = getattr(importlib.import_module(module), name)+ except Exception:+ return default+ return value if isinstance(value, type(default)) else default+++API_CONTENT_ROLES = ("user", "assistant")+++def api_content(row: Any) -> Any:+ """Return the content that Hermes sends for a stored row. A user or assistant row can carry an api_content+ sidecar: the exact text of the earlier request, which Hermes sends in place of content."""+ sidecar = attr(row, "api_content")+ if isinstance(sidecar, str) and sidecar and attr(row, "role") in API_CONTENT_ROLES:+ return sidecar+ return attr(row, "content")++def tool_calls_of(row: Any) -> list[tuple[str, str, Any]]:"""Return (id, name, arguments) for each tool call of a row or a reply object."""calls = []diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex e7a02b0..09a4e7d 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -9,7 +9,9 @@ import urllib.errorimport urllib.requestfrom typing import Any, Callable-from .rows import attr, compact_json, estimate_tokens, plain_text, reply_text, row_digest, tool_calls_of+from .rows import (+ api_content, attr, compact_json, estimate_tokens, plain_text, reply_text, row_digest, tool_calls_of,+)DEFAULT_RESERVE = 4096TIMEOUT_S = 120.0@@ -78,16 +80,32 @@ def _shape(row: Any) -> tuple:return attr(row, "role"), attr(row, "tool_call_id") or None, calls-def _words(content: Any) -> str:- return " ".join(plain_text(content).split())+def _words(text: str) -> str:+ return " ".join(text.split())-def _media(content: Any) -> list:- """Return the parts of a content list that are not text, in order."""+def _is_text(part: Any) -> bool:+ return isinstance(part, str) or (+ isinstance(part, dict) and part.get("type", "text") == "text" and isinstance(part.get("text"), str))+++def _parts(content: Any) -> tuple[list[str], list]:+ """Return the text runs between the non-text parts (as words) and the non-text parts, in order. A message+ with n image, audio, or file parts has n + 1 text runs."""if not isinstance(content, list):- return []- return [part for part in content if not (isinstance(part, str) or (- isinstance(part, dict) and part.get("type", "text") == "text" and isinstance(part.get("text"), str)))]+ return [_words(plain_text(content))], []+ runs: list[str] = []+ media: list = []+ current: list[str] = []+ for part in content:+ if _is_text(part):+ current.append(part if isinstance(part, str) else part["text"])+ else:+ runs.append(_words(" ".join(current)))+ media.append(part)+ current = []+ runs.append(_words(" ".join(current)))+ return runs, mediadef _arguments(value: Any) -> Any:@@ -101,14 +119,18 @@ def _arguments(value: Any) -> Any:def _same_row(wire: Any, row: Any) -> bool:- """True when the sent row carries the stored row: the same shape, the same name or no name (the Hermes- transport removes the name from some rows), the stored text inside the sent text (Hermes can add- request-time context to a row), the same image, audio, and file parts, and the same tool-call arguments."""- if _shape(wire) != _shape(row) or attr(wire, "name") not in (None, attr(row, "name")):+ """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."""+ if _shape(wire) != _shape(row):return False- if _words(attr(row, "content")) not in _words(attr(wire, "content")):+ name = attr(wire, "name")+ if name != attr(row, "name") and not (name is None and attr(row, "role") == "tool"):return False- if _media(attr(wire, "content")) != _media(attr(row, "content")):+ 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 in sent for stored, sent in zip(stored_runs, sent_runs)):return Falsereturn [_arguments(arguments) for _id, _name, arguments in tool_calls_of(wire)] == [_arguments(arguments) for _id, _name, arguments in tool_calls_of(row)]@@ -126,8 +148,9 @@ def check_source(body: dict[str, Any], history_rows: list) -> None:def wire_row(row: Any) -> dict[str, Any]:- """Return the wire form of a stored row. Keep only the fields that the API reads."""- wire: dict[str, Any] = {"role": attr(row, "role"), "content": copy.deepcopy(attr(row, "content"))}+ """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."""+ 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)if value is not None: