Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Keep the tail when a new request ends the history and add a Decisions section (#48)
Elevatormusic1c348f96b56b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 591ca2c..c229a8c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ All notable changes are listed here. The format follows [Keep a Changelog](https### Changed+- Keep the verbatim tail when a new user request is at the end of the history. Before, the tail started at the first user row in the tail budget, so a new request just before a compaction left only that request and its reply (2 rows, about 40 tokens, in the synthetic benchmark fixtures). The tail now keeps the rows that fit, and a copy of the request of the first tail turn goes first; the copy counts in the tail budget.+- Add an optional `## Decisions` section to the warm handoff and the relaxed fallback: each decision with its reason. A reply without it still passes the gate. The quoted fallback format keeps its five sections.- The fallback summary uses the free handoff sections of the warm request by default (`fallback_format: relaxed`). The source-quote format stays available as `fallback_format: quoted`. A relaxed reply without its end marker passes when all headings are present and the reported output count is below the generation limit. Small local models could not write the quoted format: a local 4B model passed 0 of 16 quoted replies and 10 of 10 relaxed replies in one synthetic test.- Give fallback generation an 8,192-token allowance while keeping the visible summary within 2,048 estimated tokens. Check a fresh end marker and the summary content instead of refusing a short reply because its reported output count can include thinking. Retry an invalid reply once from the original transcript, within a shared deadline and cancellation checks. The public API still cannot report the server stop reason or stop an in-flight call.diff --git a/README.md b/README.mdindex afe1cb2..a111462 100644--- a/README.md+++ b/README.md@@ -66,11 +66,11 @@ Run these commands in a terminal (PowerShell, Terminal, or any shell) where the<img src="assets/how-it-works.svg" alt="The built-in compressor sends a separate summary request with a new prompt prefix. warm_compaction sends the last request again with the new rows and a handoff instruction, so the server reuses its prefix cache." width="100%"></p>-At each compaction, the plugin sends the last main-model request of the session again. It adds the rows that came after that request and one handoff instruction at the end. This is the *warm request*. The server can reuse the cached prefix of the earlier request, so it reads only the new rows. The reply is a Markdown handoff with five headings: Goal, User instructions, Current state, Key facts, and Next step. The plugin replaces the older rows with the handoff and keeps a verbatim tail of recent rows.+At each compaction, the plugin sends the last main-model request of the session again. It adds the rows that came after that request and one handoff instruction at the end. This is the *warm request*. The server can reuse the cached prefix of the earlier request, so it reads only the new rows. The reply is a Markdown handoff with six headings: Goal, User instructions, Current state, Decisions, Key facts, and Next step. Decisions is optional: a reply without it passes the gate, so a small model that leaves it out still compacts. The plugin replaces the older rows with the handoff and keeps a verbatim tail of recent rows.After the handoff, the plugin adds a **work ledger**. Code writes the ledger from the tool calls and tool results before the tail; no model writes it. It has two lists: the commands that ran, each with its exit code (or `exit unknown`) and the first error line of its output, and the files that tools wrote, changed, moved, or deleted. A failed edit, or an edit without a result, is listed as a tool call, not as a changed file. Reads are not listed. A later compaction keeps the ledger lines of the earlier summary and adds the new ones. The ledger uses the summary budget that the handoff leaves, at most 1,000 estimated tokens; when it is too large, the oldest commands go first, then the oldest files. It is reference data for the next request, not a list of tasks. Set `ledger: false` to turn it off.-If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a model-based fallback summary through the Hermes auxiliary route. If neither path produces a usable summary and the rows before the tail have tool work, the plugin compacts with a **ledger-only summary**: the five headings with an unknown line, the work ledger, and the copied user messages (`path=ledger`). This keeps a small local model from growing the context without limit when it cannot write a valid summary. Without tool work, or with `ledger_on_failure: false`, the plugin stops the current compaction pass, preserves its original input history, and reports an error with safe codes only. Hermes can retry an automatic failure; the plugin cannot stop the entire host turn through its documented API. When Hermes cancels an attempt, the history stays unchanged.+If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a model-based fallback summary through the Hermes auxiliary route. If neither path produces a usable summary and the rows before the tail have tool work, the plugin compacts with a **ledger-only summary**: the handoff headings with an unknown line, the work ledger, and the copied user messages (`path=ledger`). This keeps a small local model from growing the context without limit when it cannot write a valid summary. Without tool work, or with `ledger_on_failure: false`, the plugin stops the current compaction pass, preserves its original input history, and reports an error with safe codes only. Hermes can retry an automatic failure; the plugin cannot stop the entire host turn through its documented API. When Hermes cancels an attempt, the history stays unchanged.The plugin does this for manual `/compress` and for automatic compaction.@@ -349,7 +349,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and- On Chat Completions routes, the source check accepts exact text or removal of trailing whitespace from a complete text string, including a stored `api_content` string. Leading or inner whitespace changes, added whitespace, and changes to text inside a content list still refuse the warm path (`source_transform_unsupported`). The captured request prefix stays unchanged.- 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.+- The verbatim tail keeps the newest rows that fit in `tail_tokens`, also when a new user request is among them: a new request just before a compaction does not remove the recent work. When the tail starts in the middle of a turn, a copy of the latest user request before it goes first, and that copy counts in the tail budget. The tail must also fit 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 `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.diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex 4516ca3..dc861e0 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -969,6 +969,11 @@ class RelaxedFallbackTest(unittest.TestCase):self.assertIn("Use only facts from the transcript.", instruction)self.assertEqual(instruction.count("End the summary with this line:"), 1)self.assertTrue(self.marker(llm.calls[0][0]).startswith("[END OF SUMMARY "))+ # The relaxed format asks for the Decisions section; the quoted format keeps its five sections.+ self.assertIn("\n## Decisions\n", instruction)+ quoted = FakeLlm(text=lambda messages, kwargs, count: PLAIN + "\n" + self.marker(messages))+ llm_summary(quoted, [user("hi")], PREFIXES, quoted=True)+ self.assertNotIn("## Decisions", quoted.calls[0][0][0]["content"])def test_paraphrased_bullets_pass_in_relaxed_mode_and_fail_in_quoted_mode(self):reply = lambda messages, kwargs, count: PLAIN + "\n" + self.marker(messages) # noqa: E731diff --git a/tests/test_wc_handoff.py b/tests/test_wc_handoff.pyindex d6c6418..833faec 100644--- a/tests/test_wc_handoff.py+++ b/tests/test_wc_handoff.py@@ -36,6 +36,17 @@ class HandoffTest(unittest.TestCase):self.assertIsNone(reason)self.assertTrue(text.startswith("## Goal"))+ def test_the_decisions_section_is_optional_but_keeps_its_order(self):+ # A small model can leave out the optional section (HEADINGS_TEXT has no Decisions section).+ self.assertIsNone(gate(reply(HEADINGS_TEXT))[1])+ decisions = "## Decisions\n- Use JSON, not YAML: the parser needs it.\n\n"+ with_decisions = HEADINGS_TEXT.replace("## Key facts", decisions + "## Key facts")+ text, reason = gate(reply(with_decisions))+ self.assertIsNone(reason)+ self.assertIn("- Use JSON, not YAML", text)+ self.assertEqual(gate(reply(decisions + HEADINGS_TEXT))[1], "heading_order")+ self.assertEqual(gate(reply(with_decisions + "\n\n## Decisions\n- again"))[1], "heading_repeated")+def test_gate_reasons(self):cases = {"finish_not_stop": reply(finish_reason="length"),diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex a0bbd95..b271cfa 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -123,6 +123,13 @@ class TailTest(unittest.TestCase):tool("c1", "x" * 4000)]self.assertEqual(tail_start(rows, 10, PREFIXES), (3, {"role": "user", "content": "do it"}))+ def test_a_new_user_row_at_the_end_keeps_the_budget_tail(self):+ # A new request right before a compaction: the tail keeps the rows that fit in the budget, not only the+ # new request. The first tail rows answer an older request, so a copy of that request goes first.+ rows = [user("old " * 50), user("task"), assistant("", [("c1", "f", "{}")]), tool("c1", "r " * 20),+ assistant("", [("c2", "f", "{}")]), tool("c2", "s " * 20), user("new"), assistant("b")]+ self.assertEqual(tail_start(rows, 100, PREFIXES), (4, {"role": "user", "content": "task"}))+def test_no_row_before_the_tail(self):self.assertEqual(tail_start([user("only")], 10_000, PREFIXES), (0, None))diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex eb6f6a2..8b79be4 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -413,7 +413,7 @@ class WarmCompactionEngine(ContextEngine):return messagesif summary is None and self._settings["ledger"] and self._settings["ledger_on_failure"]:# Both model summaries failed (a small model can miss the format): compact with the work ledger and the- # copied user messages, under the five headings with an unknown line. Without a ledger, keep history.+ # copied user messages, under the handoff headings with an unknown line. Without a ledger, keep history.stub = "\n\n".join(f"{heading}\n{LEDGER_ONLY_LINE}" for heading in handoff.HEADINGS)# Leave room for the cut quote of a long prepended request, as on the fallback path.quote_room = fallback.CUT_QUOTE_CHARS // 4 if prepend else 0diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex 6165b79..95d5cb1 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -12,7 +12,7 @@ from collections.abc import Callable, Iterablefrom .handoff import (DEFAULT_SUMMARY_WORDS, END_MARKER, HEADINGS, INSTRUCTION_TEMPLATE, LEGACY_PREFIX, MAX_REPLY_BYTES,- SUMMARY_WORDS_TOKEN,+ OPTIONAL_HEADINGS, SUMMARY_WORDS_TOKEN,extras, gate_content,)from .layout import COPY_HEADING, CUT_NOTE, is_real_user, is_summary, quote@@ -118,10 +118,9 @@ FALLBACK_INSTRUCTION = FALLBACK_INSTRUCTION_TEMPLATE.replace(SUMMARY_WORDS_TOKEN# The relaxed format: the rules of the quoted format with the handoff sections of the warm request, without source# quotes. A small model can write it. The work ledger keeps the exact command results and file changes.-_SECTIONS = "Use these five headings"RELAXED_INSTRUCTION_TEMPLATE = (- FALLBACK_INSTRUCTION_TEMPLATE[:FALLBACK_INSTRUCTION_TEMPLATE.index(_SECTIONS)]- + INSTRUCTION_TEMPLATE[INSTRUCTION_TEMPLATE.index(_SECTIONS):]+ FALLBACK_INSTRUCTION_TEMPLATE[:FALLBACK_INSTRUCTION_TEMPLATE.index("Use these five headings")]+ + INSTRUCTION_TEMPLATE[INSTRUCTION_TEMPLATE.index("Use these six headings"):]+ "\nEnd the summary with this line:\n" + END_LINE + "\n")@@ -396,6 +395,9 @@ def error_class(error: Exception) -> str:return name if name.isascii() and name.isidentifier() and len(name) <= 80 else "Exception"+# The quoted format has the five required-order sections only, not the optional ones of the handoff. In an earlier+# summary, an optional heading is section text.+QUOTED_HEADINGS = tuple(heading for heading in HEADINGS if heading not in OPTIONAL_HEADINGS)SOURCE_SECTIONS = (("## Goal", "## User instructions", "- goal unknown"),("## User instructions", "## Current state", "- instructions unknown"),("## Current state", "## Key facts", "- progress unknown"),@@ -430,7 +432,7 @@ def _source_spans(lines: list[str], prior: bool = False) -> list[tuple[int, int,continuestart = headings.index(heading) + 1end = headings.index(next_heading) if next_heading is not None else len(lines)- if start <= end and not any(line in HEADINGS for line in headings[start:end]):+ if start <= end and not any(line in QUOTED_HEADINGS for line in headings[start:end]):spans.append((start, end, unknown))return spans@@ -465,7 +467,7 @@ class _SourceTable:structural: set[int] = set()for start, end, unknown in spans:structural.add(start - 1)- if end < len(earlier_lines) and earlier_lines[end].strip() in HEADINGS:+ if end < len(earlier_lines) and earlier_lines[end].strip() in QUOTED_HEADINGS:structural.add(end)structural.update(index for index in range(start, end) if earlier_lines[index].strip() == unknown)for index in range(start, end):diff --git a/warm_compaction/handoff.py b/warm_compaction/handoff.pyindex 20cbccd..b55faa0 100644--- a/warm_compaction/handoff.py+++ b/warm_compaction/handoff.py@@ -7,8 +7,10 @@ from collections.abc import Iterablefrom .rows import reply_text-HEADINGS = ("## Goal", "## User instructions", "## Current state", "## Key facts", "## Next step")+HEADINGS = ("## Goal", "## User instructions", "## Current state", "## Decisions", "## Key facts", "## Next step")REQUIRED_SECTIONS = ("## Goal", "## Current state", "## Next step")+# A reply can leave out an optional heading: a small model can miss it. When it is present, its order is checked.+OPTIONAL_HEADINGS = ("## Decisions",)MAX_REPLY_BYTES = 24_000LEGACY_PREFIX = "[CONTEXT SUMMARY]:"END_MARKER = "--- END OF CONTEXT SUMMARY"@@ -27,7 +29,7 @@ Rules:- Write in the language of the conversation. Use short bullets. Use at most {summary_words} words.- Leave out data that the task does not need, for example unrelated records or logs.-Use these five headings, in this order, each on its own line. Start the reply with "## Goal":+Use these six headings, in this order, each on its own line. Start the reply with "## Goal":## GoalThe current goal of the user, in one or two sentences.@@ -46,6 +48,11 @@ asked for it.what is missing.- [CANCELLED] when the user cancelled or replaced it.+## Decisions+Each decision that was made, as a bullet with its reason when the conversation gives one: for example a chosen \+approach, a rejected option, or a changed plan. When a later message changed a decision, give the current \+decision and say what it replaces. Write "- none" when no decision was made.+## Key factsIdentifiers, names, values, and results that the next step needs. When a value replaced an older value, give the \current value and say that it replaces the old one. Write "unverified" next to a claim that the conversation does \@@ -100,12 +107,13 @@ def gate_content(content: Any, summary_prefixes: Iterable[str] = ()) -> tuple[stif any(marker and marker in text for marker in (LEGACY_PREFIX, END_MARKER, *summary_prefixes)):return None, "carrier_marker"lines = [line.strip() for line in text.splitlines()]- if any(heading not in lines for heading in HEADINGS):+ if any(heading not in lines for heading in HEADINGS if heading not in OPTIONAL_HEADINGS):return None, "heading_missing"# A repeated heading is not section text: "## Goal" twice must not count as a goal.if any(lines.count(heading) > 1 for heading in HEADINGS):return None, "heading_repeated"- starts = [lines.index(heading) for heading in HEADINGS]+ present = [heading for heading in HEADINGS if heading in lines]+ starts = [lines.index(heading) for heading in present]if starts != sorted(starts):return None, "heading_order"# Text before the first heading can be an answer, or an action that did not occur: not a summary.@@ -113,7 +121,7 @@ def gate_content(content: Any, summary_prefixes: Iterable[str] = ()) -> tuple[streturn None, "heading_preamble"# The goal, the state, and the next step are necessary to continue the task. The user instructions and# the key facts can be empty: there can be none.- for heading, start, end in zip(HEADINGS, starts, [*starts[1:], len(lines)]):+ for heading, start, end in zip(present, starts, [*starts[1:], len(lines)]):if heading in REQUIRED_SECTIONS and not any(lines[start + 1:end]):return None, "section_empty"return text, Nonediff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex 55f2a04..bf3bd19 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -163,24 +163,38 @@ def units(messages: list) -> list[tuple[int, int]]:def tail_start(messages: list, tail_tokens: int, prefixes: Iterable[str],policy: SendPolicy = SendPolicy()) -> tuple[int, dict[str, Any] | None]:- """Return the first tail index and, in the middle of a task, a copy of the latest real user row."""+ """Return the first tail index and, when the tail does not start at a real user row, a copy of the latest+ real user row before it."""prefixes = tuple(prefixes)spans = units(messages)if not spans:return 0, None+ # The latest real user row before each index: when the tail starts in the middle of a turn, a copy of that+ # request goes first.+ before: list[dict[str, Any] | None] = []+ latest = None+ for row in messages:+ before.append(latest)+ if is_real_user(row, prefixes):+ latest = row++ def needs_copy(index: int) -> bool:+ return not is_real_user(messages[index], prefixes) and before[index] is not None+start = spans[-1][0]# As Hermes sends the rows: the stored display text of a row with api_content is not in the request.size = sum(sent_tokens(row, policy) for row in messages[start:])+ # The tail keeps all rows that fit, also when a newer user row is in it: a new request just before a compaction+ # must not remove the recent work. A start in the middle of a turn counts the copy of its request too.for span_start, span_end in reversed(spans[:-1]):- cost = sum(sent_tokens(row, policy) for row in messages[span_start:span_end])- if size + cost > tail_tokens:+ size += sum(sent_tokens(row, policy) for row in messages[span_start:span_end])+ if size > tail_tokens:break- size += cost- start = span_start- for index in range(start, len(messages)):- if is_real_user(messages[index], prefixes):- return index, None- latest = next((row for row in reversed(messages[:start]) if is_real_user(row, prefixes)), None)+ if not needs_copy(span_start) or size + sent_tokens(before[span_start], policy) <= tail_tokens:+ start = span_start+ if not needs_copy(start):+ return start, None+ latest = before[start]if latest is None:return start, Noneprepend = {"role": "user", "content": copy.deepcopy(latest["content"])}diff --git a/warm_compaction/warm.py b/warm_compaction/warm.pyindex 79b2914..d25c4e5 100644--- a/warm_compaction/warm.py+++ b/warm_compaction/warm.py@@ -437,7 +437,7 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, contextrequest["messages"] = [*body["messages"], *_join_user_rows(added, instruction)]request["stream"] = Falserequest.pop("stream_options", None)- # A stop sequence of the main request could cut the handoff after the five headings.+ # A stop sequence of the main request could cut the handoff after the handoff headings.request.pop("stop", None)# A web search costs a search and can bring text that is not in the conversation into the handoff.request.pop("web_search_options", None)