Skip to content

The agent that grows with you

refactor(adapters/matrix_group): 9272->6311; matrix dead fetch_history/_send_simple_message/HTMLParser stubs removed, simplex/mattermost/irc one-verb API helpers and send builders

Teknium791417590d6b
diff --git a/plugins/platforms/irc/adapter.py b/plugins/platforms/irc/adapter.py
index 8afce0ff19a..a8534a1fd7c 100644
--- a/plugins/platforms/irc/adapter.py
+++ b/plugins/platforms/irc/adapter.py
@@ -1,9 +1,4 @@
-"""
-IRC Platform Adapter for Hermes Agent.
-
-A plugin-based gateway adapter that connects to an IRC server and relays
-messages to/from the Hermes agent. Zero external dependencies — uses
-Python's stdlib asyncio for the IRC protocol.
+"""IRC Platform Adapter for Hermes Agent — stdlib asyncio only, zero external dependencies.
Configuration in config.yaml::
@@ -28,83 +23,39 @@ Or via environment variables (overrides config.yaml):
"""
import asyncio
+import datetime
+import contextlib
import logging
-import os
import re
import ssl
import time
from typing import Any, Dict, List, Optional
-from agent.secret_scope import UnscopedSecretError as _UnscopedSecretError
-from agent.secret_scope import get_secret as _scoped_get_secret
-
-
-def _get_scoped_secret(name, default=None):
- """Scope-aware credential read with the default-profile startup fallback.
-
- Secondary profiles construct their adapters under a profile secret
- scope -- the scope is authoritative and a scoped miss returns ``default``
- (no cross-profile borrow from ``os.environ``, which may hold another
- profile's value). The DEFAULT profile's adapter constructs and sends
- *unscoped* under multiplexing, where a bare ``get_secret`` would raise
- ``UnscopedSecretError`` and crash this path; there ``os.environ`` is that
- profile's own value, so fall back to it. Same pattern as the Slack
- ``SLACK_APP_TOKEN`` read (#59739) and
- ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
- """
- try:
- val = _scoped_get_secret(name, default)
- except _UnscopedSecretError:
- val = os.getenv(name)
- return val if val is not None else default
+from gateway.platforms._shared import coerce_port, get_scoped_secret as _get_scoped_secret
+from gateway.platforms.base import BasePlatformAdapter, SendResult, MessageEvent, MessageType
+from gateway.config import Platform
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Lazy import: BasePlatformAdapter and friends live in the main repo.
-# We import at function/class level to avoid import errors when the plugin
-# is discovered but the gateway hasn't been fully initialised yet.
-# ---------------------------------------------------------------------------
-
-from gateway.platforms.base import (
- BasePlatformAdapter,
- SendResult,
- MessageEvent,
- MessageType,
-)
-from gateway.config import Platform
+_TRUTHY = {"1", "true", "yes"}
+_EOF = object() # _standalone_send: server closed the connection
-# ---------------------------------------------------------------------------
-# IRC protocol helpers
-# ---------------------------------------------------------------------------
+# ── IRC protocol helpers ─────────────────────────────────────────────────────
def _parse_irc_message(raw: str) -> dict:
- """Parse a raw IRC protocol line into components.
-
- Returns dict with keys: prefix, command, params.
- """
- prefix = ""
- trailing = ""
-
+ """Parse a raw IRC line into ``{"prefix", "command", "params"}``."""
+ prefix, trailing = "", ""
if raw.startswith(":"):
- try:
- prefix, raw = raw[1:].split(" ", 1)
- except ValueError:
- prefix = raw[1:]
- raw = ""
-
+ prefix, _, raw = raw[1:].partition(" ")
if " :" in raw:
raw, trailing = raw.split(" :", 1)
-
parts = raw.split()
- command = parts[0] if parts else ""
params = parts[1:] if len(parts) > 1 else []
if trailing:
params.append(trailing)
-
- return {"prefix": prefix, "command": command, "params": params}
+ return {"prefix": prefix, "command": parts[0] if parts else "", "params": params}
def _extract_nick(prefix: str) -> str:
@@ -112,58 +63,82 @@ def _extract_nick(prefix: str) -> str:
return prefix.split("!")[0] if "!" in prefix else prefix
-# ---------------------------------------------------------------------------
-# IRC Adapter
-# ---------------------------------------------------------------------------
+def _ms_id() -> str:
+ return str(int(time.time() * 1000))
-class IRCAdapter(BasePlatformAdapter):
- """Async IRC adapter implementing the BasePlatformAdapter interface.
- This class is instantiated by the adapter_factory passed to
- register_platform().
- """
+def _env_or_extra(extra: dict, env: str, key: str, default: Any = "") -> Any:
+ """Env var overrides config.yaml ``extra``."""
+ return _get_scoped_secret(env) or extra.get(key, default)
- def __init__(self, config, **kwargs):
- platform = Platform("irc")
- super().__init__(config=config, platform=platform)
- extra = getattr(config, "extra", {}) or {}
+def _server_channel(config) -> tuple:
+ extra = getattr(config, "extra", {}) or {}
+ return _env_or_extra(extra, "IRC_SERVER", "server"), _env_or_extra(extra, "IRC_CHANNEL", "channel")
+
+
+def _chunk_paragraph(paragraph: str, limit: int) -> List[str]:
+ """Split one line into UTF-8 chunks of at most ``limit`` bytes, preferring space boundaries."""
+ chunks: List[str] = []
+ while paragraph:
+ if len(paragraph.encode("utf-8")) <= limit:
+ chunks.append(paragraph)
+ break
+ # Binary search for the largest character prefix that fits within limit
+ low, high, best = 1, len(paragraph), 0
+ while low <= high:
+ mid = (low + high) // 2
+ if len(paragraph[:mid].encode("utf-8")) <= limit:
+ best = mid
+ low = mid + 1
+ else:
+ high = mid - 1
+ split_at = best
+ space = paragraph.rfind(" ", 0, split_at)
+ if space > split_at // 3:
+ split_at = space
+ chunks.append(paragraph[:split_at].rstrip())
+ paragraph = paragraph[split_at:].lstrip()
+ return chunks
- # Connection settings (env vars override config.yaml)
- self.server = _get_scoped_secret("IRC_SERVER") or extra.get("server", "")
- try:
- self.port = int(_get_scoped_secret("IRC_PORT") or extra.get("port", 6697))
- except (ValueError, TypeError):
- self.port = 6697
- self.nickname = _get_scoped_secret("IRC_NICKNAME") or extra.get("nickname", "hermes-bot")
- self.channel = _get_scoped_secret("IRC_CHANNEL") or extra.get("channel", "")
+
+def _privmsg_budget(target: str) -> int:
+ """Payload bytes left in a 510-byte line after ``PRIVMSG <target> :`` and CRLF."""
+ return 510 - (len(f"PRIVMSG {target} :".encode("utf-8")) + 2)
+
+
+def _split_lines(paragraphs, limit: int) -> List[str]:
+ return [chunk for paragraph in paragraphs for chunk in _chunk_paragraph(paragraph, limit)]
+
+
+# ── IRC Adapter ──────────────────────────────────────────────────────────────
+
+class IRCAdapter(BasePlatformAdapter):
+ """Async IRC adapter implementing the BasePlatformAdapter interface."""
+
+ def __init__(self, config, **kwargs):
+ super().__init__(config=config, platform=Platform("irc"))
+ extra = getattr(config, "extra", {}) or {}
+ self.server = _env_or_extra(extra, "IRC_SERVER", "server")
+ self.port = coerce_port(_env_or_extra(extra, "IRC_PORT", "port", 6697), 6697)
+ self.nickname = _env_or_extra(extra, "IRC_NICKNAME", "nickname", "hermes-bot")
+ self.channel = _env_or_extra(extra, "IRC_CHANNEL", "channel")
_use_tls_raw = _get_scoped_secret("IRC_USE_TLS")
- self.use_tls = (
- _use_tls_raw.lower() in {"1", "true", "yes"}
- if _use_tls_raw
- else extra.get("use_tls", True)
- )
- self.server_password = _get_scoped_secret("IRC_SERVER_PASSWORD") or extra.get("server_password", "")
- self.nickserv_password = _get_scoped_secret("IRC_NICKSERV_PASSWORD") or extra.get("nickserv_password", "")
-
- # Auth
+ self.use_tls = _use_tls_raw.lower() in _TRUTHY if _use_tls_raw else extra.get("use_tls", True)
+ self.server_password = _env_or_extra(extra, "IRC_SERVER_PASSWORD", "server_password")
+ self.nickserv_password = _env_or_extra(extra, "IRC_NICKSERV_PASSWORD", "nickserv_password")
self.allowed_users: list = extra.get("allowed_users", [])
# IRC nicks are case-insensitive — normalise for lookups
self._allowed_users_lower: set = {u.lower() for u in self.allowed_users if isinstance(u, str)}
- # IRC limits
max_msg = extra.get("max_message_length")
if max_msg is None:
- try:
+ with contextlib.suppress(Exception):
from gateway.platform_registry import platform_registry
entry = platform_registry.get("irc")
if entry and entry.max_message_length:
max_msg = entry.max_message_length
- except Exception:
- pass
self.max_message_length = int(max_msg or 450)
-
- # Runtime state
self._reader: Optional[asyncio.StreamReader] = None
self._writer: Optional[asyncio.StreamWriter] = None
self._recv_task: Optional[asyncio.Task] = None
@@ -175,22 +150,16 @@ class IRCAdapter(BasePlatformAdapter):
def name(self) -> str:
return "IRC"
- # ── Connection lifecycle ──────────────────────────────────────────────
-
async def connect(self, *, is_reconnect: bool = False) -> bool:
"""Connect to the IRC server, register, and join the channel."""
if not self.server or not self.channel:
logger.error("IRC: server and channel must be configured")
- self._set_fatal_error(
- "config_missing",
- "IRC_SERVER and IRC_CHANNEL must be set",
- retryable=False,
- )
+ self._set_fatal_error("config_missing", "IRC_SERVER and IRC_CHANNEL must be set", retryable=False)
return False
# Prevent two profiles from using the same IRC identity
try:
- from gateway.status import acquire_scoped_lock, release_scoped_lock
+ from gateway.status import acquire_scoped_lock
lock_key = f"{self.server}:{self.nickname}"
if not acquire_scoped_lock("irc", lock_key):
logger.error("IRC: %s@%s already in use by another profile", self.nickname, self.server)
@@ -201,30 +170,21 @@ class IRCAdapter(BasePlatformAdapter):
self._lock_key = None # status module not available (e.g. tests)
try:
- ssl_ctx = None
- if self.use_tls:
- ssl_ctx = ssl.create_default_context()
-
+ ssl_ctx = ssl.create_default_context() if self.use_tls else None
self._reader, self._writer = await asyncio.wait_for(
- asyncio.open_connection(self.server, self.port, ssl=ssl_ctx),
- timeout=30.0,
+ asyncio.open_connection(self.server, self.port, ssl=ssl_ctx), timeout=30.0,
)
except Exception as e:
logger.error("IRC: failed to connect to %s:%s — %s", self.server, self.port, e)
self._set_fatal_error("connect_failed", str(e), retryable=True)
return False
- # IRC registration sequence
if self.server_password:
await self._send_raw(f"PASS {self.server_password}")
await self._send_raw(f"NICK {self.nickname}")
await self._send_raw(f"USER {self.nickname} 0 * :Hermes Agent")
-
- # Start receive loop
self._recv_task = asyncio.create_task(self._receive_loop())
-
- # Wait for registration (001 RPL_WELCOME) with timeout
- try:
+ try: # wait for registration (001 RPL_WELCOME)
await asyncio.wait_for(self._registration_event.wait(), timeout=30.0)
except asyncio.TimeoutError:
logger.error("IRC: registration timed out")
@@ -232,163 +192,79 @@ class IRCAdapter(BasePlatformAdapter):
self._set_fatal_error("registration_timeout", "IRC server did not send RPL_WELCOME", retryable=True)
return False
- # NickServ identification
if self.nickserv_password:
await self._send_raw(f"PRIVMSG NickServ :IDENTIFY {self.nickserv_password}")
await asyncio.sleep(2) # Give NickServ time to process
-
- # Join channel
await self._send_raw(f"JOIN {self.channel}")
-
self._mark_connected()
logger.info("IRC: connected to %s:%s as %s, joined %s", self.server, self.port, self._current_nick, self.channel)
- # Plugin-registered native handlers (ctx.register_platform_handler).
self._wire_plugin_handlers(None)
return True
async def disconnect(self) -> None:
"""Quit and close the connection."""
- # Release the scoped lock so another profile can use this identity
if getattr(self, "_lock_key", None):
- try:
+ with contextlib.suppress(Exception):
from gateway.status import release_scoped_lock
release_scoped_lock("irc", self._lock_key)
- except Exception:
- pass
self._mark_disconnected()
if self._writer and not self._writer.is_closing():
- try:
+ with contextlib.suppress(Exception):
await self._send_raw("QUIT :Hermes Agent shutting down")
await asyncio.sleep(0.5)
- except Exception:
- pass
- try:
+ with contextlib.suppress(Exception):
self._writer.close()
await self._writer.wait_closed()
- except Exception:
- pass
-
if self._recv_task and not self._recv_task.done():
self._recv_task.cancel()
- try:
+ with contextlib.suppress(asyncio.CancelledError):
await self._recv_task
- except asyncio.CancelledError:
- pass
-
self._reader = None
self._writer = None
self._registered = False
self._registration_event.clear()
- # ── Sending ───────────────────────────────────────────────────────────
-
- async def send(
- self,
- chat_id: str,
- content: str,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- ):
+ async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None):
if not self._writer or self._writer.is_closing():
return SendResult(success=False, error="Not connected")
-
- target = chat_id # channel name or nick for DMs
- lines = self._split_message(content, target)
-
- for line in lines:
+ for line in self._split_message(content, chat_id):
try:
- await self._send_raw(f"PRIVMSG {target} :{line}")
- # Basic rate limiting to avoid excess flood
- await asyncio.sleep(0.3)
+ await self._send_raw(f"PRIVMSG {chat_id} :{line}")
+ await asyncio.sleep(0.3) # Basic flood protection
except Exception as e:
return SendResult(success=False, error=str(e))
-
- return SendResult(success=True, message_id=str(int(time.time() * 1000)))
+ return SendResult(success=True, message_id=_ms_id())
async def send_typing(self, chat_id: str, metadata=None) -> None:
"""IRC has no typing indicator — no-op."""
- pass
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
- is_channel = chat_id.startswith("#") or chat_id.startswith("&")
- return {
- "name": chat_id,
- "type": "group" if is_channel else "dm",
- }
-
- # ── Message splitting ─────────────────────────────────────────────────
+ return {"name": chat_id, "type": "group" if chat_id.startswith(("#", "&")) else "dm"}
def _split_message(self, content: str, target: str) -> List[str]:
- """Split a long message into IRC-safe chunks.
-
- IRC has a ~512 byte line limit. After accounting for protocol
- overhead (``PRIVMSG <target> :``), we split content into chunks.
- """
- # Strip markdown formatting that doesn't render in IRC
- content = self._strip_markdown(content)
-
- overhead = len(f"PRIVMSG {target} :".encode("utf-8")) + 2 # +2 for \r\n
- max_bytes = 510 - overhead
- user_limit = self.max_message_length
-
- lines: List[str] = []
- for paragraph in content.split("\n"):
- if not paragraph.strip():
- continue
- while True:
- para_bytes = paragraph.encode("utf-8")
- limit = min(user_limit, max_bytes)
- if len(para_bytes) <= limit:
- if paragraph.strip():
- lines.append(paragraph)
- break
- # Binary search for a safe character boundary <= limit
- low, high = 1, len(paragraph)
- best = 0
- while low <= high:
- mid = (low + high) // 2
- if len(paragraph[:mid].encode("utf-8")) <= limit:
- best = mid
- low = mid + 1
- else:
- high = mid - 1
- split_at = best
- # Prefer a space boundary
- space = paragraph.rfind(" ", 0, split_at)
- if space > split_at // 3:
- split_at = space
- lines.append(paragraph[:split_at].rstrip())
- paragraph = paragraph[split_at:].lstrip()
-
- return lines if lines else [""]
+ """Split a long message into IRC-safe chunks (510-byte line limit minus PRIVMSG overhead)."""
+ paragraphs = [p for p in self._strip_markdown(content).split("\n") if p.strip()]
+ return _split_lines(paragraphs, min(self.max_message_length, _privmsg_budget(target))) or [""]
@staticmethod
def _strip_markdown(text: str) -> str:
"""Convert basic markdown to plain text for IRC."""
- # Bold: **text** or __text__ → text
- text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
+ text = re.sub(r"\*\*(.+?)\*\*", r"\1", text) # bold
text = re.sub(r"__(.+?)__", r"\1", text)
- # Italic: *text* or _text_ → text
- text = re.sub(r"\*(.+?)\*", r"\1", text)
+ text = re.sub(r"\*(.+?)\*", r"\1", text) # italic
text = re.sub(r"(?<!\w)_(.+?)_(?!\w)", r"\1", text)
- # Inline code: `text` → text
- text = re.sub(r"`(.+?)`", r"\1", text)
- # Code blocks: ```...``` → content
- text = re.sub(r"```\w*\n?", "", text)
- # Images: ![alt](url) → url (must come BEFORE links)
- text = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"\2", text)
- # Links: [text](url) → text (url)
- text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", text)
+ text = re.sub(r"`(.+?)`", r"\1", text) # inline code
+ text = re.sub(r"```\w*\n?", "", text) # code fences
+ text = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"\2", text) # images → url (must precede links)
+ text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", text) # links → text (url)
return text
- # ── Raw IRC I/O ──────────────────────────────────────────────────────
-
async def _send_raw(self, line: str) -> None:
"""Send a raw IRC protocol line."""
if not self._writer or self._writer.is_closing():
return
- encoded = (line + "\r\n").encode("utf-8")
- self._writer.write(encoded)
+ self._writer.write((line + "\r\n").encode("utf-8"))
await self._writer.drain()
async def _receive_loop(self) -> None:
@@ -403,8 +279,7 @@ class IRCAdapter(BasePlatformAdapter):
while b"\r\n" in buffer:
line, buffer = buffer.split(b"\r\n", 1)
try:
- decoded = line.decode("utf-8", errors="replace")
- await self._handle_line(decoded)
+ await self._handle_line(line.decode("utf-8", errors="replace"))
except Exception as e:
logger.warning("IRC: error handling line: %s", e)
except asyncio.CancelledError:
@@ -420,32 +295,23 @@ class IRCAdapter(BasePlatformAdapter):
async def _handle_line(self, raw: str) -> None:
"""Dispatch a single IRC protocol line."""
msg = _parse_irc_message(raw)
- command = msg["command"]
- params = msg["params"]
-
- # PING/PONG keepalive
+ command, params = msg["command"], msg["params"]
if command == "PING":
- payload = params[0] if params else ""
- await self._send_raw(f"PONG :{payload}")
+ await self._send_raw(f"PONG :{params[0] if params else ''}")
return
- # RPL_WELCOME (001) — registration complete
- if command == "001":
+ if command == "001": # RPL_WELCOME — registration complete
self._registered = True
self._registration_event.set()
if params:
- # Server may confirm our nick in the first param
- self._current_nick = params[0]
+ self._current_nick = params[0] # server may confirm our nick
return
- # ERR_NICKNAMEINUSE (433) — nick collision during registration
- if command == "433":
- # Retry with incrementing suffix: hermes_, hermes_1, hermes_2...
+ if command == "433": # ERR_NICKNAMEINUSE — retry: hermes_, hermes_1, hermes_2...
base = self.nickname.rstrip("_0123456789")
suffix_match = re.search(r"_(\d+)$", self._current_nick)
if suffix_match:
- next_num = int(suffix_match.group(1)) + 1
- self._current_nick = f"{base}_{next_num}"
+ self._current_nick = f"{base}_{int(suffix_match.group(1)) + 1}"
elif self._current_nick == self.nickname:
self._current_nick = self.nickname + "_"
else:
@@ -453,130 +319,63 @@ class IRCAdapter(BasePlatformAdapter):
await self._send_raw(f"NICK {self._current_nick}")
return
- # PRIVMSG — incoming message (channel or DM)
if command == "PRIVMSG" and len(params) >= 2:
sender_nick = _extract_nick(msg["prefix"])
- target = params[0]
- text = params[1]
-
- # Ignore our own messages
+ target, text = params[0], params[1]
if sender_nick.lower() == self._current_nick.lower():
- return
-
- # CTCP ACTION (/me) — convert to text
+ return # our own message
if text.startswith("\x01ACTION ") and text.endswith("\x01"):
- text = f"* {sender_nick} {text[8:-1]}"
-
- # Ignore other CTCP
+ text = f"* {sender_nick} {text[8:-1]}" # CTCP ACTION (/me)
if text.startswith("\x01"):
- return
-
- # Determine if this is a channel message or DM
- is_channel = target.startswith("#") or target.startswith("&")
- chat_id = target if is_channel else sender_nick
- chat_type = "group" if is_channel else "dm"
-
- # In channels, only respond if addressed (nick: or nick,)
+ return # other CTCP
+ is_channel = target.startswith(("#", "&"))
+ # In channels, only respond if addressed (nick: / nick, / nick )
if is_channel:
- addressed = False
- for prefix in (f"{self._current_nick}:", f"{self._current_nick},",
- f"{self._current_nick} "):
+ for prefix in (f"{self._current_nick}:", f"{self._current_nick},", f"{self._current_nick} "):
if text.lower().startswith(prefix.lower()):
text = text[len(prefix):].strip()
- addressed = True
break
- if not addressed:
- return # Ignore unaddressed channel messages
-
- # Auth check (case-insensitive)
+ else:
+ return
if self._allowed_users_lower and sender_nick.lower() not in self._allowed_users_lower:
logger.debug("IRC: ignoring message from unauthorized user %s", sender_nick)
return
-
- await self._dispatch_message(
- text=text,
- chat_id=chat_id,
- chat_type=chat_type,
- user_id=sender_nick,
- user_name=sender_nick,
- )
+ await self._dispatch_message(text=text, chat_id=target if is_channel else sender_nick,
+ chat_type="group" if is_channel else "dm",
+ user_id=sender_nick, user_name=sender_nick)
# NICK — track our own nick changes
- if command == "NICK" and _extract_nick(msg["prefix"]).lower() == self._current_nick.lower():
- if params:
- self._current_nick = params[0]
-
- async def _dispatch_message(
- self,
- text: str,
- chat_id: str,
- chat_type: str,
- user_id: str,
- user_name: str,
- ) -> None:
+ if command == "NICK" and params and _extract_nick(msg["prefix"]).lower() == self._current_nick.lower():
+ self._current_nick = params[0]
+
+ async def _dispatch_message(self, text: str, chat_id: str, chat_type: str, user_id: str, user_name: str) -> None:
"""Build a MessageEvent and hand it to the base class handler."""
if not self._message_handler:
return
+ source = self.build_source(chat_id=chat_id, chat_name=chat_id, chat_type=chat_type,
+ user_id=user_id, user_name=user_name)
+ await self.handle_message(MessageEvent(text=text, message_type=MessageType.TEXT, source=source,
+ message_id=_ms_id(), timestamp=datetime.datetime.now()))
- source = self.build_source(
- chat_id=chat_id,
- chat_name=chat_id,
- chat_type=chat_type,
- user_id=user_id,
- user_name=user_name,
- )
-
- event = MessageEvent(
- text=text,
- message_type=MessageType.TEXT,
- source=source,
- message_id=str(int(time.time() * 1000)),
- timestamp=__import__("datetime").datetime.now(),
- )
- await self.handle_message(event)
-
-
-# ---------------------------------------------------------------------------
-# Plugin registration
-# ---------------------------------------------------------------------------
+# ── Plugin registration ──────────────────────────────────────────────────────
def check_requirements() -> bool:
- """Check if IRC is configured.
-
- Only requires the server and channel — no external pip packages needed.
- """
- server = _get_scoped_secret("IRC_SERVER", "")
- channel = _get_scoped_secret("IRC_CHANNEL", "")
- # Also accept config.yaml-only configuration (no env vars).
- # The gateway passes PlatformConfig; we just check env for the
- # hermes setup / requirements check path.
- return bool(server and channel)
+ """Check if IRC is configured via env (server + channel; no pip packages needed)."""
+ return bool(_get_scoped_secret("IRC_SERVER", "") and _get_scoped_secret("IRC_CHANNEL", ""))
def validate_config(config) -> bool:
- """Validate that the platform config has enough info to connect."""
- extra = getattr(config, "extra", {}) or {}
- server = _get_scoped_secret("IRC_SERVER") or extra.get("server", "")
- channel = _get_scoped_secret("IRC_CHANNEL") or extra.get("channel", "")
+ """Validate that the platform config (env or config.yaml) has enough info to connect."""
+ server, channel = _server_channel(config)
return bool(server and channel)
def interactive_setup() -> None:
- """Interactive `hermes gateway setup` flow for the IRC platform.
-
- Lazy-imports ``hermes_cli.setup`` helpers so the plugin stays importable
- in non-CLI contexts (gateway runtime, tests).
- """
+ """Interactive `hermes gateway setup` flow (lazy-imports hermes_cli so the plugin imports in non-CLI contexts)."""
from hermes_cli.setup import (
- prompt,
- prompt_yes_no,
- save_env_value,
- get_env_value,
- print_header,
- print_info,
- print_warning,
- print_success,
+ prompt, prompt_yes_no, save_env_value, get_env_value,
+ print_header, print_info, print_warning, print_success,
)
print_header("IRC")
@@ -590,11 +389,16 @@ def interactive_setup() -> None:
print_info(" Works with Libera.Chat, OFTC, your own ZNC/InspIRCd, etc.")
print()
- server = prompt("IRC server hostname (e.g. irc.libera.chat)", default=existing_server or "")
- if not server:
- print_warning("Server is required — skipping IRC setup")
+ def _required(label: str, env: str, default: str, what: str) -> bool:
+ value = prompt(label, default=default)
+ if not value:
+ print_warning(f"{what} is required — skipping IRC setup")
+ return False
+ save_env_value(env, value.strip())
+ return True
+
+ if not _required("IRC server hostname (e.g. irc.libera.chat)", "IRC_SERVER", existing_server or "", "Server"):
return
- save_env_value("IRC_SERVER", server.strip())
use_tls = prompt_yes_no("Use TLS (recommended)?", True)
save_env_value("IRC_USE_TLS", "true" if use_tls else "false")
@@ -607,56 +411,39 @@ def interactive_setup() -> None:
except ValueError:
print_warning(f"Invalid port — using default {default_port}")
elif get_env_value("IRC_PORT"):
- # User cleared the prompt; drop the override so the default applies.
- save_env_value("IRC_PORT", "")
+ save_env_value("IRC_PORT", "") # user cleared the prompt; drop the override
- nickname = prompt(
- "Bot nickname (e.g. hermes-bot)",
- default=get_env_value("IRC_NICKNAME") or "",
- )
- if not nickname:
- print_warning("Nickname is required — skipping IRC setup")
+ if not _required("Bot nickname (e.g. hermes-bot)", "IRC_NICKNAME", get_env_value("IRC_NICKNAME") or "", "Nickname"):
return
- save_env_value("IRC_NICKNAME", nickname.strip())
-
- channel = prompt(
- "Channel to join (e.g. #hermes — comma-separate for multiple)",
- default=get_env_value("IRC_CHANNEL") or "",
- )
- if not channel:
- print_warning("Channel is required — skipping IRC setup")
+ if not _required("Channel to join (e.g. #hermes — comma-separate for multiple)", "IRC_CHANNEL",
+ get_env_value("IRC_CHANNEL") or "", "Channel"):
return
- save_env_value("IRC_CHANNEL", channel.strip())
print()
print_info("🔑 Optional authentication")
print_info(" Leave blank to skip.")
- if prompt_yes_no("Configure a server password (PASS command)?", False):
- server_password = prompt("Server password", password=True)
- if server_password:
- save_env_value("IRC_SERVER_PASSWORD", server_password)
-
- if prompt_yes_no("Identify with NickServ on connect?", False):
- nickserv = prompt("NickServ password", password=True)
- if nickserv:
- save_env_value("IRC_NICKSERV_PASSWORD", nickserv)
+ for question, label, env in (
+ ("Configure a server password (PASS command)?", "Server password", "IRC_SERVER_PASSWORD"),
+ ("Identify with NickServ on connect?", "NickServ password", "IRC_NICKSERV_PASSWORD"),
+ ):
+ if prompt_yes_no(question, False):
+ secret = prompt(label, password=True)
+ if secret:
+ save_env_value(env, secret)
print()
print_info("🔒 Access control: restrict who can message the bot")
print_info(" IRC nicks are not authenticated — anyone can claim any nick.")
print_info(" For public channels, pair with NickServ-only mode on your network")
print_info(" if you want stronger identity guarantees.")
- allow_all = prompt_yes_no("Allow all users in the channel to talk to the bot?", False)
- if allow_all:
+ if prompt_yes_no("Allow all users in the channel to talk to the bot?", False):
save_env_value("IRC_ALLOW_ALL_USERS", "true")
save_env_value("IRC_ALLOWED_USERS", "")
print_warning("⚠️ Open access — any nick in the channel can command the bot.")
else:
save_env_value("IRC_ALLOW_ALL_USERS", "false")
- allowed = prompt(
- "Allowed nicks (comma-separated, leave empty to deny everyone)",
- default=get_env_value("IRC_ALLOWED_USERS") or "",
- )
+ allowed = prompt("Allowed nicks (comma-separated, leave empty to deny everyone)",
+ default=get_env_value("IRC_ALLOWED_USERS") or "")
if allowed:
save_env_value("IRC_ALLOWED_USERS", allowed.replace(" ", ""))
print_success("Allowlist configured")
@@ -671,71 +458,39 @@ def interactive_setup() -> None:
def is_connected(config) -> bool:
"""Check whether IRC is configured (env or config.yaml)."""
- extra = getattr(config, "extra", {}) or {}
- server = _get_scoped_secret("IRC_SERVER") or extra.get("server", "")
- channel = _get_scoped_secret("IRC_CHANNEL") or extra.get("channel", "")
- return bool(server and channel)
+ return validate_config(config)
def _env_enablement() -> dict | None:
- """Seed ``PlatformConfig.extra`` from env vars during gateway config load.
+ """Seed ``PlatformConfig.extra`` from env vars BEFORE adapter construction.
- Called by the platform registry's env-enablement hook (landed in the
- generic-plugin-interface migration) BEFORE adapter construction, so
- ``gateway status`` and ``get_connected_platforms()`` reflect env-only
- configuration without instantiating the IRC client. Returns ``None``
- when IRC isn't minimally configured; the caller skips auto-enabling.
-
- The special ``home_channel`` key in the returned dict is handled by
- the core hook — it becomes a proper ``HomeChannel`` dataclass on the
- ``PlatformConfig`` rather than being merged into ``extra``.
+ Returns ``None`` when IRC isn't minimally configured (caller skips auto-enabling).
+ The special ``home_channel`` key becomes a ``HomeChannel`` on the PlatformConfig.
"""
server = _get_scoped_secret("IRC_SERVER", "").strip()
channel = _get_scoped_secret("IRC_CHANNEL", "").strip()
if not (server and channel):
return None
- seed: dict = {
- "server": server,
- "channel": channel,
- }
- port = _get_scoped_secret("IRC_PORT", "").strip()
- if port:
- try:
+ seed: dict = {"server": server, "channel": channel}
+ if port := _get_scoped_secret("IRC_PORT", "").strip():
+ with contextlib.suppress(ValueError):
seed["port"] = int(port)
- except ValueError:
- pass
- nickname = _get_scoped_secret("IRC_NICKNAME", "").strip()
- if nickname:
+ if nickname := _get_scoped_secret("IRC_NICKNAME", "").strip():
seed["nickname"] = nickname
- use_tls = _get_scoped_secret("IRC_USE_TLS", "").strip().lower()
- if use_tls:
- seed["use_tls"] = use_tls in {"1", "true", "yes"}
- # Passwords live in PlatformConfig.extra as well for back-compat with
- # existing config.yaml users; env-reads at construct time still win.
- if _get_scoped_secret("IRC_SERVER_PASSWORD"):
- seed["server_password"] = _get_scoped_secret("IRC_SERVER_PASSWORD")
- if _get_scoped_secret("IRC_NICKSERV_PASSWORD"):
- seed["nickserv_password"] = _get_scoped_secret("IRC_NICKSERV_PASSWORD")
- # Optional home-channel (usually the same as IRC_CHANNEL, but can be a
- # dedicated reports channel). Defaults to IRC_CHANNEL so cron jobs
- # with ``deliver=irc`` have a sensible target without extra config.
- home = _get_scoped_secret("IRC_HOME_CHANNEL") or channel
- if home:
- seed["home_channel"] = {
- "chat_id": home,
- "name": _get_scoped_secret("IRC_HOME_CHANNEL_NAME", home),
- }
+ if use_tls := _get_scoped_secret("IRC_USE_TLS", "").strip().lower():
+ seed["use_tls"] = use_tls in _TRUTHY
+ # Passwords also live in extra for back-compat with config.yaml users; env wins at construct time.
+ for env, key in (("IRC_SERVER_PASSWORD", "server_password"), ("IRC_NICKSERV_PASSWORD", "nickserv_password")):
+ if _get_scoped_secret(env):
+ seed[key] = _get_scoped_secret(env)
+ # Home channel defaults to IRC_CHANNEL so cron ``deliver=irc`` has a target without extra config.
+ if home := _get_scoped_secret("IRC_HOME_CHANNEL") or channel:
+ seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("IRC_HOME_CHANNEL_NAME", home)}
return seed
def _strip_irc_control_chars(text: str) -> str:
- """Strip IRC line terminators and the NUL byte from ``text``.
-
- IRC commands are CRLF-delimited; a bare ``\\r`` or ``\\n`` in user
- content lets an attacker inject arbitrary IRC commands (CTCP, JOIN,
- KICK). ``\\x00`` is a protocol-illegal byte. Everything else is
- valid in PRIVMSG payloads.
- """
+ """Neutralise CR/LF (IRC command injection vector) and the protocol-illegal NUL byte."""
return text.replace("\r", " ").replace("\n", " ").replace("\x00", "")
@@ -743,75 +498,39 @@ def _is_irc_channel(target: str) -> bool:
return bool(target) and target[0] in "#&+!"
-async def _standalone_send(
- pconfig,
- chat_id: str,
- message: str,
- *,
- thread_id: Optional[str] = None,
- media_files: Optional[List[str]] = None,
- force_document: bool = False,
-) -> Dict[str, Any]:
- """Open an ephemeral IRC connection, send a PRIVMSG, and quit.
-
- Used by ``tools/send_message_tool._send_via_adapter`` when the gateway
- runner is not in this process (e.g. ``hermes cron`` running as a
- separate process from ``hermes gateway``). Without this hook,
- ``deliver=irc`` cron jobs fail with ``No live adapter for platform``.
-
- The standalone client uses a distinct nick suffix (``-cron``) so it
- does not collide with the long-running gateway adapter that may already
- be holding the configured nickname on the same network. When the
- target is a channel, the client JOINs it before sending PRIVMSG so
- networks with the default ``+n`` (no external messages) channel mode
- accept the delivery.
-
- ``thread_id`` and ``media_files`` are accepted for signature parity but
- are not meaningful on IRC: IRC has no native thread or attachment
- primitive.
+async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Optional[str] = None,
+ media_files: Optional[List[str]] = None, force_document: bool = False) -> Dict[str, Any]:
+ """Open an ephemeral IRC connection, send a PRIVMSG, and quit (out-of-process cron delivery).
+
+ Used by ``tools/send_message_tool._send_via_adapter`` when the gateway isn't in this process.
+ Uses a distinct ``-cron`` nick so it never collides with the live gateway adapter.
+ ``thread_id``/``media_files`` are accepted for signature parity only.
"""
extra = getattr(pconfig, "extra", {}) or {}
- server = _get_scoped_secret("IRC_SERVER") or extra.get("server", "")
- channel = _get_scoped_secret("IRC_CHANNEL") or extra.get("channel", "")
+ server, channel = _server_channel(pconfig)
if not server or not channel:
return {"error": "IRC standalone send: IRC_SERVER and IRC_CHANNEL must be configured"}
-
- port_value = _get_scoped_secret("IRC_PORT") or extra.get("port", 6697)
+ port_value = _env_or_extra(extra, "IRC_PORT", "port", 6697)
try:
port = int(port_value)
except (TypeError, ValueError):
return {"error": f"IRC standalone send: invalid port {port_value!r}"}
-
- nickname = _get_scoped_secret("IRC_NICKNAME") or extra.get("nickname", "hermes-bot")
+ nickname = _env_or_extra(extra, "IRC_NICKNAME", "nickname", "hermes-bot")
use_tls_env = _get_scoped_secret("IRC_USE_TLS")
- if use_tls_env is not None:
- use_tls = use_tls_env.lower() in {"1", "true", "yes"}
- else:
- use_tls = bool(extra.get("use_tls", True))
-
- server_password = _get_scoped_secret("IRC_SERVER_PASSWORD") or extra.get("server_password", "")
- nickserv_password = _get_scoped_secret("IRC_NICKSERV_PASSWORD") or extra.get("nickserv_password", "")
-
+ use_tls = use_tls_env.lower() in _TRUTHY if use_tls_env is not None else bool(extra.get("use_tls", True))
+ server_password = _env_or_extra(extra, "IRC_SERVER_PASSWORD", "server_password")
+ nickserv_password = _env_or_extra(extra, "IRC_NICKSERV_PASSWORD", "nickserv_password")
# Reject control characters in chat_id to block IRC command injection.
- raw_target = chat_id or channel
- if any(ch in raw_target for ch in ("\r", "\n", "\x00", " ")):
+ target = chat_id or channel
+ if any(ch in target for ch in ("\r", "\n", "\x00", " ")):
return {"error": "IRC standalone send: chat_id contains illegal IRC characters"}
- target = raw_target
-
- # Distinct nick prevents NICK collision with a live gateway adapter
- # that may already be holding the configured nickname. Cap to 24 chars
- # so subsequent collision retries do not overflow the 30-char NICKLEN
- # most networks enforce.
+ # Cap the base to 24 chars so collision retries stay within the 30-char NICKLEN most networks enforce.
nick_base = nickname.rstrip("_0123456789-")[:24] or "hermes-bot"
standalone_nick = f"{nick_base}-cron"[:30]
plain = IRCAdapter._strip_markdown(message)
-
ssl_ctx = ssl.create_default_context() if use_tls else None
try:
- reader, writer = await asyncio.wait_for(
- asyncio.open_connection(server, port, ssl=ssl_ctx),
- timeout=15.0,
- )
+ reader, writer = await asyncio.wait_for(asyncio.open_connection(server, port, ssl=ssl_ctx), timeout=15.0)
except asyncio.CancelledError:
raise
except Exception as e:
@@ -821,136 +540,93 @@ async def _standalone_send(
writer.write((line + "\r\n").encode("utf-8"))
await writer.drain()
- nick_attempts = 0
- max_nick_attempts = 5
- try:
- if server_password:
- await _raw(f"PASS {_strip_irc_control_chars(server_password)}")
- await _raw(f"NICK {standalone_nick}")
- await _raw(f"USER {standalone_nick} 0 * :Hermes Agent (cron)")
+ loop = asyncio.get_running_loop()
- loop = asyncio.get_running_loop()
- deadline = loop.time() + 15.0
- registered = False
- while not registered:
+ async def _pump(deadline: float, on_msg):
+ """Feed lines to ``on_msg`` until it returns non-None; answers PINGs. None on timeout/EOF."""
+ while True:
remaining = deadline - loop.time()
if remaining <= 0:
- return {"error": "IRC standalone send: registration timeout (no RPL_WELCOME)"}
+ return None
try:
raw_line = await asyncio.wait_for(reader.readuntil(b"\r\n"), timeout=remaining)
except asyncio.TimeoutError:
- return {"error": "IRC standalone send: registration timeout (no RPL_WELCOME)"}
+ return None
except asyncio.IncompleteReadError:
- return {"error": "IRC standalone send: server closed connection during registration"}
- decoded = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
- msg = _parse_irc_message(decoded)
- cmd = msg["command"]
- if cmd == "PING":
- payload = msg["params"][0] if msg["params"] else ""
- await _raw(f"PONG :{payload}")
- elif cmd == "001":
- registered = True
- elif cmd in {"432", "433"}:
- nick_attempts += 1
- if nick_attempts > max_nick_attempts:
- return {"error": "IRC standalone send: too many nick collisions"}
- # Build the next nick from the stable base, not the
- # mutated value, so the suffix stays bounded.
- standalone_nick = f"{nick_base}-cron-{nick_attempts}"[:30]
- await _raw(f"NICK {standalone_nick}")
- elif cmd in {"464", "465"}:
- return {"error": f"IRC standalone send: server rejected client ({cmd})"}
+ return _EOF
+ msg = _parse_irc_message(raw_line.decode("utf-8", errors="replace").rstrip("\r\n"))
+ if msg["command"] == "PING":
+ await _raw(f"PONG :{msg['params'][0] if msg['params'] else ''}")
+ continue
+ result = await on_msg(msg["command"])
+ if result is not None:
+ return result
+
+ nick_attempts = 0
+ async def _on_registration(cmd: str):
+ nonlocal nick_attempts, standalone_nick
+ if cmd in {"432", "433"}:
+ nick_attempts += 1
+ if nick_attempts > 5:
+ return {"error": "IRC standalone send: too many nick collisions"}
+ # Build from the stable base, not the mutated nick, so the suffix stays bounded.
+ standalone_nick = f"{nick_base}-cron-{nick_attempts}"[:30]
+ await _raw(f"NICK {standalone_nick}")
+ elif cmd in {"464", "465"}:
+ return {"error": f"IRC standalone send: server rejected client ({cmd})"}
+ return True if cmd == "001" else None
+
+ async def _on_join(cmd: str):
+ if cmd in {"403", "405", "471", "473", "474", "475"}:
+ return {"error": f"IRC standalone send: JOIN {target} rejected ({cmd})"}
+ return True if cmd in {"366", "JOIN"} else None
+
+ try:
+ if server_password:
+ await _raw(f"PASS {_strip_irc_control_chars(server_password)}")
+ await _raw(f"NICK {standalone_nick}")
+ await _raw(f"USER {standalone_nick} 0 * :Hermes Agent (cron)")
+ registered = await _pump(loop.time() + 15.0, _on_registration)
+ if registered is None:
+ return {"error": "IRC standalone send: registration timeout (no RPL_WELCOME)"}
+ if registered is _EOF:
+ return {"error": "IRC standalone send: server closed connection during registration"}
+ if registered is not True:
+ return registered
if nickserv_password:
await _raw(f"PRIVMSG NickServ :IDENTIFY {_strip_irc_control_chars(nickserv_password)}")
await asyncio.sleep(2)
-
- # JOIN before PRIVMSG. IRC channels with the default ``+n`` mode
- # (no external messages: Libera, OFTC, EFnet, IRCNet, undernet)
- # silently drop PRIVMSG from non-members. Do not JOIN bare nicks
- # (DM target) or server queries.
+ # JOIN before PRIVMSG: ``+n`` channels silently drop PRIVMSG from non-members.
+ # Do not JOIN bare nicks (DM target) or server queries.
if _is_irc_channel(target):
await _raw(f"JOIN {target}")
- join_deadline = loop.time() + 5.0
- joined = False
- while not joined:
- remaining = join_deadline - loop.time()
- if remaining <= 0:
- # Timed out waiting for a JOIN ack: proceed anyway, the
- # server may still deliver the PRIVMSG depending on mode.
- break
- try:
- raw_line = await asyncio.wait_for(reader.readuntil(b"\r\n"), timeout=remaining)
- except (asyncio.TimeoutError, asyncio.IncompleteReadError):
- break
- decoded = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
- jmsg = _parse_irc_message(decoded)
- jcmd = jmsg["command"]
- if jcmd == "PING":
- payload = jmsg["params"][0] if jmsg["params"] else ""
- await _raw(f"PONG :{payload}")
- elif jcmd in {"366", "JOIN"}:
- joined = True
- elif jcmd in {"403", "405", "471", "473", "474", "475"}:
- return {"error": f"IRC standalone send: JOIN {target} rejected ({jcmd})"}
-
- # Bytes-aware per-line splitting so multi-line plain text never
- # exceeds the IRC 510-byte protocol limit. Reuses the same
- # algorithm as IRCAdapter._split_message, with control-character
- # stripping per line to block CRLF injection from message content.
- overhead = len(f"PRIVMSG {target} :".encode("utf-8")) + 2
- max_bytes = 510 - overhead
- sent_any = False
- for paragraph in plain.split("\n"):
- paragraph = _strip_irc_control_chars(paragraph).rstrip()
- if not paragraph:
- continue
- while paragraph:
- encoded = paragraph.encode("utf-8")
- if len(encoded) <= max_bytes:
- await _raw(f"PRIVMSG {target} :{paragraph}")
- await asyncio.sleep(0.3)
- sent_any = True
- break
- # Binary search for largest prefix that fits within max_bytes
- low, high, best = 1, len(paragraph), 0
- while low <= high:
- mid = (low + high) // 2
- if len(paragraph[:mid].encode("utf-8")) <= max_bytes:
- best = mid
- low = mid + 1
- else:
- high = mid - 1
- split_at = best
- space = paragraph.rfind(" ", 0, split_at)
- if space > split_at // 3:
- split_at = space
- await _raw(f"PRIVMSG {target} :{paragraph[:split_at].rstrip()}")
- await asyncio.sleep(0.3)
- sent_any = True
- paragraph = paragraph[split_at:].lstrip()
-
- if not sent_any:
+ # No JOIN ack within 5s (or EOF): proceed anyway, the server may still deliver.
+ joined = await _pump(loop.time() + 5.0, _on_join)
+ if isinstance(joined, dict):
+ return joined
+ # Bytes-aware per-line splitting (same algorithm as IRCAdapter._split_message),
+ # with control-character stripping per line to block CRLF injection from content.
+ paragraphs = [q for q in (_strip_irc_control_chars(p).rstrip() for p in plain.split("\n")) if q]
+ lines = _split_lines(paragraphs, _privmsg_budget(target))
+ for line in lines:
+ await _raw(f"PRIVMSG {target} :{line}")
+ await asyncio.sleep(0.3)
+ if not lines:
return {"error": "IRC standalone send: empty message after stripping"}
-
await _raw("QUIT :delivered")
- try:
+ with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(reader.read(1024), timeout=2.0)
- except asyncio.TimeoutError:
- pass
-
- return {"success": True, "message_id": str(int(time.time() * 1000))}
+ return {"success": True, "message_id": _ms_id()}
except asyncio.CancelledError:
raise
except Exception as e:
logger.debug("IRC standalone send raised", exc_info=True)
return {"error": f"IRC standalone send failed: {e}"}
finally:
- try:
+ with contextlib.suppress(Exception):
writer.close()
await asyncio.wait_for(writer.wait_closed(), timeout=5.0)
- except (asyncio.TimeoutError, Exception):
- pass
def register(ctx):
@@ -965,29 +641,15 @@ def register(ctx):
required_env=["IRC_SERVER", "IRC_CHANNEL", "IRC_NICKNAME"],
install_hint="No extra packages needed (stdlib only)",
setup_fn=interactive_setup,
- # Env-driven auto-configuration: seeds PlatformConfig.extra with
- # server/channel/port/tls + home_channel so env-only setups show
- # up in gateway status without instantiating the adapter.
- env_enablement_fn=_env_enablement,
- # Cron home-channel delivery support. IRC_HOME_CHANNEL defaults to
- # IRC_CHANNEL (see _env_enablement), so cron jobs with
- # deliver=irc route to the joined channel by default.
- cron_deliver_env_var="IRC_HOME_CHANNEL",
- # Out-of-process cron delivery. Without this hook, deliver=irc
- # cron jobs fail with "No live adapter" when cron runs separately
- # from the gateway.
- standalone_sender_fn=_standalone_send,
- # Auth env vars for _is_user_authorized() integration
+ env_enablement_fn=_env_enablement, # env-only setups show in gateway status
+ cron_deliver_env_var="IRC_HOME_CHANNEL", # defaults to IRC_CHANNEL (see _env_enablement)
+ standalone_sender_fn=_standalone_send, # cron running separately from the gateway
allowed_users_env="IRC_ALLOWED_USERS",
allow_all_env="IRC_ALLOW_ALL_USERS",
- # IRC line limit after protocol overhead
- max_message_length=450,
- # Display
+ max_message_length=450, # IRC line limit after protocol overhead
emoji="💬",
- # IRC doesn't have phone numbers to redact
- pii_safe=False,
+ pii_safe=False, # IRC doesn't have phone numbers to redact
allow_update_command=True,
- # LLM guidance
platform_hint=(
"You are chatting via IRC. IRC does not support markdown formatting "
"— use plain text only. Messages are limited to ~450 characters per "
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 6a2eb362ff5..1f32d4a1060 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -74,69 +74,31 @@ from agent.secret_scope import UnscopedSecretError, get_secret
try:
from mautrix.types import (
- ContentURI,
- EventID,
- EventType,
- PaginationDirection,
- PresenceState,
- RoomCreatePreset,
- RoomID,
- SyncToken,
- TrustState,
- UserID,
+ ContentURI, EventID, EventType, PresenceState, RoomCreatePreset, RoomID, TrustState, UserID,
)
except ImportError:
# Stubs so the module is importable without mautrix installed.
# check_matrix_requirements() will return False and the adapter
# won't be instantiated in production, but tests may exercise
# adapter methods so stubs must have the right attributes.
- ContentURI = EventID = RoomID = SyncToken = UserID = str # type: ignore[misc,assignment]
-
- class _EventTypeStub: # type: ignore[no-redef]
- ROOM_MESSAGE = "m.room.message"
- REACTION = "m.reaction"
- ROOM_ENCRYPTED = "m.room.encrypted"
- ROOM_NAME = "m.room.name"
-
- EventType = _EventTypeStub # type: ignore[misc,assignment]
-
- class _PaginationDirectionStub: # type: ignore[no-redef]
- BACKWARD = "b"
- FORWARD = "f"
-
- PaginationDirection = _PaginationDirectionStub # type: ignore[misc,assignment]
-
- class _PresenceStateStub: # type: ignore[no-redef]
- ONLINE = "online"
- OFFLINE = "offline"
- UNAVAILABLE = "unavailable"
-
- PresenceState = _PresenceStateStub # type: ignore[misc,assignment]
-
- class _RoomCreatePresetStub: # type: ignore[no-redef]
- PRIVATE = "private_chat"
- PUBLIC = "public_chat"
- TRUSTED_PRIVATE = "trusted_private_chat"
-
- RoomCreatePreset = _RoomCreatePresetStub # type: ignore[misc,assignment]
-
- class _TrustStateStub: # type: ignore[no-redef]
- UNVERIFIED = 0
- VERIFIED = 1
-
- TrustState = _TrustStateStub # type: ignore[misc,assignment]
+ ContentURI = EventID = RoomID = UserID = str # type: ignore[misc,assignment]
+
+ EventType = type("_EventTypeStub", (), { # type: ignore[misc,assignment]
+ "ROOM_MESSAGE": "m.room.message", "REACTION": "m.reaction",
+ "ROOM_ENCRYPTED": "m.room.encrypted", "ROOM_NAME": "m.room.name",
+ })
+ PresenceState = type("_PresenceStateStub", (), { # type: ignore[misc,assignment]
+ "ONLINE": "online", "OFFLINE": "offline", "UNAVAILABLE": "unavailable",
+ })
+ RoomCreatePreset = type("_RoomCreatePresetStub", (), { # type: ignore[misc,assignment]
+ "PRIVATE": "private_chat", "PUBLIC": "public_chat", "TRUSTED_PRIVATE": "trusted_private_chat",
+ })
+ TrustState = type("_TrustStateStub", (), {"UNVERIFIED": 0, "VERIFIED": 1}) # type: ignore[misc,assignment]
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
- gateway_trust_env,
- BasePlatformAdapter,
- MessageEvent,
- MessageType,
- ProcessingOutcome,
- SendResult,
- resolve_proxy_url,
- proxy_kwargs_for_aiohttp,
- _ssrf_redirect_guard,
+ gateway_trust_env, BasePlatformAdapter, MessageEvent, MessageType, ProcessingOutcome,
+ SendResult, resolve_proxy_url, proxy_kwargs_for_aiohttp, _ssrf_redirect_guard,
)
from gateway.platforms.helpers import ThreadParticipationTracker
@@ -145,35 +107,21 @@ logger = logging.getLogger(__name__)
_MATRIX_VOICE_WAVEFORM_BINS = 30
-def _matrix_voice_metadata_for_file(path: Path) -> Dict[str, Any]:
- """Return best-effort Matrix voice metadata for an audio file.
+def _run_media_tool(cmd: list, *, timeout: int, text: bool = False):
+ """Run ffmpeg/ffprobe with captured output and no stdin."""
+ return subprocess.run(cmd, capture_output=True, text=text, timeout=timeout, stdin=subprocess.DEVNULL)
- Matrix clients such as Element render ``m.audio`` events with
- ``org.matrix.msc3245.voice`` as voice bubbles. They are more reliable when
- the event also includes duration and MSC1767 waveform metadata. Metadata
- extraction is deliberately best-effort: media delivery must still work on
- systems without ffprobe/ffmpeg.
- """
- metadata: Dict[str, Any] = {}
+def _matrix_voice_metadata_for_file(path: Path) -> Dict[str, Any]:
+ """Best-effort duration + MSC1767 waveform for voice bubbles; must work without ffprobe/ffmpeg."""
+ metadata: Dict[str, Any] = {}
ffprobe = shutil.which("ffprobe")
if ffprobe:
try:
- result = subprocess.run(
- [
- ffprobe,
- "-v",
- "error",
- "-show_entries",
- "format=duration",
- "-of",
- "default=noprint_wrappers=1:nokey=1",
- str(path),
- ],
- capture_output=True,
- text=True,
- timeout=10,
- stdin=subprocess.DEVNULL,
+ result = _run_media_tool(
+ [ffprobe, "-v", "error", "-show_entries", "format=duration", "-of",
+ "default=noprint_wrappers=1:nokey=1", str(path)],
+ timeout=10, text=True,
)
if result.returncode == 0:
duration = float((result.stdout or "").strip() or 0)
@@ -181,28 +129,12 @@ def _matrix_voice_metadata_for_file(path: Path) -> Dict[str, Any]:
metadata["duration"] = int(duration * 1000)
except Exception:
logger.debug("Matrix: failed to probe voice duration for %s", path, exc_info=True)
-
ffmpeg = shutil.which("ffmpeg")
if ffmpeg:
try:
- result = subprocess.run(
- [
- ffmpeg,
- "-v",
- "error",
- "-i",
- str(path),
- "-ac",
- "1",
- "-ar",
- "8000",
- "-f",
- "s16le",
- "-",
- ],
- capture_output=True,
+ result = _run_media_tool(
+ [ffmpeg, "-v", "error", "-i", str(path), "-ac", "1", "-ar", "8000", "-f", "s16le", "-"],
timeout=15,
- stdin=subprocess.DEVNULL,
)
if result.returncode == 0 and result.stdout:
samples = array.array("h")
@@ -220,50 +152,24 @@ def _matrix_voice_metadata_for_file(path: Path) -> Dict[str, Any]:
metadata["waveform"] = waveform
except Exception:
logger.debug("Matrix: failed to build voice waveform for %s", path, exc_info=True)
-
return metadata
def _matrix_transcode_voice_to_ogg(path: str) -> Optional[str]:
- """Best-effort transcode of an audio file to Ogg/Opus for MSC3245 delivery.
+ """Transcode to a NEW temp .ogg (caller owns cleanup); None if ffmpeg is missing/fails.
- Returns the path of a NEW temporary ``.ogg`` file (caller owns cleanup), or
- ``None`` when ffmpeg is unavailable or fails — callers then send the
- original file, matching the adapter's previous behaviour. Runs blocking
- subprocess work; call via ``asyncio.to_thread`` from async code.
+ Blocking subprocess work — call via ``asyncio.to_thread`` from async code.
"""
ffmpeg = shutil.which("ffmpeg")
if not ffmpeg:
return None
import tempfile
-
fd, ogg_path = tempfile.mkstemp(prefix="matrix_voice_", suffix=".ogg")
os.close(fd)
try:
- result = subprocess.run(
- [
- ffmpeg,
- "-v",
- "error",
- "-y",
- "-i",
- str(path),
- "-acodec",
- "libopus",
- "-ac",
- "1",
- "-b:a",
- "48k",
- "-vbr",
- "on",
- "-application",
- "voip",
- "-compression_level",
- "10",
- ogg_path,
- ],
- capture_output=True,
+ result = _run_media_tool(
+ [ffmpeg, "-v", "error", "-y", "-i", str(path), "-acodec", "libopus", "-ac", "1", "-b:a", "48k",
+ "-vbr", "on", "-application", "voip", "-compression_level", "10", ogg_path],
timeout=30,
- stdin=subprocess.DEVNULL,
)
if result.returncode == 0 and os.path.getsize(ogg_path) > 0:
return ogg_path
@@ -276,60 +182,38 @@ def _matrix_transcode_voice_to_ogg(path: str) -> Optional[str]:
return None
-_MATRIX_BANG_COMMAND_RE = re.compile(
- r"^!([A-Za-z][A-Za-z0-9_-]*)(?=$|\s)(.*)$",
- re.DOTALL,
-)
+_MATRIX_BANG_COMMAND_RE = re.compile(r"^!([A-Za-z][A-Za-z0-9_-]*)(?=$|\s)(.*)$", re.DOTALL)
def _resolve_matrix_bang_command(name: str) -> str | None:
- """Resolve a ``!command`` token to a dispatchable Hermes command token.
-
- Matrix clients often reserve leading ``/`` for local client commands.
- Hermes accepts ``!command`` as a Matrix-friendly alias, but only for
- commands that the gateway can actually dispatch so ordinary exclamations
- remain normal chat text.
-
- Returns the token form that actually resolves (which may differ from
- *name* only by underscore→hyphen normalization, e.g. ``reload_skills`` →
- ``reload-skills``) so the emitted ``/command`` always resolves downstream,
- or ``None`` when *name* is not a known command. Aliases are intentionally
- left as-is — the gateway dispatcher resolves them to their canonical name.
+ """Resolve a ``!command`` token (Matrix clients reserve ``/``) to a dispatchable token.
+
+ Only known gateway/skill commands resolve, so ordinary exclamations stay chat text.
+ Returns whichever candidate resolved — raw lowercased first, then the ``_``→``-``
+ variant — never a forced canonical form: aliases pass through for the dispatcher.
"""
if not name:
return None
- # Try the raw lowercased token first, then its hyphenated variant, so
- # forms like ``!reload_skills`` resolve against ``reload-skills``. We emit
- # whichever candidate resolved (not a forced canonical form) to preserve
- # alias passthrough — the gateway dispatcher canonicalizes aliases itself.
candidates = [name.lower()]
hyphenated = name.lower().replace("_", "-")
if hyphenated != candidates[0]:
candidates.append(hyphenated)
-
try:
from hermes_cli.commands import is_gateway_known_command
-
for candidate in candidates:
if is_gateway_known_command(candidate):
return candidate
except Exception:
- logger.debug(
- "Matrix: is_gateway_known_command failed for %r", name, exc_info=True
- )
-
+ logger.debug("Matrix: is_gateway_known_command failed for %r", name, exc_info=True)
try:
from agent.skill_commands import get_skill_commands
-
skill_commands = get_skill_commands() or {}
- # Skill command keys are stored slash-prefixed (e.g. "/arxiv"), so
- # compare against the "/candidate" form, not the bare token.
+ # Skill command keys are slash-prefixed ("/arxiv").
for candidate in candidates:
if f"/{candidate}" in skill_commands:
return candidate
except Exception:
logger.debug("Matrix: get_skill_commands failed for %r", name, exc_info=True)
-
return None
@@ -346,55 +230,32 @@ def _normalize_matrix_bang_command(text: str) -> str:
return f"/{resolved}{match.group(2) or ''}"
-# Matrix reply fallback prefix looks like:
-# > <@alice:example.org> quoted text
-# > continuation of quoted text
-# <empty line>
-# actual reply text
-# Capture the original quoted text and the quoted author's MXID so the
-# gateway prompt layer can render "[Replying to: \"...\"]" with the author
-# attached. Returns (text, author_id) — text is the joined quoted body,
-# author_id is the MXID parsed from the leading "<@user:server>" pill or
-# ``None`` if the fallback uses an unsupported shape.
+# Reply fallback prefix: "> <@alice:example.org> quoted\n> more\n\nactual reply".
_MATRIX_REPLY_FALLBACK_PILL_RE = re.compile(r"^>\s*<(@[^>]+)>\s*(.*)$")
def _extract_reply_fallback(body: str) -> tuple[Optional[str], Optional[str]]:
- """Return (reply_to_text, reply_to_author_id) parsed from a Matrix reply body.
-
- Matrix stores reply text inline as ``> <@user:server> <line>\\n> <line>...``
- followed by a blank line and the actual reply. The first line carries an
- optional ``<@user:server>`` mention pill naming the original author.
- """
+ """Return (quoted_text, author_mxid) from the inline reply fallback; author from the first-line pill."""
if not body or not body.startswith("> "):
return None, None
-
quoted_lines: list[str] = []
author_id: Optional[str] = None
for line in body.split("\n"):
if not line.startswith("> "):
- # Blank line or the start of the actual reply — stop accumulating.
break
content = line[2:]
if author_id is None:
pill_match = _MATRIX_REPLY_FALLBACK_PILL_RE.match(line)
if pill_match:
author_id = pill_match.group(1)
- # Drop the pill from the visible quoted text so "[Replying
- # to: ...]" in the LLM prompt reads naturally.
- content = pill_match.group(2)
+ content = pill_match.group(2) # drop the pill from the visible quote
quoted_lines.append(content)
-
quoted_text = "\n".join(quoted_lines).strip() or None
return quoted_text, author_id
def _strip_reply_fallback(body: str) -> str:
- """Strip Matrix's inline ``> <text>\\n\\n<actual reply>`` fallback prefix.
-
- Returns the body without the quoted lines. If the body doesn't start
- with a reply fallback, returns it unchanged.
- """
+ """Strip the inline ``> quote\\n\\nreply`` fallback prefix; unchanged if absent."""
if not body or not body.startswith("> "):
return body
lines = body.split("\n")
@@ -512,22 +373,13 @@ class MatrixRoomIdentity:
class _MatrixApprovalPrompt:
"""Tracks a pending Matrix reaction-based exec approval prompt."""
- def __init__(
- self,
- session_key: str,
- chat_id: str,
- message_id: str,
- resolved: bool = False,
- requester_user_id: str | None = None,
- expires_at: float | None = None,
- ):
- self.session_key = session_key
- self.chat_id = chat_id
- self.message_id = message_id
- self.resolved = resolved
- self.requester_user_id = requester_user_id
- self.expires_at = expires_at
- self.bot_reaction_events: dict[str, str] = {} # emoji -> event_id
+ session_key: str
+ chat_id: str
+ message_id: str
+ resolved: bool = False
+ requester_user_id: str | None = None
+ expires_at: float | None = None
+ bot_reaction_events: dict[str, str] = field(default_factory=dict, init=False) # emoji -> event_id
@dataclass
@@ -560,9 +412,7 @@ class _MatrixChoicePickerPrompt:
bot_reaction_events: dict[str, str] = field(default_factory=dict)
-# 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).
+# Spec allows ~65 KB events; 4000 was too small (split Markdown tables mid-row).
DEFAULT_MAX_MESSAGE_LENGTH = 16000
MATRIX_MAX_MESSAGE_LENGTH_CEILING = 65535
@@ -576,7 +426,6 @@ def _resolve_max_message_length(config) -> int:
if raw is None:
try:
from gateway.platform_registry import platform_registry
-
entry = platform_registry.get("matrix")
if entry and entry.max_message_length:
raw = entry.max_message_length
@@ -594,20 +443,15 @@ def _resolve_max_message_length(config) -> int:
# Back-compat alias for callers/tests that import the module constant.
MAX_MESSAGE_LENGTH = DEFAULT_MAX_MESSAGE_LENGTH
-# Store directory for E2EE keys and sync state. Resolved per adapter in
-# ``connect()`` (see ``_resolve_store_dir``), NOT at module scope: the
-# multiplex gateway imports this module once, so a module-level constant
-# would pin the root HERMES_HOME for every profile and all bots' Olm
-# identities would collide in one crypto.db (#89168). Mirrors the
-# pairing-store fix (a6397c379).
+# E2EE store dir is resolved per adapter in connect() (``_resolve_store_dir``), NOT at
+# module scope: the multiplex gateway imports this once, and a module constant would make
+# every profile's Olm identity collide in one crypto.db.
from hermes_constants import get_hermes_dir as _get_hermes_dir
# Grace period: ignore messages older than this many seconds before startup.
_STARTUP_GRACE_SECONDS = 5
-_OUTBOUND_MENTION_RE = re.compile(
- r"(?<![\w/])(@[0-9A-Za-z._=/-]+:[0-9A-Za-z.-]+(?::\d+)?)"
-)
+_OUTBOUND_MENTION_RE = re.compile(r"(?<![\w/])(@[0-9A-Za-z._=/-]+:[0-9A-Za-z.-]+(?::\d+)?)")
_E2EE_INSTALL_HINT = (
"Install with: pip install 'mautrix[encryption]' asyncpg aiosqlite "
@@ -627,153 +471,81 @@ _MATRIX_IMAGE_FILENAME_EXTS = frozenset({
".avif",
})
-# Extensions for audio/video/file msgtypes whose ``content.body`` is
-# the uploaded filename when the sender adds no caption.
_MATRIX_MEDIA_FILENAME_EXTS = frozenset({
".ogg", ".oga", ".opus", ".m4a", ".mp3", ".wav", ".flac", ".aac", ".amr",
".mp4", ".webm", ".mov", ".mkv",
})
_MATRIX_MODEL_PICKER_REACTIONS = (
- "1\ufe0f\u20e3",
- "2\ufe0f\u20e3",
- "3\ufe0f\u20e3",
- "4\ufe0f\u20e3",
- "5\ufe0f\u20e3",
- "6\ufe0f\u20e3",
- "7\ufe0f\u20e3",
- "8\ufe0f\u20e3",
- "9\ufe0f\u20e3",
- "\U0001f51f",
+ "1\ufe0f\u20e3", "2\ufe0f\u20e3", "3\ufe0f\u20e3", "4\ufe0f\u20e3", "5\ufe0f\u20e3",
+ "6\ufe0f\u20e3", "7\ufe0f\u20e3", "8\ufe0f\u20e3", "9\ufe0f\u20e3", "\U0001f51f",
)
-# Choice pickers (/reasoning, /fast) can need more than 10 slots
-# (8 effort levels + none + reset/show/hide = 12), so extend the keycap
-# set with lettered squares.
+# Choice pickers (/reasoning, /fast) can need 12 slots, so extend the keycaps.
_MATRIX_CHOICE_PICKER_REACTIONS = _MATRIX_MODEL_PICKER_REACTIONS + (
"\U0001f170\ufe0f", # 🅰️
"\U0001f171\ufe0f", # 🅱️
)
-_MATRIX_CAPABILITIES: Dict[str, str] = {
- "text": "yes",
- "threads": "yes",
- "reactions": "yes",
- "approvals": "yes",
- "model picker": "yes",
- "thinking panes": "yes",
- "images": "yes",
- "multiple images": "yes",
- "files": "yes",
- "voice/audio": "yes",
- "video": "yes",
- "E2EE": "off / optional / required",
- "diagnostics": "yes",
-}
-
-
-def get_matrix_capabilities() -> Dict[str, str]:
- """Return Matrix gateway capabilities for docs and release checks."""
- return dict(_MATRIX_CAPABILITIES)
-
-
def _looks_like_matrix_image_filename(text: str) -> bool:
- """Return True when Matrix image body text is probably just a transport filename.
+ """True when an m.image body is just the uploaded filename (no caption) — not user text."""
+ return _looks_like_transport_filename(text, "image/", _MATRIX_IMAGE_FILENAME_EXTS)
- Matrix ``m.image`` events commonly populate ``content.body`` with the uploaded
- filename when the user did not add a caption. Treating that raw filename as
- user-authored text confuses downstream vision enrichment.
- """
+
+def _looks_like_transport_filename(text: str, mime_prefixes, exts: frozenset, reject_spaces: bool = False) -> bool:
+ """Bare single-token filename with a known media extension or a matching guessed MIME type."""
candidate = str(text or "").strip()
if not candidate or "\n" in candidate or candidate.endswith("/"):
return False
-
+ # A genuine caption essentially always contains whitespace; a bare transport filename does not.
+ if reject_spaces and any(ch.isspace() for ch in candidate):
+ return False
name = Path(candidate).name
if not name or name != candidate:
return False
-
suffix = Path(name).suffix.lower()
if not suffix:
return False
-
guessed_type, _ = mimetypes.guess_type(name)
- if guessed_type and guessed_type.startswith("image/"):
+ if guessed_type and guessed_type.startswith(mime_prefixes):
return True
- return suffix in _MATRIX_IMAGE_FILENAME_EXTS
+ return suffix in exts
def _looks_like_matrix_media_filename(text: str) -> bool:
- """Return True when Matrix audio/video/file body text is a transport filename.
-
- Matrix ``m.audio``/``m.file``/``m.video`` events populate ``content.body``
- with the uploaded filename when the sender adds no caption. Same
- conservative heuristic as :func:`_looks_like_matrix_image_filename` but
- for non-image media types.
- """
- candidate = str(text or "").strip()
- if not candidate or "\n" in candidate or candidate.endswith("/"):
- return False
- # A genuine caption essentially always contains whitespace; a bare
- # transport filename does not.
- if any(ch.isspace() for ch in candidate):
- return False
-
- name = Path(candidate).name
- if not name or name != candidate:
- return False
-
- suffix = Path(name).suffix.lower()
- if not suffix:
- return False
-
- guessed_type, _ = mimetypes.guess_type(name)
- if guessed_type and guessed_type.startswith(("audio/", "video/")):
- return True
- return suffix in _MATRIX_MEDIA_FILENAME_EXTS
+ """True when an m.audio/m.file/m.video body is just the uploaded filename (no caption)."""
+ return _looks_like_transport_filename(text, ("audio/", "video/"), _MATRIX_MEDIA_FILENAME_EXTS, True)
def _matrix_event_timestamp_seconds(event: Any) -> float:
"""Return a Matrix event timestamp in seconds, accepting ms or sec values."""
- raw_ts = (
- getattr(event, "timestamp", None)
- or getattr(event, "server_timestamp", None)
- or 0
- )
+ raw_ts = (getattr(event, "timestamp", None) or getattr(event, "server_timestamp", None) or 0)
if not raw_ts:
return 0.0
try:
ts = float(raw_ts)
except (TypeError, ValueError):
return 0.0
- # Matrix origin_server_ts is milliseconds. Some tests/fakes and SDK objects
- # expose seconds; do not turn those into 1970-era timestamps.
+ # origin_server_ts is ms; some SDK objects/fakes expose seconds — keep both sane.
if ts > 10_000_000_000:
return ts / 1000.0
return ts
def _create_matrix_session(proxy_url: str | None):
- """Create an ``aiohttp.ClientSession`` whose proxy applies to *all* requests.
-
- mautrix's ``HTTPAPI._send()`` calls ``session.request()`` without forwarding
- per-request ``proxy=`` kwargs. For HTTP(S) proxies we use aiohttp's native
- ``proxy=`` session parameter which sets a default for every request. For SOCKS
- we use ``aiohttp_socks.ProxyConnector`` (connector-level).
- When no proxy is configured we enable ``trust_env`` so standard env vars
- (``HTTP_PROXY`` / ``HTTPS_PROXY``) are honoured automatically.
+ """ClientSession whose proxy applies to *all* requests.
+
+ mautrix's ``HTTPAPI._send()`` never forwards per-request ``proxy=``, so it must be
+ session-level (``proxy=`` for HTTP(S), ``ProxyConnector`` for SOCKS); with no proxy,
+ ``trust_env`` honours HTTP(S)_PROXY.
"""
import aiohttp
-
if not proxy_url:
return aiohttp.ClientSession(trust_env=gateway_trust_env())
-
if proxy_url.split("://")[0].lower().startswith("socks"):
try:
from aiohttp_socks import ProxyConnector
-
- return aiohttp.ClientSession(
- connector=ProxyConnector.from_url(proxy_url, rdns=True),
- )
+ return aiohttp.ClientSession(connector=ProxyConnector.from_url(proxy_url, rdns=True))
except ImportError:
logger.warning(
"aiohttp_socks not installed — SOCKS proxy %s ignored. "
@@ -781,28 +553,19 @@ def _create_matrix_session(proxy_url: str | None):
proxy_url,
)
return aiohttp.ClientSession(trust_env=gateway_trust_env())
-
return aiohttp.ClientSession(proxy=proxy_url)
def _check_e2ee_deps() -> bool:
- """Return True if mautrix E2EE dependencies are available.
-
- Verifies python-olm (via mautrix.crypto.OlmMachine), the SQLite crypto
- store backend (mautrix.crypto.store.asyncpg.PgCryptoStore — yes, the
- PgCryptoStore class also drives the sqlite backend in mautrix 0.21),
- and the database drivers actually used at connect time (``asyncpg`` for
- the underlying upgrade_table machinery, ``aiosqlite`` for the
- ``sqlite:///`` URL we pass to ``Database.create``). Without all four,
- encrypted rooms fail at connect time with a confusing
- ``No module named 'asyncpg'`` (#31116).
+ """True if all four E2EE deps import: olm, PgCryptoStore (also drives sqlite), asyncpg, aiosqlite.
+
+ Without all four, encrypted rooms fail at connect with ``No module named 'asyncpg'``.
"""
try:
from mautrix.crypto import OlmMachine # noqa: F401
from mautrix.crypto.store.asyncpg import PgCryptoStore # noqa: F401
import asyncpg # noqa: F401
import aiosqlite # noqa: F401
-
return True
except (ImportError, AttributeError):
return False
@@ -824,13 +587,38 @@ def _resolve_e2ee_mode(extra: Optional[Dict[str, Any]] = None) -> str:
explicit = extra.get("e2ee_mode") or os.getenv("MATRIX_E2EE_MODE", "")
if explicit:
return _normalize_e2ee_mode(explicit)
- legacy_enabled = extra.get(
- "encryption",
- os.getenv("MATRIX_ENCRYPTION", "").lower() in ("true", "1", "yes"),
- )
+ legacy_enabled = extra.get("encryption", _env_truthy("MATRIX_ENCRYPTION"))
return "required" if legacy_enabled else "off"
+def _env_truthy(name: str, default: str = "") -> bool:
+ """Return True when the env var is one of true/1/yes (case-insensitive)."""
+ return os.getenv(name, default).lower() in ("true", "1", "yes")
+
+
+def _env_number(name: str, default, cast):
+ """Parse a numeric env var, falling back to *default* on ValueError."""
+ try:
+ return cast(os.getenv(name, str(default)))
+ except ValueError:
+ return default
+
+
+def _csv_set(raw: Any) -> Set[str]:
+ """Normalize a comma-separated string or list into a set of stripped tokens."""
+ if isinstance(raw, list):
+ return {str(r).strip() for r in raw if str(r).strip()}
+ return {r.strip() for r in str(raw).split(",") if r.strip()}
+
+
+def _extra_csv_set(config, key: str, env_name: str) -> Set[str]:
+ """Resolve a room/user list from config.extra[key], else the env var."""
+ raw = config.extra.get(key)
+ if raw is None:
+ raw = os.getenv(env_name, "")
+ return _csv_set(raw)
+
+
def _redact_matrix_value(value: Any) -> str:
"""Return a safe, non-reversible preview for Matrix diagnostics."""
text = str(value or "").strip()
@@ -840,11 +628,7 @@ def _redact_matrix_value(value: Any) -> str:
def _write_matrix_recovery_key_output_file(recovery_key: str) -> Optional[Path]:
- """Write a generated Matrix recovery key to an operator-chosen file.
-
- The file is created with mode 0600 and never overwritten. Returns the path
- when written, otherwise None.
- """
+ """Write a generated recovery key to MATRIX_RECOVERY_KEY_OUTPUT_FILE (0600, never overwritten)."""
output_file = os.getenv("MATRIX_RECOVERY_KEY_OUTPUT_FILE", "").strip()
if not output_file:
return None
@@ -901,7 +685,6 @@ def _handle_generated_matrix_recovery_key(mxid: str, recovery_key: str) -> None:
exc,
)
return
-
if output_path:
logger.warning(
"Matrix: bootstrapped cross-signing for %s. A new recovery key was "
@@ -921,16 +704,10 @@ def _handle_generated_matrix_recovery_key(mxid: str, recovery_key: str) -> None:
def _scoped_recovery_key() -> str:
- """Resolve MATRIX_RECOVERY_KEY honoring the active profile's secret scope.
-
- Under ``gateway.multiplex_profiles`` the secret scope holds the secondary
- profile's credentials, while ``os.environ`` may carry the default profile's
- key — so a bare ``os.getenv`` resolves the wrong key and E2EE verification
- fails with "Key MAC does not match" (#69090). We read through
- :func:`get_secret`, which is scope-aware. An *unscoped* read under multiplex
- (e.g. the default-profile startup loop) raises ``UnscopedSecretError``; in
- that context ``os.environ`` is that profile's own value, so we fall back to
- it — mirroring the established Slack app-token pattern (#59739).
+ """MATRIX_RECOVERY_KEY via the profile-scoped secret store (see _startup_env_secret).
+
+ A bare os.getenv under multiplex resolves the default profile's key and verification
+ fails with "Key MAC does not match".
"""
try:
return (get_secret("MATRIX_RECOVERY_KEY") or "").strip()
@@ -961,16 +738,8 @@ def _redact_url_for_log(url: str) -> str:
def _pre_sanitize_matrix_markdown(text: str) -> str:
"""Remove unsafe raw HTML before Markdown conversion can escape it."""
- result = re.sub(
- r"(?is)<\s*(script|style)\b[^>]*>.*?<\s*/\s*\1\s*>",
- "",
- text or "",
- )
- result = re.sub(
- r"""(?is)\s+on[a-z0-9_-]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)""",
- "",
- result,
- )
+ result = re.sub(r"(?is)<\s*(script|style)\b[^>]*>.*?<\s*/\s*\1\s*>", "", text or "")
+ result = re.sub(r"""(?is)\s+on[a-z0-9_-]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)""", "", result)
result = re.sub(
r"""(?is)\s+(href|src)\s*=\s*("[^"]*(?:javascript|data|vbscript):[^"]*"|'[^']*(?:javascript|data|vbscript):[^']*'|[^\s>]*(?:javascript|data|vbscript):[^\s>]*)""",
"",
@@ -980,13 +749,8 @@ def _pre_sanitize_matrix_markdown(text: str) -> str:
def _startup_env_secret(name: str) -> str:
- """Read a Matrix credential at adapter-startup time, scope-aware.
-
- Slack pattern (#59739): a scoped read honors the installed profile's
- secret scope verdict (scoped miss ⇒ empty, no borrowing the process
- env); only an UNSCOPED read under multiplex (default-profile startup
- loop) falls back to ``os.environ``, which is that profile's own value.
- """
+ """Scope-aware credential read: a scoped miss is empty (never borrow the process env);
+ only an UNSCOPED read (default-profile startup loop) falls back to os.environ."""
try:
return (get_secret(name) or "").strip()
except UnscopedSecretError:
@@ -994,13 +758,7 @@ def _startup_env_secret(name: str) -> str:
def matrix_deps_present() -> bool:
- """PASSIVE probe: are the ``platform.matrix`` packages installed?
-
- Registry ``check_fn`` — called from status displays and config loading,
- so it must never install anything. The ACTIVE lazy-installer
- (``check_matrix_requirements``) is registered as ``ensure_deps_fn``
- and runs from ``create_adapter()`` when this returns False (#79812).
- """
+ """PASSIVE registry ``check_fn`` — must never install; ``ensure_matrix_deps`` is the installer."""
try:
from tools.lazy_deps import is_available
return is_available("platform.matrix")
@@ -1009,44 +767,25 @@ def matrix_deps_present() -> bool:
def check_matrix_requirements() -> bool:
- """Return True if the Matrix adapter can be used.
-
- Combined credentials + deps answer for setup/status callers. The
- registry's ``ensure_deps_fn`` is the deps-only
- :func:`ensure_matrix_deps` below — credentials must NOT gate the
- installer (they're handled by ``is_connected``, which also accepts
- ``PlatformConfig.extra``-configured setups that these env checks
- would wrongly veto).
- """
+ """Credentials + deps answer for setup/status callers (credentials must NOT gate the installer)."""
token = _startup_env_secret("MATRIX_ACCESS_TOKEN")
password = _startup_env_secret("MATRIX_PASSWORD")
homeserver = _startup_env_secret("MATRIX_HOMESERVER")
-
if not token and not password:
logger.debug("Matrix: neither MATRIX_ACCESS_TOKEN nor MATRIX_PASSWORD set")
return False
if not homeserver:
logger.warning("Matrix: MATRIX_HOMESERVER not set")
return False
-
return ensure_matrix_deps()
def ensure_matrix_deps() -> bool:
- """ACTIVE deps-only installer (registry ``ensure_deps_fn``).
-
- Lazy-installs the full ``platform.matrix`` feature group via
- ``tools.lazy_deps.ensure_and_bind`` whenever any of the declared
- packages (mautrix, Markdown, aiosqlite, asyncpg, aiohttp-socks) is
- missing — not just mautrix itself. Previously this short-circuited on
- ``import mautrix``, which left the other four packages uninstalled
- forever and broke E2EE connect with ``No module named 'asyncpg'``
- (#31116). Rebinds module-level type globals on success.
+ """ACTIVE deps-only installer (registry ``ensure_deps_fn``); rebinds the type globals.
+
+ Installs the whole ``platform.matrix`` group when ANY declared package is missing —
+ short-circuiting on ``import mautrix`` left asyncpg/aiosqlite uninstalled forever.
"""
- # Check whether any package in the platform.matrix feature group is
- # missing. ``feature_missing`` is cheap (per-spec importlib.metadata
- # lookups) and correctly handles ``mautrix[encryption]`` by stripping
- # the extras marker before checking the bare package.
try:
from tools.lazy_deps import feature_missing, ensure_and_bind
missing = feature_missing("platform.matrix")
@@ -1054,27 +793,17 @@ def ensure_matrix_deps() -> bool:
logger.debug("Matrix: lazy_deps lookup failed: %s", exc)
missing = ()
ensure_and_bind = None # type: ignore[assignment]
-
if missing or ensure_and_bind is None:
def _import():
from mautrix.types import (
- ContentURI, EventID, EventType, PaginationDirection,
- PresenceState, RoomCreatePreset, RoomID, SyncToken,
- TrustState, UserID,
+ ContentURI, EventID, EventType, PresenceState, RoomCreatePreset,
+ RoomID, TrustState, UserID,
)
return {
- "ContentURI": ContentURI,
- "EventID": EventID,
- "EventType": EventType,
- "PaginationDirection": PaginationDirection,
- "PresenceState": PresenceState,
- "RoomCreatePreset": RoomCreatePreset,
- "RoomID": RoomID,
- "SyncToken": SyncToken,
- "TrustState": TrustState,
- "UserID": UserID,
+ "ContentURI": ContentURI, "EventID": EventID, "EventType": EventType,
+ "PresenceState": PresenceState, "RoomCreatePreset": RoomCreatePreset,
+ "RoomID": RoomID, "TrustState": TrustState, "UserID": UserID,
}
-
if ensure_and_bind is None:
return False
if not ensure_and_bind("platform.matrix", _import, globals(), prompt=False):
@@ -1085,7 +814,6 @@ def ensure_matrix_deps() -> bool:
", ".join(missing) if missing else "platform.matrix",
)
return False
-
e2ee_mode = _resolve_e2ee_mode()
if e2ee_mode == "required" and not _check_e2ee_deps():
logger.error(
@@ -1096,33 +824,19 @@ def ensure_matrix_deps() -> bool:
)
return False
if e2ee_mode == "optional" and not _check_e2ee_deps():
- logger.warning(
- "Matrix: E2EE optional but dependencies are missing. %s",
- _E2EE_INSTALL_HINT,
- )
-
+ logger.warning("Matrix: E2EE optional but dependencies are missing. %s", _E2EE_INSTALL_HINT)
return True
class _CryptoStateStore:
- """Adapter that satisfies the mautrix crypto StateStore interface.
-
- OlmMachine requires a StateStore with ``is_encrypted``,
- ``get_encryption_info``, and ``find_shared_rooms``. The basic
- ``MemoryStateStore`` from ``mautrix.client`` doesn't implement these,
- so we provide simple implementations that consult the client's room
- state, falling back to a direct homeserver state event query when
- the in-memory store has no encryption info for a room.
- """
+ """StateStore shim for OlmMachine (MemoryStateStore lacks is_encrypted/get_encryption_info/
+ find_shared_rooms); falls back to a homeserver state query when the store has no info."""
def __init__(self, client_state_store: Any, joined_rooms: set, client=None):
self._ss = client_state_store
self._joined_rooms = joined_rooms
self._client = client
- # Cache encryption info queried from the homeserver so we don't
- # make a network round-trip on every is_encrypted() call.
- # MemoryStateStore doesn't implement set_encryption_info, so the
- # cache-back in get_encryption_info is a no-op without this.
+ # MemoryStateStore has no set_encryption_info, so cache homeserver answers here.
self._enc_info_cache: dict = {}
async def is_encrypted(self, room_id: str) -> bool:
@@ -1134,7 +848,6 @@ class _CryptoStateStore:
info = await self._ss.get_encryption_info(room_id)
if info is not None:
return info
- # Check local cache before hitting the homeserver.
if room_id in self._enc_info_cache:
return self._enc_info_cache[room_id]
client = self._client
@@ -1142,17 +855,11 @@ class _CryptoStateStore:
return None
try:
from mautrix.types import (
- EventType as _ET,
- RoomEncryptionStateEventContent as _Enc,
- RoomID as _RID,
+ EventType as _ET, RoomEncryptionStateEventContent as _Enc, RoomID as _RID,
)
raw = await client.get_state_event(_RID(room_id), _ET.ROOM_ENCRYPTION)
except Exception as exc:
- logger.debug(
- "Matrix: homeserver encryption-info query failed for %s: %s",
- room_id,
- exc,
- )
+ logger.debug("Matrix: homeserver encryption-info query failed for %s: %s", room_id, exc)
return None
if not raw:
return None
@@ -1168,8 +875,7 @@ class _CryptoStateStore:
return content
async def find_shared_rooms(self, user_id: str) -> list:
- # Return all joined rooms — simple but correct for a single-user bot.
- return list(self._joined_rooms)
+ return list(self._joined_rooms) # all joined rooms: correct for a single-user bot
class MatrixAdapter(BasePlatformAdapter):
@@ -1178,26 +884,16 @@ class MatrixAdapter(BasePlatformAdapter):
supports_code_blocks = True # Matrix renders fenced code blocks (HTML/markdown)
splits_long_messages = True # send() chunks via truncate_message(max_message_length)
- # Matrix clients commonly reserve typed "/" for client-local commands;
- # the adapter accepts "!command" as the alias that always reaches Hermes
- # (see _normalize_matrix_bang_command), so instruction text shows "!".
+ # Clients reserve typed "/" for local commands; "!command" always reaches Hermes.
typed_command_prefix = "!"
- # Class-level defaults so partially-constructed instances (tests build
- # adapters via object.__new__ without __init__) keep working; __init__
- # overrides both from _resolve_max_message_length().
+ # Class-level defaults keep object.__new__-built test instances working.
max_message_length = DEFAULT_MAX_MESSAGE_LENGTH
_split_threshold = DEFAULT_MAX_MESSAGE_LENGTH - 100
def _resolve_store_dir(self) -> Path:
- """Pin this adapter's crypto-store directory to the active profile.
-
- Called from ``connect()``, which the multiplex gateway runs inside
- ``_profile_runtime_scope`` -- ``get_hermes_dir`` honors that
- context-local HERMES_HOME, so each profile's adapter gets its own
- store. Cached on the instance so later reads (diagnostics, error
- logs) outside the scope still report the store actually in use.
- """
+ """Pin the crypto-store dir to the active profile (connect() runs inside the profile
+ scope); cached so later out-of-scope reads report the store actually in use."""
self._store_dir = _get_hermes_dir("platforms/matrix/store", "matrix/store")
return self._store_dir
@@ -1208,32 +904,20 @@ class MatrixAdapter(BasePlatformAdapter):
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform.MATRIX)
-
self.max_message_length = _resolve_max_message_length(config)
- # Mirror other platform adapters for tests/tooling that read MAX_MESSAGE_LENGTH.
- self.MAX_MESSAGE_LENGTH = self.max_message_length
- # When a chunk is near the outbound limit, a continuation is almost certain.
+ self.MAX_MESSAGE_LENGTH = self.max_message_length # mirrors other adapters for tooling
+ # A chunk near the outbound limit almost certainly has a continuation.
self._split_threshold = max(100, self.max_message_length - 100)
-
self._homeserver: str = (
config.extra.get("homeserver", "") or os.getenv("MATRIX_HOMESERVER", "")
).rstrip("/")
- self._access_token: str = config.token or _startup_env_secret(
- "MATRIX_ACCESS_TOKEN"
- )
- self._user_id: str = config.extra.get("user_id", "") or os.getenv(
- "MATRIX_USER_ID", ""
- )
- self._password: str = config.extra.get("password", "") or _startup_env_secret(
- "MATRIX_PASSWORD"
- )
+ self._access_token: str = config.token or _startup_env_secret("MATRIX_ACCESS_TOKEN")
+ self._user_id: str = config.extra.get("user_id", "") or os.getenv("MATRIX_USER_ID", "")
+ self._password: str = config.extra.get("password", "") or _startup_env_secret("MATRIX_PASSWORD")
self._e2ee_mode: str = _resolve_e2ee_mode(config.extra)
self._encryption: bool = self._e2ee_mode != "off"
- self._device_id: str = config.extra.get("device_id", "") or os.getenv(
- "MATRIX_DEVICE_ID", ""
- )
+ self._device_id: str = config.extra.get("device_id", "") or os.getenv("MATRIX_DEVICE_ID", "")
self._device_id_unverified: bool = False
-
self._client: Any = None # mautrix.client.Client
self._crypto_db: Any = None # mautrix.util.async_db.Database
self._store_dir: Optional[Path] = None # pinned per profile in connect()
@@ -1241,152 +925,63 @@ class MatrixAdapter(BasePlatformAdapter):
self._invite_join_tasks: Dict[str, asyncio.Task] = {}
self._closing = False
self._startup_ts: float = 0.0
- # Clock-skew detection: count grace-check drops that happen well
- # after startup (i.e. not initial-sync backfill). If the host's
- # system clock is set ahead of real time, the startup grace check
- # `event_ts < startup_ts - 5` silently drops every live message.
- # See #12614 — the symptom is "bot joins rooms but never replies".
- # Drops only count when their skew matches the first sampled drop
- # (within 60s), so varied-age backfill from freshly-invited rooms
- # doesn't trip the heuristic.
+ # Clock-skew detector state (see _note_late_grace_drop).
self._late_grace_drops: int = 0
self._late_grace_skew: float = 0.0
self._clock_skew_warned: bool = False
self._last_sync_ts: float = 0.0
-
- # Cache: room_id → bool (is DM)
self._dm_rooms: Dict[str, bool] = {}
self._room_identities: Dict[str, MatrixRoomIdentity] = {}
self._room_identity_cached_at: Dict[str, float] = {}
- try:
- self._room_identity_ttl_seconds = float(
- os.getenv("MATRIX_ROOM_IDENTITY_TTL_SECONDS", "60")
- )
- except ValueError:
- self._room_identity_ttl_seconds = 60.0
+ self._room_identity_ttl_seconds = _env_number("MATRIX_ROOM_IDENTITY_TTL_SECONDS", 60.0, float)
self._room_identity_cache_max = 256
- # Set of room IDs we've joined
self._joined_rooms: Set[str] = set()
- # Event deduplication (bounded deque keeps newest entries)
from collections import deque
-
- self._processed_events: deque = deque(maxlen=1000)
+ self._processed_events: deque = deque(maxlen=1000) # event dedup, newest kept
self._processed_events_set: set = set()
-
- # Buffer for undecrypted events pending key receipt.
- # Each entry: (room_id, event, timestamp)
-
- # Thread participation tracking (for require_mention bypass)
- self._threads = ThreadParticipationTracker("matrix")
-
- # Mention/thread gating — parsed once from config.extra or env vars.
+ self._threads = ThreadParticipationTracker("matrix") # require_mention bypass
self._require_mention: bool = self._parse_require_mention(config)
self._thread_require_mention: bool = self._parse_thread_require_mention(config)
- free_rooms_raw = config.extra.get("free_response_rooms")
- if free_rooms_raw is None:
- free_rooms_raw = os.getenv("MATRIX_FREE_RESPONSE_ROOMS", "")
- if isinstance(free_rooms_raw, list):
- self._free_rooms: Set[str] = {
- str(r).strip() for r in free_rooms_raw if str(r).strip()
- }
- else:
- self._free_rooms: Set[str] = {
- r.strip() for r in str(free_rooms_raw).split(",") if r.strip()
- }
+ self._free_rooms: Set[str] = _extra_csv_set(config, "free_response_rooms", "MATRIX_FREE_RESPONSE_ROOMS")
# If non-empty, bot ONLY responds in these rooms (whitelist); DMs exempt.
- allowed_rooms_raw = config.extra.get("allowed_rooms")
- if allowed_rooms_raw is None:
- allowed_rooms_raw = os.getenv("MATRIX_ALLOWED_ROOMS", "")
- if isinstance(allowed_rooms_raw, list):
- self._allowed_rooms: Set[str] = {
- str(r).strip() for r in allowed_rooms_raw if str(r).strip()
- }
- else:
- self._allowed_rooms: Set[str] = {
- r.strip() for r in str(allowed_rooms_raw).split(",") if r.strip()
- }
- self._allow_room_mentions: bool = os.getenv(
- "MATRIX_ALLOW_ROOM_MENTIONS", "false"
- ).lower() in ("true", "1", "yes")
- self._auto_thread: bool = os.getenv("MATRIX_AUTO_THREAD", "true").lower() in (
- "true",
- "1",
- "yes",
- )
- self._dm_auto_thread: bool = os.getenv(
- "MATRIX_DM_AUTO_THREAD", "false"
- ).lower() in {"true", "1", "yes"}
- self._dm_mention_threads: bool = os.getenv(
- "MATRIX_DM_MENTION_THREADS", "false"
- ).lower() in ("true", "1", "yes")
+ self._allowed_rooms: Set[str] = _extra_csv_set(config, "allowed_rooms", "MATRIX_ALLOWED_ROOMS")
+ self._allow_room_mentions: bool = _env_truthy("MATRIX_ALLOW_ROOM_MENTIONS", "false")
+ self._auto_thread: bool = _env_truthy("MATRIX_AUTO_THREAD", "true")
+ self._dm_auto_thread: bool = _env_truthy("MATRIX_DM_AUTO_THREAD", "false")
+ self._dm_mention_threads: bool = _env_truthy("MATRIX_DM_MENTION_THREADS", "false")
raw_session_scope = os.getenv("MATRIX_SESSION_SCOPE", "auto").strip().lower()
self._matrix_session_scope = (
raw_session_scope if raw_session_scope in {"auto", "room", "thread"} else "auto"
)
- self._process_notices: bool = os.getenv(
- "MATRIX_PROCESS_NOTICES", "false"
- ).lower() in ("true", "1", "yes")
-
- # Reactions: configurable via MATRIX_REACTIONS (default: true).
- self._reactions_enabled: bool = os.getenv(
- "MATRIX_REACTIONS", "true"
- ).lower() not in {"false", "0", "no"}
+ self._process_notices: bool = _env_truthy("MATRIX_PROCESS_NOTICES", "false")
+ self._reactions_enabled: bool = os.getenv("MATRIX_REACTIONS", "true").lower() not in {"false", "0", "no"}
self._pending_reactions: dict[tuple[str, str], str] = {}
- # Delay before redacting reactions so Matrix homeservers have time to
- # deliver the final message event without tripping "missing event"
- # errors in some clients. 5s is empirically safe; not user-tunable —
- # if that changes, add a config.yaml entry rather than an env var.
+ # Let the final message land before redacting reactions ("missing event" in some
+ # clients). 5s is empirically safe; if it must be tunable, use config.yaml not env.
self._reaction_redaction_delay_seconds = 5.0
self._reaction_redaction_tasks: Set[asyncio.Task] = set()
-
- # Proxy support — resolve once at init, reuse for all HTTP traffic.
self._proxy_url: str | None = resolve_proxy_url(platform_env_var="MATRIX_PROXY")
if self._proxy_url:
logger.info("Matrix: proxy configured — %s", self._proxy_url)
- try:
- self._max_media_bytes = int(os.getenv("MATRIX_MAX_MEDIA_BYTES", str(100 * 1024 * 1024)))
- except ValueError:
- self._max_media_bytes = 100 * 1024 * 1024
-
- # Text batching: merge rapid successive messages (Telegram-style).
- # Matrix clients split long messages around 4000 chars.
- self._text_batch_delay_seconds = float(
- os.getenv("HERMES_MATRIX_TEXT_BATCH_DELAY_SECONDS", "0.6")
- )
+ self._max_media_bytes = _env_number("MATRIX_MAX_MEDIA_BYTES", 100 * 1024 * 1024, int)
+ # Text batching merges client-side splits (~4000 chars) of one long message.
+ self._text_batch_delay_seconds = float(os.getenv("HERMES_MATRIX_TEXT_BATCH_DELAY_SECONDS", "0.6"))
self._text_batch_split_delay_seconds = float(
os.getenv("HERMES_MATRIX_TEXT_BATCH_SPLIT_DELAY_SECONDS", "2.0")
)
self._pending_text_batches: Dict[str, MessageEvent] = {}
self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}
-
- # Matrix reaction-based dangerous command approvals.
self._approval_reaction_map = {
- "✅": "once",
- "🌀": "session",
- "♾️": "always",
- "♾": "always",
- "\u267e\ufe0f": "always",
- "\u267e": "always",
- "❌": "deny",
- "❎": "deny",
+ "✅": "once", "🌀": "session", "♾️": "always", "♾": "always", "\u267e\ufe0f": "always",
+ "\u267e": "always", "❌": "deny", "❎": "deny",
}
self._approval_prompts_by_event: Dict[str, _MatrixApprovalPrompt] = {}
self._approval_prompt_by_session: Dict[str, str] = {}
- self._approval_require_sender: bool = os.getenv(
- "MATRIX_APPROVAL_REQUIRE_SENDER", "true"
- ).lower() in ("true", "1", "yes")
- try:
- self._approval_timeout_seconds = int(
- os.getenv("MATRIX_APPROVAL_TIMEOUT_SECONDS", "300")
- )
- except ValueError:
- self._approval_timeout_seconds = 300
+ self._approval_require_sender: bool = _env_truthy("MATRIX_APPROVAL_REQUIRE_SENDER", "true")
+ self._approval_timeout_seconds = _env_number("MATRIX_APPROVAL_TIMEOUT_SECONDS", 300, int)
self._model_picker_prompts_by_event: Dict[str, _MatrixModelPickerPrompt] = {}
self._choice_picker_prompts_by_event: Dict[str, _MatrixChoicePickerPrompt] = {}
- allowed_users_raw = os.getenv("MATRIX_ALLOWED_USERS", "")
- self._allowed_user_ids: Set[str] = {
- u.strip() for u in allowed_users_raw.split(",") if u.strip()
- }
+ self._allowed_user_ids: Set[str] = _csv_set(os.getenv("MATRIX_ALLOWED_USERS", ""))
self._allowed_room_ids: Set[str] = set(self._allowed_rooms)
ignore_patterns_raw = os.getenv("MATRIX_IGNORE_USER_PATTERNS", "")
self._ignored_user_patterns: list[re.Pattern[str]] = []
@@ -1394,11 +989,7 @@ class MatrixAdapter(BasePlatformAdapter):
try:
self._ignored_user_patterns.append(re.compile(pattern))
except re.error as exc:
- logger.warning(
- "Matrix: ignoring invalid MATRIX_IGNORE_USER_PATTERNS entry %r: %s",
- pattern,
- exc,
- )
+ logger.warning("Matrix: ignoring invalid MATRIX_IGNORE_USER_PATTERNS entry %r: %s", pattern, exc)
def _is_duplicate_event(self, event_id) -> bool:
"""Return True if this event was already processed. Tracks the ID otherwise."""
@@ -1414,44 +1005,32 @@ class MatrixAdapter(BasePlatformAdapter):
return False
@staticmethod
- def _parse_require_mention(config) -> bool:
- """Parse require_mention from config.extra or env var.
+ def _configured_bool(config, key: str) -> Optional[bool]:
+ """Parse a YAML bool / "true"/"off"-style string from config.extra; None if unset."""
+ configured = config.extra.get(key)
+ if configured is None:
+ return None
+ if isinstance(configured, bool):
+ return configured
+ if isinstance(configured, str):
+ return configured.lower() not in {"false", "0", "no", "off"}
+ return bool(configured)
- Handles both YAML booleans and string values (``\"true\"``, ``\"false\"``,
- ``\"yes\"``, ``\"no\"``, ``\"on\"``, ``\"off\"``, ``\"1\"``, ``\"0\"``).
- Falls back to ``MATRIX_REQUIRE_MENTION`` env var, default ``true``.
- """
- configured = config.extra.get("require_mention")
+ @staticmethod
+ def _parse_require_mention(config) -> bool:
+ """require_mention from config.extra, else MATRIX_REQUIRE_MENTION (default true)."""
+ configured = MatrixAdapter._configured_bool(config, "require_mention")
if configured is not None:
- if isinstance(configured, bool):
- return configured
- if isinstance(configured, str):
- return configured.lower() not in {"false", "0", "no", "off"}
- return bool(configured)
- return os.getenv(
- "MATRIX_REQUIRE_MENTION", "true"
- ).lower() not in {"false", "0", "no", "off"}
+ return configured
+ return os.getenv("MATRIX_REQUIRE_MENTION", "true").lower() not in {"false", "0", "no", "off"}
@staticmethod
def _parse_thread_require_mention(config) -> bool:
- """Parse thread_require_mention from config.extra or env var.
-
- Handles both YAML booleans and string values (``\"true\"``, ``\"false\"``,
- ``\"yes\"``, ``\"no\"``, ``\"on\"``, ``\"off\"``, ``\"1\"``, ``\"0\"``).
- Falls back to ``MATRIX_THREAD_REQUIRE_MENTION`` env var, default ``false``.
- Mirrors Discord adapter's parsing pattern.
- """
- configured = config.extra.get("thread_require_mention")
+ """thread_require_mention from config.extra, else MATRIX_THREAD_REQUIRE_MENTION (default false)."""
+ configured = MatrixAdapter._configured_bool(config, "thread_require_mention")
if configured is not None:
- if isinstance(configured, bool):
- return configured
- if isinstance(configured, str):
- return configured.lower() not in {"false", "0", "no", "off"}
- # int, float, etc. — truthiness fallback
- return bool(configured)
- return os.getenv(
- "MATRIX_THREAD_REQUIRE_MENTION", "false"
- ).lower() in {"true", "1", "yes", "on"}
+ return configured
+ return os.getenv("MATRIX_THREAD_REQUIRE_MENTION", "false").lower() in {"true", "1", "yes", "on"}
# ------------------------------------------------------------------
# E2EE helpers
@@ -1465,9 +1044,7 @@ class MatrixAdapter(BasePlatformAdapter):
return str(kval)
return None
- async def _reverify_keys_after_upload(
- self, client: Any, local_ed25519: str
- ) -> bool:
+ async def _reverify_keys_after_upload(self, client: Any, local_ed25519: str) -> bool:
"""Re-query the server after share_keys() and verify our ed25519 key matches."""
if not client.device_id or self._device_id_unverified:
logger.warning(
@@ -1498,14 +1075,10 @@ class MatrixAdapter(BasePlatformAdapter):
async def _reset_crypto_store_if_device_changed(
self, crypto_store: Any, device_id: str
) -> bool:
- """Reset the local Olm account when the access token's device changed.
-
- The crypto store is keyed by user ID, so a new access token (= new
- device ID) would otherwise inherit the previous device's Olm account.
- Its identity keys can never be published under the new device ID
- (and the pickle key embeds the old device ID anyway), which leads to
- stale-key mismatches and cross-signing signatures that the
- homeserver refuses to replace. Returns True if the store was reset.
+ """Reset the Olm account when the token's device changed; True if reset.
+
+ The store is keyed by user ID, so a new device would inherit the old Olm account
+ whose identity keys can never be published under the new device ID.
"""
if not device_id:
return False
@@ -1529,46 +1102,32 @@ class MatrixAdapter(BasePlatformAdapter):
async def _migrate_legacy_crypto_pickle(
self, crypto_store: Any, crypto_db: Any, acct_id: str, pickle_key: str
) -> bool:
- """Re-pickle the Olm account when the pickle key changed.
-
- The pickle key embeds the *configured* device ID. If the account was
- created before MATRIX_DEVICE_ID was set (e.g. first password login,
- where the device ID is only known after connecting), the store was
- pickled under ``<acct>:default``; setting MATRIX_DEVICE_ID afterwards
- changes the key and unpickling fails with BAD_ACCOUNT_KEY — which in
- optional-E2EE mode silently disables encryption. Try known legacy
- keys and re-pickle under the current one. Returns False only when an
- account exists but no key can unpickle it.
+ """Re-pickle the Olm account under the current pickle key when it changed.
+
+ The key embeds the device ID; an account created before MATRIX_DEVICE_ID was set
+ lives under ``<acct>:default`` and later fails with BAD_ACCOUNT_KEY (silently
+ disabling optional E2EE). False only when an account exists but no key opens it.
"""
try:
await crypto_store.get_account()
return True
except Exception:
pass
-
from mautrix.crypto.store.asyncpg import PgCryptoStore
-
for legacy_key in (f"{acct_id}:default", acct_id):
if legacy_key == pickle_key:
continue
- legacy_store = PgCryptoStore(
- account_id=acct_id, pickle_key=legacy_key, db=crypto_db
- )
+ legacy_store = PgCryptoStore(account_id=acct_id, pickle_key=legacy_key, db=crypto_db)
try:
account = await legacy_store.get_account()
except Exception:
continue
if account is None:
continue
- # Sessions first, account last. The account is the migration's
- # commit marker: once it reads under the current key, the fast
- # path above short-circuits every later startup. Writing it
- # before the sweep means an interrupted sweep is never retried
- # and the remaining legacy-key sessions are stranded for good.
+ # Sessions first, account last: the account is the commit marker (the fast path
+ # above short-circuits once it reads), so an interrupted sweep is retried.
try:
- await self._repickle_crypto_sessions(
- crypto_db, acct_id, legacy_key, pickle_key
- )
+ await self._repickle_crypto_sessions(crypto_db, acct_id, legacy_key, pickle_key)
except Exception as exc:
logger.error(
"Matrix: pickle key migration failed while re-pickling "
@@ -1584,7 +1143,6 @@ class MatrixAdapter(BasePlatformAdapter):
"account was created)"
)
return True
-
logger.error(
"Matrix: crypto store account exists but cannot be unpickled "
"with the current or any legacy pickle key. If MATRIX_DEVICE_ID "
@@ -1595,14 +1153,8 @@ class MatrixAdapter(BasePlatformAdapter):
async def _repickle_crypto_sessions(
self, crypto_db: Any, acct_id: str, legacy_key: str, pickle_key: str
) -> None:
- """Re-pickle olm/megolm session blobs alongside the account.
-
- The account and every stored session share the pickle key; migrating
- only the account leaves sessions unreadable (BAD_ACCOUNT_KEY on the
- next olm decrypt), which breaks key sharing with peers.
- """
+ """Re-pickle olm/megolm sessions too — they share the key; account-only breaks key sharing."""
import olm as olm_lib
-
tables = {
"crypto_olm_session": olm_lib.Session,
"crypto_megolm_inbound_session": olm_lib.InboundGroupSession,
@@ -1610,8 +1162,7 @@ class MatrixAdapter(BasePlatformAdapter):
}
for table, session_cls in tables.items():
rows = await crypto_db.fetch(
- f"SELECT session_id, session FROM {table} WHERE account_id=$1",
- acct_id,
+ f"SELECT session_id, session FROM {table} WHERE account_id=$1", acct_id,
)
for row in rows:
blob = row["session"]
@@ -1626,10 +1177,7 @@ class MatrixAdapter(BasePlatformAdapter):
try:
session = session_cls.from_pickle(pickled, legacy_key)
except Exception as exc:
- # Readable under neither key. The row is left untouched
- # rather than deleted — it is already unusable, and
- # removing crypto material is not worth doing on a
- # guess. It stays inert.
+ # Readable under neither key: leave it inert rather than delete crypto material.
logger.warning(
"Matrix: %s row %s cannot be unpickled with the "
"current or legacy key; leaving it in place, its "
@@ -1648,11 +1196,7 @@ class MatrixAdapter(BasePlatformAdapter):
)
async def _verify_device_keys_on_server(self, client: Any, olm: Any) -> bool:
- """Verify our device keys are on the homeserver after loading crypto state.
-
- Returns True if keys are valid or were successfully re-uploaded.
- Returns False if verification fails (caller should refuse E2EE).
- """
+ """True if our device keys are on the server (or were re-uploaded); False ⇒ refuse E2EE."""
if not client.device_id or self._device_id_unverified:
logger.warning(
"Matrix: skipping device key verification — "
@@ -1663,17 +1207,14 @@ class MatrixAdapter(BasePlatformAdapter):
resp = await client.query_keys({client.mxid: [client.device_id]})
except Exception as exc:
logger.error(
- "Matrix: cannot verify device keys on server: %s — refusing E2EE",
- exc,
+ "Matrix: cannot verify device keys on server: %s — refusing E2EE", exc,
exc_info=True,
)
return False
-
device_keys_map = getattr(resp, "device_keys", {}) or {}
our_user_devices = device_keys_map.get(str(client.mxid)) or {}
our_keys = our_user_devices.get(str(client.device_id))
local_ed25519 = olm.account.identity_keys.get("ed25519")
-
if not our_keys:
logger.warning("Matrix: device keys missing from server — re-uploading")
olm.account.shared = False
@@ -1683,9 +1224,7 @@ class MatrixAdapter(BasePlatformAdapter):
logger.error("Matrix: failed to re-upload device keys: %s", exc, exc_info=True)
return False
return await self._reverify_keys_after_upload(client, local_ed25519)
-
server_ed25519 = self._extract_server_ed25519(our_keys)
-
if server_ed25519 != local_ed25519:
if olm.account.shared:
logger.error(
@@ -1695,7 +1234,6 @@ class MatrixAdapter(BasePlatformAdapter):
str(self._crypto_db_path),
)
return False
-
logger.warning(
"Matrix: server has stale keys for device %s — attempting re-upload",
client.device_id,
@@ -1707,9 +1245,7 @@ class MatrixAdapter(BasePlatformAdapter):
else "DELETE",
f"/_matrix/client/v3/devices/{client.device_id}",
)
- logger.info(
- "Matrix: deleted stale device %s from server", client.device_id
- )
+ logger.info("Matrix: deleted stale device %s from server", client.device_id)
except Exception:
pass
try:
@@ -1724,60 +1260,16 @@ class MatrixAdapter(BasePlatformAdapter):
)
return False
return await self._reverify_keys_after_upload(client, local_ed25519)
-
return True
# ------------------------------------------------------------------
# Required overrides
# ------------------------------------------------------------------
- async def connect(self, *, is_reconnect: bool = False) -> bool:
- """Connect to the Matrix homeserver and start syncing."""
- self._device_id_unverified = False
- if self._client is not None:
- try:
- await self.disconnect()
- except Exception as exc:
- logger.warning("Matrix: error disconnecting before reconnect: %s", exc)
-
- from mautrix.api import HTTPAPI
- from mautrix.client import Client
- from mautrix.client.state_store import MemoryStateStore, MemorySyncStore
-
- if not self._homeserver:
- logger.error("Matrix: homeserver URL not configured")
- return False
-
- # Ensure store dir exists for E2EE key persistence (resolved here,
- # inside the profile scope, so multiplexed profiles never share it).
- self._resolve_store_dir().mkdir(parents=True, exist_ok=True)
-
- # Create the HTTP API layer.
- client_session = _create_matrix_session(self._proxy_url)
- api = HTTPAPI(
- base_url=self._homeserver,
- token=self._access_token or "",
- client_session=client_session,
- )
-
- # Create the client.
- state_store = MemoryStateStore()
- sync_store = MemorySyncStore()
- client = Client(
- mxid=UserID(self._user_id) if self._user_id else UserID(""),
- device_id=self._device_id or None,
- api=api,
- state_store=state_store,
- sync_store=sync_store,
- )
-
- self._client = client
-
- # Authenticate.
+ async def _connect_authenticate(self, client: Any, api: Any) -> bool:
+ """Authenticate via access token (whoami) or password login; resolve user/device IDs."""
if self._access_token:
api.token = self._access_token
-
- # Validate the token and learn user_id / device_id.
try:
resp = await client.whoami()
resolved_user_id = getattr(resp, "user_id", "") or self._user_id
@@ -1785,21 +1277,9 @@ class MatrixAdapter(BasePlatformAdapter):
if resolved_user_id:
self._user_id = str(resolved_user_id)
client.mxid = UserID(self._user_id)
-
- # Normally the user-configured device_id wins, giving a stable
- # E2EE identity when whoami() reports no device.
- #
- # But an access token is bound to exactly one device, and the
- # homeserver only accepts key uploads for that device. If
- # MATRIX_DEVICE_ID names a different one, honouring it means
- # claiming an identity this token cannot publish — which is
- # the stale-key failure mode this reset exists to clear. The
- # live whoami() device therefore wins on conflict, loudly.
- if (
- resolved_device_id
- and self._device_id
- and resolved_device_id != self._device_id
- ):
+ # The configured device_id wins when whoami() reports none, but a token can
+ # only upload keys for its own device — on conflict whoami() wins, loudly.
+ if resolved_device_id and self._device_id and resolved_device_id != self._device_id:
logger.error(
"Matrix: MATRIX_DEVICE_ID=%s does not match the device "
"this access token belongs to (%s). A token can only "
@@ -1815,7 +1295,6 @@ class MatrixAdapter(BasePlatformAdapter):
effective_device_id = self._device_id or resolved_device_id
if effective_device_id:
client.device_id = effective_device_id
-
if not client.device_id:
try:
dev_resp = await client.query_keys({client.mxid: []})
@@ -1832,10 +1311,7 @@ class MatrixAdapter(BasePlatformAdapter):
client.mxid,
)
except Exception as exc:
- logger.warning(
- "Matrix: device list query failed: %s", exc
- )
-
+ logger.warning("Matrix: device list query failed: %s", exc)
if not client.device_id:
logger.warning(
"Matrix: device_id could not be resolved for %s. "
@@ -1845,26 +1321,21 @@ class MatrixAdapter(BasePlatformAdapter):
client.mxid,
)
self._device_id_unverified = True
-
logger.info(
- "Matrix: using access token for %s%s",
- self._user_id or "(unknown user)",
+ "Matrix: using access token for %s%s", self._user_id or "(unknown user)",
f" (device {effective_device_id})" if effective_device_id else "",
)
except Exception as exc:
logger.error(
"Matrix: whoami failed — check MATRIX_ACCESS_TOKEN and MATRIX_HOMESERVER: %s",
- exc,
- exc_info=True,
+ exc, exc_info=True,
)
await api.session.close()
return False
elif self._password and self._user_id:
try:
resp = await client.login(
- identifier=self._user_id,
- password=self._password,
- device_name="Hermes Agent",
+ identifier=self._user_id, password=self._password, device_name="Hermes Agent",
device_id=self._device_id or None,
)
if resp and hasattr(resp, "device_id"):
@@ -1875,248 +1346,173 @@ class MatrixAdapter(BasePlatformAdapter):
await api.session.close()
return False
else:
- logger.error(
- "Matrix: need MATRIX_ACCESS_TOKEN or MATRIX_USER_ID + MATRIX_PASSWORD"
- )
+ logger.error("Matrix: need MATRIX_ACCESS_TOKEN or MATRIX_USER_ID + MATRIX_PASSWORD")
await api.session.close()
return False
+ return True
- # Set up E2EE if requested.
+ async def _connect_setup_e2ee(self, client: Any, api: Any, state_store: Any) -> bool:
+ """Set up the Olm machine + crypto store. Returns False when connect must abort."""
+ if not _check_e2ee_deps():
+ if self._e2ee_mode == "optional":
+ logger.warning(
+ "Matrix: E2EE optional but dependencies are missing. "
+ "Continuing without encrypted-room support. %s",
+ _E2EE_INSTALL_HINT,
+ )
+ self._encryption = False
+ else:
+ logger.error(
+ "Matrix: E2EE is required but dependencies are missing. %s. "
+ "Refusing to connect — encrypted rooms would silently fail.",
+ _E2EE_INSTALL_HINT,
+ )
+ await api.session.close()
+ return False
if self._encryption:
- if not _check_e2ee_deps():
- if self._e2ee_mode == "optional":
- logger.warning(
- "Matrix: E2EE optional but dependencies are missing. "
- "Continuing without encrypted-room support. %s",
- _E2EE_INSTALL_HINT,
+ try:
+ from mautrix.crypto import OlmMachine
+ from mautrix.crypto.store.asyncpg import PgCryptoStore
+ from mautrix.util.async_db import Database
+ self._store_dir.mkdir(parents=True, exist_ok=True)
+ except Exception as exc:
+ if not await self._e2ee_setup_failed("import", exc, api):
+ return False
+ if self._encryption:
+ try:
+ # Remove legacy pickle file from pre-SQLite era.
+ legacy_pickle = self._store_dir / "crypto_store.pickle"
+ if legacy_pickle.exists():
+ logger.info("Matrix: removing legacy crypto_store.pickle (migrated to SQLite)")
+ legacy_pickle.unlink()
+ crypto_db = Database.create(
+ f"sqlite:///{self._crypto_db_path}", upgrade_table=PgCryptoStore.upgrade_table,
+ )
+ await crypto_db.start()
+ self._crypto_db = crypto_db
+ _acct_id = self._user_id or "hermes"
+ # Key on the RESOLVED client.device_id (token's real device), not the configured
+ # one, or the Olm account is stored under a key that can never be looked up.
+ _pickle_key = f"{_acct_id}:{client.device_id or self._device_id or 'default'}"
+ crypto_store = PgCryptoStore(
+ account_id=_acct_id, pickle_key=_pickle_key, db=crypto_db,
+ )
+ await crypto_store.open()
+ if client.device_id:
+ _store_was_reset = await self._reset_crypto_store_if_device_changed(
+ crypto_store, client.device_id
)
- self._encryption = False
+ await crypto_store.put_device_id(client.device_id)
else:
- logger.error(
- "Matrix: E2EE is required but dependencies are missing. %s. "
- "Refusing to connect — encrypted rooms would silently fail.",
- _E2EE_INSTALL_HINT,
- )
+ _store_was_reset = False
+ # A just-deleted store has no account to migrate.
+ if not _store_was_reset and not await self._migrate_legacy_crypto_pickle(
+ crypto_store, crypto_db, _acct_id, _pickle_key
+ ):
+ logger.warning("Matrix: crypto pickle migration failed — E2EE may not work correctly")
+ crypto_state = _CryptoStateStore(state_store, self._joined_rooms, client)
+ olm = OlmMachine(client, crypto_store, crypto_state)
+ olm.share_keys_min_trust = TrustState.UNVERIFIED
+ olm.send_keys_min_trust = TrustState.UNVERIFIED
+ await olm.load()
+ if not await self._verify_device_keys_on_server(client, olm):
+ await crypto_db.stop()
await api.session.close()
return False
- if not self._encryption:
- pass
- else:
try:
- from mautrix.crypto import OlmMachine
- from mautrix.crypto.store.asyncpg import PgCryptoStore
- from mautrix.util.async_db import Database
-
- self._store_dir.mkdir(parents=True, exist_ok=True)
+ await olm.share_keys()
except Exception as exc:
- if self._e2ee_mode == "optional":
- logger.warning(
- "Matrix: failed to import optional E2EE client; "
- "continuing without encrypted-room support: %s. %s",
- exc,
- _E2EE_INSTALL_HINT,
- )
- self._encryption = False
- else:
+ exc_str = str(exc)
+ if "already exists" in exc_str:
logger.error(
- "Matrix: failed to import E2EE client: %s. %s",
- exc,
- _E2EE_INSTALL_HINT,
+ "Matrix: device %s has stale one-time keys on the "
+ "server signed with a previous identity key. "
+ "Delete the device from the homeserver and restart, "
+ "or generate a new access token to get a fresh device ID.",
+ client.device_id,
)
+ await crypto_db.stop()
await api.session.close()
return False
- if self._encryption:
- try:
- # Remove legacy pickle file from pre-SQLite era.
- legacy_pickle = self._store_dir / "crypto_store.pickle"
- if legacy_pickle.exists():
- logger.info(
- "Matrix: removing legacy crypto_store.pickle (migrated to SQLite)"
- )
- legacy_pickle.unlink()
+ logger.warning("Matrix: share_keys() warning during startup: %s", exc)
+ await self._verify_or_bootstrap_cross_signing(olm, client)
+ client.crypto = olm
+ logger.info(
+ "Matrix: E2EE enabled (store: %s%s)", str(self._crypto_db_path),
+ f", device_id={client.device_id}" if client.device_id else "",
+ )
+ except Exception as exc:
+ if not await self._e2ee_setup_failed("create", exc, api):
+ return False
+ return True
- crypto_db = Database.create(
- f"sqlite:///{self._crypto_db_path}",
- upgrade_table=PgCryptoStore.upgrade_table,
- )
- await crypto_db.start()
- self._crypto_db = crypto_db
-
- _acct_id = self._user_id or "hermes"
- # Use the resolved client.device_id (from whoami or password
- # login), not self._device_id (the configured value), because
- # #71543 makes the token's real device win over a stale
- # MATRIX_DEVICE_ID. The pickle key must match the device the
- # token actually belongs to, or the Olm account is stored
- # under a key that can never be looked up again.
- _pickle_key = f"{_acct_id}:{client.device_id or self._device_id or 'default'}"
- crypto_store = PgCryptoStore(
- account_id=_acct_id,
- pickle_key=_pickle_key,
- db=crypto_db,
- )
- await crypto_store.open()
-
- if client.device_id:
- _store_was_reset = await self._reset_crypto_store_if_device_changed(
- crypto_store, client.device_id
- )
- await crypto_store.put_device_id(client.device_id)
- else:
- _store_was_reset = False
-
- # Skip the pickle-key migration when the store was just
- # deleted — there is no account to migrate.
- if not _store_was_reset:
- if not await self._migrate_legacy_crypto_pickle(
- crypto_store, crypto_db, _acct_id, _pickle_key
- ):
- logger.warning(
- "Matrix: crypto pickle migration failed — "
- "E2EE may not work correctly"
- )
-
- crypto_state = _CryptoStateStore(state_store, self._joined_rooms, client)
- olm = OlmMachine(client, crypto_store, crypto_state)
- olm.share_keys_min_trust = TrustState.UNVERIFIED
- olm.send_keys_min_trust = TrustState.UNVERIFIED
-
- await olm.load()
-
- if not await self._verify_device_keys_on_server(client, olm):
- await crypto_db.stop()
- await api.session.close()
- return False
+ async def _e2ee_setup_failed(self, what: str, exc: Exception, api: Any) -> bool:
+ """Optional mode: log + disable E2EE and return True; required mode: close + return False."""
+ if self._e2ee_mode == "optional":
+ logger.warning(
+ "Matrix: failed to %s optional E2EE client; "
+ "continuing without encrypted-room support: %s. %s",
+ what, exc, _E2EE_INSTALL_HINT,
+ )
+ self._encryption = False
+ return True
+ logger.error("Matrix: failed to %s E2EE client: %s. %s", what, exc, _E2EE_INSTALL_HINT)
+ await api.session.close()
+ return False
+ async def _verify_or_bootstrap_cross_signing(self, olm: Any, client: Any) -> None:
+ """Verify cross-signing via MATRIX_RECOVERY_KEY, or bootstrap a new key (non-fatal)."""
+ recovery_key = _scoped_recovery_key()
+ if recovery_key:
+ try:
+ await olm.verify_with_recovery_key(recovery_key)
+ logger.info("Matrix: cross-signing verified via recovery key")
+ except Exception as exc:
+ logger.warning("Matrix: recovery key verification failed: %s", exc)
+ else:
+ try:
+ own_xsign = await olm.get_own_cross_signing_public_keys()
+ except Exception as exc:
+ own_xsign = None
+ logger.warning("Matrix: cross-signing key lookup failed: %s", exc)
+ if own_xsign is None:
+ _, output_error = _get_matrix_recovery_key_output_target()
+ if output_error == "not_configured":
+ logger.warning(
+ "Matrix: cross-signing keys are missing, but "
+ "automatic bootstrap is skipped because "
+ "MATRIX_RECOVERY_KEY_OUTPUT_FILE is not configured. "
+ "Configure MATRIX_RECOVERY_KEY from your Matrix client "
+ "or set MATRIX_RECOVERY_KEY_OUTPUT_FILE to write a new "
+ "recovery key once with mode 0600."
+ )
+ elif output_error == "exists":
+ logger.warning(
+ "Matrix: cross-signing keys are missing, but "
+ "automatic bootstrap is skipped because "
+ "MATRIX_RECOVERY_KEY_OUTPUT_FILE already exists and "
+ "will not be overwritten."
+ )
+ elif output_error:
+ logger.warning(
+ "Matrix: cross-signing keys are missing, but "
+ "automatic bootstrap is skipped because "
+ "MATRIX_RECOVERY_KEY_OUTPUT_FILE is not usable: %s",
+ output_error,
+ )
+ else:
try:
- await olm.share_keys()
+ new_recovery_key = await olm.generate_recovery_key()
+ _handle_generated_matrix_recovery_key(str(client.mxid), new_recovery_key)
except Exception as exc:
- exc_str = str(exc)
- if "already exists" in exc_str:
- logger.error(
- "Matrix: device %s has stale one-time keys on the "
- "server signed with a previous identity key. "
- "Delete the device from the homeserver and restart, "
- "or generate a new access token to get a fresh device ID.",
- client.device_id,
- )
- await crypto_db.stop()
- await api.session.close()
- return False
- logger.warning("Matrix: share_keys() warning during startup: %s", exc)
-
- # Honor the active profile's secret scope so a secondary
- # profile under gateway.multiplex_profiles resolves its own
- # recovery key instead of the default profile's (which fails
- # E2EE verification with "Key MAC does not match", #69090).
- recovery_key = _scoped_recovery_key()
- if recovery_key:
- try:
- await olm.verify_with_recovery_key(recovery_key)
- logger.info("Matrix: cross-signing verified via recovery key")
- except Exception as exc:
- logger.warning("Matrix: recovery key verification failed: %s", exc)
- else:
- try:
- own_xsign = await olm.get_own_cross_signing_public_keys()
- except Exception as exc:
- own_xsign = None
- logger.warning("Matrix: cross-signing key lookup failed: %s", exc)
- if own_xsign is None:
- _, output_error = _get_matrix_recovery_key_output_target()
- if output_error == "not_configured":
- logger.warning(
- "Matrix: cross-signing keys are missing, but "
- "automatic bootstrap is skipped because "
- "MATRIX_RECOVERY_KEY_OUTPUT_FILE is not configured. "
- "Configure MATRIX_RECOVERY_KEY from your Matrix client "
- "or set MATRIX_RECOVERY_KEY_OUTPUT_FILE to write a new "
- "recovery key once with mode 0600."
- )
- elif output_error == "exists":
- logger.warning(
- "Matrix: cross-signing keys are missing, but "
- "automatic bootstrap is skipped because "
- "MATRIX_RECOVERY_KEY_OUTPUT_FILE already exists and "
- "will not be overwritten."
- )
- elif output_error:
- logger.warning(
- "Matrix: cross-signing keys are missing, but "
- "automatic bootstrap is skipped because "
- "MATRIX_RECOVERY_KEY_OUTPUT_FILE is not usable: %s",
- output_error,
- )
- else:
- try:
- new_recovery_key = await olm.generate_recovery_key()
- _handle_generated_matrix_recovery_key(
- str(client.mxid),
- new_recovery_key,
- )
- except Exception as exc:
- logger.warning(
- "Matrix: cross-signing bootstrap failed "
- "(non-fatal — Element will show 'not verified by its owner'): %s",
- exc,
- )
-
- client.crypto = olm
- logger.info(
- "Matrix: E2EE enabled (store: %s%s)",
- str(self._crypto_db_path),
- f", device_id={client.device_id}" if client.device_id else "",
- )
- except Exception as exc:
- if self._e2ee_mode == "optional":
logger.warning(
- "Matrix: failed to create optional E2EE client; "
- "continuing without encrypted-room support: %s. %s",
- exc,
- _E2EE_INSTALL_HINT,
- )
- self._encryption = False
- else:
- logger.error(
- "Matrix: failed to create E2EE client: %s. %s",
+ "Matrix: cross-signing bootstrap failed "
+ "(non-fatal — Element will show 'not verified by its owner'): %s",
exc,
- _E2EE_INSTALL_HINT,
)
- await api.session.close()
- return False
-
- # Register event handlers.
- from mautrix.client import InternalEventType as IntEvt
- from mautrix.client.dispatcher import MembershipEventDispatcher
-
- # Without this the INVITE handler below never fires.
- client.add_dispatcher(MembershipEventDispatcher)
-
- client.add_event_handler(
- EventType.ROOM_MESSAGE,
- self._on_room_message,
- wait_sync=True,
- )
- client.add_event_handler(
- EventType.REACTION,
- self._on_reaction,
- wait_sync=True,
- )
- client.add_event_handler(
- IntEvt.INVITE,
- self._on_invite,
- wait_sync=True,
- )
-
- # Initial sync to catch up, then start background sync.
- self._startup_ts = time.time()
- # Reset clock-skew detector for each connect cycle so a reconnect
- # after the user fixes NTP doesn't inherit stale counters.
- self._late_grace_drops = 0
- self._late_grace_skew = 0.0
- self._clock_skew_warned = False
- self._closing = False
+ async def _connect_initial_sync(self, client: Any) -> None:
+ """Full initial sync: seed joined rooms, DM cache, and dispatch queued to-device events."""
try:
sync_data = await client.sync(timeout=10000, full_state=True)
if isinstance(sync_data, dict):
@@ -2126,20 +1522,12 @@ class MatrixAdapter(BasePlatformAdapter):
self._joined_rooms.update(rooms_join.keys())
self._room_identities.clear()
self._room_identity_cached_at.clear()
- # Store the next_batch token so incremental syncs start
- # from where the initial sync left off.
- nb = sync_data.get("next_batch")
+ nb = sync_data.get("next_batch") # incremental syncs resume from here
if nb:
await client.sync_store.put_next_batch(nb)
- logger.info(
- "Matrix: initial sync complete, joined %d rooms",
- len(self._joined_rooms),
- )
- # Build DM room cache from m.direct account data.
+ logger.info("Matrix: initial sync complete, joined %d rooms", len(self._joined_rooms))
await self._refresh_dm_cache()
-
- # Dispatch events from the initial sync so the OlmMachine
- # receives to-device key shares queued while we were offline.
+ # Dispatch so the OlmMachine sees to-device key shares queued while offline.
try:
await self._dispatch_sync(sync_data)
except Exception as exc:
@@ -2147,133 +1535,134 @@ class MatrixAdapter(BasePlatformAdapter):
self._schedule_pending_invite_joins(sync_data)
else:
logger.warning(
- "Matrix: initial sync returned unexpected type %s",
- type(sync_data).__name__,
+ "Matrix: initial sync returned unexpected type %s", type(sync_data).__name__,
)
except Exception as exc:
logger.warning("Matrix: initial sync error: %s", exc)
- # Share keys after initial sync if E2EE is enabled.
+ async def connect(self, *, is_reconnect: bool = False) -> bool:
+ """Connect to the Matrix homeserver and start syncing."""
+ self._device_id_unverified = False
+ if self._client is not None:
+ try:
+ await self.disconnect()
+ except Exception as exc:
+ logger.warning("Matrix: error disconnecting before reconnect: %s", exc)
+ from mautrix.api import HTTPAPI
+ from mautrix.client import Client
+ from mautrix.client.state_store import MemoryStateStore, MemorySyncStore
+ if not self._homeserver:
+ logger.error("Matrix: homeserver URL not configured")
+ return False
+ # Resolved here, inside the profile scope, so multiplexed profiles never share it.
+ self._resolve_store_dir().mkdir(parents=True, exist_ok=True)
+ client_session = _create_matrix_session(self._proxy_url)
+ api = HTTPAPI(base_url=self._homeserver, token=self._access_token or "", client_session=client_session)
+ state_store = MemoryStateStore()
+ sync_store = MemorySyncStore()
+ client = Client(
+ mxid=UserID(self._user_id) if self._user_id else UserID(""),
+ device_id=self._device_id or None, api=api, state_store=state_store,
+ sync_store=sync_store,
+ )
+ self._client = client
+ if not await self._connect_authenticate(client, api):
+ return False
+ if self._encryption and not await self._connect_setup_e2ee(client, api, state_store):
+ return False
+ from mautrix.client import InternalEventType as IntEvt
+ from mautrix.client.dispatcher import MembershipEventDispatcher
+ client.add_dispatcher(MembershipEventDispatcher) # without this INVITE never fires
+ client.add_event_handler(EventType.ROOM_MESSAGE, self._on_room_message, wait_sync=True)
+ client.add_event_handler(EventType.REACTION, self._on_reaction, wait_sync=True)
+ client.add_event_handler(IntEvt.INVITE, self._on_invite, wait_sync=True)
+ self._startup_ts = time.time()
+ # Reset the clock-skew detector per connect so a reconnect after an NTP fix starts clean.
+ self._late_grace_drops = 0
+ self._late_grace_skew = 0.0
+ self._clock_skew_warned = False
+ self._closing = False
+ await self._connect_initial_sync(client)
if self._encryption and getattr(client, "crypto", None):
try:
await client.crypto.share_keys()
except Exception as exc:
logger.warning("Matrix: initial key share failed: %s", exc)
-
- # Start the sync loop.
self._sync_task = asyncio.create_task(self._sync_loop())
self._mark_connected()
- # Plugin-registered native handlers (Matrix client — event callbacks).
- self._wire_plugin_handlers(self._client)
+ self._wire_plugin_handlers(self._client) # plugin-registered native handlers
return True
async def disconnect(self) -> None:
"""Disconnect from Matrix."""
self._closing = True
-
if self._sync_task and not self._sync_task.done():
self._sync_task.cancel()
try:
await self._sync_task
except (asyncio.CancelledError, Exception):
pass
-
- invite_join_tasks = list(self._invite_join_tasks.values())
- for task in invite_join_tasks:
- if not task.done():
- task.cancel()
- if invite_join_tasks:
- await asyncio.gather(*invite_join_tasks, return_exceptions=True)
+ for tasks in (self._invite_join_tasks.values(), self._reaction_redaction_tasks):
+ pending = list(tasks)
+ for task in pending:
+ if not task.done():
+ task.cancel()
+ if pending:
+ await asyncio.gather(*pending, return_exceptions=True)
self._invite_join_tasks.clear()
-
- redaction_tasks = list(self._reaction_redaction_tasks)
- for task in redaction_tasks:
- if not task.done():
- task.cancel()
- if redaction_tasks:
- await asyncio.gather(*redaction_tasks, return_exceptions=True)
self._reaction_redaction_tasks.clear()
-
- # Close the SQLite crypto store database.
if hasattr(self, "_crypto_db") and self._crypto_db:
try:
await self._crypto_db.stop()
except Exception as exc:
logger.debug("Matrix: could not close crypto DB on disconnect: %s", exc)
-
if self._client:
try:
await self._client.api.session.close()
except Exception:
pass
self._client = None
-
logger.info("Matrix: disconnected")
async def send(
- self,
- chat_id: str,
- content: str,
- reply_to: Optional[str] = None,
+ self, chat_id: str, content: str, reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Send a message to a Matrix room."""
-
if not content:
return SendResult(success=True)
-
formatted = self.format_message(content)
chunks = self.truncate_message(formatted, self.max_message_length)
-
last_event_id = None
- for i, chunk in enumerate(chunks):
+ for chunk in chunks:
msg_content = self._build_text_message_content(chunk)
-
self._apply_relation_metadata(msg_content, reply_to=reply_to, metadata=metadata)
-
try:
- event_id = await asyncio.wait_for(
- self._client.send_message_event(
- RoomID(chat_id),
- EventType.ROOM_MESSAGE,
- msg_content,
- ),
- timeout=45,
- )
- last_event_id = str(event_id)
+ last_event_id = await self._send_room_message(chat_id, msg_content)
logger.info("Matrix: sent event %s to %s", last_event_id, chat_id)
except Exception as exc:
# On E2EE errors, retry after sharing keys.
if self._encryption and getattr(self._client, "crypto", None):
try:
await self._client.crypto.share_keys()
- event_id = await asyncio.wait_for(
- self._client.send_message_event(
- RoomID(chat_id),
- EventType.ROOM_MESSAGE,
- msg_content,
- ),
- timeout=45,
- )
- last_event_id = str(event_id)
- logger.info(
- "Matrix: sent event %s to %s (after key share)",
- last_event_id,
- chat_id,
- )
+ last_event_id = await self._send_room_message(chat_id, msg_content)
+ logger.info("Matrix: sent event %s to %s (after key share)", last_event_id, chat_id)
continue
except Exception as retry_exc:
- logger.error(
- "Matrix: failed to send to %s after retry: %s",
- chat_id,
- retry_exc,
- )
+ logger.error("Matrix: failed to send to %s after retry: %s", chat_id, retry_exc)
return SendResult(success=False, error=str(retry_exc))
logger.error("Matrix: failed to send to %s: %s", chat_id, exc)
return SendResult(success=False, error=str(exc))
-
return SendResult(success=True, message_id=last_event_id)
+ async def _send_room_message(self, chat_id: str, msg_content: Dict[str, Any]) -> str:
+ """Send one m.room.message event (45s cap) and return its event ID as str."""
+ event_id = await asyncio.wait_for(
+ self._client.send_message_event(RoomID(chat_id), EventType.ROOM_MESSAGE, msg_content),
+ timeout=45,
+ )
+ return str(event_id)
+
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
"""Return room name and type (dm/group)."""
identity = await self._resolve_room_identity(chat_id)
@@ -2290,10 +1679,8 @@ class MatrixAdapter(BasePlatformAdapter):
"platform": "matrix",
"homeserver": self._homeserver,
"auth": {
- "access_token_present": token_present,
- "password_present": bool(self._password),
- "token_preview": "***" if token_present else "",
- "user_id": user_id,
+ "access_token_present": token_present, "password_present": bool(self._password),
+ "token_preview": "***" if token_present else "", "user_id": user_id,
"device_id_present": bool(device_id),
"device_id_preview": _redact_matrix_value(device_id),
},
@@ -2305,13 +1692,10 @@ class MatrixAdapter(BasePlatformAdapter):
),
},
"e2ee": {
- "mode": self._e2ee_mode,
- "enabled": bool(self._encryption),
+ "mode": self._e2ee_mode, "enabled": bool(self._encryption),
"deps_available": _check_e2ee_deps(),
"crypto_store_path": str(self._crypto_db_path),
- "recovery_key_configured": bool(
- _scoped_recovery_key().strip()
- ),
+ "recovery_key_configured": bool(_scoped_recovery_key().strip()),
},
"policy": {
"allowed_user_count": len(self._allowed_user_ids),
@@ -2321,21 +1705,16 @@ class MatrixAdapter(BasePlatformAdapter):
"free_response_room_count": len(self._free_rooms),
"allow_room_mentions": self._allow_room_mentions,
"process_notices": self._process_notices,
- "allow_public_rooms": os.getenv("MATRIX_ALLOW_PUBLIC_ROOMS", "").lower()
- in ("true", "1", "yes"),
- },
- "media": {
- "max_media_bytes": self._max_media_bytes,
+ "allow_public_rooms": _env_truthy("MATRIX_ALLOW_PUBLIC_ROOMS"),
},
+ "media": {"max_media_bytes": self._max_media_bytes},
}
# ------------------------------------------------------------------
# Optional overrides
# ------------------------------------------------------------------
- async def send_typing(
- self, chat_id: str, metadata: Optional[Dict[str, Any]] = None
- ) -> None:
+ async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Send a typing indicator."""
if self._client:
try:
@@ -2351,145 +1730,93 @@ class MatrixAdapter(BasePlatformAdapter):
except Exception:
pass
-
async def edit_message(
self, chat_id: str, message_id: str, content: str, *, finalize: bool = False
) -> SendResult:
"""Edit an existing message (via m.replace)."""
-
formatted = self.format_message(content)
new_content = self._build_text_message_content(formatted)
msg_content: Dict[str, Any] = {
- "msgtype": "m.text",
- "body": f"* {formatted}",
- "m.new_content": new_content,
+ "msgtype": "m.text", "body": f"* {formatted}", "m.new_content": new_content,
}
if "m.mentions" in new_content:
msg_content["m.mentions"] = new_content["m.mentions"]
if "formatted_body" in new_content:
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,
- }
-
- try:
- event_id = await self._client.send_message_event(
- RoomID(chat_id),
- EventType.ROOM_MESSAGE,
- msg_content,
- )
- return SendResult(success=True, message_id=str(event_id))
- except Exception as exc:
- return SendResult(success=False, error=str(exc))
+ msg_content["m.relates_to"] = {"rel_type": "m.replace", "event_id": message_id}
+ return await self._send_content_event(chat_id, msg_content)
async def send_image(
- self,
- chat_id: str,
- image_url: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, image_url: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Download an image URL and upload it to Matrix."""
from tools.url_safety import is_safe_url
-
if not is_safe_url(image_url):
logger.warning("Matrix: blocked unsafe image URL (SSRF protection)")
- return await super().send_image(
- chat_id, image_url, caption, reply_to, metadata=metadata
- )
-
+ return await super().send_image(chat_id, image_url, caption, reply_to, metadata=metadata)
try:
data, ct, fname = await self._download_external_media_with_cap(image_url)
except Exception as exc:
- logger.warning(
- "Matrix: failed to download image %s: %s",
- _redact_url_for_log(image_url),
- exc,
- )
+ logger.warning("Matrix: failed to download image %s: %s", _redact_url_for_log(image_url), exc)
fallback = (
"I couldn't download and upload the image to Matrix. "
"The source URL was not shown because it may contain private tokens."
)
if caption:
fallback = f"{caption}\n{fallback}"
- return await self.send(
- chat_id,
- fallback,
- reply_to,
- )
-
- return await self._upload_and_send(
- chat_id, data, fname, ct, "m.image", caption, reply_to, metadata
- )
+ return await self.send(chat_id, fallback, reply_to)
+ return await self._upload_and_send(chat_id, data, fname, ct, "m.image", caption, reply_to, metadata)
async def _download_external_media_with_cap(self, url: str) -> tuple[bytes, str, str]:
"""Download external media while enforcing redirect safety and size caps."""
from tools.url_safety import is_safe_url
-
if not is_safe_url(url):
raise ValueError("blocked unsafe media URL")
- def _check_content_length(headers: Any) -> None:
+ async def _read_capped(resp, chunks, content_type) -> tuple[bytes, str]:
+ """Enforce Content-Length + streamed size caps, then require an image/* type."""
raw = None
try:
- raw = headers.get("Content-Length") or headers.get("content-length")
+ raw = resp.headers.get("Content-Length") or resp.headers.get("content-length")
except Exception:
raw = None
- if raw is None:
- return
- try:
- size = int(raw)
- except (TypeError, ValueError):
- return
- if size > self._max_media_bytes:
- raise ValueError(
- f"media exceeds Matrix limit ({size} > {self._max_media_bytes} bytes)"
- )
-
- def _check_image_content_type(content_type: str) -> str:
+ if raw is not None:
+ try:
+ size = int(raw)
+ except (TypeError, ValueError):
+ size = None
+ if size is not None and size > self._max_media_bytes:
+ raise ValueError(f"media exceeds Matrix limit ({size} > {self._max_media_bytes} bytes)")
+ parts: list[bytes] = []
+ total = 0
+ async for chunk in chunks:
+ total += len(chunk)
+ if total > self._max_media_bytes:
+ raise ValueError(f"media exceeds Matrix limit (> {self._max_media_bytes} bytes)")
+ parts.append(bytes(chunk))
content_type = str(content_type or "").split(";", 1)[0].strip().lower()
if not content_type.startswith("image/"):
raise ValueError("external media is not an image")
- return content_type
-
- def _append_chunk(parts: list[bytes], total: int, chunk: bytes) -> int:
- total += len(chunk)
- if total > self._max_media_bytes:
- raise ValueError(
- f"media exceeds Matrix limit (> {self._max_media_bytes} bytes)"
- )
- parts.append(chunk)
- return total
-
+ return b"".join(parts), content_type
fname = url.rsplit("/", 1)[-1].split("?")[0] or "image.png"
def _safe_redirect_target(current_url: str, location: str) -> str:
- """Resolve a redirect Location and re-validate it against SSRF policy.
-
- A public-looking URL can 302-redirect the gateway toward loopback,
- private-network, or cloud-metadata endpoints. Validating only the
- final URL is insufficient because the connection to the unsafe hop
- has already been made. Re-check every hop before following it.
- """
+ """Re-validate EVERY redirect hop: a public URL can 302 toward loopback/metadata
+ endpoints, and checking only the final URL is too late (the hop already connected)."""
next_url = urljoin(current_url, location)
if not is_safe_url(next_url):
raise ValueError("blocked unsafe redirect URL")
return next_url
-
try:
import aiohttp as _aiohttp
-
_sess_kw, _req_kw = proxy_kwargs_for_aiohttp(self._proxy_url)
async with _aiohttp.ClientSession(**_sess_kw) as http:
fetch_url = url
for _ in range(20):
async with http.get(
- fetch_url,
- timeout=_aiohttp.ClientTimeout(total=30),
- allow_redirects=False,
+ fetch_url, timeout=_aiohttp.ClientTimeout(total=30), allow_redirects=False,
**_req_kw,
) as resp:
if resp.status in {301, 302, 303, 307, 308}:
@@ -2499,67 +1826,42 @@ class MatrixAdapter(BasePlatformAdapter):
fetch_url = _safe_redirect_target(fetch_url, location)
continue
resp.raise_for_status()
- _check_content_length(resp.headers)
- parts: list[bytes] = []
- total = 0
- async for chunk in resp.content.iter_chunked(65536):
- total = _append_chunk(parts, total, bytes(chunk))
- ct = _check_image_content_type(
+ data, ct = await _read_capped(
+ resp, resp.content.iter_chunked(65536),
getattr(resp, "content_type", None)
- or resp.headers.get("content-type", "application/octet-stream")
+ or resp.headers.get("content-type", "application/octet-stream"),
)
- return b"".join(parts), ct, fname
+ return data, ct, fname
raise ValueError("too many redirects")
except ImportError:
from tools.url_safety import create_ssrf_safe_async_client
-
_httpx_kw: dict = {}
if self._proxy_url:
_httpx_kw["proxy"] = self._proxy_url
_httpx_kw["event_hooks"] = {"response": [_ssrf_redirect_guard]}
async with create_ssrf_safe_async_client(**_httpx_kw) as http:
- async with http.stream(
- "GET",
- url,
- follow_redirects=True,
- timeout=30,
- ) as resp:
+ async with http.stream("GET", url, follow_redirects=True, timeout=30) as resp:
resp.raise_for_status()
- _check_content_length(resp.headers)
- parts: list[bytes] = []
- total = 0
- async for chunk in resp.aiter_bytes():
- total = _append_chunk(parts, total, bytes(chunk))
- ct = _check_image_content_type(
- resp.headers.get("content-type", "application/octet-stream")
+ data, ct = await _read_capped(
+ resp, resp.aiter_bytes(), resp.headers.get("content-type", "application/octet-stream")
)
- return b"".join(parts), ct, fname
+ return data, ct, fname
async def send_image_file(
- self,
- chat_id: str,
- image_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, image_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a local image file to Matrix."""
- return await self._send_local_file(
- chat_id, image_path, "m.image", caption, reply_to, metadata=metadata
- )
+ return await self._send_local_file(chat_id, image_path, "m.image", caption, reply_to, metadata=metadata)
async def send_multiple_images(
- self,
- chat_id: str,
- images: list[tuple[str, str]],
- metadata: Optional[Dict[str, Any]] = None,
- human_delay: float = 0.0,
+ self, chat_id: str, images: list[tuple[str, str]],
+ metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0,
) -> None:
"""Send multiple Matrix images as one ordered logical batch."""
if not images:
return
from urllib.parse import unquote as _unquote
-
total = len(images)
for idx, (image_url, alt_text) in enumerate(images, start=1):
if human_delay > 0 and idx > 1:
@@ -2569,77 +1871,45 @@ class MatrixAdapter(BasePlatformAdapter):
caption = f"{caption} ({idx}/{total})"
if image_url.startswith("file://"):
result = await self.send_image_file(
- chat_id=chat_id,
- image_path=_unquote(image_url[7:]),
- caption=caption,
+ chat_id=chat_id, image_path=_unquote(image_url[7:]), caption=caption,
metadata=metadata,
)
else:
result = await self.send_image(
- chat_id=chat_id,
- image_url=image_url,
- caption=caption,
- metadata=metadata,
+ chat_id=chat_id, image_url=image_url, caption=caption, metadata=metadata,
)
if not result.success:
logger.warning("Matrix: failed to send image %d/%d: %s", idx, total, result.error)
async def send_document(
- self,
- chat_id: str,
- file_path: str,
- caption: Optional[str] = None,
- file_name: Optional[str] = None,
- reply_to: Optional[str] = None,
+ self, chat_id: str, file_path: str, caption: Optional[str] = None,
+ file_name: Optional[str] = None, reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a local file as a document."""
- return await self._send_local_file(
- chat_id, file_path, "m.file", caption, reply_to, file_name, metadata
- )
+ return await self._send_local_file(chat_id, file_path, "m.file", caption, reply_to, file_name, metadata)
async def send_voice(
- self,
- chat_id: str,
- audio_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, audio_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Upload an audio file as a voice message (MSC3245 native voice).
-
- Matrix voice bubbles require Opus in an Ogg container (MSC3245), but
- callers can reach this with any audio format — e.g. a model-invoked
- ``text_to_speech`` result routed through gateway media delivery, not
- just ``_send_voice_reply``. Enforce the codec at this boundary:
- transcode non-Ogg input to Ogg/Opus (best-effort — if ffmpeg is
- unavailable the original file is sent unchanged, preserving the
- previous behaviour).
+ """Upload audio as an MSC3245 voice message.
+
+ Voice bubbles need Ogg/Opus but callers pass any format (e.g. TTS output), so
+ transcode here — best-effort: without ffmpeg the original file is sent unchanged.
"""
converted_path: Optional[str] = None
send_path = audio_path
if not str(audio_path).lower().endswith((".ogg", ".oga", ".opus")):
- converted_path = await asyncio.to_thread(
- _matrix_transcode_voice_to_ogg, audio_path
- )
+ converted_path = await asyncio.to_thread(_matrix_transcode_voice_to_ogg, audio_path)
if converted_path:
send_path = converted_path
try:
return await self._send_local_file(
- chat_id,
- send_path,
- "m.audio",
- caption,
- reply_to,
- # keep the caller's basename (the temp transcode file has a
- # generated name) so the event body stays meaningful
- file_name=(
- Path(audio_path).with_suffix(".ogg").name
- if converted_path
- else None
- ),
- metadata=metadata,
- is_voice=True,
+ chat_id, send_path, "m.audio", caption, reply_to,
+ # keep the caller's basename (the temp transcode file has a generated name)
+ file_name=(Path(audio_path).with_suffix(".ogg").name if converted_path else None),
+ metadata=metadata, is_voice=True,
)
finally:
if converted_path:
@@ -2649,45 +1919,52 @@ class MatrixAdapter(BasePlatformAdapter):
pass
async def send_video(
- self,
- chat_id: str,
- video_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, video_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a video file."""
- return await self._send_local_file(
- chat_id, video_path, "m.video", caption, reply_to, metadata=metadata
- )
+ return await self._send_local_file(chat_id, video_path, "m.video", caption, reply_to, metadata=metadata)
- # Template attrs for the shared _format_exec_approval core. Matrix keeps
- # the smart-deny/scope wording in its local tail (reaction legend), so the
- # core is used for the header + fence + reason head only.
+ # Template attrs for the shared _format_exec_approval core (header + fence + reason only;
+ # the smart-deny/scope wording lives in the reaction legend below).
_EA_HEADER = "⚠️ **Dangerous command requires approval**\n"
_EA_CMD_BUDGET = 2000
+ async def _send_reaction_prompt(
+ self, chat_id: str, text: str, metadata: Optional[dict], make_prompt, registry: dict,
+ emojis, label: str,
+ ) -> SendResult:
+ """Send *text*, register ``make_prompt(message_id, requester, expires_at)`` under
+ the resulting event, then seed the bot's reaction controls (recording their IDs)."""
+ result = await self.send(chat_id, text, metadata=metadata)
+ if not result.success or not result.message_id:
+ return result
+ prompt = make_prompt(
+ result.message_id, str((metadata or {}).get("requester_user_id") or "") or None,
+ time.monotonic() + max(self._approval_timeout_seconds, 0),
+ )
+ registry[result.message_id] = prompt
+ for emoji in emojis:
+ try:
+ reaction_event_id = await self._send_reaction(chat_id, result.message_id, emoji)
+ if reaction_event_id:
+ prompt.bot_reaction_events[emoji] = str(reaction_event_id)
+ except Exception as exc:
+ logger.debug("Matrix: failed to add %s reaction %s: %s", label, emoji, exc)
+ return result
+
async def send_exec_approval(
- self,
- chat_id: str,
- command: str,
- session_key: str,
- description: str = "dangerous command",
- metadata: Optional[dict] = None,
- allow_permanent: bool = True,
- allow_session: bool = True,
+ self, chat_id: str, command: str, session_key: str, description: str = "dangerous command",
+ metadata: Optional[dict] = None, allow_permanent: bool = True, allow_session: bool = True,
smart_denied: bool = False,
) -> SendResult:
"""Send a reaction-based exec approval prompt for Matrix."""
if not self._client:
return SendResult(success=False, error="Not connected")
-
- requester_user_id = str((metadata or {}).get("requester_user_id") or "") or None
scope_choices = ""
if smart_denied:
scope_choices = "Smart DENY: owner override applies to this one operation only.\n"
else:
- scope_choices = ""
if allow_session:
scope_choices += "Reply `!approve session` to approve this pattern for the session, "
if allow_permanent:
@@ -2704,55 +1981,33 @@ class MatrixAdapter(BasePlatformAdapter):
"You can also click the reaction to approve:\n"
+ "\n".join(reaction_legend_parts)
)
-
- result = await self.send(chat_id, text, metadata=metadata)
- if not result.success or not result.message_id:
- return result
-
- prompt = _MatrixApprovalPrompt(
- session_key=session_key,
- chat_id=chat_id,
- message_id=result.message_id,
- requester_user_id=requester_user_id,
- expires_at=time.monotonic() + max(self._approval_timeout_seconds, 0),
- )
- old_event = self._approval_prompt_by_session.get(session_key)
- if old_event:
- self._approval_prompts_by_event.pop(old_event, None)
- self._approval_prompts_by_event[result.message_id] = prompt
- self._approval_prompt_by_session[session_key] = result.message_id
-
if not allow_session:
reactions = ("✅", "❌")
elif not allow_permanent:
reactions = ("✅", "🌀", "❌")
else:
reactions = ("✅", "🌀", "♾️", "❌")
- for emoji in reactions:
- try:
- reaction_result = await self._send_reaction(chat_id, result.message_id, emoji)
- # Save the bot's reaction event_id for later cleanup
- if reaction_result:
- prompt.bot_reaction_events[emoji] = str(reaction_result)
- except Exception as exc:
- logger.debug("Matrix: failed to add approval reaction %s: %s", emoji, exc)
- return result
+ def _make(message_id, requester, expires_at):
+ old_event = self._approval_prompt_by_session.get(session_key)
+ if old_event:
+ self._approval_prompts_by_event.pop(old_event, None)
+ self._approval_prompt_by_session[session_key] = message_id
+ return _MatrixApprovalPrompt(
+ session_key=session_key, chat_id=chat_id, message_id=message_id,
+ requester_user_id=requester, expires_at=expires_at,
+ )
+ return await self._send_reaction_prompt(
+ chat_id, text, metadata, _make, self._approval_prompts_by_event, reactions, "approval"
+ )
async def send_model_picker(
- self,
- chat_id: str,
- providers: list,
- current_model: str,
- current_provider: str,
- session_key: str,
- on_model_selected,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, providers: list, current_model: str, current_provider: str,
+ session_key: str, on_model_selected, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Send a Matrix reaction-based model picker."""
if not self._client:
return SendResult(success=False, error="Not connected")
-
flat_choices: list[tuple[str, str, str, str]] = []
for provider in providers or []:
provider_slug = str(provider.get("slug") or "")
@@ -2761,82 +2016,42 @@ class MatrixAdapter(BasePlatformAdapter):
for model_id in models:
if len(flat_choices) >= len(_MATRIX_MODEL_PICKER_REACTIONS):
break
- flat_choices.append((
- _MATRIX_MODEL_PICKER_REACTIONS[len(flat_choices)],
- str(model_id),
- provider_slug,
- provider_name,
- ))
+ flat_choices.append(
+ (_MATRIX_MODEL_PICKER_REACTIONS[len(flat_choices)], str(model_id), provider_slug, provider_name)
+ )
if len(flat_choices) >= len(_MATRIX_MODEL_PICKER_REACTIONS):
break
-
if not flat_choices:
- return await self.send(
- chat_id,
- "No authenticated models are available for this session.",
- metadata=metadata,
- )
-
+ return await self.send(chat_id, "No authenticated models are available for this session.", metadata=metadata)
try:
from hermes_cli.providers import get_label
provider_label = get_label(current_provider)
except Exception:
provider_label = current_provider
-
lines = [
- "⚙ **Model Configuration**",
- f"Current model: `{current_model or 'unknown'}`",
- f"Provider: {provider_label or 'unknown'}",
- "",
- "React to choose a model:",
+ "⚙ **Model Configuration**", f"Current model: `{current_model or 'unknown'}`",
+ f"Provider: {provider_label or 'unknown'}", "", "React to choose a model:",
]
choices: dict[str, tuple[str, str]] = {}
for emoji, model_id, provider_slug, provider_name in flat_choices:
choices[emoji] = (model_id, provider_slug)
lines.append(f"{emoji} `{model_id}` — {provider_name}")
-
- result = await self.send(chat_id, "\n".join(lines), metadata=metadata)
- if not result.success or not result.message_id:
- return result
-
- prompt = _MatrixModelPickerPrompt(
- chat_id=chat_id,
- message_id=result.message_id,
- session_key=session_key,
- choices=choices,
- on_model_selected=on_model_selected,
- requester_user_id=str((metadata or {}).get("requester_user_id") or "") or None,
- expires_at=time.monotonic() + max(self._approval_timeout_seconds, 0),
+ return await self._send_reaction_prompt(
+ chat_id, "\n".join(lines), metadata,
+ lambda message_id, requester, expires_at: _MatrixModelPickerPrompt(
+ chat_id=chat_id, message_id=message_id, session_key=session_key, choices=choices,
+ on_model_selected=on_model_selected, requester_user_id=requester, expires_at=expires_at,
+ ),
+ self._model_picker_prompts_by_event, choices, "model picker",
)
- self._model_picker_prompts_by_event[result.message_id] = prompt
-
- for emoji in choices:
- try:
- reaction_event_id = await self._send_reaction(chat_id, result.message_id, emoji)
- if reaction_event_id:
- prompt.bot_reaction_events[emoji] = str(reaction_event_id)
- except Exception as exc:
- logger.debug("Matrix: failed to add model picker reaction %s: %s", emoji, exc)
-
- return result
async def send_choice_picker(
- self,
- chat_id: str,
- title: str,
- choices: list,
- session_key: str,
- on_choice_selected,
+ self, chat_id: str, title: str, choices: list, session_key: str, on_choice_selected,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Send a Matrix reaction-based choice picker (/reasoning, /fast).
-
- Generic single-level companion to ``send_model_picker``. Each choice
- dict: ``{"value": str, "label": str, "is_current": bool}``.
- """
+ """Reaction-based choice picker (/reasoning, /fast); choice = {value, label, is_current}."""
if not self._client:
return SendResult(success=False, error="Not connected")
-
emoji_choices: dict[str, str] = {}
lines = [title, ""]
for i, choice in enumerate(choices):
@@ -2849,67 +2064,35 @@ class MatrixAdapter(BasePlatformAdapter):
label = f"{label} ← current"
emoji_choices[emoji] = value
lines.append(f"{emoji} {label}")
-
if not emoji_choices:
return SendResult(success=False, error="No choices")
-
- lines.append("")
- lines.append("React to choose.")
- result = await self.send(chat_id, "\n".join(lines), metadata=metadata)
- if not result.success or not result.message_id:
- return result
-
- prompt = _MatrixChoicePickerPrompt(
- chat_id=chat_id,
- message_id=result.message_id,
- session_key=session_key,
- choices=emoji_choices,
- on_choice_selected=on_choice_selected,
- requester_user_id=str((metadata or {}).get("requester_user_id") or "") or None,
- expires_at=time.monotonic() + max(self._approval_timeout_seconds, 0),
+ lines += ["", "React to choose."]
+ return await self._send_reaction_prompt(
+ chat_id, "\n".join(lines), metadata,
+ lambda message_id, requester, expires_at: _MatrixChoicePickerPrompt(
+ chat_id=chat_id, message_id=message_id, session_key=session_key, choices=emoji_choices,
+ on_choice_selected=on_choice_selected, requester_user_id=requester, expires_at=expires_at,
+ ),
+ self._choice_picker_prompts_by_event, emoji_choices, "choice picker",
)
- self._choice_picker_prompts_by_event[result.message_id] = prompt
-
- for emoji in emoji_choices:
- try:
- reaction_event_id = await self._send_reaction(chat_id, result.message_id, emoji)
- if reaction_event_id:
- prompt.bot_reaction_events[emoji] = str(reaction_event_id)
- except Exception as exc:
- logger.debug("Matrix: failed to add choice picker reaction %s: %s", emoji, exc)
-
- return result
def format_message(self, content: str) -> str:
- """Pass-through — Matrix supports standard Markdown natively."""
- # Strip image markdown; media is uploaded separately.
- content = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"\2", content)
- return content
+ """Markdown passes through; strip image markdown (media is uploaded separately)."""
+ return re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"\2", content)
# ------------------------------------------------------------------
# File helpers
# ------------------------------------------------------------------
async def _upload_and_send(
- self,
- room_id: str,
- data: bytes,
- filename: str,
- content_type: str,
- msgtype: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- is_voice: bool = False,
+ self, room_id: str, data: bytes, filename: str, content_type: str, msgtype: str,
+ caption: Optional[str] = None, reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None, is_voice: bool = False,
voice_metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload bytes to Matrix and send as a media message."""
if len(data) > self._max_media_bytes:
- return SendResult(
- success=False,
- error=f"Media file exceeds Matrix limit ({len(data)} > {self._max_media_bytes} bytes)",
- )
-
+ return self._media_too_large(len(data))
upload_data = data
encrypted_file = None
if self._encryption and getattr(self._client, "crypto", None):
@@ -2926,27 +2109,16 @@ class MatrixAdapter(BasePlatformAdapter):
except Exception as exc:
logger.error("Matrix: attachment encryption failed: %s", exc)
return SendResult(success=False, error=str(exc))
-
- # Upload to homeserver.
try:
mxc_url = await self._client.upload_media(
- upload_data,
- mime_type=content_type,
- filename=filename,
- size=len(upload_data),
+ upload_data, mime_type=content_type, filename=filename, size=len(upload_data),
)
except Exception as exc:
logger.error("Matrix: upload failed: %s", exc)
return SendResult(success=False, error=str(exc))
-
- # Build media message content.
msg_content: Dict[str, Any] = {
- "msgtype": msgtype,
- "body": caption or filename,
- "info": {
- "mimetype": content_type,
- "size": len(data),
- },
+ "msgtype": msgtype, "body": caption or filename,
+ "info": {"mimetype": content_type, "size": len(data)},
}
if encrypted_file is not None:
file_payload = encrypted_file.serialize()
@@ -2954,66 +2126,47 @@ class MatrixAdapter(BasePlatformAdapter):
msg_content["file"] = file_payload
else:
msg_content["url"] = str(mxc_url)
-
- # Add MSC3245 voice flag for native voice messages.
- if is_voice:
+ if is_voice: # MSC3245 native voice flag + MSC1767 audio metadata
msg_content["org.matrix.msc3245.voice"] = {}
- duration = (voice_metadata or {}).get("duration")
- waveform = (voice_metadata or {}).get("waveform")
- if duration is not None:
- msg_content["info"]["duration"] = duration
- if duration is not None or waveform is not None:
- audio_metadata: Dict[str, Any] = {}
- if duration is not None:
- audio_metadata["duration"] = duration
- if waveform is not None:
- audio_metadata["waveform"] = waveform
+ audio_metadata = {
+ k: v for k in ("duration", "waveform") if (v := (voice_metadata or {}).get(k)) is not None
+ }
+ if "duration" in audio_metadata:
+ msg_content["info"]["duration"] = audio_metadata["duration"]
+ if audio_metadata:
msg_content["org.matrix.msc1767.audio"] = audio_metadata
-
self._apply_relation_metadata(msg_content, reply_to=reply_to, metadata=metadata)
+ return await self._send_content_event(room_id, msg_content)
+
+ def _media_too_large(self, size: int) -> SendResult:
+ return SendResult(success=False, error=f"Media file exceeds Matrix limit ({size} > {self._max_media_bytes} bytes)")
+ async def _send_content_event(self, room_id: str, msg_content: Dict[str, Any]) -> SendResult:
+ """Send a prebuilt m.room.message payload, mapping exceptions to SendResult."""
try:
- event_id = await self._client.send_message_event(
- RoomID(room_id),
- EventType.ROOM_MESSAGE,
- msg_content,
- )
+ event_id = await self._client.send_message_event(RoomID(room_id), EventType.ROOM_MESSAGE, msg_content)
return SendResult(success=True, message_id=str(event_id))
except Exception as exc:
return SendResult(success=False, error=str(exc))
async def _send_local_file(
- self,
- room_id: str,
- file_path: str,
- msgtype: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- file_name: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- is_voice: bool = False,
+ self, room_id: str, file_path: str, msgtype: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, file_name: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None, is_voice: bool = False,
) -> SendResult:
"""Read a local file and upload it."""
p = Path(file_path).expanduser()
if not p.exists():
- # file_path is a host-local path; never echo it into chat.
- logger.warning(
- "[%s] upload fallback: media file not found for %s",
- self.name, file_path,
- )
- text = f"{caption}\n⚠️ Couldn't deliver the attachment." if caption \
- else "⚠️ Couldn't deliver the attachment."
- return await self.send(room_id, text, reply_to)
+ # file_path is host-local; never echo it into chat.
+ logger.warning("[%s] upload fallback: media file not found for %s", self.name, file_path)
+ text = "⚠️ Couldn't deliver the attachment."
+ return await self.send(room_id, f"{caption}\n{text}" if caption else text, reply_to)
try:
file_size = p.stat().st_size
except OSError:
file_size = 0
if file_size > self._max_media_bytes:
- return SendResult(
- success=False,
- error=f"Media file exceeds Matrix limit ({file_size} > {self._max_media_bytes} bytes)",
- )
-
+ return self._media_too_large(file_size)
fname = file_name or p.name
ct = mimetypes.guess_type(fname)[0] or "application/octet-stream"
data = p.read_bytes()
@@ -3024,18 +2177,8 @@ class MatrixAdapter(BasePlatformAdapter):
if is_voice
else None
)
-
return await self._upload_and_send(
- room_id,
- data,
- fname,
- ct,
- msgtype,
- caption,
- reply_to,
- metadata,
- is_voice,
- voice_metadata,
+ room_id, data, fname, ct, msgtype, caption, reply_to, metadata, is_voice, voice_metadata
)
# ------------------------------------------------------------------
@@ -3045,76 +2188,43 @@ class MatrixAdapter(BasePlatformAdapter):
async def _sync_loop(self) -> None:
"""Continuously sync with the homeserver."""
client = self._client
- # Resume from the token stored during the initial sync.
- next_batch = await client.sync_store.get_next_batch()
+ next_batch = await client.sync_store.get_next_batch() # resume from the initial sync
while not self._closing:
try:
- # Wrap in asyncio.wait_for to guard against TCP-level hangs
- # that the Matrix long-poll timeout cannot catch. Long-poll
- # is 30s, so 45s gives 15s slack for network drain.
- sync_data = await asyncio.wait_for(
- client.sync(
- since=next_batch,
- timeout=30000,
- ),
- timeout=45.0,
- )
-
- # nio returns SyncError objects (not exceptions) for auth
- # failures like M_UNKNOWN_TOKEN. Detect and stop immediately.
+ # 45s outer cap guards TCP-level hangs the 30s long-poll timeout can't catch.
+ sync_data = await asyncio.wait_for(client.sync(since=next_batch, timeout=30000), timeout=45.0)
+ # Auth failures (M_UNKNOWN_TOKEN) arrive as SyncError objects, not exceptions.
_sync_msg = getattr(sync_data, "message", None)
if _sync_msg and isinstance(_sync_msg, str):
_lower = _sync_msg.lower()
if "m_unknown_token" in _lower or "unknown_token" in _lower:
- logger.error(
- "Matrix: permanent auth error from sync: %s — stopping",
- _sync_msg,
- )
+ logger.error("Matrix: permanent auth error from sync: %s — stopping", _sync_msg)
return
-
if isinstance(sync_data, dict):
self._last_sync_ts = time.time()
- # Update joined rooms from sync response.
rooms_join = sync_data.get("rooms", {}).get("join", {})
if rooms_join:
self._joined_rooms.update(rooms_join.keys())
self._room_identities.clear()
self._room_identity_cached_at.clear()
-
- # Advance the sync token so the next request is
- # incremental instead of a full initial sync.
nb = sync_data.get("next_batch")
if nb:
next_batch = nb
await client.sync_store.put_next_batch(nb)
-
- # Dispatch events to registered handlers so that
- # _on_room_message / _on_reaction / _on_invite fire.
try:
await self._dispatch_sync(sync_data)
except Exception as exc:
logger.warning("Matrix: sync event dispatch error: %s", exc)
self._schedule_pending_invite_joins(sync_data)
- # Let freshly scheduled invite joins start before the next
- # sync iteration without waiting for slow or stuck joins.
- await asyncio.sleep(0)
-
+ await asyncio.sleep(0) # let fresh invite joins start before the next sync
except asyncio.CancelledError:
return
except Exception as exc:
if self._closing:
return
- # Detect permanent auth/permission failures.
err_str = str(exc).lower()
- if (
- "401" in err_str
- or "403" in err_str
- or "unauthorized" in err_str
- or "forbidden" in err_str
- ):
- logger.error(
- "Matrix: permanent auth error: %s — stopping sync", exc
- )
+ if any(k in err_str for k in ("401", "403", "unauthorized", "forbidden")):
+ logger.error("Matrix: permanent auth error: %s — stopping sync", exc)
return
logger.warning("Matrix: sync error: %s — retrying in 5s", exc)
await asyncio.sleep(5)
@@ -3132,32 +2242,17 @@ class MatrixAdapter(BasePlatformAdapter):
if inspect.isawaitable(tasks):
tasks = await tasks
if tasks:
- # return_exceptions=True so one failing event handler doesn't abort
- # the whole gather and silently drop the SIBLING events in the same
- # sync response (a bare gather re-raises the first exception, leaving
- # the rest of the batch unprocessed). Mirrors the invite/redaction
- # gathers above. Surface each failure instead of swallowing it.
+ # return_exceptions=True: one failing handler must not drop its SIBLING events.
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
- logger.warning(
- "Matrix: event handler failed during sync dispatch: %s",
- result,
- )
+ logger.warning("Matrix: event handler failed during sync dispatch: %s", result)
def _is_self_sender(self, sender: str) -> bool:
- """Return True if the sender refers to the bot's own account.
-
- Matrix user IDs are byte-compared after trimming whitespace and
- lowercasing — some homeservers normalize the localpart case
- differently at different API surfaces, and the reply-loop tail
- of the "hall of mirrors" bug (#15763) has been observed with the
- bot's own account bypassing a case-sensitive equality check.
-
- When ``self._user_id`` is empty (whoami hasn't resolved yet, or
- login failed), we cannot prove a sender is NOT us, so we return
- True defensively — an unidentified bot dropping its own events
- is always preferable to falling into an echo loop.
+ """True if *sender* is the bot itself (case-insensitive: homeservers vary localpart case).
+
+ With no resolved user_id we can't prove a sender is NOT us, so return True — dropping
+ our own events beats an echo loop ("hall of mirrors").
"""
own = (self._user_id or "").strip().lower()
if not own:
@@ -3166,31 +2261,14 @@ class MatrixAdapter(BasePlatformAdapter):
@staticmethod
def _is_system_or_bridge_sender(sender: str) -> bool:
- """Return True if the sender looks like a system / bridge / appservice
- identity rather than a real user.
-
- Appservice namespaces on Matrix conventionally prefix bot / puppet
- user IDs with an underscore (e.g. ``@_telegram_12345:server``,
- ``@_discord_999:server``, ``@_slack_...:server``). Server-notices
- bots and bridge-controller bots on many homeservers use the same
- pattern.
-
- We treat these as system identities for pairing purposes: they
- should never be offered a pairing code, because an operator
- approving the code would hand the bridge itself permanent
- authorization — and every outbound message relayed by the bridge
- would then loop back into the agent as an "authorized user
- message", which is the root of issue #15763.
-
- Matches:
- ``@_something:server`` — appservice namespace convention
- ``@:server`` — malformed / empty localpart
- ``:server`` — malformed, no leading ``@``
+ """True for appservice/bridge/system identities (``@_telegram_123:server``) or malformed IDs.
+
+ Never offer these a pairing code: an approved bridge would relay every outbound
+ message back as an "authorized user message" (echo loop).
"""
s = (sender or "").strip()
if not s:
return True
- # Localpart is everything between leading '@' and ':'
if s.startswith("@"):
s = s[1:]
if ":" in s:
@@ -3210,209 +2288,128 @@ class MatrixAdapter(BasePlatformAdapter):
return not self._allowed_room_ids or room_id in self._allowed_room_ids
async def _is_allowed_matrix_room_event(self, room_id: str) -> bool:
- """Return True when a room event may proceed past intake filters.
-
- MATRIX_ALLOWED_ROOMS constrains shared rooms. Matrix DMs are exempt so
- personal chats still work when operators use a room allowlist for
- project rooms.
- """
+ """MATRIX_ALLOWED_ROOMS gate; DMs are exempt so personal chats survive a project allowlist."""
if self._is_allowed_matrix_room(room_id):
return True
try:
return await self._is_dm_room(room_id)
except Exception as exc:
- logger.debug(
- "Matrix: could not resolve room identity for allowlist check in %s: %s",
- room_id,
- exc,
- )
+ logger.debug("Matrix: could not resolve room identity for allowlist check in %s: %s", room_id, exc)
return False
+ def _note_late_grace_drop(self, event_ts: float) -> None:
+ """Clock-skew heuristic for grace-check drops well after startup (#12614).
+
+ A host clock set ahead of real time makes every live event look "older
+ than startup" and the bot silently never replies. Warn once when drops
+ keep happening >30s after startup with a *consistent* skew — a constant
+ offset, unlike backfill from a freshly invited room whose event ages
+ vary widely and reset the counter.
+ """
+ if self._clock_skew_warned or time.time() - self._startup_ts <= 30:
+ return
+ skew = self._startup_ts - event_ts
+ if not (5 < skew < 86400): # ignore malformed/absurd timestamps
+ return
+ if self._late_grace_drops and abs(skew - self._late_grace_skew) < 60:
+ self._late_grace_drops += 1
+ else:
+ self._late_grace_skew = skew
+ self._late_grace_drops = 1
+ if self._late_grace_drops >= 3:
+ logger.warning(
+ "Matrix: dropped %d consecutive live events as "
+ "'too old' more than 30s after startup (skew "
+ "≈ %.0fs). The host system clock is likely set "
+ "ahead of real time, which causes the startup "
+ "grace filter to silently discard every incoming "
+ "message. Run `timedatectl set-ntp true` (or "
+ "sync NTP) and restart the bot.",
+ self._late_grace_drops,
+ skew,
+ )
+ self._clock_skew_warned = True
+
async def _on_room_message(self, event: Any) -> None:
"""Handle incoming room message events (text, media)."""
room_id = str(getattr(event, "room_id", ""))
sender = str(getattr(event, "sender", ""))
-
- # Diagnostic: confirm the callback is firing at all when DEBUG is on.
- # Helps users troubleshoot silent inbound issues like #5819, #7914, #12614.
+ # DEBUG-level proof the callback fires at all (silent-inbound troubleshooting).
logger.debug(
- "Matrix: callback fired — event %s from %s in %s",
- getattr(event, "event_id", "?"),
- sender,
- room_id,
+ "Matrix: callback fired — event %s from %s in %s", getattr(event, "event_id", "?"), sender, room_id
)
-
- # Ignore own messages (case-insensitive; also drops when our own
- # user_id hasn't been resolved yet — see _is_self_sender docstring
- # and issue #15763).
if self._is_self_sender(sender):
return
-
- # Ignore appservice / bridge / system identities so they never
- # trigger the pairing flow. Once a bridge user is paired, every
- # outbound message it relays would loop back as an authorized
- # user message (the "hall of mirrors" in #15763).
+ # Bridge/system identities must never reach the pairing flow (echo loop once paired).
if self._is_system_or_bridge_sender(sender):
- logger.debug(
- "Matrix: ignoring system/bridge sender %s in %s",
- sender,
- room_id,
- )
+ logger.debug("Matrix: ignoring system/bridge sender %s in %s", sender, room_id)
return
if self._matches_ignored_user_pattern(sender):
- logger.debug(
- "Matrix: ignoring sender %s in %s due to configured ignore pattern",
- sender,
- room_id,
- )
+ logger.debug("Matrix: ignoring sender %s in %s due to configured ignore pattern", sender, room_id)
return
if not await self._is_allowed_matrix_room_event(room_id):
- logger.info(
- "Matrix: ignoring message from unauthorized room %s",
- room_id,
- )
+ logger.info("Matrix: ignoring message from unauthorized room %s", room_id)
return
-
- # Deduplicate by event ID.
event_id = str(getattr(event, "event_id", ""))
if self._is_duplicate_event(event_id):
return
-
- # Startup grace: ignore old messages from initial sync.
+ # Startup grace: ignore old messages replayed by the initial sync.
event_ts = _matrix_event_timestamp_seconds(event)
if event_ts and event_ts < self._startup_ts - _STARTUP_GRACE_SECONDS:
- # If we are well past startup but events are still being dropped
- # by the grace check, the host clock is probably set ahead of
- # real time — every live event then looks "older than startup".
- # Warn once so users can fix NTP instead of chasing a ghost.
- # See #12614 (Schnurzel700, April 2026).
- #
- # Filter out backfill (events legitimately old) by requiring:
- # - we are >30s past startup (initial-sync replay window closed)
- # - the skew is *consistent* across consecutive drops, which is
- # the signature of a constant clock offset rather than a
- # variable-age room history. Backfill from a freshly invited
- # room can deliver events spanning hours/days — those skews
- # will be all over the place and reset the counter.
- if not self._clock_skew_warned and (
- time.time() - self._startup_ts > 30
- ):
- skew = self._startup_ts - event_ts
- # Sanity bound: malformed events with negative or absurd
- # timestamps shouldn't count.
- if 5 < skew < 86400:
- if self._late_grace_drops == 0:
- self._late_grace_skew = skew
- self._late_grace_drops = 1
- elif abs(skew - self._late_grace_skew) < 60:
- # Consistent offset → likely real clock skew.
- self._late_grace_drops += 1
- else:
- # Varied skew → likely backfill, restart sampling.
- self._late_grace_skew = skew
- self._late_grace_drops = 1
- if self._late_grace_drops >= 3:
- logger.warning(
- "Matrix: dropped %d consecutive live events as "
- "'too old' more than 30s after startup (skew "
- "≈ %.0fs). The host system clock is likely set "
- "ahead of real time, which causes the startup "
- "grace filter to silently discard every incoming "
- "message. Run `timedatectl set-ntp true` (or "
- "sync NTP) and restart the bot.",
- self._late_grace_drops,
- skew,
- )
- self._clock_skew_warned = True
+ self._note_late_grace_drop(event_ts)
return
-
- # Extract content from the event.
content = getattr(event, "content", None)
if content is None:
return
-
- # Get msgtype — either from content object or raw dict.
if hasattr(content, "msgtype"):
msgtype = str(content.msgtype)
elif isinstance(content, dict):
msgtype = content.get("msgtype", "")
else:
msgtype = ""
-
- # Determine source content dict for relation/thread extraction.
if isinstance(content, dict):
source_content = content
elif hasattr(content, "serialize"):
source_content = content.serialize()
else:
source_content = {}
-
relates_to = source_content.get("m.relates_to", {})
-
- # Skip edits (m.replace relation).
- if relates_to.get("rel_type") == "m.replace":
+ if relates_to.get("rel_type") == "m.replace": # skip edits
return
-
- # Ignore m.notice to prevent bot-to-bot loops (m.notice is the
- # conventional msgtype for bot responses in the Matrix ecosystem).
+ # m.notice is the conventional bot-response msgtype; ignoring it prevents bot-to-bot loops.
if msgtype == "m.notice" and not self._process_notices:
return
-
- # Dispatch by msgtype.
- media_msgtypes = ("m.image", "m.audio", "m.video", "m.file")
- if msgtype in media_msgtypes:
+ if msgtype in ("m.image", "m.audio", "m.video", "m.file"):
await self._handle_media_message(
room_id, sender, event_id, event_ts, source_content, relates_to, msgtype
)
elif msgtype in ("m.text", "m.notice"):
- await self._handle_text_message(
- room_id, sender, event_id, event_ts, source_content, relates_to
- )
+ await self._handle_text_message(room_id, sender, event_id, event_ts, source_content, relates_to)
async def _resolve_message_context(
- self,
- room_id: str,
- sender: str,
- event_id: str,
- body: str,
- source_content: dict,
+ self, room_id: str, sender: str, event_id: str, body: str, source_content: dict,
relates_to: dict,
) -> Optional[tuple]:
- """Shared mention/thread/DM gating for text and media handlers.
-
- Returns (body, is_dm, chat_type, thread_id, display_name, source)
- or None if the message should be dropped (mention gating).
- """
+ """Shared mention/thread/DM gating. Returns (body, is_dm, chat_type, thread_id,
+ display_name, source) or None when the message should be dropped."""
identity = await self._resolve_room_identity(room_id)
is_dm = await self._is_dm_room(room_id)
chat_type = "dm" if is_dm else "group"
-
thread_id = None
if relates_to.get("rel_type") == "m.thread":
thread_id = relates_to.get("event_id")
-
formatted_body = source_content.get("formatted_body")
- # m.mentions.user_ids (MSC3952 / Matrix v1.7) — authoritative mention signal.
- mentions_block = source_content.get("m.mentions") or {}
- mention_user_ids = (
- mentions_block.get("user_ids") if isinstance(mentions_block, dict) else None
- )
+ mentions_block = source_content.get("m.mentions") or {} # MSC3952: authoritative signal
+ mention_user_ids = mentions_block.get("user_ids") if isinstance(mentions_block, dict) else None
is_mentioned = self._is_bot_mentioned(body, formatted_body, mention_user_ids)
-
- # Require-mention gating.
if not is_dm:
- # allowed_rooms check (whitelist — must pass before other gating).
- # When set, messages from rooms NOT in this whitelist are silently
- # ignored, even if @mentioned. DMs are already excluded above.
+ # Whitelist first: non-listed rooms are dropped even when @mentioned (DMs exempt).
if self._allowed_rooms and room_id not in self._allowed_rooms:
logger.debug(
- "Matrix: ignoring message %s in %s — room not in "
- "MATRIX_ALLOWED_ROOMS whitelist",
- event_id,
- room_id,
+ "Matrix: ignoring message %s in %s — room not in MATRIX_ALLOWED_ROOMS whitelist",
+ event_id, room_id,
)
return None
-
is_free_room = room_id in self._free_rooms
in_bot_thread = bool(thread_id and thread_id in self._threads)
is_command = body.startswith("/")
@@ -3421,37 +2418,23 @@ class MatrixAdapter(BasePlatformAdapter):
logger.debug(
"Matrix: ignoring message %s in %s — no @mention "
"(set MATRIX_REQUIRE_MENTION=false to disable)",
- event_id,
- room_id,
- )
- return None
-
- # Thread-level @mention gating: even in a bot-participated thread,
- # require @mention when thread_require_mention is enabled.
- # Prevents infinite reply loops in multi-agent shared rooms
- # where multiple bots all participate in the same thread.
- elif (self._thread_require_mention and in_bot_thread
- and not is_free_room):
- if not is_mentioned:
- logger.debug(
- "Matrix: ignoring message %s in thread %s — "
- "no @mention (thread_require_mention=true)",
- event_id,
- thread_id,
+ event_id, room_id,
)
return None
-
- # DM mention-thread.
+ # thread_require_mention: even inside a bot thread require @mention — prevents
+ # infinite reply loops when several bots share one thread.
+ elif self._thread_require_mention and in_bot_thread and not is_free_room and not is_mentioned:
+ logger.debug(
+ "Matrix: ignoring message %s in thread %s — no @mention (thread_require_mention=true)",
+ event_id, thread_id,
+ )
+ return None
if is_dm and not thread_id and self._dm_mention_threads and is_mentioned:
thread_id = event_id
self._threads.mark(thread_id)
-
- # Strip mention from body (only when mention-gating is active).
if is_mentioned and self._require_mention:
body = self._strip_mention(body)
-
- # Auto-thread/session-scope policy. Real Matrix thread roots are
- # preserved above; synthetic thread roots are policy-driven.
+ # Real thread roots are preserved above; synthetic roots follow session-scope policy.
if not thread_id:
if is_dm:
if self._dm_auto_thread:
@@ -3459,144 +2442,87 @@ class MatrixAdapter(BasePlatformAdapter):
self._threads.mark(thread_id)
elif self._matrix_session_scope == "room":
thread_id = None
- elif self._matrix_session_scope == "thread":
+ elif self._matrix_session_scope == "thread" or self._auto_thread:
thread_id = event_id
self._threads.mark(thread_id)
- elif self._auto_thread:
- thread_id = event_id
- self._threads.mark(thread_id)
-
display_name = await self._get_display_name(room_id, sender)
source = self.build_source(
- chat_id=room_id,
- chat_name=identity.display_name,
- chat_type=chat_type,
- user_id=sender,
- user_name=display_name,
- thread_id=thread_id,
- chat_topic=identity.room_topic,
- guild_id=identity.server_name,
- parent_chat_id=room_id if thread_id else None,
+ chat_id=room_id, chat_name=identity.display_name, chat_type=chat_type, user_id=sender,
+ user_name=display_name, thread_id=thread_id, chat_topic=identity.room_topic,
+ guild_id=identity.server_name, parent_chat_id=room_id if thread_id else None,
message_id=event_id,
)
-
if thread_id:
self._threads.mark(thread_id)
-
self._background_read_receipt(room_id, event_id)
-
return body, is_dm, chat_type, thread_id, display_name, source
- async def _handle_text_message(
- self,
- room_id: str,
- sender: str,
- event_id: str,
- event_ts: float,
- source_content: dict,
- relates_to: dict,
- ) -> None:
- """Process a text message event."""
- body = source_content.get("body", "") or ""
- if not body:
- return
- body = _normalize_matrix_bang_command(body)
+ async def _extract_reply_context(
+ self, room_id: str, body: str, relates_to: dict
+ ) -> tuple[str, Optional[str], Optional[str], Optional[str], Optional[str]]:
+ """Return (body, reply_to, reply_to_text, reply_to_author_id, reply_to_author_name).
- ctx = await self._resolve_message_context(
- room_id,
- sender,
- event_id,
- body,
- source_content,
- relates_to,
- )
- if ctx is None:
- return
- body, is_dm, chat_type, thread_id, display_name, source = ctx
-
- # Reply-to detection.
+ Captures the Matrix inline reply fallback (``> <@user:srv> text\\n\\nreply``)
+ BEFORE stripping it, so the prompt layer can render "[Replying to: ...]"
+ like Signal/Slack/Telegram do from their quote payloads.
+ """
reply_to = None
in_reply_to = relates_to.get("m.in_reply_to", {})
if in_reply_to:
reply_to = in_reply_to.get("event_id")
-
- # Capture the reply fallback BEFORE stripping it from body, so the
- # gateway prompt layer can render "[Replying to: \"<original>\"]".
- # Other adapters (Signal, Slack, Telegram) populate reply_to_text
- # from their quote payload; Matrix stores it inline as `> <@user:srv>
- # <text>\n\n<actual reply>` and discards it after stripping.
reply_to_text: Optional[str] = None
reply_to_author_id: Optional[str] = None
reply_to_author_name: Optional[str] = None
if reply_to and body.startswith("> "):
reply_to_text, reply_to_author_id = _extract_reply_fallback(body)
body = _strip_reply_fallback(body)
-
- # Resolve the replied-to author's display name when we have the
- # state_store available — falls back to the localpart otherwise.
+ # Resolve the replied-to author's display name (falls back to localpart).
if reply_to_author_id:
- reply_to_author_name = await self._get_display_name(
- room_id, reply_to_author_id
- )
+ reply_to_author_name = await self._get_display_name(room_id, reply_to_author_id)
+ return body, reply_to, reply_to_text, reply_to_author_id, reply_to_author_name
- # Re-run bang normalization after reply-fallback stripping so a quoted
- # reply whose actual content is a bang command (e.g. ``> quoted\n\n!model``)
- # is treated as a command, matching how ``/command`` is recognized below.
+ async def _handle_text_message(
+ self, room_id: str, sender: str, event_id: str, event_ts: float, source_content: dict,
+ relates_to: dict,
+ ) -> None:
+ """Process a text message event."""
+ body = source_content.get("body", "") or ""
+ if not body:
+ return
body = _normalize_matrix_bang_command(body)
-
- msg_type = MessageType.TEXT
- if body.startswith("/"):
- msg_type = MessageType.COMMAND
-
+ ctx = await self._resolve_message_context(room_id, sender, event_id, body, source_content, relates_to)
+ if ctx is None:
+ return
+ body, is_dm, chat_type, thread_id, display_name, source = ctx
+ body, reply_to, reply_to_text, reply_to_author_id, reply_to_author_name = (
+ await self._extract_reply_context(room_id, body, relates_to)
+ )
+ # Re-normalize after reply stripping so ``> quoted\n\n!model`` is still a command.
+ body = _normalize_matrix_bang_command(body)
+ msg_type = MessageType.COMMAND if body.startswith("/") else MessageType.TEXT
msg_event = MessageEvent(
- text=body,
- message_type=msg_type,
- source=source,
- raw_message=source_content,
- message_id=event_id,
- reply_to_message_id=reply_to,
- reply_to_text=reply_to_text,
- reply_to_author_id=reply_to_author_id,
- reply_to_author_name=reply_to_author_name,
- # Sender metadata at MessageEvent level — `source.user_name`
- # already carries this, but downstream code (e.g. the prompt
- # layer, ghost-context rendering) historically reads the
- # top-level fields. Mirror them so matrix matches signal/slack.
- user_id=sender,
- user_name=display_name,
+ text=body, message_type=msg_type, source=source, raw_message=source_content,
+ message_id=event_id, reply_to_message_id=reply_to, reply_to_text=reply_to_text,
+ reply_to_author_id=reply_to_author_id, reply_to_author_name=reply_to_author_name,
+ # Top-level sender fields mirror source.* — downstream prompt code reads them.
+ user_id=sender, user_name=display_name,
)
-
if msg_type == MessageType.TEXT and self._text_batch_delay_seconds > 0:
self._enqueue_text_event(msg_event)
else:
await self.handle_message(msg_event)
async def _handle_media_message(
- self,
- room_id: str,
- sender: str,
- event_id: str,
- event_ts: float,
- source_content: dict,
- relates_to: dict,
- msgtype: str,
+ self, room_id: str, sender: str, event_id: str, event_ts: float, source_content: dict,
+ relates_to: dict, msgtype: str,
) -> None:
"""Process a media message event (image, audio, video, file)."""
body = source_content.get("body", "") or ""
url = source_content.get("url", "")
if url and not str(url).startswith("mxc://"):
- logger.warning(
- "[Matrix] Rejecting inbound media %s with non-MXC URL",
- event_id,
- )
+ logger.warning("[Matrix] Rejecting inbound media %s with non-MXC URL", event_id)
return
-
- # Convert mxc:// to HTTP URL for downstream processing.
- http_url = ""
- if url and url.startswith("mxc://"):
- http_url = self._mxc_to_http(url)
-
- # Extract MIME type from content info.
+ http_url = self._mxc_to_http(url) if url and url.startswith("mxc://") else ""
content_info = source_content.get("info", {})
if not isinstance(content_info, dict):
content_info = {}
@@ -3608,240 +2534,120 @@ class MatrixAdapter(BasePlatformAdapter):
event_size_int = 0
if event_size_int and event_size_int > self._max_media_bytes:
logger.warning(
- "[Matrix] Rejecting oversized inbound media %s (%d > %d bytes)",
- event_id,
- event_size_int,
- self._max_media_bytes,
+ "[Matrix] Rejecting oversized inbound media %s (%d > %d bytes)", event_id,
+ event_size_int, self._max_media_bytes,
)
return
-
- # For encrypted media, the URL may be in file.url.
- file_content = source_content.get("file", {})
+ file_content = source_content.get("file", {}) # encrypted media carries file.url
if not url and isinstance(file_content, dict):
url = file_content.get("url", "") or ""
if url and not str(url).startswith("mxc://"):
- logger.warning(
- "[Matrix] Rejecting inbound encrypted media %s with non-MXC URL",
- event_id,
- )
+ logger.warning("[Matrix] Rejecting inbound encrypted media %s with non-MXC URL", event_id)
return
if url and url.startswith("mxc://"):
http_url = self._mxc_to_http(url)
-
- is_encrypted_media = bool(
- file_content and isinstance(file_content, dict) and file_content.get("url")
- )
-
- media_type = "application/octet-stream"
- msg_type = MessageType.DOCUMENT
- is_voice_message = False
-
- if msgtype == "m.image":
- msg_type = MessageType.PHOTO
- media_type = event_mimetype or "image/png"
- elif msgtype == "m.audio":
- if source_content.get("org.matrix.msc3245.voice") is not None:
- is_voice_message = True
- msg_type = MessageType.VOICE
- else:
- msg_type = MessageType.AUDIO
- media_type = event_mimetype or "audio/ogg"
- elif msgtype == "m.video":
- msg_type = MessageType.VIDEO
- media_type = event_mimetype or "video/mp4"
- elif event_mimetype:
- media_type = event_mimetype
-
- # Cache media locally when downstream tools need a real file path.
+ is_encrypted_media = bool(file_content and isinstance(file_content, dict) and file_content.get("url"))
+ msg_type, media_type, is_voice_message = self._classify_inbound_media(msgtype, event_mimetype, source_content)
+ # Cache locally so downstream tools get a real file path.
cached_path = None
- should_cache_locally = msg_type in {
- MessageType.PHOTO, MessageType.AUDIO, MessageType.VIDEO, MessageType.DOCUMENT,
- } or is_voice_message or is_encrypted_media
- if should_cache_locally and url:
+ if url:
try:
- file_bytes = await self._client.download_media(ContentURI(url))
- if file_bytes is not None:
- if is_encrypted_media:
- from mautrix.crypto.attachments import decrypt_attachment
-
- hashes_value = (
- file_content.get("hashes")
- if isinstance(file_content, dict)
- else None
- )
- hash_value = (
- hashes_value.get("sha256")
- if isinstance(hashes_value, dict)
- else None
- )
-
- key_value = (
- file_content.get("key")
- if isinstance(file_content, dict)
- else None
- )
- if isinstance(key_value, dict):
- key_value = key_value.get("k")
-
- iv_value = (
- file_content.get("iv")
- if isinstance(file_content, dict)
- else None
- )
-
- if key_value and hash_value and iv_value:
- file_bytes = decrypt_attachment(
- file_bytes, key_value, hash_value, iv_value
- )
- else:
- logger.warning(
- "[Matrix] Encrypted media event missing decryption metadata for %s",
- event_id,
- )
- file_bytes = None
-
- if file_bytes is not None:
- from gateway.platforms.base import (
- cache_audio_from_bytes,
- cache_document_from_bytes,
- cache_image_from_bytes,
- )
-
- if msg_type == MessageType.PHOTO:
- ext_map = {
- "image/jpeg": ".jpg",
- "image/png": ".png",
- "image/gif": ".gif",
- "image/webp": ".webp",
- }
- ext = ext_map.get(media_type, ".jpg")
- cached_path = cache_image_from_bytes(file_bytes, ext=ext)
- logger.info("[Matrix] Cached user image at %s", cached_path)
- elif msg_type in {MessageType.AUDIO, MessageType.VOICE}:
- ext = (
- Path(
- body
- or (
- "voice.ogg" if is_voice_message else "audio.ogg"
- )
- ).suffix
- or ".ogg"
- )
- cached_path = cache_audio_from_bytes(file_bytes, ext=ext)
- else:
- filename = body or (
- "video.mp4"
- if msg_type == MessageType.VIDEO
- else "document"
- )
- cached_path = cache_document_from_bytes(
- file_bytes, filename
- )
+ cached_path = await self._download_and_cache_media(
+ url, event_id, file_content if is_encrypted_media else None,
+ msg_type, media_type, is_voice_message, body,
+ )
except Exception as e:
logger.warning("[Matrix] Failed to cache media: %s", e)
-
- ctx = await self._resolve_message_context(
- room_id,
- sender,
- event_id,
- body,
- source_content,
- relates_to,
- )
+ ctx = await self._resolve_message_context(room_id, sender, event_id, body, source_content, relates_to)
if ctx is None:
return
body, is_dm, chat_type, thread_id, display_name, source = ctx
-
- # Reply-to detection (mirrors _handle_text_message).
- reply_to = None
- in_reply_to = relates_to.get("m.in_reply_to", {})
- if in_reply_to:
- reply_to = in_reply_to.get("event_id")
-
- reply_to_text: Optional[str] = None
- reply_to_author_id: Optional[str] = None
- reply_to_author_name: Optional[str] = None
- if reply_to and body.startswith("> "):
- reply_to_text, reply_to_author_id = _extract_reply_fallback(body)
- body = _strip_reply_fallback(body)
-
- if reply_to_author_id:
- reply_to_author_name = await self._get_display_name(
- room_id, reply_to_author_id
- )
-
- if msgtype == "m.image" and _looks_like_matrix_image_filename(body):
- body = ""
- elif msgtype in ("m.audio", "m.file", "m.video") and _looks_like_matrix_media_filename(body):
+ body, reply_to, reply_to_text, reply_to_author_id, reply_to_author_name = (
+ await self._extract_reply_context(room_id, body, relates_to)
+ )
+ if (msgtype == "m.image" and _looks_like_matrix_image_filename(body)) or (
+ msgtype in ("m.audio", "m.file", "m.video") and _looks_like_matrix_media_filename(body)
+ ):
body = ""
-
allow_http_fallback = bool(http_url) and not is_encrypted_media
- media_urls = (
- [cached_path]
- if cached_path
- else ([http_url] if allow_http_fallback else None)
- )
+ media_urls = [cached_path] if cached_path else ([http_url] if allow_http_fallback else None)
media_types = [media_type] if media_urls else None
-
msg_event = MessageEvent(
- text=body,
- message_type=msg_type,
- source=source,
- raw_message=source_content,
- message_id=event_id,
- media_urls=media_urls,
- media_types=media_types,
- reply_to_message_id=reply_to,
- reply_to_text=reply_to_text,
- reply_to_author_id=reply_to_author_id,
- reply_to_author_name=reply_to_author_name,
- user_id=sender,
- user_name=display_name,
+ text=body, message_type=msg_type, source=source, raw_message=source_content,
+ message_id=event_id, media_urls=media_urls, media_types=media_types,
+ reply_to_message_id=reply_to, reply_to_text=reply_to_text,
+ reply_to_author_id=reply_to_author_id, reply_to_author_name=reply_to_author_name,
+ user_id=sender, user_name=display_name,
)
-
await self.handle_message(msg_event)
+ @staticmethod
+ def _classify_inbound_media(
+ msgtype: str, event_mimetype: str, source_content: dict
+ ) -> tuple[MessageType, str, bool]:
+ """Map a Matrix media msgtype to (MessageType, mime type, is_voice_message)."""
+ media_type = event_mimetype or "application/octet-stream"
+ if msgtype == "m.image":
+ return MessageType.PHOTO, event_mimetype or "image/png", False
+ if msgtype == "m.audio":
+ media_type = event_mimetype or "audio/ogg"
+ if source_content.get("org.matrix.msc3245.voice") is not None:
+ return MessageType.VOICE, media_type, True
+ return MessageType.AUDIO, media_type, False
+ if msgtype == "m.video":
+ return MessageType.VIDEO, event_mimetype or "video/mp4", False
+ return MessageType.DOCUMENT, media_type, False
+
+ async def _download_and_cache_media(
+ self, url: str, event_id: str, encrypted_file: Optional[dict], msg_type: MessageType,
+ media_type: str, is_voice_message: bool, body: str,
+ ) -> Optional[str]:
+ """Download (and decrypt, when *encrypted_file* is given) media into the local cache."""
+ file_bytes = await self._client.download_media(ContentURI(url))
+ if file_bytes is None:
+ return None
+ if encrypted_file is not None:
+ from mautrix.crypto.attachments import decrypt_attachment
+ hashes_value = encrypted_file.get("hashes")
+ hash_value = hashes_value.get("sha256") if isinstance(hashes_value, dict) else None
+ key_value = encrypted_file.get("key")
+ if isinstance(key_value, dict):
+ key_value = key_value.get("k")
+ iv_value = encrypted_file.get("iv")
+ if not (key_value and hash_value and iv_value):
+ logger.warning(
+ "[Matrix] Encrypted media event missing decryption metadata for %s", event_id
+ )
+ return None
+ file_bytes = decrypt_attachment(file_bytes, key_value, hash_value, iv_value)
+ from gateway.platforms.base import (
+ cache_audio_from_bytes, cache_document_from_bytes, cache_image_from_bytes,
+ )
+ if msg_type == MessageType.PHOTO:
+ ext_map = {"image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif", "image/webp": ".webp"}
+ cached_path = cache_image_from_bytes(file_bytes, ext=ext_map.get(media_type, ".jpg"))
+ logger.info("[Matrix] Cached user image at %s", cached_path)
+ return cached_path
+ if msg_type in {MessageType.AUDIO, MessageType.VOICE}:
+ ext = Path(body or ("voice.ogg" if is_voice_message else "audio.ogg")).suffix or ".ogg"
+ return cache_audio_from_bytes(file_bytes, ext=ext)
+ filename = body or ("video.mp4" if msg_type == MessageType.VIDEO else "document")
+ return cache_document_from_bytes(file_bytes, filename)
+
async def _on_invite(self, event: Any) -> None:
"""Auto-join rooms when invited, recording DM rooms in m.direct."""
-
room_id = str(getattr(event, "room_id", ""))
content = getattr(event, "content", None)
is_direct = bool(getattr(content, "is_direct", False))
inviter = str(getattr(event, "sender", ""))
-
- # Only auto-join when the inviter is authorized. Without this, any
- # federated Matrix user could invite the bot into arbitrary rooms,
- # exposing its presence and metadata. Mirrors the allow-list gate
- # used on the message/reaction paths.
- allow_all = os.getenv("GATEWAY_ALLOW_ALL_USERS", "").lower() in {
- "true",
- "1",
- "yes",
- }
- if not allow_all and not (
- self._allowed_user_ids and inviter in self._allowed_user_ids
- ):
- logger.warning(
- "Matrix: rejecting invite to %s from unauthorized user %s",
- room_id,
- inviter,
- )
+ # Only authorized inviters — otherwise any federated user could pull the bot into rooms.
+ allow_all = _env_truthy("GATEWAY_ALLOW_ALL_USERS")
+ if not allow_all and not (self._allowed_user_ids and inviter in self._allowed_user_ids):
+ logger.warning("Matrix: rejecting invite to %s from unauthorized user %s", room_id, inviter)
return
-
- logger.info(
- "Matrix: invited to %s — joining (is_direct=%s)",
- room_id,
- is_direct,
- )
- # When the invite declares this as a DM, record it in m.direct after
- # the (non-blocking) join completes so that _resolve_room_identity
- # treats it correctly even when the bot account has no prior DM
- # history. The join itself stays off the sync path.
- self._schedule_invite_join(
- room_id,
- is_direct=is_direct and bool(inviter),
- inviter=inviter,
- )
+ logger.info("Matrix: invited to %s — joining (is_direct=%s)", room_id, is_direct)
+ # Join off the sync path; a declared DM is recorded in m.direct once the join lands.
+ self._schedule_invite_join(room_id, is_direct=is_direct and bool(inviter), inviter=inviter)
async def _join_room_by_id(self, room_id: str) -> bool:
"""Join a room by ID and refresh local caches on success."""
@@ -3859,12 +2665,8 @@ class MatrixAdapter(BasePlatformAdapter):
return True
except Exception as exc:
logger.warning("Matrix: error joining %s: %s", room_id, exc)
- # Abandoned rooms (no current members) surface as "no servers
- # in the room have been provided" or "room not found". The
- # pending invite keeps retrying every startup unless we
- # explicitly leave it. The match is narrow enough that
- # transient failures still leave the invite untouched for the
- # next try.
+ # Abandoned rooms ("no servers ..." / "room not found") would retry every startup
+ # unless we leave the invite; the match is narrow so transient errors keep retrying.
msg = str(exc).lower()
if ("no servers" in msg) or ("room not found" in msg):
try:
@@ -3875,11 +2677,7 @@ class MatrixAdapter(BasePlatformAdapter):
return False
def _schedule_invite_join(
- self,
- room_id: str,
- *,
- is_direct: bool = False,
- inviter: str = "",
+ self, room_id: str, *, is_direct: bool = False, inviter: str = "",
) -> None:
"""Schedule an invite join without blocking sync or gateway readiness."""
if not room_id or room_id in self._joined_rooms:
@@ -3890,18 +2688,13 @@ class MatrixAdapter(BasePlatformAdapter):
async def _join_invite() -> None:
try:
- joined = await asyncio.wait_for(
- self._join_room_by_id(room_id), timeout=45.0
- )
- # Persist the DM signal from the invite once the join lands,
- # so m.direct is authoritative even on a fresh bot account.
+ joined = await asyncio.wait_for(self._join_room_by_id(room_id), timeout=45.0)
if joined and is_direct and inviter:
await self._record_dm_room(room_id, inviter)
except asyncio.TimeoutError:
logger.warning("Matrix: timed out joining invite %s", room_id)
finally:
self._invite_join_tasks.pop(room_id, None)
-
self._invite_join_tasks[room_id] = asyncio.create_task(_join_invite())
def _schedule_pending_invite_joins(self, sync_data: Dict[str, Any]) -> None:
@@ -3920,31 +2713,13 @@ class MatrixAdapter(BasePlatformAdapter):
# Reactions (send, receive, processing lifecycle)
# ------------------------------------------------------------------
- async def _send_reaction(
- self,
- room_id: str,
- event_id: str,
- emoji: str,
- ) -> Optional[str]:
- """Send an emoji reaction to a message in a room.
- Returns the reaction event_id on success, None on failure.
- """
-
+ async def _send_reaction(self, room_id: str, event_id: str, emoji: str) -> Optional[str]:
+ """Send an emoji reaction; returns the reaction event_id, or None on failure."""
if not self._client:
return None
- content = {
- "m.relates_to": {
- "rel_type": "m.annotation",
- "event_id": event_id,
- "key": emoji,
- }
- }
+ content = {"m.relates_to": {"rel_type": "m.annotation", "event_id": event_id, "key": emoji}}
try:
- resp_event_id = await self._client.send_message_event(
- RoomID(room_id),
- EventType.REACTION,
- content,
- )
+ resp_event_id = await self._client.send_message_event(RoomID(room_id), EventType.REACTION, content)
logger.debug("Matrix: sent reaction %s to %s", emoji, event_id)
return str(resp_event_id)
except Exception as exc:
@@ -3952,19 +2727,13 @@ class MatrixAdapter(BasePlatformAdapter):
return None
async def _redact_reaction(
- self,
- room_id: str,
- reaction_event_id: str,
- reason: str = "",
+ self, room_id: str, reaction_event_id: str, reason: str = "",
) -> bool:
"""Remove a reaction by redacting its event."""
return await self.redact_message(room_id, reaction_event_id, reason)
def _schedule_reaction_redaction(
- self,
- room_id: str,
- reaction_event_id: str,
- reason: str = "",
+ self, room_id: str, reaction_event_id: str, reason: str = "",
) -> None:
"""Redact a reaction after a short delay so message delivery settles."""
@@ -3973,18 +2742,11 @@ class MatrixAdapter(BasePlatformAdapter):
if self._reaction_redaction_delay_seconds:
await asyncio.sleep(self._reaction_redaction_delay_seconds)
if not await self._redact_reaction(room_id, reaction_event_id, reason):
- logger.debug(
- "Matrix: failed to redact reaction %s", reaction_event_id
- )
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- logger.debug(
- "Matrix: delayed reaction redaction failed for %s: %s",
- reaction_event_id,
- exc,
- )
-
+ logger.debug("Matrix: failed to redact reaction %s", reaction_event_id)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ logger.debug("Matrix: delayed reaction redaction failed for %s: %s", reaction_event_id, exc)
task = asyncio.create_task(_redact_later())
self._reaction_redaction_tasks.add(task)
task.add_done_callback(self._reaction_redaction_tasks.discard)
@@ -4000,11 +2762,7 @@ class MatrixAdapter(BasePlatformAdapter):
if reaction_event_id:
self._pending_reactions[(room_id, msg_id)] = reaction_event_id
- async def on_processing_complete(
- self,
- event: MessageEvent,
- outcome: ProcessingOutcome,
- ) -> None:
+ async def on_processing_complete(self, event: MessageEvent, outcome: ProcessingOutcome) -> None:
"""Replace eyes with checkmark (success) or cross (failure)."""
if not self._reactions_enabled:
return
@@ -4017,16 +2775,8 @@ class MatrixAdapter(BasePlatformAdapter):
reaction_key = (room_id, msg_id)
if reaction_key in self._pending_reactions:
eyes_event_id = self._pending_reactions.pop(reaction_key)
- self._schedule_reaction_redaction(
- room_id,
- eyes_event_id,
- "processing complete",
- )
- await self._send_reaction(
- room_id,
- msg_id,
- "\u2705" if outcome == ProcessingOutcome.SUCCESS else "\u274c",
- )
+ self._schedule_reaction_redaction(room_id, eyes_event_id, "processing complete")
+ await self._send_reaction(room_id, msg_id, "\u2705" if outcome == ProcessingOutcome.SUCCESS else "\u274c")
async def _on_reaction(self, event: Any) -> None:
"""Handle incoming reaction events."""
@@ -4036,7 +2786,6 @@ class MatrixAdapter(BasePlatformAdapter):
event_id = str(getattr(event, "event_id", ""))
if self._is_duplicate_event(event_id):
return
-
room_id = str(getattr(event, "room_id", ""))
content = getattr(event, "content", None)
if content:
@@ -4053,228 +2802,164 @@ class MatrixAdapter(BasePlatformAdapter):
elif hasattr(relates_to, "event_id"):
reacts_to = str(getattr(relates_to, "event_id", ""))
key = str(getattr(relates_to, "key", ""))
- logger.info(
- "Matrix: reaction %s from %s on %s in %s",
- key,
- sender,
- reacts_to,
- room_id,
- )
-
- # Check if this reaction resolves a pending approval prompt.
- prompt = self._approval_prompts_by_event.get(reacts_to)
- if prompt and not prompt.resolved:
- if room_id != prompt.chat_id:
- return
- if self._matrix_prompt_expired(prompt):
- await self._expire_matrix_approval_prompt(room_id, reacts_to, prompt)
- return
- if not await self._validate_matrix_prompt_reactor(
- room_id, reacts_to, sender, prompt, "approval"
- ):
- return
- choice = self._approval_reaction_map.get(key)
- if not choice:
- await self._send_invalid_reaction_feedback(
- room_id,
- reacts_to,
- "That reaction is not valid for this approval prompt.",
- )
- return
- try:
- from tools.approval import resolve_gateway_approval
-
- count = resolve_gateway_approval(prompt.session_key, choice)
- if count:
- prompt.resolved = True
- self._approval_prompts_by_event.pop(reacts_to, None)
- self._approval_prompt_by_session.pop(prompt.session_key, None)
- logger.info(
- "Matrix reaction resolved %d approval(s) for session %s "
- "(choice=%s, user=%s)",
- count, prompt.session_key, choice, sender,
- )
- # Redact bot's seed reactions, leaving only the user's
- await self._redact_bot_approval_reactions(room_id, prompt)
- except Exception as exc:
- logger.error("Failed to resolve gateway approval from Matrix reaction: %s", exc)
+ logger.info("Matrix: reaction %s from %s on %s in %s", key, sender, reacts_to, room_id)
+ if await self._handle_approval_reaction(room_id, reacts_to, key, sender):
return
-
- model_prompt = self._model_picker_prompts_by_event.get(reacts_to)
- if model_prompt and not model_prompt.resolved:
- if room_id != model_prompt.chat_id:
- return
- if self._matrix_prompt_expired(model_prompt):
- await self._expire_matrix_model_picker_prompt(room_id, reacts_to, model_prompt)
- return
- if not await self._validate_matrix_prompt_reactor(
- room_id, reacts_to, sender, model_prompt, "model picker"
- ):
- return
- selection = model_prompt.choices.get(key)
- if not selection:
- await self._send_invalid_reaction_feedback(
- room_id,
- reacts_to,
- "That reaction is not one of the available model choices.",
- )
- return
- model_prompt.resolved = True
- self._model_picker_prompts_by_event.pop(reacts_to, None)
- model_id, provider_slug = selection
- try:
- confirmation = await model_prompt.on_model_selected(
- room_id, model_id, provider_slug
- )
- await self._redact_bot_model_picker_reactions(room_id, model_prompt)
- if confirmation:
- await self.send(room_id, confirmation, reply_to=reacts_to)
- except Exception as exc:
- logger.error("Failed to switch model from Matrix reaction: %s", exc)
- await self.send(
- room_id,
- f"Failed to switch model: {exc}",
- reply_to=reacts_to,
- )
+ if await self._handle_model_picker_reaction(room_id, reacts_to, key, sender):
return
+ await self._handle_choice_picker_reaction(room_id, reacts_to, key, sender)
- choice_prompt = self._choice_picker_prompts_by_event.get(reacts_to)
- if choice_prompt and not choice_prompt.resolved:
- if room_id != choice_prompt.chat_id:
- return
- if self._matrix_prompt_expired(choice_prompt):
- self._choice_picker_prompts_by_event.pop(reacts_to, None)
- return
- if not await self._validate_matrix_prompt_reactor(
- room_id, reacts_to, sender, choice_prompt, "choice picker"
- ):
- return
- value = choice_prompt.choices.get(key)
- if value is None:
- await self._send_invalid_reaction_feedback(
- room_id,
- reacts_to,
- "That reaction is not one of the available choices.",
+ async def _handle_approval_reaction(self, room_id: str, reacts_to: str, key: str, sender: str) -> bool:
+ """Resolve a pending exec-approval prompt from a reaction. True if it was the target."""
+ prompt = self._approval_prompts_by_event.get(reacts_to)
+ if prompt and not prompt.resolved:
+ if room_id != prompt.chat_id:
+ return True
+ if self._matrix_prompt_expired(prompt):
+ await self._expire_matrix_approval_prompt(room_id, reacts_to, prompt)
+ return True
+ if not await self._validate_matrix_prompt_reactor(room_id, reacts_to, sender, prompt, "approval"):
+ return True
+ choice = self._approval_reaction_map.get(key)
+ if not choice:
+ await self._send_invalid_reaction_feedback(
+ room_id, reacts_to, "That reaction is not valid for this approval prompt.",
+ )
+ return True
+ try:
+ from tools.approval import resolve_gateway_approval
+ count = resolve_gateway_approval(prompt.session_key, choice)
+ if count:
+ prompt.resolved = True
+ self._approval_prompts_by_event.pop(reacts_to, None)
+ self._approval_prompt_by_session.pop(prompt.session_key, None)
+ logger.info(
+ "Matrix reaction resolved %d approval(s) for session %s (choice=%s, user=%s)",
+ count, prompt.session_key, choice, sender,
)
- return
- choice_prompt.resolved = True
+ await self._redact_bot_approval_reactions(room_id, prompt)
+ except Exception as exc:
+ logger.error("Failed to resolve gateway approval from Matrix reaction: %s", exc)
+ return True
+ return False
+
+ async def _handle_model_picker_reaction(self, room_id: str, reacts_to: str, key: str, sender: str) -> bool:
+ """Apply a model-picker reaction. True if the reaction targeted a pending picker."""
+ model_prompt = self._model_picker_prompts_by_event.get(reacts_to)
+ if model_prompt and not model_prompt.resolved:
+ if room_id != model_prompt.chat_id:
+ return True
+ if self._matrix_prompt_expired(model_prompt):
+ await self._expire_matrix_model_picker_prompt(room_id, reacts_to, model_prompt)
+ return True
+ if not await self._validate_matrix_prompt_reactor(room_id, reacts_to, sender, model_prompt, "model picker"):
+ return True
+ selection = model_prompt.choices.get(key)
+ if not selection:
+ await self._send_invalid_reaction_feedback(
+ room_id, reacts_to, "That reaction is not one of the available model choices."
+ )
+ return True
+ model_prompt.resolved = True
+ self._model_picker_prompts_by_event.pop(reacts_to, None)
+ model_id, provider_slug = selection
+ try:
+ confirmation = await model_prompt.on_model_selected(room_id, model_id, provider_slug)
+ await self._redact_bot_model_picker_reactions(room_id, model_prompt)
+ if confirmation:
+ await self.send(room_id, confirmation, reply_to=reacts_to)
+ except Exception as exc:
+ logger.error("Failed to switch model from Matrix reaction: %s", exc)
+ await self.send(room_id, f"Failed to switch model: {exc}", reply_to=reacts_to)
+ return True
+ return False
+
+ async def _handle_choice_picker_reaction(self, room_id: str, reacts_to: str, key: str, sender: str) -> bool:
+ """Apply a choice-picker reaction. True if the reaction targeted a pending picker."""
+ choice_prompt = self._choice_picker_prompts_by_event.get(reacts_to)
+ if choice_prompt and not choice_prompt.resolved:
+ if room_id != choice_prompt.chat_id:
+ return True
+ if self._matrix_prompt_expired(choice_prompt):
self._choice_picker_prompts_by_event.pop(reacts_to, None)
- try:
- confirmation = await choice_prompt.on_choice_selected(room_id, value)
- if confirmation:
- await self.send(room_id, confirmation, reply_to=reacts_to)
- except Exception as exc:
- logger.error("Failed to apply choice from Matrix reaction: %s", exc)
- await self.send(
- room_id,
- f"Failed to apply selection: {exc}",
- reply_to=reacts_to,
- )
- return
+ return True
+ if not await self._validate_matrix_prompt_reactor(
+ room_id, reacts_to, sender, choice_prompt, "choice picker"
+ ):
+ return True
+ value = choice_prompt.choices.get(key)
+ if value is None:
+ await self._send_invalid_reaction_feedback(room_id, reacts_to, "That reaction is not one of the available choices.")
+ return True
+ choice_prompt.resolved = True
+ self._choice_picker_prompts_by_event.pop(reacts_to, None)
+ try:
+ confirmation = await choice_prompt.on_choice_selected(room_id, value)
+ if confirmation:
+ await self.send(room_id, confirmation, reply_to=reacts_to)
+ except Exception as exc:
+ logger.error("Failed to apply choice from Matrix reaction: %s", exc)
+ await self.send(room_id, f"Failed to apply selection: {exc}", reply_to=reacts_to)
+ return True
+ return False
def _matrix_prompt_expired(self, prompt: Any) -> bool:
expires_at = getattr(prompt, "expires_at", None)
return expires_at is not None and time.monotonic() > float(expires_at)
async def _validate_matrix_prompt_reactor(
- self,
- room_id: str,
- target_event_id: str,
- sender: str,
- prompt: Any,
- prompt_label: str,
+ self, room_id: str, target_event_id: str, sender: str, prompt: Any, prompt_label: str,
) -> bool:
- allow_all = os.getenv("GATEWAY_ALLOW_ALL_USERS", "").lower() in {
- "true",
- "1",
- "yes",
- }
- if not allow_all and not (
- self._allowed_user_ids and sender in self._allowed_user_ids
- ):
+ allow_all = _env_truthy("GATEWAY_ALLOW_ALL_USERS")
+ if not allow_all and not (self._allowed_user_ids and sender in self._allowed_user_ids):
logger.info(
- "Matrix: ignoring %s reaction from unauthorized user %s on %s",
- prompt_label, sender, target_event_id,
+ "Matrix: ignoring %s reaction from unauthorized user %s on %s", prompt_label, sender, target_event_id
)
await self._send_invalid_reaction_feedback(
- room_id,
- target_event_id,
- "Only an authorized Matrix user can use these controls.",
+ room_id, target_event_id, "Only an authorized Matrix user can use these controls."
)
return False
-
requester = getattr(prompt, "requester_user_id", None)
approval_require_sender = getattr(self, "_approval_require_sender", True)
if approval_require_sender and requester and sender != requester:
- logger.info(
- "Matrix: ignoring %s reaction from %s; requester is %s",
- prompt_label, sender, requester,
- )
+ logger.info("Matrix: ignoring %s reaction from %s; requester is %s", prompt_label, sender, requester)
await self._send_invalid_reaction_feedback(
- room_id,
- target_event_id,
- "Only the user who requested this action can use these controls.",
+ room_id, target_event_id, "Only the user who requested this action can use these controls."
)
return False
return True
- async def _send_invalid_reaction_feedback(
- self,
- room_id: str,
- target_event_id: str,
- text: str,
- ) -> None:
+ async def _send_invalid_reaction_feedback(self, room_id: str, target_event_id: str, text: str) -> None:
try:
await self.send(room_id, text, reply_to=target_event_id)
except Exception as exc:
logger.debug("Matrix: failed to send invalid reaction feedback: %s", exc)
- async def _expire_matrix_approval_prompt(
- self,
- room_id: str,
- target_event_id: str,
- prompt: "_MatrixApprovalPrompt",
- ) -> None:
+ async def _expire_matrix_approval_prompt(self, room_id: str, target_event_id: str, prompt: Any) -> None:
prompt.resolved = True
self._approval_prompts_by_event.pop(target_event_id, None)
self._approval_prompt_by_session.pop(prompt.session_key, None)
await self._redact_bot_approval_reactions(room_id, prompt)
await self._send_invalid_reaction_feedback(
- room_id,
- target_event_id,
+ room_id, target_event_id,
"This approval prompt has expired. Run the command again if you still want to approve it.",
)
- async def _expire_matrix_model_picker_prompt(
- self,
- room_id: str,
- target_event_id: str,
- prompt: "_MatrixModelPickerPrompt",
- ) -> None:
+ async def _expire_matrix_model_picker_prompt(self, room_id: str, target_event_id: str, prompt: Any) -> None:
prompt.resolved = True
self._model_picker_prompts_by_event.pop(target_event_id, None)
await self._redact_bot_model_picker_reactions(room_id, prompt)
await self._send_invalid_reaction_feedback(
- room_id,
- target_event_id,
- "This model picker has expired. Run `/model` again to choose a model.",
+ room_id, target_event_id, "This model picker has expired. Run `/model` again to choose a model."
)
- async def _redact_bot_approval_reactions(
- self,
- room_id: str,
- prompt: "_MatrixApprovalPrompt",
- ) -> None:
+ async def _redact_bot_approval_reactions(self, room_id: str, prompt: Any) -> None:
"""Redact the bot's seeded approval reactions, leaving only the user's reaction."""
for emoji, evt_id in prompt.bot_reaction_events.items():
self._schedule_reaction_redaction(room_id, evt_id, "approval resolved")
logger.debug("Matrix: scheduled bot reaction redaction %s (%s)", emoji, evt_id)
- async def _redact_bot_model_picker_reactions(
- self,
- room_id: str,
- prompt: "_MatrixModelPickerPrompt",
- ) -> None:
+ async def _redact_bot_model_picker_reactions(self, room_id: str, prompt: Any) -> None:
"""Redact the bot's seeded model picker reactions."""
for emoji, evt_id in prompt.bot_reaction_events.items():
try:
@@ -4287,46 +2972,6 @@ class MatrixAdapter(BasePlatformAdapter):
# Text message aggregation (handles Matrix client-side splits)
# ------------------------------------------------------------------
- def _text_batch_key(self, event: MessageEvent) -> str:
- """Session-scoped key for text message batching."""
- from gateway.session import build_session_key
-
- return build_session_key(
- event.source,
- group_sessions_per_user=self.config.extra.get(
- "group_sessions_per_user", True
- ),
- thread_sessions_per_user=self.config.extra.get(
- "thread_sessions_per_user", False
- ),
- profile=self._session_key_profile(event.source),
- )
-
- def _enqueue_text_event(self, event: MessageEvent) -> None:
- """Buffer a text event and reset the flush timer."""
- key = self._text_batch_key(event)
- existing = self._pending_text_batches.get(key)
- chunk_len = len(event.text or "")
- if existing is None:
- event._last_chunk_len = chunk_len # type: ignore[attr-defined]
- self._pending_text_batches[key] = event
- else:
- if event.text:
- existing.text = (
- f"{existing.text}\n{event.text}" if existing.text else event.text
- )
- existing._last_chunk_len = chunk_len # type: ignore[attr-defined]
- if event.media_urls:
- existing.media_urls.extend(event.media_urls)
- existing.media_types.extend(event.media_types)
-
- prior_task = self._pending_text_batch_tasks.get(key)
- if prior_task and not prior_task.done():
- prior_task.cancel()
- self._pending_text_batch_tasks[key] = asyncio.create_task(
- self._flush_text_batch(key)
- )
-
async def _flush_text_batch(self, key: str) -> None:
"""Wait for the quiet period then dispatch the aggregated text."""
current_task = asyncio.current_task()
@@ -4341,11 +2986,7 @@ class MatrixAdapter(BasePlatformAdapter):
event = self._pending_text_batches.pop(key, None)
if not event:
return
- logger.info(
- "[Matrix] Flushing text batch %s (%d chars)",
- key,
- len(event.text or ""),
- )
+ logger.info("[Matrix] Flushing text batch %s (%d chars)", key, len(event.text or ""))
await self.handle_message(event)
finally:
if self._pending_text_batch_tasks.get(key) is current_task:
@@ -4363,7 +3004,6 @@ class MatrixAdapter(BasePlatformAdapter):
await self.send_read_receipt(room_id, event_id)
except Exception as exc: # pragma: no cover — defensive
logger.debug("Matrix: background read receipt failed: %s", exc)
-
asyncio.ensure_future(_send())
async def send_read_receipt(self, room_id: str, event_id: str) -> bool:
@@ -4378,11 +3018,7 @@ class MatrixAdapter(BasePlatformAdapter):
elif hasattr(self._client, "send_receipt"):
await self._client.send_receipt(room, event)
elif hasattr(self._client, "set_read_markers"):
- await self._client.set_read_markers(
- room,
- fully_read_event=event,
- read_receipt=event,
- )
+ await self._client.set_read_markers(room, fully_read_event=event, read_receipt=event)
else:
logger.debug("Matrix: client has no read receipt method")
return False
@@ -4396,21 +3032,12 @@ class MatrixAdapter(BasePlatformAdapter):
# Message redaction
# ------------------------------------------------------------------
- async def redact_message(
- self,
- room_id: str,
- event_id: str,
- reason: str = "",
- ) -> bool:
+ async def redact_message(self, room_id: str, event_id: str, reason: str = "") -> bool:
"""Redact (delete) a message or event from a room."""
if not self._client:
return False
try:
- await self._client.redact(
- RoomID(room_id),
- EventID(event_id),
- reason=reason or None,
- )
+ await self._client.redact(RoomID(room_id), EventID(event_id), reason=reason or None)
logger.info("Matrix: redacted %s in %s", event_id, room_id)
return True
except Exception as exc:
@@ -4422,36 +3049,23 @@ class MatrixAdapter(BasePlatformAdapter):
# ------------------------------------------------------------------
async def create_room(
- self,
- name: str = "",
- topic: str = "",
- invite: Optional[list] = None,
- is_direct: bool = False,
- preset: str = "private_chat",
+ self, name: str = "", topic: str = "", invite: Optional[list] = None,
+ is_direct: bool = False, preset: str = "private_chat",
) -> Optional[str]:
"""Create a new Matrix room."""
if not self._client:
return None
- if preset == "public_chat" and os.getenv("MATRIX_ALLOW_PUBLIC_ROOMS", "").lower() not in (
- "true",
- "1",
- "yes",
- ):
+ if preset == "public_chat" and not _env_truthy("MATRIX_ALLOW_PUBLIC_ROOMS"):
logger.warning("Matrix: refusing to create public room without MATRIX_ALLOW_PUBLIC_ROOMS=true")
return None
try:
preset_enum = {
- "private_chat": RoomCreatePreset.PRIVATE,
- "public_chat": RoomCreatePreset.PUBLIC,
+ "private_chat": RoomCreatePreset.PRIVATE, "public_chat": RoomCreatePreset.PUBLIC,
"trusted_private_chat": RoomCreatePreset.TRUSTED_PRIVATE,
}.get(preset, RoomCreatePreset.PRIVATE)
invitees = [UserID(u) for u in (invite or [])]
room_id = await self._client.create_room(
- name=name or None,
- topic=topic or None,
- invitees=invitees,
- is_direct=is_direct,
- preset=preset_enum,
+ name=name or None, topic=topic or None, invitees=invitees, is_direct=is_direct, preset=preset_enum
)
room_id_str = str(room_id)
self._joined_rooms.add(room_id_str)
@@ -4473,63 +3087,6 @@ class MatrixAdapter(BasePlatformAdapter):
logger.warning("Matrix: invite error: %s", exc)
return False
- async def fetch_history(
- self,
- room_id: str,
- limit: int = 20,
- from_token: str = "",
- ) -> list[dict[str, Any]]:
- """Fetch recent Matrix room history using the live client."""
- if not self._client:
- return []
- limit = max(1, min(int(limit or 20), 100))
- try:
- direction = getattr(PaginationDirection, "BACKWARD", "b")
- if hasattr(self._client, "messages"):
- response = await self._client.messages(
- RoomID(room_id),
- from_token=SyncToken(from_token) if from_token else None,
- direction=direction,
- limit=limit,
- )
- elif hasattr(self._client, "get_messages"):
- response = await self._client.get_messages(
- RoomID(room_id),
- start=SyncToken(from_token) if from_token else None,
- direction=direction,
- limit=limit,
- )
- else:
- logger.debug("Matrix: client has no messages/get_messages method")
- return []
- chunk = getattr(response, "chunk", None)
- if chunk is None and isinstance(response, dict):
- chunk = response.get("chunk")
- return [self._serialize_history_event(evt) for evt in (chunk or [])]
- except Exception as exc:
- logger.warning("Matrix: fetch history error: %s", exc)
- return []
-
- def _serialize_history_event(self, event: Any) -> dict[str, Any]:
- content = getattr(event, "content", None)
- if content is None and isinstance(event, dict):
- content = event.get("content", {})
- if not isinstance(content, dict):
- content = dict(content) if hasattr(content, "items") else {}
- return {
- "event_id": str(
- getattr(event, "event_id", "")
- or (event.get("event_id", "") if isinstance(event, dict) else "")
- ),
- "sender": str(
- getattr(event, "sender", "")
- or (event.get("sender", "") if isinstance(event, dict) else "")
- ),
- "timestamp": _matrix_event_timestamp_seconds(event),
- "msgtype": str(content.get("msgtype", "")),
- "body": str(content.get("body", "")),
- }
-
# ------------------------------------------------------------------
# Presence
# ------------------------------------------------------------------
@@ -4545,46 +3102,16 @@ class MatrixAdapter(BasePlatformAdapter):
return False
try:
presence_map = {
- "online": PresenceState.ONLINE,
- "offline": PresenceState.OFFLINE,
+ "online": PresenceState.ONLINE, "offline": PresenceState.OFFLINE,
"unavailable": PresenceState.UNAVAILABLE,
}
- await self._client.set_presence(
- presence=presence_map[state],
- status=status_msg or None,
- )
+ await self._client.set_presence(presence=presence_map[state], status=status_msg or None)
logger.debug("Matrix: presence set to %s", state)
return True
except Exception as exc:
logger.debug("Matrix: set_presence failed: %s", exc)
return False
- # ------------------------------------------------------------------
- # Emote & notice message types
- # ------------------------------------------------------------------
-
- async def _send_simple_message(
- self,
- chat_id: str,
- text: str,
- msgtype: str,
- ) -> SendResult:
- """Send a simple message (emote, notice) with optional HTML formatting."""
- if not self._client or not text:
- return SendResult(success=False, error="No client or empty text")
-
- msg_content = self._build_text_message_content(text, msgtype=msgtype)
-
- try:
- event_id = await self._client.send_message_event(
- RoomID(chat_id),
- EventType.ROOM_MESSAGE,
- msg_content,
- )
- return SendResult(success=True, message_id=str(event_id))
- except Exception as exc:
- return SendResult(success=False, error=str(exc))
-
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
@@ -4611,10 +3138,8 @@ class MatrixAdapter(BasePlatformAdapter):
return None
async def _get_room_member_count(self, room_id: str) -> Optional[int]:
- # Tier 1: state_store (fast, cache-backed).
- state_store = (
- getattr(self._client, "state_store", None) if self._client else None
- )
+ """state_store first (cached), then a direct joined_members API query."""
+ state_store = (getattr(self._client, "state_store", None) if self._client else None)
if state_store:
try:
members = await state_store.get_members(room_id)
@@ -4622,8 +3147,6 @@ class MatrixAdapter(BasePlatformAdapter):
return len(members)
except Exception:
pass
-
- # Tier 2: API fallback (direct server query) when the cache is empty.
client = getattr(self, "_client", None)
if client is not None and hasattr(client, "joined_members"):
try:
@@ -4632,46 +3155,17 @@ class MatrixAdapter(BasePlatformAdapter):
return len(resp.members)
except Exception:
pass
-
return None
- async def _get_room_name(self, room_id: str) -> Optional[str]:
- if not self._client or not hasattr(self._client, "get_state_event"):
- return None
- try:
- event = await self._client.get_state_event(
- RoomID(room_id),
- "m.room.name",
- )
- except Exception:
- return None
- value = self._state_event_value(event, "name")
- return value.strip() if value and value.strip() else None
-
- async def _get_room_canonical_alias(self, room_id: str) -> Optional[str]:
- if not self._client or not hasattr(self._client, "get_state_event"):
- return None
- try:
- event = await self._client.get_state_event(
- RoomID(room_id),
- "m.room.canonical_alias",
- )
- except Exception:
- return None
- value = self._state_event_value(event, "alias")
- return value.strip() if value and value.strip() else None
-
- async def _get_room_topic(self, room_id: str) -> Optional[str]:
+ async def _get_room_state_value(self, room_id: str, event_type: str, key: str) -> Optional[str]:
+ """Fetch a stripped string field from a room state event, or None."""
if not self._client or not hasattr(self._client, "get_state_event"):
return None
try:
- event = await self._client.get_state_event(
- RoomID(room_id),
- "m.room.topic",
- )
+ event = await self._client.get_state_event(RoomID(room_id), event_type)
except Exception:
return None
- value = self._state_event_value(event, "topic")
+ value = self._state_event_value(event, key)
return value.strip() if value and value.strip() else None
@staticmethod
@@ -4683,28 +3177,15 @@ class MatrixAdapter(BasePlatformAdapter):
def _cache_room_identity(self, room_id: str, identity: MatrixRoomIdentity) -> None:
if len(self._room_identities) >= self._room_identity_cache_max:
- oldest = min(
- self._room_identity_cached_at,
- key=self._room_identity_cached_at.get,
- default=None,
- )
+ oldest = min(self._room_identity_cached_at, key=self._room_identity_cached_at.get, default=None)
if oldest:
self._room_identities.pop(oldest, None)
self._room_identity_cached_at.pop(oldest, None)
self._room_identities[room_id] = identity
self._room_identity_cached_at[room_id] = time.monotonic()
- async def _resolve_room_identity(
- self,
- room_id: str,
- *,
- force_refresh: bool = False,
- ) -> MatrixRoomIdentity:
- """Resolve Matrix room identity without member-count DM heuristics.
-
- Matrix ``m.direct`` account data is the authoritative DM signal, but
- explicitly named rooms win over stale/conflicting DM account data.
- """
+ async def _resolve_room_identity(self, room_id: str, *, force_refresh: bool = False) -> MatrixRoomIdentity:
+ """Resolve room identity; member count is the primary DM signal (see below)."""
cached = self._room_identities.get(room_id)
cached_at = self._room_identity_cached_at.get(room_id, 0.0)
cache_fresh = (
@@ -4713,43 +3194,23 @@ class MatrixAdapter(BasePlatformAdapter):
)
if cached is not None and cache_fresh and not force_refresh:
return cached
-
- room_name = await self._get_room_name(room_id)
- room_topic = await self._get_room_topic(room_id)
- canonical_alias = await self._get_room_canonical_alias(room_id)
+ room_name = await self._get_room_state_value(room_id, "m.room.name", "name")
+ room_topic = await self._get_room_state_value(room_id, "m.room.topic", "topic")
+ canonical_alias = await self._get_room_state_value(room_id, "m.room.canonical_alias", "alias")
member_count = await self._get_room_member_count(room_id)
has_explicit_name = bool(room_name)
is_direct = bool(self._dm_rooms.get(room_id, False))
- # member_count is the primary DM signal: <=2 members means this is
- # necessarily a 1:1 conversation (or self-DM), regardless of m.direct
- # or room name. Most Matrix clients auto-name DM rooms (e.g.
- # "Alice & Bot"), so the old `not has_explicit_name` check
- # misclassified virtually all client-created DMs as rooms. Falls back
- # to the m.direct + name heuristic when the count is unavailable (e.g.
- # state_store and API query both fail). A room that grew to 3+ members
- # but is still in stale m.direct is correctly classified as a room.
- is_likely_dm = (member_count is not None and member_count <= 2) or (
- is_direct and not has_explicit_name
- )
- conflict = bool(
- is_direct
- and has_explicit_name
- and (member_count is None or member_count > 2)
- )
+ # <=2 members is necessarily a DM regardless of m.direct/name (clients auto-name DMs
+ # like "Alice & Bot"); fall back to m.direct + unnamed only when the count is unknown.
+ is_likely_dm = (member_count is not None and member_count <= 2) or (is_direct and not has_explicit_name)
+ conflict = bool(is_direct and has_explicit_name and (member_count is None or member_count > 2))
chat_type = "dm" if is_likely_dm else "room"
display_name = room_name or canonical_alias or room_id
-
identity = MatrixRoomIdentity(
- room_id=room_id,
- room_name=room_name,
- room_topic=room_topic,
- canonical_alias=canonical_alias,
- server_name=self._room_server_name(room_id),
- joined_member_count=member_count,
- is_direct_account_data=is_direct,
- display_name=display_name,
- has_explicit_name=has_explicit_name,
- chat_type=chat_type,
+ room_id=room_id, room_name=room_name, room_topic=room_topic,
+ canonical_alias=canonical_alias, server_name=self._room_server_name(room_id),
+ joined_member_count=member_count, is_direct_account_data=is_direct,
+ display_name=display_name, has_explicit_name=has_explicit_name, chat_type=chat_type,
conflict=conflict,
)
self._cache_room_identity(room_id, identity)
@@ -4759,30 +3220,31 @@ class MatrixAdapter(BasePlatformAdapter):
"""Check if a room is a DM."""
return (await self._resolve_room_identity(room_id)).chat_type == "dm"
- async def _refresh_dm_cache(self) -> None:
- """Refresh the DM room cache from m.direct account data."""
- if not self._client:
- return
-
- dm_data: Optional[Dict] = None
-
+ async def _fetch_m_direct(self, *, log_failure: bool = False, require_dict: bool = False):
+ """Return the m.direct account-data mapping, or None when absent/unreadable."""
try:
resp = await self._client.get_account_data("m.direct")
- if hasattr(resp, "content"):
- dm_data = resp.content
- elif isinstance(resp, dict):
- dm_data = resp
except Exception as exc:
- logger.debug("Matrix: get_account_data('m.direct') failed: %s", exc)
+ if log_failure:
+ logger.debug("Matrix: get_account_data('m.direct') failed: %s", exc)
+ return None
+ if hasattr(resp, "content") and (not require_dict or isinstance(resp.content, dict)):
+ return resp.content
+ if isinstance(resp, dict):
+ return resp
+ return None
+ async def _refresh_dm_cache(self) -> None:
+ """Refresh the DM room cache from m.direct account data."""
+ if not self._client:
+ return
+ dm_data = await self._fetch_m_direct(log_failure=True)
if dm_data is None:
return
-
dm_room_ids: Set[str] = set()
for user_id, rooms in dm_data.items():
if isinstance(rooms, list):
dm_room_ids.update(str(r) for r in rooms if isinstance(r, str))
-
self._dm_rooms = {rid: (rid in dm_room_ids) for rid in self._joined_rooms}
self._room_identities.clear()
self._room_identity_cached_at.clear()
@@ -4799,16 +3261,8 @@ class MatrixAdapter(BasePlatformAdapter):
if not self._client:
return
- dm_data: Dict[str, list] = {}
- try:
- resp = await self._client.get_account_data("m.direct")
- if hasattr(resp, "content") and isinstance(resp.content, dict):
- dm_data = resp.content
- elif isinstance(resp, dict):
- dm_data = resp
- except Exception:
- pass # m.direct doesn't exist yet — start fresh
-
+ # m.direct may not exist yet (404) — start fresh.
+ dm_data: Dict[str, list] = await self._fetch_m_direct(require_dict=True) or {}
rooms_for_user = dm_data.get(inviter, [])
if not isinstance(rooms_for_user, list):
rooms_for_user = []
@@ -4817,13 +3271,10 @@ class MatrixAdapter(BasePlatformAdapter):
dm_data[inviter] = rooms_for_user
try:
await self._client.set_account_data("m.direct", dm_data)
- logger.info(
- "Matrix: recorded %s as DM room (inviter=%s)", room_id, inviter
- )
+ logger.info("Matrix: recorded %s as DM room (inviter=%s)", room_id, inviter)
except Exception as exc:
logger.warning("Matrix: failed to update m.direct: %s", exc)
-
- # Update local cache so _resolve_room_identity sees it immediately.
+ # Local cache so _resolve_room_identity sees it immediately.
self._dm_rooms[room_id] = True
self._room_identities.pop(room_id, None)
self._room_identity_cached_at.pop(room_id, None)
@@ -4841,20 +3292,15 @@ class MatrixAdapter(BasePlatformAdapter):
msg_content["m.mentions"] = {"user_ids": mention_user_ids}
if room_mentioned:
msg_content.setdefault("m.mentions", {})["room"] = True
-
html_source = self._inject_outbound_mention_links(text)
html = self._markdown_to_html(html_source)
if html and html != text:
msg_content["format"] = "org.matrix.custom.html"
msg_content["formatted_body"] = html
-
return msg_content
def _apply_relation_metadata(
- self,
- msg_content: Dict[str, Any],
- *,
- reply_to: Optional[str] = None,
+ self, msg_content: Dict[str, Any], *, reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Apply Matrix reply/thread relation metadata to an outbound payload."""
@@ -4866,13 +3312,8 @@ class MatrixAdapter(BasePlatformAdapter):
relates_to["rel_type"] = "m.thread"
relates_to["event_id"] = thread_id
relates_to["is_falling_back"] = True
- # Matrix clients that do not render threads still use reply
- # fallback. If no explicit reply target is available, fall back
- # to the thread root.
- relates_to.setdefault(
- "m.in_reply_to",
- {"event_id": reply_to or thread_id},
- )
+ # Non-thread clients render the reply fallback; default it to the thread root.
+ relates_to.setdefault("m.in_reply_to", {"event_id": reply_to or thread_id})
msg_content["m.relates_to"] = relates_to
def _extract_outbound_mentions(self, text: str) -> list[str]:
@@ -4896,17 +3337,12 @@ class MatrixAdapter(BasePlatformAdapter):
"""Wrap outbound Matrix mentions in markdown links outside code spans."""
if not text:
return text
-
protected, placeholders = self._protect_outbound_mention_regions(text)
-
linked = _OUTBOUND_MENTION_RE.sub(
- lambda match: f"[{match.group(1)}](https://matrix.to/#/{match.group(1)})",
- protected,
+ lambda match: f"[{match.group(1)}](https://matrix.to/#/{match.group(1)})", protected
)
-
for idx, original in enumerate(placeholders):
linked = linked.replace(f"\x00MENTION_PROTECTED{idx}\x00", original)
-
return linked
def _protect_outbound_mention_regions(self, text: str) -> tuple[str, list[str]]:
@@ -4917,41 +3353,16 @@ class MatrixAdapter(BasePlatformAdapter):
idx = len(placeholders)
placeholders.append(fragment)
return f"\x00MENTION_PROTECTED{idx}\x00"
-
- protected = re.sub(
- r"```[\s\S]*?```",
- lambda match: _protect(match.group(0)),
- text or "",
- )
- protected = re.sub(
- r"`[^`\n]+`",
- lambda match: _protect(match.group(0)),
- protected,
- )
- protected = re.sub(
- r"\[[^\]]+\]\([^)]+\)",
- lambda match: _protect(match.group(0)),
- protected,
- )
-
+ protected = text or ""
+ for pattern in (r"```[\s\S]*?```", r"`[^`\n]+`", r"\[[^\]]+\]\([^)]+\)"):
+ protected = re.sub(pattern, lambda match: _protect(match.group(0)), protected)
return protected, placeholders
def _is_bot_mentioned(
- self,
- body: str,
- formatted_body: Optional[str] = None,
- mention_user_ids: Optional[list] = None,
+ self, body: str, formatted_body: Optional[str] = None, mention_user_ids: Optional[list] = None
) -> bool:
- """Return True if the bot is mentioned in the message.
-
- Per MSC3952, ``m.mentions.user_ids`` is the authoritative mention
- signal in the Matrix spec. When the sender's client populates that
- field with the bot's user-id, we trust it — even when the visible
- body text does not contain an explicit ``@bot`` string (some clients
- only render mention "pills" in ``formatted_body`` or use display
- names).
- """
- # m.mentions.user_ids — authoritative per MSC3952 / Matrix v1.7.
+ """True if the bot is mentioned; ``m.mentions.user_ids`` (MSC3952) is authoritative
+ even when the body has no ``@bot`` text (pills may live only in formatted_body)."""
if mention_user_ids and self._user_id and self._user_id in mention_user_ids:
return True
if not body and not formatted_body:
@@ -4960,40 +3371,21 @@ class MatrixAdapter(BasePlatformAdapter):
return True
if self._user_id and ":" in self._user_id:
localpart = self._user_id.split(":")[0].lstrip("@")
- if localpart and re.search(
- r"\b" + re.escape(localpart) + r"\b", body, re.IGNORECASE
- ):
- return True
- if formatted_body and self._user_id:
- if f"matrix.to/#/{self._user_id}" in formatted_body:
+ if localpart and re.search(r"\b" + re.escape(localpart) + r"\b", body, re.IGNORECASE):
return True
- return False
+ return bool(formatted_body and self._user_id and f"matrix.to/#/{self._user_id}" in formatted_body)
def _strip_mention(self, body: str) -> str:
- """Remove explicit bot mentions from message body.
-
- Important: only strip explicit mention tokens (``@user:server`` or
- ``@localpart``). Do NOT strip bare words matching the bot localpart,
- otherwise normal phrases like "Hermes Agent" become "Agent".
- """
+ """Strip explicit ``@user:server`` / ``@localpart`` tokens only — never bare localpart
+ words, or "Hermes Agent" would become "Agent"."""
if not body:
return ""
-
- # Strip explicit full MXID mentions.
if self._user_id:
body = body.replace(self._user_id, "")
-
- # Strip explicit @localpart mentions only (not bare localpart words).
if self._user_id and ":" in self._user_id:
localpart = self._user_id.split(":")[0].lstrip("@")
if localpart:
- body = re.sub(
- r'(?<![\w])@' + re.escape(localpart) + r'\b',
- '',
- body,
- flags=re.IGNORECASE,
- )
-
+ body = re.sub(r'(?<![\w])@' + re.escape(localpart) + r'\b', '', body, flags=re.IGNORECASE)
# Normalize spacing after mention removal.
body = re.sub(r'[ \t]{2,}', ' ', body)
body = re.sub(r'\s+([,.;:!?])', r'\1', body)
@@ -5001,9 +3393,7 @@ class MatrixAdapter(BasePlatformAdapter):
async def _get_display_name(self, room_id: str, user_id: str) -> str:
"""Get a user's display name in a room, falling back to user_id."""
- state_store = (
- getattr(self._client, "state_store", None) if self._client else None
- )
+ state_store = (getattr(self._client, "state_store", None) if self._client else None)
if state_store:
try:
member = await state_store.get_member(room_id, user_id)
@@ -5011,7 +3401,6 @@ class MatrixAdapter(BasePlatformAdapter):
return member.displayname
except Exception:
pass
- # Strip the @...:server format to just the localpart.
if user_id.startswith("@") and ":" in user_id:
return user_id[1:].split(":")[0]
return user_id
@@ -5024,39 +3413,22 @@ class MatrixAdapter(BasePlatformAdapter):
return f"{self._homeserver}/_matrix/client/v1/media/download/{parts}"
def _markdown_to_html(self, text: str) -> str:
- """Convert Markdown to Matrix-compatible HTML (org.matrix.custom.html).
-
- Uses the ``markdown`` library (a core dependency) when available.
- Falls back to a comprehensive regex converter that handles fenced
- code blocks, inline code, headers, bold, italic, strikethrough,
- links, blockquotes, lists, and horizontal rules — everything the
- Matrix HTML spec allows.
- """
+ """Markdown → org.matrix.custom.html via ``markdown`` when installed, else the regex fallback."""
text = _pre_sanitize_matrix_markdown(text)
try:
import markdown as _md
-
- md = _md.Markdown(
- extensions=["fenced_code", "tables", "nl2br", "sane_lists"],
- )
+ md = _md.Markdown(extensions=["fenced_code", "tables", "nl2br", "sane_lists"])
if "html_block" in md.preprocessors:
md.preprocessors.deregister("html_block")
-
html = md.convert(text)
md.reset()
-
if html.count("<p>") == 1:
html = html.replace("<p>", "").replace("</p>", "")
return _sanitize_matrix_html(html)
except ImportError:
pass
-
return _sanitize_matrix_html(self._markdown_to_html_fallback(text))
- # ------------------------------------------------------------------
- # Regex-based Markdown -> HTML (no extra dependencies)
- # ------------------------------------------------------------------
-
@staticmethod
def _sanitize_link_url(url: str) -> str:
"""Sanitize a URL for use in an href attribute."""
@@ -5071,12 +3443,14 @@ class MatrixAdapter(BasePlatformAdapter):
"""Comprehensive regex Markdown-to-HTML for Matrix."""
placeholders: list = []
+ def _is_bq_line(ln: str) -> bool:
+ return ln.startswith(("&gt; ", "> ")) or ln in ("&gt;", ">")
+
def _protect_html(html_fragment: str) -> str:
idx = len(placeholders)
placeholders.append(html_fragment)
return f"\x00PROTECTED{idx}\x00"
- # Fenced code blocks: ```lang\n...\n```
result = re.sub(
r"```(\w*)\n(.*?)```",
lambda m: _protect_html(
@@ -5088,68 +3462,39 @@ class MatrixAdapter(BasePlatformAdapter):
text,
flags=re.DOTALL,
)
-
- # Inline code: `code`
- result = re.sub(
- r"`([^`\n]+)`",
- lambda m: _protect_html(f"<code>{_html_escape(m.group(1))}</code>"),
- result,
- )
-
- # Extract and protect markdown links before escaping.
+ result = re.sub(r"`([^`\n]+)`", lambda m: _protect_html(f"<code>{_html_escape(m.group(1))}</code>"), result)
+ # Protect markdown links before escaping.
result = re.sub(
r"\[([^\]]+)\]\(([^)]+)\)",
lambda m: _protect_html(
- '<a href="{}">{}</a>'.format(
- MatrixAdapter._sanitize_link_url(m.group(2)),
- _html_escape(m.group(1)),
- )
+ '<a href="{}">{}</a>'.format(MatrixAdapter._sanitize_link_url(m.group(2)), _html_escape(m.group(1)))
),
result,
)
-
- # HTML-escape remaining text.
parts = re.split(r"(\x00PROTECTED\d+\x00)", result)
for idx, part in enumerate(parts):
if not part.startswith("\x00PROTECTED"):
parts[idx] = _html_escape(part)
result = "".join(parts)
-
- # Block-level transforms (line-oriented).
+ # Block-level transforms (line-oriented): hr, headers, blockquote, lists.
lines = result.split("\n")
out_lines: list = []
i = 0
while i < len(lines):
line = lines[i]
-
- # Horizontal rule
if re.match(r"^[\s]*([-*_])\s*\1\s*\1[\s\-*_]*$", line):
out_lines.append("<hr>")
i += 1
continue
-
- # Headers
hdr = re.match(r"^(#{1,6})\s+(.+)$", line)
if hdr:
level = len(hdr.group(1))
out_lines.append(f"<h{level}>{hdr.group(2).strip()}</h{level}>")
i += 1
continue
-
- # Blockquote
- if (
- line.startswith("&gt; ")
- or line == "&gt;"
- or line.startswith("> ")
- or line == ">"
- ):
+ if _is_bq_line(line):
bq_lines = []
- while i < len(lines) and (
- lines[i].startswith("&gt; ")
- or lines[i] == "&gt;"
- or lines[i].startswith("> ")
- or lines[i] == ">"
- ):
+ while i < len(lines) and _is_bq_line(lines[i]):
ln = lines[i]
if ln.startswith("&gt; "):
bq_lines.append(ln[5:])
@@ -5160,87 +3505,42 @@ class MatrixAdapter(BasePlatformAdapter):
i += 1
out_lines.append(f"<blockquote>{'<br>'.join(bq_lines)}</blockquote>")
continue
-
- # Unordered list
- ul_match = re.match(r"^[\s]*[-*+]\s+(.+)$", line)
- if ul_match:
- items = []
- while i < len(lines) and re.match(r"^[\s]*[-*+]\s+(.+)$", lines[i]):
- items.append(re.match(r"^[\s]*[-*+]\s+(.+)$", lines[i]).group(1))
- i += 1
- li = "".join(f"<li>{item}</li>" for item in items)
- out_lines.append(f"<ul>{li}</ul>")
- continue
-
- # Ordered list
- ol_match = re.match(r"^[\s]*\d+[.)]\s+(.+)$", line)
- if ol_match:
- items = []
- while i < len(lines) and re.match(r"^[\s]*\d+[.)]\s+(.+)$", lines[i]):
- items.append(re.match(r"^[\s]*\d+[.)]\s+(.+)$", lines[i]).group(1))
- i += 1
- li = "".join(f"<li>{item}</li>" for item in items)
- out_lines.append(f"<ol>{li}</ol>")
- continue
-
- out_lines.append(line)
- i += 1
-
+ for item_re, tag in ((r"^[\s]*[-*+]\s+(.+)$", "ul"), (r"^[\s]*\d+[.)]\s+(.+)$", "ol")):
+ if re.match(item_re, line):
+ items = []
+ while i < len(lines) and re.match(item_re, lines[i]):
+ items.append(re.match(item_re, lines[i]).group(1))
+ i += 1
+ li = "".join(f"<li>{item}</li>" for item in items)
+ out_lines.append(f"<{tag}>{li}</{tag}>")
+ break
+ else:
+ out_lines.append(line)
+ i += 1
result = "\n".join(out_lines)
-
- # Inline transforms.
- result = re.sub(
- r"\*\*(.+?)\*\*", r"<strong>\1</strong>", result, flags=re.DOTALL
- )
- result = re.sub(r"__(.+?)__", r"<strong>\1</strong>", result, flags=re.DOTALL)
- result = re.sub(r"\*(.+?)\*", r"<em>\1</em>", result, flags=re.DOTALL)
- result = re.sub(
- r"(?<!\w)_(.+?)_(?!\w)", r"<em>\1</em>", result, flags=re.DOTALL
- )
- result = re.sub(r"~~(.+?)~~", r"<del>\1</del>", result, flags=re.DOTALL)
+ for pattern, repl in (
+ (r"\*\*(.+?)\*\*", r"<strong>\1</strong>"), (r"__(.+?)__", r"<strong>\1</strong>"),
+ (r"\*(.+?)\*", r"<em>\1</em>"), (r"(?<!\w)_(.+?)_(?!\w)", r"<em>\1</em>"),
+ (r"~~(.+?)~~", r"<del>\1</del>"),
+ ):
+ result = re.sub(pattern, repl, result, flags=re.DOTALL)
result = re.sub(r"\n", "<br>\n", result)
- result = re.sub(
- r"<br>\n(</?(?:pre|blockquote|h[1-6]|ul|ol|li|hr))", r"\n\1", result
- )
+ result = re.sub(r"<br>\n(</?(?:pre|blockquote|h[1-6]|ul|ol|li|hr))", r"\n\1", result)
result = re.sub(r"(</(?:pre|blockquote|h[1-6]|ul|ol|li)>)<br>", r"\1", result)
-
- # Restore protected regions.
for idx, original in enumerate(placeholders):
result = result.replace(f"\x00PROTECTED{idx}\x00", original)
-
return result
-# ──────────────────────────────────────────────────────────────────────────
-# Plugin migration glue (#41112 / #3823)
-#
-# Added when the Matrix adapter moved from gateway/platforms/matrix.py into
-# this bundled plugin. Mirrors the Discord (#24356) / Slack migrations: a
-# register(ctx) entry point plus hook implementations that replace the
-# per-platform core touchpoints (the Platform.MATRIX elif in gateway/run.py,
-# the matrix_cfg YAML→env block in gateway/config.py, the _setup_matrix wizard
-# + _PLATFORMS["matrix"] static dict in hermes_cli/{setup,gateway}.py, and the
-# _send_matrix dispatch in tools/send_message_tool.py). Matrix uses the
-# generic token/api_key connected check, so no is_connected override is needed.
-# ──────────────────────────────────────────────────────────────────────────
+# Plugin glue: register(ctx) plus the hook implementations that replaced the
+# per-platform core touchpoints (gateway/run.py, gateway/config.py, hermes_cli setup,
+# tools/send_message_tool.py) when Matrix became a bundled plugin.
async def _standalone_send(
- pconfig,
- chat_id,
- message,
- *,
- thread_id=None,
- media_files=None,
- force_document=False,
+ pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False,
):
- """Out-of-process Matrix delivery via the Client-Server API.
-
- Implements the standalone_sender_fn contract so deliver=matrix cron jobs
- succeed when cron runs separately from the gateway. Converts markdown to
- HTML for rich rendering, falling back to plain text when the markdown
- library is absent. Replaces the legacy _send_matrix helper.
- """
+ """standalone_sender_fn: out-of-process delivery via the Client-Server API (cron without gateway)."""
extra = getattr(pconfig, "extra", {}) or {}
token = getattr(pconfig, "token", None)
try:
@@ -5249,9 +3549,7 @@ async def _standalone_send(
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
try:
homeserver = (extra.get("homeserver") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/")
- # In-turn read: standalone sends run inside an installed secret
- # scope, so honor get_secret's verdict directly (no env fallback on
- # a scoped miss).
+ # In-turn read inside an installed secret scope: honor get_secret, no env fallback.
token = token or get_secret("MATRIX_ACCESS_TOKEN", "") or ""
if not homeserver or not token:
return {"error": "Matrix not configured (MATRIX_HOMESERVER, MATRIX_ACCESS_TOKEN required)"}
@@ -5260,7 +3558,6 @@ async def _standalone_send(
encoded_room = quote(chat_id, safe="")
url = f"{homeserver}/_matrix/client/v3/rooms/{encoded_room}/send/m.room.message/{txn_id}"
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
-
payload = {"msgtype": "m.text", "body": message}
try:
import markdown as _md
@@ -5270,10 +3567,8 @@ async def _standalone_send(
payload["formatted_body"] = html
except ImportError:
pass
-
- # Use asyncio.wait_for() instead of aiohttp.ClientTimeout to avoid
- # "Timeout context manager should be used inside a task" errors when
- # invoked via asyncio.run_coroutine_threadsafe() from cron jobs.
+ # 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 with session.put(url, headers=headers, json=payload) as resp:
@@ -5291,34 +3586,21 @@ async def _standalone_send(
def interactive_setup() -> None:
- """Configure Matrix credentials. Replaces hermes_cli/setup.py::_setup_matrix
- and the static _PLATFORMS["matrix"] dict. CLI helpers are lazy-imported."""
- import shutil
- import sys as _sys
+ """Interactive credential setup (setup_fn); CLI helpers are lazy-imported."""
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
- from hermes_cli.cli_output import (
- prompt,
- prompt_yes_no,
- print_header,
- print_info,
- print_success,
- print_warning,
- )
-
+ from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_info, print_success, print_warning
print_header("Matrix")
existing = get_env_value("MATRIX_ACCESS_TOKEN") or get_env_value("MATRIX_PASSWORD")
if existing:
print_info("Matrix: already configured")
if not prompt_yes_no("Reconfigure Matrix?", False):
return
-
print_info("Works with any Matrix homeserver (Synapse, Conduit, Dendrite, or matrix.org).")
print_info(" 1. Create a bot user on your homeserver, or use your own account")
print_info(" 2. Get an access token from Element, or provide user ID + password")
homeserver = prompt("Homeserver URL (e.g. https://matrix.example.org)")
if homeserver:
save_env_value("MATRIX_HOMESERVER", homeserver.rstrip("/"))
-
print_info("Auth: provide an access token (recommended), or user ID + password.")
token = prompt("Access token (leave empty for password login)", password=True)
if token:
@@ -5335,13 +3617,11 @@ def interactive_setup() -> None:
if password:
save_env_value("MATRIX_PASSWORD", password)
print_success("Matrix credentials saved")
-
if token or get_env_value("MATRIX_PASSWORD"):
want_e2ee = prompt_yes_no("Enable end-to-end encryption (E2EE)?", False)
if want_e2ee:
save_env_value("MATRIX_ENCRYPTION", "true")
print_success("E2EE enabled")
-
matrix_pkg = "mautrix[encryption]" if want_e2ee else "mautrix"
try:
from tools.lazy_deps import ensure as _lazy_ensure, feature_missing
@@ -5363,7 +3643,6 @@ def interactive_setup() -> None:
except ImportError:
print_info(f"Installing {matrix_pkg}...")
from hermes_cli.tools_config import _pip_install
-
result = _pip_install([matrix_pkg])
if result.returncode == 0:
print_success(f"{matrix_pkg} installed")
@@ -5372,7 +3651,6 @@ def interactive_setup() -> None:
f"Install failed — run manually: uv pip install "
f"'{matrix_pkg}' asyncpg aiosqlite Markdown aiohttp-socks"
)
-
print_info("🔒 Security: Restrict who can use your bot")
print_info(" Matrix user IDs look like @username:server")
allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for open access)")
@@ -5381,7 +3659,6 @@ def interactive_setup() -> None:
print_success("Matrix allowlist configured")
else:
print_info("⚠️ No allowlist set - anyone who can message the bot can use it!")
-
print_info("📬 Home Room: where Hermes delivers cron job results and notifications.")
print_info(" Room IDs look like !abc123:server (shown in Element room settings)")
print_info(" You can also set this later by typing /set-home in a Matrix room.")
@@ -5389,62 +3666,46 @@ def interactive_setup() -> None:
home_room = prompt("Home room ID (leave empty to set later with /set-home)").strip()
if home_room:
save_env_value("MATRIX_HOME_ROOM", home_room)
- else:
- if remove_env_value("MATRIX_HOME_ROOM"):
- print_info("Home room cleared.")
+ elif remove_env_value("MATRIX_HOME_ROOM"):
+ print_info("Home room cleared.")
+
+
+_YAML_LOWER_KEYS = (
+ ("require_mention", "MATRIX_REQUIRE_MENTION"), ("process_notices", "MATRIX_PROCESS_NOTICES"),
+ ("session_scope", "MATRIX_SESSION_SCOPE"), ("auto_thread", "MATRIX_AUTO_THREAD"),
+ ("dm_mention_threads", "MATRIX_DM_MENTION_THREADS"),
+)
+_YAML_LIST_KEYS = (
+ ("allowed_users", "MATRIX_ALLOWED_USERS"),
+ ("free_response_rooms", "MATRIX_FREE_RESPONSE_ROOMS"),
+ ("allowed_rooms", "MATRIX_ALLOWED_ROOMS"),
+ ("ignore_user_patterns", "MATRIX_IGNORE_USER_PATTERNS"),
+)
def _apply_yaml_config(yaml_cfg: dict, matrix_cfg: dict) -> dict | None:
- """Translate config.yaml matrix: keys into MATRIX_* env vars.
+ """apply_yaml_config_fn: config.yaml matrix: keys → MATRIX_* env (env wins). Returns None.
- Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy
- matrix_cfg block from gateway/config.py::load_gateway_config(). Env vars
- take precedence over YAML. Returns None — everything flows through env.
+ Lowercased flags apply whenever the key is present (None still writes "none");
+ list-valued keys skip None.
"""
- if "require_mention" in matrix_cfg and not os.getenv("MATRIX_REQUIRE_MENTION"):
- os.environ["MATRIX_REQUIRE_MENTION"] = str(matrix_cfg["require_mention"]).lower()
- au = matrix_cfg.get("allowed_users")
- if au is not None and not os.getenv("MATRIX_ALLOWED_USERS"):
- if isinstance(au, list):
- au = ",".join(str(v) for v in au)
- os.environ["MATRIX_ALLOWED_USERS"] = str(au)
- frc = matrix_cfg.get("free_response_rooms")
- if frc is not None and not os.getenv("MATRIX_FREE_RESPONSE_ROOMS"):
- if isinstance(frc, list):
- frc = ",".join(str(v) for v in frc)
- os.environ["MATRIX_FREE_RESPONSE_ROOMS"] = str(frc)
- ar = matrix_cfg.get("allowed_rooms")
- if ar is not None and not os.getenv("MATRIX_ALLOWED_ROOMS"):
- if isinstance(ar, list):
- ar = ",".join(str(v) for v in ar)
- os.environ["MATRIX_ALLOWED_ROOMS"] = str(ar)
- ignore_patterns = matrix_cfg.get("ignore_user_patterns")
- if ignore_patterns is not None and not os.getenv("MATRIX_IGNORE_USER_PATTERNS"):
- if isinstance(ignore_patterns, list):
- ignore_patterns = ",".join(str(v) for v in ignore_patterns)
- os.environ["MATRIX_IGNORE_USER_PATTERNS"] = str(ignore_patterns)
- if "process_notices" in matrix_cfg and not os.getenv("MATRIX_PROCESS_NOTICES"):
- os.environ["MATRIX_PROCESS_NOTICES"] = str(matrix_cfg["process_notices"]).lower()
- if "session_scope" in matrix_cfg and not os.getenv("MATRIX_SESSION_SCOPE"):
- os.environ["MATRIX_SESSION_SCOPE"] = str(matrix_cfg["session_scope"]).lower()
- if "auto_thread" in matrix_cfg and not os.getenv("MATRIX_AUTO_THREAD"):
- os.environ["MATRIX_AUTO_THREAD"] = str(matrix_cfg["auto_thread"]).lower()
- if "dm_mention_threads" in matrix_cfg and not os.getenv("MATRIX_DM_MENTION_THREADS"):
- os.environ["MATRIX_DM_MENTION_THREADS"] = str(matrix_cfg["dm_mention_threads"]).lower()
+ for key, env_name in _YAML_LOWER_KEYS:
+ if key in matrix_cfg and not os.getenv(env_name):
+ os.environ[env_name] = str(matrix_cfg[key]).lower()
+ for key, env_name in _YAML_LIST_KEYS:
+ value = matrix_cfg.get(key)
+ if value is not None and not os.getenv(env_name):
+ if isinstance(value, list):
+ value = ",".join(str(v) for v in value)
+ os.environ[env_name] = str(value)
if "max_message_length" in matrix_cfg and not os.getenv("MATRIX_MAX_MESSAGE_LENGTH"):
os.environ["MATRIX_MAX_MESSAGE_LENGTH"] = str(matrix_cfg["max_message_length"])
return None
def _is_connected(config) -> bool:
- """Matrix is connected when a homeserver + access token (or password) are
- configured. Read via hermes_cli.gateway.get_env_value so setup-status
- callers that patch get_env_value observe the same value, and PlatformConfig
- extras (homeserver) are honored too. As a built-in, Matrix used the generic
- token check; as a plugin it needs an explicit is_connected so
- _platform_status / get_connected_platforms reflect real configuration
- rather than mere SDK presence. #41112.
- """
+ """Connected = homeserver + token (or password). Reads via hermes_cli.gateway.get_env_value so
+ setup-status callers that patch it see the same value; PlatformConfig extras are honored."""
extra = getattr(config, "extra", {}) or {}
import hermes_cli.gateway as gateway_mod
homeserver = extra.get("homeserver") or gateway_mod.get_env_value("MATRIX_HOMESERVER") or ""
@@ -5465,21 +3726,12 @@ def _build_adapter(config):
def register(ctx) -> None:
"""Plugin entry point — called by the Hermes plugin system."""
ctx.register_platform(
- name="matrix",
- label="Matrix",
- adapter_factory=_build_adapter,
- check_fn=matrix_deps_present,
- ensure_deps_fn=ensure_matrix_deps,
- is_connected=_is_connected,
+ name="matrix", label="Matrix", adapter_factory=_build_adapter, check_fn=matrix_deps_present,
+ ensure_deps_fn=ensure_matrix_deps, is_connected=_is_connected,
required_env=["MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"],
- install_hint="pip install 'mautrix[encryption]'",
- setup_fn=interactive_setup,
- apply_yaml_config_fn=_apply_yaml_config,
- allowed_users_env="MATRIX_ALLOWED_USERS",
- allow_all_env="MATRIX_ALLOW_ALL_USERS",
- cron_deliver_env_var="MATRIX_HOME_ROOM",
- standalone_sender_fn=_standalone_send,
- max_message_length=DEFAULT_MAX_MESSAGE_LENGTH,
- emoji="🔐",
- allow_update_command=True,
+ install_hint="pip install 'mautrix[encryption]'", setup_fn=interactive_setup,
+ apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="MATRIX_ALLOWED_USERS",
+ allow_all_env="MATRIX_ALLOW_ALL_USERS", cron_deliver_env_var="MATRIX_HOME_ROOM",
+ standalone_sender_fn=_standalone_send, max_message_length=DEFAULT_MAX_MESSAGE_LENGTH,
+ emoji="🔐", allow_update_command=True,
)
diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.py
index 6f5172bb019..2747fa15d51 100644
--- a/plugins/platforms/mattermost/adapter.py
+++ b/plugins/platforms/mattermost/adapter.py
@@ -23,51 +23,19 @@ from typing import Any, Dict, List, Optional, Tuple
from gateway.config import Platform, PlatformConfig
from gateway.platforms.helpers import MessageDeduplicator
-from gateway.platforms.base import (
- gateway_trust_env,
- BasePlatformAdapter,
- MessageEvent,
- MessageType,
- SendResult,
-)
-
-from agent.secret_scope import UnscopedSecretError as _UnscopedSecretError
-from agent.secret_scope import get_secret as _scoped_get_secret
-
-
-def _get_scoped_secret(name, default=None):
- """Scope-aware credential read with the default-profile startup fallback.
-
- Secondary profiles construct their adapters under a profile secret
- scope -- the scope is authoritative and a scoped miss returns ``default``
- (no cross-profile borrow from ``os.environ``, which may hold another
- profile's value). The DEFAULT profile's adapter constructs and sends
- *unscoped* under multiplexing, where a bare ``get_secret`` would raise
- ``UnscopedSecretError`` and crash this path; there ``os.environ`` is that
- profile's own value, so fall back to it. Same pattern as the Slack
- ``SLACK_APP_TOKEN`` read (#59739) and
- ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
- """
- try:
- val = _scoped_get_secret(name, default)
- except _UnscopedSecretError:
- val = os.getenv(name)
- return val if val is not None else default
+from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, MessageEvent, MessageType, SendResult
+
+from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
+from gateway.platforms._shared import profile_scoped as _profile_scoped_config_load
logger = logging.getLogger(__name__)
-# Mattermost post size limit (server default is 16383, but 4000 is the
-# practical limit for readable messages — matching OpenClaw's choice).
+# Server default is 16383, but 4000 is the practical limit for readable messages.
MAX_POST_LENGTH = 4000
-# Channel type codes returned by the Mattermost API.
-_CHANNEL_TYPE_MAP = {
- "D": "dm",
- "G": "group",
- "P": "group", # private channel → treat as group
- "O": "channel",
-}
+# Channel type codes returned by the Mattermost API ("P" private → treat as group).
+_CHANNEL_TYPE_MAP = {"D": "dm", "G": "group", "P": "group", "O": "channel"}
_MATTERMOST_DISABLE_MENTIONS_PROPS = {"disable_mentions": True}
@@ -87,6 +55,22 @@ def _with_mentions_disabled(payload: Dict[str, Any]) -> Dict[str, Any]:
return payload
+def _channel_id_set(raw: Any) -> set:
+ """Parse a list or comma-separated string of channel IDs into a stripped set."""
+ items = raw if isinstance(raw, list) else str(raw).split(",")
+ return {str(c).strip() for c in items if str(c).strip()}
+
+
+def _csv(value: Any) -> str:
+ return ",".join(str(v) for v in value) if isinstance(value, list) else str(value)
+
+
+def _post_result(data: Dict[str, Any], error: str) -> SendResult:
+ if not data or "id" not in data:
+ return SendResult(success=False, error=error)
+ return SendResult(success=True, message_id=data["id"])
+
+
def check_mattermost_requirements() -> bool:
"""Return True if the Mattermost adapter runtime dependency is available."""
try:
@@ -118,96 +102,68 @@ class MattermostAdapter(BasePlatformAdapter):
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform.MATTERMOST)
-
- self._base_url: str = (
- config.extra.get("url", "")
- or _get_scoped_secret("MATTERMOST_URL", "")
- ).rstrip("/")
+ self._base_url: str = (config.extra.get("url", "") or _get_scoped_secret("MATTERMOST_URL", "")).rstrip("/")
self._token: str = config.token or _get_scoped_secret("MATTERMOST_TOKEN", "")
-
self._bot_user_id: str = ""
self._bot_username: str = ""
-
- # aiohttp session + websocket handle
self._session: Any = None # aiohttp.ClientSession
- self._ws: Any = None # aiohttp.ClientWebSocketResponse
+ self._ws: Any = None # aiohttp.ClientWebSocketResponse
self._ws_task: Optional[asyncio.Task] = None
self._reconnect_task: Optional[asyncio.Task] = None
self._closing = False
-
# Reply mode: "thread" to nest replies, "off" for flat messages.
self._reply_mode: str = (
- config.extra.get("reply_mode", "")
- or _get_scoped_secret("MATTERMOST_REPLY_MODE", "off")
+ config.extra.get("reply_mode", "") or _get_scoped_secret("MATTERMOST_REPLY_MODE", "off")
).lower()
-
self._last_post_status: Optional[int] = None
self._last_post_error: str = ""
-
- # Dedup cache (prevent reprocessing)
self._dedup = MessageDeduplicator()
- # ------------------------------------------------------------------
- # HTTP helpers
- # ------------------------------------------------------------------
+ # --- HTTP helpers ---
def _headers(self) -> Dict[str, str]:
- return {
- "Authorization": f"Bearer {self._token}",
- "Content-Type": "application/json",
- }
+ return {"Authorization": f"Bearer {self._token}", "Content-Type": "application/json"}
- async def _api_get(self, path: str) -> Dict[str, Any]:
- """GET /api/v4/{path}."""
+ async def _api(self, method: str, path: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+ """{method} /api/v4/{path}; POST also records _last_post_status/_last_post_error."""
import aiohttp
if ".." in path:
logger.error("MM API path traversal blocked: %s", path)
return {}
url = f"{self._base_url}/api/v4/{path.lstrip('/')}"
+ is_post = method == "POST"
+ if is_post:
+ self._last_post_status = None
+ self._last_post_error = ""
+ kwargs: Dict[str, Any] = {"headers": self._headers()}
+ if payload is not None:
+ kwargs["json"] = payload
+ if method != "PUT": # PUT relies on the session default timeout
+ kwargs["timeout"] = aiohttp.ClientTimeout(total=30)
try:
- async with self._session.get(url, headers=self._headers(), timeout=aiohttp.ClientTimeout(total=30)) as resp:
+ async with getattr(self._session, method.lower())(url, **kwargs) as resp:
+ if is_post:
+ self._last_post_status = resp.status
if resp.status >= 400:
body = await resp.text()
- logger.error("MM API GET %s → %s: %s", path, resp.status, body[:200])
+ if is_post:
+ self._last_post_error = body or ""
+ logger.error("MM API %s %s → %s: %s", method, path, resp.status, body[:200])
return {}
return await resp.json()
except aiohttp.ClientError as exc:
- logger.error("MM API GET %s network error: %s", path, exc)
+ if is_post:
+ self._last_post_error = str(exc)
+ logger.error("MM API %s %s network error: %s", method, path, exc)
return {}
- async def _api_post(
- self, path: str, payload: Dict[str, Any]
- ) -> Dict[str, Any]:
- """POST /api/v4/{path} with JSON body."""
- import aiohttp
- if ".." in path:
- logger.error("MM API path traversal blocked: %s", path)
- return {}
- url = f"{self._base_url}/api/v4/{path.lstrip('/')}"
- self._last_post_status = None
- self._last_post_error = ""
- try:
- async with self._session.post(
- url, headers=self._headers(), json=payload,
- timeout=aiohttp.ClientTimeout(total=30)
- ) as resp:
- self._last_post_status = resp.status
- if resp.status >= 400:
- body = await resp.text()
- self._last_post_error = body or ""
- logger.error("MM API POST %s → %s: %s", path, resp.status, body[:200])
- return {}
- return await resp.json()
- except aiohttp.ClientError as exc:
- self._last_post_error = str(exc)
- logger.error("MM API POST %s network error: %s", path, exc)
- return {}
+ async def _api_get(self, path: str) -> Dict[str, Any]:
+ return await self._api("GET", path)
- async def _thread_root_for_send(
- self,
- reply_to: Optional[str],
- metadata: Optional[Dict[str, Any]],
- ) -> Optional[str]:
+ async def _api_post(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
+ return await self._api("POST", path, payload)
+
+ async def _thread_root_for_send(self, reply_to: Optional[str], metadata: Optional[Dict[str, Any]]) -> Optional[str]:
"""Resolve the Mattermost root_id from reply_to or metadata."""
if self._reply_mode != "thread":
return None
@@ -230,10 +186,7 @@ class MattermostAdapter(BasePlatformAdapter):
return rootish and broken
async def _post_preserving_thread(
- self,
- chat_id: str,
- payload: Dict[str, Any],
- metadata: Optional[Dict[str, Any]],
+ self, chat_id: str, payload: Dict[str, Any], metadata: Optional[Dict[str, Any]]
) -> Dict[str, Any]:
"""Post once, optionally falling back flat for final notify content."""
data = await self._api_post("posts", payload)
@@ -243,41 +196,28 @@ class MattermostAdapter(BasePlatformAdapter):
return data
if not self._last_post_failure_is_broken_thread_root():
return data
-
flat_payload = dict(payload)
flat_payload.pop("root_id", None)
original = str(flat_payload.get("message") or "")
flat_payload["message"] = (
- "⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n"
- + original
+ "⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n" + original
).strip()
- logger.warning(
- "Mattermost: falling back to flat channel delivery for notify-worthy post in %s",
- chat_id,
- )
+ logger.warning("Mattermost: falling back to flat channel delivery for notify-worthy post in %s", chat_id)
return await self._api_post("posts", flat_payload)
- async def _api_put(
- self, path: str, payload: Dict[str, Any]
+ async def _post_message(
+ self, chat_id: str, message: str, reply_to: Optional[str], metadata: Optional[Dict[str, Any]],
+ file_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
- """PUT /api/v4/{path} with JSON body."""
- import aiohttp
- if ".." in path:
- logger.error("MM API path traversal blocked: %s", path)
- return {}
- url = f"{self._base_url}/api/v4/{path.lstrip('/')}"
- try:
- async with self._session.put(
- url, headers=self._headers(), json=payload
- ) as resp:
- if resp.status >= 400:
- body = await resp.text()
- logger.error("MM API PUT %s → %s: %s", path, resp.status, body[:200])
- return {}
- return await resp.json()
- except aiohttp.ClientError as exc:
- logger.error("MM API PUT %s network error: %s", path, exc)
- return {}
+ """Build a mentions-disabled post payload (+ optional root_id) and post it."""
+ base: Dict[str, Any] = {"channel_id": chat_id, "message": message}
+ if file_ids is not None:
+ base["file_ids"] = file_ids
+ payload = _with_mentions_disabled(base)
+ resolved_root = await self._thread_root_for_send(reply_to, metadata)
+ if resolved_root:
+ payload["root_id"] = resolved_root
+ return await self._post_preserving_thread(chat_id, payload, metadata)
async def _upload_file(
self, channel_id: str, file_data: bytes, filename: str, content_type: str = "application/octet-stream"
@@ -288,12 +228,7 @@ class MattermostAdapter(BasePlatformAdapter):
url = f"{self._base_url}/api/v4/files"
form = aiohttp.FormData()
form.add_field("channel_id", channel_id)
- form.add_field(
- "files",
- file_data,
- filename=filename,
- content_type=content_type,
- )
+ form.add_field("files", file_data, filename=filename, content_type=content_type)
headers = {"Authorization": f"Bearer {self._token}"}
async with self._session.post(url, headers=headers, data=form, timeout=aiohttp.ClientTimeout(total=60)) as resp:
if resp.status >= 400:
@@ -304,9 +239,7 @@ class MattermostAdapter(BasePlatformAdapter):
infos = data.get("file_infos", [])
return infos[0]["id"] if infos else None
- # ------------------------------------------------------------------
- # Required overrides
- # ------------------------------------------------------------------
+ # --- Required overrides ---
async def connect(self, *, is_reconnect: bool = False) -> bool:
"""Connect to Mattermost and start the WebSocket listener."""
@@ -316,13 +249,9 @@ class MattermostAdapter(BasePlatformAdapter):
logger.error("Mattermost: URL or token not configured")
return False
- self._session = aiohttp.ClientSession(
- timeout=aiohttp.ClientTimeout(total=30),
- trust_env=gateway_trust_env(),
- )
+ self._session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), trust_env=gateway_trust_env())
self._closing = False
- # Verify credentials and fetch bot identity.
me = await self._api_get("users/me")
if not me or "id" not in me:
logger.error("Mattermost: failed to authenticate — check MATTERMOST_TOKEN and MATTERMOST_URL")
@@ -331,14 +260,8 @@ class MattermostAdapter(BasePlatformAdapter):
self._bot_user_id = me["id"]
self._bot_username = me.get("username", "")
- logger.info(
- "Mattermost: authenticated as @%s (%s) on %s",
- self._bot_username,
- self._bot_user_id,
- self._base_url,
- )
+ logger.info("Mattermost: authenticated as @%s (%s) on %s", self._bot_username, self._bot_user_id, self._base_url)
- # Start WebSocket in background.
self._ws_task = asyncio.create_task(self._ws_loop())
self._mark_connected()
# Plugin-registered native handlers (ctx.register_platform_handler).
@@ -348,73 +271,48 @@ class MattermostAdapter(BasePlatformAdapter):
async def disconnect(self) -> None:
"""Disconnect from Mattermost."""
self._closing = True
-
if self._ws_task and not self._ws_task.done():
self._ws_task.cancel()
try:
await self._ws_task
except (asyncio.CancelledError, Exception):
pass
-
if self._reconnect_task and not self._reconnect_task.done():
self._reconnect_task.cancel()
-
if self._ws:
await self._ws.close()
self._ws = None
-
if self._session and not self._session.closed:
await self._session.close()
-
logger.info("Mattermost: disconnected")
-
async def _resolve_root_id(self, post_id: str) -> str:
- """Resolve a post_id to the thread root_id for Mattermost.
+ """Resolve a post_id to its thread root_id.
- Mattermost requires root_id to be the *root* post of a thread.
- If the post is a reply (has its own root_id), we must use that
- root_id instead. Using a reply's own ID as root_id causes
- "Invalid RootId parameter" errors.
+ Mattermost requires root_id to be the *root* post; using a reply's own
+ ID causes "Invalid RootId parameter" errors.
"""
if not post_id:
return post_id
- # Check if this post has a root_id (meaning it's a reply)
data = await self._api_get(f"posts/{post_id}")
if data and data.get("root_id"):
return data["root_id"]
return post_id
async def send(
- self,
- chat_id: str,
- content: str,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None
) -> SendResult:
"""Send a message (or multiple chunks) to a channel."""
if not content:
return SendResult(success=True)
-
- formatted = self.format_message(content)
- chunks = self.truncate_message(formatted, MAX_POST_LENGTH)
-
+ chunks = self.truncate_message(self.format_message(content), MAX_POST_LENGTH)
last_id = None
for chunk in chunks:
- payload: Dict[str, Any] = _with_mentions_disabled({
- "channel_id": chat_id,
- "message": chunk,
- })
# Thread support: reply_to or metadata["thread_id"] is the root post ID.
- resolved_root = await self._thread_root_for_send(reply_to, metadata)
- if resolved_root:
- payload["root_id"] = resolved_root
-
- data = await self._post_preserving_thread(chat_id, payload, metadata)
+ data = await self._post_message(chat_id, chunk, reply_to, metadata)
if not data or "id" not in data:
return SendResult(success=False, error="Failed to create post")
last_id = data["id"]
-
return SendResult(success=True, message_id=last_id)
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
@@ -422,131 +320,78 @@ class MattermostAdapter(BasePlatformAdapter):
data = await self._api_get(f"channels/{chat_id}")
if not data:
return {"name": chat_id, "type": "channel"}
-
ch_type = _CHANNEL_TYPE_MAP.get(data.get("type", "O"), "channel")
display_name = data.get("display_name") or data.get("name") or chat_id
return {"name": display_name, "type": ch_type}
- # ------------------------------------------------------------------
- # Optional overrides
- # ------------------------------------------------------------------
+ # --- Optional overrides ---
- async def send_typing(
- self, chat_id: str, metadata: Optional[Dict[str, Any]] = None
- ) -> None:
+ async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Send a typing indicator."""
- await self._api_post(
- f"users/{self._bot_user_id}/typing",
- {"channel_id": chat_id},
- )
+ await self._api_post(f"users/{self._bot_user_id}/typing", {"channel_id": chat_id})
async def edit_message(
self, chat_id: str, message_id: str, content: str, *, finalize: bool = False
) -> SendResult:
"""Edit an existing post."""
formatted = self.format_message(content)
- data = await self._api_put(
- f"posts/{message_id}/patch",
- _with_mentions_disabled({"message": formatted}),
- )
- if not data or "id" not in data:
- return SendResult(success=False, error="Failed to edit post")
- return SendResult(success=True, message_id=data["id"])
+ data = await self._api("PUT", f"posts/{message_id}/patch", _with_mentions_disabled({"message": formatted}))
+ return _post_result(data, "Failed to edit post")
async def send_image(
- self,
- chat_id: str,
- image_url: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, image_url: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Download an image and upload it as a file attachment."""
- return await self._send_url_as_file(
- chat_id, image_url, caption, reply_to, "image", metadata
- )
+ return await self._send_url_as_file(chat_id, image_url, caption, reply_to, "image", metadata)
async def send_image_file(
- self,
- chat_id: str,
- image_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, image_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a local image file."""
- return await self._send_local_file(
- chat_id, image_path, caption, reply_to, metadata=metadata
- )
+ return await self._send_local_file(chat_id, image_path, caption, reply_to, metadata=metadata)
async def send_document(
- self,
- chat_id: str,
- file_path: str,
- caption: Optional[str] = None,
- file_name: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a local file as a document."""
- return await self._send_local_file(
- chat_id, file_path, caption, reply_to, file_name, metadata
- )
+ return await self._send_local_file(chat_id, file_path, caption, reply_to, file_name, metadata)
async def send_voice(
- self,
- chat_id: str,
- audio_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, audio_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload an audio file."""
- return await self._send_local_file(
- chat_id, audio_path, caption, reply_to, metadata=metadata
- )
+ return await self._send_local_file(chat_id, audio_path, caption, reply_to, metadata=metadata)
async def send_video(
- self,
- chat_id: str,
- video_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, video_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a video file."""
- return await self._send_local_file(
- chat_id, video_path, caption, reply_to, metadata=metadata
- )
+ return await self._send_local_file(chat_id, video_path, caption, reply_to, metadata=metadata)
def format_message(self, content: str) -> str:
- """Mattermost uses standard Markdown — mostly pass through.
-
- Strip image markdown into plain links (files are uploaded separately).
- """
- # Convert ![alt](url) to just the URL — Mattermost renders
- # image URLs as inline previews automatically.
- content = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"\2", content)
- return content
+ """Mattermost renders standard Markdown; reduce ![alt](url) to the bare URL (inline preview)."""
+ return re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"\2", content)
- # ------------------------------------------------------------------
- # File helpers
- # ------------------------------------------------------------------
+ # --- File helpers ---
async def _send_url_as_file(
- self,
- chat_id: str,
- url: str,
- caption: Optional[str],
- reply_to: Optional[str],
- kind: str = "file",
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, url: str, caption: Optional[str], reply_to: Optional[str],
+ kind: str = "file", metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Download a URL and upload it as a file attachment."""
+ """Download a URL and upload it as a file attachment (text fallback with the URL on failure)."""
from tools.url_safety import is_safe_url
+
+ async def fallback() -> SendResult:
+ return await self.send(chat_id, f"{caption or ''}\n{url}".strip(), reply_to, metadata=metadata)
+
if not is_safe_url(url):
logger.warning("Mattermost: blocked unsafe URL (SSRF protection)")
- return await self.send(chat_id, f"{caption or ''}\n{url}".strip(), reply_to, metadata=metadata)
+ return await fallback()
import aiohttp
@@ -557,14 +402,13 @@ class MattermostAdapter(BasePlatformAdapter):
for attempt in range(3):
try:
async with self._session.get(url, timeout=aiohttp.ClientTimeout(total=30)) as resp:
- if resp.status >= 500 or resp.status == 429:
- if attempt < 2:
- logger.debug("Mattermost download retry %d/2 for %s (status %d)",
- attempt + 1, url[:80], resp.status)
- await asyncio.sleep(1.5 * (attempt + 1))
- continue
+ if (resp.status >= 500 or resp.status == 429) and attempt < 2:
+ logger.debug("Mattermost download retry %d/2 for %s (status %d)",
+ attempt + 1, url[:80], resp.status)
+ await asyncio.sleep(1.5 * (attempt + 1))
+ continue
if resp.status >= 400:
- return await self.send(chat_id, f"{caption or ''}\n{url}".strip(), reply_to, metadata=metadata)
+ return await fallback()
file_data = await resp.read()
ct = resp.content_type or "application/octet-stream"
break
@@ -573,171 +417,113 @@ class MattermostAdapter(BasePlatformAdapter):
await asyncio.sleep(1.5 * (attempt + 1))
continue
logger.warning("Mattermost: failed to download %s after %d attempts: %s", url, attempt + 1, exc)
- return await self.send(chat_id, f"{caption or ''}\n{url}".strip(), reply_to, metadata=metadata)
+ return await fallback()
if file_data is None:
logger.warning("Mattermost: download returned no data for %s", url)
- return await self.send(chat_id, f"{caption or ''}\n{url}".strip(), reply_to, metadata=metadata)
+ return await fallback()
file_id = await self._upload_file(chat_id, file_data, fname, ct)
if not file_id:
- return await self.send(chat_id, f"{caption or ''}\n{url}".strip(), reply_to, metadata=metadata)
-
- payload: Dict[str, Any] = _with_mentions_disabled({
- "channel_id": chat_id,
- "message": caption or "",
- "file_ids": [file_id],
- })
- resolved_root = await self._thread_root_for_send(reply_to, metadata)
- if resolved_root:
- payload["root_id"] = resolved_root
-
- data = await self._post_preserving_thread(chat_id, payload, metadata)
- if not data or "id" not in data:
- return SendResult(success=False, error="Failed to post with file")
- return SendResult(success=True, message_id=data["id"])
+ return await fallback()
+ data = await self._post_message(chat_id, caption or "", reply_to, metadata, [file_id])
+ return _post_result(data, "Failed to post with file")
async def _send_local_file(
- self,
- chat_id: str,
- file_path: str,
- caption: Optional[str],
- reply_to: Optional[str],
- file_name: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, file_path: str, caption: Optional[str], reply_to: Optional[str],
+ file_name: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Upload a local file and attach it to a post."""
import mimetypes
p = Path(file_path)
if not p.exists():
- logger.warning(
- "Mattermost: local file not found, skipping: %s", file_path
- )
+ logger.warning("Mattermost: local file not found, skipping: %s", file_path)
return SendResult(success=True, message_id=None)
fname = file_name or p.name
ct = mimetypes.guess_type(fname)[0] or "application/octet-stream"
- file_data = p.read_bytes()
-
- file_id = await self._upload_file(chat_id, file_data, fname, ct)
+ file_id = await self._upload_file(chat_id, p.read_bytes(), fname, ct)
if not file_id:
return SendResult(success=False, error="File upload failed")
+ data = await self._post_message(chat_id, caption or "", reply_to, metadata, [file_id])
+ return _post_result(data, "Failed to post with file")
- payload: Dict[str, Any] = _with_mentions_disabled({
- "channel_id": chat_id,
- "message": caption or "",
- "file_ids": [file_id],
- })
- resolved_root = await self._thread_root_for_send(reply_to, metadata)
- if resolved_root:
- payload["root_id"] = resolved_root
+ async def _load_batch_image(self, image_url: str, index: int) -> Optional[Tuple[bytes, str, str]]:
+ """Read a file:// or remote image for a batch post → (data, filename, content_type), or None to skip."""
+ import mimetypes
+ import aiohttp
+ from urllib.parse import unquote as _unquote
+
+ if image_url.startswith("file://"):
+ local_path = _unquote(image_url[7:])
+ p = Path(local_path)
+ if not p.exists():
+ logger.warning("Mattermost: skipping missing image %s", local_path)
+ return None
+ return p.read_bytes(), p.name, mimetypes.guess_type(p.name)[0] or "image/png"
- data = await self._post_preserving_thread(chat_id, payload, metadata)
- if not data or "id" not in data:
- return SendResult(success=False, error="Failed to post with file")
- return SendResult(success=True, message_id=data["id"])
+ from tools.url_safety import is_safe_url
+ if not is_safe_url(image_url):
+ logger.warning("Mattermost: blocked unsafe image URL in batch")
+ return None
+ try:
+ async with self._session.get(image_url, timeout=aiohttp.ClientTimeout(total=30)) as resp:
+ if resp.status >= 400:
+ logger.warning("Mattermost: failed to download image (HTTP %d): %s", resp.status, image_url[:80])
+ return None
+ file_data = await resp.read()
+ ct = resp.content_type or "image/png"
+ except Exception as dl_err:
+ logger.warning("Mattermost: download failed for %s: %s", image_url[:80], dl_err)
+ return None
+ fname = image_url.rsplit("/", 1)[-1].split("?")[0] or f"image_{index}.png"
+ return file_data, fname, ct
async def send_multiple_images(
- self,
- chat_id: str,
- images: List[Tuple[str, str]],
- metadata: Optional[Dict[str, Any]] = None,
+ self, chat_id: str, images: List[Tuple[str, str]], metadata: Optional[Dict[str, Any]] = None,
human_delay: float = 0.0,
) -> None:
- """Send a batch of images as a single Mattermost post with multiple attachments.
+ """Send a batch of images as one post with multiple attachments.
- Mattermost supports up to 5 ``file_ids`` per post. Each image is
- uploaded individually (Mattermost's file API is one-at-a-time),
- then a single post is created referencing all uploaded file_ids
- at once. Batches larger than 5 are chunked. Falls back to the
- base per-image loop on total failure.
+ Mattermost caps ``file_ids`` at 5 per post and uploads one file at a time,
+ so batches are chunked at 5; each chunk falls back to the base per-image
+ loop on failure.
"""
if not images:
return
-
- import mimetypes
- import aiohttp
- from urllib.parse import unquote as _unquote
-
CHUNK = 5 # Mattermost post file_ids cap
chunks = [images[i:i + CHUNK] for i in range(0, len(images), CHUNK)]
for chunk_idx, chunk in enumerate(chunks):
if human_delay > 0 and chunk_idx > 0:
await asyncio.sleep(human_delay)
-
file_ids: List[str] = []
caption_parts: List[str] = []
try:
for image_url, alt_text in chunk:
if alt_text:
caption_parts.append(alt_text)
-
- if image_url.startswith("file://"):
- local_path = _unquote(image_url[7:])
- p = Path(local_path)
- if not p.exists():
- logger.warning("Mattermost: skipping missing image %s", local_path)
- continue
- fname = p.name
- ct = mimetypes.guess_type(fname)[0] or "image/png"
- file_data = p.read_bytes()
- else:
- from tools.url_safety import is_safe_url
- if not is_safe_url(image_url):
- logger.warning("Mattermost: blocked unsafe image URL in batch")
- continue
- try:
- async with self._session.get(
- image_url, timeout=aiohttp.ClientTimeout(total=30)
- ) as resp:
- if resp.status >= 400:
- logger.warning(
- "Mattermost: failed to download image (HTTP %d): %s",
- resp.status, image_url[:80],
- )
- continue
- file_data = await resp.read()
- ct = resp.content_type or "image/png"
- except Exception as dl_err:
- logger.warning("Mattermost: download failed for %s: %s", image_url[:80], dl_err)
- continue
- fname = image_url.rsplit("/", 1)[-1].split("?")[0] or f"image_{len(file_ids)}.png"
-
- fid = await self._upload_file(chat_id, file_data, fname, ct)
+ loaded = await self._load_batch_image(image_url, len(file_ids))
+ if loaded is None:
+ continue
+ fid = await self._upload_file(chat_id, *loaded)
if fid:
file_ids.append(fid)
-
if not file_ids:
continue
-
- payload: Dict[str, Any] = _with_mentions_disabled({
- "channel_id": chat_id,
- "message": "\n".join(caption_parts),
- "file_ids": file_ids,
- })
- resolved_root = await self._thread_root_for_send(None, metadata)
- if resolved_root:
- payload["root_id"] = resolved_root
- logger.info(
- "Mattermost: sending %d image(s) as single post (chunk %d/%d)",
- len(file_ids), chunk_idx + 1, len(chunks),
- )
- data = await self._post_preserving_thread(chat_id, payload, metadata)
+ logger.info("Mattermost: sending %d image(s) as single post (chunk %d/%d)",
+ len(file_ids), chunk_idx + 1, len(chunks))
+ data = await self._post_message(chat_id, "\n".join(caption_parts), None, metadata, file_ids)
if not data or "id" not in data:
logger.warning("Mattermost: multi-image post failed, falling back")
await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
except Exception as e:
- logger.warning(
- "Mattermost: multi-image send failed (chunk %d/%d), falling back: %s",
- chunk_idx + 1, len(chunks), e, exc_info=True,
- )
+ logger.warning("Mattermost: multi-image send failed (chunk %d/%d), falling back: %s",
+ chunk_idx + 1, len(chunks), e, exc_info=True)
await super().send_multiple_images(chat_id, chunk, metadata, human_delay=human_delay)
- # ------------------------------------------------------------------
- # WebSocket
- # ------------------------------------------------------------------
+ # --- WebSocket ---
async def _ws_loop(self) -> None:
"""Connect to the WebSocket and listen for events, reconnecting on failure."""
@@ -745,30 +531,24 @@ class MattermostAdapter(BasePlatformAdapter):
while not self._closing:
try:
await self._ws_connect_and_listen()
- # Clean disconnect — reset delay.
- delay = _RECONNECT_BASE_DELAY
+ delay = _RECONNECT_BASE_DELAY # clean disconnect — reset backoff
except asyncio.CancelledError:
return
except Exception as exc:
if self._closing:
return
- # Detect permanent auth/permission failures that will never
- # succeed on retry — stop reconnecting instead of looping forever.
+ # Permanent auth/permission failure: escalate via the fatal-error hook
+ # (a bare return would leave is_connected() reporting healthy with a dead
+ # listener). Type-based only — substring matching on "401" misclassified
+ # transient errors.
import aiohttp
if isinstance(exc, aiohttp.WSServerHandshakeError) and exc.status in {401, 403}:
logger.error("Mattermost WS auth failed (HTTP %d) — stopping reconnect", exc.status)
- # Escalate through the fatal-error hook instead of a bare
- # return: the old silent exit left _running True, so
- # is_connected() kept reporting healthy while the listener
- # was dead and the gateway was never told (OOF-156 class).
- # Type-based only — the substring fallback that used to sit
- # below this branch misclassified transient errors whose
- # message merely contained "401" (#80489).
self._set_fatal_error(
"mattermost_auth_error",
- f"Mattermost WebSocket authentication rejected (HTTP {exc.status}). "
- "The bot token is invalid, revoked, or lacks permission — check "
- "MATTERMOST_TOKEN and the bot account in the System Console.",
+ f"Mattermost WebSocket authentication rejected (HTTP {exc.status}). The bot token is "
+ "invalid, revoked, or lacks permission — check MATTERMOST_TOKEN and the bot account in "
+ "the System Console.",
retryable=False,
)
await self._notify_fatal_error()
@@ -777,8 +557,6 @@ class MattermostAdapter(BasePlatformAdapter):
if self._closing:
return
-
- # Exponential backoff with jitter.
import random
jitter = delay * _RECONNECT_JITTER * random.random()
await asyncio.sleep(delay + jitter)
@@ -786,413 +564,243 @@ class MattermostAdapter(BasePlatformAdapter):
async def _ws_connect_and_listen(self) -> None:
"""Single WebSocket session: connect, authenticate, process events."""
- # Build WS URL: https:// → wss://, http:// → ws://
- ws_url = re.sub(r"^http", "ws", self._base_url) + "/api/v4/websocket"
+ ws_url = re.sub(r"^http", "ws", self._base_url) + "/api/v4/websocket" # https→wss, http→ws
logger.info("Mattermost: connecting to %s", ws_url)
-
self._ws = await self._session.ws_connect(ws_url, heartbeat=30.0)
-
- # Authenticate via the WebSocket.
- auth_msg = {
- "seq": 1,
- "action": "authentication_challenge",
- "data": {"token": self._token},
- }
- await self._ws.send_json(auth_msg)
+ await self._ws.send_json({"seq": 1, "action": "authentication_challenge", "data": {"token": self._token}})
logger.info("Mattermost: WebSocket connected and authenticated")
async for raw_msg in self._ws:
if self._closing:
return
-
- if raw_msg.type in {
- raw_msg.type.TEXT,
- raw_msg.type.BINARY,
- }:
+ if raw_msg.type in {raw_msg.type.TEXT, raw_msg.type.BINARY}:
try:
event = json.loads(raw_msg.data)
except (json.JSONDecodeError, TypeError):
continue
await self._handle_ws_event(event)
- elif raw_msg.type in {
- raw_msg.type.ERROR,
- raw_msg.type.CLOSE,
- raw_msg.type.CLOSING,
- raw_msg.type.CLOSED,
- }:
+ elif raw_msg.type in {raw_msg.type.ERROR, raw_msg.type.CLOSE, raw_msg.type.CLOSING, raw_msg.type.CLOSED}:
logger.info("Mattermost: WebSocket closed (%s)", raw_msg.type)
break
+ def _extra_or_env(self, key: str, env: str, default: str = "") -> Any:
+ """config.yaml ``mattermost.<key>`` (PlatformConfig.extra) first, env var fallback."""
+ raw = self.config.extra.get(key) if self.config.extra else None
+ if raw is None:
+ raw = _get_scoped_secret(env, default)
+ return raw
+
+ def _apply_channel_gating(self, channel_id: str, message_text: str) -> Optional[str]:
+ """Mention-gate a non-DM post; return the cleaned text, or None to ignore it.
+
+ allowed_channels is a whitelist checked first (even @mentions are ignored
+ elsewhere); require_mention (default true) is bypassed in free_response_channels.
+ """
+ allowed_channels = _channel_id_set(self._extra_or_env("allowed_channels", "MATTERMOST_ALLOWED_CHANNELS"))
+ if allowed_channels and channel_id not in allowed_channels:
+ logger.debug("Mattermost: ignoring message in non-allowed channel: %s", channel_id)
+ return None
+
+ require_mention_raw = self._extra_or_env("require_mention", "MATTERMOST_REQUIRE_MENTION", "true")
+ require_mention = str(require_mention_raw).lower() not in {"false", "0", "no"}
+ free_channels = _channel_id_set(
+ self._extra_or_env("free_response_channels", "MATTERMOST_FREE_RESPONSE_CHANNELS")
+ )
+ mention_patterns = [f"@{self._bot_username}", f"@{self._bot_user_id}"]
+ has_mention = any(pattern.lower() in message_text.lower() for pattern in mention_patterns)
+
+ if require_mention and channel_id not in free_channels and not has_mention:
+ logger.debug("Mattermost: skipping non-DM message without @mention (channel=%s)", channel_id)
+ return None
+ if has_mention: # strip the @mention so the agent sees clean input
+ for pattern in mention_patterns:
+ message_text = re.sub(re.escape(pattern), "", message_text, flags=re.IGNORECASE).strip()
+ return message_text
+
+ async def _download_attachments(self, file_ids: List[str]) -> Tuple[List[str], List[str]]:
+ """Download attachments now (URLs need auth headers downstream tools lack) → (paths, mime types)."""
+ media_urls: List[str] = []
+ media_types: List[str] = []
+ for fid in file_ids:
+ try:
+ file_info = await self._api_get(f"files/{fid}/info")
+ fname = file_info.get("name", f"file_{fid}")
+ ext = Path(fname).suffix or ""
+ mime = file_info.get("mime_type", "application/octet-stream")
+
+ import aiohttp
+ async with self._session.get(
+ f"{self._base_url}/api/v4/files/{fid}",
+ headers={"Authorization": f"Bearer {self._token}"},
+ timeout=aiohttp.ClientTimeout(total=30),
+ ) as resp:
+ if resp.status >= 400:
+ logger.warning("Mattermost: failed to download file %s: HTTP %s", fid, resp.status)
+ continue
+ file_data = await resp.read()
+ from gateway.platforms.base import (
+ cache_audio_from_bytes, cache_document_from_bytes, cache_image_from_bytes,
+ )
+ if mime.startswith("image/"):
+ local_path = cache_image_from_bytes(file_data, ext or ".png")
+ elif mime.startswith("audio/"):
+ local_path = cache_audio_from_bytes(file_data, ext or ".ogg")
+ else:
+ local_path = cache_document_from_bytes(file_data, fname)
+ media_urls.append(local_path)
+ media_types.append(mime)
+ except Exception as exc:
+ logger.warning("Mattermost: error downloading file %s: %s", fid, exc)
+ return media_urls, media_types
+
async def _handle_ws_event(self, event: Dict[str, Any]) -> None:
"""Process a single WebSocket event."""
- event_type = event.get("event")
- if event_type != "posted":
+ if event.get("event") != "posted":
return
-
data = event.get("data", {})
raw_post_str = data.get("post")
if not raw_post_str:
return
-
try:
post = json.loads(raw_post_str)
except (json.JSONDecodeError, TypeError):
return
-
- # Ignore own messages.
- if post.get("user_id") == self._bot_user_id:
- return
-
- # Ignore system posts.
- if post.get("type"):
+ # Ignore own messages and system posts.
+ if post.get("user_id") == self._bot_user_id or post.get("type"):
return
-
post_id = post.get("id", "")
-
- # Dedup.
if self._dedup.is_duplicate(post_id):
return
- # Build message event.
channel_id = post.get("channel_id", "")
channel_type_raw = data.get("channel_type", "O")
chat_type = _CHANNEL_TYPE_MAP.get(channel_type_raw, "channel")
-
- # For DMs, user_id is sufficient. For channels, check for @mention.
message_text = post.get("message", "")
- # Mention-gating for non-DM channels.
- # Config (config.yaml `mattermost.*` with env-var fallback):
- # require_mention / MATTERMOST_REQUIRE_MENTION: Require @mention in channels (default: true)
- # free_response_channels / MATTERMOST_FREE_RESPONSE_CHANNELS: Channel IDs where bot responds without mention
- # allowed_channels / MATTERMOST_ALLOWED_CHANNELS: If set, bot ONLY responds in these channels (whitelist)
+ # DMs need no gating; channels are mention-gated.
if channel_type_raw != "D":
- # allowed_channels check (whitelist — must pass before other gating).
- # When set, messages from channels NOT in this list are silently
- # ignored, even if @mentioned. DMs are already excluded above.
- allowed_raw = self.config.extra.get("allowed_channels") if self.config.extra else None
- if allowed_raw is None:
- allowed_raw = _get_scoped_secret("MATTERMOST_ALLOWED_CHANNELS", "")
- if isinstance(allowed_raw, list):
- allowed_channels = {str(c).strip() for c in allowed_raw if str(c).strip()}
- else:
- allowed_channels = {
- c.strip() for c in str(allowed_raw).split(",") if c.strip()
- }
- if allowed_channels and channel_id not in allowed_channels:
- logger.debug(
- "Mattermost: ignoring message in non-allowed channel: %s",
- channel_id,
- )
+ message_text = self._apply_channel_gating(channel_id, message_text)
+ if message_text is None:
return
- require_mention_raw = self.config.extra.get("require_mention") if self.config.extra else None
- if require_mention_raw is None:
- require_mention_raw = _get_scoped_secret("MATTERMOST_REQUIRE_MENTION", "true")
- require_mention = str(require_mention_raw).lower() not in {"false", "0", "no"}
-
- free_channels_raw = self.config.extra.get("free_response_channels") if self.config.extra else None
- if free_channels_raw is None:
- free_channels_raw = _get_scoped_secret("MATTERMOST_FREE_RESPONSE_CHANNELS", "")
- if isinstance(free_channels_raw, list):
- free_channels = {str(ch).strip() for ch in free_channels_raw if str(ch).strip()}
- else:
- free_channels = {ch.strip() for ch in str(free_channels_raw).split(",") if ch.strip()}
- is_free_channel = channel_id in free_channels
-
- mention_patterns = [
- f"@{self._bot_username}",
- f"@{self._bot_user_id}",
- ]
- has_mention = any(
- pattern.lower() in message_text.lower()
- for pattern in mention_patterns
- )
-
- if require_mention and not is_free_channel and not has_mention:
- logger.debug(
- "Mattermost: skipping non-DM message without @mention (channel=%s)",
- channel_id,
- )
- return
-
- # Strip @mention from the message text so the agent sees clean input.
- if has_mention:
- for pattern in mention_patterns:
- message_text = re.sub(
- re.escape(pattern), "", message_text, flags=re.IGNORECASE
- ).strip()
-
- # Resolve sender info.
sender_id = post.get("user_id", "")
sender_name = data.get("sender_name", "").lstrip("@") or sender_id
- # Thread support: if the post is in a thread, use root_id. In
- # thread mode, top-level channel posts are valid roots for progress.
+ # Thread support: replies use root_id; in thread mode a top-level channel
+ # post is itself a valid root for progress.
thread_id = post.get("root_id") or None
- if (
- not thread_id
- and self._reply_mode == "thread"
- and channel_type_raw != "D"
- and post_id
- ):
+ if not thread_id and self._reply_mode == "thread" and channel_type_raw != "D" and post_id:
thread_id = post_id
- # Determine message type.
- file_ids = post.get("file_ids") or []
msg_type = MessageType.TEXT
if message_text[:1].isspace() and message_text.lstrip().startswith("/"):
message_text = message_text.lstrip()
if message_text.startswith("/"):
msg_type = MessageType.COMMAND
- # Download file attachments immediately (URLs require auth headers
- # that downstream tools won't have).
- media_urls: List[str] = []
- media_types: List[str] = []
- for fid in file_ids:
- try:
- file_info = await self._api_get(f"files/{fid}/info")
- fname = file_info.get("name", f"file_{fid}")
- ext = Path(fname).suffix or ""
- mime = file_info.get("mime_type", "application/octet-stream")
-
- import aiohttp
- dl_url = f"{self._base_url}/api/v4/files/{fid}"
- async with self._session.get(
- dl_url,
- headers={"Authorization": f"Bearer {self._token}"},
- timeout=aiohttp.ClientTimeout(total=30),
- ) as resp:
- if resp.status < 400:
- file_data = await resp.read()
- from gateway.platforms.base import cache_image_from_bytes, cache_document_from_bytes
- if mime.startswith("image/"):
- local_path = cache_image_from_bytes(file_data, ext or ".png")
- media_urls.append(local_path)
- media_types.append(mime)
- elif mime.startswith("audio/"):
- from gateway.platforms.base import cache_audio_from_bytes
- local_path = cache_audio_from_bytes(file_data, ext or ".ogg")
- media_urls.append(local_path)
- media_types.append(mime)
- else:
- local_path = cache_document_from_bytes(file_data, fname)
- media_urls.append(local_path)
- media_types.append(mime)
- else:
- logger.warning("Mattermost: failed to download file %s: HTTP %s", fid, resp.status)
- except Exception as exc:
- logger.warning("Mattermost: error downloading file %s: %s", fid, exc)
-
- # Set message type based on downloaded media types.
+ media_urls, media_types = await self._download_attachments(post.get("file_ids") or [])
if media_types and msg_type == MessageType.TEXT:
if any(m.startswith("image/") for m in media_types):
msg_type = MessageType.PHOTO
elif any(m.startswith("audio/") for m in media_types):
msg_type = MessageType.VOICE
- elif media_types:
+ else:
msg_type = MessageType.DOCUMENT
source = self.build_source(
- chat_id=channel_id,
- chat_type=chat_type,
- user_id=sender_id,
- user_name=sender_name,
- thread_id=thread_id,
- message_id=post_id,
+ chat_id=channel_id, chat_type=chat_type, user_id=sender_id, user_name=sender_name,
+ thread_id=thread_id, message_id=post_id,
)
-
- # Per-channel ephemeral prompt
from gateway.platforms.base import resolve_channel_prompt
- _channel_prompt = resolve_channel_prompt(
- self.config.extra, channel_id, None,
- )
-
msg_event = MessageEvent(
- text=message_text,
- message_type=msg_type,
- source=source,
- raw_message=post,
- message_id=post_id,
- media_urls=media_urls if media_urls else None,
- media_types=media_types if media_types else None,
- channel_prompt=_channel_prompt,
+ text=message_text, message_type=msg_type, source=source, raw_message=post, message_id=post_id,
+ media_urls=media_urls if media_urls else None, media_types=media_types if media_types else None,
+ channel_prompt=resolve_channel_prompt(self.config.extra, channel_id, None),
)
-
await self.handle_message(msg_event)
-
-
-# ---------------------------------------------------------------------------
-# Plugin standalone-send (out-of-process cron delivery via Mattermost REST)
-# ---------------------------------------------------------------------------
+# --- Plugin standalone-send (out-of-process cron delivery via Mattermost REST) ---
async def _standalone_send(
- pconfig,
- chat_id: str,
- message: str,
- *,
- thread_id: Optional[str] = None,
- media_files: Optional[list] = None,
- force_document: bool = False,
+ pconfig, chat_id: str, message: str, *, thread_id: Optional[str] = None,
+ media_files: Optional[list] = None, force_document: bool = False,
) -> Dict[str, Any]:
"""Send via the Mattermost v4 REST API without a live gateway adapter.
- Used by ``tools/send_message_tool._send_via_adapter`` when the gateway
- runner is not in this process (typical for cron jobs running out-of-process).
- Reads ``MATTERMOST_TOKEN`` from ``pconfig.token`` (set by the gateway
- config loader from env) and falls back to the ``MATTERMOST_TOKEN`` env
- var. Server URL comes from ``pconfig.extra["url"]`` (set by the YAML
- bridge / env loader) or the ``MATTERMOST_URL`` env var.
-
- Thread replies (Mattermost CRT) are supported via the ``root_id`` field
- on the ``POST /posts`` payload — pass ``thread_id`` when threading is
- desired. ``media_files`` are uploaded via ``POST /files``
- (multipart/form-data), then their returned ``file_id`` values are
- attached to the post.
-
- ``force_document`` is accepted for signature parity with other
- standalone senders but unused — Mattermost stores every uploaded file
- as a generic attachment regardless.
+ Used by ``tools/send_message_tool._send_via_adapter`` when the gateway runner
+ is out-of-process (cron). Token/URL come from ``pconfig`` with env fallback.
+ ``media_files`` are uploaded via ``POST /files`` and attached by file_id;
+ ``thread_id`` becomes ``root_id``. ``force_document`` is accepted for
+ signature parity but unused (Mattermost stores every upload as an attachment).
"""
try:
import aiohttp
except ImportError:
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
- base_url = (
- (getattr(pconfig, "extra", {}) or {}).get("url")
- or _get_scoped_secret("MATTERMOST_URL", "")
- ).rstrip("/")
+ base_url = ((getattr(pconfig, "extra", {}) or {}).get("url") or _get_scoped_secret("MATTERMOST_URL", "")).rstrip("/")
token = (getattr(pconfig, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip()
if not base_url or not token:
- return {
- "error": (
- "Mattermost standalone send: MATTERMOST_URL and "
- "MATTERMOST_TOKEN must both be set"
- )
- }
-
- headers = {
- "Authorization": f"Bearer {token}",
- "Content-Type": "application/json",
- }
- upload_headers = {"Authorization": f"Bearer {token}"}
+ return {"error": "Mattermost standalone send: MATTERMOST_URL and MATTERMOST_TOKEN must both be set"}
- media_files = media_files or []
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+ upload_headers = {"Authorization": f"Bearer {token}"}
try:
- # Resolve proxy + session kwargs once so a single ClientSession can
- # cover the optional file uploads + final post.
+ # One ClientSession (with proxy) covers the optional uploads + final post.
from gateway.platforms.base import resolve_proxy_url, proxy_kwargs_for_aiohttp
- _proxy = resolve_proxy_url(platform_env_var="MATTERMOST_PROXY")
- _sess_kw, _req_kw = proxy_kwargs_for_aiohttp(_proxy)
-
- async with aiohttp.ClientSession(
- timeout=aiohttp.ClientTimeout(total=60),
- **_sess_kw,
- ) as session:
- # 1. Upload media (if any) and collect file_ids.
+ _sess_kw, _req_kw = proxy_kwargs_for_aiohttp(resolve_proxy_url(platform_env_var="MATTERMOST_PROXY"))
+
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=60), **_sess_kw) as session:
file_ids: List[str] = []
- for media in media_files:
+ for media in media_files or []:
file_path = media.get("path") if isinstance(media, dict) else media
if not file_path or not os.path.exists(file_path):
continue
form = aiohttp.FormData()
- # Mattermost requires channel_id on file uploads so the
- # server can attribute them.
- form.add_field("channel_id", chat_id)
+ form.add_field("channel_id", chat_id) # required so the server can attribute the upload
with open(file_path, "rb") as fh:
- form.add_field(
- "files",
- fh.read(),
- filename=os.path.basename(file_path),
- )
+ form.add_field("files", fh.read(), filename=os.path.basename(file_path))
async with session.post(
- f"{base_url}/api/v4/files",
- data=form,
- headers=upload_headers,
- **_req_kw,
+ f"{base_url}/api/v4/files", data=form, headers=upload_headers, **_req_kw
) as upload_resp:
if upload_resp.status not in {200, 201}:
body = await upload_resp.text()
- return {
- "error": (
- f"Mattermost file upload failed "
- f"({upload_resp.status}): {body[:400]}"
- )
- }
+ return {"error": f"Mattermost file upload failed ({upload_resp.status}): {body[:400]}"}
upload_data = await upload_resp.json()
for info in upload_data.get("file_infos", []):
if info.get("id"):
file_ids.append(info["id"])
- # 2. Post the message (with thread root + attached file_ids).
- payload: Dict[str, Any] = {
- "channel_id": chat_id,
- "message": message,
- }
+ payload: Dict[str, Any] = {"channel_id": chat_id, "message": message}
if thread_id:
payload["root_id"] = thread_id
if file_ids:
payload["file_ids"] = file_ids
- async with session.post(
- f"{base_url}/api/v4/posts",
- headers=headers,
- json=payload,
- **_req_kw,
- ) as resp:
+ async with session.post(f"{base_url}/api/v4/posts", headers=headers, json=payload, **_req_kw) as resp:
if resp.status not in {200, 201}:
body = await resp.text()
- return {
- "error": (
- f"Mattermost API error ({resp.status}): "
- f"{body[:400]}"
- )
- }
+ return {"error": f"Mattermost API error ({resp.status}): {body[:400]}"}
data = await resp.json()
- return {
- "success": True,
- "platform": "mattermost",
- "chat_id": chat_id,
- "message_id": data.get("id"),
- }
+ return {"success": True, "platform": "mattermost", "chat_id": chat_id, "message_id": data.get("id")}
except aiohttp.ClientError as exc:
return {"error": f"Mattermost send failed (network): {exc}"}
except Exception as exc: # noqa: BLE001
return {"error": f"Mattermost send failed: {exc}"}
-# ---------------------------------------------------------------------------
-# Interactive setup wizard
-# ---------------------------------------------------------------------------
+# --- Interactive setup wizard ---
def interactive_setup() -> None:
- """Guide the user through Mattermost bot setup.
-
- Mirrors Discord/Teams' ``interactive_setup`` shape: lazy-imports CLI
- helpers so the plugin's import surface stays small, prompts for the
- server URL + bot token, captures an allowlist, and offers to set a
- home channel. Replaces the central
- ``hermes_cli/setup.py::_setup_mattermost`` function this migration
- removes.
- """
+ """Guide the user through Mattermost bot setup (URL + token, allowlist, home channel)."""
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
- from hermes_cli.cli_output import (
- prompt,
- prompt_yes_no,
- print_header,
- print_info,
- print_success,
- )
+ from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_info, print_success
print_header("Mattermost")
- existing = get_env_value("MATTERMOST_TOKEN")
- if existing:
+ if get_env_value("MATTERMOST_TOKEN"):
print_info("Mattermost: already configured")
if not prompt_yes_no("Reconfigure Mattermost?", False):
return
@@ -1229,88 +837,48 @@ def interactive_setup() -> None:
home_channel = prompt("Home channel ID (leave empty to set later with /set-home)").strip()
if home_channel:
save_env_value("MATTERMOST_HOME_CHANNEL", home_channel)
- else:
- if remove_env_value("MATTERMOST_HOME_CHANNEL"):
- print_info("Home channel cleared.")
+ elif remove_env_value("MATTERMOST_HOME_CHANNEL"):
+ print_info("Home channel cleared.")
print_info(" Open config in your editor: hermes config edit")
-# ---------------------------------------------------------------------------
-# YAML → env config bridge (apply_yaml_config_fn, #25443)
-# ---------------------------------------------------------------------------
+# --- YAML → env config bridge (apply_yaml_config_fn) ---
-def _profile_scoped_config_load() -> bool:
- """True when running inside a multiplexed secondary profile's scope.
+def _apply_yaml_config(yaml_cfg: dict, mattermost_cfg: dict) -> dict | None:
+ """Translate ``config.yaml`` ``mattermost:`` keys into env vars + ``PlatformConfig.extra``.
- Secondary-profile adapters are constructed and connected inside
- ``_profile_runtime_scope`` (secret scope installed + multiplex active) --
- the same discriminator the Buzz/Discord/Telegram/WhatsApp/LINE/DingTalk
- adapters use for this bug class (#98738 / #72348 / #80099). The DEFAULT
- profile under multiplexing runs unscoped: ``os.environ`` holds its own
- bridge output there and keeps its legacy precedence.
+ Env vars win over YAML (each write is guarded by ``not os.getenv``). Under a
+ multiplexed secondary profile the env write is skipped entirely (it would leak
+ into every other profile via process-global ``os.environ``); the values are
+ returned instead so the caller seeds this profile's ``PlatformConfig.extra``,
+ which the adapter's read sites check first.
"""
- try:
- from agent.secret_scope import current_secret_scope, is_multiplex_active
-
- return bool(is_multiplex_active() and current_secret_scope() is not None)
- except Exception:
- return False
+ skip_env_bridge = _profile_scoped_config_load()
+ seeded: dict = {}
+ def bridge(key: str, env: str, value: Any, to_env) -> None:
+ seeded[key] = value
+ if not skip_env_bridge and not os.getenv(env):
+ os.environ[env] = to_env(value)
-def _apply_yaml_config(yaml_cfg: dict, mattermost_cfg: dict) -> dict | None:
- """Translate ``config.yaml`` ``mattermost:`` keys into env vars and
- ``PlatformConfig.extra`` entries.
-
- Implements the ``apply_yaml_config_fn`` contract (#24836 / #25443).
- Mirrors the legacy ``mattermost_cfg`` block that used to live in
- ``gateway/config.py::load_gateway_config()`` before this migration.
-
- Env vars take precedence over YAML for single-profile deployments --
- each env write is guarded by ``not os.getenv(...)`` so an explicit env
- var survives a config.yaml update. Under a multiplexed secondary
- profile's scope, the env write is skipped entirely (it would otherwise
- leak into the process-global ``os.environ`` and be inherited by every
- other profile); instead the values are returned so the caller merges
- them into this profile's own ``PlatformConfig.extra``, which the
- require_mention/free_response_channels/allowed_channels read sites now
- check first.
- """
- _skip_env_bridge = _profile_scoped_config_load()
- seeded: dict = {}
if "require_mention" in mattermost_cfg:
- seeded["require_mention"] = mattermost_cfg["require_mention"]
- if not _skip_env_bridge and not os.getenv("MATTERMOST_REQUIRE_MENTION"):
- os.environ["MATTERMOST_REQUIRE_MENTION"] = str(mattermost_cfg["require_mention"]).lower()
- frc = mattermost_cfg.get("free_response_channels")
- if frc is not None:
- seeded["free_response_channels"] = frc
- if not _skip_env_bridge and not os.getenv("MATTERMOST_FREE_RESPONSE_CHANNELS"):
- _frc = ",".join(str(v) for v in frc) if isinstance(frc, list) else str(frc)
- os.environ["MATTERMOST_FREE_RESPONSE_CHANNELS"] = _frc
- # allowed_channels: if set, bot ONLY responds in these channels (whitelist)
- ac = mattermost_cfg.get("allowed_channels")
- if ac is not None:
- seeded["allowed_channels"] = ac
- if not _skip_env_bridge and not os.getenv("MATTERMOST_ALLOWED_CHANNELS"):
- _ac = ",".join(str(v) for v in ac) if isinstance(ac, list) else str(ac)
- os.environ["MATTERMOST_ALLOWED_CHANNELS"] = _ac
+ bridge("require_mention", "MATTERMOST_REQUIRE_MENTION", mattermost_cfg["require_mention"], lambda v: str(v).lower())
+ for key, env in (
+ ("free_response_channels", "MATTERMOST_FREE_RESPONSE_CHANNELS"),
+ ("allowed_channels", "MATTERMOST_ALLOWED_CHANNELS"), # whitelist: bot ONLY responds in these
+ ):
+ value = mattermost_cfg.get(key)
+ if value is not None:
+ bridge(key, env, value, _csv)
return seeded or None
-# ---------------------------------------------------------------------------
-# is_connected probe
-# ---------------------------------------------------------------------------
-
-
def _is_connected(config) -> bool:
- """Mattermost is considered connected when BOTH MATTERMOST_TOKEN and
- MATTERMOST_URL are set.
+ """Connected when BOTH MATTERMOST_TOKEN and MATTERMOST_URL are set.
- Looks up via ``hermes_cli.gateway.get_env_value`` at call time (not via
- the plugin's own bound import) so tests that patch
- ``gateway_mod.get_env_value`` can suppress ambient env vars. Matches
- what the legacy connected-platforms check did before this migration.
+ Looks up ``hermes_cli.gateway.get_env_value`` at call time so tests that patch
+ ``gateway_mod.get_env_value`` can suppress ambient env vars.
"""
import hermes_cli.gateway as gateway_mod
return bool(
@@ -1319,9 +887,7 @@ def _is_connected(config) -> bool:
)
-# ---------------------------------------------------------------------------
-# Plugin registration entry point
-# ---------------------------------------------------------------------------
+# --- Plugin registration entry point ---
def _build_adapter(config):
@@ -1340,31 +906,15 @@ def register(ctx) -> None:
is_connected=_is_connected,
required_env=["MATTERMOST_URL", "MATTERMOST_TOKEN"],
install_hint="pip install aiohttp",
- # Interactive setup wizard — replaces the central
- # hermes_cli/setup.py::_setup_mattermost function.
setup_fn=interactive_setup,
- # YAML→env config bridge — owns the translation of
- # ``config.yaml`` ``mattermost:`` keys (require_mention,
- # free_response_channels, allowed_channels) into ``MATTERMOST_*``
- # env vars that the adapter reads via ``os.getenv()``. Replaces
- # the hardcoded block that used to live in ``gateway/config.py``.
- # Hook contract: #24836 / #25443.
+ # YAML→env bridge for require_mention / free_response_channels / allowed_channels.
apply_yaml_config_fn=_apply_yaml_config,
- # Auth env vars for _is_user_authorized() integration.
allowed_users_env="MATTERMOST_ALLOWED_USERS",
allow_all_env="MATTERMOST_ALLOW_ALL_USERS",
- # Cron home-channel delivery.
cron_deliver_env_var="MATTERMOST_HOME_CHANNEL",
- # Out-of-process cron delivery via Mattermost REST API. Without
- # this hook, ``deliver=mattermost`` cron jobs fail with "No live
- # adapter" when cron runs separately from the gateway. Mirrors
- # the Discord / Teams pattern.
+ # Out-of-process cron delivery; without it `deliver=mattermost` fails with "No live adapter".
standalone_sender_fn=_standalone_send,
- # Mattermost practical post-length limit (server default is 16383
- # but 4000 is the readable threshold the adapter has used since
- # day one).
max_message_length=MAX_POST_LENGTH,
- # Display
emoji="💬",
allow_update_command=True,
)
diff --git a/plugins/platforms/simplex/adapter.py b/plugins/platforms/simplex/adapter.py
index 979c1e6ea3a..45c1941b97c 100644
--- a/plugins/platforms/simplex/adapter.py
+++ b/plugins/platforms/simplex/adapter.py
@@ -1,14 +1,10 @@
"""SimpleX Chat platform adapter (Hermes plugin).
-Connects to a simplex-chat daemon running in WebSocket mode.
-Inbound messages arrive via a persistent WebSocket connection.
-Outbound messages use the same WebSocket with JSON commands.
-
-This adapter ships as a Hermes platform plugin under
-``plugins/platforms/simplex/``. The Hermes plugin loader scans the
-directory at startup, calls ``register(ctx)``, and the platform
-becomes available to ``gateway/run.py`` and ``tools/send_message_tool``
-through the registry — no edits to core files are required.
+Connects to a simplex-chat daemon running in WebSocket mode. Inbound messages
+arrive via a persistent WebSocket connection; outbound messages use the same
+WebSocket with JSON commands. The plugin loader calls ``register(ctx)`` at
+startup and the platform becomes available to ``gateway/run.py`` and
+``tools/send_message_tool`` through the registry.
SimpleX chat daemon setup:
simplex-chat -p 5225 # start daemon on port 5225
@@ -35,13 +31,11 @@ Optional environment variables:
HERMES_SIMPLEX_TEXT_BATCH_DELAY
Quiet-period seconds (default: 0.8) used to
concatenate rapid-fire inbound text messages
- into a single MessageEvent — same pattern as
- Telegram's text batching.
+ into a single MessageEvent.
-The ``websockets`` Python package is imported lazily — the plugin is
-discoverable and ``hermes setup`` can describe it even when websockets is
-not installed. ``check_requirements()`` returns False until the package
-is present, so the gateway will not attempt to instantiate the adapter.
+``websockets`` is imported lazily so the plugin stays discoverable (and
+``hermes setup`` can describe it) when the package is missing;
+``check_requirements()`` returns False until it is present.
"""
import asyncio
@@ -56,44 +50,12 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional
-from agent.secret_scope import UnscopedSecretError as _UnscopedSecretError
-from agent.secret_scope import get_secret as _scoped_get_secret
-
-
-def _get_scoped_secret(name, default=None):
- """Scope-aware env read with the default-profile startup fallback.
-
- Secondary profiles construct their adapters under a profile secret
- scope -- the scope is authoritative and a scoped miss returns ``default``
- (no cross-profile borrow from ``os.environ``, which holds the DEFAULT
- profile's YAML-to-env bridge output under multiplexing). The default
- profile's adapter constructs *unscoped*, where a bare ``get_secret``
- would raise ``UnscopedSecretError``; there ``os.environ`` is that
- profile's own value, so fall back to it. Same helper as the IRC/ntfy/
- Mattermost plugins.
- """
- try:
- val = _scoped_get_secret(name, default)
- except _UnscopedSecretError:
- val = os.getenv(name)
- return val if val is not None else default
-
-# Lazy import: BasePlatformAdapter and friends live in the main repo.
-# Imported at module top because they're stdlib-only inside Hermes — no
-# external dependency that would block the plugin from loading.
+from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
from gateway.config import Platform, PlatformConfig
-from gateway.platforms.base import (
- BasePlatformAdapter,
- MessageEvent,
- MessageType,
- SendResult,
-)
+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Constants
-# ---------------------------------------------------------------------------
MAX_MESSAGE_LENGTH = 8000 # SimpleX has no hard limit; chunk for sanity
WS_RETRY_DELAY_INITIAL = 2.0
WS_RETRY_DELAY_MAX = 60.0
@@ -103,10 +65,9 @@ HEALTH_CHECK_STALE_THRESHOLD = 300.0
# Correlation ID prefix for requests we send so we can ignore our own echoes.
_CORR_PREFIX = "hermes-"
+_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
+_AUDIO_EXTS = {".mp3", ".wav", ".ogg", ".m4a", ".aac", ".opus"}
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
def _parse_comma_list(value: str) -> List[str]:
"""Split a comma-separated string into a stripped list."""
@@ -118,112 +79,89 @@ def _redact_id(contact_id: str) -> str:
if not contact_id:
return "<none>"
s = str(contact_id)
- if len(s) <= 4:
- return s
- return s[:2] + "**" + s[-2:]
-
-
-def _guess_extension(data: bytes) -> str:
- """Guess file extension from magic bytes."""
- if data[:4] == b"\x89PNG":
- return ".png"
- if data[:2] == b"\xff\xd8":
- return ".jpg"
- if data[:4] == b"GIF8":
- return ".gif"
- if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
- return ".webp"
- if data[:4] == b"%PDF":
- return ".pdf"
- if len(data) >= 8 and data[4:8] == b"ftyp":
- return ".mp4"
- if data[:4] == b"OggS":
- return ".ogg"
- if len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0:
- return ".mp3"
- return ".bin"
+ return s if len(s) <= 4 else s[:2] + "**" + s[-2:]
def _is_image_ext(ext: str) -> bool:
- return ext.lower() in {".jpg", ".jpeg", ".png", ".gif", ".webp"}
+ return ext.lower() in _IMAGE_EXTS
def _is_audio_ext(ext: str) -> bool:
- return ext.lower() in {".mp3", ".wav", ".ogg", ".m4a", ".aac", ".opus"}
+ return ext.lower() in _AUDIO_EXTS
-# ---------------------------------------------------------------------------
-# SimpleX Adapter
-# ---------------------------------------------------------------------------
-
-class SimplexAdapter(BasePlatformAdapter):
- """SimpleX Chat adapter using the simplex-chat daemon WebSocket API.
+def _send_cmd(chat_id: str, items: list) -> str:
+ """Build a structured ``/_send`` command addressing *chat_id* by ID.
- Instantiated by the ``adapter_factory`` passed to
- ``ctx.register_platform()`` in :func:`register`.
+ The structured json form is used (rather than ``@name text`` / ``#[id]``)
+ because the daemon parses the bare syntax as a display-name lookup and
+ silently drops messages when the name doesn't resolve; json.dumps also
+ escapes newlines/special chars correctly.
"""
+ composed = json.dumps(items)
+ if chat_id.startswith("group:"):
+ return f"/_send #{chat_id[6:]} json {composed}"
+ return f"/_send @{chat_id} json {composed}"
+
+
+async def _cancel_task(task: Optional[asyncio.Task]) -> None:
+ if task:
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+
+class SimplexAdapter(BasePlatformAdapter):
+ """SimpleX Chat adapter using the simplex-chat daemon WebSocket API."""
MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
def __init__(self, config: PlatformConfig, **kwargs):
- platform = Platform("simplex")
- super().__init__(config=config, platform=platform)
+ super().__init__(config=config, platform=Platform("simplex"))
extra = getattr(config, "extra", {}) or {}
self.ws_url = extra.get("ws_url", "ws://127.0.0.1:5225").rstrip("/")
- # Contact-request auto-accept (on by default — matches the way most
- # bot deployments expect to behave). Read from env first, then fall
- # back to the value seeded by ``_env_enablement``.
+ # Auto-accept is on by default; env wins over the ``_env_enablement`` seed.
env_auto = _get_scoped_secret("SIMPLEX_AUTO_ACCEPT")
if env_auto is not None:
self.auto_accept = env_auto.strip().lower() not in {"0", "false", "no", ""}
else:
self.auto_accept = bool(extra.get("auto_accept", True))
- # Group allowlist. Without ``SIMPLEX_GROUP_ALLOWED``, group messages
- # are ignored entirely (safer default — a bot in a group otherwise
- # processes every member's traffic). Use ``*`` to accept any group.
- group_allowed_str = _get_scoped_secret("SIMPLEX_GROUP_ALLOWED", "") or extra.get(
- "group_allowed", ""
- )
+ # Without SIMPLEX_GROUP_ALLOWED, group messages are ignored entirely
+ # (safer default). ``*`` accepts any group.
+ group_allowed_str = (_get_scoped_secret("SIMPLEX_GROUP_ALLOWED", "")
+ or extra.get("group_allowed", ""))
self.group_allow_from = set(_parse_comma_list(group_allowed_str))
- # Running state
self._ws = None # websockets connection
self._ws_task: Optional[asyncio.Task] = None
self._health_task: Optional[asyncio.Task] = None
self._running = False
self._last_ws_activity = 0.0
- # Track sent correlation IDs to filter echoes
+ # Cosmetic echo filter: corrIds we minted, bounded.
self._pending_corr_ids: set = set()
self._max_pending_corr = 200
- # File transfers awaiting rcvFileComplete (keyed by fileId). Populated
- # when a newChatItems event carries an unfinished rcvFileTransfer,
- # consumed when the file finishes downloading.
+ # File transfers awaiting rcvFileComplete (keyed by fileId).
self._pending_file_transfers: Dict[int, dict] = {}
- # Correlation tracking for ``_send_command``. Separate from
- # ``_pending_corr_ids`` (which is the upstream cosmetic echo filter)
- # because we actually await responses to commands we send.
+ # Futures for commands whose responses we actually await (``_send_command``).
self._pending_responses: Dict[str, asyncio.Future] = {}
self._corr_counter = 0
- # Text message batching — concatenate rapid-fire messages into one
- # event before dispatching, mirroring Telegram's batching.
- self._text_batch_delay = float(
- os.getenv("HERMES_SIMPLEX_TEXT_BATCH_DELAY", "0.8")
- )
+ # Text batching state consumed by BasePlatformAdapter._enqueue_text_event.
+ self._text_batch_delay = float(os.getenv("HERMES_SIMPLEX_TEXT_BATCH_DELAY", "0.8"))
self._pending_text_batches: Dict[str, MessageEvent] = {}
self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}
logger.info(
"SimpleX adapter initialized: url=%s auto_accept=%s groups=%s",
- self.ws_url,
- self.auto_accept,
- "enabled" if self.group_allow_from else "disabled",
+ self.ws_url, self.auto_accept, "enabled" if self.group_allow_from else "disabled",
)
# ------------------------------------------------------------------
@@ -233,21 +171,17 @@ class SimplexAdapter(BasePlatformAdapter):
async def connect(self, *, is_reconnect: bool = False) -> bool:
"""Connect to the simplex-chat daemon and start the WebSocket listener."""
try:
- import websockets # noqa: F401
+ import websockets as _wsclient
except ImportError:
- logger.error(
- "SimpleX: 'websockets' package not installed. "
- "Run: pip install websockets"
- )
+ logger.error("SimpleX: 'websockets' package not installed. Run: pip install websockets")
return False
if not self.ws_url:
logger.error("SimpleX: SIMPLEX_WS_URL is required")
return False
- # Quick connectivity check — try to open and immediately close
+ # Quick connectivity check — open and immediately close.
try:
- import websockets as _wsclient
async with _wsclient.connect(self.ws_url, open_timeout=10):
pass
except Exception as e:
@@ -262,27 +196,14 @@ class SimplexAdapter(BasePlatformAdapter):
if hasattr(self, "_mark_connected"):
self._mark_connected()
logger.info("SimpleX: connected to %s", self.ws_url)
- # Plugin-registered native handlers (ctx.register_platform_handler).
self._wire_plugin_handlers(None)
return True
async def disconnect(self) -> None:
"""Stop WebSocket listener and clean up."""
self._running = False
-
- if self._ws_task:
- self._ws_task.cancel()
- try:
- await self._ws_task
- except asyncio.CancelledError:
- pass
-
- if self._health_task:
- self._health_task.cancel()
- try:
- await self._health_task
- except asyncio.CancelledError:
- pass
+ await _cancel_task(self._ws_task)
+ await _cancel_task(self._health_task)
if self._ws:
try:
@@ -291,14 +212,12 @@ class SimplexAdapter(BasePlatformAdapter):
pass
self._ws = None
- # Cancel pending text-batch flush timers
for task in list(self._pending_text_batch_tasks.values()):
if not task.done():
task.cancel()
self._pending_text_batch_tasks.clear()
self._pending_text_batches.clear()
- # Cancel pending command futures
for fut in self._pending_responses.values():
if not fut.done():
fut.cancel()
@@ -309,7 +228,7 @@ class SimplexAdapter(BasePlatformAdapter):
logger.info("SimpleX: disconnected")
# ------------------------------------------------------------------
- # WebSocket listener
+ # WebSocket listener / health
# ------------------------------------------------------------------
async def _ws_listener(self) -> None:
@@ -318,15 +237,11 @@ class SimplexAdapter(BasePlatformAdapter):
from websockets.exceptions import ConnectionClosed
backoff = WS_RETRY_DELAY_INITIAL
-
while self._running:
try:
logger.debug("SimpleX WS: connecting to %s", self.ws_url)
async with _wsclient.connect(
- self.ws_url,
- ping_interval=20,
- ping_timeout=20,
- close_timeout=10,
+ self.ws_url, ping_interval=20, ping_timeout=20, close_timeout=10
) as ws:
self._ws = ws
backoff = WS_RETRY_DELAY_INITIAL
@@ -338,46 +253,34 @@ class SimplexAdapter(BasePlatformAdapter):
break
self._last_ws_activity = time.time()
try:
- msg = json.loads(raw)
- await self._handle_event(msg)
+ await self._handle_event(json.loads(raw))
except json.JSONDecodeError:
logger.debug("SimpleX WS: invalid JSON: %.100s", raw)
except Exception:
logger.exception("SimpleX WS: error handling event")
-
except asyncio.CancelledError:
break
except ConnectionClosed as e:
if self._running:
- logger.warning(
- "SimpleX WS: connection closed: %s (reconnecting in %.0fs)",
- e, backoff,
- )
+ logger.warning("SimpleX WS: connection closed: %s (reconnecting in %.0fs)",
+ e, backoff)
except Exception as e:
if self._running:
- logger.warning(
- "SimpleX WS: unexpected error: %s (reconnecting in %.0fs)",
- e, backoff,
- )
+ logger.warning("SimpleX WS: unexpected error: %s (reconnecting in %.0fs)",
+ e, backoff)
finally:
self._ws = None
if self._running:
- jitter = backoff * 0.2 * random.random()
- await asyncio.sleep(backoff + jitter)
+ await asyncio.sleep(backoff + backoff * 0.2 * random.random())
backoff = min(backoff * 2, WS_RETRY_DELAY_MAX)
- # ------------------------------------------------------------------
- # Health monitor
- # ------------------------------------------------------------------
-
async def _health_monitor(self) -> None:
"""Observe WebSocket idleness without reconnecting healthy quiet links.
- simplex-chat can legitimately stay application-silent for long periods
- when no messages arrive. The websockets client already sends protocol
- pings (see _ws_listener ping_interval/ping_timeout), so treating lack of
- chat events as a stale connection causes needless reconnect churn.
+ simplex-chat can legitimately stay application-silent for long periods;
+ the websockets client already sends protocol pings, so idleness is only
+ logged — reconnecting on it causes needless churn.
"""
while self._running:
await asyncio.sleep(HEALTH_CHECK_INTERVAL)
@@ -393,153 +296,116 @@ class SimplexAdapter(BasePlatformAdapter):
async def _handle_event(self, event: dict) -> None:
"""Dispatch a daemon event to the appropriate handler."""
- # simplex-chat WebSocket messages are usually shaped as:
- # {"corrId": "...", "resp": {"type": "newChatItems", ...}}
- # Older/examples may put the response fields at top-level. Normalize
- # both forms before dispatching, otherwise inbound chatItems are lost.
+ # Messages are usually {"corrId": ..., "resp": {"type": ...}}, but some
+ # daemons put the response fields at top level — normalize both.
resp = event.get("resp") if isinstance(event.get("resp"), dict) else event
corr_id = event.get("corrId")
- # Handle correlated responses (replies to our own commands)
if corr_id and corr_id in self._pending_responses:
fut = self._pending_responses.pop(corr_id)
if not fut.done():
fut.set_result(resp)
return
- # Cosmetic echo filter: prefixed corrIds are ours but didn't make it
- # into _pending_responses (e.g. fire-and-forget).
+ # Cosmetic echo filter: prefixed corrIds are ours but weren't awaited.
if corr_id and isinstance(corr_id, str) and corr_id.startswith(_CORR_PREFIX):
self._pending_corr_ids.discard(corr_id)
return
resp_type = resp.get("type") or event.get("type", "")
- # Auto-accept contact requests
if resp_type == "contactRequest" and self.auto_accept:
contact_req = resp.get("contactRequest", {}) or {}
contact_req_id = contact_req.get("contactRequestId")
if contact_req_id is not None:
- logger.info(
- "SimpleX: auto-accepting contact request %s",
- _redact_id(str(contact_req_id)),
- )
+ logger.info("SimpleX: auto-accepting contact request %s",
+ _redact_id(str(contact_req_id)))
await self._send_command(f"/accept {contact_req_id}")
return
- # Early file-descriptor ready: simplex fires this before newChatItems
- # for some file types (especially large files and voice messages
- # transferred via XFTP). Send /freceive immediately so the download
- # starts; the chat item arrives in a subsequent newChatItems event.
+ # simplex fires rcvFileDescrReady before newChatItems for some (XFTP)
+ # files; start the download now, the chat item arrives later.
if resp_type == "rcvFileDescrReady":
rcv_file = resp.get("rcvFileTransfer", {}) or {}
file_id = rcv_file.get("fileId") if isinstance(rcv_file, dict) else None
if file_id is not None:
- logger.debug(
- "SimpleX: rcvFileDescrReady for fileId=%s — sending /freceive",
- file_id,
- )
+ logger.debug("SimpleX: rcvFileDescrReady for fileId=%s — sending /freceive",
+ file_id)
await self._send_fire_and_forget(f"/freceive {file_id}")
return
- # New messages — simplex-chat sends "newChatItems" with an array
if resp_type == "newChatItems":
chat_items = resp.get("chatItems", []) or []
if not isinstance(chat_items, list):
chat_items = [chat_items]
for item in chat_items:
- try:
- await self._handle_chat_item(item)
- except Exception:
- logger.exception("SimpleX: error processing chat item")
+ await self._safe_handle_chat_item(item, "SimpleX: error processing chat item")
return
# Singular variant — some daemon versions emit this
if resp_type == "newChatItem":
- try:
- await self._handle_chat_item(resp)
- except Exception:
- logger.exception("SimpleX: error processing chat item")
+ await self._safe_handle_chat_item(resp, "SimpleX: error processing chat item")
return
# File transfer completion — deliver any deferred chat item
if resp_type == "rcvFileComplete":
- chat_item = resp.get("chatItem", {}) or {}
- chat_item_data = chat_item.get("chatItem", {}) or {}
+ chat_item_data = (resp.get("chatItem", {}) or {}).get("chatItem", {}) or {}
file_info = chat_item_data.get("file", {}) or {}
file_id = file_info.get("fileId") if isinstance(file_info, dict) else None
if file_id is not None and file_id in self._pending_file_transfers:
pending = self._pending_file_transfers.pop(file_id)
file_source = file_info.get("fileSource", {}) or {}
- file_path = (
- file_source.get("filePath")
- if isinstance(file_source, dict)
- else None
- )
+ file_path = file_source.get("filePath") if isinstance(file_source, dict) else None
if file_path:
pending_item_data = pending.get("chatItem", {}) or {}
- pending_item_data.setdefault("file", {})["fileSource"] = {
- "filePath": file_path
- }
+ pending_item_data.setdefault("file", {})["fileSource"] = {"filePath": file_path}
pending["chatItem"] = pending_item_data
- try:
- await self._handle_chat_item(pending)
- except Exception:
- logger.exception(
- "SimpleX: error processing deferred file message"
- )
+ await self._safe_handle_chat_item(
+ pending, "SimpleX: error processing deferred file message")
return
if resp_type:
logger.debug("SimpleX: unhandled event type: %s", resp_type)
+ async def _safe_handle_chat_item(self, item: dict, err_msg: str) -> None:
+ try:
+ await self._handle_chat_item(item)
+ except Exception:
+ logger.exception(err_msg)
+
async def _handle_chat_item(self, chat_item: dict) -> None:
"""Process a single chat item from a newChatItems event."""
chat_info = chat_item.get("chatInfo", {}) or {}
chat_item_data = chat_item.get("chatItem", {}) or {}
-
chat_type = chat_info.get("type", "")
-
meta = chat_item_data.get("meta", {}) or {}
content = chat_item_data.get("content", {}) or {}
msg_content = content.get("msgContent", {}) or {}
# Filter out our own messages
item_direction = chat_item_data.get("chatDir", {}) or {}
- direction_type = (
- item_direction.get("type", "") if isinstance(item_direction, dict) else ""
- )
+ direction_type = item_direction.get("type", "") if isinstance(item_direction, dict) else ""
if direction_type in ("directSnd", "groupSnd"):
return
- # Only process received messages
content_type = content.get("type", "") if isinstance(content, dict) else ""
if content_type != "rcvMsgContent":
return
- # Text content
text = ""
- msg_type_str = (
- msg_content.get("type", "") if isinstance(msg_content, dict) else ""
- )
+ msg_type_str = msg_content.get("type", "") if isinstance(msg_content, dict) else ""
if msg_type_str in ("text", "file", "image", "voice", "link", "video"):
text = msg_content.get("text", "")
-
if not text and msg_type_str not in ("image", "file", "voice"):
return
- # Sender + chat IDs
- sender_id = ""
- sender_name = ""
- chat_id = ""
+ sender_id = sender_name = chat_id = ""
is_group = False
-
if chat_type == "direct":
contact = chat_info.get("contact", {}) or {}
sender_id = str(contact.get("contactId", ""))
- sender_name = contact.get("localDisplayName", "") or contact.get(
- "profile", {}
- ).get("displayName", "")
+ sender_name = (contact.get("localDisplayName", "")
+ or contact.get("profile", {}).get("displayName", ""))
chat_id = sender_id
elif chat_type == "group":
group_info = chat_info.get("groupInfo", {}) or {}
@@ -549,25 +415,15 @@ class SimplexAdapter(BasePlatformAdapter):
member = item_direction.get("groupMember", {}) or {}
sender_id = str(member.get("memberId", ""))
- sender_name = member.get("localDisplayName", "") or member.get(
- "memberProfile", {}
- ).get("displayName", "")
+ sender_name = (member.get("localDisplayName", "")
+ or member.get("memberProfile", {}).get("displayName", ""))
- # Group allowlist
if self.group_allow_from:
- if (
- "*" not in self.group_allow_from
- and group_id not in self.group_allow_from
- ):
- logger.debug(
- "SimpleX: group %s not in allowlist",
- _redact_id(group_id),
- )
+ if "*" not in self.group_allow_from and group_id not in self.group_allow_from:
+ logger.debug("SimpleX: group %s not in allowlist", _redact_id(group_id))
return
else:
- logger.debug(
- "SimpleX: ignoring group message (no SIMPLEX_GROUP_ALLOWED)"
- )
+ logger.debug("SimpleX: ignoring group message (no SIMPLEX_GROUP_ALLOWED)")
return
else:
logger.debug("SimpleX: unhandled chat type: %s", chat_type)
@@ -577,72 +433,49 @@ class SimplexAdapter(BasePlatformAdapter):
logger.debug("SimpleX: ignoring message with no sender")
return
- # File / image / voice attachment handling. File info is at
- # chatItem.chatItem.file (sibling of meta, content, chatDir).
+ # Attachment: chatItem.chatItem.file (sibling of meta/content/chatDir).
media_urls: List[str] = []
media_types: List[str] = []
file_info = chat_item_data.get("file")
-
if file_info and isinstance(file_info, dict):
file_source = file_info.get("fileSource", {}) or {}
- file_path = (
- file_source.get("filePath")
- if isinstance(file_source, dict)
- else None
- )
+ file_path = file_source.get("filePath") if isinstance(file_source, dict) else None
file_name = file_info.get("fileName", "")
file_id = file_info.get("fileId")
- ext = ""
- if file_path:
- ext = Path(file_path).suffix.lower()
+ ext = Path(file_path).suffix.lower() if file_path else ""
if not ext and file_name:
ext = Path(file_name).suffix.lower()
- # Voice notes typically arrive before the file finishes
- # downloading. Defer the message until rcvFileComplete fires.
+ # Voice notes typically arrive before the file finishes downloading;
+ # defer until rcvFileComplete. /freceive gets no corrId reply, so
+ # awaiting one would block the event loop.
if not file_path and _is_audio_ext(ext) and file_id is not None:
- logger.info(
- "SimpleX: voice file %d not yet received, accepting transfer",
- file_id,
- )
+ logger.info("SimpleX: voice file %d not yet received, accepting transfer", file_id)
self._pending_file_transfers[file_id] = chat_item
- # Fire-and-forget: simplex-chat does not return a corrId reply
- # for /freceive, so awaiting one would block the event loop.
await self._send_fire_and_forget(f"/freceive {file_id}")
return
if file_path:
- ext = Path(file_path).suffix.lower() or (
- Path(file_name).suffix.lower() if file_name else ""
- )
if _is_image_ext(ext):
- media_urls.append(file_path)
- media_types.append(f"image/{ext.lstrip('.')}")
+ mime = f"image/{ext.lstrip('.')}"
elif _is_audio_ext(ext):
- media_urls.append(file_path)
- media_types.append(f"audio/{ext.lstrip('.')}")
+ mime = f"audio/{ext.lstrip('.')}"
else:
- media_urls.append(file_path)
- media_types.append("application/octet-stream")
+ mime = "application/octet-stream"
+ media_urls.append(file_path)
+ media_types.append(mime)
- # Source
chat_name = sender_name
if is_group:
- group_info = chat_info.get("groupInfo", {}) or {}
chat_name = group_info.get("localDisplayName", "") or group_info.get(
"groupProfile", {}
).get("displayName", chat_id)
-
source = self.build_source(
- chat_id=chat_id,
- chat_name=chat_name,
- chat_type="group" if is_group else "dm",
- user_id=sender_id,
- user_name=sender_name or sender_id,
+ chat_id=chat_id, chat_name=chat_name, chat_type="group" if is_group else "dm",
+ user_id=sender_id, user_name=sender_name or sender_id,
)
- # Message type
msg_type = MessageType.TEXT
if media_types:
if any(mt.startswith("audio/") for mt in media_types):
@@ -650,76 +483,38 @@ class SimplexAdapter(BasePlatformAdapter):
elif any(mt.startswith("image/") for mt in media_types):
msg_type = MessageType.PHOTO
else:
- # Catch-all: non-image/non-audio files (tagged
- # application/octet-stream above) are documents so run.py's
+ # Non-image/non-audio files are documents so run.py's
# document-context injection surfaces the file to the agent.
msg_type = MessageType.DOCUMENT
- # Timestamp
ts_str = meta.get("itemTs") or meta.get("createdAt", "")
try:
- if ts_str:
- timestamp = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
- else:
- timestamp = datetime.now(tz=timezone.utc)
+ timestamp = (datetime.fromisoformat(ts_str.replace("Z", "+00:00")) if ts_str
+ else datetime.now(tz=timezone.utc))
except (ValueError, AttributeError):
timestamp = datetime.now(tz=timezone.utc)
msg_event = MessageEvent(
- source=source,
- text=text or "",
- message_type=msg_type,
- media_urls=media_urls,
- media_types=media_types,
- timestamp=timestamp,
- raw_message=chat_item,
- )
-
- logger.debug(
- "SimpleX: message from %s in %s: %s",
- _redact_id(sender_id),
- chat_id[:20],
- (text or "")[:50],
+ source=source, text=text or "", message_type=msg_type, media_urls=media_urls,
+ media_types=media_types, timestamp=timestamp, raw_message=chat_item,
)
+ logger.debug("SimpleX: message from %s in %s: %s",
+ _redact_id(sender_id), chat_id[:20], (text or "")[:50])
- # Batch consecutive text messages so the agent sees one combined
- # message instead of dropping earlier ones when the user pastes
- # several lines in quick succession.
+ # Batch rapid-fire text so the agent sees one combined message.
if msg_type == MessageType.TEXT and text:
self._enqueue_text_event(msg_event)
else:
await self.handle_message(msg_event)
# ------------------------------------------------------------------
- # Text message batching
+ # Text message batching (enqueue lives on BasePlatformAdapter)
# ------------------------------------------------------------------
def _text_batch_key(self, event: MessageEvent) -> str:
"""Session-scoped key for text message batching."""
return f"{event.source.platform.value}:{event.source.chat_id}"
- def _enqueue_text_event(self, event: MessageEvent) -> None:
- """Buffer a text event and reset the flush timer."""
- key = self._text_batch_key(event)
- existing = self._pending_text_batches.get(key)
- if existing is None:
- self._pending_text_batches[key] = event
- else:
- if event.text:
- existing.text = (
- f"{existing.text}\n{event.text}" if existing.text else event.text
- )
- if event.media_urls:
- existing.media_urls.extend(event.media_urls)
- existing.media_types.extend(event.media_types)
-
- prior_task = self._pending_text_batch_tasks.get(key)
- if prior_task and not prior_task.done():
- prior_task.cancel()
- self._pending_text_batch_tasks[key] = asyncio.create_task(
- self._flush_text_batch(key)
- )
-
async def _flush_text_batch(self, key: str) -> None:
"""Wait for the quiet period then dispatch the aggregated text."""
current_task = asyncio.current_task()
@@ -728,11 +523,7 @@ class SimplexAdapter(BasePlatformAdapter):
event = self._pending_text_batches.pop(key, None)
if not event:
return
- logger.info(
- "[SimpleX] Flushing text batch %s (%d chars)",
- key,
- len(event.text or ""),
- )
+ logger.info("[SimpleX] Flushing text batch %s (%d chars)", key, len(event.text or ""))
await self.handle_message(event)
finally:
if self._pending_text_batch_tasks.get(key) is current_task:
@@ -743,13 +534,10 @@ class SimplexAdapter(BasePlatformAdapter):
# ------------------------------------------------------------------
def _make_corr_id(self) -> str:
- """Mint a new correlation ID and remember it for echo-filtering.
+ """Mint a correlation ID and remember it for echo-filtering.
- We add every minted id to ``_pending_corr_ids`` so the inbound
- event loop can drop the daemon's echo of our own commands without
- ever invoking ``_handle_chat_item``. The set is bounded — when
- it grows past ``_max_pending_corr``, the oldest entries are
- evicted in a single sweep.
+ ``_pending_corr_ids`` is bounded: past ``_max_pending_corr`` the
+ overflow is evicted in a single sweep.
"""
self._corr_counter += 1
corr_id = f"{_CORR_PREFIX}{self._corr_counter}-{int(time.time() * 1000)}"
@@ -764,12 +552,7 @@ class SimplexAdapter(BasePlatformAdapter):
return corr_id
async def _send_ws(self, payload: dict) -> None:
- """Fire-and-forget JSON payload write.
-
- Drops cleanly when the WebSocket is missing or already closed; the
- caller never has to handle reconnection — the ``_ws_listener``
- loop does that out of band.
- """
+ """Fire-and-forget JSON write; drops cleanly when the WS is missing/closed."""
ws = self._ws
if not ws:
logger.debug("SimpleX: WS send dropped (not connected)")
@@ -779,9 +562,7 @@ class SimplexAdapter(BasePlatformAdapter):
except Exception as e:
logger.warning("SimpleX: WS send error: %s", e)
- async def _send_command(
- self, command: str, timeout: float = 30.0
- ) -> Optional[dict]:
+ async def _send_command(self, command: str, timeout: float = 30.0) -> Optional[dict]:
"""Send a command and await the correlated response."""
ws = self._ws
if not ws:
@@ -790,15 +571,11 @@ class SimplexAdapter(BasePlatformAdapter):
corr_id = self._make_corr_id()
payload = json.dumps({"corrId": corr_id, "cmd": command})
-
- loop = asyncio.get_event_loop()
- fut: asyncio.Future = loop.create_future()
+ fut: asyncio.Future = asyncio.get_event_loop().create_future()
self._pending_responses[corr_id] = fut
-
try:
await ws.send(payload)
- result = await asyncio.wait_for(fut, timeout=timeout)
- return result
+ return await asyncio.wait_for(fut, timeout=timeout)
except asyncio.TimeoutError:
logger.warning("SimpleX: command timed out: %s", command[:50])
self._pending_responses.pop(corr_id, None)
@@ -809,14 +586,15 @@ class SimplexAdapter(BasePlatformAdapter):
return None
async def _send_fire_and_forget(self, command: str) -> None:
- """Send a command without waiting for a correlated response.
+ """Send a command the daemon never replies to with a corrId (e.g. ``/freceive``)."""
+ await self._send_ws({"corrId": self._make_corr_id(), "cmd": command})
- Use this for commands the daemon never sends a corrId reply for,
- such as ``/freceive``. Awaiting a corr-id reply on those would
- stall the event loop for the full command timeout.
- """
- corr_id = self._make_corr_id()
- await self._send_ws({"corrId": corr_id, "cmd": command})
+ async def _send_items(self, chat_id: str, items: list, error: str) -> SendResult:
+ """Send a structured ``/_send`` payload and await the reply."""
+ result = await self._send_command(_send_cmd(chat_id, items))
+ if result is not None:
+ return SendResult(success=True)
+ return SendResult(success=False, error=error)
# ------------------------------------------------------------------
# Outbound — text
@@ -831,21 +609,11 @@ class SimplexAdapter(BasePlatformAdapter):
) -> SendResult:
"""Send a text message.
- If *content* contains ``MEDIA:<path>`` tags (embedded by TTS / audio
- tools to signal file attachments), they are stripped from the text
- body and sent as native voice notes or documents.
-
- Groups use the structured ``/_send #<id> json [...]`` form
- because the bracket chat-command syntax (``#[<id>] text``) is
- parsed by the daemon as a display-name lookup, which silently
- drops when the group's display name isn't the literal ID. DMs
- use the simple ``@<id> text`` form which has always worked in
- production.
-
- The call is fire-and-forget at the WebSocket level: the daemon
- doesn't always return a corrId reply for chat commands, and
- waiting for one would serialise all outbound traffic behind a
- 30-second timeout.
+ ``MEDIA:<path>`` tags (embedded by TTS / audio tools) are stripped from
+ the body and sent as native voice notes or documents. The text send is
+ fire-and-forget at the WebSocket level: the daemon doesn't always return
+ a corrId reply for chat commands, and waiting would serialise all
+ outbound traffic behind a 30-second timeout.
"""
_voice_exts = {".ogg", ".mp3", ".wav", ".m4a", ".opus"}
media_paths = re.findall(r"MEDIA:(\S+)", content)
@@ -854,23 +622,11 @@ class SimplexAdapter(BasePlatformAdapter):
if content:
corr_id = self._make_corr_id()
- # Structured form: addresses by ID, and json.dumps escapes
- # newlines + special chars correctly. The bare @id text
- # syntax is unreliable for DMs — the daemon silently drops
- # messages when it cannot resolve the display name.
- composed = json.dumps(
- [{"msgContent": {"type": "text", "text": content}}]
- )
- if chat_id.startswith("group:"):
- cmd_str = f"/_send #{chat_id[6:]} json {composed}"
- else:
- cmd_str = f"/_send @{chat_id} json {composed}"
-
+ cmd_str = _send_cmd(chat_id, [{"msgContent": {"type": "text", "text": content}}])
await self._send_ws({"corrId": corr_id, "cmd": cmd_str})
for path in media_paths:
- is_voice = os.path.splitext(path)[1].lower() in _voice_exts
- if is_voice:
+ if os.path.splitext(path)[1].lower() in _voice_exts:
media_result = await self.send_voice(chat_id, path)
else:
media_result = await self.send_document(chat_id, path)
@@ -886,15 +642,10 @@ class SimplexAdapter(BasePlatformAdapter):
async def list_channels(self) -> Optional[List[Dict[str, Any]]]:
"""Enumerate contacts and allowed groups for the channel directory.
- Called by ``gateway.channel_directory.build_channel_directory()``
- every refresh cycle. Uses the daemon's ``/contacts`` and ``/groups``
- commands over the live WebSocket. Returns ``None`` (not ``[]``) when
- the WebSocket is down so the directory falls back to session-history
- discovery instead of wiping previously known targets.
-
- Entry ``id`` values match the send-target formats the adapter
- accepts: bare contact display name for DMs (``simplex:<name>``) and
- ``group:<groupId>`` for groups (``simplex:group:<id>``).
+ Returns ``None`` (not ``[]``) when the WebSocket is down or the daemon
+ is unresponsive so the directory falls back to session-history
+ discovery instead of wiping known targets. Entry ``id`` values match
+ the adapter's send targets: display name for DMs, ``group:<id>`` for groups.
"""
if not self._ws:
return None
@@ -903,31 +654,23 @@ class SimplexAdapter(BasePlatformAdapter):
resp = await self._send_command("/contacts", timeout=10.0)
if resp is None:
- # Daemon unresponsive — keep whatever the directory already has.
return None
for contact in resp.get("contacts") or []:
if not isinstance(contact, dict):
continue
contact_id = contact.get("contactId")
- name = (
- contact.get("localDisplayName", "")
- or (contact.get("profile", {}) or {}).get("displayName", "")
- )
+ name = (contact.get("localDisplayName", "")
+ or (contact.get("profile", {}) or {}).get("displayName", ""))
if contact_id is None and not name:
continue
- channels.append({
- # Display name is what the DM send path (``@<name>``)
- # actually addresses; fall back to the numeric contactId.
- "id": str(name or contact_id),
- "name": str(name or contact_id),
- "type": "dm",
- })
+ # Display name is what the DM send path addresses; fall back to contactId.
+ channels.append(
+ {"id": str(name or contact_id), "name": str(name or contact_id), "type": "dm"})
resp = await self._send_command("/groups", timeout=10.0)
if resp is not None:
for group in resp.get("groups") or []:
- # The daemon returns each group as either a groupInfo dict
- # or a [groupInfo, groupSummary] pair depending on version.
+ # Each group is either a groupInfo dict or a [groupInfo, groupSummary] pair.
if isinstance(group, list) and group:
group = group[0]
if not isinstance(group, dict):
@@ -940,11 +683,7 @@ class SimplexAdapter(BasePlatformAdapter):
or (group.get("groupProfile", {}) or {}).get("displayName", "")
or str(group_id)
)
- channels.append({
- "id": f"group:{group_id}",
- "name": str(name),
- "type": "group",
- })
+ channels.append({"id": f"group:{group_id}", "name": str(name), "type": "group"})
return channels
@@ -954,13 +693,11 @@ class SimplexAdapter(BasePlatformAdapter):
@staticmethod
def _prepare_image(file_path: str) -> tuple[str, str]:
- """Ensure *file_path* is a PNG and return ``(png_path, thumb_data_uri)``.
+ """Ensure *file_path* is PNG/JPEG and return ``(png_path, thumb_data_uri)``.
- SimpleX clients can't display WebP and a few other formats inline.
- This converts to PNG when needed and generates a small JPEG thumbnail
- for the ``image`` field in the ``/_send`` payload so the chat shows
- an inline preview. Uses Pillow when available, falls back to
- ImageMagick ``convert``.
+ SimpleX clients can't display WebP etc. inline, so convert to PNG when
+ needed and build a 128px JPEG thumbnail for the ``image`` field (inline
+ preview). Uses Pillow when available, else ImageMagick ``convert``.
"""
import subprocess
import tempfile
@@ -968,54 +705,35 @@ class SimplexAdapter(BasePlatformAdapter):
p = Path(file_path)
png_path = file_path
thumb_uri = ""
+ needs_png = p.suffix.lower() not in (".png", ".jpg", ".jpeg")
try:
from PIL import Image
+ import io
img = Image.open(file_path)
- if p.suffix.lower() not in (".png", ".jpg", ".jpeg"):
+ if needs_png:
png_path = str(p.with_suffix(".png"))
img.save(png_path, "PNG")
thumb = img.copy()
thumb.thumbnail((128, 128))
- import io
-
buf = io.BytesIO()
thumb.save(buf, "JPEG", quality=70)
- thumb_uri = (
- "data:image/jpg;base64,"
- + base64.b64encode(buf.getvalue()).decode()
- )
+ thumb_uri = "data:image/jpg;base64," + base64.b64encode(buf.getvalue()).decode()
except ImportError:
try:
- if p.suffix.lower() not in (".png", ".jpg", ".jpeg"):
+ if needs_png:
png_path = str(p.with_suffix(".png"))
- subprocess.run(
- ["convert", file_path, png_path],
- check=True,
- capture_output=True,
- timeout=30,
- )
+ subprocess.run(["convert", file_path, png_path],
+ check=True, capture_output=True, timeout=30)
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
tmp_path = tmp.name
subprocess.run(
- [
- "convert",
- file_path,
- "-resize",
- "128x128",
- "-quality",
- "70",
- tmp_path,
- ],
- check=True,
- capture_output=True,
- timeout=30,
+ ["convert", file_path, "-resize", "128x128", "-quality", "70", tmp_path],
+ check=True, capture_output=True, timeout=30,
)
with open(tmp_path, "rb") as f:
- thumb_uri = (
- "data:image/jpg;base64," + base64.b64encode(f.read()).decode()
- )
+ thumb_uri = "data:image/jpg;base64," + base64.b64encode(f.read()).decode()
os.remove(tmp_path)
except (FileNotFoundError, subprocess.SubprocessError) as exc:
logger.warning("SimpleX: image conversion unavailable: %s", exc)
@@ -1023,11 +741,7 @@ class SimplexAdapter(BasePlatformAdapter):
return png_path, thumb_uri
async def send_image(
- self,
- chat_id: str,
- image_url: str,
- caption: Optional[str] = None,
- **kwargs,
+ self, chat_id: str, image_url: str, caption: Optional[str] = None, **kwargs
) -> SendResult:
"""Send an image. Supports ``file://`` URLs and ``http(s)://`` URLs."""
from urllib.parse import unquote
@@ -1047,131 +761,47 @@ class SimplexAdapter(BasePlatformAdapter):
return SendResult(success=False, error="Image file not found")
png_path, thumb_uri = self._prepare_image(file_path)
-
- # /_send addresses by numeric ID; /f only accepts display names which
- # breaks for group IDs.
- composed = json.dumps(
- [
- {
- "filePath": png_path,
- "msgContent": {
- "type": "image",
- "image": thumb_uri,
- "text": caption or "",
- },
- }
- ]
- )
-
- if chat_id.startswith("group:"):
- group_id = chat_id[6:]
- command = f"/_send #{group_id} json {composed}"
- else:
- command = f"/_send @{chat_id} json {composed}"
-
- result = await self._send_command(command)
- if result is not None:
- return SendResult(success=True)
- return SendResult(success=False, error="Failed to send image")
+ # /_send addresses by numeric ID; /f only accepts display names.
+ item = {"filePath": png_path,
+ "msgContent": {"type": "image", "image": thumb_uri, "text": caption or ""}}
+ return await self._send_items(chat_id, [item], "Failed to send image")
async def send_image_file(
- self,
- chat_id: str,
- image_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- **kwargs,
+ self, chat_id: str, image_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, **kwargs,
) -> SendResult:
"""Send a local image file via SimpleX."""
- return await self.send_image(
- chat_id, f"file://{image_path}", caption=caption, **kwargs
- )
+ return await self.send_image(chat_id, f"file://{image_path}", caption=caption, **kwargs)
async def send_video(
- self,
- chat_id: str,
- video_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- **kwargs,
+ self, chat_id: str, video_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, **kwargs,
) -> SendResult:
"""Send a video file via SimpleX (as a file attachment)."""
return await self.send_document(chat_id, video_path, caption=caption)
async def send_document(
- self,
- chat_id: str,
- file_path: str,
- caption: Optional[str] = None,
- filename: Optional[str] = None,
- **kwargs,
+ self, chat_id: str, file_path: str, caption: Optional[str] = None,
+ filename: Optional[str] = None, **kwargs,
) -> SendResult:
"""Send a document/file attachment."""
if not Path(file_path).exists():
return SendResult(success=False, error="File not found")
-
- composed = json.dumps(
- [
- {
- "filePath": file_path,
- "msgContent": {"type": "file", "text": caption or ""},
- }
- ]
- )
-
- if chat_id.startswith("group:"):
- group_id = chat_id[6:]
- command = f"/_send #{group_id} json {composed}"
- else:
- command = f"/_send @{chat_id} json {composed}"
-
- result = await self._send_command(command)
- if result is not None:
- return SendResult(success=True)
- return SendResult(success=False, error="Failed to send document")
+ item = {"filePath": file_path, "msgContent": {"type": "file", "text": caption or ""}}
+ return await self._send_items(chat_id, [item], "Failed to send document")
async def send_voice(
- self,
- chat_id: str,
- audio_path: str,
- caption: Optional[str] = None,
- reply_to: Optional[str] = None,
- duration: int = 0,
- **kwargs,
+ self, chat_id: str, audio_path: str, caption: Optional[str] = None,
+ reply_to: Optional[str] = None, duration: int = 0, **kwargs,
) -> SendResult:
- """Send an audio file as a SimpleX voice note (plays inline).
-
- SimpleX distinguishes a generic file attachment (``type: "file"``)
- from an inline voice note (``type: "voice"``). ``/f`` would deliver
- a downloadable file; the structured ``/_send`` form with
- ``msgContent.type == "voice"`` produces the voice-note player.
- """
+ """Send an audio file as an inline SimpleX voice note (``msgContent.type == "voice"``)."""
if not Path(audio_path).exists():
return SendResult(success=False, error="Voice file not found")
-
- composed = json.dumps(
- [
- {
- "msgContent": {
- "type": "voice",
- "text": caption or "",
- "duration": duration,
- },
- "fileSource": {"filePath": audio_path},
- }
- ]
- )
-
- if chat_id.startswith("group:"):
- group_id = chat_id[6:]
- command = f"/_send #{group_id} json {composed}"
- else:
- command = f"/_send @{chat_id} json {composed}"
-
- result = await self._send_command(command)
- if result is not None:
- return SendResult(success=True)
- return SendResult(success=False, error="Failed to send voice message")
+ item = {
+ "msgContent": {"type": "voice", "text": caption or "", "duration": duration},
+ "fileSource": {"filePath": audio_path},
+ }
+ return await self._send_items(chat_id, [item], "Failed to send voice message")
async def send_typing(self, chat_id: str, metadata=None) -> None:
"""SimpleX has no typing-indicator API — no-op."""
@@ -1188,12 +818,7 @@ class SimplexAdapter(BasePlatformAdapter):
# ---------------------------------------------------------------------------
def check_requirements() -> bool:
- """Plugin gate: require SIMPLEX_WS_URL AND the websockets package.
-
- Returning False keeps the platform out of ``get_connected_platforms()``
- so the gateway never instantiates the adapter when the dependency is
- missing or no daemon URL is configured.
- """
+ """Plugin gate: require SIMPLEX_WS_URL AND the websockets package."""
if not _get_scoped_secret("SIMPLEX_WS_URL"):
return False
try:
@@ -1206,28 +831,20 @@ def check_requirements() -> bool:
def validate_config(config) -> bool:
"""Validate that the platform config has enough info to connect."""
extra = getattr(config, "extra", {}) or {}
- ws_url = _get_scoped_secret("SIMPLEX_WS_URL") or extra.get("ws_url", "")
- return bool(ws_url)
+ return bool(_get_scoped_secret("SIMPLEX_WS_URL") or extra.get("ws_url", ""))
def is_connected(config) -> bool:
"""Check whether SimpleX is configured (env or config.yaml)."""
- extra = getattr(config, "extra", {}) or {}
- ws_url = _get_scoped_secret("SIMPLEX_WS_URL") or extra.get("ws_url", "")
- return bool(ws_url)
+ return validate_config(config)
def _env_enablement() -> Optional[dict]:
"""Seed ``PlatformConfig.extra`` from env vars during gateway config load.
- Called by the platform registry's env-enablement hook BEFORE adapter
- construction, so ``gateway status`` and ``get_connected_platforms()``
- reflect env-only configuration without instantiating the WebSocket
- client. Returns ``None`` when SimpleX isn't minimally configured.
-
- The special ``home_channel`` key is handled by the core hook — it
- becomes a proper ``HomeChannel`` dataclass on the ``PlatformConfig``
- rather than being merged into ``extra``.
+ Runs BEFORE adapter construction so ``gateway status`` reflects env-only
+ configuration. Returns ``None`` when SimpleX isn't minimally configured.
+ ``home_channel`` is turned into a ``HomeChannel`` by the core hook.
"""
ws_url = _get_scoped_secret("SIMPLEX_WS_URL", "").strip()
if not ws_url:
@@ -1262,16 +879,11 @@ async def _standalone_send(
) -> Dict[str, Any]:
"""Open an ephemeral WebSocket to the daemon, send, and close.
- Used by ``tools/send_message_tool._send_via_adapter`` when the gateway
- runner is not in this process (e.g. ``hermes cron`` running as a
- separate process from ``hermes gateway``). Without this hook,
- ``deliver=simplex`` cron jobs fail with "No live adapter for platform".
-
- ``thread_id`` and ``force_document`` are accepted for signature parity
- with other plugins but are not meaningful here. ``media_files`` is
- accepted but only the text body is delivered — SimpleX file transfers
- require the daemon's filesystem-backed flow, which an ephemeral
- connection cannot drive safely.
+ Used by ``tools/send_message_tool`` when the gateway runner is not in this
+ process (e.g. ``hermes cron``). ``thread_id``/``force_document`` are
+ signature parity only; ``media_files`` is accepted but only the text body
+ is delivered — SimpleX file transfers need the daemon's filesystem-backed
+ flow, which an ephemeral connection cannot drive safely.
"""
try:
import websockets as _wsclient
@@ -1279,46 +891,26 @@ async def _standalone_send(
return {"error": "websockets not installed. Run: pip install websockets"}
extra = getattr(pconfig, "extra", {}) or {}
- ws_url = _get_scoped_secret("SIMPLEX_WS_URL") or extra.get(
- "ws_url", "ws://127.0.0.1:5225"
- )
+ ws_url = _get_scoped_secret("SIMPLEX_WS_URL") or extra.get("ws_url", "ws://127.0.0.1:5225")
if not ws_url:
return {"error": "SimpleX standalone send: SIMPLEX_WS_URL is required"}
try:
- composed = json.dumps(
- [{"msgContent": {"type": "text", "text": message}}]
- )
- if chat_id.startswith("group:"):
- group_id = chat_id[6:]
- cmd_str = f"/_send #{group_id} json {composed}"
- else:
- cmd_str = f"/_send @{chat_id} json {composed}"
-
payload = {
"corrId": f"{_CORR_PREFIX}snd-{int(time.time() * 1000)}",
- "cmd": cmd_str,
+ "cmd": _send_cmd(chat_id, [{"msgContent": {"type": "text", "text": message}}]),
}
-
- async with _wsclient.connect(
- ws_url, open_timeout=10, close_timeout=5
- ) as ws:
+ async with _wsclient.connect(ws_url, open_timeout=10, close_timeout=5) as ws:
await ws.send(json.dumps(payload))
# Give the daemon a moment to process the command before closing.
await asyncio.sleep(0.5)
-
return {"success": True, "platform": "simplex", "chat_id": chat_id}
except Exception as e:
return {"error": f"SimpleX send failed: {e}"}
def interactive_setup() -> None:
- """Minimal stdin wizard for ``hermes setup gateway`` → SimpleX.
-
- Prompts for the WebSocket URL and the optional allowlist / groups /
- auto-accept / home channel. Writes to ``~/.hermes/.env`` via
- ``hermes_cli.config``.
- """
+ """Minimal stdin wizard for ``hermes setup gateway`` → SimpleX; writes ``~/.hermes/.env``."""
print()
print("SimpleX Chat setup")
print("------------------")
@@ -1330,21 +922,14 @@ def interactive_setup() -> None:
try:
from hermes_cli.config import get_env_value, save_env_value
except ImportError:
- print(
- "hermes_cli.config not available; set SIMPLEX_* vars manually in "
- "~/.hermes/.env"
- )
+ print("hermes_cli.config not available; set SIMPLEX_* vars manually in ~/.hermes/.env")
return
- def _prompt(var: str, prompt: str, *, secret: bool = False) -> None:
+ def _prompt(var: str, prompt: str) -> None:
existing = get_env_value(var) if callable(get_env_value) else None
suffix = " [keep current]" if existing else ""
try:
- if secret:
- from hermes_cli.secret_prompt import masked_secret_prompt
- value = masked_secret_prompt(f"{prompt}{suffix}: ")
- else:
- value = input(f"{prompt}{suffix}: ").strip()
+ value = input(f"{prompt}{suffix}: ").strip()
except (EOFError, KeyboardInterrupt):
print()
return
@@ -1352,20 +937,14 @@ def interactive_setup() -> None:
save_env_value(var, value)
_prompt("SIMPLEX_WS_URL", "Daemon WebSocket URL (default ws://127.0.0.1:5225)")
- _prompt("SIMPLEX_ALLOWED_USERS", "Allowed contactIds or display names (comma-separated; blank=skip)")
- _prompt(
- "SIMPLEX_GROUP_ALLOWED",
- "Allowed group IDs (comma-separated, or '*' for any; blank=disable groups)",
- )
- _prompt(
- "SIMPLEX_AUTO_ACCEPT",
- "Auto-accept incoming contact requests? (true/false, default true)",
- )
+ _prompt("SIMPLEX_ALLOWED_USERS",
+ "Allowed contactIds or display names (comma-separated; blank=skip)")
+ _prompt("SIMPLEX_GROUP_ALLOWED",
+ "Allowed group IDs (comma-separated, or '*' for any; blank=disable groups)")
+ _prompt("SIMPLEX_AUTO_ACCEPT",
+ "Auto-accept incoming contact requests? (true/false, default true)")
_prompt("SIMPLEX_HOME_CHANNEL", "Home channel contact/group ID (or empty)")
- print(
- "Done. Make sure the simplex-chat daemon is running before starting "
- "the gateway."
- )
+ print("Done. Make sure the simplex-chat daemon is running before starting the gateway.")
def register(ctx) -> None:
@@ -1378,10 +957,7 @@ def register(ctx) -> None:
validate_config=validate_config,
is_connected=is_connected,
required_env=["SIMPLEX_WS_URL"],
- install_hint=(
- "pip install websockets # SimpleX adapter requires the "
- "websockets package"
- ),
+ install_hint=("pip install websockets # SimpleX adapter requires the websockets package"),
setup_fn=interactive_setup,
env_enablement_fn=_env_enablement,
cron_deliver_env_var="SIMPLEX_HOME_CHANNEL",
@@ -1390,8 +966,7 @@ def register(ctx) -> None:
allow_all_env="SIMPLEX_ALLOW_ALL_USERS",
max_message_length=MAX_MESSAGE_LENGTH,
emoji="🔒",
- # SimpleX uses opaque contact IDs only — no phone numbers or email
- # addresses to redact.
+ # SimpleX uses opaque contact IDs only — nothing to redact.
pii_safe=True,
allow_update_command=True,
platform_hint=(