Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
feat: add warm_providers to keep routes out of the warm path
HopeValentinee88ac2215e3c
diff --git a/README.md b/README.mdindex e67b962..712d641 100644--- a/README.md+++ b/README.md@@ -167,6 +167,7 @@ The settings are in `plugins.entries.warm_compaction.settings`. An invalid value| `tail_tokens` | int, 0 or more | 0: 2.5% of the context window, from 10,000 to 25,000 | Size of the verbatim tail, at most half of the compaction threshold || `user_copy_chars` | int, 0 or more | 24,000 | Total characters of user messages that the summary copies || `warm` | bool | true | Set false to use only the fallback summary, for comparison runs |+| `warm_providers` | text | empty: every provider | Comma-separated provider names that may use the warm path. A provider outside the list sends no warm request, so a route that can miss its prefix cache does not pay for the whole prompt. Names are matched without case. An empty value keeps every provider |```yamlplugins:@@ -202,7 +203,7 @@ warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021```- `path` is `warm`, `fallback`, or `fixed`. `unchanged` means that an indivisible native replay block left no room for a valid new history; no compaction was committed.-- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `auth_unsupported`, `route_changed`, `settings_unsupported`, `request_not_mapping`, `request_options_unsupported`, `request_not_json`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.+- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `provider_not_allowed`, `api_mode_unsupported`, `auth_unsupported`, `route_changed`, `settings_unsupported`, `request_not_mapping`, `request_options_unsupported`, `request_not_json`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `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.Capture refusal codes identify the failed check: `request_not_mapping` means that the request is not a mapping; `request_options_unsupported` means that extra headers, query options, or `extra_body` cannot be kept; `request_not_json` means that a body value cannot be sent as JSON (including NaN and infinity). `settings_unsupported` still applies to unsupported model settings. These codes contain no request values.diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 979ff9b..4964829 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -1553,6 +1553,43 @@ class EngineTest(unittest.TestCase):self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]), ("fallback", "disabled"))self.assertEqual(self.post.calls, [])+ def test_a_provider_outside_the_list_skips_the_warm_request(self):+ # The route is kept out of the warm path: no warm request is sent, and the fallback summary runs.+ engine = self.make(warm_providers="opencode-go,commandcode")+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ engine.compress([*rows, reply])+ self.assertEqual((engine.warm_last["path"], engine.warm_last["reason"]),+ ("fallback", "provider_not_allowed"))+ self.assertEqual(self.post.calls, [])++ def test_a_provider_inside_the_list_uses_the_warm_request(self):+ engine = self.make(warm_providers="opencode-go, custom ")+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ engine.compress([*rows, reply])+ self.assertEqual(engine.warm_last["path"], "warm")+ self.assertNotEqual(self.post.calls, [])++ def test_an_empty_provider_list_allows_every_provider(self):+ engine = self.make(warm_providers="")+ rows = old_turns()+ reply = assistant("final")+ self.seed(rows, reply)+ engine.compress([*rows, reply])+ self.assertEqual(engine.warm_last["path"], "warm")++ def test_the_provider_names_match_without_case_or_spaces(self):+ from warm_compaction.engine import provider_allowed+ self.assertTrue(provider_allowed("", "nous"))+ self.assertTrue(provider_allowed(None, "nous"))+ self.assertTrue(provider_allowed(" Opencode-Go , commandcode ", "opencode-go"))+ self.assertTrue(provider_allowed("opencode-go,commandcode", "COMMANDCODE"))+ self.assertFalse(provider_allowed("opencode-go,commandcode", "nous"))+ self.assertFalse(provider_allowed("opencode-go", ""))+def test_cancelled_attempt_keeps_the_history(self):rows = old_turns()reply = assistant("final")@@ -1834,15 +1871,17 @@ class SettingsTest(unittest.TestCase):self.module = enginedef test_valid_values(self):- values = {"threshold": 0.6, "tail_tokens": 12_000, "user_copy_chars": 0, "warm": False}+ values = {"threshold": 0.6, "tail_tokens": 12_000, "user_copy_chars": 0, "warm": False,+ "warm_providers": "opencode-go,commandcode"}self.assertEqual(self.module.read_settings(lambda key, default: values.get(key, default)), values)def test_invalid_values_use_the_defaults_with_a_warning(self):- values = {"threshold": 2.0, "tail_tokens": -1, "user_copy_chars": "big", "warm": "no"}+ values = {"threshold": 2.0, "tail_tokens": -1, "user_copy_chars": "big", "warm": "no",+ "warm_providers": 7}with self.assertLogs("warm_compaction.engine", level="WARNING") as logs:settings = self.module.read_settings(lambda key, default: values.get(key, default))self.assertEqual(settings, self.module.DEFAULTS)- self.assertEqual(len(logs.output), 4)+ self.assertEqual(len(logs.output), 5)def test_tail_budget(self):self.assertEqual(self.module.tail_budget(0, 200_000), 10_000)diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 5224be8..3283312 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -18,7 +18,8 @@ from .rows import SendPolicy, api_content, attr, estimate_tokens, hermes_value,logger = logging.getLogger(__name__)NAME = "warm_compaction"-DEFAULTS: dict[str, Any] = {"threshold": 0.50, "tail_tokens": 0, "user_copy_chars": 24_000, "warm": True}+DEFAULTS: dict[str, Any] = {"threshold": 0.50, "tail_tokens": 0, "user_copy_chars": 24_000, "warm": True,+ "warm_providers": ""}THRESHOLD_RANGE = (0.10, 0.95)TAIL_SHARE = 0.025TAIL_MIN = 10_000@@ -43,6 +44,7 @@ FAILURE_HINTS = {"provider_error": "the server refused the warm request (a provider error, or a gateway that needs a cookie)","timeout": "the warm request took longer than its time limit","api_mode_unsupported": "this API format has no supported warm path",+ "provider_not_allowed": "this provider is not in the warm_providers list","auth_unsupported": "the warm path cannot keep the authentication of this route","settings_unsupported": "the main request uses a setting that the warm request cannot keep","request_not_mapping": "the main request is not a mapping",@@ -66,6 +68,8 @@ HERMES_DB_MARKER = "_db_persisted"def _valid(key: str, value: Any) -> bool:if key == "warm":return isinstance(value, bool)+ if key == "warm_providers":+ return isinstance(value, str)if isinstance(value, bool):return Falseif key == "threshold":@@ -92,6 +96,15 @@ def read_settings(get_config: Callable[..., Any] | None) -> dict[str, Any]:return settings+def provider_allowed(setting: Any, provider: Any) -> bool:+ """True when the warm path may run for this provider. An empty setting allows every provider.+ The names are comma-separated and matched without case."""+ names = {part.strip().lower() for part in str(setting or "").split(",") if part.strip()}+ if not names:+ return True+ return str(provider or "").strip().lower() in names++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 size is also at most half of the compaction threshold, for a set value too. Otherwise the tail can hold@@ -515,6 +528,11 @@ class WarmCompactionEngine(ContextEngine):raise warm.WarmRefusal("disabled")if capture is None:raise warm.WarmRefusal("no_capture")+ # A provider that is not in the list never sends a warm request. A route that rotates its upstream+ # can miss the prefix cache, and the warm request would then pay for the whole prompt. The+ # fallback summary, which sends a small transcript, runs in its place.+ if not provider_allowed(self._settings.get("warm_providers"), attempt[2]):+ raise warm.WarmRefusal("provider_not_allowed")# The capture belongs to the key that sent it. Hermes can give the key as a function whose value# changes (a token that refreshes or rotates): resolve it one time, for this check and the request.key = warm.api_key_text(attempt[1])diff --git a/warm_compaction/plugin.yaml b/warm_compaction/plugin.yamlindex 389a30b..821ddbc 100644--- a/warm_compaction/plugin.yaml+++ b/warm_compaction/plugin.yaml@@ -28,3 +28,7 @@ config_schema:type: booldefault: truedescription: Use the warm request. Set false for comparison runs.+ warm_providers:+ type: str+ default: ""+ description: Comma-separated provider names that may use the warm path. Empty means every provider.