Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Keep reasoning_details on replaying routes, compare argument types, and count repeated call ids
Elevatormusic56014422dc0d
diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex fb894d5..3479b10 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-06T08:45:08Z",+ "started_utc": "2026-10-06T09:00:36Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -9,14 +9,14 @@"script_sha256": "85397c1e4879f7cf21d3b2619baecf72fb67eb27e69376f428d0426ee69ab3d1","plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",- "warm_compaction/capture.py": "3ee60f35ae4e8fc0376ab6634c721ae1ca429593d10730f19addc3be545fe682",+ "warm_compaction/capture.py": "9d6414ec2dc552a01d7ba0ab84009ee30a363d57b9a061c2b5d9bc699c0efb75","warm_compaction/engine.py": "83e2434a172a540e7e21053fd8da6d7204bc8eacadab1809213095821b362b96","warm_compaction/fallback.py": "5997b3c96ad7bbdaa4f505ffb470aa850c7c7afd33630f02823b3fdda6c46339","warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2","warm_compaction/layout.py": "fd4d260380ce2cc44aa846758762a05bb4737c10677bceec0b17fd3c59c943f5","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "c0c0b7cfc5bebfa9caa58e9621ff3eda0db108c7976ca769da159be13574874b",- "warm_compaction/warm.py": "d5b619314975fad925137fd6b2b730634c4b264ee6a5fd402969810364a26775"+ "warm_compaction/warm.py": "536c9b208a5540bf7309a2f4bdf366faebc01b4045c6b63a2191e84762259dc5"},"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.109,+ "compress_seconds": 0.113,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.021,+ "elapsed_s": 0.023,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -87,11 +87,10 @@"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"@@ -100,7 +99,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"@@ -188,7 +186,7 @@"install","run"],- "process_seconds": 56.444+ "process_seconds": 82.046},{"scenario": "manual_fallback",@@ -247,11 +245,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.224,+ "compress_seconds": 0.274,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.094,+ "elapsed_s": 0.125,"prompt_tokens": null,"cached_tokens": null},@@ -360,7 +358,7 @@"install","run"],- "process_seconds": 33.685+ "process_seconds": 60.664},{"scenario": "manual_fixed",@@ -418,11 +416,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.249,+ "compress_seconds": 0.258,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.094,"prompt_tokens": null,"cached_tokens": null},@@ -430,7 +428,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 +529,7 @@"install","run"],- "process_seconds": 31.663+ "process_seconds": 34.137},{"scenario": "auto_tool_loop",@@ -617,7 +615,7 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.032,"prompt_tokens": 35205,"cached_tokens": 17602},@@ -630,8 +628,8 @@},"compression_count": 2,"fence_denied": {- "child_process_blocked": 8,- "network_host_blocked": 1+ "network_host_blocked": 1,+ "child_process_blocked": 7},"fence_blocked_programs": ["git",@@ -645,7 +643,6 @@"fence_blocked_callers": ["child_process_blocked from hermes_cli/local_runtime/processes.py:spawn_server < hermes_cli/_subprocess_compat.py:bounded_probe_run < hermes_cli/_subprocess_compat.py:bounded_git_probe","child_process_blocked from hermes_cli/local_runtime/processes.py:spawn_server < hermes_cli/_subprocess_compat.py:bounded_probe_run < hermes_cli/_subprocess_compat.py:noninteractive_repo_git_env",- "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"@@ -734,7 +731,7 @@"install","run"],- "process_seconds": 35.646+ "process_seconds": 35.194},{"scenario": "rollback",@@ -784,11 +781,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.143,+ "compress_seconds": 0.156,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -970,10 +967,10 @@"run","rollback"],- "process_seconds": 42.283+ "process_seconds": 40.061}],- "finished_utc": "2026-10-06T08:48:28Z",+ "finished_utc": "2026-10-06T09:04:48Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_capture.py b/tests/test_wc_capture.pyindex bb0a6ab..3a6e5e0 100644--- a/tests/test_wc_capture.py+++ b/tests/test_wc_capture.py@@ -72,6 +72,12 @@ class CaptureStoreTest(unittest.TestCase):self.assertEqual(capture["reply"], {"role": "assistant", "content": "done", "tool_calls": []})self.assertEqual((capture["finish_reason"], capture["captured_at"]), ("stop", 5.0))+ def test_a_repeated_call_id_gets_the_hermes_rename(self):+ # Hermes renames a repeated id in one reply (c1, c1 -> c1, c1_d2) after this hook runs.+ self.run_request(finish="tool_calls", message=reply_object("", [("c1", "read"), ("c1", "ls"), ("c1", "cat")]))+ self.assertEqual(self.store.latest("s1")["reply"]["tool_calls"],+ [["c1", "read"], ["c1_d2", "ls"], ["c1_d3", "cat"]])+def test_keeps_tool_call_ids_and_names(self):self.run_request(finish="tool_calls", message=reply_object("", [("c1", "read")]))self.assertEqual(self.store.latest("s1")["reply"]["tool_calls"], [["c1", "read"]])diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 4bca7f0..ec39cce 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -53,6 +53,19 @@ class SplitHistoryTest(unittest.TestCase):self.assertEqual(caught.exception.code, "history_changed")+class RepeatedCallIdTest(unittest.TestCase):+ def test_tool_results_are_counted_by_occurrence(self):+ rows = history()+ reply = assistant("", [("c1", "read", "{}"), ("c1", "ls", "{}")])+ capture = capture_for(rows, reply)+ new_rows, _trailing = split_history(capture, [*rows, reply, tool("c1", "r1"), tool("c1", "r2")])+ self.assertEqual(len(new_rows), 3)+ with self.assertRaises(WarmRefusal):+ split_history(capture, [*rows, reply, tool("c1", "r1"), tool("c1", "r2"), tool("c1", "r3")])+ with self.assertRaises(WarmRefusal):+ split_history(capture, [*rows, reply, tool("c1", "r1")])++class ApiContentHistoryTest(unittest.TestCase):def test_the_reply_matches_by_its_api_content(self):rows = history()@@ -272,6 +285,28 @@ class BuildRequestTest(unittest.TestCase):self.build(capture)self.assertEqual(caught.exception.code, "source_transform_unsupported")+ def test_refuses_a_changed_json_type_in_arguments(self):+ for old, new in (('{"path":"a","force":true}', '{"path":"a","force":1}'),+ ('{"path":"a","n":0}', '{"path":"a","n":false}')):+ rows = [user("u1"), assistant("", [("c0", "read", old)]), tool("c0", "r0"), user("u2")]+ self.rows, self.messages = rows, [*rows, self.reply, tool("c1", "r1"), user("u3")]+ capture = capture_for(self.rows, self.reply)+ capture["body"]["messages"][2]["tool_calls"][0]["function"]["arguments"] = new+ with self.subTest(new=new), self.assertRaises(WarmRefusal) as caught:+ self.build(capture)+ self.assertEqual(caught.exception.code, "source_transform_unsupported")++ def test_appended_rows_keep_reasoning_details_on_a_replaying_route(self):+ details = [{"type": "reasoning.encrypted", "data": "abc"}, {"type": "x.native_assistant", "data": "n"}]+ reply = assistant("", [("c1", "read", "{}")], reasoning_details=details)+ self.messages = [*self.rows, reply, tool("c1", "r1")]+ for base_url, expected in (("https://openrouter.ai/api/v1", [details[0]]), ("https://api.example.com/v1", None)):+ route = (ROUTE[0], base_url, ROUTE[2])+ sent = build_request(capture_for(self.rows, self.reply, route=route), self.messages, route, 100_000,+ INSTRUCTION)["messages"][-3]+ with self.subTest(base_url=base_url):+ self.assertEqual(sent.get("reasoning_details"), expected)+def test_accepts_request_time_context_and_reformatted_arguments(self):capture = self._tool_round()sent = capture["body"]["messages"]diff --git a/warm_compaction/capture.py b/warm_compaction/capture.pyindex 3a5c3b0..6504f6b 100644--- a/warm_compaction/capture.py+++ b/warm_compaction/capture.py@@ -38,6 +38,20 @@ def final_body(request: Any) -> dict[str, Any]:raise UnsupportedRequest("request_not_json") from error+def unique_call_ids(calls: list[list[str]]) -> list[list[str]]:+ """Give a repeated tool-call id the name that Hermes gives it after this hook runs: the second c1 becomes+ c1_d2, the third c1_d3 (agent.message_sanitization.uniquify_tool_call_ids of Hermes 45871e10)."""+ seen: set[str] = set()+ out = []+ for call_id, name in calls:+ if call_id and call_id in seen:+ call_id = next(f"{call_id}_d{n}" for n in range(2, len(seen) + 3) if f"{call_id}_d{n}" not in seen)+ if call_id:+ seen.add(call_id)+ out.append([call_id, name])+ return out++class CaptureStore:"""Keeps the latest usable main-model request of each session, in memory only."""@@ -105,7 +119,8 @@ class CaptureStore:reply = {"role": "assistant","content": plain_text(attr(assistant_message, "content")),- "tool_calls": [[call_id, name] for call_id, name, _arguments in tool_calls_of(assistant_message)],+ "tool_calls": unique_call_ids(+ [[call_id, name] for call_id, name, _arguments in tool_calls_of(assistant_message)]),}except Exception:return Nonediff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 05fa83e..2f4f75e 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -2,10 +2,12 @@from __future__ import annotations+import collectionsimport copyimport jsonimport timeimport urllib.error+import urllib.parseimport urllib.requestfrom typing import Any, Callable@@ -49,14 +51,15 @@ def split_history(capture: dict[str, Any], messages: list) -> tuple[list, list]:rest = messages[count:]if not _matches_reply(rest[0], capture["reply"]):raise WarmRefusal("history_changed")- expected = {call_id for call_id, _name in capture["reply"]["tool_calls"]}- answered: set = set()+ # A multiset: one tool row for each tool call, also when an id repeats.+ expected = collections.Counter(call_id for call_id, _name in capture["reply"]["tool_calls"])+ answered: collections.Counter = collections.Counter()index = 1while index < len(rest) and attr(rest[index], "role") == "tool":call_id = attr(rest[index], "tool_call_id")- if call_id not in expected or call_id in answered:+ if answered[call_id] >= expected[call_id]:raise WarmRefusal("history_changed")- answered.add(call_id)+ answered[call_id] += 1index += 1if answered != expected:raise WarmRefusal("history_changed")@@ -107,14 +110,16 @@ def _parts(content: Any) -> tuple[list[str], list]:return runs, media-def _arguments(value: Any) -> Any:- """Return the JSON value of tool-call arguments, so that a change of spacing or key order is not a change."""+def _arguments(value: Any) -> tuple[str, str]:+ """Return a canonical form of tool-call arguments: a change of spacing or key order is not a change, but a+ change of a JSON type is (true and 1 are different, which Python == does not see). Text that is not JSON+ stays as it is."""if isinstance(value, str):try:- return json.loads(value)+ value = json.loads(value)except ValueError:- return " ".join(value.split())- return value+ return "text", value+ return "json", json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)def _same_row(wire: Any, row: Any) -> bool:@@ -190,10 +195,31 @@ def _signature(extra: Any) -> Any:return copy.deepcopy(extra) if isinstance(candidate, str) and candidate.strip() else None-def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None) -> dict[str, Any]:+REPLAY_DETAILS_HOSTS = ("openrouter.ai", "nousresearch.com")+++def _route_replays_reasoning_details(base_url: Any) -> bool:+ """Hermes 45871e10 (agent.transports.chat_completions): only OpenRouter and the Nous Portal read replayed+ reasoning_details; strict routes reject the field."""+ host = (urllib.parse.urlparse(str(base_url or "")).hostname or "").lower()+ return any(host == name or host.endswith("." + name) for name in REPLAY_DETAILS_HOSTS)+++def _replay_details(details: Any) -> list | None:+ """Return reasoning_details without private native-assistant carriers (the profile that reads them is not+ known here), or None when nothing is left."""+ if not isinstance(details, list):+ return None+ kept = [copy.deepcopy(item) for item in details if not (+ isinstance(item, dict) and isinstance(item.get("type"), str) and item["type"].endswith(".native_assistant"))]+ return kept or None+++def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_url: Any = None) -> dict[str, Any]:"""Return the wire form of a stored row, as Hermes sends it: only the fields that the API reads, theapi_content sidecar of a user or assistant row in place of its content, reasoning_content on an assistant- row when the route needs it, and the thought signature (extra_content) of a tool call for a Gemini model."""+ row when the route needs it, the thought signature (extra_content) of a tool call for a Gemini model, and+ reasoning_details of an assistant row on a route that replays 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)@@ -216,6 +242,12 @@ def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None) -> dict[extra = _signature(attr(source, "extra_content")) if consumes else Noneif extra is not None:call["extra_content"] = extra+ if attr(row, "role") == "assistant" and hermes_value(+ "agent.transports.chat_completions", "_route_replays_reasoning_details",+ _route_replays_reasoning_details)(base_url):+ details = _replay_details(attr(row, "reasoning_details"))+ if details is not None:+ wire["reasoning_details"] = detailsif isinstance(row, dict):policy = hermes_value("agent.message_sanitization", "apply_reasoning_content_policy", _reasoning_policy)policy(row, wire, reasoning_echo)@@ -256,7 +288,7 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, contextrequest = dict(body)# Send the trailing user rows too: the tail can keep only the newest of them, and compaction removes the others.echo = needs_reasoning_echo(body, new_rows)- added = [wire_row(row, echo, body.get("model")) for row in (*new_rows, *trailing)]+ added = [wire_row(row, echo, body.get("model"), route[1]) for row in (*new_rows, *trailing)]request["messages"] = [*body["messages"], *added, {"role": "user", "content": instruction}]request["stream"] = Falserequest.pop("stream_options", None)