Skip to content

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

Make the summary time limit a setting (timeout_s, default 300 s) (#43)

Elevatormusicbe1ca35321d5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60e467b..591ca2c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- Add a work ledger after the summary: the commands that ran, with their exit codes and first error lines, and the files that tools changed. Code writes it from the tool calls and results; no model writes it. A later compaction keeps the earlier ledger lines. Setting `ledger` (default true).
- Add a ledger-only summary when both model summaries fail and the rows before the tail have tool work (`path=ledger`). Setting `ledger_on_failure` (default true).
+- Add the setting `timeout_s` (default 300 seconds, range 10 to 3600) for the warm request time limit and the fallback deadline. The old fixed limit was 120 seconds, which a slow local model could not meet. Hermes gives its own compression requests at least 300 seconds.
### Changed
diff --git a/README.md b/README.md
index e95e202..afe1cb2 100644
--- a/README.md
+++ b/README.md
@@ -174,6 +174,7 @@ The settings are in `plugins.entries.warm_compaction.settings`. An invalid value
| `ledger` | bool | true | Add the work ledger (commands with exit codes and first error lines, changed files) after the summary. Set false for comparison runs |
| `fallback_format` | `relaxed` or `quoted` | `relaxed` | Format of the fallback summary. `relaxed` uses the free handoff sections; `quoted` builds every section from verified source quotes. See [Fallback model and keys](#fallback-model-and-keys) |
| `ledger_on_failure` | bool | true | When both model summaries fail and the rows before the tail have tool work, compact with a ledger-only summary instead of stopping. It applies only when `ledger` is true. Set false to keep the history unchanged in that case |
+| `timeout_s` | number, 10 to 3600 | 300 | Time limit in seconds for the warm request, and the shared deadline of the fallback summary calls. The fallback task `warm_compaction` gets the same value as its default timeout. The two paths run one after the other, so one compaction can take up to two times this value. Hermes has its own compression time limits (`compression.context_timeout_seconds`, `compression.context_total_ceiling_seconds`, default ceiling 600 seconds); a larger value needs them to be large enough too. A slow local model can need more than 300 seconds |
```yaml
plugins:
@@ -216,7 +217,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. 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.
+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 one deadline: `timeout_s` (default 300 seconds). 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.
@@ -349,7 +350,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 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).
+- Responses warm requests are streamed; Chat Completions and Messages warm requests are not streamed. No warm request is retried. Its time limit is `timeout_s` (default 300 seconds). The fallback has one shared `timeout_s` 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_engine.py b/tests/test_wc_engine.py
index 2072c9d..7f90c34 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -54,7 +54,7 @@ class FakeLlm:
def fake_post(content=HEADINGS_TEXT, cached=900):
def post(url, data, headers, timeout_s):
- post.calls.append({"url": url, "body": json.loads(data), "headers": headers})
+ post.calls.append({"url": url, "body": json.loads(data), "headers": headers, "timeout_s": timeout_s})
payload = {"choices": [{"message": {"content": content}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1000, "completion_tokens": 50,
"prompt_tokens_details": {"cached_tokens": cached}}}
@@ -1962,6 +1962,29 @@ class EngineTest(unittest.TestCase):
new = engine.compress([*self.ledger_rows(), assistant("final")])
self.assertNotIn(ledger.HEADING, self.summary_text(new))
+ def test_the_time_limit_setting_reaches_the_warm_request(self):
+ for settings, expected in (({}, 300.0), ({"timeout_s": 900.0}, 900.0)):
+ with self.subTest(settings=settings):
+ self.post.calls.clear()
+ engine = self.make(**settings)
+ rows = old_turns()
+ reply = assistant("final")
+ self.seed(rows, reply)
+ engine.compress([*rows, reply])
+ self.assertEqual(engine.warm_last["path"], "warm")
+ self.assertEqual(self.post.calls[0]["timeout_s"], expected)
+
+ def test_the_time_limit_setting_reaches_the_fallback_summary(self):
+ # A slow local model (synthetic): the fallback call gets the configured limit, not the old fixed 120 s.
+ for settings, expected in (({}, 300.0), ({"timeout_s": 900.0}, 900.0)):
+ with self.subTest(settings=settings):
+ self.llm.calls.clear()
+ engine = self.make(warm=False, **settings)
+ engine.compress([user("Check PKG-17 progress."), *old_turns(), assistant("synthetic final reply")])
+ timeout = self.llm.calls[0][1]["timeout"]
+ self.assertGreater(timeout, expected - 5)
+ self.assertLessEqual(timeout, expected)
+
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")
@@ -2340,17 +2363,33 @@ class SettingsTest(unittest.TestCase):
def test_valid_values(self):
values = {"threshold": 0.6, "tail_tokens": 12_000, "user_copy_chars": 0, "warm": False,
"summary_words": 1200, "warm_providers": "opencode-go,commandcode", "ledger": False,
- "fallback_format": "quoted", "ledger_on_failure": False}
+ "fallback_format": "quoted", "ledger_on_failure": False, "timeout_s": 900.0}
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",
"summary_words": 0, "warm_providers": 7, "ledger": "yes", "fallback_format": "strict",
- "ledger_on_failure": 1}
+ "ledger_on_failure": 1, "timeout_s": 0}
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), 9)
+ self.assertEqual(len(logs.output), 10)
+
+ def test_the_time_limit_setting(self):
+ def reader(values):
+ return lambda key, default: values.get(key, default)
+
+ self.assertEqual(self.module.DEFAULTS["timeout_s"], 300.0)
+ for good, expected in ((10, 10.0), (600, 600.0), (3600.0, 3600.0), (450.5, 450.5)):
+ with self.subTest(good=good):
+ settings = self.module.read_settings(reader({"timeout_s": good}))
+ self.assertEqual(settings["timeout_s"], expected)
+ self.assertIs(type(settings["timeout_s"]), float)
+ for bad in (0, 9.9, -1, 3601, "600", True, float("nan"), float("inf")):
+ with self.subTest(bad=bad):
+ with self.assertLogs("warm_compaction.engine", level="WARNING"):
+ settings = self.module.read_settings(reader({"timeout_s": bad}))
+ self.assertEqual(settings["timeout_s"], 300.0)
def test_a_word_count_below_one_uses_the_default(self):
def reader(values):
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index 32193f4..4516ca3 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -176,7 +176,7 @@ class LlmSummaryTest(unittest.TestCase):
self.assertEqual((text, tokens), (useful_summary("hi"), 321))
self.assertEqual((kwargs["task"], kwargs["max_tokens"]), (TASK, REQUEST_MAX_TOKENS))
self.assertGreater(kwargs["timeout"], 0)
- self.assertLessEqual(kwargs["timeout"], 120.0)
+ self.assertLessEqual(kwargs["timeout"], 300.0)
self.assertIn("Give more detail to this topic: db", messages[0]["content"])
self.assertEqual(messages[1]["role"], "user")
self.assertRegex(self.marker(messages), r"^\[END OF SUMMARY [0-9a-f]{32}\]$")
diff --git a/tests/test_wc_register.py b/tests/test_wc_register.py
index 4a2eb14..3145cb6 100644
--- a/tests/test_wc_register.py
+++ b/tests/test_wc_register.py
@@ -73,7 +73,7 @@ class RegisterTest(unittest.TestCase):
engine = engine_of(ctx)
self.assertTrue(all(call[2].__self__ is engine._store for call in ctx.calls[2:]))
self.assertEqual((engine._task, engine._llm), ("warm_compaction", ctx.llm))
- self.assertEqual(ctx.calls[0][2], {"timeout": 120})
+ self.assertEqual(ctx.calls[0][2], {"timeout": 300.0})
def test_missing_method_registers_nothing(self):
ctx = FakeContext()
@@ -137,7 +137,7 @@ class RegisterTest(unittest.TestCase):
text = (ROOT / "warm_compaction" / "plugin.yaml").read_text(encoding="utf-8")
for line in ("manifest_version: 2", "name: warm_compaction", "config_schema:", " threshold:",
" tail_tokens:", " user_copy_chars:", " warm:", " ledger:", " fallback_format:",
- " ledger_on_failure:"):
+ " ledger_on_failure:", " timeout_s:"):
self.assertIn(line + "\n", text)
def test_the_alpha_files_are_gone(self):
diff --git a/warm_compaction/__init__.py b/warm_compaction/__init__.py
index b0ebee7..bebe2e3 100644
--- a/warm_compaction/__init__.py
+++ b/warm_compaction/__init__.py
@@ -67,17 +67,19 @@ def register(ctx: Any) -> None:
from .capture import CaptureStore
from .engine import WarmCompactionEngine, read_settings
+ settings = read_settings(ctx.get_config)
task: str | None = TASK
try:
+ # The task default follows the plugin time limit; each fallback call also sends its remaining time.
ctx.register_auxiliary_task(TASK, display_name="Warm compaction fallback",
description="Model for the warm_compaction fallback summary.",
- defaults={"timeout": 120})
+ defaults={"timeout": settings["timeout_s"]})
except Exception as error:
task = None
logger.warning("warm_compaction could not register its auxiliary task (%s); the fallback summary uses "
"the main model route", type(error).__name__)
store = CaptureStore()
- engine = WarmCompactionEngine(store=store, llm=ctx.llm, settings=read_settings(ctx.get_config), task=task)
+ engine = WarmCompactionEngine(store=store, llm=ctx.llm, settings=settings, task=task)
if ctx.register_context_engine(engine) is None:
logger.warning("Hermes did not accept the warm_compaction context engine; the plugin registers no hooks")
return
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index 0470356..eb6f6a2 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -21,11 +21,13 @@ NAME = "warm_compaction"
DEFAULTS: dict[str, Any] = {"threshold": 0.50, "tail_tokens": 0, "user_copy_chars": 24_000, "warm": True,
"summary_words": handoff.DEFAULT_SUMMARY_WORDS,
"warm_providers": "", "ledger": True, "fallback_format": "relaxed",
- "ledger_on_failure": True}
+ "ledger_on_failure": True, "timeout_s": warm.TIMEOUT_S}
FALLBACK_FORMATS = ("relaxed", "quoted")
# The text of each section of a ledger-only summary: no model wrote a summary.
LEDGER_ONLY_LINE = "- unknown: no model summary; see the work ledger and the copied user messages"
THRESHOLD_RANGE = (0.10, 0.95)
+# The time limit of one summary path, in seconds: the warm request, and the shared deadline of the fallback calls.
+TIMEOUT_RANGE = (10.0, 3600.0)
TAIL_SHARE = 0.025
TAIL_MIN = 10_000
TAIL_MAX = 25_000
@@ -89,6 +91,8 @@ def _valid(key: str, value: Any) -> bool:
return isinstance(value, int) and value >= 1
if key == "threshold":
return isinstance(value, (int, float)) and THRESHOLD_RANGE[0] <= float(value) <= THRESHOLD_RANGE[1]
+ if key == "timeout_s":
+ return isinstance(value, (int, float)) and TIMEOUT_RANGE[0] <= float(value) <= TIMEOUT_RANGE[1]
return isinstance(value, int) and value >= 0
@@ -105,7 +109,7 @@ def read_settings(get_config: Callable[..., Any] | None) -> dict[str, Any]:
if value is None:
continue
if _valid(key, value):
- settings[key] = float(value) if key == "threshold" else value
+ settings[key] = float(value) if key in ("threshold", "timeout_s") else value
else:
logger.warning("Invalid warm_compaction setting %s; using the default %r", key, default)
return settings
@@ -380,6 +384,7 @@ class WarmCompactionEngine(ContextEngine):
summary, _tokens = fallback.llm_summary(
self._llm, [*messages[:start], *removed], prefixes, focus_topic=focus_topic, memory_context=memory,
task=self._task, summary_words=self._settings["summary_words"],
+ timeout_s=float(self._settings["timeout_s"]),
ready=lambda: not self._cancelled() and self._attempt() == attempt, failure=failure,
quoted=self._settings["fallback_format"] == "quoted")
if summary is None:
@@ -670,8 +675,9 @@ class WarmCompactionEngine(ContextEngine):
# extra_headers is an SDK option, not part of the JSON body.
wire_body = ({name: value for name, value in base.items() if name != "extra_headers"}
if request_headers else base)
- result = warm.send(wire_body, route[1], key, post=self._post, extra_headers=headers, ssl_context=tls,
- api_mode=route[2], provider=provider)
+ result = warm.send(wire_body, route[1], key, timeout_s=float(self._settings["timeout_s"]),
+ post=self._post, extra_headers=headers, ssl_context=tls, api_mode=route[2],
+ provider=provider)
# The send blocks on the network: a switch can occur before it returns.
if self._attempt() != attempt:
raise warm.WarmRefusal("route_changed")
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index 0fa2faa..6165b79 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -34,7 +34,7 @@ REQUEST_MAX_TOKENS = 8192
MAX_ATTEMPTS = 3
MAX_ATTEMPTS_OTHER = 2
MARKER_FAILURES = ("missing_end_marker", "duplicate_end_marker")
-TIMEOUT_S = 120.0
+TIMEOUT_S = 300.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
diff --git a/warm_compaction/plugin.yaml b/warm_compaction/plugin.yaml
index 9e91aac..1414427 100644
--- a/warm_compaction/plugin.yaml
+++ b/warm_compaction/plugin.yaml
@@ -40,6 +40,10 @@ config_schema:
type: bool
default: true
description: When both model summaries fail and the rows before the tail have tool work, compact with a ledger-only summary instead of stopping. Applies only when ledger is true.
+ timeout_s:
+ type: float
+ default: 300.0
+ description: Time limit in seconds (10 to 3600) for the warm request, and the shared deadline of the fallback summary calls.
summary_words:
type: int
default: 600
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index a4d3097..79b2914 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -24,7 +24,7 @@ DEFAULT_RESERVE = 4096
# thinking model that counts its reasoning in the same limit.
HANDOFF_MIN_TOKENS = 2048
HANDOFF_MAX_TOKENS = 8192
-TIMEOUT_S = 120.0
+TIMEOUT_S = 300.0
# Cloudflare-fronted routes reject Python's default "Python-urllib/x.y" User-Agent with
# HTTP 403 (error 1010). Send an explicit one, as the Hermes SDK client does.
USER_AGENT = "hermes-warm-compaction/0.2"