Skip to content

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

Mark attachments, bound the fallback transcript in tokens, and keep the prepended row whole

Elevatormusic933d701875de
diff --git a/README.md b/README.md
index 2289d06..aec3fb3 100644
--- a/README.md
+++ b/README.md
@@ -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_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `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_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `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.json
index b8d981b..2579c7c 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-06T06:01:30Z",
+ "started_utc": "2026-10-06T06:21:17Z",
"hermes": {
"commit": "45871e100feceb89769536c88e5e6e265226a409",
"clean": true
@@ -10,12 +10,12 @@
"plugin_files_sha256": {
"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",
"warm_compaction/capture.py": "3ee60f35ae4e8fc0376ab6634c721ae1ca429593d10730f19addc3be545fe682",
- "warm_compaction/engine.py": "862f6a11b7dcbd93fd382e438de67bebeb1c64795dbfcd9197faa594fcee9004",
- "warm_compaction/fallback.py": "0535a4e6b54a871233a1d861eded496ed980c7c341acb83a8e35ab201f2be63d",
+ "warm_compaction/engine.py": "2df68d8b31641f54cebb87de909441e87b293638c5a5af9d4d6158cc827bf0fe",
+ "warm_compaction/fallback.py": "45fc805aba7bd96360ad86d9fed6e43a5eabb6ae7716bae35cd95a05c821502f",
"warm_compaction/handoff.py": "2fcdc2af2eba2d36eaabfef912ce0dd6d64bccc7849849e6411869a0025a06c2",
- "warm_compaction/layout.py": "c9e63764e78ebf8ddce2e35f7e8b013ee664770371a224102dfe7e208bc7e5d7",
+ "warm_compaction/layout.py": "b3d9ffbf60fb6ee890615ed2f18d427aaba4fdd8f886bd93459bd7e40474b190",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
- "warm_compaction/rows.py": "d7ad318ca994ede8bc7a17b27d68c40f49712dc8b4700087b6a8af47a2466c6e",
+ "warm_compaction/rows.py": "482c62b87fb42f1aa26473d474d6a3c70c85307632675b02a4a9861b80b6b4bf",
"warm_compaction/warm.py": "340f7e49b4cb095df29da9e7dfdb13575c6dc1eb5f63a7a9a3f5bc4bd21f9bf1"
},
"privacy": "metadata only: names, counts, codes, booleans, and times; no message text",
@@ -75,11 +75,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.194,
+ "compress_seconds": 0.18,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.022,
+ "elapsed_s": 0.026,
"prompt_tokens": 33883,
"cached_tokens": 16941
},
@@ -87,15 +87,17 @@
"final_session_id": "wc-enable_manual_warm",
"continuation_keeps_custom_system_text": false,
"fence_denied": {
- "child_process_blocked": 3
+ "child_process_blocked": 4
},
"fence_blocked_programs": [
+ "git",
"pip",
"python",
"python3"
],
"fence_blocked_hosts": [],
"fence_blocked_callers": [
+ "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_branch_tip < hermes_cli/source_check.py:_check_branch",
"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"
],
@@ -182,7 +184,7 @@
"install",
"run"
],
- "process_seconds": 74.341
+ "process_seconds": 75.186
},
{
"scenario": "manual_fallback",
@@ -241,11 +243,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.44,
+ "compress_seconds": 0.388,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
- "elapsed_s": 0.281,
+ "elapsed_s": 0.235,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -354,7 +356,7 @@
"install",
"run"
],
- "process_seconds": 38.303
+ "process_seconds": 38.163
},
{
"scenario": "manual_fixed",
@@ -412,11 +414,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.298,
+ "compress_seconds": 0.262,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.156,
+ "elapsed_s": 0.11,
"prompt_tokens": null,
"cached_tokens": null
},
@@ -525,7 +527,7 @@
"install",
"run"
],
- "process_seconds": 36.005
+ "process_seconds": 34.074
},
{
"scenario": "auto_tool_loop",
@@ -728,7 +730,7 @@
"install",
"run"
],
- "process_seconds": 37.736
+ "process_seconds": 37.231
},
{
"scenario": "rollback",
@@ -778,7 +780,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.159,
+ "compress_seconds": 0.163,
"warm_last": {
"path": "warm",
"reason": "accepted",
@@ -964,10 +966,10 @@
"run",
"rollback"
],
- "process_seconds": 43.144
+ "process_seconds": 42.605
}
],
- "finished_utc": "2026-10-06T06:05:20Z",
+ "finished_utc": "2026-10-06T06:25:04Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 6c609b6..39bd0eb 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -177,6 +177,20 @@ class EngineTest(unittest.TestCase):
("fallback", reason))
self.assertEqual(self.post.calls, [])
+ def test_a_rewriting_middleware_stops_the_warm_request(self):
+ # The capture keeps the body before later middleware. A middleware that rewrites requests can have
+ # rewritten the captured request too, so the warm request is not sent.
+ def rewrite(request=None, next_call=None, **context):
+ return next_call({**request, "messages": request["messages"][1:]})
+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(rewrite)
+ rows = old_turns()
+ reply = assistant("final")
+ self.seed(rows, reply)
+ self.engine.compress([*rows, reply])
+ self.assertEqual((self.engine.warm_last["path"], self.engine.warm_last["reason"]),
+ ("fallback", "middleware_rewrite"))
+ self.assertEqual(self.post.calls, [])
+
def test_fixed_summary_when_the_fallback_fails(self):
self.llm = FakeLlm(error=RuntimeError("down"))
engine = self.make()
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index fe144ee..de58995 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -4,9 +4,10 @@ import unittest
from types import SimpleNamespace
from warm_compaction.fallback import (
- FALLBACK_INSTRUCTION, MAX_TOKENS, MIDDLE_MARK, TASK, TOOL_CHARS, TRANSCRIPT_CHARS, fixed_summary, llm_summary,
- render_row, transcript,
+ FALLBACK_INSTRUCTION, MAX_TOKENS, MIDDLE_MARK, TASK, TOOL_CHARS, TRANSCRIPT_CHARS, TRANSCRIPT_TOKENS,
+ fixed_summary, llm_summary, render_row, transcript,
)
+from warm_compaction.rows import estimate_tokens
from warm_compaction.handoff import HEADINGS
from wc_fixtures import assistant, tool, user
@@ -25,6 +26,18 @@ class FakeLlm:
class TranscriptTest(unittest.TestCase):
+ def test_attachments_are_marked_in_the_transcript(self):
+ text = transcript([user([{"type": "text", "text": "see"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}]), assistant("ok")], PREFIXES)
+ self.assertIn("[first user message]\nsee\n[image attachment]", text)
+ self.assertIn("[user]\nsee\n[image attachment]", text)
+
+ def test_dense_text_is_bounded_in_tokens(self):
+ rows = [user("\u4f60" * 3_000), *[assistant("\u597d" * 3_000) for _ in range(20)]]
+ text = transcript(rows, PREFIXES)
+ self.assertLessEqual(estimate_tokens(text), TRANSCRIPT_TOKENS)
+ self.assertIn("[first user message]", text)
+ self.assertTrue(text.endswith("\u597d"))
+
def test_think_blocks_are_removed_only_from_assistant_rows(self):
text = "<think>keep me</think> body"
self.assertNotIn("keep me", render_row(assistant(text)))
diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.py
index f5e1e89..33d049e 100644
--- a/tests/test_wc_layout.py
+++ b/tests/test_wc_layout.py
@@ -65,6 +65,30 @@ class CopyTest(unittest.TestCase):
self.assertEqual(copied_user_messages(rows, 24_000, PREFIXES, max_tokens=100), [])
+class AttachmentAndPrependTest(unittest.TestCase):
+ def test_an_image_only_user_row_is_real_and_copied_as_a_mark(self):
+ row = user([{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}])
+ self.assertTrue(is_real_user(row, PREFIXES))
+ self.assertEqual(copied_user_messages([row], 1_000, PREFIXES), ["[image attachment]"])
+
+ def test_the_prepended_row_keeps_its_name(self):
+ rows = [user("do it", name="alice"), assistant("", [("c1", "f", "{}")]), tool("c1", "r")]
+ start, prepend = tail_start(rows, 1, PREFIXES)
+ self.assertEqual((start, prepend), (1, {"role": "user", "content": "do it", "name": "alice"}))
+
+ def test_the_prepended_row_is_not_copied_and_counts_in_the_copy_budget(self):
+ rows = [user("older ask"), assistant("a"), user("do it " + "x" * 400),
+ assistant("", [("c1", "f", "{}")]), tool("c1", "r")]
+ prepend = {"role": "user", "content": rows[2]["content"]}
+ new = build(rows, "S", start=3, prepend=prepend, copy_chars=10_000, header_prefix="[HERMES PREFIX]",
+ prefixes=PREFIXES, end_marker=END, copy_tokens=1_000)
+ self.assertIn("> older ask", new[1]["content"])
+ self.assertNotIn("do it", new[1]["content"])
+ new = build(rows, "S", start=3, prepend=prepend, copy_chars=10_000, header_prefix="[HERMES PREFIX]",
+ prefixes=PREFIXES, end_marker=END, copy_tokens=105)
+ self.assertNotIn("older ask", new[1]["content"])
+
+
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_rows.py b/tests/test_wc_rows.py
index 80f02da..03f394c 100644
--- a/tests/test_wc_rows.py
+++ b/tests/test_wc_rows.py
@@ -5,10 +5,20 @@ from types import SimpleNamespace
from warm_compaction.rows import (
attr, compact_json, estimate_tokens, plain_text, reply_text, row_digest, strip_think, tool_calls_of,
+ visible_text,
)
class RowsTest(unittest.TestCase):
+ def test_visible_text_marks_each_non_text_part(self):
+ content = [{"type": "text", "text": "see"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},
+ {"type": "image_url", "image_url": {"url": "https://example.invalid/a.png"}},
+ {"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}},
+ {"type": "file", "file": {"filename": "report.pdf", "file_data": "AAAA"}}]
+ self.assertEqual(visible_text(content), "see\n[image attachment]\n[image attachment: "
+ "https://example.invalid/a.png]\n[audio attachment]\n[file attachment: report.pdf]")
+ self.assertEqual(visible_text("plain"), "plain")
+
def test_attr_reads_mappings_and_objects(self):
self.assertEqual(attr({"a": 1}, "a"), 1)
self.assertEqual(attr(SimpleNamespace(a=2), "a"), 2)
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index e0e3de1..a5e514d 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -233,6 +233,10 @@ class WarmCompactionEngine(ContextEngine):
raise warm.WarmRefusal("middleware_unavailable") from error
def terminal(request: Any) -> dict[str, Any]:
+ # The capture keeps the body before later middleware. A middleware that rewrites this request can
+ # also have rewritten the captured request, so the warm request is not sent.
+ if request != body:
+ raise warm.WarmRefusal("middleware_rewrite")
return warm.send(request, self._wc_route[1], self._wc_api_key, post=self._post)
try:
reply = run_llm_execution_middleware(
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index 8180309..5169d98 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -8,7 +8,7 @@ from typing import Any, Iterable
from .handoff import END_MARKER, LEGACY_PREFIX, MAX_REPLY_BYTES, extras
from .layout import is_real_user, is_summary
-from .rows import attr, compact_json, plain_text, strip_think, tool_calls_of
+from .rows import attr, compact_json, estimate_tokens, plain_text, strip_think, tool_calls_of, visible_text
logger = logging.getLogger(__name__)
@@ -25,6 +25,13 @@ CUT_MARK = " [cut]"
ROW_CHARS = 4_000
MIDDLE_MARK = " [cut] "
MIN_PART_CHARS = 200
+# Token limits for dense text (CJK text, emoji): the character limits divided by 4. ASCII text meets the two
+# limits at about the same point; dense text meets the token limit first, so a small fallback model can read it.
+TRANSCRIPT_TOKENS = TRANSCRIPT_CHARS // 4
+EARLIER_SUMMARY_TOKENS = EARLIER_SUMMARY_CHARS // 4
+FIRST_USER_TOKENS = FIRST_USER_CHARS // 4
+ROW_TOKENS = ROW_CHARS // 4
+MARK_TOKENS = 8
FALLBACK_INSTRUCTION = """\
Write a handoff summary of the conversation transcript in the next message. The host program will replace the \
@@ -74,6 +81,16 @@ def _cut_middle(text: str, limit: int) -> str:
return text[:head] + MIDDLE_MARK + text[len(text) - (keep - head):]
+def _bound(text: str, chars: int, tokens: int, middle: bool = False) -> str:
+ """Cut the text to at most chars characters and about tokens estimated tokens. A character is at most
+ one estimated token, so a cut to tokens characters meets the token limit."""
+ cut = _cut_middle if middle else _cut
+ text = cut(text, chars)
+ if estimate_tokens(text) > tokens:
+ text = cut(text, max(tokens - MARK_TOKENS, 0))
+ return text
+
+
def _summary_text(row: Any, prefixes: tuple[str, ...]) -> str:
text = plain_text(attr(row, "content")).strip()
for prefix in sorted({*prefixes, LEGACY_PREFIX}, key=len, reverse=True):
@@ -86,7 +103,7 @@ def _summary_text(row: Any, prefixes: tuple[str, ...]) -> str:
def render_row(row: Any) -> str:
"""Return one transcript entry for a row."""
role = str(attr(row, "role") or "unknown")
- text = plain_text(attr(row, "content"))
+ text = visible_text(attr(row, "content"))
text = (strip_think(text) if role == "assistant" else text).strip()
if role == "tool":
return "[tool result]\n" + _cut(text, TOOL_CHARS)
@@ -109,22 +126,27 @@ def transcript(messages: list, prefixes: Iterable[str]) -> str:
head = []
summaries = [row for row in messages if is_summary(row, prefixes)]
if summaries:
- head.append("[earlier summary]\n" + _cut(_summary_text(summaries[-1], prefixes), EARLIER_SUMMARY_CHARS))
+ head.append("[earlier summary]\n" + _bound(_summary_text(summaries[-1], prefixes), EARLIER_SUMMARY_CHARS,
+ EARLIER_SUMMARY_TOKENS))
first = next((row for row in messages if is_real_user(row, prefixes)), None)
if first is not None:
- head.append("[first user message]\n" + _cut(plain_text(first.get("content")).strip(), FIRST_USER_CHARS))
+ head.append("[first user message]\n" + _bound(visible_text(first.get("content")).strip(), FIRST_USER_CHARS,
+ FIRST_USER_TOKENS))
budget = TRANSCRIPT_CHARS - sum(len(part) + 2 for part in head)
+ tokens = TRANSCRIPT_TOKENS - sum(estimate_tokens(part) + 1 for part in head)
recent: collections.deque = collections.deque()
for row in reversed(messages):
if is_summary(row, prefixes):
continue
- part = _cut_middle(render_row(row), ROW_CHARS)
- if len(part) + 2 > budget:
- if budget - 2 >= MIN_PART_CHARS:
- recent.appendleft(_cut_middle(part, budget - 2))
+ part = _bound(render_row(row), ROW_CHARS, ROW_TOKENS, middle=True)
+ cost = estimate_tokens(part) + 1
+ if len(part) + 2 > budget or cost > tokens:
+ if budget - 2 >= MIN_PART_CHARS and tokens - 1 >= MIN_PART_CHARS // 4:
+ recent.appendleft(_bound(part, budget - 2, tokens - 1, middle=True))
break
recent.appendleft(part)
budget -= len(part) + 2
+ tokens -= cost
return "\n\n".join([*head, *recent])
diff --git a/warm_compaction/layout.py b/warm_compaction/layout.py
index dec902c..5957638 100644
--- a/warm_compaction/layout.py
+++ b/warm_compaction/layout.py
@@ -6,7 +6,7 @@ import copy
from typing import Any, Iterable
from .handoff import LEGACY_PREFIX
-from .rows import attr, estimate_tokens, plain_text
+from .rows import attr, estimate_tokens, plain_text, visible_text
HEADER_TEXT = "The summary of the earlier turns follows."
COPY_HEADING = "## Copied user messages"
@@ -42,7 +42,7 @@ def is_real_user(row: Any, prefixes: Iterable[str]) -> bool:
return False
if row.get("display_kind") and row.get("display_kind") != STEER_KIND:
return False
- text = plain_text(row.get("content")).strip()
+ text = visible_text(row.get("content")).strip()
if not text or text.startswith(SYNTHETIC_PREFIXES):
return False
return not is_summary(row, prefixes)
@@ -82,7 +82,10 @@ def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str]) -> tup
latest = next((row for row in reversed(messages[:start]) if is_real_user(row, prefixes)), None)
if latest is None:
return start, None
- return start, {"role": "user", "content": copy.deepcopy(latest["content"])}
+ prepend = {"role": "user", "content": copy.deepcopy(latest["content"])}
+ if latest.get("name"):
+ prepend["name"] = latest["name"]
+ return start, prepend
def copied_user_messages(messages: list, total_chars: int, prefixes: Iterable[str],
@@ -95,7 +98,7 @@ def copied_user_messages(messages: list, total_chars: int, prefixes: Iterable[st
for row in reversed(messages):
if not is_real_user(row, prefixes):
continue
- text = plain_text(row.get("content")).strip()[:COPY_EACH]
+ text = visible_text(row.get("content")).strip()[:COPY_EACH]
cost = estimate_tokens(text)
if used + len(text) > total_chars or (max_tokens is not None and tokens + cost > max_tokens):
break
@@ -132,7 +135,15 @@ def build(messages: list, summary_text: str, *, start: int, prepend: dict[str, A
return None
prefixes = tuple(prefixes)
header = f"{header_prefix}\n\n{HEADER_TEXT}"
- copies = copied_user_messages(messages[:start], copy_chars, prefixes, copy_tokens)
+ earlier = messages[:start]
+ if prepend:
+ # The prepended row is the latest real user row before the tail. Do not copy it a second time, and
+ # count it in the copy budget.
+ last = max((index for index, row in enumerate(earlier) if is_real_user(row, prefixes)), default=len(earlier))
+ earlier = earlier[:last]
+ if copy_tokens is not None:
+ copy_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:]]
if attr(rest[0], "role") != "user":
diff --git a/warm_compaction/rows.py b/warm_compaction/rows.py
index 48f69a4..65d5c0f 100644
--- a/warm_compaction/rows.py
+++ b/warm_compaction/rows.py
@@ -44,6 +44,36 @@ def plain_text(content: Any) -> str:
return str(content)
+ATTACHMENT_KINDS = {"image_url": "image", "input_audio": "audio", "file": "file"}
+REFERENCE_CHARS = 200
+
+
+def _attachment_mark(part: dict) -> str:
+ kind = str(part.get("type") or "unknown")
+ label = ATTACHMENT_KINDS.get(kind, kind)
+ body = part.get(kind) if isinstance(part.get(kind), dict) else {}
+ reference = body.get("filename") if kind == "file" else body.get("url") if kind == "image_url" else None
+ if isinstance(reference, str) and reference and not reference.startswith("data:"):
+ return f"[{label} attachment: {reference[:REFERENCE_CHARS]}]"
+ return f"[{label} attachment]"
+
+
+def visible_text(content: Any) -> str:
+ """Return the text of a content value and one mark for each image, audio, or file part. A data URL is not
+ copied; a web URL or a file name is."""
+ if not isinstance(content, list):
+ return plain_text(content)
+ lines = []
+ for part in content:
+ if isinstance(part, str):
+ lines.append(part)
+ elif isinstance(part, dict) and isinstance(part.get("text"), str) and part.get("type", "text") == "text":
+ lines.append(part["text"])
+ elif isinstance(part, dict):
+ lines.append(_attachment_mark(part))
+ return "\n".join(lines)
+
+
def strip_think(text: str) -> str:
"""Remove one leading <think>...</think> block and the white space around it."""
return THINK_BLOCK.sub("", text, count=1)