The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(matrix): keep every outbound event under the homeserver's byte cap
Frorautd584836ffaa5
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 3b95ade06b4..03e448d16a6 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -10,7 +10,7 @@ Env vars (config.yaml ``matrix:`` keys alias several — env wins):MATRIX_REQUIRE_MENTION (default true), MATRIX_THREAD_REQUIRE_MENTION, MATRIX_FREE_RESPONSE_ROOMS,MATRIX_PROCESS_NOTICES, MATRIX_ALLOW_ROOM_MENTIONS, MATRIX_ALLOW_PUBLIC_ROOMS (all default false);MATRIX_AUTO_THREAD (default true), MATRIX_DM_AUTO_THREAD, MATRIX_DM_MENTION_THREADS,- MATRIX_SESSION_SCOPE auto|room|thread; MATRIX_MAX_MESSAGE_LENGTH (default 16000),+ MATRIX_SESSION_SCOPE auto|room|thread; MATRIX_MAX_MESSAGE_LENGTH (UTF-8 bytes, default/max 15000),MATRIX_MAX_MEDIA_BYTES, MATRIX_ROOM_IDENTITY_TTL_SECONDS; MATRIX_APPROVAL_REQUIRE_SENDER (defaulttrue), MATRIX_APPROVAL_TIMEOUT_SECONDS (default 300).@@ -28,6 +28,7 @@ from __future__ import annotationsimport asyncioimport arrayimport inspect+import jsonfrom contextlib import suppressimport loggingimport mimetypes@@ -370,12 +371,23 @@ class _MatrixPickerPrompt:_MatrixModelPickerPrompt = _MatrixChoicePickerPrompt = _MatrixPickerPrompt-# Spec allows ~65 KB events; 4000 was too small (split Markdown tables mid-row).-# Matrix message size limit. The spec allows large events (~65 KB), but very large bodies can render poorly-# in some clients. The previous 4,000-char default was overly conservative and split Markdown tables mid-row-# (#53026).-DEFAULT_MAX_MESSAGE_LENGTH = 16000-MATRIX_MAX_MESSAGE_LENGTH_CEILING = 65535+# The homeserver rejects an event whose JSON exceeds 65,536 bytes (M_TOO_LARGE). Event content stays+# under this budget so the envelope (ids, hashes, signatures) and E2EE's 4/3 base64 inflation still fit.+_MAX_CONTENT_BYTES = 45_000+# Outbound text is measured in UTF-8 bytes (``message_len_fn``). A message carries it twice (body ++# formatted_body, whose HTML runs up to about twice the Markdown), so a chunk gets a third of the+# budget. The previous 4,000-char default split Markdown tables mid-row (#53026).+MATRIX_MAX_MESSAGE_LENGTH_CEILING = _MAX_CONTENT_BYTES // 3+DEFAULT_MAX_MESSAGE_LENGTH = MATRIX_MAX_MESSAGE_LENGTH_CEILING+++def _utf8_len(text: str) -> int:+ return len(text.encode("utf-8"))+++def _content_bytes(content: Dict[str, Any]) -> int:+ """Size of event content as the homeserver counts it (canonical JSON is UTF-8, not \\u-escaped)."""+ return _utf8_len(json.dumps(content, ensure_ascii=False, separators=(",", ":")))def _resolve_max_message_length(config) -> int:@@ -830,6 +842,11 @@ class MatrixAdapter(BasePlatformAdapter):max_message_length = DEFAULT_MAX_MESSAGE_LENGTH_SPLIT_THRESHOLD = DEFAULT_MAX_MESSAGE_LENGTH - 100+ @property+ def message_len_fn(self):+ """UTF-8 bytes, the unit of the homeserver's event cap (a CJK character is three)."""+ return _utf8_len+def _resolve_store_dir(self) -> Path:"""Pin the crypto-store dir to the active profile (connect() runs inside the profilescope); cached so later out-of-scope reads report the store actually in use."""@@ -1408,7 +1425,8 @@ class MatrixAdapter(BasePlatformAdapter):if not content:return SendResult(success=True)last_event_id = None- for chunk in self.truncate_message(self.format_message(content), self.max_message_length):+ for chunk in self.truncate_message(+ self.format_message(content), self.max_message_length, len_fn=self.message_len_fn):msg_content = self._build_text_message_content(chunk)self._apply_relation_metadata(msg_content, reply_to=reply_to, metadata=metadata)try:@@ -1501,6 +1519,15 @@ class MatrixAdapter(BasePlatformAdapter):msg_content["format"] = "org.matrix.custom.html"msg_content["formatted_body"] = f'* {new_content["formatted_body"]}'msg_content["m.relates_to"] = {"rel_type": "m.replace", "event_id": message_id}+ if _content_bytes(msg_content) > _MAX_CONTENT_BYTES:+ # The top-level copy is only the fallback for clients without edit support (edit-aware+ # clients render m.new_content); shorten it rather than double the event past the cap.+ msg_content.pop("format", None)+ msg_content.pop("formatted_body", None)+ room = _MAX_CONTENT_BYTES - _content_bytes({**msg_content, "body": ""})+ # JSON escaping grows a character at most sixfold (\u00XX).+ fallback = formatted.encode("utf-8")[: max(0, room // 6)].decode("utf-8", "ignore")+ msg_content["body"] = f"* {fallback}…"return await self._send_content_event(chat_id, msg_content)async def send_image(@@ -2862,6 +2889,9 @@ class MatrixAdapter(BasePlatformAdapter):if html and html != text:msg_content["format"] = "org.matrix.custom.html"msg_content["formatted_body"] = html+ if _content_bytes(msg_content) > _MAX_CONTENT_BYTES:+ # Escape-heavy text can outgrow the budget as HTML; send it as plain text instead.+ del msg_content["format"], msg_content["formatted_body"]return msg_contentdef _apply_relation_metadata(@@ -3096,36 +3126,51 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_ftoken = getattr(pconfig, "token", None) or get_secret("MATRIX_ACCESS_TOKEN", "") or ""if not homeserver or not token:return send_error("Matrix not configured (MATRIX_HOMESERVER, MATRIX_ACCESS_TOKEN required)")- txn_id = f"hermes_{int(time.time() * 1000)}_{os.urandom(4).hex()}"from urllib.parse import quote- url = f"{homeserver}/_matrix/client/v3/rooms/{quote(chat_id, safe='')}/send/m.room.message/{txn_id}"headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}- payload = {"msgtype": "m.text", "body": message}- with suppress(ImportError):- import markdown as _md- tokenized, tex_store = _latex_to_tokens(message)- html = _md.markdown(tokenized, extensions=["fenced_code", "tables"])- payload["format"] = "org.matrix.custom.html"- payload["formatted_body"] = _tokens_to_mx_maths(- re.sub(r"<h[1-6]>(.*?)</h[1-6]>", r"<strong>\1</strong>", html), tex_store)# asyncio.wait_for, not aiohttp.ClientTimeout: cron invokes this via# run_coroutine_threadsafe ("Timeout context manager should be used inside a task").async with aiohttp.ClientSession() as session:- async def _do_send():+ async def _do_send(payload):+ txn_id = f"hermes_{int(time.time() * 1000)}_{os.urandom(4).hex()}"+ url = f"{homeserver}/_matrix/client/v3/rooms/{quote(chat_id, safe='')}/send/m.room.message/{txn_id}"async with session.put(url, headers=headers, json=payload) as resp:if resp.status not in {200, 201}:return send_error(f"Matrix API error ({resp.status}): {await resp.text()}")data = await resp.json()return {"success": True, "platform": "matrix", "chat_id": chat_id,"message_id": data.get("event_id")}- try:- return await asyncio.wait_for(_do_send(), timeout=30)- except asyncio.TimeoutError:- return send_error("Matrix API timeout (30s)")+ result = None+ for payload in _standalone_payloads(message):+ try:+ result = await asyncio.wait_for(_do_send(payload), timeout=30)+ except asyncio.TimeoutError:+ return send_error("Matrix API timeout (30s)")+ if not result.get("success"):+ break+ return resultexcept Exception as e:return send_error(f"Matrix send failed: {e}")+def _standalone_payloads(message: str) -> list[Dict[str, Any]]:+ """One m.room.message content per chunk. The caller chunks on characters, and a chunk of+ non-Latin text can still exceed the homeserver's byte cap, so re-chunk on UTF-8 bytes."""+ payloads = []+ for chunk in BasePlatformAdapter.truncate_message(message, MATRIX_MAX_MESSAGE_LENGTH_CEILING, _utf8_len):+ payload = {"msgtype": "m.text", "body": chunk}+ with suppress(ImportError):+ import markdown as _md+ tokenized, tex_store = _latex_to_tokens(chunk)+ html = _md.markdown(tokenized, extensions=["fenced_code", "tables"])+ formatted = {"format": "org.matrix.custom.html", "formatted_body": _tokens_to_mx_maths(+ re.sub(r"<h[1-6]>(.*?)</h[1-6]>", r"<strong>\1</strong>", html), tex_store)}+ if _content_bytes({**payload, **formatted}) <= _MAX_CONTENT_BYTES:+ payload.update(formatted)+ payloads.append(payload)+ return payloads++def interactive_setup() -> None:"""Interactive credential setup (setup_fn); CLI helpers are lazy-imported."""from hermes_cli.config import get_env_value, remove_env_value, save_env_valuediff --git a/tests/gateway/test_matrix_message_length.py b/tests/gateway/test_matrix_message_length.pyindex 32d203c9d27..b743beb7fce 100644--- a/tests/gateway/test_matrix_message_length.py+++ b/tests/gateway/test_matrix_message_length.py@@ -1,5 +1,10 @@-"""Tests for Matrix outbound message length configuration (#53026)."""+"""Tests for Matrix outbound message length configuration (#53026) and the event byte cap."""+import json+import sys+import types++import pytestfrom gateway.config import PlatformConfig@@ -27,8 +32,100 @@ class TestMatrixMaxMessageLength:assert adapter._SPLIT_THRESHOLD == 11900def test_env_override(self, monkeypatch):- monkeypatch.setenv("MATRIX_MAX_MESSAGE_LENGTH", "20000")+ monkeypatch.setenv("MATRIX_MAX_MESSAGE_LENGTH", "9000")adapter = _make_adapter()- assert adapter.max_message_length == 20000+ assert adapter.max_message_length == 9000+++++# The homeserver rejects an event whose canonical JSON exceeds 65,536 bytes (M_TOO_LARGE). E2EE+# base64-inflates the content by 4/3, and the envelope (ids, hashes, signatures) needs room too.+_EVENT_CAP = 65_536+_TEXTS = {+ "english": "The **quick** brown fox jumps over the *lazy* dog, and `code` too.\n",+ "cyrillic": "Быстрая **коричневая** лиса прыгает через *ленивую* собаку, и `код` тоже.\n",+ "cjk": "敏捷的**棕色**狐狸跳过了*懒惰的*狗,还有`代码`也是。这是一个很长的段落。\n",+ "code": "```html\n<a href=\"x&y\">it's <b><bold></b></a>\n```\n",+}+++def _fits_one_event(content: dict) -> bool:+ size = len(json.dumps(content, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))+ return size * 4 // 3 + 4096 <= _EVENT_CAP+++class TestMatrixEventSize:+ """Every event Matrix builds fits the homeserver's byte cap, whatever the script of the text."""++ @pytest.mark.asyncio+ async def test_sends_and_budget_sized_edits_fit_one_event(self):+ from gateway.platforms.base import SendResult, _custom_unit_to_cp++ adapter = _make_adapter()+ sent, edits = [], []++ async def send_room_message(chat_id, content):+ sent.append(content)+ return "$sent"++ async def send_content_event(chat_id, content):+ edits.append(content)+ return SendResult(success=True, message_id="$edit")++ adapter._send_room_message = send_room_message+ adapter._send_content_event = send_content_event+ chat = "!room:example.org"+ # Stream previews and progress edits stay within the adapter's advertised per-chat budget.+ limit, len_fn = adapter.max_message_length_for_chat(chat), adapter.message_len_fn_for_chat(chat)+ for name, line in _TEXTS.items():+ text = line * (40_000 // len(line))+ assert (await adapter.send(chat, text)).success, name+ preview = text[: _custom_unit_to_cp(text, limit, len_fn)]+ assert (await adapter.edit_message(chat, "$preview", preview)).success, name++ oversized = [len(json.dumps(c, ensure_ascii=False)) for c in sent + edits if not _fits_one_event(c)]+ assert oversized == []+ # Chunking keeps Markdown rendering: an ordinary chunk still carries its HTML.+ assert all("formatted_body" in c for c in sent if "quick" in c["body"])++ @pytest.mark.asyncio+ async def test_standalone_sender_events_fit_one_event(self, monkeypatch):+ from plugins.platforms.matrix.adapter import DEFAULT_MAX_MESSAGE_LENGTH, _standalone_send++ payloads = []++ class _Response:+ status = 200++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return None++ async def json(self):+ return {"event_id": f"$e{len(payloads)}"}++ class _Session:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return None++ def put(self, url, **kwargs):+ payloads.append(kwargs["json"])+ return _Response()+ monkeypatch.setitem(sys.modules, "aiohttp", types.SimpleNamespace(ClientSession=_Session))+ pconfig = PlatformConfig(enabled=True, token="syt_test_token",+ extra={"homeserver": "https://matrix.example.org"})+ for name, line in _TEXTS.items():+ # send_message chunks plugin platforms on characters at the registry's max_message_length.+ text = line * (DEFAULT_MAX_MESSAGE_LENGTH // len(line))+ result = await _standalone_send(pconfig, "!room:example.org", text)+ assert result["success"], (name, result)+ assert payloads+ assert [len(json.dumps(p, ensure_ascii=False)) for p in payloads if not _fits_one_event(p)] == []diff --git a/website/docs/user-guide/messaging/matrix.md b/website/docs/user-guide/messaging/matrix.mdindex a4ba1c86a8b..184929217fe 100644--- a/website/docs/user-guide/messaging/matrix.md+++ b/website/docs/user-guide/messaging/matrix.md@@ -102,7 +102,7 @@ matrix:session_scope: room # auto|room|thread; room is recommended for project roomsauto_thread: true # Auto-create threads for responses (default: true)dm_mention_threads: false # Create thread when @mentioned in DM (default: false)- max_message_length: 16000 # Outbound chunk size in chars (default: 16000, max: 65535)+ max_message_length: 15000 # Outbound chunk size in UTF-8 bytes (default and max: 15000)```Or via environment variables: