Skip to content

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

Drop payloads that the minimum cut does not fit, quote cut middles in the fixed summary, and set a handoff limit

Elevatormusic8803a623bf0c
diff --git a/README.md b/README.md
index 6136238..a2ec07b 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`. 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.
+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. If the earlier request had no limit, the warm request gets 8,192 tokens in the field that Hermes uses for the route (`max_completion_tokens` for OpenAI, Azure OpenAI, GitHub Copilot, and the newer OpenAI models; else `max_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
@@ -196,7 +196,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
## Limits
- The warm path needs a captured main-model request in the current Hermes process. After a restart or a resume, the first compaction uses the fallback summary if no main-model request completed before it (`no_capture`).
-- 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. Signed `reasoning_details` stay as they are. The fallback summary gets the cut middles. 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, 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). 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, 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 dc1501f..f73c818 100644
--- a/evidence/plugin-integration.json
+++ b/evidence/plugin-integration.json
@@ -1,22 +1,22 @@
{
"check": "standalone warm_compaction plugin on unpatched Hermes Agent",
- "started_utc": "2026-10-06T13:12:39Z",
+ "started_utc": "2026-10-06T13:29:33Z",
"hermes": {
"commit": "45871e100feceb89769536c88e5e6e265226a409",
"clean": true
},
"python": "3.11.14",
- "script_sha256": "74bb090a6af32a6e0994d3189c3ea9d551328a88e634501b1eaa09135aed3c2c",
+ "script_sha256": "08a2bedce89ede3a05576013351c1397e00bef0d50a24e28c9b6c0168d86c8ae",
"plugin_files_sha256": {
"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6",
"warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",
"warm_compaction/engine.py": "4364e59bc2f896a5ea138de88895c127e0a3d41e44586cdcac983905af2b194a",
- "warm_compaction/fallback.py": "30ef046f0511491175d99a772afcc2c9a8f3a9920d0c077821a89f19147682f9",
+ "warm_compaction/fallback.py": "8d03c6a86a975c1f7c0d13d53e14b6561ab46be705b2ff813c69cec4ce747974",
"warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",
- "warm_compaction/layout.py": "e0f5a265278f64bf89f826ccea04b084973c0fcf38df26effd53eb02a5dbd359",
+ "warm_compaction/layout.py": "2ade107c1b6fc4f4d1bc35e0118c17184d8fe241484aad4b36d03800acb965c7",
"warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",
"warm_compaction/rows.py": "689c0619df6a7f8b89ef05ae87ec81b62c812ce34f81bfe557eb653158effac4",
- "warm_compaction/warm.py": "081642f19498b379551af33b70ad01dae3902e1e805c360a08be9f74242d320f"
+ "warm_compaction/warm.py": "8122ac98d000a964fde02f9b1f7fa2e4d5379cedaf75641b80a7582d3deed8cc"
},
"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.098,
+ "compress_seconds": 0.109,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.023,
+ "elapsed_s": 0.026,
"prompt_tokens": 33883,
"cached_tokens": 16941
},
@@ -189,7 +189,7 @@
"install",
"run"
],
- "process_seconds": 53.019
+ "process_seconds": 57.387
},
{
"scenario": "manual_fallback",
@@ -248,7 +248,7 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.241,
+ "compress_seconds": 0.245,
"warm_last": {
"path": "fallback",
"reason": "provider_error",
@@ -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": 31.935
+ "process_seconds": 34.627
},
{
"scenario": "manual_fixed",
@@ -419,11 +419,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.24,
+ "compress_seconds": 0.279,
"warm_last": {
"path": "fixed",
"reason": "provider_error",
- "elapsed_s": 0.11,
+ "elapsed_s": 0.125,
"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": 29.927
+ "process_seconds": 32.876
},
{
"scenario": "auto_tool_loop",
@@ -627,7 +627,7 @@
"warm_last_2": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.015,
+ "elapsed_s": 0.016,
"prompt_tokens": 18427,
"cached_tokens": 9213
},
@@ -737,7 +737,7 @@
"install",
"run"
],
- "process_seconds": 33.118
+ "process_seconds": 35.944
},
{
"scenario": "rollback",
@@ -787,11 +787,11 @@
"threshold_tokens": 100000,
"context_length": 200000
},
- "compress_seconds": 0.21,
+ "compress_seconds": 0.162,
"warm_last": {
"path": "warm",
"reason": "accepted",
- "elapsed_s": 0.016,
+ "elapsed_s": 0.015,
"prompt_tokens": 33873,
"cached_tokens": 16936
},
@@ -973,10 +973,10 @@
"run",
"rollback"
],
- "process_seconds": 37.359
+ "process_seconds": 40.669
}
],
- "finished_utc": "2026-10-06T13:15:44Z",
+ "finished_utc": "2026-10-06T13:32:55Z",
"passed": true,
"run_folder": "outside repository"
}
diff --git a/scripts/check_plugin_hermes.py b/scripts/check_plugin_hermes.py
index 7907d83..ed679a7 100644
--- a/scripts/check_plugin_hermes.py
+++ b/scripts/check_plugin_hermes.py
@@ -671,10 +671,16 @@ def check_warm_request(server, checks, label, tool_rows=0):
if key not in {"messages", "stream", "stream_options", *limits}}
checks[f"{label}_settings_kept"] = all(warm["body"].get(key) == value for key, value in same.items())
# The handoff has its own reply limit: the main limit kept between HANDOFF_MIN_TOKENS and HANDOFF_MAX_TOKENS.
- checks[f"{label}_reply_limit"] = all(
- warm["body"].get(key) == (min(max(value, HANDOFF_MIN_TOKENS), HANDOFF_MAX_TOKENS)
- if type(value) is int and value > 0 else value)
- for key, value in ((key, main["body"].get(key)) for key in limits))
+ # Without a main limit, the handoff gets HANDOFF_MAX_TOKENS in one field (the field that Hermes uses).
+ if any(type(main["body"].get(key)) is int and main["body"].get(key) > 0 for key in limits):
+ checks[f"{label}_reply_limit"] = all(
+ warm["body"].get(key) == (min(max(value, HANDOFF_MIN_TOKENS), HANDOFF_MAX_TOKENS)
+ if type(value) is int and value > 0 else value)
+ for key, value in ((key, main["body"].get(key)) for key in limits))
+ else:
+ checks[f"{label}_reply_limit"] = sorted(
+ key for key in limits if warm["body"].get(key) == HANDOFF_MAX_TOKENS) in (
+ ["max_tokens"], ["max_completion_tokens"])
if tool_rows:
roles = [row.get("role") for row in extended[len(sent):]]
checks[f"{label}_tool_rows_sent"] = roles == ["assistant", *["tool"] * tool_rows, "user"]
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 336e94c..4923ab7 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -604,6 +604,16 @@ class EngineTest(unittest.TestCase):
self.assertIn("u" * 100, transcript)
self.assertTrue(any(str(row.get("content")).endswith(" end") for row in new))
+ 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", "{}")]),
+ tool("c1", "head " + "u" * 20_000 + " MIDDLE-FACT " + "u" * 20_000 + " end")]
+ engine = self.make(tail_tokens=2_000, warm=False)
+ new = engine.compress(rows)
+ self.assertEqual(engine.warm_last["path"], "fixed")
+ self.assertTrue(any("## Key facts" in str(row.get("content")) and "u" * 50 in str(row.get("content"))
+ for row in new))
+
def test_a_capture_with_a_changed_source_is_not_used_for_the_budget(self):
# A middleware removed a stored row: the captured body no longer shows which rows are the system rows.
from warm_compaction.rows import estimate_tokens
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index 749288c..4c459c4 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -203,6 +203,15 @@ class LlmSummaryTest(unittest.TestCase):
class FixedSummaryTest(unittest.TestCase):
+ def test_the_fixed_summary_quotes_the_cut_middles(self):
+ # Without a model summary, the middles that the tail cut are not lost: a bounded quote keeps them.
+ from warm_compaction.layout import CUT_NOTE
+ rows = [user("old"), assistant("a"), tool("c1", CUT_NOTE + "REQ-42 must stay " + "m" * 40_000 + " REQ-END")]
+ text = fixed_summary(rows)
+ self.assertIn("REQ-42 must stay", text)
+ self.assertIn("REQ-END", text)
+ self.assertLess(len(text), 12_000)
+
def test_five_headings_and_tool_counts(self):
rows = [assistant("", [("c1", "read", "{}"), ("c2", "read", "{}")]), assistant("", [("c3", "ls", "{}")])]
text = fixed_summary(rows)
diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.py
index c9f890f..3aab847 100644
--- a/tests/test_wc_layout.py
+++ b/tests/test_wc_layout.py
@@ -241,6 +241,20 @@ class BoundTailTest(unittest.TestCase):
self.assertEqual(len(removed), 2)
self.assertTrue(all(part["content"].startswith(CUT_NOTE) for part in removed))
+ def test_a_cap_below_the_minimum_cut_drops_the_payloads(self):
+ # Short rows, and many small parts: the minimum cut is not enough, so the payloads are dropped (the
+ # fallback gets them whole). Only the row structure stays.
+ from warm_compaction.layout import CUT_NOTE, DROPPED, bound_tail
+ from warm_compaction.rows import estimate_tokens
+ for rows, tokens, whole in (([user("x" * 150), assistant("y" * 150)], 20, "x" * 150),
+ ([user(["p" * 100] * 20), assistant("ok")], 100, "p" * 100)):
+ with self.subTest(tokens=tokens):
+ removed = []
+ bounded = bound_tail(rows, tokens, removed)
+ self.assertLessEqual(sum(estimate_tokens(row) for row in bounded), tokens)
+ self.assertIn(CUT_NOTE + whole, [part["content"] for part in removed])
+ self.assertTrue(any(DROPPED in str(row["content"]) for row in bounded))
+
def test_the_cut_middles_are_given_back(self):
# The fallback summary gets the parts that the tail cuts: they are not lost.
from warm_compaction.layout import CUT_NOTE, bound_tail
diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.py
index 9ad7be1..605d9b6 100644
--- a/tests/test_wc_warm.py
+++ b/tests/test_wc_warm.py
@@ -7,7 +7,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from warm_compaction.rows import estimate_tokens
from warm_compaction.warm import (
- DEFAULT_RESERVE, HANDOFF_MAX_TOKENS, ends_with_instruction, HANDOFF_MIN_TOKENS, SAFETY, WarmRefusal, build_request, check_settings, fits, send, split_history, urllib_post,
+ 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
@@ -207,13 +207,24 @@ class BuildRequestTest(unittest.TestCase):
({"max_tokens": 3_000}, {"max_tokens": 3_000}),
({"max_tokens": 60_000}, {"max_tokens": HANDOFF_MAX_TOKENS}),
({"max_completion_tokens": 500}, {"max_completion_tokens": HANDOFF_MIN_TOKENS}),
- ({}, {}))
+ # Without a limit the server default applies: it can cut the handoff, or reserve more than the
+ # capacity check does. The handoff gets its own limit in the field that Hermes uses for the route.
+ ({}, {"max_tokens": HANDOFF_MAX_TOKENS}))
for extra, expected in cases:
with self.subTest(extra=extra):
body = self.build(capture_for(self.rows, self.reply, body_extra=extra))
self.assertEqual({key: body[key] for key in ("max_tokens", "max_completion_tokens") if key in body},
expected)
+ def test_a_route_that_needs_max_completion_tokens_gets_it(self):
+ for route in (("gpt-5.1", ROUTE[1], ROUTE[2]), ("m", "https://api.openai.com/v1", ROUTE[2]),
+ ("m", "https://x.openai.azure.com/v1", ROUTE[2])):
+ with self.subTest(route=route):
+ capture = capture_for(self.rows, self.reply, route=route)
+ body = self.build(capture, route=route)
+ self.assertEqual(body.get("max_completion_tokens"), HANDOFF_MAX_TOKENS)
+ self.assertNotIn("max_tokens", body)
+
def test_a_large_main_reply_limit_does_not_refuse_a_handoff_that_fits(self):
capture = capture_for(self.rows, self.reply, body_extra={"max_tokens": 60_000})
self.build(capture, context_length=20_000)
@@ -445,13 +456,14 @@ class BuildRequestTest(unittest.TestCase):
capture = capture_for(self.rows, self.reply)
body = self.build(capture, context_length=0)
sent = len(capture["body"]["messages"])
- whole = estimate_tokens({"messages": body["messages"], "tools": None}) * SAFETY + DEFAULT_RESERVE
+ # The capture has no reply limit: the handoff gets HANDOFF_MAX_TOKENS, and the check reserves it.
+ whole = estimate_tokens({"messages": body["messages"], "tools": None}) * SAFETY + HANDOFF_MAX_TOKENS
window = int(whole) - 1
with self.assertRaises(WarmRefusal) as caught:
self.build(capture, context_length=window)
self.assertEqual(caught.exception.code, "capacity")
capture["prompt_tokens"] = 1
- self.assertLess(1 + estimate_tokens({"messages": body["messages"][sent:]}) * SAFETY + DEFAULT_RESERVE, window)
+ self.assertLess(1 + estimate_tokens({"messages": body["messages"][sent:]}) * SAFETY + HANDOFF_MAX_TOKENS, window)
self.assertEqual(self.build(capture, context_length=window)["messages"], body["messages"])
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index f8a3c39..ee15a94 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -7,7 +7,7 @@ import logging
from typing import Any, Iterable
from .handoff import END_MARKER, LEGACY_PREFIX, extras, gate
-from .layout import is_real_user, is_summary, quote
+from .layout import CUT_NOTE, is_real_user, is_summary, quote
from .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,
@@ -27,6 +27,8 @@ ARGUMENT_CHARS = 300
CUT_MARK = " [cut]"
ROW_CHARS = 4_000
MIN_PART_CHARS = 200
+# The fixed summary quotes the middles that the tail cut (layout.bound_tail): at most this many characters.
+CUT_QUOTE_CHARS = 8_000
# 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
@@ -225,6 +227,14 @@ def fixed_summary(messages: list, prefixes: Iterable[str] = ()) -> str:
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)]
+ cut = [text[len(CUT_NOTE):] for text in (attr(row, "content") for row in messages)
+ if isinstance(text, str) and text.startswith(CUT_NOTE)]
+ if cut:
+ # The tail keeps only the start and end of these newest payloads: without a model summary, a bounded quote
+ # of their middles keeps the requirements and the tool output that they have.
+ each = max(MIN_PART_CHARS, CUT_QUOTE_CHARS // len(cut))
+ facts.append("- Parts that the tail cut from the newest rows (their start and end):")
+ facts += [quote(_bound(text, each, each // 4, middle=True)) for text in cut[-(CUT_QUOTE_CHARS // each):]]
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.py
index c806b61..24f3f99 100644
--- a/warm_compaction/layout.py
+++ b/warm_compaction/layout.py
@@ -14,6 +14,8 @@ HEADER_TEXT = "The summary of the earlier turns follows."
COPY_HEADING = "## Copied user messages"
COPY_EACH = 4_000
MIN_COPY_CHARS = 200
+# A payload that even the minimum cut does not fit: it is dropped, and the fallback summary gets all of it.
+DROPPED = "[cut]"
CUT_NOTE = "[The middle of a newest row; its start and end stay after the summary.]\n"
NO_COPIES = "(none)"
STEER_KIND = "steer"
@@ -292,7 +294,9 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:
largest sent payloads (_tail_parts) are cut to their start and end, until the rows fit or no payload has more
than MIN_COPY_CHARS characters. A tool call keeps its id and name, and its arguments stay a JSON object. A
media part (an image, for example) is replaced by a short text. Other rows and fields stay as they are; signed
- reasoning_details stay, because a cut breaks the signature.
+ reasoning_details stay, because a cut breaks the signature. When the minimum cuts are not enough (a small cap,
+ or many small payloads), the payloads are dropped (DROPPED), largest first. Only the row structure (roles, tool
+ call ids and names) can then stay above the cap.
With a removed list, one row for each cut payload is added to it: the removed middle after CUT_NOTE, with the
role (and the tool call id) of the row. The fallback summary can then keep what the tail cuts."""
@@ -300,21 +304,29 @@ def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:
originals: dict[tuple, Any] = {}
current: dict[tuple, Any] = {}
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(estimate_tokens(row) for row in rows) > tokens:
cuttable = []
for index, row in enumerate(rows):
for key, value in _tail_parts(row):
value = current.get((index, key), value)
- if (isinstance(value, str) and len(value) > MIN_COPY_CHARS) or (
+ if (isinstance(value, str) and len(value) > max(floor, len(DROPPED))) or (
key[0] == "media" and (index, key) not in current
- and estimate_tokens(value) > MIN_COPY_CHARS // 4):
+ and estimate_tokens(value) > floor // 4):
cuttable.append((estimate_tokens(value), index, key, value))
if not cuttable:
+ if floor:
+ floor = 0
+ continue
break
cost, index, key, value = max(cuttable, key=lambda item: (item[0], -item[1]))
originals.setdefault((index, key), value)
if key[0] == "media":
new_value: Any = {"type": "text", "text": f"[{value.get('type') or 'media'} removed]"}
+ elif not floor:
+ limits[(index, key)] = 0
+ new_value = DROPPED
else:
target = cost - (sum(estimate_tokens(row) for row in rows) - tokens)
limit = max(MIN_COPY_CHARS, min(len(value) - 1, len(value) * max(target, 0) // max(cost, 1)))
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index 0e70158..60b36c1 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -216,6 +216,25 @@ def _signature(extra: Any) -> Any:
REPLAY_DETAILS_HOSTS = ("openrouter.ai", "nousresearch.com")
+LIMIT_KEYS = ("max_tokens", "max_completion_tokens")
+
+
+def _forces_completion_field(model: Any) -> bool:
+ """Hermes 45871e10 (utils.model_forces_max_completion_tokens): OpenAI families that reject max_tokens."""
+ name = str(model or "").strip().lower().rsplit("/", 1)[-1]
+ return name.startswith(("gpt-4o", "gpt-4.1", "gpt-5", "o1", "o3", "o4"))
+
+
+def limit_field(model: Any, base_url: Any) -> str:
+ """The reply limit field that Hermes 45871e10 sends on the route (AIAgent._max_tokens_param):
+ max_completion_tokens for OpenAI, Azure OpenAI, GitHub Copilot, and the newer OpenAI model families, else
+ max_tokens."""
+ host = (urllib.parse.urlparse(str(base_url or "")).hostname or "").lower()
+ forces = hermes_value("utils", "model_forces_max_completion_tokens", _forces_completion_field)
+ if (host == "api.openai.com" or host == "openai.azure.com" or host.endswith(".openai.azure.com")
+ or host.endswith(".githubcopilot.com") or forces(model)):
+ return "max_completion_tokens"
+ return "max_tokens"
def _route_replays_reasoning_details(base_url: Any) -> bool:
@@ -375,10 +394,14 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, context
request.pop("web_search_options", None)
# The reply limit of the main request is for another task: a small one cuts the handoff, a large one reserves
# space that the handoff does not need. Keep the field that the route uses.
- for key in ("max_tokens", "max_completion_tokens"):
+ for key in LIMIT_KEYS:
value = body.get(key)
if type(value) is int and value > 0:
request[key] = min(max(value, HANDOFF_MIN_TOKENS), HANDOFF_MAX_TOKENS)
+ # Without a limit the server default applies: a small one cuts the handoff, a large one can take more space
+ # than the capacity check reserves. The handoff gets HANDOFF_MAX_TOKENS in the field of the route.
+ if not any(type(body.get(key)) is int and body.get(key) > 0 for key in LIMIT_KEYS):
+ request[limit_field(body.get("model"), route[1])] = HANDOFF_MAX_TOKENS
if not fits(request, context_length, capture.get("prompt_tokens"), len(body["messages"])):
raise WarmRefusal("capacity")
return request