Skip to content

Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix

Cut and quote the tail at the final cap, and estimate rows with the fields that Hermes sends

Elevatormusic42cf8243ecf6
diff --git a/README.md b/README.md
index 4c5ef81..55d94b2 100644
--- a/README.md
+++ b/README.md
@@ -201,7 +201,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
- 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 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`. 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 a short text. 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. 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 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`. 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 a short text. 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. The sizes come from the fields that Hermes sends: a stored `reasoning` field and row metadata do not count, and `reasoning_details` counts only on a route that replays it. 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 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.json
index 20e0946..14f5d11 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-06T15:00:00Z",
+ "started_utc": "2026-10-06T15:16:24Z",
"hermes": {
"commit": "45871e100feceb89769536c88e5e6e265226a409",
"clean": true
@@ -10,12 +10,12 @@
"plugin_files_sha256": {
"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",
"warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",
- "warm_compaction/engine.py": "1e8c9ec97c6c1de67c8fd8cff3aef284836737063428c813636ebf07e5528633",
+ "warm_compaction/engine.py": "290d49c5c8307703033414475fe6cf0101c5c8581c23d77cd6ba46f5995a2328",
"warm_compaction/fallback.py": "f4cf08186f38fc9a46f47af2bedf22584b6ede4f11de1c3abd0fd598aec2f8a4",
"warm_compaction/handoff.py": "9afea62ec2f8ef46cbeefd70b1071bb6c7111fa6fd1cd073e1fb2c7eae30f3c2",
- "warm_compaction/layout.py": "9ef3d55e5275551ea388367b578164a3a0d2c0c1edbd40aba5a1ec38fc25a950",
+ "warm_compaction/layout.py": "6fe5feace2962f1d8af8a4a0dfcd75366aae0bc991e1422b1e0b32951b45ad98",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
- "warm_compaction/rows.py": "e80983b65a0c6406c06d4e64c6cb58c101799ea55dcd759e21ab625925466107",
+ "warm_compaction/rows.py": "8a20a325f18e7cf49f38358c61529fafbae102c1350833ae1033d0274487fc5a",
"warm_compaction/warm.py": "f76aa64c739f8db7e228c25f9f3ee0c7d890c48eea8215f75577a2d6e5f4736b"
},
"privacy": "metadata only: names, counts, codes, booleans, and times; no message text",
@@ -67,7 +67,7 @@
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 22
+ "message_count": 24
}
],
"error": null,
@@ -76,11 +76,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.104,
+ "compress_seconds": 0.105,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.028,
+ "elapsed_s": 0.025,
"prompt_tokens": 33892,
"cached_tokens": 16946
},
@@ -189,7 +189,7 @@
"install",
"run"
],
- "process_seconds": 82.1
+ "process_seconds": 55.212
},
{
"scenario": "manual_fallback",
@@ -239,7 +239,7 @@
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 22
+ "message_count": 24
}
],
"error": null,
@@ -248,11 +248,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.252,
+ "compress_seconds": 0.249,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
- "elapsed_s": 0.109,
+ "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": 4,
+ "child_process_blocked": 5,
"network_host_blocked": 1
},
"fence_blocked_programs": [
@@ -361,7 +361,7 @@
"install",
"run"
],
- "process_seconds": 39.555
+ "process_seconds": 34.293
},
{
"scenario": "manual_fixed",
@@ -410,7 +410,7 @@
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 22
+ "message_count": 24
}
],
"error": null,
@@ -419,11 +419,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.26,
+ "compress_seconds": 0.245,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.125,
+ "elapsed_s": 0.11,
"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": 36.904
+ "process_seconds": 31.541
},
{
"scenario": "auto_tool_loop",
@@ -587,28 +587,28 @@
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 22
+ "message_count": 24
},
{
"seq": 3,
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 24
+ "message_count": 26
},
{
"seq": 4,
"kind": "warm",
"status": 200,
"stream": false,
- "message_count": 27
+ "message_count": 29
},
{
"seq": 5,
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 26
+ "message_count": 28
}
],
"error": null,
@@ -620,21 +620,21 @@
"warm_last_1": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.031,
+ "elapsed_s": 0.016,
"prompt_tokens": 35209,
"cached_tokens": 17604
},
"warm_last_2": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.016,
- "prompt_tokens": 18436,
- "cached_tokens": 9218
+ "elapsed_s": 0.0,
+ "prompt_tokens": 19504,
+ "cached_tokens": 9752
},
"compression_count": 2,
"fence_denied": {
- "child_process_blocked": 8,
- "network_host_blocked": 1
+ "network_host_blocked": 1,
+ "child_process_blocked": 7
},
"fence_blocked_programs": [
"git",
@@ -648,7 +648,6 @@
"fence_blocked_callers": [
"child_process_blocked from hermes_cli/local_runtime/processes.py:spawn_server < hermes_cli/_subprocess_compat.py:bounded_probe_run < hermes_cli/_subprocess_compat.py:bounded_git_probe",
"child_process_blocked from hermes_cli/local_runtime/processes.py:spawn_server < hermes_cli/_subprocess_compat.py:bounded_probe_run < hermes_cli/_subprocess_compat.py:noninteractive_repo_git_env",
- "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout",
"child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version",
"child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of",
"network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"
@@ -737,7 +736,7 @@
"install",
"run"
],
- "process_seconds": 41.908
+ "process_seconds": 38.027
},
{
"scenario": "rollback",
@@ -778,7 +777,7 @@
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 22
+ "message_count": 24
}
],
"error": null,
@@ -787,7 +786,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.149,
+ "compress_seconds": 0.144,
"warm_last": {
"path": "warm",
"reason": "accepted",
@@ -912,7 +911,7 @@
"kind": "main",
"status": 200,
"stream": true,
- "message_count": 64
+ "message_count": 66
},
{
"seq": 1,
@@ -941,7 +940,7 @@
}
],
"engine": "compressor",
- "builtin_removed_rows": 34,
+ "builtin_removed_rows": 36,
"builtin_summary_requests": 1,
"plugin_summary_in_builtin_request": true,
"plugin_summary_kept_verbatim": false,
@@ -970,10 +969,10 @@
"run",
"rollback"
],
- "process_seconds": 45.121
+ "process_seconds": 38.51
}
],
- "finished_utc": "2026-10-06T15:04:06Z",
+ "finished_utc": "2026-10-06T15:19:41Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 625654c..46f1336 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -744,6 +744,32 @@ class EngineTest(unittest.TestCase):
self.assertIn("u" * 100, transcript)
self.assertTrue(any(str(row.get("content")).endswith(" end") for row in new))
+ def test_a_fallback_summary_above_the_reserve_goes_to_the_fixed_summary(self):
+ # A dense summary (CJK) can pass the byte gate and still be above the token reserve: the tail would then
+ # cut more than the fallback transcript had.
+ self.llm = FakeLlm(text=HEADINGS_TEXT.replace("Finish the test task.", "\u76ee\u6807" * 2_500) + "\n" + END_LINE)
+ engine = self.make(warm=False)
+ engine.compress([*old_turns(), assistant("done")])
+ self.assertEqual(engine.warm_last["path"], "fixed")
+
+ def test_the_fixed_summary_quotes_the_middle_that_the_final_tail_cuts(self):
+ # A large earlier summary (CJK) makes the fixed summary larger than the reserve: the tail is cut at the
+ # final cap, and the quote starts where the kept start ends.
+ from warm_compaction.rows import MIDDLE_MARK
+ self.llm.error = RuntimeError("down")
+ text = "".join(f"{index:07d}" for index in range(30_000))
+ rows = [assistant("\u65e7" * 9_000, _compressed_summary=True), *old_turns(4), user("go"),
+ assistant("", [("c1", "read", "{}")]), tool("c1", text)]
+ engine = self.make(threshold=0.95, tail_tokens=30_000, warm=False)
+ 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)
+ self.assertEqual(engine.warm_last["path"], "fixed")
+ kept = next(row for row in new if row.get("role") == "tool")["content"]
+ head = kept.split(MIDDLE_MARK)[0]
+ summary = "\n".join(str(row["content"]) for row in new if row.get("_compressed_summary"))
+ self.assertIn("> " + text[len(head):len(head) + 40], summary)
+
def test_the_fixed_summary_gets_the_middles_that_the_tail_cuts(self):
self.llm.error = RuntimeError("down")
rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]),
diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.py
index 7edadc6..8cb35f0 100644
--- a/tests/test_wc_layout.py
+++ b/tests/test_wc_layout.py
@@ -194,6 +194,10 @@ class BoundTailTest(unittest.TestCase):
self.assertEqual(tail_start(rows, 1_500, PREFIXES), (2, None))
self.assertIs(bound_tail(rows[2:], 1_500)[0], rows[2])
+ def test_unsent_reasoning_does_not_move_the_tail(self):
+ rows = [user("o" * 4_000), assistant("a"), user("q"), assistant("b", reasoning="r" * 40_000)]
+ self.assertEqual(tail_start(rows, 900, PREFIXES), (2, None))
+
def test_a_large_assistant_row_is_cut_and_keeps_its_tool_calls(self):
from warm_compaction.layout import bound_tail
from warm_compaction.rows import MIDDLE_MARK, estimate_tokens
diff --git a/tests/test_wc_rows.py b/tests/test_wc_rows.py
index 03f394c..24ed918 100644
--- a/tests/test_wc_rows.py
+++ b/tests/test_wc_rows.py
@@ -63,3 +63,17 @@ class RowsTest(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+
+
+class SentRowsTest(unittest.TestCase):
+ def test_the_estimate_uses_the_fields_that_hermes_sends(self):
+ # wire_row: no stored reasoning field, no metadata, reasoning_details only on a route that replays it.
+ from warm_compaction.rows import sent_tokens
+ base = {"role": "assistant", "content": "ok"}
+ small = sent_tokens(base)
+ self.assertEqual(sent_tokens({**base, "reasoning": "r" * 40_000, "timestamp": "t" * 4_000}), small)
+ self.assertGreater(sent_tokens({**base, "reasoning_content": "r" * 4_000}), small + 900)
+ details = {**base, "reasoning_details": [{"type": "reasoning.text", "text": "d" * 4_000}]}
+ self.assertGreater(sent_tokens(details), small + 900)
+ self.assertEqual(sent_tokens(details, details=False), small)
+
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index 5b6c789..8b5f706 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -192,7 +192,7 @@ class WarmCompactionEngine(ContextEngine):
if self.threshold_tokens <= 0:
return False
# As Hermes sends the rows: the stored display text of a row with api_content is not in the request.
- tokens = estimate_tokens(sent_rows(messages))
+ tokens = estimate_tokens(sent_rows(messages, self._details()))
window = int(self.context_length or 0)
budget = self._budget_capture(self._store.latest(self._wc_session_id), messages)
if budget is not None:
@@ -204,7 +204,7 @@ class WarmCompactionEngine(ContextEngine):
return tokens >= self.threshold_tokens
def has_content_to_compress(self, messages: list) -> bool:
- start, _prepend = layout.tail_start(messages, self._tail_tokens(), self._prefixes())
+ start, _prepend = layout.tail_start(messages, self._tail_tokens(), self._prefixes(), self._details())
return start > 0
def on_session_reset(self) -> None:
@@ -224,7 +224,8 @@ class WarmCompactionEngine(ContextEngine):
"""Replace the rows before the tail with a summary. Keep the history when no row comes before the tail."""
started = self._clock()
prefixes = self._prefixes()
- start, prepend = layout.tail_start(messages, self._tail_tokens(), prefixes)
+ details = self._details()
+ start, prepend = layout.tail_start(messages, self._tail_tokens(), prefixes, details)
if start <= 0:
return messages
memory = sanitize_memory(memory_context)
@@ -243,11 +244,16 @@ class WarmCompactionEngine(ContextEngine):
# The middles that the tail cuts (see layout.bound_tail): the rows before the tail do not have them.
removed: list = []
if summary is None and not self._cancelled() and self._attempt() == attempt:
- layout.bound_tail(messages[start:], self._tail_cap(SUMMARY_RESERVE, overhead, reserve), removed)
+ layout.bound_tail(messages[start:], self._tail_cap(SUMMARY_RESERVE, overhead, reserve), removed, details)
# Only the rows before the tail: the tail stays as it is, and a transcript of the whole history
# can spend its budget on the tail.
summary, _tokens = fallback.llm_summary(self._llm, [*messages[:start], *removed], prefixes,
focus_topic=focus_topic, memory_context=memory, task=self._task)
+ if summary is not None and estimate_tokens(summary) > SUMMARY_RESERVE:
+ # A dense summary (CJK, for example) above the reserve: the tail would cut more than the
+ # transcript had. The fixed summary quotes what the final tail cuts.
+ logger.warning("warm_compaction: the fallback summary is above the reserve; fixed summary used")
+ summary = None
if summary is not None:
record["path"] = "fallback"
if self._cancelled():
@@ -266,6 +272,7 @@ class WarmCompactionEngine(ContextEngine):
# 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, reserve)
+ cut: list = []
if prepend is not None and room is not None:
allowed = room if overhead is not None else 0
if estimate_tokens(prepend) > allowed:
@@ -275,23 +282,38 @@ class WarmCompactionEngine(ContextEngine):
else:
# The row is not copied and the fixed summary does not have it: its cut middle goes into the
# summary as a quote. The room keeps space for that quote.
- cut: list = []
prepend = layout.fit_user_row(prepend, allowed - fallback.CUT_QUOTE_CHARS // 4, cut)
summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)
copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead, reserve)
- tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve,
- estimate_tokens(prepend) if prepend is not None else 0)
+ prepend_tokens = estimate_tokens(prepend) if prepend is not None else 0
+ tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)
+ if record["path"] == "fixed":
+ # The fixed summary quotes what the tail cuts: cut and quote at the same (final) cap. A larger summary
+ # makes a smaller cap; a few rounds reach it.
+ for _round in range(3):
+ final: list = []
+ layout.bound_tail(messages[start:], tail_tokens, final, details)
+ if final == removed:
+ break
+ removed = final
+ summary = fallback.fixed_summary([*messages[:start], *removed, *cut], prefixes)
+ tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve, prepend_tokens)
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, tail_tokens=tail_tokens)
+ copy_tokens=copy_tokens, tail_tokens=tail_tokens, details=details)
self.compression_count += 1
self._finish(record, started)
return new
+ def _details(self) -> bool:
+ """True when the route replays reasoning_details (warm.wire_row sends them)."""
+ return bool(hermes_value("agent.transports.chat_completions", "_route_replays_reasoning_details",
+ warm._route_replays_reasoning_details)(self._wc_route[1]))
+
def _attempt(self) -> tuple:
"""(route, api key, provider, session id) now."""
return tuple(self._wc_route), self._wc_api_key, self._wc_provider, self._wc_session_id
@@ -418,7 +440,8 @@ class WarmCompactionEngine(ContextEngine):
return None
window = int(self.context_length or 0)
limit = min(threshold, window - reserve) if window > 0 else threshold
- return limit - (overhead + estimate_tokens(sent_rows(tail_rows)) + estimate_tokens(summary) + CARRIER_TOKENS)
+ return limit - (overhead + estimate_tokens(sent_rows(tail_rows, self._details())) + estimate_tokens(summary)
+ + CARRIER_TOKENS)
def _tail_cap(self, summary_tokens: int, overhead: int | None, reserve: int, prepend_tokens: int = 0) -> int:
"""The tail budget, and at most the free room for the tail after the overhead, the summary, and the
diff --git a/warm_compaction/layout.py b/warm_compaction/layout.py
index 5a3953e..22999cb 100644
--- a/warm_compaction/layout.py
+++ b/warm_compaction/layout.py
@@ -125,7 +125,8 @@ def units(messages: list) -> list[tuple[int, int]]:
return spans
-def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str]) -> tuple[int, dict[str, Any] | None]:
+def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str],
+ details: bool = True) -> tuple[int, dict[str, Any] | None]:
"""Return the first tail index and, in the middle of a task, a copy of the latest real user row."""
prefixes = tuple(prefixes)
spans = units(messages)
@@ -133,9 +134,9 @@ def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str]) -> tup
return 0, None
start = spans[-1][0]
# As Hermes sends the rows: the stored display text of a row with api_content is not in the request.
- size = sum(sent_tokens(row) for row in messages[start:])
+ size = sum(sent_tokens(row, details) for row in messages[start:])
for span_start, span_end in reversed(spans[:-1]):
- cost = sum(sent_tokens(row) for row in messages[span_start:span_end])
+ cost = sum(sent_tokens(row, details) for row in messages[span_start:span_end])
if size + cost > tail_tokens:
break
size += cost
@@ -300,7 +301,7 @@ def _set_part(row: dict[str, Any], key: tuple, value: Any) -> dict[str, Any]:
return new
-def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:
+def bound_tail(rows: list, tokens: int, removed: list | None = None, details: bool = True) -> 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, assistant reply, tool call, or tool result). Then the
largest sent payloads (_tail_parts) are cut to their start and end, until the rows fit or no payload has more
@@ -318,7 +319,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:
limits: dict[tuple, int] = {}
# First the cuts to start and end (at least MIN_COPY_CHARS), then, when they are not enough, the drops.
floor = MIN_COPY_CHARS
- while sum(sent_tokens(row) for row in rows) > tokens:
+ while sum(sent_tokens(row, details) for row in rows) > tokens:
cuttable = []
for index, row in enumerate(rows):
for key, value in _tail_parts(row):
@@ -340,7 +341,7 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:
limits[(index, key)] = 0
new_value = DROPPED
else:
- target = cost - (sum(sent_tokens(row) for row in rows) - tokens)
+ target = cost - (sum(sent_tokens(row, details) for row in rows) - tokens)
limit = max(MIN_COPY_CHARS, min(len(value) - 1, len(value) * max(target, 0) // max(cost, 1)))
# Cut the original text again: the kept start and end are then parts of the original text.
limits[(index, key)] = limit
@@ -365,7 +366,8 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:
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, tail_tokens: int | None = None) -> list | None:
+ marker: str = "_db_persisted", copy_tokens: int | None = None, tail_tokens: int | None = None,
+ details: bool = True) -> 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:
@@ -384,7 +386,7 @@ def build(messages: list, summary_text: str, *, start: int, prepend: dict[str, A
body = summary_body(summary_text, copies, end_marker)
tail = [_tail_row(row, marker) for row in messages[start:]]
if tail_tokens is not None:
- tail = bound_tail(tail, tail_tokens)
+ tail = bound_tail(tail, tail_tokens, details=details)
rest = ([copy.deepcopy(prepend)] if prepend else []) + tail
if attr(rest[0], "role") != "user":
return [{"role": "user", "content": f"{header}\n\n{body}", "_compressed_summary": True}, *rest]
diff --git a/warm_compaction/rows.py b/warm_compaction/rows.py
index d0ad452..97ba2b2 100644
--- a/warm_compaction/rows.py
+++ b/warm_compaction/rows.py
@@ -99,13 +99,18 @@ def visible_text(content: Any) -> str:
MIDDLE_MARK = " [cut] "
-def sent_rows(messages: list) -> list:
- """Return the rows as Hermes sends them, for an estimate: the api_content sidecar in place of the content, and
- no private (underscore) fields."""
+# The fields of a row that Hermes sends (warm.wire_row): a stored reasoning field and metadata are not sent.
+SENT_FIELDS = ("role", "content", "name", "tool_call_id", "tool_calls", "reasoning_content")
+
+
+def sent_rows(messages: list, details: bool = True) -> list:
+ """Return the rows as Hermes sends them, for an estimate: the fields of warm.wire_row, with the api_content
+ sidecar in place of the content. reasoning_details only with details (a route that replays it)."""
+ fields = (*SENT_FIELDS, "reasoning_details") if details else SENT_FIELDS
out = []
for row in messages:
if isinstance(row, dict):
- sent = {key: value for key, value in row.items() if key != "api_content" and not key.startswith("_")}
+ sent = {key: row[key] for key in fields if key in row}
sent["content"] = api_content(row)
out.append(sent)
else:
@@ -113,9 +118,9 @@ def sent_rows(messages: list) -> list:
return out
-def sent_tokens(row: Any) -> int:
+def sent_tokens(row: Any, details: bool = True) -> int:
"""Estimated tokens of one row as Hermes sends it (sent_rows)."""
- return estimate_tokens(sent_rows([row])[0])
+ return estimate_tokens(sent_rows([row], details)[0])
def cut_bounds(text: str, limit: int) -> tuple[int, int]: