Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Fit the prepended row, keep outer white space, use route TLS, and join user rows
Elevatormusic2cb8e922d435
diff --git a/README.md b/README.mdindex f2b5c17..07df043 100644--- a/README.md+++ b/README.md@@ -112,7 +112,7 @@ plugins:threshold: 0.5```-The warm request sends the whole earlier request again, plus the new rows and the reply reserve. The reply limit of the warm request is the `max_tokens` or `max_completion_tokens` value of the earlier request, kept between 2,048 and 8,192 tokens. The warm request sends the default headers of the Hermes client for the route: the provider headers, `model.default_headers`, and `providers.<name>.extra_headers`. Thus it must fit in the context window. At the default threshold, about half of the window stays free for it. If the request does not fit, the plugin uses the fallback summary (refusal code `capacity`). The plugin uses the prompt token count that the server reported for the earlier request, and estimates only the new rows.+The warm request sends the whole earlier request again, plus the new rows and the reply reserve. The reply limit of the warm request is the `max_tokens` or `max_completion_tokens` value of the earlier request, kept between 2,048 and 8,192 tokens. The warm request sends the default headers of the Hermes client for the route: the provider headers, `model.default_headers`, and `providers.<name>.extra_headers`. It uses the `ssl_ca_cert` of a custom provider route. A route with `ssl_verify: false` uses the fallback summary (refusal code `tls_unverified`): the plugin does not send without certificate checks. Thus it must fit in the context window. At the default threshold, about half of the window stays free for it. If the request does not fit, the plugin uses the fallback summary (refusal code `capacity`). The plugin uses the prompt token count that the server reported for the earlier request, and estimates only the new rows.## Fallback model and keys@@ -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_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `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.+- `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_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `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 a50d1ff..bb8ae02 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-06T11:27:57Z",+ "started_utc": "2026-10-06T11:49:06Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,13 +10,13 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "3021157e4bfabcd9dbfc48e42d2702d084a3cf6690ec207a7e87fe9b70137720",+ "warm_compaction/engine.py": "925ea1326a938f31565117a0a4b9d1d493f5d78c0e612177c707d6c845bd0cba","warm_compaction/fallback.py": "45dffdab8983292f4d6b7e5b7f60b7578078c8b1abb436c0e47acef3b2f77960","warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",- "warm_compaction/layout.py": "5e730211647eed0beec1e6819dfc008b0855a0866dc920bb0cf8d6d8ab2dfa92",+ "warm_compaction/layout.py": "2d7bb6a351fb25cdaa629a49c26f7b4c48e97b63164fa9f30f198bf47344d26b","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "cc2a8a3d0561559f24fc40881453441d938ea9d7803e1df81a107a5e05e5f00a",- "warm_compaction/warm.py": "ff83b4681f52afa9eb82cbdb5893e7165c2f93b2c644c7424aa57ec95ddd9260"+ "warm_compaction/warm.py": "7d439ad3ce7cc6cbf05bde64324f0ea65f097fc2b380169b05b12edc37147a77"},"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.253,+ "compress_seconds": 0.212,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.139,+ "elapsed_s": 0.13,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 66.713+ "process_seconds": 55.746},{"scenario": "manual_fallback",@@ -248,11 +248,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.518,+ "compress_seconds": 0.375,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.328,+ "elapsed_s": 0.219,"prompt_tokens": null,"cached_tokens": null},@@ -260,7 +260,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": [@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 41.703+ "process_seconds": 32.742},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.542,+ "compress_seconds": 0.335,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.312,+ "elapsed_s": 0.203,"prompt_tokens": null,"cached_tokens": null},@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 40.152+ "process_seconds": 29.894},{"scenario": "auto_tool_loop",@@ -620,14 +620,14 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.141,+ "elapsed_s": 0.109,"prompt_tokens": 35201,"cached_tokens": 17600},"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.156,+ "elapsed_s": 0.109,"prompt_tokens": 18427,"cached_tokens": 9213},@@ -737,7 +737,7 @@"install","run"],- "process_seconds": 46.077+ "process_seconds": 33.626},{"scenario": "rollback",@@ -787,7 +787,7 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.269,+ "compress_seconds": 0.26,"warm_last": {"path": "warm","reason": "accepted",@@ -950,7 +950,8 @@"stored": 30},"fence_denied": {- "child_process_blocked": 4+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -958,7 +959,9 @@"python","python3"],- "fence_blocked_hosts": []+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ]},"exit": [0,@@ -970,10 +973,10 @@"run","rollback"],- "process_seconds": 47.662+ "process_seconds": 37.635}],- "finished_utc": "2026-10-06T11:31:59Z",+ "finished_utc": "2026-10-06T11:52:15Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex e5e42ad..54c2aae 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -436,6 +436,22 @@ class EngineTest(unittest.TestCase):summary = next(row["content"] for row in new if "## Copied user messages" in str(row["content"]))self.assertFalse(summary.split("## Copied user messages", 1)[1].strip().startswith("(none)"))+ def test_a_large_prepended_user_row_is_cut_to_fit(self):+ # The newest user message is before the tail (it is larger than the tail) and goes in front of it. It+ # must fit below the threshold and the window less the reply reserve.+ from warm_compaction.rows import MIDDLE_MARK, estimate_tokens+ from warm_compaction.warm import DEFAULT_RESERVE+ rows = [*old_turns(4), user("BIG start " + "q" * 240_000 + " big end"),+ assistant("", [("c1", "read", "{}")]), tool("c1", "r1"), assistant("done")]+ engine = self.make(threshold=0.95, tail_tokens=2_000)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ new = engine.compress(rows, current_tokens=estimate_tokens(rows) + 1_000)+ prepended = next(row for row in new if str(row.get("content")).startswith("BIG start"))+ self.assertIn(MIDDLE_MARK, prepended["content"])+ self.assertTrue(prepended["content"].endswith(" big end"))+ self.assertLessEqual(estimate_tokens(new) + 1_000, min(engine.threshold_tokens, 64_000 - DEFAULT_RESERVE))+def test_without_a_capture_the_copies_leave_room_for_the_system_prompt_and_tools(self):# After a restart there is no capture. The system prompt and the tool schemas still take their space.from warm_compaction.rows import estimate_tokensdiff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 23eecf2..93b6845 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -7,7 +7,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom warm_compaction.rows import estimate_tokensfrom warm_compaction.warm import (- DEFAULT_RESERVE, HANDOFF_MAX_TOKENS, HANDOFF_MIN_TOKENS, SAFETY, WarmRefusal, build_request, check_settings, fits, send, split_history, urllib_post,+ DEFAULT_RESERVE, HANDOFF_MAX_TOKENS, ends_with_instruction, HANDOFF_MIN_TOKENS, SAFETY, WarmRefusal, build_request, check_settings, fits, send, split_history, urllib_post,wire_row,)from wc_fixtures import ROUTE, assistant, capture_for, tool, user@@ -148,9 +148,11 @@ class BuildRequestTest(unittest.TestCase):body = self.build(capture)sent = capture["body"]["messages"]self.assertEqual(json.dumps(body["messages"][: len(sent)]), json.dumps(sent))+ # The instruction joins the trailing user row: no two adjacent user rows.self.assertEqual(body["messages"][len(sent):], [- wire_row(self.reply), wire_row(tool("c1", "r1")), wire_row(user("u3")),- {"role": "user", "content": INSTRUCTION}])+ wire_row(self.reply), wire_row(tool("c1", "r1")), {"role": "user", "content": "u3\n\n" + INSTRUCTION}])+ self.assertTrue(ends_with_instruction(body["messages"][-1], INSTRUCTION))+ self.assertFalse(ends_with_instruction({"role": "user", "content": "u3"}, INSTRUCTION))self.assertEqual((body["stream"], body["temperature"]), (False, 0.2))self.assertNotIn("stream_options", body)@@ -218,9 +220,21 @@ class BuildRequestTest(unittest.TestCase):def test_sends_every_trailing_user_row(self):# The tail can keep only the newest of several user rows. The handoff must see the older ones too.+ # Strict chat templates refuse two adjacent user rows: they are joined, as Hermes joins them, and the+ # host instruction is the last block of the last user row.self.messages = [*self.messages, user("u4 " + "x" * 5_000)]body = self.build(capture_for(self.rows, self.reply))- self.assertEqual(body["messages"][-3:-1], [wire_row(user("u3")), wire_row(user("u4 " + "x" * 5_000))])+ self.assertEqual(body["messages"][-1], {"role": "user",+ "content": "u3\n\nu4 " + "x" * 5_000 + "\n\n" + INSTRUCTION})+ self.assertEqual(body["messages"][-2]["role"], "tool")+ roles = [row["role"] for row in body["messages"]]+ self.assertFalse(any(a == b == "user" for a, b in zip(roles, roles[1:])))++ def test_a_named_trailing_user_row_is_not_joined(self):+ self.messages = [*self.messages[:-1], user("u3", name="alice")]+ body = self.build(capture_for(self.rows, self.reply))+ self.assertEqual(body["messages"][-2:], [wire_row(user("u3", name="alice")),+ {"role": "user", "content": INSTRUCTION}])def test_refusal_codes(self):good = capture_for(self.rows, self.reply)@@ -378,7 +392,23 @@ class BuildRequestTest(unittest.TestCase):self.rows = [user("Delete A"), assistant("a1"), user("u2")]self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]for sent, accepted in (("Do not Delete A", False), ("Delete A now", False), ("Delete A\n\n[context]", True),- ("[context]\nDelete A", True), ("[a]\n\nDelete A \n\n[b]", True)):+ ("[context]\nDelete A", True), ("[a]\n\nDelete A\n\n[b]", True),+ ("[a]\n\nDelete A \n\n[b]", False)):+ capture = capture_for(self.rows, self.reply)+ capture["body"]["messages"][1]["content"] = sent+ with self.subTest(sent=sent):+ if accepted:+ self.build(capture)+ continue+ with self.assertRaises(WarmRefusal) as caught:+ self.build(capture)+ self.assertEqual(caught.exception.code, "source_transform_unsupported")++ def test_refuses_changed_white_space_around_the_stored_text(self):+ # A middleware that dedents the first line of a code fragment changes its meaning.+ self.rows = [user(" return 1\nx = 2"), assistant("a1"), user("u2")]+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]+ for sent, accepted in (("return 1\nx = 2", False), ("[ctx]\n\n return 1\nx = 2", True)):capture = capture_for(self.rows, self.reply)capture["body"]["messages"][1]["content"] = sentwith self.subTest(sent=sent):@@ -430,6 +460,48 @@ def fake_post(status, payload, calls):return post+class RouteTlsTest(unittest.TestCase):+ def setUp(self):+ import wc_hermes_stub+ wc_hermes_stub.install(self)+ self.stub = wc_hermes_stub++ def test_tls_of_the_route(self):+ import ssl+ from warm_compaction.warm import route_tls+ self.assertIsNone(route_tls("http://127.0.0.1:9/v1"))+ self.stub.TLS_VERIFY.append(True)+ self.assertIsNone(route_tls("https://h/v1"))+ # The plugin does not send without certificate checks (ssl_verify: false): the warm path stops.+ self.stub.TLS_VERIFY[:] = [False]+ with self.assertRaises(WarmRefusal) as caught:+ route_tls("https://h/v1")+ self.assertEqual(caught.exception.code, "tls_unverified")+ own = ssl.create_default_context()+ self.stub.TLS_VERIFY[:] = [own]+ self.assertIs(route_tls("https://h/v1"), own)++ def test_an_unreadable_tls_setting_stops_the_warm_request(self):+ from warm_compaction.warm import route_tls+ self.stub.TLS_VERIFY[:] = [RuntimeError("changed")]+ with self.assertRaises(WarmRefusal) as caught:+ route_tls("https://h/v1")+ self.assertEqual(caught.exception.code, "tls_unknown")++ def test_the_context_goes_to_the_post(self):+ import ssl+ context = ssl.create_default_context()+ seen = []++ def post(url, data, headers, timeout_s, context=None):+ seen.append(context)+ return 200, json.dumps({"choices": [{"message": {"content": "t"}, "finish_reason": "stop"}]}).encode()+ send({"messages": []}, "https://h/v1", "k", post=post, ssl_context=context)+ send({"messages": []}, "http://h/v1", "k", post=fake_post(200, {"choices": [+ {"message": {"content": "t"}, "finish_reason": "stop"}]}, []))+ self.assertEqual(seen, [context])++class SendTest(unittest.TestCase):def test_the_finish_reason_is_normalized(self):# Some OpenAI-compatible servers send STOP or MAX_TOKENS. The gate needs the contract value.diff --git a/tests/wc_hermes_stub.py b/tests/wc_hermes_stub.pyindex 0527171..636bdce 100644--- a/tests/wc_hermes_stub.py+++ b/tests/wc_hermes_stub.py@@ -103,6 +103,20 @@ HOST_HEADERS: dict = {}PROFILE_HEADERS: 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+# in it is raised.+TLS_VERIFY: list = []+++def resolve_httpx_verify(*, ca_bundle=None, ssl_verify=None, base_url=""):+ value = TLS_VERIFY[0] if TLS_VERIFY else True+ if isinstance(value, Exception):+ raise value+ return value+++SSL_VERIFY = _module("agent.ssl_verify", resolve_httpx_verify=resolve_httpx_verify)+AGENT.ssl_verify = SSL_VERIFYAGENT_INIT = _module("agent.agent_init", _host_default_headers_factory=lambda base_url: ((lambda api_key, base: dict(HOST_HEADERS)) if HOST_HEADERS else None))AUXILIARY_CLIENT = _module("agent.auxiliary_client", _apply_user_default_headers=lambda headers: (@@ -160,7 +174,8 @@ MIDDLEWARE = _module("hermes_cli.middleware", VALID_MIDDLEWARE={run_llm_execution_middleware=run_llm_execution_middleware,apply_llm_request_middleware=apply_llm_request_middleware)CONFIG_PROVIDERS = _module("hermes_cli.config_providers",- get_custom_provider_extra_headers=lambda base_url, *args, **kwargs: dict(CUSTOM_HEADERS))+ get_custom_provider_extra_headers=lambda base_url, *args, **kwargs: dict(CUSTOM_HEADERS),+ get_custom_provider_tls_settings=lambda base_url, *args, **kwargs: {})HERMES_CLI.config_providers = CONFIG_PROVIDERSHERMES_CLI.plugins = PLUGINSHERMES_CLI.middleware = MIDDLEWARE@@ -168,7 +183,7 @@ MODULES = {"agent": AGENT, "agent.context_engine": CONTEXT_ENGINE, "agent.context_compressor": CONTEXT_COMPRESSOR,"hermes_cli": HERMES_CLI, "hermes_cli.plugins": PLUGINS, "hermes_cli.middleware": MIDDLEWARE,"agent.agent_init": AGENT_INIT, "agent.auxiliary_client": AUXILIARY_CLIENT, "providers": PROVIDERS,- "hermes_cli.config_providers": CONFIG_PROVIDERS,+ "hermes_cli.config_providers": CONFIG_PROVIDERS, "agent.ssl_verify": SSL_VERIFY,}@@ -180,5 +195,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):+ for headers in (HOST_HEADERS, PROFILE_HEADERS, USER_HEADERS, CUSTOM_HEADERS, TLS_VERIFY):test_case.addCleanup(headers.clear)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex f00a1a5..21112d6 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -217,6 +217,10 @@ class WarmCompactionEngine(ContextEngine):overhead = request_overhead(budget, messages, current_tokens)copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead,request_reserve(budget))+ # The prepended user row must be in the tail: when it does not fit in the room, keep its start and end.+ room = self._room(messages[start:], summary, overhead or 0, request_reserve(budget))+ if prepend is not None and room is not None and estimate_tokens(prepend) > room:+ prepend = layout.fit_user_row(prepend, room)new = layout.build(messages, summary, start=start, prepend=prepend, copy_chars=int(self._settings["user_copy_chars"]),header_prefix=hermes_value("agent.context_compressor", "SUMMARY_PREFIX", handoff.LEGACY_PREFIX),@@ -235,11 +239,12 @@ class WarmCompactionEngine(ContextEngine):raise warm.WarmRefusal("disabled")if capture is None:raise warm.WarmRefusal("no_capture")- body = warm.build_request(capture, messages, self._wc_route, self.context_length,- handoff.build_instruction(focus_topic, memory))+ instruction = handoff.build_instruction(focus_topic, memory)+ body = warm.build_request(capture, messages, self._wc_route, self.context_length, instruction)if self._cancelled():raise warm.WarmRefusal("cancelled")- reply = self._execute(body, len(capture["body"]["messages"]), capture.get("prompt_tokens"))+ reply = self._execute(body, instruction, len(capture["body"]["messages"]),+ capture.get("prompt_tokens"))record.update(prompt_tokens=reply["prompt_tokens"], cached_tokens=reply["cached_tokens"])text, reason = handoff.gate(reply, prefixes)if text is None:@@ -253,7 +258,8 @@ class WarmCompactionEngine(ContextEngine):record.update(path="warm", reason="accepted")return text- def _execute(self, body: dict[str, Any], captured: int, measured: int | None = None) -> dict[str, Any]:+ def _execute(self, body: dict[str, Any], instruction: str, captured: int,+ measured: int | 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@@ -265,6 +271,7 @@ 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.headers = warm.route_headers(self._wc_api_key, self._wc_route[1], self._wc_provider)+ tls = warm.route_tls(self._wc_route[1])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:@@ -277,8 +284,9 @@ class WarmCompactionEngine(ContextEngine):# example, adds a system row) would apply twice and change the cached prefix. It can change the new rows.if ({k: v for k, v in changed.items() if k != "messages"} != {k: v for k, v in body.items() if k != "messages"}or changed["messages"][:captured] != body["messages"][:captured]- # The host instruction must stay the last row: without it, the reply is not a handoff.- or changed["messages"][-1:] != body["messages"][-1:]):+ # The host instruction must stay the last block of the last row: without it, the reply is not a+ # handoff. The user text in front of it (a trailing user row) can change, as the other new rows.+ or not changed["messages"] or not warm.ends_with_instruction(changed["messages"][-1], instruction)):raise warm.WarmRefusal("middleware_rewrite")body = changed# A request middleware can add text to the new rows. Check the size again before the request is sent.@@ -299,7 +307,8 @@ class WarmCompactionEngine(ContextEngine):# attempt stops even when the middleware catches this refusal.repeated.append(True)raise warm.WarmRefusal("middleware_repeated")- result = warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post, extra_headers=headers)+ result = warm.send(base, self._wc_route[1], self._wc_api_key, post=self._post, extra_headers=headers,+ ssl_context=tls)sent.append((result, dict(result)))return resulttry:@@ -325,18 +334,23 @@ class WarmCompactionEngine(ContextEngine):return tail_budget(int(self._settings["tail_tokens"]), int(self.context_length or 0),int(self.threshold_tokens or 0))- def _copy_tokens(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0) -> int:- """Token allowance for the copied user messages: at most the tail size, and small enough that the request- overhead (system rows and tool schemas), the tail rows, the summary, the summary row headings, and the- copies fit below the compaction threshold, and below the context window less the reply reserve."""- tail = self._tail_tokens()+ def _room(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0) -> int | None:+ """Tokens that stay free below the compaction threshold, and below the context window less the reply+ reserve, after the request overhead (system rows and tool schemas), the tail rows, the summary, and the+ summary row headings. None without a threshold."""threshold = int(self.threshold_tokens or 0)if threshold <= 0:- return tail+ return Nonewindow = int(self.context_length or 0)limit = min(threshold, window - reserve) if window > 0 else threshold- used = overhead + estimate_tokens(tail_rows) + estimate_tokens(summary) + CARRIER_TOKENS- return max(0, min(tail, limit - used))+ return limit - (overhead + estimate_tokens(tail_rows) + estimate_tokens(summary) + CARRIER_TOKENS)++ def _copy_tokens(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0) -> int:+ """Token allowance for the copied user messages and the prepended user row: at most the tail size, and+ the free room (_room)."""+ tail = self._tail_tokens()+ room = self._room(tail_rows, summary, overhead, reserve)+ return tail if room is None else max(0, min(tail, room))def _cancelled(self) -> bool:check = getattr(self, "_compression_cancelled_check", None)diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex a8925b7..5dfbc3d 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -180,6 +180,21 @@ def _fit_copy(text: str, chars: int, tokens: int | None) -> str | None:return None+def fit_user_row(row: dict[str, Any], tokens: int) -> dict[str, Any]:+ """Return the user row cut to its start and end, at most tokens estimated tokens (the text that Hermes+ sent; an attachment becomes a mark). At least MIN_COPY_CHARS characters stay: the tail starts with it."""+ text = visible_text(api_content(row)).strip()+ limit = len(text)+ while True:+ out = {"role": "user", "content": cut_middle(text, limit)}+ if attr(row, "name"):+ out["name"] = attr(row, "name")+ cost = estimate_tokens(out)+ if cost <= tokens or limit <= MIN_COPY_CHARS:+ return out+ limit = max(MIN_COPY_CHARS, min(limit - 1, limit * max(tokens, 0) // cost))++def quote(text: str) -> str:"""Return the text as a Markdown block quote."""return "\n".join(">" + (" " + line if line else "") for line in text.splitlines()) or ">"diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 6d4243a..304c81c 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -6,6 +6,7 @@ import collectionsimport copyimport jsonimport re+import sslimport timeimport urllib.errorimport urllib.parse@@ -128,12 +129,12 @@ def _arguments(value: Any) -> tuple[str, str]:def _in_whole_lines(stored: str, sent: str) -> bool:- """True when the stored text is in the sent text as whole lines. Hermes adds request-time context as- separate lines ("\n\n" + context); text on the same line can change the meaning ("Delete A" to- "Do not Delete A")."""- if not stored:+ """True when the stored text is in the sent text as whole lines, with its white space. Hermes adds+ request-time context as separate lines ("\n\n" + context); text on the same line can change the meaning+ ("Delete A" to "Do not Delete A"), and so can changed indentation."""+ if not stored.strip():return True- return re.search(r"(?:^|\n)[ \t]*" + re.escape(stored) + r"[ \t]*(?:\n|$)", sent) is not None+ return re.search(r"(?:^|\n)" + re.escape(stored) + r"(?:\n|$)", sent) is not Nonedef _same_row(wire: Any, row: Any) -> bool:@@ -149,7 +150,7 @@ def _same_row(wire: Any, row: Any) -> bool:sent_runs, sent_media = _parts(attr(wire, "content"))stored_runs, stored_media = _parts(api_content(row))if sent_media != stored_media or not all(- _in_whole_lines(stored.strip(), sent) for stored, sent in zip(stored_runs, sent_runs)):+ _in_whole_lines(stored, 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)]@@ -283,6 +284,47 @@ def wire_row(row: Any, reasoning_echo: bool = False, model: Any = None, base_urlreturn wire+def _join_content(first: Any, second: Any) -> Any:+ """The rule of Hermes 45871e10 (agent.agent_runtime_helpers._merge_user_content): two texts join with a blank+ line; lists append as separate parts. None for another shape."""+ if isinstance(first, str) and isinstance(second, str):+ return first + ("\n\n" if first and second else "") + second+ first_parts = first if isinstance(first, list) else [{"type": "text", "text": first}] if first else []+ second_parts = second if isinstance(second, list) else [{"type": "text", "text": second}] if second else []+ if not isinstance(first, (str, list)) or not isinstance(second, (str, list)):+ return None+ return [*first_parts, *second_parts]+++def ends_with_instruction(row: Any, instruction: str) -> bool:+ """True when the row is a user row whose last block is the host instruction (it can join the last user row+ of the history; see _join_user_rows)."""+ if attr(row, "role") != "user":+ return False+ content = attr(row, "content")+ if isinstance(content, str):+ return content == instruction or content.endswith("\n\n" + instruction)+ return (isinstance(content, list) and bool(content) and isinstance(content[-1], dict)+ and content[-1].get("type") == "text" and content[-1].get("text") == instruction)+++def _join_user_rows(rows: list) -> list:+ """Join adjacent user rows of the same author (no name, or the same name). The ordinary request has no+ adjacent user rows (Hermes joins them), and strict chat templates refuse them. The host instruction is the+ last block of the last user row; it says that it comes from the host."""+ out: list = []+ for row in rows:+ last = out[-1] if out else None+ if (last is not None and last.get("role") == row.get("role") == "user" and last.get("name") == row.get("name")+ and set(last) <= {"role", "content", "name"} and set(row) <= {"role", "content", "name"}):+ joined = _join_content(last.get("content"), row.get("content"))+ if joined is not None:+ out[-1] = {**last, "content": joined}+ continue+ out.append(row)+ return out++def reply_reserve(body: Any) -> int:"""The reply reserve of a request: the larger positive max_tokens or max_completion_tokens (a server canhonor either), else DEFAULT_RESERVE."""@@ -326,7 +368,7 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, context# 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)]- request["messages"] = [*body["messages"], *added, {"role": "user", "content": instruction}]+ request["messages"] = [*body["messages"], *_join_user_rows([*added, {"role": "user", "content": instruction}])]request["stream"] = Falserequest.pop("stream_options", None)# A stop sequence of the main request could cut the handoff after the five headings.@@ -351,11 +393,15 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):return None-def urllib_post(url: str, data: bytes, headers: dict[str, str], timeout_s: float) -> tuple[int, bytes]:+def urllib_post(url: str, data: bytes, headers: dict[str, str], timeout_s: float,+ context: ssl.SSLContext | None = None) -> tuple[int, bytes]:"""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())+ is not followed: its status comes back, and the caller treats it as a provider error. context is the TLS+ context of the route (route_tls)."""+ handlers: list = [urllib.request.ProxyHandler(urllib.request.getproxies_environment()), _NoRedirect()]+ if context is not None:+ handlers.append(urllib.request.HTTPSHandler(context=context))+ opener = urllib.request.build_opener(*handlers)request = urllib.request.Request(url, data=data, headers=headers, method="POST")try:with opener.open(request, timeout=timeout_s) as response:@@ -418,12 +464,40 @@ def route_headers(api_key: Any, base_url: Any, provider: Any) -> dict[str, str]:return {str(key): str(value) for key, value in headers.items()}+def route_tls(base_url: Any) -> ssl.SSLContext | None:+ """Return the TLS context of an https route as the Hermes client has it (ssl_ca_cert of a custom provider,+ through agent.ssl_verify.resolve_httpx_verify), or None for the default context. Raise+ WarmRefusal("tls_unknown") when the setting cannot be read: with another trust setting, the request fails+ or goes to a server that the main requests do not trust. Raise WarmRefusal("tls_unverified") for+ ssl_verify: false: the plugin does not send without certificate checks."""+ url = str(base_url or "")+ if not url.lower().startswith("https:"):+ return None+ try:+ from agent.ssl_verify import resolve_httpx_verify+ from hermes_cli.config_providers import get_custom_provider_tls_settings+ tls = get_custom_provider_tls_settings(url) or {}+ verify = resolve_httpx_verify(ca_bundle=tls.get("ssl_ca_cert"), ssl_verify=tls.get("ssl_verify"),+ base_url=url)+ except Exception as error:+ raise WarmRefusal("tls_unknown") from error+ if isinstance(verify, ssl.SSLContext):+ return verify+ if verify is False:+ # ssl_verify: false. The plugin does not send without certificate checks; the fallback runs.+ raise WarmRefusal("tls_unverified")+ if verify is True:+ return None+ raise WarmRefusal("tls_unknown")++def _optional_int(value: Any) -> int | None:return value if isinstance(value, int) and not isinstance(value, bool) else Nonedef send(body: dict[str, Any], base_url: str, api_key: Any, timeout_s: float = TIMEOUT_S,- post: Post | None = None, extra_headers: dict[str, str] | None = None) -> dict[str, Any]:+ post: Post | None = None, extra_headers: dict[str, str] | None = None,+ ssl_context: ssl.SSLContext | None = None) -> dict[str, Any]:"""Send the warm request one time. Return the reply fields and the usage, or raise WarmRefusal.extra_headers are the client default headers of the route (route_headers); they win, as in the SDK."""if not base_url:@@ -436,7 +510,11 @@ def send(body: dict[str, Any], base_url: str, api_key: Any, timeout_s: float = Tdata = json.dumps(body).encode("utf-8")started = time.monotonic()try:- status, raw = (post or urllib_post)(str(base_url).rstrip("/") + "/chat/completions", data, headers, timeout_s)+ url = str(base_url).rstrip("/") + "/chat/completions"+ if ssl_context is None:+ status, raw = (post or urllib_post)(url, data, headers, timeout_s)+ else:+ status, raw = (post or urllib_post)(url, data, headers, timeout_s, context=ssl_context)except TimeoutError as error:raise WarmRefusal("timeout") from errorexcept Exception as error: