Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Cut large assistant rows, cap the tail with an unknown overhead, and summarize cut middles
Elevatormusicc2969574daf2
diff --git a/README.md b/README.mdindex 183a88d..a6cec3c 100644--- a/README.md+++ b/README.md@@ -196,7 +196,7 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and## Limits- The warm path needs a captured main-model request in the current Hermes process. After a restart or a resume, the first compaction uses the fallback summary if no main-model request completed before it (`no_capture`).-- The verbatim tail keeps the newest rows that fit in `tail_tokens`. It stops at the first older row that does not fit, and that row goes into the summary.+- The verbatim tail keeps the newest rows that fit in `tail_tokens`. 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 user, assistant, and tool rows keep only their start and end; an assistant row keeps its tool calls. The fallback summary gets the cut middles. With an unknown request overhead (no usable capture and no host token count), the tail takes at most half of the free room. A capture of another route, or one whose rows a middleware changed, is not used for the room.- 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`).- 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/evidence/plugin-integration.json b/evidence/plugin-integration.jsonindex d4ff5e7..4e4bb73 100644--- a/evidence/plugin-integration.json+++ b/evidence/plugin-integration.json@@ -1,6 +1,6 @@{"check": "standalone warm_compaction plugin on unpatched Hermes Agent",- "started_utc": "2026-10-06T12:08:10Z",+ "started_utc": "2026-10-06T12:35:21Z","hermes": {"commit": "45871e100feceb89769536c88e5e6e265226a409","clean": true@@ -10,12 +10,12 @@"plugin_files_sha256": {"warm_compaction/__init__.py": "11e038f05813627b2d1d8b82b3b775ecfe41015746c8e90ed6d452cfdaec65a6","warm_compaction/capture.py": "387a5bda2c97530c6e9114e810ac062199e3731c12a582d75598d2bdb95e8c57",- "warm_compaction/engine.py": "46e139f7c1b1fca9926aae215686ee63c42320373ff7e1ab4630a9ec6f0623cd",+ "warm_compaction/engine.py": "c70f188a789215e70d1252ea350d1f8433a1f989572b174a316447011a0d71d1","warm_compaction/fallback.py": "30ef046f0511491175d99a772afcc2c9a8f3a9920d0c077821a89f19147682f9","warm_compaction/handoff.py": "3ce85d76fce4afbefec0d9c2e91b100e09ac677a28e50ea749f4d25533d68c7e",- "warm_compaction/layout.py": "ebc6859b93bc82536cce769eb0513f9d946cab3f0417848723518f1216fd1ad3",+ "warm_compaction/layout.py": "8e05c88f13c29330e1bd1a3bdb4410cd1c0a8a6ce30fcf8a118bd88a8e0a55e4","warm_compaction/plugin.yaml": "d67560fd4625ec80d9e26f3e6d712763e77474f68d469c7e48f09fd3506ccc71",- "warm_compaction/rows.py": "cc2a8a3d0561559f24fc40881453441d938ea9d7803e1df81a107a5e05e5f00a",+ "warm_compaction/rows.py": "689c0619df6a7f8b89ef05ae87ec81b62c812ce34f81bfe557eb653158effac4","warm_compaction/warm.py": "081642f19498b379551af33b70ad01dae3902e1e805c360a08be9f74242d320f"},"privacy": "metadata only: names, counts, codes, booleans, and times; no message text",@@ -76,11 +76,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.095,+ "compress_seconds": 0.098,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.02,+ "elapsed_s": 0.025,"prompt_tokens": 33883,"cached_tokens": 16941},@@ -88,11 +88,10 @@"final_session_id": "wc-enable_manual_warm","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 4,- "network_host_blocked": 1+ "network_host_blocked": 1,+ "child_process_blocked": 3},"fence_blocked_programs": [- "git","pip","python","python3"@@ -101,7 +100,6 @@"hermes-assets.nousresearch.com"],"fence_blocked_callers": [- "child_process_blocked from hermes_cli/source_check.py:_git_run < hermes_cli/source_check.py:_git_stdout < hermes_cli/source_check.py:_read_checkout","child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_pip_python_version","child_process_blocked from tools/env_probe.py:_run < tools/env_probe.py:_py_out < tools/env_probe.py:_python_version_of","network_host_blocked from hermes_cli/release_channels.py:read < hermes_cli/release_channels.py:read_bytes < hermes_cli/release_channels.py:read_record"@@ -189,7 +187,7 @@"install","run"],- "process_seconds": 52.135+ "process_seconds": 53.236},{"scenario": "manual_fallback",@@ -248,11 +246,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.23,+ "compress_seconds": 0.227,"warm_last": {"path": "fallback","reason": "provider_error",- "elapsed_s": 0.094,+ "elapsed_s": 0.109,"prompt_tokens": null,"cached_tokens": null},@@ -361,7 +359,7 @@"install","run"],- "process_seconds": 32.312+ "process_seconds": 32.914},{"scenario": "manual_fixed",@@ -419,11 +417,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.238,+ "compress_seconds": 0.241,"warm_last": {"path": "fixed","reason": "provider_error",- "elapsed_s": 0.11,+ "elapsed_s": 0.125,"prompt_tokens": null,"cached_tokens": null},@@ -532,7 +530,7 @@"install","run"],- "process_seconds": 29.699+ "process_seconds": 29.487},{"scenario": "auto_tool_loop",@@ -620,7 +618,7 @@"warm_last_1": {"path": "warm","reason": "accepted",- "elapsed_s": 0.016,+ "elapsed_s": 0.0,"prompt_tokens": 35201,"cached_tokens": 17600},@@ -737,7 +735,7 @@"install","run"],- "process_seconds": 32.063+ "process_seconds": 32.249},{"scenario": "rollback",@@ -787,11 +785,11 @@"threshold_tokens": 100000,"context_length": 200000},- "compress_seconds": 0.136,+ "compress_seconds": 0.163,"warm_last": {"path": "warm","reason": "accepted",- "elapsed_s": 0.015,+ "elapsed_s": 0.016,"prompt_tokens": 33873,"cached_tokens": 16936},@@ -799,7 +797,7 @@"final_session_id": "wc-rollback","continuation_keeps_custom_system_text": false,"fence_denied": {- "child_process_blocked": 5,+ "child_process_blocked": 4,"network_host_blocked": 1},"fence_blocked_programs": [@@ -950,7 +948,8 @@"stored": 30},"fence_denied": {- "child_process_blocked": 5+ "child_process_blocked": 5,+ "network_host_blocked": 1},"fence_blocked_programs": ["git",@@ -958,7 +957,9 @@"python","python3"],- "fence_blocked_hosts": []+ "fence_blocked_hosts": [+ "hermes-assets.nousresearch.com"+ ]},"exit": [0,@@ -970,10 +971,10 @@"run","rollback"],- "process_seconds": 36.313+ "process_seconds": 37.327}],- "finished_utc": "2026-10-06T12:11:13Z",+ "finished_utc": "2026-10-06T12:38:26Z","passed": true,"run_folder": "outside repository"}diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex f9b743a..515fec0 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -539,6 +539,56 @@ class EngineTest(unittest.TestCase):self.assertEqual((self.engine.warm_last, self.engine.compression_count), (None, 0))self.assertIn("warm_last", self.engine.get_status())+ def test_an_unknown_overhead_caps_the_tail(self):+ # Without a known overhead (no capture and no host count), the tail takes at most half of the free room:+ # the other half is for the system rows and the tool schemas.+ from warm_compaction.engine import CARRIER_TOKENS+ from warm_compaction.rows import estimate_tokens+ from warm_compaction.warm import DEFAULT_RESERVE+ rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]),+ tool("c1", "head " + "r" * 200_000 + " tail")]+ engine = self.make(threshold=0.95, tail_tokens=9_500, warm=False)+ engine.update_model(model=ROUTE[0], context_length=20_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ limit = min(engine.threshold_tokens, 20_000 - DEFAULT_RESERVE)+ for current, capped in ((estimate_tokens(rows) + 1_000, False), (None, True)):+ with self.subTest(current=current):+ new = engine.compress(list(rows), current_tokens=current)+ tail = [row for row in new if not row.get("_compressed_summary")]+ self.assertEqual(estimate_tokens(tail) <= (limit - CARRIER_TOKENS) // 2, capped)++ def test_the_fallback_summary_gets_the_middles_that_the_tail_cuts(self):+ from warm_compaction.layout import CUT_NOTE+ rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]),+ tool("c1", "head " + "u" * 40_000 + " end")]+ engine = self.make(tail_tokens=2_000, warm=False)+ new = engine.compress(rows, current_tokens=None)+ self.assertEqual(engine.warm_last["path"], "fallback")+ transcript = self.llm.calls[-1][0][1]["content"]+ self.assertIn(CUT_NOTE, transcript)+ self.assertIn("u" * 100, transcript)+ self.assertTrue(any(str(row.get("content")).endswith(" end") for row in new))++ def test_a_capture_with_a_changed_source_is_not_used_for_the_budget(self):+ # A middleware removed a stored row: the captured body no longer shows which rows are the system rows.+ from warm_compaction.rows import estimate_tokens+ large = "s " * 120_000+ rows = [user("first " + "f" * 239_990), assistant("a"), *old_turns(6), assistant("final")]+ engine = self.make(threshold=0.95, tail_tokens=2_000)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ self.store.on_pre_api_request(api_request_id="r1", session_id="s1", conversation_history=list(rows[:-1]),+ model=ROUTE[0], base_url=ROUTE[1], api_mode=ROUTE[2])+ self.store.on_llm_execution(request={"model": ROUTE[0], "messages": [{"role": "system", "content": large},+ *wire(rows[1:-1])]},+ next_call=lambda: None, api_request_id="r1")+ self.store.on_post_api_request(api_request_id="r1", session_id="s1", finish_reason="stop",+ assistant_message=reply_object(rows[-1]))+ new = engine.compress(rows, current_tokens=estimate_tokens(rows) + estimate_tokens(large))+ self.assertEqual(engine.warm_last["reason"], "source_transform_unsupported")+ summary = next(row["content"] for row in new if "## Copied user messages" in str(row["content"]))+ self.assertTrue(summary.split("## Copied user messages", 1)[1].strip().startswith("(none)"))+class SettingsTest(unittest.TestCase):def setUp(self):diff --git a/tests/test_wc_layout.py b/tests/test_wc_layout.pyindex 9151965..c85571f 100644--- a/tests/test_wc_layout.py+++ b/tests/test_wc_layout.py@@ -177,6 +177,32 @@ class BoundTailTest(unittest.TestCase):self.assertNotIn("api_content", bounded[2])self.assertIs(bound_tail(rows[:1], 2_000)[0], rows[0])+ def test_a_large_assistant_row_is_cut_and_keeps_its_tool_calls(self):+ from warm_compaction.layout import bound_tail+ from warm_compaction.rows import MIDDLE_MARK, estimate_tokens+ rows = [user("ask"), assistant("start " + "a" * 40_000 + " end", [("c1", "read", "{}")]), tool("c1", "r")]+ bounded = bound_tail(rows, 2_000)+ self.assertLessEqual(sum(estimate_tokens(row) for row in bounded), 2_000)+ self.assertEqual(bounded[1]["tool_calls"], rows[1]["tool_calls"])+ self.assertTrue(bounded[1]["content"].startswith("start ") and bounded[1]["content"].endswith(" end"))+ self.assertIn(MIDDLE_MARK, bounded[1]["content"])++ def test_the_cut_middles_are_given_back(self):+ # The fallback summary gets the parts that the tail cuts: they are not lost.+ from warm_compaction.layout import CUT_NOTE, bound_tail+ from warm_compaction.rows import MIDDLE_MARK+ text = "head " + "".join(f"{index:06d}" for index in range(8_000)) + " tail"+ rows = [assistant("", [("c1", "read", "{}")]), tool("c1", text), user("short")]+ removed = []+ bounded = bound_tail(rows, 1_000, removed)+ self.assertEqual(len(removed), 1)+ self.assertEqual((removed[0]["role"], removed[0]["tool_call_id"]), ("tool", "c1"))+ self.assertTrue(removed[0]["content"].startswith(CUT_NOTE))+ head, end = bounded[1]["content"].split(MIDDLE_MARK)+ self.assertEqual(head + removed[0]["content"][len(CUT_NOTE):] + end, text)+ self.assertEqual(bound_tail(rows[2:], 1_000, removed), rows[2:])+ self.assertEqual(len(removed), 1)+def test_build_bounds_the_tail(self):from warm_compaction.rows import estimate_tokensrows = [user("old"), assistant("a"), user("huge " + "z" * 40_000 + " end")]diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex c7aad51..45c3202 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -24,6 +24,9 @@ TAIL_MAX = 25_000# The summary row without the summary text and the copies: the header, the headings, the end marker, and the# quote marks, with a margin for the estimate.CARRIER_TOKENS = 500+# The summary size that the tail cap keeps free before the fallback summary is known: two times its reply+# limit, because the estimate and the server count do not use the same tokenizer.+SUMMARY_RESERVE = 2 * fallback.MAX_TOKENSHERMES_END_MARKER = "--- END OF CONTEXT SUMMARY — respond to the message below, not the summary above ---"HERMES_DB_MARKER = "_db_persisted"@@ -196,12 +199,20 @@ class WarmCompactionEngine(ContextEngine):record: dict[str, Any] = {"path": None, "reason": None, "elapsed_s": None, "prompt_tokens": None,"cached_tokens": None}capture = self._store.latest(self._wc_session_id)+ # An unknown overhead can be most of the window: then no copies. A capture of another route says nothing+ # about the system prompt, the tools, and the reply limit of this one.+ budget = self._budget_capture(capture, messages)+ overhead = request_overhead(budget, messages, current_tokens)+ reserve = request_reserve(budget)summary = self._warm_summary(messages, capture, focus_topic, memory, prefixes, record)+ # The middles that the tail cuts (see layout.bound_tail): the rows before the tail do not have them.+ removed: list = []if summary is None and not self._cancelled():+ layout.bound_tail(messages[start:], self._tail_cap(SUMMARY_RESERVE, overhead, reserve), removed)# Only the rows before the tail: the tail stays as it is, and a transcript of the whole history# can spend its budget on the tail.- summary, _tokens = fallback.llm_summary(self._llm, messages[:start], prefixes, focus_topic=focus_topic,- memory_context=memory, task=self._task)+ summary, _tokens = fallback.llm_summary(self._llm, [*messages[:start], *removed], prefixes,+ focus_topic=focus_topic, memory_context=memory, task=self._task)if summary is not None:record["path"] = "fallback"if self._cancelled():@@ -209,28 +220,25 @@ class WarmCompactionEngine(ContextEngine):self._finish(record, started)return messagesif summary is None:- summary = fallback.fixed_summary(messages[:start], prefixes)+ summary = fallback.fixed_summary([*messages[:start], *removed], prefixes)record["path"] = "fixed"- # An unknown overhead can be most of the window: then no copies. A capture of another route says- # nothing about the system prompt, the tools, and the reply limit of this one.- budget = capture if capture is not None and tuple(capture.get("route") or ()) == tuple(self._wc_route) else None- overhead = request_overhead(budget, messages, current_tokens)- copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead,- request_reserve(budget))+ copy_tokens = 0 if overhead is None else self._copy_tokens(messages[start:], summary, overhead, reserve)# The prepended user row must be in the tail: when it does not fit in the room, keep its start and end.# With an unknown overhead, the room is unknown too: the row keeps only its minimum.- room = self._room(messages[start:], summary, overhead or 0, request_reserve(budget))+ room = self._room(messages[start:], summary, overhead or 0, reserve)if prepend is not None and room is not None:allowed = room if overhead is not None else 0if estimate_tokens(prepend) > allowed:prepend = layout.fit_user_row(prepend, allowed)+ tail_tokens = self._tail_cap(estimate_tokens(summary), overhead, reserve,+ estimate_tokens(prepend) if prepend is not None else 0)new = layout.build(messages, summary, start=start, prepend=prepend, copy_chars=int(self._settings["user_copy_chars"]),header_prefix=hermes_value("agent.context_compressor", "SUMMARY_PREFIX", handoff.LEGACY_PREFIX),prefixes=prefixes,end_marker=hermes_value("agent.context_compressor", "_SUMMARY_END_MARKER", HERMES_END_MARKER),marker=hermes_value("agent.context_compressor", "_DB_PERSISTED_MARKER", HERMES_DB_MARKER),- copy_tokens=copy_tokens, tail_tokens=self._tail_tokens())+ copy_tokens=copy_tokens, tail_tokens=tail_tokens)self.compression_count += 1self._finish(record, started)return new@@ -348,6 +356,35 @@ class WarmCompactionEngine(ContextEngine):limit = min(threshold, window - reserve) if window > 0 else thresholdreturn limit - (overhead + estimate_tokens(tail_rows) + estimate_tokens(summary) + CARRIER_TOKENS)+ def _tail_cap(self, summary_tokens: int, overhead: int | None, reserve: int, prepend_tokens: int = 0) -> int:+ """The tail budget, and at most the free room for the tail after the overhead, the summary, and the+ prepended row. With an unknown overhead, the tail takes at most half of that room: the other half is for+ the system rows and the tool schemas that the next request also sends."""+ tail = self._tail_tokens()+ free = self._room([], "", overhead or 0, reserve)+ if free is None:+ return tail+ free -= summary_tokens + prepend_tokens+ if overhead is None:+ free //= 2+ return max(0, min(tail, free))++ def _budget_capture(self, capture: dict[str, Any] | None, messages: list) -> dict[str, Any] | None:+ """The capture for the request budget, or None. Its body must be of this route, and it must be the system+ rows followed by the stored rows (the warm path checks): otherwise, the count of its system rows is not+ known."""+ if capture is None or tuple(capture.get("route") or ()) != tuple(self._wc_route):+ return None+ body = capture.get("body")+ if not isinstance(body, dict) or not isinstance(body.get("messages"), list):+ return None+ try:+ warm.split_history(capture, messages)+ warm.check_source(body, messages[: len(capture["digests"])], self._wc_route[1])+ except Exception:+ return None+ return capture+def _copy_tokens(self, tail_rows: list, summary: str, overhead: int = 0, reserve: int = 0) -> int:"""Token allowance for the copied user messages and the prepended user row: at most the tail size, andthe free room (_room)."""diff --git a/warm_compaction/layout.py b/warm_compaction/layout.pyindex 1b11a27..fed641c 100644--- a/warm_compaction/layout.py+++ b/warm_compaction/layout.py@@ -7,12 +7,13 @@ import functoolsfrom typing import Any, Iterablefrom .handoff import END_MARKER, LEGACY_PREFIX-from .rows import api_content, attr, cut_middle, estimate_tokens, hermes_value, plain_text, visible_text+from .rows import api_content, attr, cut_bounds, cut_middle, estimate_tokens, hermes_value, plain_text, visible_textHEADER_TEXT = "The summary of the earlier turns follows."COPY_HEADING = "## Copied user messages"COPY_EACH = 4_000MIN_COPY_CHARS = 200+CUT_NOTE = "[The middle of a newest row; its start and end stay after the summary.]\n"NO_COPIES = "(none)"STEER_KIND = "steer"SYNTHETIC_FLAGS = ("_dropped_toolcall_nudge",)@@ -223,19 +224,24 @@ def _tail_row(row: Any, marker: str) -> Any:return clean-def bound_tail(rows: list, tokens: int) -> list:+def bound_tail(rows: list, tokens: int, removed: list | None = None) -> list:"""Return the tail rows in about tokens estimated tokens. The tail keeps whole units, so the newest unit can- be larger than the tail budget (a large user message or tool result). Then the largest text rows (tool- results and user messages, as Hermes sent them) are cut to their start and end, until the rows fit or no- row has more than MIN_COPY_CHARS characters. Other rows stay as they are."""+ be larger than the tail budget (a large user message, assistant reply, or tool result). Then the largest text+ rows (as Hermes sent them) are cut to their start and end, until the rows fit or no row has more than+ MIN_COPY_CHARS characters. An assistant row keeps its tool calls. Other rows stay as they are.++ With a removed list, one row for each cut row is added to it: the removed middle after CUT_NOTE, with the role+ (and the tool call id) of the row. The fallback summary can then keep what the tail cuts."""rows = list(rows)+ originals: dict[int, str] = {}+ limits: dict[int, int] = {}def text_of(row: Any) -> Any:- return api_content(row) if attr(row, "role") == "user" else attr(row, "content")+ return api_content(row) if attr(row, "role") in ("user", "assistant") else attr(row, "content")while sum(estimate_tokens(row) for row in rows) > tokens:cuttable = [(estimate_tokens(row), index) for index, row in enumerate(rows)- if isinstance(row, dict) and attr(row, "role") in ("user", "tool")+ if isinstance(row, dict) and attr(row, "role") in ("user", "assistant", "tool")and isinstance(text_of(row), str) and len(text_of(row)) > MIN_COPY_CHARS]if not cuttable:break@@ -243,9 +249,20 @@ def bound_tail(rows: list, tokens: int) -> list:text = text_of(rows[index])target = cost - (sum(estimate_tokens(row) for row in rows) - tokens)limit = max(MIN_COPY_CHARS, min(len(text) - 1, len(text) * max(target, 0) // max(cost, 1)))+ # Cut the original text again: the kept start and end are then parts of the original text.+ original = originals.setdefault(index, text)+ limits[index] = limitcut = {key: value for key, value in rows[index].items() if key != "api_content"}- cut["content"] = cut_middle(text, limit)+ cut["content"] = cut_middle(original, limit)rows[index] = cut+ if removed is not None:+ for index in sorted(originals):+ original = originals[index]+ first, second = cut_bounds(original, limits[index])+ part = {"role": attr(rows[index], "role"), "content": CUT_NOTE + original[first:second]}+ if part["role"] == "tool":+ part["tool_call_id"] = attr(rows[index], "tool_call_id")+ removed.append(part)return rowsdiff --git a/warm_compaction/rows.py b/warm_compaction/rows.pyindex 960d2ca..d5b8fb8 100644--- a/warm_compaction/rows.py+++ b/warm_compaction/rows.py@@ -99,16 +99,27 @@ def visible_text(content: Any) -> str:MIDDLE_MARK = " [cut] "+def cut_bounds(text: str, limit: int) -> tuple[int, int]:+ """Return (end of the kept start, start of the kept end) of cut_middle: text[first:second] is the removed+ part."""+ if len(text) <= limit:+ return len(text), len(text)+ keep = limit - len(MIDDLE_MARK)+ if keep < 2:+ return max(limit, 0), len(text)+ head = keep * 2 // 3+ return head, len(text) - (keep - head)++def cut_middle(text: str, limit: int) -> str:"""Return at most limit characters: the start (two thirds) and the end of the text, with a mark between.The end of a long text often has the result, the question, or the output rules."""if len(text) <= limit:return text- keep = limit - len(MIDDLE_MARK)- if keep < 2:- return text[:max(limit, 0)]- head = keep * 2 // 3- return text[:head] + MIDDLE_MARK + text[len(text) - (keep - head):]+ head, end = cut_bounds(text, limit)+ if end == len(text):+ return text[:head]+ return text[:head] + MIDDLE_MARK + text[end:]def strip_think(text: str) -> str: