From 036c76735458683c2a5fef80018ad22445fdd0b4 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sun, 7 Jun 2026 05:12:34 -0700 Subject: [PATCH] refactor(gateway): migrate matrix adapter to bundled plugin WIP toward #41112. Matrix adapter relocated to plugins/platforms/matrix/ with register() + standalone_sender_fn (REST text path) / apply_yaml_config_fn / setup_fn (full E2EE-aware wizard) hooks. Core touchpoints stripped: run.py elif, config.py matrix_cfg YAML bridge, gateway.py static dict + setup-map entry, setup.py _setup_matrix, send_message_tool _send_matrix + dispatch. _send_matrix_via_adapter (native media path) kept in send_message_tool with its import repointed to plugins.platforms.matrix.adapter. Matrix uses the generic token connected-check (no is_connected override needed). feishu + telegram still to come. --- gateway/config.py | 23 +- gateway/run.py | 7 - hermes_cli/gateway.py | 56 +---- hermes_cli/setup.py | 116 +-------- plugins/platforms/matrix/__init__.py | 3 + .../platforms/matrix/adapter.py | 229 ++++++++++++++++++ plugins/platforms/matrix/plugin.yaml | 41 ++++ tools/send_message_tool.py | 49 +--- 8 files changed, 289 insertions(+), 235 deletions(-) create mode 100644 plugins/platforms/matrix/__init__.py rename gateway/platforms/matrix.py => plugins/platforms/matrix/adapter.py (91%) create mode 100644 plugins/platforms/matrix/plugin.yaml diff --git a/gateway/config.py b/gateway/config.py index e45ecc60b005..d4b3c36b1fb6 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -1109,26 +1109,9 @@ def load_gateway_config() -> GatewayConfig: # Mattermost config bridge moved into plugins/platforms/mattermost/ # adapter.py::_apply_yaml_config β€” see #25443 (apply_yaml_config_fn). - # Matrix settings β†’ env vars (env vars take precedence) - matrix_cfg = yaml_cfg.get("matrix", {}) - if isinstance(matrix_cfg, dict): - if "require_mention" in matrix_cfg and not os.getenv("MATRIX_REQUIRE_MENTION"): - os.environ["MATRIX_REQUIRE_MENTION"] = str(matrix_cfg["require_mention"]).lower() - 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) - # allowed_rooms: if set, bot ONLY responds in these rooms (whitelist) - 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) - 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() + # Matrix settings β†’ env vars: migrated to the matrix plugin's + # apply_yaml_config_fn hook (plugins/platforms/matrix/adapter.py). + # #41112 / #3823. # Feishu settings β†’ env vars (env vars take precedence) feishu_cfg = yaml_cfg.get("feishu", {}) diff --git a/gateway/run.py b/gateway/run.py index 019f7dcb5ba4..eb453aebb690 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -6952,13 +6952,6 @@ class GatewayRunner: return None return WeixinAdapter(config) - elif platform == Platform.MATRIX: - from gateway.platforms.matrix import MatrixAdapter, check_matrix_requirements - if not check_matrix_requirements(): - logger.warning("Matrix: mautrix not installed or credentials not set. Run: pip install 'mautrix[encryption]'") - return None - return MatrixAdapter(config) - elif platform == Platform.API_SERVER: from gateway.platforms.api_server import APIServerAdapter, check_api_server_requirements if not check_api_server_requirements(): diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py index 8e07bdc80722..3cc1835e3a08 100644 --- a/hermes_cli/gateway.py +++ b/hermes_cli/gateway.py @@ -3876,55 +3876,9 @@ _PLATFORMS = [ }, ], }, - { - "key": "matrix", - "label": "Matrix", - "emoji": "πŸ”", - "token_var": "MATRIX_ACCESS_TOKEN", - "setup_instructions": [ - "1. Works with any Matrix homeserver (self-hosted Synapse/Conduit/Dendrite or matrix.org)", - "2. Create a bot user on your homeserver, or use your own account", - "3. Get an access token: Element β†’ Settings β†’ Help & About β†’ Access Token", - " Or via API: curl -X POST https://your-server/_matrix/client/v3/login \\", - ' -d \'{"type":"m.login.password","user":"@bot:server","password":"..."}\'', - "4. Alternatively, provide user ID + password and Hermes will log in directly", - "5. For E2EE: set MATRIX_ENCRYPTION=true (requires pip install 'mautrix[encryption]')", - "6. To find your user ID: it's @username:your-server (shown in Element profile)", - ], - "vars": [ - { - "name": "MATRIX_HOMESERVER", - "prompt": "Homeserver URL (e.g. https://matrix.example.org)", - "password": False, - "help": "Your Matrix homeserver URL. Works with any self-hosted instance.", - }, - { - "name": "MATRIX_ACCESS_TOKEN", - "prompt": "Access token (leave empty to use password login instead)", - "password": True, - "help": "Paste your access token, or leave empty and provide user ID + password below.", - }, - { - "name": "MATRIX_USER_ID", - "prompt": "User ID (@bot:server β€” required for password login)", - "password": False, - "help": "Full Matrix user ID, e.g. @hermes:matrix.example.org", - }, - { - "name": "MATRIX_ALLOWED_USERS", - "prompt": "Allowed user IDs (comma-separated, e.g. @you:server)", - "password": False, - "is_allowlist": True, - "help": "Matrix user IDs who can interact with the bot.", - }, - { - "name": "MATRIX_HOME_ROOM", - "prompt": "Home room ID (for cron/notification delivery, or empty to set later with /set-home)", - "password": False, - "help": "Room ID (e.g. !abc123:server) for delivering cron results and notifications.", - }, - ], - }, + # Matrix moved to plugins/platforms/matrix/ β€” setup metadata discovered + # dynamically via the platform registry entry registered by + # plugins/platforms/matrix/adapter.py::register(). #41112. { "key": "mattermost", "label": "Mattermost", @@ -5517,7 +5471,9 @@ def _builtin_setup_fn(key: str): # plugins/platforms/discord/adapter.py::register() and dispatched # via the plugin path in _configure_platform(). "slack": _s._setup_slack, - "matrix": _s._setup_matrix, + # matrix moved into the plugin: setup_fn registered by + # plugins/platforms/matrix/adapter.py::register() and dispatched via + # the plugin path in _configure_platform(). #41112. # mattermost moved into the plugin: setup_fn is registered by # plugins/platforms/mattermost/adapter.py::register() and dispatched # via the plugin path in _configure_platform(). diff --git a/hermes_cli/setup.py b/hermes_cli/setup.py index 266eb9eaa392..da8ec65d4b4f 100644 --- a/hermes_cli/setup.py +++ b/hermes_cli/setup.py @@ -1906,120 +1906,8 @@ def _write_slack_manifest_and_instruct(): ) -def _setup_matrix(): - """Configure Matrix credentials.""" - 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") - print() - homeserver = prompt("Homeserver URL (e.g. https://matrix.example.org)") - if homeserver: - save_env_value("MATRIX_HOMESERVER", homeserver.rstrip("/")) - - print() - 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: - save_env_value("MATRIX_ACCESS_TOKEN", token) - user_id = prompt("User ID (@bot:server β€” optional, will be auto-detected)") - if user_id: - save_env_value("MATRIX_USER_ID", user_id) - print_success("Matrix access token saved") - else: - user_id = prompt("User ID (@bot:server)") - if user_id: - save_env_value("MATRIX_USER_ID", user_id) - password = prompt("Password", password=True) - if password: - save_env_value("MATRIX_PASSWORD", password) - print_success("Matrix credentials saved") - - if token or get_env_value("MATRIX_PASSWORD"): - print() - 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" - # Use the central lazy-deps feature group so we install ALL of - # platform.matrix's dependencies (mautrix, Markdown, aiosqlite, - # asyncpg, aiohttp-socks) β€” not just mautrix itself. The previous - # hand-rolled ``pip install mautrix[encryption]`` left asyncpg / - # aiosqlite uninstalled and broke E2EE connect with - # ``No module named 'asyncpg'`` on every fresh install (#31116). - try: - from tools.lazy_deps import ensure as _lazy_ensure, feature_missing - _missing_before = feature_missing("platform.matrix") - if _missing_before: - print_info( - f"Installing {matrix_pkg} (+ {len(_missing_before)} runtime deps)..." - ) - try: - _lazy_ensure("platform.matrix", prompt=False) - print_success(f"{matrix_pkg} installed") - except Exception as exc: - print_warning( - f"Install failed β€” run manually: pip install " - f"'mautrix[encryption]' asyncpg aiosqlite Markdown " - f"aiohttp-socks" - ) - print_info(f" Error: {exc}") - except ImportError: - # tools.lazy_deps unavailable (extreme edge case β€” partial - # install). Fall back to the legacy single-package install - # path so the wizard still does *something*. - try: - __import__("mautrix") - except ImportError: - print_info(f"Installing {matrix_pkg}...") - import subprocess - uv_bin = shutil.which("uv") - if uv_bin: - result = subprocess.run( - [uv_bin, "pip", "install", "--python", sys.executable, matrix_pkg], - capture_output=True, text=True, - ) - else: - result = subprocess.run( - [sys.executable, "-m", "pip", "install", matrix_pkg], - capture_output=True, text=True, - ) - if result.returncode == 0: - print_success(f"{matrix_pkg} installed") - else: - print_warning( - f"Install failed β€” run manually: pip install " - f"'{matrix_pkg}' asyncpg aiosqlite Markdown aiohttp-socks" - ) - if result.stderr: - print_info(f" Error: {result.stderr.strip().splitlines()[-1]}") - - print() - print_info("πŸ”’ Security: Restrict who can use your bot") - print_info(" Matrix user IDs look like @username:server") - print() - allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for open access)") - if allowed_users: - save_env_value("MATRIX_ALLOWED_USERS", allowed_users.replace(" ", "")) - print_success("Matrix allowlist configured") - else: - print_info("⚠️ No allowlist set - anyone who can message the bot can use it!") - - print() - 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.") - home_room = prompt("Home room ID (leave empty to set later with /set-home)") - if home_room: - save_env_value("MATRIX_HOME_ROOM", home_room) +# _setup_matrix moved to plugins/platforms/matrix/adapter.py::interactive_setup +# (registered via setup_fn, dispatched through the plugin path). #41112. def _setup_bluebubbles(): diff --git a/plugins/platforms/matrix/__init__.py b/plugins/platforms/matrix/__init__.py new file mode 100644 index 000000000000..d4f1d7bf0e3f --- /dev/null +++ b/plugins/platforms/matrix/__init__.py @@ -0,0 +1,3 @@ +from .adapter import register + +__all__ = ["register"] diff --git a/gateway/platforms/matrix.py b/plugins/platforms/matrix/adapter.py similarity index 91% rename from gateway/platforms/matrix.py rename to plugins/platforms/matrix/adapter.py index a649bb91e594..3ccb3abb55be 100644 --- a/gateway/platforms/matrix.py +++ b/plugins/platforms/matrix/adapter.py @@ -2981,3 +2981,232 @@ class MatrixAdapter(BasePlatformAdapter): 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. +# ────────────────────────────────────────────────────────────────────────── + + +async def _standalone_send( + 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. + """ + extra = getattr(pconfig, "extra", {}) or {} + token = getattr(pconfig, "token", None) + try: + import aiohttp + except ImportError: + return {"error": "aiohttp not installed. Run: pip install aiohttp"} + try: + homeserver = (extra.get("homeserver") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/") + token = token or os.getenv("MATRIX_ACCESS_TOKEN", "") + if not homeserver or not token: + return {"error": "Matrix not configured (MATRIX_HOMESERVER, MATRIX_ACCESS_TOKEN required)"} + txn_id = f"hermes_{int(time.time() * 1000)}_{os.urandom(4).hex()}" + from urllib.parse import quote + 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 + html = _md.markdown(message, extensions=["fenced_code", "tables"]) + html = re.sub(r"(.*?)", r"\1", html) + payload["format"] = "org.matrix.custom.html" + payload["formatted_body"] = html + except ImportError: + pass + + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session: + async with session.put(url, headers=headers, json=payload) as resp: + if resp.status not in {200, 201}: + body = await resp.text() + return {"error": f"Matrix API error ({resp.status}): {body}"} + data = await resp.json() + return {"success": True, "platform": "matrix", "chat_id": chat_id, "message_id": data.get("event_id")} + except Exception as e: + return {"error": f"Matrix send failed: {e}"} + + +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 + from hermes_cli.config import get_env_value, save_env_value + 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: + save_env_value("MATRIX_ACCESS_TOKEN", token) + user_id = prompt("User ID (@bot:server β€” optional, will be auto-detected)") + if user_id: + save_env_value("MATRIX_USER_ID", user_id) + print_success("Matrix access token saved") + else: + user_id = prompt("User ID (@bot:server)") + if user_id: + save_env_value("MATRIX_USER_ID", user_id) + password = prompt("Password", password=True) + 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 + _missing_before = feature_missing("platform.matrix") + if _missing_before: + print_info(f"Installing {matrix_pkg} (+ {len(_missing_before)} runtime deps)...") + try: + _lazy_ensure("platform.matrix", prompt=False) + print_success(f"{matrix_pkg} installed") + except Exception as exc: + print_warning( + "Install failed β€” run manually: pip install " + "'mautrix[encryption]' asyncpg aiosqlite Markdown aiohttp-socks" + ) + print_info(f" Error: {exc}") + except ImportError: + try: + __import__("mautrix") + except ImportError: + print_info(f"Installing {matrix_pkg}...") + import subprocess + uv_bin = shutil.which("uv") + if uv_bin: + result = subprocess.run( + [uv_bin, "pip", "install", "--python", _sys.executable, matrix_pkg], + capture_output=True, text=True, + ) + else: + result = subprocess.run( + [_sys.executable, "-m", "pip", "install", matrix_pkg], + capture_output=True, text=True, + ) + if result.returncode == 0: + print_success(f"{matrix_pkg} installed") + else: + print_warning( + f"Install failed β€” run manually: 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)") + if allowed_users: + save_env_value("MATRIX_ALLOWED_USERS", allowed_users.replace(" ", "")) + 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.") + home_room = prompt("Home room ID (leave empty to set later with /set-home)") + if home_room: + save_env_value("MATRIX_HOME_ROOM", home_room) + + +def _apply_yaml_config(yaml_cfg: dict, matrix_cfg: dict) -> dict | None: + """Translate config.yaml matrix: keys into MATRIX_* env vars. + + 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. + """ + if "require_mention" in matrix_cfg and not os.getenv("MATRIX_REQUIRE_MENTION"): + os.environ["MATRIX_REQUIRE_MENTION"] = str(matrix_cfg["require_mention"]).lower() + 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) + 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() + return None + + +def _build_adapter(config): + """Factory wrapper that constructs MatrixAdapter from a PlatformConfig.""" + return MatrixAdapter(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=check_matrix_requirements, + 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=4000, + emoji="πŸ”", + allow_update_command=True, + ) diff --git a/plugins/platforms/matrix/plugin.yaml b/plugins/platforms/matrix/plugin.yaml new file mode 100644 index 000000000000..77d65d933960 --- /dev/null +++ b/plugins/platforms/matrix/plugin.yaml @@ -0,0 +1,41 @@ +name: matrix-platform +label: Matrix +kind: platform +version: 1.0.0 +description: > + Matrix gateway adapter for Hermes Agent. + Connects to a Matrix homeserver via mautrix (with optional E2EE) and relays + messages between Matrix rooms/DMs and the Hermes agent. Supports threads, + HTML/markdown rendering, native media uploads, mention gating, free-response + rooms, and per-room allowlists. +author: NousResearch +requires_env: + - name: MATRIX_HOMESERVER + description: "Matrix homeserver URL (e.g. https://matrix.org)" + prompt: "Matrix homeserver URL" + password: false + - name: MATRIX_ACCESS_TOKEN + description: "Matrix access token (or use MATRIX_PASSWORD for password login)" + prompt: "Matrix access token" + password: true +optional_env: + - name: MATRIX_PASSWORD + description: "Matrix account password (alternative to MATRIX_ACCESS_TOKEN)" + prompt: "Matrix password" + password: true + - name: MATRIX_ALLOWED_USERS + description: "Comma-separated Matrix user IDs allowed to talk to the bot" + prompt: "Allowed users (comma-separated)" + password: false + - name: MATRIX_ALLOW_ALL_USERS + description: "Allow any Matrix user to trigger the bot (dev only)" + prompt: "Allow all users? (true/false)" + password: false + - name: MATRIX_HOME_CHANNEL + description: "Default room ID for cron / notification delivery" + prompt: "Home room ID" + password: false + - name: MATRIX_HOME_CHANNEL_NAME + description: "Display name for the Matrix home room" + prompt: "Home room display name" + password: false diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py index c42bb835830d..7c400fedee99 100644 --- a/tools/send_message_tool.py +++ b/tools/send_message_tool.py @@ -787,7 +787,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, elif platform == Platform.SMS: result = await _send_sms(pconfig.api_key, chat_id, chunk) elif platform == Platform.MATRIX: - result = await _send_matrix(pconfig.token, pconfig.extra, chat_id, chunk) + result = await _registry_standalone_send("matrix", pconfig, chat_id, chunk, thread_id) elif platform == Platform.DINGTALK: result = await _registry_standalone_send("dingtalk", pconfig, chat_id, chunk, thread_id) elif platform == Platform.FEISHU: @@ -1372,54 +1372,15 @@ async def _send_sms(auth_token, chat_id, message): return _error(f"SMS send failed: {e}") -async def _send_matrix(token, extra, chat_id, message): - """Send via Matrix Client-Server API. - - Converts markdown to HTML for rich rendering in Matrix clients. - Falls back to plain text if the ``markdown`` library is not installed. - """ - try: - import aiohttp - except ImportError: - return {"error": "aiohttp not installed. Run: pip install aiohttp"} - try: - homeserver = (extra.get("homeserver") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/") - token = token or os.getenv("MATRIX_ACCESS_TOKEN", "") - if not homeserver or not token: - return {"error": "Matrix not configured (MATRIX_HOMESERVER, MATRIX_ACCESS_TOKEN required)"} - txn_id = f"hermes_{int(time.time() * 1000)}_{os.urandom(4).hex()}" - from urllib.parse import quote - 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"} - - # Build message payload with optional HTML formatted_body. - payload = {"msgtype": "m.text", "body": message} - try: - import markdown as _md - html = _md.markdown(message, extensions=["fenced_code", "tables"]) - # Convert h1-h6 to bold for Element X compatibility. - html = re.sub(r"(.*?)", r"\1", html) - payload["format"] = "org.matrix.custom.html" - payload["formatted_body"] = html - except ImportError: - pass - - async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session: - async with session.put(url, headers=headers, json=payload) as resp: - if resp.status not in {200, 201}: - body = await resp.text() - return _error(f"Matrix API error ({resp.status}): {body}") - data = await resp.json() - return {"success": True, "platform": "matrix", "chat_id": chat_id, "message_id": data.get("event_id")} - except Exception as e: - return _error(f"Matrix send failed: {e}") +# _send_matrix moved to plugins/platforms/matrix/adapter.py::_standalone_send, +# wired via standalone_sender_fn and reached through _registry_standalone_send. #41112. +# (_send_matrix_via_adapter below stays β€” it's the native-media upload path.) async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None, thread_id=None): """Send via the Matrix adapter so native Matrix media uploads are preserved.""" try: - from gateway.platforms.matrix import MatrixAdapter + from plugins.platforms.matrix.adapter import MatrixAdapter except ImportError: return {"error": "Matrix dependencies not installed. Run: pip install 'mautrix[encryption]'"}