Skip to content

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

Check row names, keep the automatic tail below the threshold, and count non-ASCII text as dense

Elevatormusic6e35c324252c
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index b6eea83..b21c253 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -228,6 +228,10 @@ class SettingsTest(unittest.TestCase):
self.assertEqual(self.module.tail_budget(0, 600_000), 15_000)
self.assertEqual(self.module.tail_budget(0, 2_000_000), 25_000)
self.assertEqual(self.module.tail_budget(7, 200_000), 7)
+ # The automatic tail stays at or below half of the compaction threshold, so a small window can compact.
+ self.assertEqual(self.module.tail_budget(0, 20_000, 10_000), 5_000)
+ self.assertEqual(self.module.tail_budget(0, 200_000, 100_000), 10_000)
+ self.assertEqual(self.module.tail_budget(7, 20_000, 10), 7)
def test_hermes_value_uses_the_replacement(self):
read = self.module.hermes_value
diff --git a/tests/test_wc_rows.py b/tests/test_wc_rows.py
index 5b6b423..80f02da 100644
--- a/tests/test_wc_rows.py
+++ b/tests/test_wc_rows.py
@@ -34,7 +34,12 @@ class RowsTest(unittest.TestCase):
def test_estimate_tokens_uses_utf8_bytes_of_compact_json(self):
self.assertEqual(compact_json({"a": [1, 2]}), "{\"a\":[1,2]}")
self.assertEqual(estimate_tokens("abcd"), 2)
- self.assertEqual(estimate_tokens("\u00e9"), 1)
+ self.assertEqual(estimate_tokens("\u00e9"), 2)
+
+ def test_estimate_tokens_counts_each_non_ascii_character_as_a_token(self):
+ # CJK text and emoji have about one token or more for each character, not one for each 4 bytes.
+ self.assertEqual(estimate_tokens("\u4f60" * 100), 101)
+ self.assertEqual(estimate_tokens("\U0001f600" * 10), 11)
def test_row_digest_ignores_private_keys_and_sees_calls(self):
base = {"role": "assistant", "content": "x",
diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.py
index 61a82b7..bf2298c 100644
--- a/tests/test_wc_warm.py
+++ b/tests/test_wc_warm.py
@@ -153,6 +153,19 @@ class BuildRequestTest(unittest.TestCase):
self.build(capture)
self.assertEqual(caught.exception.code, "source_transform_unsupported")
+ def test_refuses_a_renamed_row_and_accepts_a_removed_name(self):
+ self.rows = [user("u1", name="alice"), assistant("a1"), user("u2")]
+ self.messages = [*self.rows, self.reply, tool("c1", "r1"), user("u3")]
+ renamed = capture_for(self.rows, self.reply)
+ renamed["body"]["messages"][1]["name"] = "bob"
+ with self.assertRaises(WarmRefusal) as caught:
+ self.build(renamed)
+ self.assertEqual(caught.exception.code, "source_transform_unsupported")
+ # The Hermes transport removes the name from some rows. That is not a rewrite.
+ stripped = capture_for(self.rows, self.reply)
+ stripped["body"]["messages"][1].pop("name")
+ self.build(stripped)
+
def test_accepts_request_time_context_and_reformatted_arguments(self):
capture = self._tool_round()
sent = capture["body"]["messages"]
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index f3db629..3a9b029 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -54,11 +54,14 @@ def read_settings(get_config: Callable[..., Any] | None) -> dict[str, Any]:
return settings
-def tail_budget(setting: int, context_length: int) -> int:
- """Return the tail size: the setting, or 2.5% of the context window kept between 10,000 and 25,000."""
+def tail_budget(setting: int, context_length: int, threshold_tokens: int = 0) -> int:
+ """Return the tail size: the setting, or 2.5% of the context window kept between 10,000 and 25,000.
+ The automatic size is also at most half of the compaction threshold. Otherwise the tail can hold the
+ whole history when compaction starts, and nothing comes before the tail."""
if setting > 0:
return setting
- return max(TAIL_MIN, min(TAIL_MAX, int(context_length * TAIL_SHARE)))
+ budget = max(TAIL_MIN, min(TAIL_MAX, int(context_length * TAIL_SHARE)))
+ return min(budget, threshold_tokens // 2) if threshold_tokens > 0 else budget
def hermes_value(module: str, name: str, default: Any) -> Any:
@@ -226,7 +229,8 @@ class WarmCompactionEngine(ContextEngine):
return tuple(dict.fromkeys(value for value in values if isinstance(value, str) and value))
def _tail_tokens(self) -> int:
- return tail_budget(int(self._settings["tail_tokens"]), int(self.context_length or 0))
+ return tail_budget(int(self._settings["tail_tokens"]), int(self.context_length or 0),
+ int(self.threshold_tokens or 0))
def _cancelled(self) -> bool:
check = getattr(self, "_compression_cancelled_check", None)
diff --git a/warm_compaction/rows.py b/warm_compaction/rows.py
index a23e3ae..48f69a4 100644
--- a/warm_compaction/rows.py
+++ b/warm_compaction/rows.py
@@ -60,8 +60,11 @@ def compact_json(value: Any) -> str:
def estimate_tokens(value: Any) -> int:
- """Estimate tokens: the UTF-8 bytes of the compact JSON form, divided by 4."""
- return math.ceil(len(compact_json(value).encode("utf-8", "surrogatepass")) / 4)
+ """Estimate tokens of the compact JSON form: the ASCII characters divided by 4, plus one token for each
+ other character. CJK text and emoji have about one token or more for each character."""
+ text = compact_json(value)
+ ascii_count = len(text.encode("ascii", "ignore"))
+ return math.ceil(ascii_count / 4) + len(text) - ascii_count
def row_digest(row: Any) -> str:
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index 0b8f820..4d3f6f0 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -93,9 +93,12 @@ def _arguments(value: Any) -> Any:
def _same_row(wire: Any, row: Any) -> bool:
- """True when the sent row carries the stored row: the same shape, the stored text inside the sent text
- (Hermes can add request-time context to a row), and the same tool-call arguments."""
- if _shape(wire) != _shape(row) or _words(attr(row, "content")) not in _words(attr(wire, "content")):
+ """True when the sent row carries the stored row: the same shape, the same name or no name (the Hermes
+ transport removes the name from some rows), the stored text inside the sent text (Hermes can add
+ request-time context to a row), and the same tool-call arguments."""
+ if _shape(wire) != _shape(row) or attr(wire, "name") not in (None, attr(row, "name")):
+ return False
+ if _words(attr(row, "content")) not in _words(attr(wire, "content")):
return False
return [_arguments(arguments) for _id, _name, arguments in tool_calls_of(wire)] == [
_arguments(arguments) for _id, _name, arguments in tool_calls_of(row)]