Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Tie the capture to the resolved key, and replay the native reasoning carrier of the provider profile
Elevatormusic690946451cd3
diff --git a/README.md b/README.mdindex 7cb02fa..b52847c 100644--- a/README.md+++ b/README.md@@ -198,10 +198,10 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and- 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 it, also while the warm request is on the network: the history stays unchanged (`route_changed` or `cancelled`).-- A provider or API key switch forgets the capture of the session: the next compaction uses the fallback summary (`no_capture`) until a main request on the new configuration completes.+- A provider or API key switch forgets the capture of the session: the next compaction uses the fallback summary (`no_capture`) until a main request on the new configuration completes. A key that Hermes gives as a function can change without a switch (a token that refreshes or rotates): the capture keeps a digest of the key that sent it, never the key, and the warm request is not sent with another key (reason `credential_changed`). A key change while a request is open keeps no capture.- A captured row with a field that Hermes does not send for the stored row (other than the prompt caching marker `cache_control`) refuses the warm path (`source_transform_unsupported`).- 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`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. 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 its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. 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), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model or into the fixed summary. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. 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, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.+- The verbatim tail keeps the newest rows that fit in `tail_tokens`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. 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 its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. 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), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; the native-assistant entry type that the provider profile declares (`native_reasoning_details_type`) counts on every route of the provider, as Hermes replays it; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model or into the fixed summary. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. 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, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. 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`).- After `/compress`, Hermes builds the system prompt again from its configuration. A system message that a host gave in code is not kept. This is Hermes behavior, and it is the same for the built-in compressor.diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex 68dbfd9..03f7720 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-06T18:22:56Z",+ "started_utc": "2026-10-06T18:32:21Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -9,14 +9,14 @@"script_sha256": "08a2bedce89ede3a05576013351c1397e00bef0d50a24e28c9b6c0168d86c8ae","plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",- "warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "250f54624a6ca983c38221ce22acb223b5f3ba906081aa0ca17d59c149a24cc2",+ "warm_compaction/capture.py": "971abfe0751437701c030be8c23a1c33b5380e06db87cb696bc951ea080007cc",+ "warm_compaction/engine.py": "fe1b935cf1f347b582d67edb9ffd81dfc3b3d47ee52a7bacc642b2545e666ab3","warm_compaction/fallback.py": "f62143b7576fdaeb1ffda9d871fc0bf062b536a817f89841f6722d9a7ce9db07","warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2","warm_compaction/layout.py": "540526e1ece17675138820572187c956474b53a099f3fc3ddd900118b763be9a","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",- "warm_compaction/rows.py": "acba1ae0bed41c38041d1149f825a5f2c6552d2dd20549266bd2c11f1da4ba50",- "warm_compaction/warm.py": "657dd7d496e7cf64190a21a920c202a3aea2ab3cf06eb045c05b22ae25969d10"+ "warm_compaction/rows.py": "f2ca69a7361affc4fd84388ab9ac718a0e9affa609c87d75efd6e0c25fa860cf",+ "warm_compaction/warm.py": "e58399a9449e52dda63bc2edad856c41069cdef2c7c29fbc38e5b484b2e4b2a8"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text","scenarios": [@@ -76,11 +76,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.12,+ "compress_seconds": 0.107,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.027,+ "elapsed_s": 0.028,"prompt_tokens": 33892,"cached_tokens": 16946},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 54.14+ "process_seconds": 52.13},{"scenario": "manual_fallback",@@ -248,7 +248,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.24,+ "compress_seconds": 0.253,"warm_last": {"path": "fallback","reason": "provider_error",@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 33.142+ "process_seconds": 32.834},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.237,+ "compress_seconds": 0.303,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.109,+ "elapsed_s": 0.188,"prompt_tokens": null,"cached_tokens": null},@@ -431,7 +431,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": [@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 30.59+ "process_seconds": 31.942},{"scenario": "auto_tool_loop",@@ -620,14 +620,14 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 35209,"cached_tokens": 17604},"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.0,+ "elapsed_s": 0.016,"prompt_tokens": 19504,"cached_tokens": 9752},@@ -737,7 +737,7 @@"install","run"],- "process_seconds": 33.527+ "process_seconds": 33.732},{"scenario": "rollback",@@ -787,11 +787,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.146,+ "compress_seconds": 0.141,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 33882,"cached_tokens": 16941},@@ -973,10 +973,10 @@"run","rollback"],- "process_seconds": 37.468+ "process_seconds": 38.472}],- "finished_utc": "2026-10-06T18:26:05Z",+ "finished_utc": "2026-10-06T18:35:30Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 09eca88..485d22e 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -64,12 +64,15 @@ class EngineTest(unittest.TestCase):provider="custom", api_mode=ROUTE[2])return engine- def seed(self, rows, reply, session="s1", system=SYSTEM, extra=None):- """Run one main-model request through the capture store, in the Hermes order."""+ def seed(self, rows, reply, session="s1", system=SYSTEM, extra=None, during=None):+ """Run one main-model request through the capture store, in the Hermes order. during runs while the+ request is open."""self.store.on_pre_api_request(api_request_id="r1", session_id=session, conversation_history=list(rows),model=ROUTE[0], base_url=ROUTE[1], api_mode=ROUTE[2])self.store.on_llm_execution(request={"model": ROUTE[0], "messages": [system, *wire(rows)], **(extra or {})},next_call=lambda: None, api_request_id="r1")+ if during is not None:+ during()self.store.on_post_api_request(api_request_id="r1", session_id=session,finish_reason="tool_calls" if reply.get("tool_calls") else "stop",assistant_message=reply_object(reply))@@ -478,6 +481,70 @@ class EngineTest(unittest.TestCase):layout.build = realself.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("cancelled", "route_changed"))+ def callable_key_engine(self, keys):+ # Hermes can give the key as a function (a token that refreshes or rotates).+ engine = self.engine_class(store=self.store, llm=self.llm, post=self.post)+ engine.on_session_start("s1", platform="cli")+ engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key=lambda: keys[0],+ provider="custom", api_mode=ROUTE[2])+ return engine++ def test_a_callable_key_that_does_not_change_keeps_the_warm_path(self):+ keys = ["tenant-a"]+ engine = self.callable_key_engine(keys)+ rows, reply = old_turns(), assistant("final")+ self.seed(rows, reply)+ self.assertNotIn("tenant-a", json.dumps(self.store.latest("s1"), default=str))+ engine.compress([*rows, reply])+ self.assertEqual(engine.warm_last["path"], "warm")+ self.assertEqual(self.post.calls[0]["headers"]["Authorization"], "Bearer tenant-a")++ def test_a_callable_key_that_changes_after_the_capture_stops_the_warm_request(self):+ # The same function object with a new value: the old body must not go out with another credential.+ keys = ["tenant-a"]+ engine = self.callable_key_engine(keys)+ rows, reply = old_turns(), assistant("final")+ self.seed(rows, reply)+ keys[0] = "tenant-b"+ engine.compress([*rows, reply])+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("fallback", "credential_changed"))+ self.assertEqual(self.post.calls, [])++ def test_a_key_change_during_the_request_keeps_no_capture(self):+ keys = ["tenant-a"]+ self.callable_key_engine(keys)+ self.seed(old_turns(1), assistant("x"), during=lambda: keys.__setitem__(0, "tenant-b"))+ self.assertIsNone(self.store.latest("s1"))++ def test_a_capture_without_a_key_stamp_is_not_sent(self):+ # A store without the stamp function of the session cannot show which key sent the capture.+ rows, reply = old_turns(), assistant("final")+ store = type(self.store)()+ engine = self.engine_class(store=store, llm=self.llm, post=self.post)+ engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ engine._wc_session_id = "s1"+ wc_hermes_stub.CAPTURE_CHAIN.append(store.on_llm_execution)+ self.store = store+ self.seed(rows, reply)+ engine.compress([*rows, reply])+ self.assertEqual(engine.warm_last["reason"], "credential_changed")+ self.assertEqual(self.post.calls, [])++ def test_the_native_carrier_of_the_provider_profile_keeps_the_warm_path(self):+ # The profile declares the carrier that Hermes replays: the captured body has it, and the estimate counts it.+ from warm_compaction.rows import SendPolicy, sent_tokens+ wc_hermes_stub.PROFILE_FIELDS["native_reasoning_details_type"] = "acme.native_assistant"+ rows = old_turns()+ rows[1] = {**rows[1], "reasoning_details": [{"type": "acme.native_assistant", "data": "n" * 4_000}]}+ reply = assistant("final")+ self.seed(rows, reply)+ policy = self.engine._policy([*rows, reply])+ self.assertEqual((policy.native_type, policy.details), ("acme.native_assistant", True))+ self.assertGreater(sent_tokens(rows[1], policy), sent_tokens(rows[1], SendPolicy(echo=False)) + 900)+ self.engine.compress([*rows, reply])+ self.assertEqual(self.engine.warm_last["path"], "warm")+def test_an_unusable_capture_does_not_set_the_reasoning_rule(self):# The capture is of this route, but its rows are not the stored rows: it does not show what the next# request replays. The stored rows with reasoning_content do.diff --git a/tests/test_wc_rows.py b/tests/test_wc_rows.pyindex 6f8ae38..de405cf 100644--- a/tests/test_wc_rows.py+++ b/tests/test_wc_rows.py@@ -82,9 +82,13 @@ class SentRowsTest(unittest.TestCase):self.assertGreater(sent_tokens(details), small + 900)from warm_compaction.rows import SendPolicyself.assertEqual(sent_tokens(details, SendPolicy(details=False, echo=False)), small)- # The private native-assistant carriers are not replayed (warm._replay_details).+ # The private native-assistant carriers are not replayed (warm._replay_details), except the carrier of+ # the provider profile (native_reasoning_details_type).native = {**base, "reasoning_details": [{"type": "anthropic.native_assistant", "text": "n" * 8_000}]}self.assertEqual(sent_tokens(native, SendPolicy(echo=False)), small)+ self.assertEqual(sent_tokens(native, SendPolicy(echo=False, native_type="other.native_assistant")), small)+ self.assertGreater(sent_tokens(native, SendPolicy(echo=False, native_type="anthropic.native_assistant")),+ small + 1_900)def test_the_estimate_uses_the_tool_call_fields_that_hermes_sends(self):# wire_row: id, type, and function name and arguments; the thought signature only for a model that reads it.diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex c4f5462..5fe6abc 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -170,6 +170,23 @@ class BuildRequestTest(unittest.TestCase):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_the_native_carrier_of_the_provider_profile_is_replayed(self):+ # Hermes 45871e10 replays the <provider>.native_assistant carrier that the provider profile declares+ # (native_reasoning_details_type), also on a route that does not replay other reasoning_details.+ from warm_compaction.warm import WarmRefusal, check_source, wire_row+ from wc_fixtures import SYSTEM, wire+ carrier = [{"type": "acme.native_assistant", "data": "n"}]+ row = assistant("a1", reasoning_details=carrier)+ self.assertNotIn("reasoning_details", wire_row(row, base_url=ROUTE[1]))+ self.assertNotIn("reasoning_details", wire_row(row, base_url=ROUTE[1], native_type="other.native_assistant"))+ self.assertEqual(wire_row(row, base_url=ROUTE[1], native_type="acme.native_assistant")["reasoning_details"],+ carrier)+ rows = [user("u1"), row, user("u2")]+ body = {"model": ROUTE[0], "messages": [SYSTEM, *wire(rows)]}+ check_source(body, rows, ROUTE[1], native_type="acme.native_assistant")+ with self.assertRaises(WarmRefusal):+ check_source(body, rows, ROUTE[1])+def test_appended_tool_calls_keep_the_gemini_thought_signature(self):signed = {"google": {"thought_signature": "sig-1"}}reply = assistant("", [("c1", "read", "{}")])diff --git a/tests/wc_hermes_stub.py b/tests/wc_hermes_stub.pyindex 636bdce..c770619 100644--- a/tests/wc_hermes_stub.py+++ b/tests/wc_hermes_stub.py@@ -101,6 +101,8 @@ AGENT.context_compressor = CONTEXT_COMPRESSOR# factory or the provider profile, then model.default_headers, then providers.<name>.extra_headers.HOST_HEADERS: dict = {}PROFILE_HEADERS: dict = {}+# Other fields of the provider profile (native_reasoning_details_type, for example).+PROFILE_FIELDS: dict = {}USER_HEADERS: dict = {}CUSTOM_HEADERS: dict = {}# The value that agent.ssl_verify.resolve_httpx_verify gives (True, False, or an SSL context); an exception@@ -122,7 +124,8 @@ AGENT_INIT = _module("agent.agent_init", _host_default_headers_factory=lambda baAUXILIARY_CLIENT = _module("agent.auxiliary_client", _apply_user_default_headers=lambda headers: ({**(headers or {}), **USER_HEADERS} if USER_HEADERS else headers))PROVIDERS = _module("providers", get_provider_profile=lambda name: (- SimpleNamespace(default_headers=dict(PROFILE_HEADERS)) if PROFILE_HEADERS else None))+ SimpleNamespace(default_headers=dict(PROFILE_HEADERS), **PROFILE_FIELDS)+ if PROFILE_HEADERS or PROFILE_FIELDS else None))AGENT.agent_init = AGENT_INITAGENT.auxiliary_client = AUXILIARY_CLIENTHERMES_CLI = _module("hermes_cli")@@ -195,5 +198,5 @@ def install(test_case):test_case.addCleanup(EXECUTION_MIDDLEWARE.clear)test_case.addCleanup(REQUEST_MIDDLEWARE.clear)test_case.addCleanup(CAPTURE_CHAIN.clear)- for headers in (HOST_HEADERS, PROFILE_HEADERS, USER_HEADERS, CUSTOM_HEADERS, TLS_VERIFY):+ for headers in (HOST_HEADERS, PROFILE_HEADERS, PROFILE_FIELDS, USER_HEADERS, CUSTOM_HEADERS, TLS_VERIFY):test_case.addCleanup(headers.clear)diff --git a/warm_compaction/capture.py b/warm_compaction/capture.pyindex 04b8acd..d28dc82 100644--- a/warm_compaction/capture.py+++ b/warm_compaction/capture.py@@ -3,6 +3,7 @@from __future__ import annotationsimport copy+import hashlibimport jsonimport threadingimport time@@ -17,6 +18,12 @@ CLIENT_OPTIONS = ("extra_body", "extra_headers", "extra_query", "timeout")CAPTURE_FINISH = ("stop", "tool_calls")+def key_stamp(key: str) -> str:+ """A digest of a resolved API key. A capture keeps it, never the key: the capture belongs to the key that+ sent it."""+ return hashlib.sha256(key.encode("utf-8")).hexdigest()++class UnsupportedRequest(ValueError):"""The request body cannot become a warm request. The message is the reason code."""@@ -60,10 +67,31 @@ class CaptureStore:self._lock = threading.Lock()self._open: OrderedDict[str, dict[str, Any]] = OrderedDict()self._sessions: OrderedDict[str, dict[str, Any]] = OrderedDict()+ self._stamps: OrderedDict[str, Callable[[], Any]] = OrderedDict()self._max_open = max_openself._max_sessions = max_sessionsself._clock = clock+ def set_stamp(self, session_id: Any, stamp: Callable[[], Any]) -> None:+ """Keep the function that gives the key stamp (key_stamp) of a session now. Hermes can give the key as a+ function whose value changes (a token that refreshes or rotates), and the hooks do not get the key. A+ request keeps its capture only when the stamp is the same at its start and at its end."""+ key = str(session_id or "")+ with self._lock:+ self._stamps[key] = stamp+ self._stamps.move_to_end(key)+ while len(self._stamps) > self._max_sessions:+ self._stamps.popitem(last=False)++ def _stamp(self, session_id: Any) -> str | None:+ with self._lock:+ stamp = self._stamps.get(str(session_id or ""))+ try:+ value = stamp() if stamp is not None else None+ except Exception:+ return None+ return value if isinstance(value, str) else None+def on_pre_api_request(self, api_request_id: Any = None, session_id: Any = None,conversation_history: Any = None, model: Any = None, base_url: Any = None,api_mode: Any = None, **_: Any) -> None:@@ -75,7 +103,7 @@ class CaptureStore:except Exception:return Noneentry = {"session_id": str(session_id), "route": (model, base_url, api_mode), "digests": digests, "body": None,- "refusal": None}+ "refusal": None, "key_stamp": self._stamp(session_id)}with self._lock:self._open[str(api_request_id)] = entryself._open.move_to_end(str(api_request_id))@@ -140,6 +168,9 @@ class CaptureStore:return Noneif finish_reason not in CAPTURE_FINISH or assistant_message is None:return None+ # A key that changed while the request was open: the request can have gone out with either key.+ if self._stamp(entry["session_id"]) != entry["key_stamp"]:+ return Nonetry:reply = {"role": "assistant",diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 35ea4bd..ff845af 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -10,7 +10,7 @@ from typing import Any, Callablefrom agent.context_engine import ContextEnginefrom . import fallback, handoff, layout, warm-from .capture import CaptureStore+from .capture import CaptureStore, key_stampfrom .rows import SendPolicy, api_content, attr, estimate_tokens, hermes_value, sent_rows, sent_tokenslogger = logging.getLogger(__name__)@@ -161,6 +161,11 @@ class WarmCompactionEngine(ContextEngine):if kwargs.get("boundary_reason") == "compression" and kwargs.get("old_session_id"):self._store.forget(session_id=kwargs["old_session_id"])self._wc_session_id = str(session_id or "")+ # The hooks do not get the key: the store asks the engine for the stamp of the key now.+ self._store.set_stamp(self._wc_session_id, self._key_stamp)++ def _key_stamp(self) -> str:+ return key_stamp(warm.api_key_text(self._wc_api_key))def update_model(self, model: str, context_length: int, base_url: str = "", api_key: Any = "",provider: str = "", api_mode: str = "") -> None:@@ -373,11 +378,12 @@ class WarmCompactionEngine(ContextEngine):else:echo, known = warm.needs_reasoning_echo({}, messages), Falsemodule = "agent.transports.chat_completions"+ native = warm.native_details_type(self._wc_provider)return SendPolicy(# Without a capture, stored reasoning can be of an earlier route: count it, but do not cut it.- echo=echo, cut_reasoning=known,- details=bool(hermes_value(module, "_route_replays_reasoning_details",- warm._route_replays_reasoning_details)(self._wc_route[1])),+ echo=echo, cut_reasoning=known, native_type=native,+ details=bool(native) or bool(hermes_value(module, "_route_replays_reasoning_details",+ warm._route_replays_reasoning_details)(self._wc_route[1])),signatures=bool(hermes_value(module, "_model_consumes_thought_signature",warm._model_consumes_thought_signature)(self._wc_route[0])))@@ -402,12 +408,18 @@ class WarmCompactionEngine(ContextEngine):raise warm.WarmRefusal("disabled")if capture is None:raise warm.WarmRefusal("no_capture")+ # The capture belongs to the key that sent it. Hermes can give the key as a function whose value+ # changes (a token that refreshes or rotates): resolve it one time, for this check and the request.+ key = warm.api_key_text(attempt[1])+ if capture.get("key_stamp") != key_stamp(key):+ raise warm.WarmRefusal("credential_changed")instruction = handoff.build_instruction(focus_topic, memory)- body = warm.build_request(capture, messages, attempt[0], self.context_length, instruction)+ body = warm.build_request(capture, messages, attempt[0], self.context_length, instruction,+ warm.native_details_type(attempt[2]))if self._cancelled():raise warm.WarmRefusal("cancelled")reply = self._execute(body, instruction, len(capture["body"]["messages"]), attempt,- capture.get("prompt_tokens"))+ capture.get("prompt_tokens"), key)record.update(prompt_tokens=reply["prompt_tokens"], cached_tokens=reply["cached_tokens"])text, reason = handoff.gate(reply, prefixes)if text is None:@@ -422,7 +434,7 @@ class WarmCompactionEngine(ContextEngine):return textdef _execute(self, body: dict[str, Any], instruction: str, captured: int, attempt: tuple,- measured: int | None = None) -> dict[str, Any]:+ measured: int | None = None, key: str | None = None) -> dict[str, Any]:"""Send the warm request through the Hermes llm_request and llm_execution middleware, as Hermes sends amain request. A request middleware can change the request, for example to redact the new rows. Anexecution middleware can audit, block, or replace the request. A block, a rewrite, or a replaced reply@@ -434,7 +446,9 @@ class WarmCompactionEngine(ContextEngine):raise warm.WarmRefusal("middleware_unavailable") from error# Before any middleware sees the request: a route without its headers does not send it.route, api_key, provider, session_id = attempt[:4]- headers = warm.route_headers(api_key, route[1], provider)+ # The key that the capture check used (_warm_summary): a key function is not read again.+ key = warm.api_key_text(api_key) if key is None else key+ headers = warm.route_headers(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]}@@ -482,7 +496,7 @@ class WarmCompactionEngine(ContextEngine):if self._attempt() != attempt:raise warm.WarmRefusal("route_changed")started.append(True)- result = warm.send(base, route[1], api_key, post=self._post, extra_headers=headers, ssl_context=tls)+ result = warm.send(base, route[1], key, post=self._post, extra_headers=headers, ssl_context=tls)# The send blocks on the network: a switch can occur before it returns.if self._attempt() != attempt:raise warm.WarmRefusal("route_changed")@@ -568,7 +582,8 @@ class WarmCompactionEngine(ContextEngine):return Nonetry:warm.split_history(capture, messages)- warm.check_source(body, messages[: len(capture["digests"])], self._wc_route[1])+ warm.check_source(body, messages[: len(capture["digests"])], self._wc_route[1],+ warm.native_details_type(self._wc_provider))except Exception:return Nonereturn capturediff --git a/warm_compaction/rows.py b/warm_compaction/rows.pyindex 4baad50..829f645 100644--- a/warm_compaction/rows.py+++ b/warm_compaction/rows.py@@ -110,11 +110,14 @@ class SendPolicy(NamedTuple):thought signature, extra_content (a model that reads it), and reasoning_content (a route that needs it back,apply_reasoning_content_policy). The default counts all of them. cut_reasoning: a cut can take reasoning(layout.bound_tail) only when a capture of the route shows that the route sends it; else stored reasoning can- be of an earlier route, and a cut would give it to the fallback model."""+ be of an earlier route, and a cut would give it to the fallback model. native_type: the private+ <provider>.native_assistant carrier that the provider profile declares (native_reasoning_details_type); Hermes+ replays it, and only it of the native carriers."""details: bool = Truesignatures: bool = Trueecho: bool = Truecut_reasoning: bool = True+ native_type: str | None = Nonedef reasoning_policy(source: dict, wire: dict, needs_pad: bool) -> None:@@ -156,13 +159,14 @@ def has_thought_signature(extra: Any) -> bool:return isinstance(candidate, str) and bool(candidate.strip())-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. The items are not copied."""+def replay_details(details: Any, native_type: str | None = None) -> list | None:+ """Return reasoning_details without private native-assistant carriers, except the carrier of the provider+ profile (native_type), or None when nothing is left. The items are not copied."""if not isinstance(details, list):return Nonekept = [item for item in details if not (- isinstance(item, dict) and isinstance(item.get("type"), str) and item["type"].endswith(".native_assistant"))]+ isinstance(item, dict) and isinstance(item.get("type"), str) and item["type"].endswith(".native_assistant")+ and item["type"] != native_type)]return kept or None@@ -190,7 +194,7 @@ def sent_rows(messages: list, policy: SendPolicy = SendPolicy()) -> list:if calls:sent["tool_calls"] = callsif policy.details and role == "assistant":- details = replay_details(row.get("reasoning_details"))+ details = replay_details(row.get("reasoning_details"), policy.native_type)if details is not None:sent["reasoning_details"] = detailsreasoning(row, sent, policy.echo)diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 519250a..4a7dece 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -177,7 +177,8 @@ def _same_replay_fields(wire: Any, expected: dict[str, Any]) -> bool:call.get("extra_content") for call in expected.get("tool_calls") or []]-def check_source(body: dict[str, Any], history_rows: list, base_url: Any = None) -> None:+def check_source(body: dict[str, Any], history_rows: list, base_url: Any = None,+ native_type: str | None = None) -> None:"""Refuse a request whose messages are not system rows followed by the stored rows. A row that a hook ora middleware rewrote would make the handoff summarize text that is not in the history it replaces."""sent = body["messages"]@@ -188,7 +189,7 @@ def check_source(body: dict[str, Any], history_rows: list, base_url: Any = None)raise WarmRefusal("source_transform_unsupported")# The replayed fields follow the captured request only: the new rows do not change what Hermes sent.echo = needs_reasoning_echo(body, [])- expected = [wire_row(row, echo, body.get("model"), base_url) for row in history_rows]+ expected = [wire_row(row, echo, body.get("model"), base_url, native_type) for row in history_rows]if not all(_same_replay_fields(wire, want) and _no_extra_fields(wire, want)for wire, want in zip(sent[offset:], expected)):raise WarmRefusal("source_transform_unsupported")@@ -243,17 +244,32 @@ def _route_replays_reasoning_details(base_url: Any) -> bool:return any(host == name or host.endswith("." + name) for name in REPLAY_DETAILS_HOSTS)-def _replay_details(details: Any) -> list | None:- """A copy of rows.replay_details: reasoning_details without private native-assistant carriers, or None."""- kept = replay_details(details)+def native_details_type(provider: Any) -> str | None:+ """The native reasoning carrier type of the provider profile (native_reasoning_details_type of Hermes+ 45871e10), or None. Hermes replays that carrier on every route of the provider."""+ try:+ from providers import get_provider_profile+ profile = get_provider_profile(provider) if provider else None+ value = getattr(profile, "native_reasoning_details_type", None)+ except Exception:+ return None+ return value if isinstance(value, str) and value else None+++def _replay_details(details: Any, native_type: str | None = None) -> list | None:+ """A copy of rows.replay_details: reasoning_details without private native-assistant carriers, except the+ carrier of the provider profile, or None."""+ kept = replay_details(details, native_type)return copy.deepcopy(kept) if kept is not None else None-def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_url: Any = None) -> dict[str, Any]:+def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_url: Any = None,+ native_type: str | None = 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 assistantrow 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."""+ reasoning_details of an assistant row on a route that replays it or for a provider profile with a native+ carrier type (native_type: that carrier only of the native carriers)."""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)@@ -277,10 +293,10 @@ def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_urlextra = _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(+ if attr(row, "role") == "assistant" and (native_type or hermes_value("agent.transports.chat_completions", "_route_replays_reasoning_details",- _route_replays_reasoning_details)(base_url):- details = _replay_details(attr(row, "reasoning_details"))+ _route_replays_reasoning_details)(base_url)):+ details = _replay_details(attr(row, "reasoning_details"), native_type)if details is not None:wire["reasoning_details"] = detailsif isinstance(row, dict):@@ -364,8 +380,9 @@ def fits(body: dict[str, Any], context_length: int, measured_tokens: int | Nonedef build_request(capture: dict[str, Any], messages: list, route: tuple, context_length: int,- instruction: str) -> dict[str, Any]:- """Return the warm request body. Raise WarmRefusal when a condition is not true."""+ instruction: str, native_type: str | None = None) -> dict[str, Any]:+ """Return the warm request body. Raise WarmRefusal when a condition is not true. native_type: the native+ reasoning carrier type of the provider profile (native_details_type)."""if route[2] != "chat_completions":raise WarmRefusal("api_mode_unsupported")if tuple(capture["route"]) != tuple(route):@@ -375,11 +392,11 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, contextraise WarmRefusal(capture.get("refusal") or "settings_unsupported")check_settings(body)new_rows, trailing = split_history(capture, messages)- check_source(body, messages[: len(capture["digests"])], route[1])+ check_source(body, messages[: len(capture["digests"])], route[1], native_type)request = 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"), route[1]) for row in (*new_rows, *trailing)]+ added = [wire_row(row, echo, body.get("model"), route[1], native_type) for row in (*new_rows, *trailing)]request["messages"] = [*body["messages"], *_join_user_rows(added, instruction)]request["stream"] = Falserequest.pop("stream_options", None)@@ -433,7 +450,8 @@ def urllib_post(url: str, data: bytes, headers: dict[str, str], timeout_s: floatraise-def _api_key_text(api_key: Any) -> str:+def api_key_text(api_key: Any) -> str:+ """The key as text: the value of a key function now, or "" when it cannot be read."""if callable(api_key):try:api_key = api_key()@@ -468,7 +486,7 @@ def route_headers(api_key: Any, base_url: Any, provider: Any) -> dict[str, str]:from hermes_cli.config_providers import get_custom_provider_extra_headersfactory = _host_default_headers_factory(url)if factory is not None:- headers = dict(factory(_api_key_text(api_key), url) or {})+ headers = dict(factory(api_key_text(api_key), url) or {})else:from providers import get_provider_profileprofile = get_provider_profile(provider) if provider else None@@ -519,7 +537,7 @@ def send(body: dict[str, Any], base_url: str, api_key: Any, timeout_s: float = Tif not base_url:raise WarmRefusal("provider_error")headers = {"Content-Type": "application/json", "Accept": "application/json"}- key = _api_key_text(api_key)+ key = api_key_text(api_key)if key:headers["Authorization"] = f"Bearer {key}"headers.update(extra_headers or {})