Skip to content

The agent that grows with you

refactor(irc,mattermost): split _standalone_send into _StandaloneConn/_sa_register/_sa_join phases; fold inbound ws event locals

Teknium884df9d8a051
diff --git a/plugins/platforms/irc/adapter.py b/plugins/platforms/irc/adapter.py
index f944c036cd5..e5a598b7b59 100644
--- a/plugins/platforms/irc/adapter.py
+++ b/plugins/platforms/irc/adapter.py
@@ -332,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()))
@@ -474,68 +474,48 @@ def _sa_error(detail: str) -> Dict[str, Any]:
return {"error": f"IRC standalone send: {detail}"}
-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 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:
- return _sa_error("IRC_SERVER and IRC_CHANNEL must be configured")
- port_value = _env_or_extra(extra, "IRC_PORT", "port", 6697)
- try:
- port = int(port_value)
- except (TypeError, ValueError):
- return _sa_error(f"invalid port {port_value!r}")
- nickname = _env_or_extra(extra, "IRC_NICKNAME", "nickname", "hermes-bot")
- use_tls_env = _get_scoped_secret("IRC_USE_TLS")
- 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.
- target = chat_id or channel
- if any(ch in target for ch in ("\r", "\n", "\x00", " ")):
- 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:
- 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:
- return {"error": f"IRC standalone connect failed: {e}"}
+class _StandaloneConn:
+ """Raw line I/O for ``_standalone_send``; ``pump`` answers PINGs while waiting for a numeric."""
- async def _raw(line: str) -> None:
- writer.write(_encode_line(line))
- await writer.drain()
+ def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
+ self.reader, self.writer = reader, writer
+ self._loop = asyncio.get_running_loop()
- 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(deadline: float, on_msg):
- """Feed lines to ``on_msg`` until it returns non-None; answers PINGs. None on timeout/EOF."""
+ 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 - loop.time()
+ remaining = deadline - self._loop.time()
if remaining <= 0:
return None
try:
- raw_line = await asyncio.wait_for(reader.readuntil(b"\r\n"), timeout=remaining)
+ 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 _raw(f"PONG :{msg['params'][0] if msg['params'] else ''}")
+ 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
@@ -545,47 +525,89 @@ async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Op
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}")
+ 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 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:
+ return _sa_error("IRC_SERVER and IRC_CHANNEL must be configured")
+ port_value = _env_or_extra(extra, "IRC_PORT", "port", 6697)
+ try:
+ port = int(port_value)
+ except (TypeError, ValueError):
+ return _sa_error(f"invalid port {port_value!r}")
+ nickname = _env_or_extra(extra, "IRC_NICKNAME", "nickname", "hermes-bot")
+ use_tls_env = _get_scoped_secret("IRC_USE_TLS")
+ 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.
+ target = chat_id or channel
+ if any(ch in target for ch in ("\r", "\n", "\x00", " ")):
+ 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"
+ plain = IRCAdapter._strip_markdown(message)
+ ssl_ctx = ssl.create_default_context() if use_tls 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 not True:
- 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
+ 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:
+ return {"error": f"IRC standalone connect failed: {e}"}
+ conn = _StandaloneConn(reader, writer)
+ try:
+ 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()}
@@ -595,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):
diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.py
index 15fbba039ea..9beb4456557 100644
--- a/plugins/platforms/mattermost/adapter.py
+++ b/plugins/platforms/mattermost/adapter.py
@@ -212,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"
@@ -314,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,
@@ -597,50 +596,36 @@ class MattermostAdapter(BasePlatformAdapter):
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) ---