Skip to content

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

Apply review fixes to the fallback retry

Elevatormusicf4b3e6e1bc93
diff --git a/README.md b/README.md
index 294f1f2..1879064 100644
--- a/README.md
+++ b/README.md
@@ -206,7 +206,7 @@ The complete body still has at most 2,048 estimated tokens. The original reply m
Each request gets a fresh random end marker, in the form `[END OF SUMMARY <nonce>]`. The reply must contain that exact marker once, as its final visible line. The plugin removes the marker before it stores the summary. A fixed marker, an old marker, text after the marker, or a missing marker fails the check. This checks the reply format. It does not prove that every fact is correct or tell the plugin why the server stopped; the public auxiliary API does not report a finish reason.
-If a reply fails the checks, the plugin retries once; a missing or duplicated end marker earns one more retry. Each retry uses the same original transcript, a fresh marker, and a shorter summary instruction of at most 300 words. When the failure is a missing or duplicated end marker, the retry repeats the marker requirement explicitly. It does not try to complete a partial reply. All calls share a 120-second deadline. The plugin checks cancellation and route changes before each call and after each reply. It does not retry a request error. If no reply passes, it preserves the input history.
+If a reply fails the checks, the plugin retries once. After any reply fails the end-marker check (missing or duplicated marker), it can retry one more time: at most three calls. Each retry uses the same original transcript, a fresh marker, and a shorter summary instruction of at most 300 words. After an end-marker failure, the retry states the marker requirement explicitly. It does not try to complete a partial reply. All calls share a 120-second deadline. A retry starts only when at least a quarter of that time remains; otherwise the plugin reports the failure of the previous reply. The plugin checks cancellation and route changes before each call and after each reply. It does not retry a request error. If no reply passes, it preserves the input history.
When the server applies the requested generation limit, the request is about 18,000 tokens or less: about 8,000 transcript tokens, the instruction, and up to 8,192 generated tokens. The focus topic and memory context take their space from the transcript budget. Use a fallback model with at least a 24,000-token context window. The deadline can prevent a retry or reject a late reply, but the public API cannot stop an in-flight call. Hermes controls its own retries, so two plugin calls can cause more than two server requests.
@@ -339,7 +339,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
- Responses and Anthropic Messages use their own source checks. Native signed and encrypted replay records stay whole and count in tail estimates. A record that leaves no room for a valid new history fails with `path=aborted` and a safe capacity code, without replacing the input history. See [Provider support](docs/provider-support.md).
- 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`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. 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 its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. 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. The fallback body is limited to 2,048 estimated tokens, including dense CJK text. The existing 4,096-token reserve also leaves room for bounded quotes. If the summary and quotes cannot fit safely, the current compaction pass stops and preserves its input history. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; the native-assistant entry type that the provider profile declares (`native_reasoning_details_type`) counts on every route of the provider, as Hermes replays it; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. When no quote fits there, the current compaction pass stops and preserves its input history. A fallback summary that does not fit in the free room also stops the current compaction pass. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. A warm reply body above 1 MiB is not read (reason `response_too_large`). The fallback request does not start after a model, provider, or session switch. The plugin API has no request on a fixed route (an override needs a trust setting), so a switch in the short time after that check, before the host resolves the auxiliary route, can still send the transcript to the new route. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. 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 summary, the prepended row, and the tail take 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 same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.
-- Responses warm requests are streamed; Chat Completions and Messages warm requests are not streamed. No warm request is retried. Its time limit is 120 seconds. The fallback has one shared 120-second deadline for at most two plugin calls (three when the failure is a missing or duplicated end marker); the host can keep an in-flight call running beyond that deadline. Native formats have additional limits in [Provider support](docs/provider-support.md).
+- Responses warm requests are streamed; Chat Completions and Messages warm requests are not streamed. No warm request is retried. Its time limit is 120 seconds. The fallback has one shared 120-second deadline for at most two plugin calls (three after an end-marker failure); the host can keep an in-flight call running beyond that deadline. Native formats have additional limits in [Provider support](docs/provider-support.md).
- On Chat Completions routes, per-request `extra_headers` supports only one `x-opencode-session` header, with a non-empty plain ASCII string value, no control characters, and no leading or trailing space. Other headers, duplicate names with different case, non-empty `extra_query`, or an invalid `extra_body` use the fallback (`request_options_unsupported`). A JSON `extra_body.extra_headers` field cannot be combined with the session header. A request with `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.
- Each new agent writes this Hermes warning to the log: `Context engine 'warm_compaction' loaded but no engine instance found`. Hermes first tries its context engine loader, which cannot make this engine. Then Hermes uses the engine of the enabled plugin. The warning has no effect.
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index d385b4f..ec98f6e 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -245,6 +245,46 @@ class LlmSummaryTest(unittest.TestCase):
self.assertIn("did not end with the marker line", second[0][0]["content"])
self.assertEqual(failure, {})
+ def test_duplicate_marker_retry_asks_for_the_marker_exactly_once(self):
+ def reply(messages, kwargs, count):
+ marker = self.marker(messages)
+ body = useful_summary("hi")
+ return body + " " + marker + "\n" + marker if count == 1 else body + "\n" + marker
+ llm = FakeLlm(text=reply)
+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES), (useful_summary("hi"), 321))
+ second = llm.calls[1][0][0]["content"]
+ self.assertIn("had the marker line more than once", second)
+ self.assertIn("exactly once", second)
+ self.assertNotIn("did not end with the marker line", second)
+
+ def test_a_marker_failure_grants_the_third_attempt_in_either_order(self):
+ # Synthetic replies: SUMMARY with the marker fails the content check (no_useful_evidence).
+ for order in (("missing", "content"), ("content", "missing")):
+ with self.subTest(order=order):
+ def reply(messages, kwargs, count, order=order):
+ kind = order[count - 1] if count <= 2 else "content"
+ return SUMMARY if kind == "missing" else SUMMARY + "\n" + self.marker(messages)
+ llm, failure = FakeLlm(text=reply), {}
+ with self.assertLogs("warm_compaction.fallback", level="WARNING"):
+ self.assertEqual(llm_summary(llm, [user("Check JOB-X3.")], PREFIXES, failure=failure),
+ (None, None))
+ self.assertEqual(len(llm.calls), 3)
+ self.assertEqual((failure["reason"], failure["attempts"]), ("gate:no_useful_evidence", 3))
+
+ def test_no_retry_with_too_little_time_reports_the_previous_gate_failure(self):
+ clock = [0.0]
+
+ def reply(messages, kwargs, count):
+ clock[0] += 16.0 # 4 s of 20 s remain: less than RETRY_MIN_SHARE of the limit.
+ return SUMMARY
+ llm, failure = FakeLlm(text=reply), {}
+ with patch("warm_compaction.fallback.time.monotonic", side_effect=lambda: clock[0]), \
+ self.assertLogs("warm_compaction.fallback", level="WARNING"):
+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, timeout_s=20.0, failure=failure), (None, None))
+ self.assertEqual(len(llm.calls), 1)
+ self.assertEqual((failure["reason"], failure["attempts"], failure["end_marker"]),
+ ("gate:missing_end_marker", 1, "missing"))
+
def test_third_attempt_passes_after_two_missing_markers(self):
def reply(messages, kwargs, count):
body = useful_summary("hi")
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index f0c2d13..ff03aba 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -27,12 +27,16 @@ PURPOSE = "warm_compaction_fallback"
MAX_TOKENS = 2048
MAX_STATE_TOKENS = 512
REQUEST_MAX_TOKENS = 8192
-# The attempts of one fallback summary. A missing or duplicated end marker gets the first reply plus up to
-# two retries (three attempts); every other gate failure stops after the first reply plus one retry (two), so
-# a hopeless content failure does not burn a third summary call.
+# The attempts of one fallback summary. After a reply fails the end-marker check (at any attempt), the summary
+# gets up to three attempts; otherwise it stops after two, so a hopeless content failure does not use a third
+# summary call.
MAX_ATTEMPTS = 3
MAX_ATTEMPTS_OTHER = 2
+MARKER_FAILURES = ("missing_end_marker", "duplicate_end_marker")
TIMEOUT_S = 120.0
+# A retry starts only when this share of the time limit remains. The host cannot stop an in-flight call, so a
+# retry with too little time keeps a slow model busy and then fails on the deadline.
+RETRY_MIN_SHARE = 0.25
TRANSCRIPT_CHARS = 32_000
EARLIER_SUMMARY_CHARS = 8_000
FIRST_USER_CHARS = 4_000
@@ -330,6 +334,20 @@ def _complete_reply(raw: str, end_line: str) -> tuple[str | None, str]:
return None, "\n".join(lines[:-1])
+def _refuse(failure: dict[str, Any] | None, reason: str | None, result: Any, raw: str, end_line: str, body: str,
+ attempts: int) -> tuple[None, None]:
+ """Record a gate refusal with safe reply metadata only, and return (None, None)."""
+ metadata = _reply_metadata(result, raw, end_line, body, attempts)
+ if failure is not None:
+ failure["reason"] = f"gate:{reason}"
+ failure.update(metadata)
+ logger.warning("Warm compaction fallback summary refused (%s) output_tokens=%s requested_max_tokens=%s "
+ "end_marker=%s attempts=%s body_tokens=%s", reason, metadata["output_tokens"],
+ metadata["requested_max_tokens"], metadata["end_marker"], metadata["attempts"],
+ metadata["body_tokens"])
+ return None, None
+
+
def _reply_metadata(result: Any, raw: str, end_line: str, body: str, attempts: int) -> dict[str, Any]:
"""Return bounded counts and fixed codes. Do not return reply text or the nonce."""
output = getattr(getattr(result, "usage", None), "output_tokens", None)
@@ -573,7 +591,8 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
failure: dict[str, Any] | None = None) -> tuple[str | None, int | None]:
"""Return (summary text, prompt tokens) from ctx.llm, or (None, None) when the request or the reply fails.
ready checks the route and cancellation before each call and after each reply.
- An invalid reply gets one retry; a missing or duplicated end marker gets two. All calls share one time limit.
+ An invalid reply gets one retry; after an end-marker failure it gets two. All calls share one time limit, and
+ a retry starts only when RETRY_MIN_SHARE of it remains.
failure gets safe codes and bounded reply metadata only. It never gets provider text."""
if failure is not None:
failure.clear()
@@ -588,16 +607,22 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
content: list[str] = []
original = transcript(messages, prefixes, len(extra), estimate_tokens(extra), _content=content)
source = _SourceTable(original, _earlier_summary(messages, prefixes), extra, content)
- reason: str | None = None # The previous attempt's failure code; the loop only continues on one.
+ reason: str | None = None # The failure code of the previous attempt; the loop only continues after one.
+ marker_failed = False # True after any reply failed the end-marker check.
+ refused: tuple[Any, str, str, str] = (None, "", "", "") # The previous refused reply: result, raw, end_line, body.
for attempt in range(1, MAX_ATTEMPTS + 1):
end_line = END_LINE.replace("{nonce}", secrets.token_hex(16))
words = int(summary_words) if attempt == 1 else min(int(summary_words), 300)
instruction = FALLBACK_INSTRUCTION_TEMPLATE.replace(SUMMARY_WORDS_TOKEN, str(words))
instruction = instruction.replace(END_LINE, end_line)
if attempt > 1:
- # The dominant failure of a local model is the missing marker line; repeat that requirement
- # instead of the generic shorter-summary note. reason is the last attempt's failure code.
- if reason in ("missing_end_marker", "duplicate_end_marker"):
+ # The most frequent failure of a local model is the marker line; state that requirement instead of the
+ # generic shorter-summary note.
+ if reason == "duplicate_end_marker":
+ extra_instruction = ("\nThe previous reply had the marker line more than once. Write the "
+ "summary again. Write the marker line below exactly once, as the final "
+ "line of your reply, with nothing after it.\n")
+ elif reason == "missing_end_marker":
extra_instruction = ("\nThe previous reply did not end with the marker line. Write the "
"summary again. The marker line below must be the final line of "
"your reply, with nothing after it.\n")
@@ -620,6 +645,9 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
if failure is not None:
failure["reason"] = "deadline"
return None, None
+ if attempt > 1 and remaining < timeout_s * RETRY_MIN_SHARE:
+ # Too little time for a retry: report the failure of the previous reply.
+ return _refuse(failure, reason, *refused, attempt - 1)
try:
result = llm.complete(request, task=task, max_tokens=REQUEST_MAX_TOKENS,
timeout=remaining, purpose=PURPOSE)
@@ -663,18 +691,11 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
if text is not None:
tokens = getattr(getattr(result, "usage", None), "input_tokens", None)
return text, tokens if isinstance(tokens, int) and not isinstance(tokens, bool) and tokens > 0 else None
- if attempt >= (MAX_ATTEMPTS if reason in ("missing_end_marker", "duplicate_end_marker")
- else MAX_ATTEMPTS_OTHER):
- metadata = _reply_metadata(result, raw, end_line, body, attempt)
- if failure is not None:
- failure["reason"] = f"gate:{reason}"
- failure.update(metadata)
- logger.warning("Warm compaction fallback summary refused (%s) output_tokens=%s requested_max_tokens=%s "
- "end_marker=%s attempts=%s body_tokens=%s", reason, metadata["output_tokens"],
- metadata["requested_max_tokens"], metadata["end_marker"], metadata["attempts"],
- metadata["body_tokens"])
- return None, None
- return None, None
+ marker_failed = marker_failed or reason in MARKER_FAILURES
+ refused = (result, raw, end_line, body)
+ if attempt >= (MAX_ATTEMPTS if marker_failed else MAX_ATTEMPTS_OTHER):
+ return _refuse(failure, reason, *refused, attempt)
+ return None, None # Not reached: the last attempt returns in the loop.
def cut_quote(rows: list, max_tokens: int) -> str: