Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Bound an oversized newest unit, require the exact sent text, and keep the old summary
Elevatormusic1bbf14c3434a
diff --git a/README.md b/README.mdindex 07df043..183a88d 100644--- a/README.md+++ b/README.md@@ -44,7 +44,7 @@ Start a new Hermes session. Each compaction writes one `warm_compaction:` line tAt each compaction, the plugin sends the last main-model request of the session again. It adds the rows that came after that request and one handoff instruction at the end. This is the *warm request*. The server can reuse the cached prefix of the earlier request, so it reads only the new rows. The reply is a Markdown handoff with five headings: Goal, User instructions, Current state, Key facts, and Next step. The plugin replaces the older rows with the handoff and keeps a verbatim tail of recent rows.-If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a fallback summary through the Hermes auxiliary model route. If that also fails, the plugin writes a fixed-format summary without a model request. When Hermes cancels an attempt, the history stays unchanged.+If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a fallback summary through the Hermes auxiliary model route. If that also fails, the plugin writes a fixed-format summary without a model request; it keeps the newest earlier summary as a quote. When Hermes cancels an attempt, the history stays unchanged.The plugin does this for manual `/compress` and for automatic compaction.diff --git a/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex bb8ae02..d4ff5e7 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:49:06Z",+ "started_utc": "2026-10-06T12:08:10Z","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": "925ea1326a938f31565117a0a4b9d1d493f5d78c0e612177c707d6c845bd0cba",- "warm_compaction/fallback.py": "45dffdab8983292f4d6b7e5b7f60b7578078c8b1abb436c0e47acef3b2f77960",+ "warm_compaction/engine.py": "46e139f7c1b1fca9926aae215686ee63c42320373ff7e1ab4630a9ec6f0623cd",+ "warm_compaction/fallback.py": "30ef046f0511491175d99a772afcc2c9a8f3a9920d0c077821a89f19147682f9","warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",- "warm_compaction/layout.py": "2d7bb6a351fb25cdaa629a49c26f7b4c48e97b63164fa9f30f198bf47344d26b",+ "warm_compaction/layout.py": "ebc6859b93bc82536cce769eb0513f9d946cab3f0417848723518f1216fd1ad3","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71","warm_compaction/rows.py": "cc2a8a3d0561559f24fc40881453441d938ea9d7803e1df81a107a5e05e5f00a",- "warm_compaction/warm.py": "7d439ad3ce7cc6cbf05bde64324f0ea65f097fc2b380169b05b12edc37147a77"+ "warm_compaction/warm.py": "081642f19498b379551af33b70ad01dae3902e1e805c360a08be9f74242d320f"},"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.212,+ "compress_seconds": 0.095,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.13,+ "elapsed_s": 0.02,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -189,7 +189,7 @@"install","run"],- "process_seconds": 55.746+ "process_seconds": 52.135},{"scenario": "manual_fallback",@@ -248,11 +248,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.375,+ "compress_seconds": 0.23,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.219,+ "elapsed_s": 0.094,"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": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -361,7 +361,7 @@"install","run"],- "process_seconds": 32.742+ "process_seconds": 32.312},{"scenario": "manual_fixed",@@ -419,11 +419,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.335,+ "compress_seconds": 0.238,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.203,+ "elapsed_s": 0.11,"prompt_tokens": null,"cached_tokens": null},@@ -532,7 +532,7 @@"install","run"],- "process_seconds": 29.894+ "process_seconds": 29.699},{"scenario": "auto_tool_loop",@@ -620,14 +620,14 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.109,+ "elapsed_s": 0.016,"prompt_tokens": 35201,"cached_tokens": 17600},"warm_last_2": {"path": "warm","reason": "accepted",- "elapsed_s": 0.109,+ "elapsed_s": 0.016,"prompt_tokens": 18427,"cached_tokens": 9213},@@ -737,7 +737,7 @@"install","run"],- "process_seconds": 33.626+ "process_seconds": 32.063},{"scenario": "rollback",@@ -787,11 +787,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.26,+ "compress_seconds": 0.136,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.125,+ "elapsed_s": 0.015,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -799,7 +799,7 @@"final_session_id": "wc-rollback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,+ "child_process_blocked": 5,"network_host_blocked": 1},"fence_blocked_programs": [@@ -950,8 +950,7 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5,- "network_host_blocked": 1+ "child_process_blocked": 5},"fence_blocked_programs": ["git",@@ -959,9 +958,7 @@"python","python3"],- "fence_blocked_hosts": [- "hermes-assets.nousresearch.com"- ]+ "fence_blocked_hosts": []},"exit": [0,@@ -973,10 +970,10 @@"run","rollback"],- "process_seconds": 37.635+ "process_seconds": 36.313}],- "finished_utc": "2026-10-06T11:52:15Z",+ "finished_utc": "2026-10-06T12:11:13Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 54c2aae..f9b743a 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -452,6 +452,18 @@ class EngineTest(unittest.TestCase):self.assertTrue(prepended["content"].endswith(" big end"))self.assertLessEqual(estimate_tokens(new) + 1_000, min(engine.threshold_tokens, 64_000 - DEFAULT_RESERVE))+ def test_an_unknown_overhead_cuts_the_prepended_row_to_its_minimum(self):+ from warm_compaction.layout import MIN_COPY_CHARS+ rows = [*old_turns(4), user("BIG start " + "q" * 40_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=None)+ prepended = next(row for row in new if str(row.get("content")).startswith("BIG start"))+ self.assertLessEqual(len(prepended["content"]), MIN_COPY_CHARS)+ self.assertTrue(prepended["content"].endswith(" big end"))+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_fallback.py b/tests/test_wc_fallback.pyindex a22b269..749288c 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -212,6 +212,16 @@ class FixedSummaryTest(unittest.TestCase):self.assertIn("- Tool calls: read x2", text)self.assertIn("[OPEN] Continue from the latest user message.", text)+ def test_keeps_the_earlier_summary(self):+ # Goals and rules that only the earlier summary has must not be lost when both summary requests fail.+ old = assistant("[CONTEXT SUMMARY]:\n## Goal\nShip the old goal.\n## Next step\nold step\n\n"+ "--- END OF CONTEXT SUMMARY x", _compressed_summary=True)+ text = fixed_summary([old, user("x")], PREFIXES)+ self.assertIn("> ## Goal\n> Ship the old goal.", text)+ self.assertNotIn("END OF CONTEXT SUMMARY", text)+ self.assertEqual([line for line in text.splitlines() if line == "## Goal"], ["## Goal"])+ self.assertNotIn("earlier summary", fixed_summary([user("x")], PREFIXES))+def test_no_tool_calls(self):self.assertIn("- No tool calls.", fixed_summary([user("x")]))diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex bbe75f5..9151965 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -160,6 +160,32 @@ class AttachmentAndPrependTest(unittest.TestCase):self.assertNotIn("older ask", new[1]["content"])+class BoundTailTest(unittest.TestCase):+ def test_a_newest_unit_larger_than_the_tail_is_cut(self):+ # A large user message or tool result alone above the tail budget would stay above the threshold after+ # the compaction. Its start and end stay.+ from warm_compaction.layout import bound_tail+ from warm_compaction.rows import MIDDLE_MARK, estimate_tokens+ rows = [assistant("", [("c1", "read", "{}")]), tool("c1", "head " + "r" * 40_000 + " tail"),+ user("ask " + "u" * 20_000 + " end", api_content="[ctx]\n\nask " + "u" * 20_000 + " end")]+ bounded = bound_tail(rows, 2_000)+ self.assertLessEqual(sum(estimate_tokens(row) for row in bounded), 2_000)+ self.assertEqual(bounded[0], rows[0])+ self.assertTrue(bounded[1]["content"].startswith("head ") and bounded[1]["content"].endswith(" tail"))+ self.assertIn(MIDDLE_MARK, bounded[1]["content"])+ self.assertTrue(bounded[2]["content"].startswith("[ctx]") and bounded[2]["content"].endswith(" end"))+ self.assertNotIn("api_content", bounded[2])+ self.assertIs(bound_tail(rows[:1], 2_000)[0], rows[0])++ def test_build_bounds_the_tail(self):+ from warm_compaction.rows import estimate_tokens+ rows = [user("old"), assistant("a"), user("huge " + "z" * 40_000 + " end")]+ new = build(rows, "S", start=2, prepend=None, copy_chars=1000, header_prefix="[HERMES PREFIX]",+ prefixes=PREFIXES, end_marker=END, tail_tokens=1_000)+ self.assertLessEqual(estimate_tokens(new[-1]), 1_000)+ self.assertTrue(new[-1]["content"].endswith(" end"))++class BuildTest(unittest.TestCase):def test_two_summary_rows_then_the_tail_without_the_marker(self):rows = [user("goal"), assistant("a1"), user("next", _db_persisted=True), assistant("a2", _db_persisted=True)]diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.pyindex 93b6845..9ad7be1 100644--- a/tests/test_wc_warm.py+++ b/tests/test_wc_warm.py@@ -230,11 +230,13 @@ class BuildRequestTest(unittest.TestCase):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")]+ def test_the_instruction_joins_a_named_user_row_and_other_authors_stay_apart(self):+ # Two history rows of different authors stay apart. The instruction joins the last user row and keeps+ # its name: the ordinary request also ended with that row.+ self.messages = [*self.messages[:-1], user("u3", name="alice"), user("u4", name="bob")]body = self.build(capture_for(self.rows, self.reply))self.assertEqual(body["messages"][-2:], [wire_row(user("u3", name="alice")),- {"role": "user", "content": INSTRUCTION}])+ {"role": "user", "name": "bob", "content": "u4\n\n" + INSTRUCTION}])def test_refusal_codes(self):good = capture_for(self.rows, self.reply)@@ -297,10 +299,11 @@ class BuildRequestTest(unittest.TestCase):with self.assertRaises(WarmRefusal) as caught:self.build(capture)self.assertEqual(caught.exception.code, "source_transform_unsupported")- # Lines that Hermes adds inside a text run are not a move.+ # Text added inside a text run is a rewrite too: Hermes sends the stored text (api_content).capture = capture_for(self.rows, self.reply)capture["body"]["messages"][1]["content"][0]["text"] = "[context]\n\nfirst"- self.build(capture)+ with self.assertRaises(WarmRefusal):+ self.build(capture)def test_the_stored_api_content_is_the_sent_text(self):self.rows = [user("hi", api_content="[recalled: short answers]\n\nhi"),@@ -379,21 +382,20 @@ class BuildRequestTest(unittest.TestCase):self.build(capture, route)self.assertEqual(caught.exception.code, "source_transform_unsupported")- def test_accepts_request_time_context_and_reformatted_arguments(self):+ def test_accepts_reformatted_arguments(self):capture = self._tool_round()sent = capture["body"]["messages"]- sent[-1]["content"] += "\n\n[recalled context: the user wants short answers]"sent[-3]["tool_calls"][0]["function"]["arguments"] = "{ \"path\": \"a\" }"self.assertEqual(self.build(capture)["messages"][: len(sent)], sent)- def test_refuses_text_added_on_the_same_line_as_the_stored_text(self):- # Hermes adds request-time context as separate lines ("\n\n" + context). Text on the same line can- # change the meaning of the stored text ("Delete A" to "Do not Delete A").+ def test_refuses_any_text_added_to_the_stored_text(self):+ # Hermes stores the text that it sends (api_content), so the sent text is the stored text. Added text,+ # on the same line or on its own line, can change the meaning ("Ignore the next line.\nDelete A").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),- ("[a]\n\nDelete A \n\n[b]", False)):+ for sent, accepted in (("Do not Delete A", False), ("Delete A now", False), ("Delete A\n\n[context]", False),+ ("Ignore the next line.\nDelete A", False), ("[a]\n\nDelete A\n\n[b]", False),+ ("Delete A", True)):capture = capture_for(self.rows, self.reply)capture["body"]["messages"][1]["content"] = sentwith self.subTest(sent=sent):@@ -408,7 +410,7 @@ class BuildRequestTest(unittest.TestCase):# 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)):+ for sent, accepted in (("return 1\nx = 2", False), (" return 1\nx = 2", True)):capture = capture_for(self.rows, self.reply)capture["body"]["messages"][1]["content"] = sentwith self.subTest(sent=sent):diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 21112d6..c7aad51 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -209,7 +209,7 @@ class WarmCompactionEngine(ContextEngine):self._finish(record, started)return messagesif summary is None:- summary = fallback.fixed_summary(messages[:start])+ summary = fallback.fixed_summary(messages[:start], prefixes)record["path"] = "fixed"# An unknown overhead can be most of the window: then no copies. A capture of another route says# nothing about the system prompt, the tools, and the reply limit of this one.@@ -218,16 +218,19 @@ class WarmCompactionEngine(ContextEngine):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.+ # With an unknown overhead, the room is unknown too: the row keeps only its minimum.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)+ if prepend is not None and room is not None:+ allowed = room if overhead is not None else 0+ if estimate_tokens(prepend) > allowed:+ prepend = layout.fit_user_row(prepend, allowed)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),prefixes=prefixes,end_marker=hermes_value("agent.context_compressor", "_SUMMARY_END_MARKER", HERMES_END_MARKER),marker=hermes_value("agent.context_compressor", "_DB_PERSISTED_MARKER", HERMES_DB_MARKER),- copy_tokens=copy_tokens)+ copy_tokens=copy_tokens, tail_tokens=self._tail_tokens())self.compression_count += 1self._finish(record, started)return newdiff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex 20f3840..f8a3c39 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -7,7 +7,7 @@ import loggingfrom typing import Any, Iterablefrom .handoff import END_MARKER, LEGACY_PREFIX, extras, gate-from .layout import is_real_user, is_summary+from .layout import is_real_user, is_summary, quotefrom .rows import ( # noqa: F401 - MIDDLE_MARK is part of this module's names.MIDDLE_MARK, cut_middle as _cut_middle,api_content, attr, compact_json, estimate_tokens, plain_text, strip_think, tool_calls_of, visible_text,@@ -213,11 +213,18 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topireturn text, tokens if isinstance(tokens, int) and tokens > 0 else None-def fixed_summary(messages: list) -> str:- """Return a five-heading summary without a model request."""+def fixed_summary(messages: list, prefixes: Iterable[str] = ()) -> str:+ """Return a five-heading summary without a model request. The newest earlier summary goes under Key facts as+ a quote (its start and end): the goals and rules that only it has must stay."""+ prefixes = tuple(prefixes)counts = collections.Counter(name for row in messages for _call_id, name, _arguments in tool_calls_of(row) if name)facts = [f"- Tool calls: {name} x{count}" for name, count in sorted(counts.items())] or ["- No tool calls."]+ summaries = [row for row in messages if is_summary(row, prefixes)]+ if summaries:+ earlier = _bound(_summary_text(summaries[-1], prefixes), EARLIER_SUMMARY_CHARS, EARLIER_SUMMARY_TOKENS,+ middle=True)+ facts += ["- The earlier summary follows. It was not updated:", quote(earlier)]return "\n".join(["## Goal", "Summary unavailable.", "","## User instructions", "- See the copied user messages below.", "",diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex 5dfbc3d..1b11a27 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -223,10 +223,37 @@ def _tail_row(row: Any, marker: str) -> Any:return clean+def bound_tail(rows: list, tokens: int) -> list:+ """Return the tail rows in about tokens estimated tokens. The tail keeps whole units, so the newest unit can+ be larger than the tail budget (a large user message or tool result). Then the largest text rows (tool+ results and user messages, as Hermes sent them) are cut to their start and end, until the rows fit or no+ row has more than MIN_COPY_CHARS characters. Other rows stay as they are."""+ rows = list(rows)++ def text_of(row: Any) -> Any:+ return api_content(row) if attr(row, "role") == "user" else attr(row, "content")++ while sum(estimate_tokens(row) for row in rows) > tokens:+ cuttable = [(estimate_tokens(row), index) for index, row in enumerate(rows)+ if isinstance(row, dict) and attr(row, "role") in ("user", "tool")+ and isinstance(text_of(row), str) and len(text_of(row)) > MIN_COPY_CHARS]+ if not cuttable:+ break+ cost, index = max(cuttable)+ text = text_of(rows[index])+ target = cost - (sum(estimate_tokens(row) for row in rows) - tokens)+ limit = max(MIN_COPY_CHARS, min(len(text) - 1, len(text) * max(target, 0) // max(cost, 1)))+ cut = {key: value for key, value in rows[index].items() if key != "api_content"}+ cut["content"] = cut_middle(text, limit)+ rows[index] = cut+ return rows++def build(messages: list, summary_text: str, *, start: int, prepend: dict[str, Any] | None, copy_chars: int,header_prefix: str, prefixes: Iterable[str], end_marker: str,- marker: str = "_db_persisted", copy_tokens: int | None = None) -> list | None:- """Return the new history, or None when no row comes before the tail."""+ marker: str = "_db_persisted", copy_tokens: int | None = None, tail_tokens: int | None = None) -> list | None:+ """Return the new history, or None when no row comes before the tail. With tail_tokens, a tail above it+ is cut to it (bound_tail)."""if start <= 0:return Noneprefixes = tuple(prefixes)@@ -241,7 +268,10 @@ def build(messages: list, summary_text: str, *, start: int, prepend: dict[str, Acopy_tokens = max(copy_tokens - estimate_tokens(prepend), 0)copies = copied_user_messages(earlier, copy_chars, prefixes, copy_tokens)body = summary_body(summary_text, copies, end_marker)- rest = ([copy.deepcopy(prepend)] if prepend else []) + [_tail_row(row, marker) for row in messages[start:]]+ tail = [_tail_row(row, marker) for row in messages[start:]]+ if tail_tokens is not None:+ tail = bound_tail(tail, tail_tokens)+ rest = ([copy.deepcopy(prepend)] if prepend else []) + tailif attr(rest[0], "role") != "user":return [{"role": "user", "content": f"{header}\n\n{body}", "_compressed_summary": True}, *rest]return [diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 304c81c..0e70158 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport collectionsimport copyimport json-import reimport sslimport timeimport urllib.error@@ -128,20 +127,12 @@ def _arguments(value: Any) -> tuple[str, str]:return "json", json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)-def _in_whole_lines(stored: str, sent: str) -> bool:- """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)" + re.escape(stored) + r"(?:\n|$)", sent) is not None--def _same_row(wire: Any, row: Any) -> bool:"""True when the sent row carries the stored row: the same shape; the same name (the Hermes transportremoves the name from tool rows only); the same image, audio, and file parts in the same order; each stored- text run inside the sent text run at the same place, as whole lines (Hermes can add request-time context to a- row); and the same tool-call arguments. The stored text is the api_content sidecar when the row has one."""+ text run equal to the sent text run at the same place (Hermes stores the text that it sends, with its+ request-time context, in api_content; other text is a rewrite, on the same line or on its own line); and the+ same tool-call arguments. The stored text is the api_content sidecar when the row has one."""if _shape(wire) != _shape(row):return Falsename = attr(wire, "name")@@ -150,7 +141,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, sent) for stored, sent in zip(stored_runs, sent_runs)):+ 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)]@@ -308,10 +299,11 @@ def ends_with_instruction(row: Any, instruction: str) -> bool: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."""+def _join_user_rows(rows: list, instruction: str) -> list:+ """Join adjacent user rows of the same author (no name, or the same name), then join the host instruction+ to the last user row (it keeps its name: the ordinary request also ended with that row). The ordinary+ request has no adjacent user rows (Hermes joins them), and strict chat templates refuse them. The+ instruction is the last block; it says that it comes from the host."""out: list = []for row in rows:last = out[-1] if out else None@@ -322,7 +314,13 @@ def _join_user_rows(rows: list) -> list:out[-1] = {**last, "content": joined}continueout.append(row)- return out+ last = out[-1] if out else None+ if last is not None and last.get("role") == "user" and set(last) <= {"role", "content", "name"}:+ joined = _join_content(last.get("content"), instruction)+ if joined is not None:+ out[-1] = {**last, "content": joined}+ return out+ return [*out, {"role": "user", "content": instruction}]def reply_reserve(body: Any) -> int:@@ -368,7 +366,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"], *_join_user_rows([*added, {"role": "user", "content": instruction}])]+ request["messages"] = [*body["messages"], *_join_user_rows(added, instruction)]request["stream"] = Falserequest.pop("stream_options", None)# A stop sequence of the main request could cut the handoff after the five headings.