Skip to content

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

fix: preserve capture reasons and OpenCode session headers (#9)

Elevatormusic064a2e7a1aab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9437006..33f53b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
## [Unreleased]
+### Fixed
+
+- Keep safe request refusal codes in status and logs, instead of the generic `settings_unsupported`.
+- Keep the captured `x-opencode-session` header on warm requests, including the header that Hermes adds for OpenCode routes. Refuse unknown headers and header rewrites; send the session value only as an HTTP header.
+- Report `missing_end_marker` or `output_token_limit` when a fallback reply fails the completion check. Incomplete replies still use the fixed summary.
+
### Added
- A WARNING for each saved compaction that Hermes confirms without the warm path, with its reason (Hermes copies it to `errors.log`).
diff --git a/README.md b/README.md
index d15dec2..9b68dfb 100644
--- a/README.md
+++ b/README.md
@@ -144,11 +144,11 @@ 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. 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.
+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 keys
-The fallback summary uses the auxiliary task `warm_compaction`. Set `auxiliary.warm_compaction.provider` and `auxiliary.warm_compaction.model` to use a different model. The default `auto` uses the main model route. The fallback reply must end with the line `[END OF SUMMARY]`: the auxiliary route reports no finish reason, so a reply without that line counts as cut off. The fallback request is at most about 11,000 tokens: a transcript of about 8,000 tokens, the instruction, and a 2,048-token reply. The focus topic and the memory context are cut to about 1,000 tokens and take their size from the transcript. A fallback model needs a context window of at least 16,000 tokens. Hermes accepts main models with 64,000 tokens or more, so the default route has enough space.
+The fallback summary uses the auxiliary task `warm_compaction`. Set `auxiliary.warm_compaction.provider` and `auxiliary.warm_compaction.model` to use a different model. The default `auto` uses the main model route. The fallback reply must end with the line `[END OF SUMMARY]`: the auxiliary route reports no finish reason, so a reply without that line counts as cut off. The warning uses `missing_end_marker` when the final line is absent, or `output_token_limit` when the reported output count reaches the 2,048-token limit. A marker earlier in the reply does not pass the check. These cases still use the fixed summary; the plugin cannot confirm completion from the five headings alone. The fallback request is at most about 11,000 tokens: a transcript of about 8,000 tokens, the instruction, and a 2,048-token reply. The focus topic and the memory context are cut to about 1,000 tokens and take their size from the transcript. A fallback model needs a context window of at least 16,000 tokens. Hermes accepts main models with 64,000 tokens or more, so the default route has enough space.
For a custom endpoint that needs a key, put the key name in the model settings:
@@ -170,9 +170,11 @@ warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021
```
- `path` is `warm`, `fallback`, or `fixed`.
-- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `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`, `api_mode_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.
+
The engine status (`get_status()`) has the same values in `warm_last`. After a new attempt starts, an older worker cannot replace this status or write a final metadata line. The log never contains message text, request bodies, or keys.
Manual `/compress` can report `No changes from compression` when all messages fit in the recent-history tail. Then the plugin has no older history to summarize. The request estimate also includes system instructions and tool definitions, which the plugin does not compress. Use `/context` to see the token counts for each part. This unchanged result does not count as a warm-path failure.
@@ -247,7 +249,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
- 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, and the fixed summary quotes them (at most 8,000 characters), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. 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. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). 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 fixed summary is used: it quotes the cut middle. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. 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 or into the fixed summary. 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.
- 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`).
+- 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_capture.py b/tests/test_wc_capture.py
index 3c32794..7b819d2 100644
--- a/tests/test_wc_capture.py
+++ b/tests/test_wc_capture.py
@@ -1,10 +1,12 @@
"""Tests for the capture store."""
+import copy
import subprocess
import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
+from unittest.mock import patch
import wc_hermes_stub
from warm_compaction.capture import CaptureStore, UnsupportedRequest, final_body, key_stamp
@@ -57,6 +59,8 @@ class FinalBodyTest(unittest.TestCase):
cases = (
(request(extra_headers={"x": "1"}), "request_options_unsupported"),
(request(extra_query={"q": "1"}), "request_options_unsupported"),
+ (request(extra_headers={"x-opencode-session": "id"}, extra_body={"extra_headers": {}}),
+ "request_options_unsupported"),
(request(bad=object()), "request_not_json"),
(["not", "a", "mapping"], "request_not_mapping"),
)
@@ -93,6 +97,38 @@ class CaptureStoreTest(unittest.TestCase):
self.run_request(request_id="r2", usage=usage)
self.assertIsNone(self.store.latest("s1")["prompt_tokens"])
+ def test_session_header_is_separate_and_copied(self):
+ body = request(extra_headers={"X-OpenCode-Session": "synthetic-session"})
+ before = copy.deepcopy(body)
+ self.run_request(body=body)
+ capture = self.store.latest("s1")
+ self.assertIsNone(capture["refusal"])
+ self.assertEqual(capture["request_headers"], before["extra_headers"])
+ self.assertNotIn("extra_headers", capture["body"])
+ self.assertEqual(body, before)
+ body["extra_headers"]["X-OpenCode-Session"] = "changed"
+ capture["request_headers"].clear()
+ self.assertEqual(self.store.latest("s1")["request_headers"], before["extra_headers"])
+
+ def test_invalid_session_headers_are_not_kept(self):
+ for headers in (
+ {"x-opencode-session": ""}, {"x-opencode-session": " "},
+ {"x-opencode-session": "id\r\nAuthorization: private"},
+ {"x-opencode-session": "id\x00"}, {"x-opencode-session": "id\x7f"},
+ {"x-opencode-session": "id\t"}, {"x-opencode-session": "id\u00e9"},
+ {"x-opencode-session": 7}, {"x-opencode-session": None},
+ {"x-opencode-session": "id", "Authorization": "private"},
+ {"x-opencode-session": "id", "X-OpenCode-Session": "other"},
+ {"x-other-session": "private"}, ["private"], "private",
+ ):
+ with self.subTest(headers=headers):
+ self.run_request(body=request(extra_headers=headers))
+ capture = self.store.latest("s1")
+ self.assertEqual(capture["refusal"], "request_options_unsupported")
+ self.assertIsNone(capture["body"])
+ self.assertEqual(capture.get("request_headers", {}), {})
+ self.assertNotIn("private", repr(capture))
+
def test_joins_the_three_calls(self):
result, calls = self.run_request()
self.assertEqual((result, calls), ("response", [1]))
@@ -109,6 +145,44 @@ class CaptureStoreTest(unittest.TestCase):
self.assertEqual(self.store.latest("s1")["reply"]["tool_calls"],
[["c1", "read"], ["c1_d2", "ls"], ["c1_d3", "cat"]])
+ def test_keeps_fixed_request_refusals_and_runs_the_request_unchanged(self):
+ cases = (
+ (["synthetic-private-request"], "request_not_mapping"),
+ (request(extra_headers={"Authorization": "synthetic-private-key"}), "request_options_unsupported"),
+ (request(extra_query={"token": "synthetic-private-key"}), "request_options_unsupported"),
+ (request(extra_body=["synthetic-private-request"]), "request_options_unsupported"),
+ (request(value=SimpleNamespace(secret="synthetic-private-value")), "request_not_json"),
+ (request(value=float("nan")), "request_not_json"),
+ (request(value=float("inf")), "request_not_json"),
+ )
+ for body, code in cases:
+ with self.subTest(code=code):
+ before = body.copy()
+ result, calls = self.run_request(body=body)
+ capture = self.store.latest("s1")
+ self.assertEqual((result, calls), ("response", [1]))
+ self.assertEqual(body, before)
+ self.assertEqual((capture["body"], capture["refusal"]), (None, code))
+ self.assertNotIn("synthetic-private", repr(capture))
+
+ def test_unknown_exception_data_does_not_become_a_refusal(self):
+ for data in ("synthetic-private-exception", SimpleNamespace(secret="synthetic-private-value")):
+ with self.subTest(data_type=type(data).__name__), patch(
+ "warm_compaction.capture.final_body", side_effect=UnsupportedRequest(data)):
+ result, calls = self.run_request()
+ capture = self.store.latest("s1")
+ self.assertEqual((result, calls), ("response", [1]))
+ self.assertEqual((capture["body"], capture["refusal"]), (None, "settings_unsupported"))
+ self.assertNotIn("synthetic-private", repr(capture))
+
+ def test_a_valid_capture_replaces_an_earlier_request_refusal(self):
+ self.run_request(body=request(extra_headers={"x": "synthetic-private-value"}))
+ self.assertEqual(self.store.latest("s1")["refusal"], "request_options_unsupported")
+ self.run_request(request_id="r2")
+ capture = self.store.latest("s1")
+ self.assertEqual(capture["body"], request())
+ self.assertIsNone(capture["refusal"])
+
def test_no_body_when_an_execution_middleware_runs_after_the_capture(self):
# A later middleware can change the request after the capture saw it. The capture cannot see that change.
def other(request=None, next_call=None, **context):
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index 0b2b037..10d0316 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -1,8 +1,10 @@
"""Tests for the warm_compaction context engine with stand-in Hermes modules."""
+import copy
import json
import threading
import unittest
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from types import SimpleNamespace
from unittest.mock import patch
@@ -164,6 +166,47 @@ class EngineTest(unittest.TestCase):
self.assertNotIn("done", sent.split("\n"))
self.assertNotIn(rows[-2]["content"][:20], sent)
+ def test_request_refusals_reach_fallback_and_fixed_status_without_private_data(self):
+ private = "synthetic-private-request-value"
+ cases = (
+ ([private], "request_not_mapping"),
+ ({"extra_headers": {"Authorization": private}}, "request_options_unsupported"),
+ ({"extra_query": {"token": private}}, "request_options_unsupported"),
+ ({"extra_body": [private]}, "request_options_unsupported"),
+ ({"value": SimpleNamespace(secret=private)}, "request_not_json"),
+ )
+ rows, reply = old_turns(4), assistant("final")
+ for path in ("fallback", "fixed"):
+ for body, code in cases:
+ with self.subTest(path=path, code=code):
+ self.llm = FakeLlm(error=RuntimeError(private) if path == "fixed" else None)
+ engine = self.make(tail_tokens=10)
+ engine.update_model(model=ROUTE[0], context_length=200_000, base_url=ROUTE[1], api_key=private,
+ provider="custom", api_mode=ROUTE[2])
+ self.store.on_pre_api_request(api_request_id="r1", session_id="s1", conversation_history=rows,
+ model=ROUTE[0], base_url=ROUTE[1], api_mode=ROUTE[2])
+ calls = []
+ with self.assertLogs("warm_compaction", level="INFO") as logs:
+ result = self.store.on_llm_execution(
+ request=body, api_request_id="r1",
+ next_call=lambda calls=calls: calls.append(1) or "response")
+ self.store.on_post_api_request(api_request_id="r1", session_id="s1", finish_reason="stop",
+ assistant_message=reply_object(reply))
+ history = [*rows, reply]
+ new = self.compress_committed(engine, history)
+ status = engine.get_status()["warm_last"]
+ self.assertEqual((status["path"], status["reason"]), (path, code))
+ self.assertEqual((result, calls), ("response", [1]))
+ self.assertIsNot(new, history)
+ self.assertTrue(any("Fallback summary." in str(row.get("content")) for row in new)
+ if path == "fallback" else any(row.get("_compressed_summary") for row in new))
+ self.assertEqual(len(self.llm.calls), 1)
+ self.assertEqual(self.post.calls, [])
+ self.assertIn(f"path={path} reason={code}", "\n".join(logs.output))
+ self.assertNotIn(private, "\n".join(logs.output))
+ self.assertNotIn(private, json.dumps(engine.get_status()))
+ self.assertNotIn(private, repr(self.store.latest("s1")))
+
def test_gate_refusal_keeps_the_tokens_and_falls_back(self):
self.post = fake_post(content="no headings")
engine = self.make()
@@ -188,6 +231,114 @@ class EngineTest(unittest.TestCase):
self.assertEqual(self.engine.warm_last["path"], "warm")
self.assertEqual(seen, [(len(rows) + 3, "warm_compaction", None)])
+ def test_session_header_reaches_middleware_and_wire_once_without_private_metadata(self):
+ self.engine = self.make(tail_tokens=10)
+ session = "synthetic-captured-session"
+ seen = []
+
+ def request_audit(request=None, **context):
+ seen.append(("request", copy.deepcopy(request.get("extra_headers"))))
+
+ def execution_audit(request=None, next_call=None, **context):
+ seen.append(("execution", copy.deepcopy(request.get("extra_headers"))))
+ return next_call()
+
+ wc_hermes_stub.REQUEST_MIDDLEWARE.append(request_audit)
+ wc_hermes_stub.EXECUTION_MIDDLEWARE.append(execution_audit)
+ wc_hermes_stub.CUSTOM_HEADERS.update({"X-OPENCODE-SESSION": "different-default", "X-Title": "Hermes"})
+ rows, reply = old_turns(4), assistant("final")
+ extra = {"extra_headers": {"x-opencode-session": session}}
+ self.seed(rows, reply, extra=extra)
+ before = self.store.latest("s1")
+ with self.assertLogs("warm_compaction", level="INFO") as logs:
+ self.engine.compress([*rows, reply])
+ self.assertEqual(self.engine.warm_last["path"], "warm")
+ self.assertEqual(seen, [(phase, extra["extra_headers"]) for phase in ("request", "execution")])
+ self.assertEqual(len(self.post.calls), 1)
+ call = self.post.calls[0]
+ self.assertEqual([(key, value) for key, value in call["headers"].items()
+ if key.lower() == "x-opencode-session"], [("x-opencode-session", session)])
+ self.assertEqual(call["headers"]["X-Title"], "Hermes")
+ self.assertEqual(call["headers"]["Authorization"], "Bearer k")
+ self.assertNotIn("extra_headers", call["body"])
+ self.assertNotIn(session, json.dumps(call["body"]))
+ self.assertNotIn(session, json.dumps(self.engine.get_status()))
+ self.assertNotIn(session, "\n".join(logs.output))
+ self.assertEqual(self.store.latest("s1"), before)
+ self.assertEqual(extra, {"extra_headers": {"x-opencode-session": session}})
+
+ def test_session_header_rewrite_block_cancel_and_route_fences(self):
+ for phase, action, expected in (
+ ("request", "rewrite", "middleware_rewrite"), ("execution", "rewrite", "middleware_rewrite"),
+ ("execution", "rewrite_original", "middleware_rewrite"),
+ ("execution", "block", "middleware_changed_reply"), ("execution", "cancel", "cancelled"),
+ ("execution", "switch", "route_changed"),
+ ):
+ with self.subTest(phase=phase, action=action):
+ engine = self.make(tail_tokens=10)
+ self.post.calls.clear()
+ wc_hermes_stub.REQUEST_MIDDLEWARE.clear()
+ wc_hermes_stub.EXECUTION_MIDDLEWARE.clear()
+
+ def middleware(request=None, next_call=None, action=action, phase=phase, engine=engine, **context):
+ self.assertEqual(request["extra_headers"], {"x-opencode-session": "synthetic-session"})
+ if action in ("rewrite", "rewrite_original"):
+ request["extra_headers"]["x-opencode-session"] = "changed"
+ if action == "rewrite_original":
+ context["original_request"]["extra_headers"]["x-opencode-session"] = "changed"
+ elif action == "block":
+ return None
+ elif action == "cancel":
+ engine._compression_cancelled_check = lambda: True
+ elif action == "switch":
+ engine.update_model(model="other-model", context_length=200_000, base_url=ROUTE[1],
+ api_key="k", provider="custom", api_mode=ROUTE[2])
+ return {"request": request} if phase == "request" else next_call(request)
+
+ chain = (wc_hermes_stub.REQUEST_MIDDLEWARE if phase == "request"
+ else wc_hermes_stub.EXECUTION_MIDDLEWARE)
+ chain.append(middleware)
+ rows, reply = old_turns(4), assistant("final")
+ self.seed(rows, reply, extra={"extra_headers": {"x-opencode-session": "synthetic-session"}})
+ engine.compress([*rows, reply])
+ self.assertEqual(engine.warm_last["reason"], expected)
+ self.assertEqual(self.post.calls, [])
+
+ def test_session_header_on_loopback_http(self):
+ received = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ received.append((self.headers.get_all("x-opencode-session"), body))
+ data = json.dumps({"choices": [{"message": {"content": HEADINGS_TEXT},
+ "finish_reason": "stop"}]}).encode()
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ route = (ROUTE[0], f"http://127.0.0.1:{server.server_port}/v1", ROUTE[2])
+ with patch(__name__ + ".ROUTE", route):
+ self.post = None
+ engine = self.make(tail_tokens=10)
+ wc_hermes_stub.CUSTOM_HEADERS["X-OpenCode-Session"] = "default-session"
+ rows, reply = old_turns(4), assistant("final")
+ self.seed(rows, reply, extra={"extra_headers": {"x-opencode-session": "captured-session"}})
+ engine.compress([*rows, reply])
+ self.assertEqual(engine.warm_last["path"], "warm")
+ self.assertEqual(len(received), 1)
+ self.assertEqual(received[0][0], ["captured-session"])
+ self.assertNotIn("extra_headers", received[0][1])
+ self.assertNotIn("captured-session", json.dumps(received[0][1]))
+
def test_a_blocking_or_mocking_middleware_stops_the_warm_request(self):
def block(request=None, next_call=None, **context):
return None # A policy middleware blocks by not calling next_call.
diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.py
index ca0b3d8..73068f1 100644
--- a/tests/test_wc_fallback.py
+++ b/tests/test_wc_fallback.py
@@ -175,17 +175,20 @@ class LlmSummaryTest(unittest.TestCase):
# MAX_TOKENS; the five headings can already be there. Only the end line shows a complete reply.
self.assertTrue(FALLBACK_INSTRUCTION.rstrip().endswith(END_LINE))
for text in (SUMMARY, SUMMARY + "\n" + END_LINE + "\nmore text", END_LINE + "\n" + SUMMARY):
- with self.subTest(text=text[-20:]), self.assertLogs("warm_compaction.fallback", level="WARNING"):
+ with self.subTest(text=text[-20:]), self.assertLogs("warm_compaction.fallback", level="WARNING") as logs:
self.assertEqual(llm_summary(FakeLlm(text=text, output_tokens=300), [user("hi")], PREFIXES),
(None, None))
+ self.assertIn("(missing_end_marker)", logs.output[0])
+ self.assertNotIn(SUMMARY, "\n".join(logs.output))
text = "<think>plan</think>\n" + SUMMARY + "\n\n " + END_LINE + " \n"
self.assertEqual(llm_summary(FakeLlm(text=text), [user("hi")], PREFIXES), (SUMMARY, 321))
def test_a_reply_that_reached_the_token_limit_is_refused(self):
# ctx.llm reports no finish reason. A reply at the max_tokens limit can be cut off.
- for llm in (FakeLlm(output_tokens=MAX_TOKENS),):
- with self.subTest(), self.assertLogs("warm_compaction.fallback", level="WARNING"):
+ for llm in (FakeLlm(output_tokens=MAX_TOKENS), FakeLlm(text=SUMMARY, output_tokens=MAX_TOKENS + 1)):
+ with self.subTest(), self.assertLogs("warm_compaction.fallback", level="WARNING") as logs:
self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES), (None, None))
+ self.assertIn("(output_token_limit)", logs.output[0])
self.assertEqual(llm_summary(FakeLlm(output_tokens=300), [user("hi")], PREFIXES), (SUMMARY, 321))
def test_task_none_uses_the_main_model_route(self):
diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.py
index 668cf3e..2296638 100644
--- a/tests/test_wc_warm.py
+++ b/tests/test_wc_warm.py
@@ -485,10 +485,12 @@ class BuildRequestTest(unittest.TestCase):
self.assertEqual(caught.exception.code, "source_transform_unsupported")
def test_a_capture_without_a_body_gives_its_refusal(self):
- capture = dict(capture_for(self.rows, self.reply), body=None, refusal="middleware_after_capture")
- with self.assertRaises(WarmRefusal) as caught:
- self.build(capture)
- self.assertEqual(caught.exception.code, "middleware_after_capture")
+ for code in ("middleware_after_capture", "middleware_order_unknown", "request_not_mapping",
+ "request_options_unsupported", "request_not_json"):
+ capture = dict(capture_for(self.rows, self.reply), body=None, refusal=code)
+ with self.subTest(code=code), self.assertRaises(WarmRefusal) as caught:
+ self.build(capture)
+ self.assertEqual(caught.exception.code, code)
def test_refuses_when_the_window_is_too_small(self):
with self.assertRaises(WarmRefusal) as caught:
diff --git a/warm_compaction/capture.py b/warm_compaction/capture.py
index 15648c0..3486b17 100644
--- a/warm_compaction/capture.py
+++ b/warm_compaction/capture.py
@@ -18,6 +18,7 @@ MAX_OPEN = 8
MAX_SESSIONS = 16
CLIENT_OPTIONS = ("extra_body", "extra_headers", "extra_query", "timeout")
CAPTURE_FINISH = ("stop", "tool_calls")
+REQUEST_REFUSALS = ("request_not_mapping", "request_options_unsupported", "request_not_json")
# A random salt for each plugin load: the stamps of one key differ between processes.
_KEY_STAMP_SECRET = secrets.token_bytes(32)
# PBKDF2 work for each stamp (about 3 ms): a stamp is made a few times for each main request.
@@ -34,15 +35,39 @@ class UnsupportedRequest(ValueError):
"""The request body cannot become a warm request. The message is the reason code."""
+def request_headers(request: Any) -> dict[str, str]:
+ """Copy only the known session header. Refuse other headers and unsafe HTTP values.
+
+ Hermes 1d6b2786 adds x-opencode-session for OpenCode routes. Keep the captured value: a new session id
+ need not select the same server. Header values stay in memory and never go to status or logs.
+ """
+ if not isinstance(request, dict):
+ raise UnsupportedRequest("request_not_mapping")
+ headers = request.get("extra_headers")
+ if headers is None:
+ return {}
+ if not isinstance(headers, dict) or len(headers) > 1:
+ raise UnsupportedRequest("request_options_unsupported")
+ for name, value in headers.items():
+ if (type(name) is not str or name.lower() != "x-opencode-session" or type(value) is not str
+ or not value or value != value.strip() or any(ord(char) < 32 or ord(char) > 126 for char in value)):
+ raise UnsupportedRequest("request_options_unsupported")
+ return dict(headers)
+
+
def final_body(request: Any) -> dict[str, Any]:
"""Return the JSON body that the OpenAI client sends: a copy with extra_body merged in."""
if not isinstance(request, dict):
raise UnsupportedRequest("request_not_mapping")
- if request.get("extra_headers") or request.get("extra_query"):
+ headers = request_headers(request)
+ if request.get("extra_query"):
raise UnsupportedRequest("request_options_unsupported")
extra = request.get("extra_body") or {}
if not isinstance(extra, dict):
raise UnsupportedRequest("request_options_unsupported")
+ if headers and "extra_headers" in extra:
+ # A JSON field with this name would conflict with the middleware request option.
+ raise UnsupportedRequest("request_options_unsupported")
body = {key: value for key, value in request.items() if key not in CLIENT_OPTIONS}
body.update(extra)
try:
@@ -132,18 +157,25 @@ class CaptureStore:
if entry is None or entry["route"][2] != "chat_completions":
return
refusal = None
+ headers: dict[str, str] = {}
try:
body = final_body(request)
- except UnsupportedRequest:
+ headers = request_headers(request)
+ except UnsupportedRequest as error:
body = None
+ # Keep only fixed codes. Exception data must not reach the status or logs.
+ code = error.args[0] if len(error.args) == 1 else None
+ refusal = code if type(code) is str and code in REQUEST_REFUSALS else "settings_unsupported"
if body is not None:
# A later middleware can change the request after this capture saw it. The warm request would
# then send a body that the provider never received.
refusal = self._middleware_order_refusal()
if refusal is not None:
body = None
+ headers = {}
with self._lock:
entry["body"] = body
+ entry["request_headers"] = headers
entry["refusal"] = refusal
def _middleware_order_refusal(self) -> str | None:
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index 13c0f40..0fc4b26 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -42,7 +42,9 @@ FAILURE_HINTS = {
"timeout": "the warm request took longer than its time limit",
"api_mode_unsupported": "this API mode has no warm path; only chat_completions has one",
"settings_unsupported": "the main request uses a setting that the warm request cannot keep",
- "request_options_unsupported": "the main request uses extra headers or query options",
+ "request_not_mapping": "the main request is not a mapping",
+ "request_options_unsupported": "the main request has unsupported extra headers, query options, or extra_body",
+ "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",
@@ -485,7 +487,7 @@ class WarmCompactionEngine(ContextEngine):
if self._cancelled():
raise warm.WarmRefusal("cancelled")
reply = self._execute(body, instruction, len(capture["body"]["messages"]), attempt,
- capture.get("prompt_tokens"), key)
+ capture.get("prompt_tokens"), key, capture.get("request_headers"))
record.update(prompt_tokens=reply["prompt_tokens"], cached_tokens=reply["cached_tokens"])
text, reason = handoff.gate(reply, prefixes)
if text is None:
@@ -500,7 +502,8 @@ class WarmCompactionEngine(ContextEngine):
return text
def _execute(self, body: dict[str, Any], instruction: str, captured: int, attempt: tuple,
- measured: int | None = None, key: str | None = None) -> dict[str, Any]:
+ measured: int | None = None, key: str | None = None,
+ request_headers: dict[str, str] | None = None) -> dict[str, Any]:
"""Send the warm request through the Hermes llm_request and llm_execution middleware, as Hermes sends a
main request. A request middleware can change the request, for example to redact the new rows. An
execution middleware can audit, block, or replace the request. A block, a rewrite, or a replaced reply
@@ -516,6 +519,13 @@ class WarmCompactionEngine(ContextEngine):
key = warm.api_key_text(api_key) if key is None else key
headers = warm.route_headers(key, route[1], provider)
tls = warm.route_tls(route[1])
+ if request_headers:
+ # Per-request headers override client defaults without regard to case. Both middleware chains
+ # must see the option, and the rewrite checks below must protect the captured session value.
+ names = {name.lower() for name in request_headers}
+ headers = {name: value for name, value in headers.items() if name.lower() not in names}
+ headers.update(request_headers)
+ body = {**body, "extra_headers": dict(request_headers)}
context = {"purpose": NAME, "api_request_id": None, "session_id": session_id,
"model": route[0], "base_url": route[1], "api_mode": route[2]}
try:
@@ -562,14 +572,17 @@ class WarmCompactionEngine(ContextEngine):
if self._attempt() != attempt:
raise warm.WarmRefusal("route_changed")
started.append(True)
- result = warm.send(base, route[1], key, post=self._post, extra_headers=headers, ssl_context=tls)
+ # 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)
# The send blocks on the network: a switch can occur before it returns.
if self._attempt() != attempt:
raise warm.WarmRefusal("route_changed")
sent.append((result, dict(result)))
return result
try:
- reply = run_llm_execution_middleware(body, terminal, original_request=base, **context)
+ reply = run_llm_execution_middleware(body, terminal, original_request=copy.deepcopy(base), **context)
except warm.WarmRefusal:
raise
except Exception as error:
diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.py
index e721fc7..7e2c815 100644
--- a/warm_compaction/fallback.py
+++ b/warm_compaction/fallback.py
@@ -179,17 +179,17 @@ def transcript(messages: list, prefixes: Iterable[str], reserve_chars: int = 0,
return "\n\n".join([*head, *recent])
-def _complete_reply(result: Any, raw: str) -> tuple[str, str]:
- """Return (finish reason, text without the end line). ctx.llm reports no finish reason, and an output count
+def _complete_reply(result: Any, raw: str) -> tuple[str | None, str]:
+ """Return (refusal code or None, text without the end line). ctx.llm reports no finish reason, and an output count
below the limit does not show a complete reply: a content filter or a provider limit can stop it. Only a
- reply that ends with END_LINE, below the max_tokens limit, counts as complete ("stop")."""
+ reply that ends with END_LINE, below the max_tokens limit, counts as complete."""
output = getattr(getattr(result, "usage", None), "output_tokens", None)
+ if isinstance(output, int) and not isinstance(output, bool) and output >= MAX_TOKENS:
+ return "output_token_limit", raw
lines = strip_think(raw).rstrip().splitlines()
if not lines or lines[-1].strip() != END_LINE:
- return "length", raw
- if isinstance(output, int) and not isinstance(output, bool) and output >= MAX_TOKENS:
- return "length", raw
- return "stop", "\n".join(lines[:-1])
+ return "missing_end_marker", raw
+ return None, "\n".join(lines[:-1])
def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topic: str | None = None,
@@ -216,8 +216,10 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topi
# The same checks as the warm reply: the five headings, the byte limit, and no summary markers. A reply
# without them (cut off, or an answer to the conversation) must not replace the history.
raw = str(getattr(result, "text", "") or "")
- finish, body = _complete_reply(result, raw)
- text, reason = gate({"content": body, "finish_reason": finish}, prefixes)
+ reason, body = _complete_reply(result, raw)
+ text = None
+ if reason is None:
+ text, reason = gate({"content": body, "finish_reason": "stop"}, prefixes)
if text is None:
logger.warning("Warm compaction fallback summary refused (%s)", reason)
return None, None
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index edcdfa1..600d343 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -482,8 +482,8 @@ def route_headers(api_key: Any, base_url: Any, provider: Any) -> dict[str, str]:
45871e10 (agent.agent_init): the host headers or the provider profile headers, then model.default_headers,
then providers.<name>.extra_headers. Provider headers go with every request (attribution, a User-Agent for a
WAF, gateway credentials). Raise WarmRefusal("headers_unknown") when a source cannot be read: a request
- without them can be refused or go to another cache. Per-request headers (session affinity) are in the
- captured request and refused there. The values can be credentials: never log them."""
+ without them can be refused or go to another cache. The engine adds supported per-request session headers
+ from the capture after this step. The values can be credentials: never log them."""
url = str(base_url or "")
try:
from agent.agent_init import _host_default_headers_factory