Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Fix Anthropic blank rows and stop compaction when no summary can fit
Elevatormusic241e683f8efa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2c9dc42..1a78418 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,8 @@ All notable changes are listed here. The format follows [Keep a Changelog](https- Use the exact bounded focus and memory block sent to the fallback as a separate source block. Keep the existing request reserve and reject an encoded prior quote that also occurs inside an ordinary source line.- Construct all five fallback sections from complete source lines. Restore the complete line for a unique exact quoted part. Decode one JSON layer from a recognized, bounded earlier summary without wrapping prior quotes again or decoding copied user messages as Next step. Keep Unicode separators inside valid JSON bullets. Drop ambiguous, malformed, cut, oversized, or changed evidence and report each field unknown. Deduplicate identical decoded quotes without reporting a loss. Each section has a 512-token bound; the complete body keeps its 2,048-token bound. Keep evidence in the order User instructions, Next step, Goal, Current state, Key facts. Repair that keeps source content needs no retry. Source support does not prove truth, applicability, evidence selection, or complete retention.- Report safe fallback token counts, request limits, attempt counts, and end-marker status when a reply is refused. Keep summary text and random markers out of status and logs. Document a task configuration workaround for Hermes versions that omit the generation limit on custom Chat Completions routes; a general correction remains a Hermes dependency.+- Stop before both summary requests when a usable capture shows zero summary room below the compaction threshold or context limit. Report `summary_too_large` for both paths and preserve history. Keep the normal fallback when the request overhead is unknown.+- Match the blank-text rules of Hermes `6e7b83a` on Anthropic Messages routes: omit blank text blocks and use `(empty)` for an empty assistant turn. Keep nonblank text, signed thinking, tool data, and the captured prefix unchanged. Other unsupported transforms still use the fallback. This fixes a synthetic mismatch class; it does not establish the cause on a modified Hermes install.- Accept unchanged stored `reasoning` text in captured Chat Completions assistant rows. Do not require reasoning padding on captured summary or notice rows that have no reasoning. Keep checks for changed text, reasoning details, and tool signatures, and keep the captured request prefix unchanged.- Match captured content with the stored `api_content` text for context-injected rows. Keep role, tool, and native replay checks. Report each history refusal stage and use the fallback when the capture is ahead of the live history.- Keep the original history when an indivisible native replay block exceeds the compaction budget. Check the threshold, reply reserve, and unknown request overhead before accepting the new history.diff --git a/README.md b/README.mdindex e4954b0..ddc5530 100644--- a/README.md+++ b/README.md@@ -178,6 +178,12 @@ plugins:threshold: 0.5```+The threshold also limits the request after compaction. The fixed system prompt and tool schemas must fit below it, with room for the summary and retained rows. For example, `threshold: 0.15` on a 131,072-token window gives 19,660 tokens. A fixed prefix of about 41,000 tokens already exceeds that limit. No smaller summary can make that request fit below the threshold, even though the full context window has room. Start with the default `0.5`, or select a threshold above the fixed overhead with room for the summary and tail. The request must also fit in the context window with its reply reserve. Lowering the threshold can cause `summary_too_large`. The plugin estimates these sizes; provider token counters can use a different tokenizer.++If a usable capture shows zero room for a summary after the fixed overhead, reply reserve, and summary row structure, the plugin stops that compaction pass before either model summary request. It reports `path=aborted`, `reason=summary_too_large`, and `fallback_reason=summary_too_large`. History and the capture stay unchanged. An unknown overhead does not trigger this early check. Hermes controls any later retry.++`gate:finish_not_stop` means that the warm reply did not report `finish_reason: stop`. It does not by itself prove that the reply reached its output limit. Use the finish reason and completion-token count from a synthetic test to check that cause before changing `summary_words`. A host fallback timeout alone does not identify a provider cause or prove that its output limit was reached.+On Chat Completions routes, 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 also keeps a captured `x-opencode-session` request header. Hermes can add this header automatically for OpenCode routes. The captured value stays in memory and overrides a default header with the same name, without regard to case. It goes through both middleware checks and is sent as an HTTP header, never as a JSON field. 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 keysdiff --git a/docs/provider-support.md b/docs/provider-support.mdindex 73d3aa1..454390d 100644--- a/docs/provider-support.md+++ b/docs/provider-support.md@@ -24,6 +24,8 @@ Native server compaction checkpoints, stateful `previous_response_id` or conversThe request keeps the captured native `messages` prefix, system blocks, tools, cache markers, tool choice, and thinking settings. The warm request uses `/v1/messages`. Native replies use their stop reason and content blocks; the reader also accepts complete native SSE replies.+For text rows, the adapter follows the blank-text rules in Hermes `6e7b83a`: omit blank text blocks, use `(empty)` for an empty assistant turn, and use `(empty message)` for an empty user turn. It keeps every byte of nonblank text and of the captured prefix. Other changes that the adapter cannot match safely to stored history still use the fallback. A `source_transform_unsupported` code alone does not prove that a plugin or middleware changed the rows.+The adapter uses `x-api-key`, `anthropic-version`, the checked Hermes beta defaults, and custom provider headers. Claude Code OAuth or subscription authentication, bearer routes (MiniMax, Kimi, CommandCode, Palantir, and Nous), Azure/Entra authentication, and Bedrock remain on the fallback. Custom `Authorization` headers also refuse. Their authentication and final-client transformations need separate integration work.Forced or server tools, media, structured output, unknown request controls, and unproved replay blocks use the fallback. Signed thinking is replayed only on the native Anthropic host. A manual thinking budget stays unchanged; the output limit leaves at least 2,048 tokens after that budget. A request that then exceeds the window uses the fallback.diff --git a/scripts/check_provider_apis.py b/scripts/check_provider_apis.pyindex 0aaa2f6..c72a46e 100644--- a/scripts/check_provider_apis.py+++ b/scripts/check_provider_apis.py@@ -26,7 +26,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerROOT = Path(__file__).resolve().parents[1]CASES = ("responses_text", "responses_tool", "responses_incomplete","responses_codex", "responses_codex_reasoning", "anthropic_text", "anthropic_tool",- "anthropic_refusal", "anthropic_signed")+ "anthropic_refusal", "anthropic_signed", "anthropic_blank_text")MODEL = "synthetic-model"KEY = "synthetic-api-key"SYSTEM = "You are a synthetic test agent. Keep the code word BLUE-7."@@ -96,6 +96,11 @@ def history_for(case):elif case == "anthropic_signed":rows[1]["reasoning_details"] = [{"type": "thinking", "thinking": "Synthetic earlier thought.","signature": "synthetic-old-signature"}]+ elif case == "anthropic_blank_text":+ rows[1]["content"] = " \t\n"+ rows[3]["content"] = [{"type": "text", "text": " \n"},+ {"type": "text", "text": " Synthetic nonblank text.\n"},+ {"type": "text", "text": ""}]return rows@@ -321,6 +326,12 @@ def worker(source, case, dependency_paths):checks["main_instructions_exact"] = main["body"].get("instructions") == SYSTEMelse:checks["main_system_exact"] = main["body"].get("system") == SYSTEM+ if case == "anthropic_blank_text":+ native_rows = main["body"]["messages"]+ checks["stock_empty_assistant_placeholder"] = native_rows[1]["content"] == [+ {"type": "text", "text": "(empty)"}]+ checks["stock_drops_only_blank_text_blocks"] = native_rows[3]["content"] == [+ {"type": "text", "text": " Synthetic nonblank text.\n"}]row = {"role": "assistant", "content": normalized.content or ""}row.update(normalized.provider_data or {})if normalized.tool_calls:diff --git a/tests/test_wc_anthropic.py b/tests/test_wc_anthropic.pyindex 4156ed8..33a0147 100644--- a/tests/test_wc_anthropic.py+++ b/tests/test_wc_anthropic.py@@ -78,6 +78,52 @@ class BuildTest(unittest.TestCase):body = self.build()self.assertEqual(body["messages"][1]["content"][0], block)+ def test_source_blank_text_matches_stock_hermes_without_changing_the_prefix(self):+ # Synthetic stored rows and literal wire rows follow Hermes 6e7b83a.+ for blank in (None, "", " \t\n", [{"type": "text", "text": " \t\n"}]):+ with self.subTest(blank=blank):+ rows = [user("task"), assistant(blank), user("next")]+ cap = capture(rows, self.reply)+ cap["body"]["messages"] = [+ {"role": "user", "content": "task"},+ {"role": "assistant", "content": [{"type": "text", "text": "(empty)"}]},+ {"role": "user", "content": "next"},+ ]+ before = copy.deepcopy((cap, rows))+ body = self.build(cap, [*rows, self.reply])+ self.assertEqual(body["messages"][:3], cap["body"]["messages"])+ self.assertEqual((cap, rows), before)++ def test_blank_blocks_are_dropped_without_trimming_nonblank_text(self):+ text = " synthetic code\n"+ rows = [user("task"), assistant([+ {"type": "text", "text": " \n"}, {"type": "text", "text": text},+ {"type": "text", "text": ""},+ ]), user("next")]+ cap = capture(rows, self.reply)+ cap["body"]["messages"][1]["content"] = [{"type": "text", "text": text}]+ self.build(cap, [*rows, self.reply])+ for changed in (text.strip(), text.rstrip(), "changed"):+ with self.subTest(changed=changed):+ cap["body"]["messages"][1]["content"][0]["text"] = changed+ self.refusal("source_transform_unsupported", lambda: self.build(cap, [*rows, self.reply]))++ def test_new_blank_assistant_uses_the_stock_hermes_placeholder(self):+ reply = assistant(" \t\n")+ cap = capture(self.rows, reply)+ body = self.build(cap, [*self.rows, reply])+ self.assertEqual(body["messages"][-2], {+ "role": "assistant", "content": [{"type": "text", "text": "(empty)"}]})++ def test_blank_text_next_to_signed_thinking_and_tools_is_not_replayed(self):+ thought = {"type": "thinking", "thinking": "synthetic", "signature": "fake-signature"}+ call = {"type": "tool_use", "id": "c1", "name": "read", "input": {}}+ reply = assistant(" \n", [("c1", "read", "{}")], reasoning_details=[thought],+ anthropic_content_blocks=[thought, {"type": "text", "text": " \n"}, call])+ cap = capture(self.rows, reply)+ body = self.build(cap, [*self.rows, reply, tool("c1", "synthetic output")])+ self.assertEqual(body["messages"][-2]["content"], [thought, call])+def test_new_reasoning_and_media_are_refused(self):for key in anthropic.OPAQUE_ROWS:with self.subTest(key=key):diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex df3896d..aa0c7cc 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -661,6 +661,78 @@ class EngineTest(unittest.TestCase):self.assert_aborted(engine, [*rows, reply], "summary_too_large")self.assertEqual(len(self.llm.calls), 1)+ def test_known_zero_summary_room_stops_before_either_model_request(self):+ for settings in ({"threshold": 0.15, "prefix": "fixed " * 30_000, "max_tokens": 4096},+ {"threshold": 0.95, "prefix": "Synthetic rule.", "max_tokens": 131_072}):+ with self.subTest(settings={key: value for key, value in settings.items() if key != "prefix"}):+ engine = self.make(threshold=settings["threshold"])+ engine.update_model(model=ROUTE[0], context_length=131_072, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ rows, reply = old_turns(8), assistant("final")+ self.seed(rows, reply, system={"role": "system", "content": settings["prefix"]},+ extra={"max_tokens": settings["max_tokens"]})+ self.assert_aborted(engine, [*rows, reply], "summary_too_large")+ self.assertEqual(engine.warm_last["reason"], "summary_too_large")+ self.assertEqual(self.post.calls, [])+ self.assertEqual(self.llm.calls, [])++ def test_known_summary_room_still_uses_the_warm_request(self):+ engine = self.make(threshold=0.5, tail_tokens=2_000)+ engine.update_model(model=ROUTE[0], context_length=131_072, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ rows, reply = old_turns(8), assistant("final")+ self.seed(rows, reply, system={"role": "system", "content": "fixed " * 5_000},+ extra={"max_tokens": 4096})+ history = [*rows, reply]+ self.assertIsNot(engine.compress(history), history)+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("warm", "accepted"))+ self.assertEqual(len(self.post.calls), 1)+ self.assertEqual(self.llm.calls, [])++ def test_unknown_overhead_does_not_refuse_from_a_large_host_count(self):+ engine = self.make(threshold=0.15, tail_tokens=2_000)+ engine.update_model(model=ROUTE[0], context_length=131_072, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ history = [*old_turns(8), assistant("final")]+ self.assertIsNone(self.store.latest("s1"))+ self.assertIsNot(engine.compress(history, current_tokens=46_234), history)+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("fallback", "no_capture"))+ self.assertEqual(self.post.calls, [])+ self.assertEqual(len(self.llm.calls), 1)++ def test_known_zero_summary_room_keeps_cancellation_and_route_guards(self):+ for change in ("cancel", "route"):+ with self.subTest(change=change):+ engine = self.make(threshold=0.15)+ engine.update_model(model=ROUTE[0], context_length=131_072, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ rows, reply = old_turns(8), assistant("final")+ self.seed(rows, reply, system={"role": "system", "content": "fixed " * 30_000},+ extra={"max_tokens": 4096})+ if change == "cancel":+ engine._compression_cancelled_check = lambda: True+ else:+ summary_budget = engine._summary_budget++ def switch(overhead, reserve, summary_budget=summary_budget, engine=engine):+ result = summary_budget(overhead, reserve)+ engine.threshold_tokens += 1+ return result++ engine._summary_budget = switch+ history = [*rows, reply]+ before = copy.deepcopy(history)+ captured = self.store.latest("s1")+ self.assertIs(engine.compress(history), history)+ self.assertEqual(history, before)+ self.assertEqual(self.store.latest("s1"), captured)+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),+ ("cancelled", "cancelled" if change == "cancel" else "route_changed"))+ self.assertEqual(engine.compression_count, 0)+ self.assertIsNone(engine._pending_warm_result)+ self.assertEqual(self.post.calls, [])+ self.assertEqual(self.llm.calls, [])+def test_a_switch_before_the_result_is_used_discards_it(self):# The check covers the whole compaction: a switch while the new history is built also stops it.from warm_compaction import layoutdiff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex be89320..9cb369c 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -8,7 +8,7 @@ from unittest.mock import patchfrom warm_compaction.fallback import (END_LINE, FALLBACK_INSTRUCTION, MAX_STATE_TOKENS, MAX_TOKENS, REQUEST_MAX_TOKENS, MIDDLE_MARK, TASK, TOOL_CHARS,- TRANSCRIPT_CHARS, TRANSCRIPT_TOKENS,+ TIMEOUT_S, TRANSCRIPT_CHARS, TRANSCRIPT_TOKENS,llm_summary, render_row, transcript,)from warm_compaction.rows import estimate_tokens@@ -182,6 +182,12 @@ class LlmSummaryTest(unittest.TestCase):self.assertRegex(self.marker(messages), r"^\[END OF SUMMARY [0-9a-f]{32}\]$")self.assertEqual(len(llm.calls), 1)+ def test_request_timeout_does_not_exceed_the_configured_limit(self):+ llm = FakeLlm()+ with patch("warm_compaction.fallback.time.monotonic", side_effect=(0.0, -3e-14, 0.0)):+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES), (useful_summary("hi"), 321))+ self.assertEqual(llm.calls[0][1]["timeout"], TIMEOUT_S)+def test_the_fallback_instruction_asks_for_the_set_word_count(self):llm = FakeLlm()llm_summary(llm, [user("hi"), assistant("ok")], PREFIXES, summary_words=1200)diff --git a/warm_compaction/anthropic.py b/warm_compaction/anthropic.pyindex 8abf0ba..c0a9a63 100644--- a/warm_compaction/anthropic.py+++ b/warm_compaction/anthropic.py@@ -25,11 +25,14 @@ def _text(content: Any, *, empty: str = "") -> list[dict]:if content is None:content = ""if isinstance(content, str):- return [{"type": "text", "text": content or empty}] if content or empty else []+ text = content if content.strip() else empty+ return [{"type": "text", "text": text}] if text else []if isinstance(content, list) and all(isinstance(p, dict) and p.get("type") == "text"and isinstance(p.get("text"), str)and set(p) <= {"type", "text", "cache_control"} for p in content):- return [{"type": "text", "text": p["text"]} for p in content]+ # Hermes 6e7b83a drops blank text blocks. Keep all bytes of each nonblank block.+ blocks = [{"type": "text", "text": p["text"]} for p in content if p["text"].strip()]+ return blocks or ([{"type": "text", "text": empty}] if empty else [])_refuse()@@ -137,7 +140,7 @@ def _rows(rows: list, *, new: bool = False, base_url: Any = None) -> list[dict]:seen.add(call_id)if role == "assistant":content = _assistant_blocks(row, content, calls, base_url)- content = content or [{"type": "text", "text": "(empty message)"}]+ content = content or [{"type": "text", "text": "(empty)" if role == "assistant" else "(empty message)"}]else:_refuse()if result and result[-1]["role"] == role:diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 25beca4..a578b90 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -51,14 +51,14 @@ FAILURE_HINTS = {"request_not_json": "the main request has a value that cannot be sent as JSON","credential_changed": "the API key changed after the last main request","capacity": "the warm request does not fit in the context window",- "summary_too_large": "the handoff did not fit in the free room of the context window",+ "summary_too_large": "the handoff did not fit below the compaction threshold or the context limit","gate": "the warm reply failed the handoff checks","headers_unknown": "the route headers could not be read","tls_unknown": "the TLS settings of the route could not be read","middleware_after_capture": "another plugin middleware runs after the capture and can change the request","middleware_order_unknown": "the order of the plugin middleware could not be read","middleware_unavailable": "the Hermes middleware API could not be loaded",- "source_transform_unsupported": "a hook or middleware changed the stored rows in the request",+ "source_transform_unsupported": "the request rows could not be matched safely to the stored history",}HERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"HERMES_DB_MARKER = "_db_persisted"@@ -350,6 +350,10 @@ class WarmCompactionEngine(ContextEngine):memory = sanitize_memory(memory_context)record: dict[str, Any] = {"path": None, "reason": None, "elapsed_s": None, "prompt_tokens": None,"cached_tokens": None}+ if budget is not None and overhead is not None and self._summary_budget(overhead, reserve) == 0:+ # A usable capture proves that no summary can fit. Do not send either summary request.+ record.update(reason="summary_too_large", fallback_reason="summary_too_large")+ return self._abort(messages, record, started, attempt)summary = self._warm_summary(messages, capture, focus_topic, memory, prefixes, record, attempt)if summary is not None and not self._summary_fits(summary, overhead, reserve):# A dense handoff can pass the byte gate and still not fit below the threshold: the next request woulddiff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex f1671c2..774d323 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -600,7 +600,7 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topiif failure is not None:failure["reason"] = "cancelled"return None, None- remaining = deadline - time.monotonic()+ remaining = min(timeout_s, deadline - time.monotonic())if remaining <= 0:if failure is not None:failure["reason"] = "deadline"