Merge branch 'simp/r3-29-E' into simp/integration3

This commit is contained in:
Teknium
2026-09-02 23:11:49 -07:00
3 changed files with 190 additions and 246 deletions
+118 -117
View File
@@ -128,7 +128,6 @@ class IRCAdapter(BasePlatformAdapter):
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)}
max_msg = extra.get("max_message_length")
if max_msg is None:
with contextlib.suppress(Exception):
@@ -295,14 +294,11 @@ class IRCAdapter(BasePlatformAdapter):
if params:
self._current_nick = params[0] # server may confirm our nick
elif 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:
self._current_nick = f"{base}_{int(suffix_match.group(1)) + 1}"
elif self._current_nick == self.nickname:
self._current_nick = self.nickname + "_"
self._current_nick = f"{self.nickname.rstrip('_0123456789')}_{int(suffix_match.group(1)) + 1}"
else:
self._current_nick = self.nickname + "_1"
self._current_nick = self.nickname + ("_" if self._current_nick == self.nickname else "_1")
await self._send_raw(f"NICK {self._current_nick}")
elif command == "PRIVMSG" and len(params) >= 2:
await self._handle_privmsg(_extract_nick(msg["prefix"]), params[0], params[1])
@@ -336,8 +332,8 @@ class IRCAdapter(BasePlatformAdapter):
"""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)
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()))
@@ -356,11 +352,9 @@ def validate_config(config) -> bool:
def interactive_setup() -> None:
"""Interactive `hermes gateway setup` flow (lazy-imports hermes_cli so the plugin imports in non-CLI contexts)."""
"""`hermes gateway setup` flow (lazy hermes_cli imports keep the plugin importable outside the CLI)."""
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")
existing_server = get_env_value("IRC_SERVER")
@@ -397,29 +391,28 @@ def interactive_setup() -> None:
elif get_env_value("IRC_PORT"):
save_env_value("IRC_PORT", "") # user cleared the prompt; drop the override
if not _required("Bot nickname (e.g. hermes-bot)", "IRC_NICKNAME", get_env_value("IRC_NICKNAME") or "", "Nickname"):
return
if not _required("Channel to join (e.g. #hermes — comma-separate for multiple)", "IRC_CHANNEL",
get_env_value("IRC_CHANNEL") or "", "Channel"):
return
for label, env, what in (("Bot nickname (e.g. hermes-bot)", "IRC_NICKNAME", "Nickname"),
("Channel to join (e.g. #hermes — comma-separate for multiple)", "IRC_CHANNEL", "Channel")):
if not _required(label, env, get_env_value(env) or "", what):
return
print()
print_info("🔑 Optional authentication")
print_info(" Leave blank to skip.")
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"),
):
("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.")
for line in ("🔒 Access control: restrict who can message the bot",
" IRC nicks are not authenticated — anyone can claim any nick.",
" For public channels, pair with NickServ-only mode on your network",
" if you want stronger identity guarantees."):
print_info(line)
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", "")
@@ -446,23 +439,18 @@ def is_connected(config) -> bool:
def _env_enablement() -> dict | None:
"""Seed ``PlatformConfig.extra`` from env vars BEFORE adapter construction.
Returns ``None`` when IRC isn't minimally configured (caller skips auto-enabling).
The special ``home_channel`` key becomes a ``HomeChannel`` on the PlatformConfig.
"""
"""Seed ``PlatformConfig.extra`` from env vars BEFORE adapter construction; ``None`` when IRC isn't
minimally configured (caller skips auto-enabling). ``home_channel`` becomes a ``HomeChannel``."""
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}
if port := _get_scoped_secret("IRC_PORT", "").strip():
with contextlib.suppress(ValueError):
seed["port"] = int(port)
if nickname := _get_scoped_secret("IRC_NICKNAME", "").strip():
seed["nickname"] = nickname
if use_tls := _get_scoped_secret("IRC_USE_TLS", "").strip().lower():
seed["use_tls"] = use_tls in _TRUTHY
for env, key, conv in (("IRC_PORT", "port", int), ("IRC_NICKNAME", "nickname", str),
("IRC_USE_TLS", "use_tls", lambda v: v.lower() in _TRUTHY)):
if raw := _get_scoped_secret(env, "").strip():
with contextlib.suppress(ValueError): # non-numeric IRC_PORT is dropped, not fatal
seed[key] = conv(raw)
# 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):
@@ -486,14 +474,92 @@ def _sa_error(detail: str) -> Dict[str, Any]:
return {"error": f"IRC standalone send: {detail}"}
class _StandaloneConn:
"""Raw line I/O for ``_standalone_send``; ``pump`` answers PINGs while waiting for a numeric."""
def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
self.reader, self.writer = reader, writer
self._loop = asyncio.get_running_loop()
async def raw(self, line: str) -> None:
self.writer.write(_encode_line(line))
await self.writer.drain()
async def pump(self, timeout: float, on_msg):
"""Feed commands to ``on_msg`` until it returns non-None; None on timeout, ``_EOF`` on close."""
deadline = self._loop.time() + timeout
while True:
remaining = deadline - self._loop.time()
if remaining <= 0:
return None
try:
raw_line = await asyncio.wait_for(self.reader.readuntil(b"\r\n"), timeout=remaining)
except asyncio.TimeoutError:
return None
except asyncio.IncompleteReadError:
return _EOF
msg = _parse_irc_message(raw_line.decode("utf-8", errors="replace").rstrip("\r\n"))
if msg["command"] == "PING":
await self.raw(f"PONG :{msg['params'][0] if msg['params'] else ''}")
continue
result = await on_msg(msg["command"])
if result is not None:
return result
async def close(self) -> None:
with contextlib.suppress(Exception):
self.writer.close()
await asyncio.wait_for(self.writer.wait_closed(), timeout=5.0)
async def _sa_register(conn: _StandaloneConn, nick_base: str, server_password: str) -> Optional[Dict[str, Any]]:
"""PASS/NICK/USER and wait for 001, retrying nick collisions; returns an error dict or None on success."""
nick_attempts = 0
standalone_nick = f"{nick_base}-cron"[:30]
async def _on_registration(cmd: str):
nonlocal nick_attempts, standalone_nick
if cmd in {"432", "433"}:
nick_attempts += 1
if nick_attempts > 5:
return _sa_error("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 conn.raw(f"NICK {standalone_nick}")
elif cmd in {"464", "465"}:
return _sa_error(f"server rejected client ({cmd})")
return True if cmd == "001" else None
if server_password:
await conn.raw(f"PASS {_strip_irc_control_chars(server_password)}")
await conn.raw(f"NICK {standalone_nick}")
await conn.raw(f"USER {standalone_nick} 0 * :Hermes Agent (cron)")
registered = await conn.pump(15.0, _on_registration)
if registered is True:
return None
if registered is None:
return _sa_error("registration timeout (no RPL_WELCOME)")
return _sa_error("server closed connection during registration") if registered is _EOF else registered
async def _sa_join(conn: _StandaloneConn, target: str) -> Optional[Dict[str, Any]]:
"""JOIN a channel target (+n channels drop PRIVMSG from non-members); error dict only on explicit rejection."""
async def _on_join(cmd: str):
if cmd in {"403", "405", "471", "473", "474", "475"}:
return _sa_error(f"JOIN {target} rejected ({cmd})")
return True if cmd in {"366", "JOIN"} else None
await conn.raw(f"JOIN {target}")
# No JOIN ack within 5s (or EOF): proceed anyway, the server may still deliver.
joined = await conn.pump(5.0, _on_join)
return joined if isinstance(joined, dict) else None
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.
"""
"""Open an ephemeral IRC connection, send a PRIVMSG, and quit (out-of-process cron delivery via
``send_message_tool``). 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, channel = _server_channel(pconfig)
if not server or not channel:
@@ -514,7 +580,6 @@ async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Op
return _sa_error("chat_id contains illegal IRC characters")
# 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:
@@ -523,86 +588,26 @@ async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Op
raise
except Exception as e:
return {"error": f"IRC standalone connect failed: {e}"}
async def _raw(line: str) -> None:
writer.write(_encode_line(line))
await writer.drain()
loop = asyncio.get_running_loop()
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 None
try:
raw_line = await asyncio.wait_for(reader.readuntil(b"\r\n"), timeout=remaining)
except asyncio.TimeoutError:
return None
except asyncio.IncompleteReadError:
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 _sa_error("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 _sa_error(f"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 _sa_error(f"JOIN {target} rejected ({cmd})")
return True if cmd in {"366", "JOIN"} else None
conn = _StandaloneConn(reader, writer)
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 _sa_error("registration timeout (no RPL_WELCOME)")
if registered is _EOF:
return _sa_error("server closed connection during registration")
if registered is not True:
return registered
if error := await _sa_register(conn, nick_base, server_password):
return error
if nickserv_password:
await _raw(f"PRIVMSG NickServ :IDENTIFY {_strip_irc_control_chars(nickserv_password)}")
await conn.raw(f"PRIVMSG NickServ :IDENTIFY {_strip_irc_control_chars(nickserv_password)}")
await asyncio.sleep(2)
# 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}")
# 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
# JOIN before PRIVMSG; never JOIN bare nicks (DM target) or server queries.
if _is_irc_channel(target) and (error := await _sa_join(conn, target)):
return error
# 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 conn.raw(f"PRIVMSG {target} :{line}")
await asyncio.sleep(0.3)
if not lines:
return _sa_error("empty message after stripping")
await _raw("QUIT :delivered")
await conn.raw("QUIT :delivered")
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(reader.read(1024), timeout=2.0)
return {"success": True, "message_id": _ms_id()}
@@ -612,9 +617,7 @@ async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Op
logger.debug("IRC standalone send raised", exc_info=True)
return {"error": f"IRC standalone send failed: {e}"}
finally:
with contextlib.suppress(Exception):
writer.close()
await asyncio.wait_for(writer.wait_closed(), timeout=5.0)
await conn.close()
def register(ctx):
@@ -643,6 +646,4 @@ def register(ctx):
"— use plain text only. Messages are limited to ~450 characters per "
"line (long messages are automatically split). In channels, users "
"address you by prefixing your nick. Keep responses concise and "
"conversational."
),
)
"conversational."))
+45 -86
View File
@@ -13,9 +13,11 @@ import asyncio
import contextlib
import json
import logging
import mimetypes
import os
import re
from pathlib import Path
from urllib.parse import unquote as _unquote
from typing import Any, Dict, List, Optional, Tuple
from gateway.config import Platform, PlatformConfig
@@ -88,12 +90,10 @@ def check_mattermost_requirements() -> bool:
def validate_mattermost_config(config: PlatformConfig) -> bool:
"""Return True when Mattermost has enough config to connect."""
extra = getattr(config, "extra", {}) or {}
token = (getattr(config, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip()
url = (extra.get("url", "") or _get_scoped_secret("MATTERMOST_URL", "")).strip()
if not token:
if not (getattr(config, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip():
logger.debug("Mattermost: MATTERMOST_TOKEN not set")
return False
if not url:
if not (extra.get("url", "") or _get_scoped_secret("MATTERMOST_URL", "")).strip():
logger.warning("Mattermost: MATTERMOST_URL not set")
return False
return True
@@ -117,8 +117,7 @@ class MattermostAdapter(BasePlatformAdapter):
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")
).lower()
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 = ""
self._dedup = MessageDeduplicator()
@@ -182,22 +181,15 @@ class MattermostAdapter(BasePlatformAdapter):
return rootish and broken
async def _post_preserving_thread(
self, chat_id: str, payload: Dict[str, Any], metadata: _Metadata
) -> Dict[str, Any]:
self, chat_id: str, payload: Dict[str, Any], metadata: _Metadata) -> Dict[str, Any]:
"""Post once, optionally falling back flat for final notify content."""
data = await self._api_post("posts", payload)
if data or "root_id" not in payload:
if (data or "root_id" not in payload or not (isinstance(metadata, dict) and metadata.get("notify"))
or not self._last_post_failure_is_broken_thread_root()):
return data
if not (isinstance(metadata, dict) and metadata.get("notify")):
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
).strip()
flat_payload = {k: v for k, v in payload.items() if k != "root_id"}
flat_payload["message"] = ("⚠️ Mattermost thread delivery failed; posting final reply in channel.\n\n"
+ str(flat_payload.get("message") or "")).strip()
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)
@@ -220,8 +212,8 @@ class MattermostAdapter(BasePlatformAdapter):
async def _post_with_file(
self, chat_id: str, file_id: str, caption: Optional[str], reply_to: Optional[str],
metadata: _Metadata) -> SendResult:
data = await self._post_message(chat_id, caption or "", reply_to, metadata, [file_id])
return _post_result(data, _POST_WITH_FILE_ERROR)
return _post_result(await self._post_message(chat_id, caption or "", reply_to, metadata, [file_id]),
_POST_WITH_FILE_ERROR)
async def _upload_file(
self, channel_id: str, file_data: bytes, filename: str, content_type: str = "application/octet-stream"
@@ -266,8 +258,7 @@ 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
)
"Mattermost: authenticated as @%s (%s) on %s", self._bot_username, self._bot_user_id, self._base_url)
self._ws_task = asyncio.create_task(self._ws_loop())
self._mark_connected()
@@ -297,8 +288,7 @@ class MattermostAdapter(BasePlatformAdapter):
return data["root_id"] if data and data.get("root_id") else post_id
async def send(
self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: _Metadata = None
) -> SendResult:
self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: _Metadata = None) -> SendResult:
"""Send a message (or multiple chunks) to a channel."""
if not content:
return SendResult(success=True)
@@ -324,9 +314,8 @@ class MattermostAdapter(BasePlatformAdapter):
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:
formatted = self.format_message(content)
data = await self._api("PUT", f"posts/{message_id}/patch", _with_mentions_disabled({"message": formatted}))
return _post_result(data, "Failed to edit post")
payload = _with_mentions_disabled({"message": self.format_message(content)})
return _post_result(await self._api("PUT", f"posts/{message_id}/patch", payload), "Failed to edit post")
async def send_image(
self, chat_id: str, image_url: str, caption: Optional[str] = None,
@@ -396,10 +385,6 @@ class MattermostAdapter(BasePlatformAdapter):
logger.warning("Mattermost: failed to download %s after %d attempts: %s", url, attempt + 1, exc)
return await fallback()
if file_data is None:
logger.warning("Mattermost: download returned no data for %s", url)
return await fallback()
file_id = await self._upload_file(chat_id, file_data, _url_filename(url, f"{kind}.png"), ct)
if not file_id:
return await fallback()
@@ -409,8 +394,6 @@ class MattermostAdapter(BasePlatformAdapter):
self, chat_id: str, file_path: str, caption: Optional[str], reply_to: Optional[str],
file_name: Optional[str] = None, metadata: _Metadata = 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)
@@ -425,9 +408,7 @@ class MattermostAdapter(BasePlatformAdapter):
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:])
@@ -505,9 +486,8 @@ class MattermostAdapter(BasePlatformAdapter):
except Exception as exc:
if self._closing:
return
# Permanent auth/permission failure: escalate via the fatal-error hook (a bare
# return would leave is_connected() healthy with a dead listener). Type-based
# only — substring matching on "401" misclassified transient errors.
# Permanent auth failure: escalate via the fatal-error hook (a bare return leaves is_connected()
# healthy with a dead listener). Type-based: substring "401" matching 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)
@@ -598,12 +578,11 @@ class MattermostAdapter(BasePlatformAdapter):
continue
file_data = await resp.read()
if mime.startswith("image/"):
local_path = cache_image_from_bytes(file_data, ext or ".png")
media_urls.append(cache_image_from_bytes(file_data, ext or ".png"))
elif mime.startswith("audio/"):
local_path = cache_audio_from_bytes(file_data, ext or ".ogg")
media_urls.append(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_urls.append(cache_document_from_bytes(file_data, fname))
media_types.append(mime)
except Exception as exc:
logger.warning("Mattermost: error downloading file %s: %s", fid, exc)
@@ -613,62 +592,44 @@ class MattermostAdapter(BasePlatformAdapter):
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)
post = json.loads(data.get("post") or "")
except (json.JSONDecodeError, TypeError):
return
# Ignore own messages and system posts.
if post.get("user_id") == self._bot_user_id or post.get("type"):
# Ignore own messages, system posts and redeliveries.
sender_id, post_id = post.get("user_id", ""), post.get("id", "")
if sender_id == self._bot_user_id or post.get("type") or self._dedup.is_duplicate(post_id):
return
post_id = post.get("id", "")
if self._dedup.is_duplicate(post_id):
return
channel_id = post.get("channel_id", "")
channel_type_raw = data.get("channel_type", "O")
channel_id, is_dm = post.get("channel_id", ""), data.get("channel_type", "O") == "D"
message_text = post.get("message", "")
# DMs need no gating; channels are mention-gated.
if channel_type_raw != "D":
if not is_dm: # DMs need no gating; channels are mention-gated.
message_text = self._apply_channel_gating(channel_id, message_text)
if message_text is None:
return
sender_id = post.get("user_id", "")
sender_name = data.get("sender_name", "").lstrip("@") or sender_id
# Thread support: replies use root_id; in thread mode a top-level channel
# post is itself a valid root for progress.
# Thread support: replies use root_id; in thread mode a top-level channel post is itself a valid root.
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 not is_dm and post_id:
thread_id = post_id
if message_text[:1].isspace() and message_text.lstrip().startswith("/"):
message_text = message_text.lstrip()
msg_type = MessageType.COMMAND if message_text.startswith("/") else MessageType.TEXT
media_urls, media_types = await self._download_attachments(post.get("file_ids") or [])
if media_types and msg_type == MessageType.TEXT:
msg_type = next((mt for prefix, mt in _MEDIA_MSG_TYPES if any(m.startswith(prefix) for m in media_types)),
MessageType.DOCUMENT)
source = self.build_source(
chat_id=channel_id, chat_type=_CHANNEL_TYPE_MAP.get(channel_type_raw, "channel"),
user_id=sender_id, user_name=sender_name, thread_id=thread_id, message_id=post_id)
chat_id=channel_id, chat_type=_CHANNEL_TYPE_MAP.get(data.get("channel_type", "O"), "channel"),
user_id=sender_id, user_name=data.get("sender_name", "").lstrip("@") or sender_id,
thread_id=thread_id, message_id=post_id)
from gateway.platforms.base import resolve_channel_prompt
msg_event = MessageEvent(
await self.handle_message(MessageEvent(
text=message_text, message_type=msg_type, source=source, raw_message=post, message_id=post_id,
media_urls=media_urls or None, media_types=media_types or None,
channel_prompt=resolve_channel_prompt(self.config.extra, channel_id, None))
await self.handle_message(msg_event)
channel_prompt=resolve_channel_prompt(self.config.extra, channel_id, None)))
# --- 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) -> Dict[str, Any]:
@@ -734,7 +695,6 @@ async def _standalone_send(
# --- Interactive setup wizard ---
def interactive_setup() -> None:
"""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
@@ -746,9 +706,9 @@ def interactive_setup() -> None:
if not prompt_yes_no("Reconfigure Mattermost?", False):
return
print_info("Works with any self-hosted Mattermost instance.")
print_info(" 1. In Mattermost: Integrations → Bot Accounts → Add Bot Account")
print_info(" 2. Copy the bot token")
for line in ("Works with any self-hosted Mattermost instance.",
" 1. In Mattermost: Integrations → Bot Accounts → Add Bot Account", " 2. Copy the bot token"):
print_info(line)
print()
mm_url = prompt("Mattermost server URL (e.g. https://mm.example.com)")
if mm_url:
@@ -760,9 +720,9 @@ def interactive_setup() -> None:
print_success("Mattermost token saved")
print()
print_info("🔒 Security: Restrict who can use your bot")
print_info(" To find your user ID: click your avatar → Profile")
print_info(" or use the API: GET /api/v4/users/me")
for line in ("🔒 Security: Restrict who can use your bot", " To find your user ID: click your avatar → Profile",
" or use the API: GET /api/v4/users/me"):
print_info(line)
print()
allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for open access)")
if allowed_users:
@@ -772,9 +732,10 @@ def interactive_setup() -> None:
print_info("⚠️ No allowlist set - anyone who can message the bot can use it!")
print()
print_info("📬 Home Channel: where Hermes delivers cron job results and notifications.")
print_info(" To get a channel ID: click channel name → View Info → copy the ID")
print_info(" You can also set this later by typing /set-home in a Mattermost channel.")
for line in ("📬 Home Channel: where Hermes delivers cron job results and notifications.",
" To get a channel ID: click channel name → View Info → copy the ID",
" You can also set this later by typing /set-home in a Mattermost channel."):
print_info(line)
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)
@@ -785,7 +746,6 @@ def interactive_setup() -> None:
# --- YAML → env config bridge (apply_yaml_config_fn) ---
def _apply_yaml_config(yaml_cfg: dict, mattermost_cfg: dict) -> dict | None:
"""Translate ``config.yaml`` ``mattermost:`` keys into env vars + ``PlatformConfig.extra``.
@@ -825,7 +785,6 @@ def _is_connected(config) -> bool:
# --- Plugin registration entry point ---
def register(ctx) -> None:
"""Plugin entry point — called by the Hermes plugin system."""
ctx.register_platform(
+27 -43
View File
@@ -58,16 +58,14 @@ _WAKE_ID_KEYS = ("eventId", "attemptId", "messageId", "delivery_id", "wake_id",
_WAKE_PROMPT = (
"Raft wake hint received. New Raft messages may be pending. "
"If you have not read the Raft manual in this session, run "
"`raft manual get raft-cli-overview` before using Raft commands."
)
"`raft manual get raft-cli-overview` before using Raft commands.")
_CONTENT_FIELD_NAMES = {"body", "content", "message", "messages", "preview", "snippet", "text"}
_SAFE_SCALAR_RE = re.compile(r"^[a-zA-Z0-9._:@/ -]+$")
_MAX_SCALAR_LENGTH = 120
_ACTIVITY_ALLOWED_FIELDS = set(
"schema eventId sessionId hookEventName status occurredAt toolName toolInput toolOutput "
"toolInputTruncated toolOutputTruncated truncated errorClass durationMs".split()
)
"toolInputTruncated toolOutputTruncated truncated errorClass durationMs".split())
_ACTIVE_ADAPTERS: "weakref.WeakSet[RaftAdapter]" = weakref.WeakSet()
_ACTIVE_ADAPTERS_LOCK = threading.Lock()
_RAFT_CONTEXT_LOCK = threading.Lock()
@@ -82,7 +80,6 @@ def _resolve_raft_profile() -> str:
if _profile_scoped():
try:
from agent.secret_scope import get_secret
return (get_secret("RAFT_PROFILE") or "").strip()
except Exception:
return ""
@@ -136,8 +133,7 @@ def _make_activity_event(
"sessionId": _safe_scalar(session_id, "unknown") or "unknown",
"hookEventName": hook_event_name,
"status": "error" if status == "error" else "ok",
"occurredAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}
"occurredAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
for key, raw in (("toolName", tool_name), ("errorClass", error_class)):
safe = _safe_scalar(raw)
if safe:
@@ -158,6 +154,12 @@ def _make_activity_event(
return event
_OPTIONAL_FIELD_RULES = ( # checked in this order; first failure wins
(("toolName", "errorClass"), _safe_scalar, "a safe string"),
(("durationMs",), lambda v: _duration_ms(v) is not None, "a non-negative number"),
(("truncated", "toolInputTruncated", "toolOutputTruncated"), lambda v: isinstance(v, bool), "a boolean"))
def _validate_activity_event(value: Any) -> Dict[str, Any]:
if not isinstance(value, dict):
raise ValueError("activity event must be an object")
@@ -171,14 +173,10 @@ def _validate_activity_event(value: Any) -> Dict[str, Any]:
raise ValueError(f"activity event {key} must be a safe non-empty string")
if value.get("status") not in {"ok", "error"}:
raise ValueError("activity event status must be ok|error")
for key in ("toolName", "errorClass"):
if value.get(key) is not None and not _safe_scalar(value.get(key)):
raise ValueError(f"activity event {key} must be a safe string")
if value.get("durationMs") is not None and _duration_ms(value.get("durationMs")) is None:
raise ValueError("activity event durationMs must be a non-negative number")
for key in ("truncated", "toolInputTruncated", "toolOutputTruncated"):
if value.get(key) is not None and not isinstance(value.get(key), bool):
raise ValueError(f"activity event {key} must be a boolean")
for keys, ok, what in _OPTIONAL_FIELD_RULES: # optional fields: None passes, anything else must satisfy ``ok``
for key in keys:
if value.get(key) is not None and not ok(value.get(key)):
raise ValueError(f"activity event {key} must be {what}")
event = dict(value)
if event.get("durationMs") is not None:
event["durationMs"] = _duration_ms(event["durationMs"])
@@ -251,8 +249,7 @@ def _is_raft_context(**kwargs: Any) -> bool:
return True
return bool(
(safe_turn_id and safe_turn_id in _RAFT_TURN_IDS)
or (safe_session_id and safe_session_id in _RAFT_SESSION_IDS)
)
or (safe_session_id and safe_session_id in _RAFT_SESSION_IDS))
def _emit(hook_event_name: str, kwargs: Dict[str, Any], **fields: Any) -> None:
@@ -271,7 +268,6 @@ def _raft_hook(fn):
def wrapper(**kwargs: Any) -> None:
if _is_raft_context(**kwargs):
fn(**kwargs)
return wrapper
@@ -279,7 +275,6 @@ def _raft_hook(fn):
def _on_session_start(**kwargs: Any) -> None:
try:
from tools.env_passthrough import register_env_passthrough
register_env_passthrough(["RAFT_PROFILE"])
except Exception:
logger.debug("[raft] failed to register RAFT_PROFILE env passthrough", exc_info=True)
@@ -313,8 +308,7 @@ def _on_post_tool_call(**kwargs: Any) -> None:
tool_input=kwargs.get("args"),
tool_output=kwargs.get("error_message") or kwargs.get("result"),
error_class=kwargs.get("error_type") or ("tool_failure" if status == "error" else None),
duration_ms=kwargs.get("duration_ms"),
)
duration_ms=kwargs.get("duration_ms"))
@_raft_hook
@@ -417,8 +411,7 @@ class RaftAdapter(BasePlatformAdapter):
endpoint = f"http://{self._host}:{port}{self._path}"
cmd: List[str] = [
raft_bin, "--profile", profile, "agent", "bridge",
"--wake-adapter", "wake-channel", "--wake-channel-endpoint", endpoint,
]
"--wake-adapter", "wake-channel", "--wake-channel-endpoint", endpoint]
env = {**os.environ, "RAFT_CHANNEL_TOKEN": self._bridge_token}
try:
self._bridge_process = subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL)
@@ -427,10 +420,9 @@ class RaftAdapter(BasePlatformAdapter):
logger.exception("[raft] Failed to spawn bridge")
def _stop_bridge(self) -> None:
proc = self._bridge_process
proc, self._bridge_process = self._bridge_process, None
if proc is None:
return
self._bridge_process = None
try:
proc.terminate()
proc.wait(timeout=5)
@@ -453,8 +445,7 @@ class RaftAdapter(BasePlatformAdapter):
async def _handle_health(self, request: "web.Request") -> "web.Response":
activity = {"queueSize": self._activity_queue.size, "endpoint": "/activity", "drainEndpoint": "/activity/drain"}
return web.json_response(
{"status": "ok", "platform": "raft", "runtimeSession": self._runtime_session, "activity": activity}
)
{"status": "ok", "platform": "raft", "runtimeSession": self._runtime_session, "activity": activity})
def _authorized(self, request: "web.Request") -> bool:
return self._validate_bridge_token(request.headers.get(BRIDGE_TOKEN_HEADER, ""))
@@ -497,16 +488,13 @@ class RaftAdapter(BasePlatformAdapter):
return web.json_response(not_ready, status=503)
delivery_id = str(
next((payload.get(k) for k in _WAKE_ID_KEYS if payload.get(k)), None)
or f"raft-wake-{int(time.time() * 1000)}"
)
or f"raft-wake-{int(time.time() * 1000)}")
source = self.build_source(
chat_id=self._runtime_session, chat_name="Raft channel", chat_type="dm",
user_id="raft-bridge", user_name="Raft Bridge",
)
user_id="raft-bridge", user_name="Raft Bridge")
event = MessageEvent(
text=_WAKE_PROMPT, message_type=MessageType.TEXT, source=source, raw_message=payload,
message_id=delivery_id, internal=True,
)
message_id=delivery_id, internal=True)
try:
await self.handle_message(event)
except Exception:
@@ -549,8 +537,7 @@ class RaftAdapter(BasePlatformAdapter):
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),
)
profile=self._session_key_profile(event.source))
if session_key in self._active_sessions:
logger.debug("[raft] Wake queued for busy session %s", session_key)
merge_pending_message_event(self._pending_messages, session_key, event)
@@ -579,7 +566,6 @@ def interactive_setup() -> None:
CLI helpers are lazy-imported so the plugin stays importable in gateway runtime and tests."""
from hermes_cli.cli_output import print_header, print_info, print_success, print_warning, prompt, prompt_yes_no
from hermes_cli.config import get_env_value, save_env_value
print_header("Raft")
existing_profile = get_env_value("RAFT_PROFILE")
if existing_profile:
@@ -587,9 +573,9 @@ def interactive_setup() -> None:
if not prompt_yes_no("Reconfigure Raft?", False):
print_info(f"Keeping RAFT_PROFILE={existing_profile}.")
return
print_info("Connect Hermes to Raft as an external agent.")
print_info("Create the External Agent in Raft first, then run:")
print_info(" raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>")
for line in ("Connect Hermes to Raft as an external agent.", "Create the External Agent in Raft first, then run:",
" raft agent login --server <server-url> --agent <agent-id> --profile-slug <slug>"):
print_info(line)
print()
profile = prompt("Raft profile slug", default=existing_profile or "")
if not profile:
@@ -621,12 +607,10 @@ def register(ctx) -> None:
"Run `raft --profile {profile} profile show` to confirm which agent profile is active. "
"Run `raft --profile {profile} manual get raft-cli-overview` to learn available Raft commands. "
"Always pass `--profile {profile}` to every raft CLI call."
).format(profile=_resolve_raft_profile() or "your-agent-profile"),
)
).format(profile=_resolve_raft_profile() or "your-agent-profile"))
for hook_name, callback in (
("on_session_start", _on_session_start), ("pre_llm_call", _on_pre_llm_call),
("pre_tool_call", _on_pre_tool_call), ("post_tool_call", _on_post_tool_call),
("post_llm_call", _on_post_llm_call), ("on_session_end", _on_session_end),
("on_session_finalize", _on_session_finalize),
):
("on_session_finalize", _on_session_finalize)):
ctx.register_hook(hook_name, callback)