Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Refuse redirects, leave room for the summary in the copy budget, and label tool results
Elevatormusic78366bcb6d19
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex 2579c7c..e2d59e0 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:21:17Z",+ "started_utc": "2026-10-06T06:43:48Z","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": "2df68d8b31641f54cebb87de909441e87b293638c5a5af9d4d6158cc827bf0fe",- "warm_compaction/fallback.py": "45fc805aba7bd96360ad86d9fed6e43a5eabb6ae7716bae35cd95a05c821502f",+ "warm_compaction/engine.py": "4b097105b17e0daf0de09452ba6634d396166db69c1cd7f71495fdc5617a6c78",+ "warm_compaction/fallback.py": "77094a68fb91fbb0c1cf1acb4fd5f8ab555e0943422264bf585cf17541b7b267","warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2","warm_compaction/layout.py": "b3d9ffbf60fb6ee890615ed2f18d427aaba4fdd8f886bd93459bd7e40474b190","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "482c62b87fb42f1aa26473d474d6a3c70c85307632675b02a4a9861b80b6b4bf",- "warm_compaction/warm.py": "340f7e49b4cb095df29da9e7dfdb13575c6dc1eb5f63a7a9a3f5bc4bd21f9bf1"+ "warm_compaction/warm.py": "26d5605e804784ea357d3d6165a69243a527352bd6dde135b77dbc5fb5eb66b5"},"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.18,+ "compress_seconds": 0.099,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.026,+ "elapsed_s": 0.019,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -87,7 +87,8 @@"final_session_id": "wc-enable_manual_warm","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -95,11 +96,14 @@"python","python3"],- "fence_blocked_hosts": [],+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ],"fence_blocked_callers": [- "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_branch_tip < hermes_cli/source_check.py:_check_branch",+ "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"+ "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"],"fence_socketpairs": 1,"install": {@@ -184,7 +188,7 @@"install","run"],- "process_seconds": 75.186+ "process_seconds": 61.544},{"scenario": "manual_fallback",@@ -243,11 +247,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.388,+ "compress_seconds": 0.251,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.235,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -356,7 +360,7 @@"install","run"],- "process_seconds": 38.163+ "process_seconds": 39.128},{"scenario": "manual_fixed",@@ -414,11 +418,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.262,+ "compress_seconds": 0.255,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.11,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -527,7 +531,7 @@"install","run"],- "process_seconds": 34.074+ "process_seconds": 34.569},{"scenario": "auto_tool_loop",@@ -730,7 +734,7 @@"install","run"],- "process_seconds": 37.231+ "process_seconds": 43.865},{"scenario": "rollback",@@ -780,11 +784,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.163,+ "compress_seconds": 0.143,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -966,10 +970,10 @@"run","rollback"],- "process_seconds": 42.605+ "process_seconds": 43.277}],- "finished_utc": "2026-10-06T06:25:04Z",+ "finished_utc": "2026-10-06T06:47:31Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 39bd0eb..9ec2b56 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -191,6 +191,17 @@ 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+ self.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)+ engine = self.make() # A large window keeps the full allowance.+ self.assertEqual(engine._copy_tokens(), engine._tail_tokens())+def test_fixed_summary_when_the_fallback_fails(self):self.llm = FakeLlm(error=RuntimeError("down"))engine = self.make()diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex de58995..df6818d 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -51,8 +51,8 @@ class TranscriptTest(unittest.TestCase):tool("c1", "y" * (TOOL_CHARS + 100)), assistant("done")]text = transcript(rows, PREFIXES)self.assertTrue(text.startswith("[earlier summary]\nold summary\n\n[first user message]\nfirst ask"))- self.assertIn("(tool call read: {\"p\":1})", text)- self.assertIn("[tool result]\n" + "y" * TOOL_CHARS + " [cut]", text)+ self.assertIn("(tool call c1 read: {\"p\":1})", text)+ self.assertIn("[tool result c1 read]\n" + "y" * TOOL_CHARS + " [cut]", text)self.assertTrue(text.endswith("[assistant]\ndone"))def test_size_is_bounded(self):diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex d827455..8138042 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -261,8 +261,21 @@ class SendTest(unittest.TestCase):class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ # Only a followed redirect comes here.+ self.server.redirect_hits.append((self.path, self.headers.get("Authorization")))+ self.send_response(200)+ self.send_header("Content-Length", "0")+ self.end_headers()+def do_POST(self):body = self.rfile.read(int(self.headers["Content-Length"]))+ if self.path.endswith("/moved"):+ self.send_response(302)+ self.send_header("Location", "/elsewhere")+ self.send_header("Content-Length", "0")+ self.end_headers()+ returnstatus = 500 if self.path.endswith("/fail") else 200data = json.dumps({"size": len(body), "auth": self.headers.get("Authorization")}).encode("utf-8")self.send_response(status)@@ -282,6 +295,7 @@ class UrllibPostTest(unittest.TestCase):self.addCleanup(self.server.server_close)self.addCleanup(self.server.shutdown)self.base = f"http://127.0.0.1:{self.server.server_port}"+ self.server.redirect_hits = self.redirect_hits = []def test_posts_and_returns_status_and_body(self):status, raw = urllib_post(self.base + "/v1/chat/completions", b"{}", {"Authorization": "Bearer k"}, 5.0)@@ -291,6 +305,12 @@ class UrllibPostTest(unittest.TestCase):status, _raw = urllib_post(self.base + "/fail", b"{}", {}, 5.0)self.assertEqual(status, 500)+ def test_a_redirect_is_not_followed(self):+ # A followed redirect would send the Authorization header to the redirect target.+ status, _raw = urllib_post(self.base + "/moved", b"{}", {"Authorization": "Bearer k"}, 5.0)+ self.assertEqual(status, 302)+ self.assertEqual(self.redirect_hits, [])+if __name__ == "__main__":unittest.main()diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex a5e514d..f9995c8 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -21,6 +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_000HERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"HERMES_DB_MARKER = "_db_persisted"@@ -192,7 +195,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._tail_tokens())+ copy_tokens=self._copy_tokens())self.compression_count += 1self._finish(record, started)return new@@ -261,6 +264,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."""+ 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))+def _cancelled(self) -> bool:check = getattr(self, "_compression_cancelled_check", None)if not callable(check):diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex 5169d98..34a89e4 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -100,19 +100,23 @@ def _summary_text(row: Any, prefixes: tuple[str, ...]) -> str:return text.split(END_MARKER, 1)[0].strip()-def render_row(row: Any) -> str:- """Return one transcript entry for a row."""+def render_row(row: Any, call_names: dict[str, str] | None = None) -> str:+ """Return one transcript entry for a row. A tool result names its call id and tool, so that results of+ parallel calls stay linked to their calls."""role = str(attr(row, "role") or "unknown")text = visible_text(attr(row, "content"))text = (strip_think(text) if role == "assistant" else text).strip()if role == "tool":- return "[tool result]\n" + _cut(text, TOOL_CHARS)+ 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)lines = [f"[{role}]"]if text:lines.append(text)- for _call_id, name, arguments in tool_calls_of(row):+ for call_id, name, arguments in tool_calls_of(row):shown = arguments if isinstance(arguments, str) else compact_json(arguments)- lines.append(f"(tool call {name}: {_cut(shown, ARGUMENT_CHARS)})")+ lines.append(f"(tool call {' '.join(part for part in (call_id, name) if part)}: {_cut(shown, ARGUMENT_CHARS)})")return "\n".join(lines)@@ -134,11 +138,12 @@ 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}recent: collections.deque = collections.deque()for row in reversed(messages):if is_summary(row, prefixes):continue- part = _bound(render_row(row), ROW_CHARS, ROW_TOKENS, middle=True)+ part = _bound(render_row(row, call_names), 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/warm.py b/warm_compaction/warm.pyindex 68b7842..e7a02b0 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -187,9 +187,18 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, contextreturn request+class _NoRedirect(urllib.request.HTTPRedirectHandler):+ """Do not follow a redirect. A followed redirect would send the Authorization header to another origin."""++ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102+ return None++def urllib_post(url: str, data: bytes, headers: dict[str, str], timeout_s: float) -> tuple[int, bytes]:- """POST data with the standard library. Return (status, body). Raise TimeoutError on a time-out."""- opener = urllib.request.build_opener(urllib.request.ProxyHandler(urllib.request.getproxies_environment()))+ """POST data with the standard library. Return (status, body). Raise TimeoutError on a time-out. A redirect+ is not followed: its status comes back, and the caller treats it as a provider error."""+ opener = urllib.request.build_opener(urllib.request.ProxyHandler(urllib.request.getproxies_environment()),+ _NoRedirect())request = urllib.request.Request(url, data=data, headers=headers, method="POST")try:with opener.open(request, timeout=timeout_s) as response: