diff --git a/plugin/adapter.py b/plugin/adapter.py index ac33fdb..101e5f3 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -1,501 +1,768 @@ -1|""" -2|Rocket.Chat Platform Adapter for Hermes Agent. -3| -4|Plugin-based gateway adapter connecting to a self-hosted Rocket.Chat server. -5|Uses WebSocket/DDP for real-time incoming messages + presence, -6|and REST API for sending replies. -7| -8|Zero external dependencies — stdlib only. -9|""" -10| -11|import asyncio -12|import contextvars -13|import json -14|import logging -15|import os -16|import queue -17|import re -18|import socket -19|import ssl -20|import struct -21|import threading -22|import time -23|import urllib.request -24|from typing import Any, Dict, List, Optional -25| -26|from .archivar.adapter_integration import ArchivarMessageHandler -27| -28|logger = logging.getLogger(__name__) -29|logger.setLevel(logging.INFO) -30|# Ensure adapter logs are visible in gateway.log by adding a stderr handler -31|if not logger.handlers: -32| _handler = logging.StreamHandler() -33| _handler.setLevel(logging.DEBUG) -34| _handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) -35| logger.addHandler(_handler) -36| logger.propagate = False # Don't double-log to root -37| -38|# ── Option C: Virtual Room Translation ───────────────────────────────────── -39|# ContextVar tracks the real Rocket.Chat room_id that triggered the current -40|# agent turn, so send() can route the response back to the correct room even -41|# though the Hermes session uses a synthetic user-based chat_id. -42|# This is the single mechanism that makes "ein Bernd für alle Räume" work -43|# without touching Hermes Core. -44|_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( -45| "_rocketchat_origin_room", default="" -46|) -47| -48|try: -49| from gateway.platforms.base import ( -50| BasePlatformAdapter, -51| SendResult, -52| MessageEvent, -53| MessageType, -54| ) -55| from gateway.session import SessionSource -56| from gateway.config import PlatformConfig, Platform -57|except ImportError: -58| # Fallback for standalone test / development outside gateway -59| BasePlatformAdapter = object -60| SendResult = dict -61| MessageEvent = dict -62| MessageType = object -63| SessionSource = object -64| PlatformConfig = object -65| Platform = str -66| -67| -68|def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str = "") -> str: -69| extra = getattr(config, "extra", {}) or {} -70| return os.getenv(env_var) or extra.get(key, default) -71| -72| -73|class RocketChatREST: -74| def __init__(self, base_url: str): -75| self.base_url = base_url.rstrip("/") -76| self.auth_token: Optional[str] = None -77| self.user_id: Optional[str] = None -78| -79| def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None): -80| url = f"{self.base_url}{endpoint}" -81| req_headers = dict(headers) if headers else {} -82| body = json.dumps(data).encode("utf-8") if data else None -83| if body: -84| req_headers["Content-Type"] = "application/json" -85| req = urllib.request.Request(url, data=body, headers=req_headers, method=method) -86| try: -87| with urllib.request.urlopen(req, timeout=30) as resp: -88| return json.loads(resp.read().decode("utf-8")) -89| except Exception as e: -90| logger.debug("REST %s %s failed: %s", method, endpoint, e) -91| return None -92| -93| def login(self, user: str, password: str) -> bool: -94| r = self._request("POST", "/api/v1/login", data={"user": user, "password": password}) -95| if r and r.get("status") == "success": -96| self.auth_token = r["data"]["authToken"] -97| self.user_id = r["data"]["userId"] -98| return True -99| return False -100| -101| def get_rooms(self) -> List[dict]: -102| if not self.auth_token: -103| return [] -104| r = self._request("GET", "/api/v1/rooms.get", headers={ -105| "X-Auth-Token": self.auth_token, -106| "X-User-Id": self.user_id, -107| }) -108| if not r or not r.get("success"): -109| return [] -110| rooms = [] -111| for rm in r.get("update", []): -112| t = rm.get("t", "c") -113| rid = rm["_id"] -114| if t == "d": -115| usernames = rm.get("usernames", []) -116| other = [u for u in usernames if u != os.getenv("ROCKETCHAT_USER", "")] -117| name = "DM mit " + (", ".join(other) if other else "unbekannt") -118| else: -119| name = rm.get("name", "unnamed") -120| rooms.append({"id": rid, "name": name, "type": t}) -121| return rooms -122| -123| def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> bool: -124| if not self.auth_token: -125| return False -126| payload = {"roomId": room_id, "text": text} -127| if attachments: -128| payload["attachments"] = attachments -129| r = self._request("POST", "/api/v1/chat.postMessage", headers={ -130| "X-Auth-Token": self.auth_token, -131| "X-User-Id": self.user_id, -132| "Content-Type": "application/json", -133| }, data=payload) -134| return bool(r and r.get("success")) -135| -136| -137|class DDPClient: -138| PING_INTERVAL = 8.0 -139| RECONNECT_BACKOFFS = [5, 10, 20, 30, 60, 120] -140| -141| def __init__(self, host: str, on_message_cb=None, on_connected_cb=None): -142| self.host = host -143| self._on_message = on_message_cb -144| self._on_connected = on_connected_cb -145| self.sock: Optional[socket.socket] = None -146| self.connected = False -147| self._running = False -148| self._reader_thread: Optional[threading.Thread] = None -149| self._write_lock = threading.Lock() -150| self._msg_queue: queue.Queue = queue.Queue() -151| self._next_sub_id = 1 -152| self._sub_rooms: Dict[str, str] = {} -153| self._session: Optional[str] = None -154| self._reconnect_attempt = 0 -155| self._last_rx_time = 0.0 -156| -157| def _create_socket(self) -> socket.socket: -158| ctx = ssl.create_default_context() -159| raw = socket.create_connection((self.host, 443), timeout=10) -160| return ctx.wrap_socket(raw, server_hostname=self.host) -161| -162| def _handshake(self, s: socket.socket) -> bool: -163| import base64 -164| key = base64.b64encode(os.urandom(16)).decode() -165| hs = ( -166| f"GET /websocket HTTP/1.1\r\n" -167| f"Host: {self.host}\r\n" -168| f"Upgrade: websocket\r\n" -169| f"Connection: Upgrade\r\n" -170| f"Sec-WebSocket-Key: {key}\r\n" -171| f"Sec-WebSocket-Version: 13\r\n" -172| f"Origin: https://{self.host}\r\n\r\n" -173| ) -174| s.sendall(hs.encode()) -175| resp = b"" -176| while b"\r\n\r\n" not in resp: -177| chunk = s.recv(1024) -178| if not chunk: -179| break -180| resp += chunk -181| return b"101 Switching Protocols" in resp -182| -183| def _send_frame(self, data: bytes, opcode: int = 0x01, mask: bool = True) -> None: -184| if not self.sock: -185| return -186| length = len(data) -187| if length < 126: -188| header = struct.pack("!BB", 0x80 | opcode, (0x80 if mask else 0x00) | length) -189| elif length < 65536: -190| header = struct.pack("!BBH", 0x80 | opcode, (0x80 if mask else 0x00) | 126, length) -191| else: -192| header = struct.pack("!BBQ", 0x80 | opcode, (0x80 if mask else 0x00) | 127, length) -193| frame = header -194| if mask: -195| masking = os.urandom(4) -196| masked = bytes(b ^ masking[i % 4] for i, b in enumerate(data)) -197| frame += masking + masked -198| else: -199| frame += data -200| with self._write_lock: -201| self.sock.sendall(frame) -202| -203| def _send_json(self, obj: dict) -> None: -204| self._send_frame(json.dumps(obj).encode("utf-8"), opcode=0x01, mask=True) -205| -206| def _send_raw_pong(self, payload: bytes) -> None: -207| self._send_frame(payload, opcode=0x0A, mask=True) -208| -209| def _reader_loop(self): -210| import select -211| self.sock.settimeout(1.0) -212| last_ping = time.time() -213| while self._running: -214| try: -215| if time.time() - last_ping >= self.PING_INTERVAL: -216| try: -217| self._send_json({"msg": "ping"}) -218| last_ping = time.time() -219| except Exception: -220| break -221| readable, _, _ = select.select([self.sock], [], [], 1.0) -222| if not readable: -223| continue -224| hdr = self.sock.recv(2) -225| if not hdr: -226| break -227| fin = (hdr[0] & 0x80) != 0 -228| opcode = hdr[0] & 0x0F -229| masked = (hdr[1] & 0x80) != 0 -230| length = hdr[1] & 0x7F -231| if length == 126: -232| length = struct.unpack("!H", self.sock.recv(2))[0] -233| elif length == 127: -234| length = struct.unpack("!Q", self.sock.recv(8))[0] -235| payload = b"" -236| remaining = length -237| while remaining > 0: -238| chunk = self.sock.recv(min(4096, remaining)) -239| if not chunk: -240| break -241| payload += chunk -242| remaining -= len(chunk) -243| if len(payload) < length: -244| break -245| if masked: -246| mask = payload[:4] -247| payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload[4:])) -248| if opcode == 0x09: -249| self._send_raw_pong(payload) -250| elif opcode == 0x01 and payload: -251| self._last_rx_time = time.time() -252| try: -253| data = json.loads(payload.decode("utf-8", errors="ignore")) -254| msg_type = data.get("msg", "") -255| if msg_type == "connected": -256| self.connected = True -257| self._session = data.get("session") -258| if self._on_connected: -259| self._on_connected() -260| elif msg_type == "ping": -261| self._send_json({"msg": "pong"}) -262| elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages": -263| fields = data.get("fields", {}) -264| args = fields.get("args", []) -265| if args and isinstance(args, list) and len(args) >= 1: -266| self._msg_queue.put(args[0]) -267| except Exception: -268| pass -269| elif opcode == 0x08: -270| break -271| except Exception: -272| break -273| self.connected = False -274| logger.debug("DDP reader thread exited") -275| -276| def is_alive(self, max_silence: float = 300.0) -> bool: -277| """Detect silent death: socket looks connected but no traffic for max_silence seconds.""" -278| if not self.connected or not self.sock: -279| return False -280| if self._last_rx_time == 0: -281| # Never received anything yet — use connect time as baseline -282| return True -283| return (time.time() - self._last_rx_time) < max_silence -284| -285| def connect_and_login(self, token: str) -> bool: -286| self._last_rx_time = time.time() -287| try: -288| self.sock = self._create_socket() -289| if not self._handshake(self.sock): -290| return False -291| self._running = True -292| self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True) -293| self._reader_thread.start() -294| time.sleep(0.3) -295| self._send_json({"msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"]}) -296| for _ in range(50): -297| if self.connected: -298| break -299| time.sleep(0.1) -300| if not self.connected: -301| self.disconnect() -302| return False -303| time.sleep(0.2) -304| self._send_json({"msg": "method", "method": "login", -305| "params": [{"resume": token}], "id": "ddplogin"}) -306| time.sleep(0.5) -307| return True -308| except Exception as e: -309| logger.error("DDP connect failed: %s", e) -310| self.disconnect() -311| return False -312| -313| def subscribe_room(self, room_id: str) -> Optional[str]: -314| if not self.connected: -315| return None -316| sub_id = f"sub{self._next_sub_id}" -317| self._next_sub_id += 1 -318| # CRITICAL: Rocket.Chat V5+ requires {"token": "true"} as second param, -319| # otherwise subscribe succeeds but NO messages ever stream. -320| self._send_json({ -321| "msg": "sub", -322| "name": "stream-room-messages", -323| "params": [room_id, {"token": "true"}], -324| "id": sub_id -325| }) -326| self._sub_rooms[room_id] = sub_id -327| return sub_id -328| -329| def set_status(self, status: str) -> bool: -330| if not self.connected: -331| return False -332| method = f"UserPresence:{status}" -333| self._send_json({"msg": "method", "method": method, "params": [], "id": f"st{int(time.time()*1000)}"}) -334| return True -335| -336| def disconnect(self): -337| self._running = False -338| if self.sock: -339| try: -340| self.sock.close() -341| except Exception: -342| pass -343| self.sock = None -344| self.connected = False -345| self._sub_rooms.clear() -346| -347| def reconnect_and_restore(self, token: str) -> bool: -348| self.disconnect() -349| time.sleep(1) -350| old_subs = list(self._sub_rooms.keys()) -351| self._sub_rooms.clear() -352| if self.connect_and_login(token): -353| for rid in old_subs: -354| self.subscribe_room(rid) -355| return True -356| return False -357| -358| -359|class RocketChatAdapter(BasePlatformAdapter): -360| HEALTH_CHECK_INTERVAL = 60.0 # seconds -361| HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect -362| -363| def __init__(self, config: PlatformConfig): -364| super().__init__(config=config, platform=Platform("rocketchat")) -365| self.base_url = _get_config_str(config, "base_url", "ROCKETCHAT_BASE_URL") -366| self.user = _get_config_str(config, "user", "ROCKETCHAT_USER") -367| self.password = _get_config_str(config, "password", "ROCKETCHAT_PASSWORD") -368| self.rest = RocketChatREST(self.base_url) -369| self.ddp: Optional[DDPClient] = None -370| self._auth_token: Optional[str] = None -371| self._user_id: Optional[str] = None -372| self._rooms: List[dict] = [] -373| self._subscribed_rooms: set = set() -374| self._listen_task: Optional[asyncio.Task] = None -375| self._status_timer: Optional[threading.Timer] = None -376| self._last_activity = 0.0 -377| self._shutdown_event = threading.Event() -378| self._room_info: Dict[str, dict] = {} -379| # Clarify-Queue: tracks pending button questions per chat_id -380| # so incoming replies can be correlated with the original question. -381| self._pending_clarifies: Dict[str, dict] = {} -382| # Option C: user-based room mapping for virtual chat_id translation. -383| # Key: "user:", Value: list of real room_ids for that user. -384| # Built during connect() from REST get_rooms. -385| self._user_rooms: Dict[str, List[str]] = {} -386| # Health-check state -387| self._last_server_activity = 0.0 # ts of last DDP ping/pong or message -388| self._health_check_timer: Optional[threading.Timer] = None -389| self._last_ddp_ping_ok = False -390| self._running = False -391| # Archivar: Embedding-basierte Nachrichten-Klassifikation -392| self.archivar = ArchivarMessageHandler() -393| -394| async def connect(self) -> bool: -395| if not self.base_url or not self.user or not self.password: -396| logger.error("[rocketchat] Missing configuration") -397| return False -398| if not self.rest.login(self.user, self.password): -399| logger.error("[rocketchat] REST login failed") -400| return False -401| self._auth_token = self.rest.auth_token -402| self._user_id = self.rest.user_id -403| host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0] -404| self.ddp = DDPClient( -405| host=host, -406| on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None, -407| ) -408| if not self.ddp.connect_and_login(self._auth_token): -409| logger.error("[rocketchat] DDP connect/login failed") -410| return False -411| self._rooms = self.rest.get_rooms() -412| logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms)) -413| for room in self._rooms: -414| sub_id = self.ddp.subscribe_room(room["id"]) -415| if sub_id: -416| self._subscribed_rooms.add(room["id"]) -417| self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]} -418| logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"]) -419| logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms)) -420| # Option C: Build user→rooms map for virtual chat_id translation. -421| # Each Rocket.Chat user gets a synthetic "user:" chat_id that -422| # maps to all rooms they participate in. This ensures Hermes creates ONE -423| # session per user across all rooms, enabling shared context. -424| self._user_rooms.clear() -425| for room in self._rooms: -426| rid = room["id"] -427| t = room["type"] -428| if t == "d": -429| usernames = [u.lower() for u in room.get("usernames", [])] -430| for uname in usernames: -431| if uname != (self.user or "").lower(): -432| virt = f"user:{uname}" -433| if virt not in self._user_rooms: -434| self._user_rooms[virt] = [] -435| if rid not in self._user_rooms[virt]: -436| self._user_rooms[virt].append(rid) -437| else: -438| # For groups/channels: query members via REST to build mappings. -439| # Fallback: use a generic group-based virtual chat_id. -440| # We still track the room so proaktive sends have a target. -441| pass # Group mapping handled on-demand in send() -442| logger.info("[rocketchat] Built user-room map: %d users, %s", -443| len(self._user_rooms), -444| {k: f"{len(v)} rooms" for k, v in self._user_rooms.items()}) -445| # Archivar initialisieren (Embedding-basierte Klassifikation) -446| try: -447| await self.archivar.initialize() -448| logger.info("[rocketchat] Archivar initialisiert — Embedding-basierte Nachrichten-Klassifikation aktiv") -449| except Exception as e: -450| logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e) -451| self._mark_connected() -452| self._running = True -453| self._listen_task = asyncio.create_task(self._listen_loop()) -454| self._last_activity = time.time() -455| logger.info("[rocketchat] Listen loop started, _running=%s", self._running) -456| logger.info("[rocketchat] Connected to %s", self.base_url) -457| return True -458| -459| def _schedule_idle_timer(self) -> None: -460| """Schedule idle timer to mark bot as away when inactive.""" -461| if self._status_timer: -462| self._status_timer.cancel() -463| -464| def _set_away(): -465| if self.ddp: -466| self.ddp.set_status("away") -467| -468| self._status_timer = threading.Timer(300.0, _set_away) # 5 minutes -469| self._status_timer.daemon = True -470| self._status_timer.start() -471| -472| async def _process_incoming(self, msg_obj) -> None: -473| """Process an incoming message from the DDP queue.""" -474| if not isinstance(msg_obj, dict): -475| return -476| -477| # Check if this is a button click response by looking for specific fields -478| is_button_response = ( -479| msg_obj.get("triggerId") and -480| msg_obj.get("actions") and -481| msg_obj.get("params", {}).get("triggerSender") and -482| msg_obj.get("params", {}).get("payload") -483| ) -484| -485| msg_id = msg_obj.get("_id", "") -486| text = msg_obj.get("msg", "") -487| room_id = msg_obj.get("rid", "") -488| user_info = msg_obj.get("u", {}) -489| username = (user_info.get("username", "") or "").lower() # normalize case -490| -491| # NEW: Check for file attachments in the message and enrich the text -492| file_info = msg_obj.get("file") -493| attachments = msg_obj.get("attachments", []) -494| if file_info or attachments: -495| file_details = [] -496| seen_ids = set() -497| base_url = self.base_url.rstrip("/") -498| # Process file object if present (has precise MIME type) -499| if file_info and isinstance(file_info, dict): -500| filename = file_info.get("name", "unknown") -501| \ No newline at end of file +""" +Rocket.Chat Platform Adapter for Hermes Agent. + +Plugin-based gateway adapter connecting to a self-hosted Rocket.Chat server. +Uses WebSocket/DDP for real-time incoming messages + presence, +and REST API for sending replies. + +Zero external dependencies — stdlib only. +""" + +import asyncio +import contextvars +import json +import logging +import os +import queue +import re +import socket +import ssl +import struct +import threading +import time +import urllib.request +from typing import Any, Dict, List, Optional + +from .archivar.adapter_integration import ArchivarMessageHandler + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) +# Ensure adapter logs are visible in gateway.log by adding a stderr handler +if not logger.handlers: + _handler = logging.StreamHandler() + _handler.setLevel(logging.DEBUG) + _handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) + logger.addHandler(_handler) + logger.propagate = False # Don't double-log to root + +# ── Option C: Virtual Room Translation ───────────────────────────────────── +# ContextVar tracks the real Rocket.Chat room_id that triggered the current +# agent turn, so send() can route the response back to the correct room even +# though the Hermes session uses a synthetic user-based chat_id. +# This is the single mechanism that makes "ein Bernd für alle Räume" work +# without touching Hermes Core. +_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( + "_rocketchat_origin_room", default="" +) + +try: + from gateway.platforms.base import ( + BasePlatformAdapter, + SendResult, + MessageEvent, + MessageType, + ) + from gateway.session import SessionSource + from gateway.config import PlatformConfig, Platform +except ImportError: + # Fallback for standalone test / development outside gateway + BasePlatformAdapter = object + SendResult = dict + MessageEvent = dict + MessageType = object + SessionSource = object + PlatformConfig = object + Platform = str + + +def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str = "") -> str: + extra = getattr(config, "extra", {}) or {} + return os.getenv(env_var) or extra.get(key, default) + + +class RocketChatREST: + def __init__(self, base_url: str): + self.base_url = base_url.rstrip("/") + self.auth_token: Optional[str] = None + self.user_id: Optional[str] = None + + def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None): + url = f"{self.base_url}{endpoint}" + req_headers = dict(headers) if headers else {} + body = json.dumps(data).encode("utf-8") if data else None + if body: + req_headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=body, headers=req_headers, method=method) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read().decode("utf-8")) + except Exception as e: + logger.debug("REST %s %s failed: %s", method, endpoint, e) + return None + + def login(self, user: str, password: str) -> bool: + r = self._request("POST", "/api/v1/login", data={"user": user, "password": password}) + if r and r.get("status") == "success": + self.auth_token = r["data"]["authToken"] + self.user_id = r["data"]["userId"] + return True + return False + + def get_rooms(self) -> List[dict]: + if not self.auth_token: + return [] + r = self._request("GET", "/api/v1/rooms.get", headers={ + "X-Auth-Token": self.auth_token, + "X-User-Id": self.user_id, + }) + if not r or not r.get("success"): + return [] + rooms = [] + for rm in r.get("update", []): + t = rm.get("t", "c") + rid = rm["_id"] + if t == "d": + usernames = rm.get("usernames", []) + other = [u for u in usernames if u != os.getenv("ROCKETCHAT_USER", "")] + name = "DM mit " + (", ".join(other) if other else "unbekannt") + else: + name = rm.get("name", "unnamed") + rooms.append({"id": rid, "name": name, "type": t}) + return rooms + + def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> bool: + if not self.auth_token: + return False + payload = {"roomId": room_id, "text": text} + if attachments: + payload["attachments"] = attachments + r = self._request("POST", "/api/v1/chat.postMessage", headers={ + "X-Auth-Token": self.auth_token, + "X-User-Id": self.user_id, + "Content-Type": "application/json", + }, data=payload) + return bool(r and r.get("success")) + + +class DDPClient: + PING_INTERVAL = 8.0 + RECONNECT_BACKOFFS = [5, 10, 20, 30, 60, 120] + + def __init__(self, host: str, on_message_cb=None, on_connected_cb=None): + self.host = host + self._on_message = on_message_cb + self._on_connected = on_connected_cb + self.sock: Optional[socket.socket] = None + self.connected = False + self._running = False + self._reader_thread: Optional[threading.Thread] = None + self._write_lock = threading.Lock() + self._msg_queue: queue.Queue = queue.Queue() + self._next_sub_id = 1 + self._sub_rooms: Dict[str, str] = {} + self._session: Optional[str] = None + self._reconnect_attempt = 0 + self._last_rx_time = 0.0 + + def _create_socket(self) -> socket.socket: + ctx = ssl.create_default_context() + raw = socket.create_connection((self.host, 443), timeout=10) + return ctx.wrap_socket(raw, server_hostname=self.host) + + def _handshake(self, s: socket.socket) -> bool: + import base64 + key = base64.b64encode(os.urandom(16)).decode() + hs = ( + f"GET /websocket HTTP/1.1\r\n" + f"Host: {self.host}\r\n" + f"Upgrade: websocket\r\n" + f"Connection: Upgrade\r\n" + f"Sec-WebSocket-Key: {key}\r\n" + f"Sec-WebSocket-Version: 13\r\n" + f"Origin: https://{self.host}\r\n\r\n" + ) + s.sendall(hs.encode()) + resp = b"" + while b"\r\n\r\n" not in resp: + chunk = s.recv(1024) + if not chunk: + break + resp += chunk + return b"101 Switching Protocols" in resp + + def _send_frame(self, data: bytes, opcode: int = 0x01, mask: bool = True) -> None: + if not self.sock: + return + length = len(data) + if length < 126: + header = struct.pack("!BB", 0x80 | opcode, (0x80 if mask else 0x00) | length) + elif length < 65536: + header = struct.pack("!BBH", 0x80 | opcode, (0x80 if mask else 0x00) | 126, length) + else: + header = struct.pack("!BBQ", 0x80 | opcode, (0x80 if mask else 0x00) | 127, length) + frame = header + if mask: + masking = os.urandom(4) + masked = bytes(b ^ masking[i % 4] for i, b in enumerate(data)) + frame += masking + masked + else: + frame += data + with self._write_lock: + self.sock.sendall(frame) + + def _send_json(self, obj: dict) -> None: + self._send_frame(json.dumps(obj).encode("utf-8"), opcode=0x01, mask=True) + + def _send_raw_pong(self, payload: bytes) -> None: + self._send_frame(payload, opcode=0x0A, mask=True) + + def _reader_loop(self): + import select + self.sock.settimeout(1.0) + last_ping = time.time() + while self._running: + try: + if time.time() - last_ping >= self.PING_INTERVAL: + try: + self._send_json({"msg": "ping"}) + last_ping = time.time() + except Exception: + break + readable, _, _ = select.select([self.sock], [], [], 1.0) + if not readable: + continue + hdr = self.sock.recv(2) + if not hdr: + break + fin = (hdr[0] & 0x80) != 0 + opcode = hdr[0] & 0x0F + masked = (hdr[1] & 0x80) != 0 + length = hdr[1] & 0x7F + if length == 126: + length = struct.unpack("!H", self.sock.recv(2))[0] + elif length == 127: + length = struct.unpack("!Q", self.sock.recv(8))[0] + payload = b"" + remaining = length + while remaining > 0: + chunk = self.sock.recv(min(4096, remaining)) + if not chunk: + break + payload += chunk + remaining -= len(chunk) + if len(payload) < length: + break + if masked: + mask = payload[:4] + payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload[4:])) + if opcode == 0x09: + self._send_raw_pong(payload) + elif opcode == 0x01 and payload: + self._last_rx_time = time.time() + try: + data = json.loads(payload.decode("utf-8", errors="ignore")) + msg_type = data.get("msg", "") + if msg_type == "connected": + self.connected = True + self._session = data.get("session") + if self._on_connected: + self._on_connected() + elif msg_type == "ping": + self._send_json({"msg": "pong"}) + elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages": + fields = data.get("fields", {}) + args = fields.get("args", []) + if args and isinstance(args, list) and len(args) >= 1: + self._msg_queue.put(args[0]) + except Exception: + pass + elif opcode == 0x08: + break + except Exception: + break + self.connected = False + logger.debug("DDP reader thread exited") + + def is_alive(self, max_silence: float = 300.0) -> bool: + """Detect silent death: socket looks connected but no traffic for max_silence seconds.""" + if not self.connected or not self.sock: + return False + if self._last_rx_time == 0: + # Never received anything yet — use connect time as baseline + return True + return (time.time() - self._last_rx_time) < max_silence + + def connect_and_login(self, token: str) -> bool: + self._last_rx_time = time.time() + try: + self.sock = self._create_socket() + if not self._handshake(self.sock): + return False + self._running = True + self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True) + self._reader_thread.start() + time.sleep(0.3) + self._send_json({"msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"]}) + for _ in range(50): + if self.connected: + break + time.sleep(0.1) + if not self.connected: + self.disconnect() + return False + time.sleep(0.2) + self._send_json({"msg": "method", "method": "login", + "params": [{"resume": token}], "id": "ddplogin"}) + time.sleep(0.5) + return True + except Exception as e: + logger.error("DDP connect failed: %s", e) + self.disconnect() + return False + + def subscribe_room(self, room_id: str) -> Optional[str]: + if not self.connected: + return None + sub_id = f"sub{self._next_sub_id}" + self._next_sub_id += 1 + # CRITICAL: Rocket.Chat V5+ requires {"token": "true"} as second param, + # otherwise subscribe succeeds but NO messages ever stream. + self._send_json({ + "msg": "sub", + "name": "stream-room-messages", + "params": [room_id, {"token": "true"}], + "id": sub_id + }) + self._sub_rooms[room_id] = sub_id + return sub_id + + def set_status(self, status: str) -> bool: + if not self.connected: + return False + method = f"UserPresence:{status}" + self._send_json({"msg": "method", "method": method, "params": [], "id": f"st{int(time.time()*1000)}"}) + return True + + def disconnect(self): + self._running = False + if self.sock: + try: + self.sock.close() + except Exception: + pass + self.sock = None + self.connected = False + self._sub_rooms.clear() + + def reconnect_and_restore(self, token: str) -> bool: + self.disconnect() + time.sleep(1) + old_subs = list(self._sub_rooms.keys()) + self._sub_rooms.clear() + if self.connect_and_login(token): + for rid in old_subs: + self.subscribe_room(rid) + return True + return False + + +class RocketChatAdapter(BasePlatformAdapter): + HEALTH_CHECK_INTERVAL = 60.0 # seconds + HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect + + def __init__(self, config: PlatformConfig): + super().__init__(config=config, platform=Platform("rocketchat")) + self.base_url = _get_config_str(config, "base_url", "ROCKETCHAT_BASE_URL") + self.user = _get_config_str(config, "user", "ROCKETCHAT_USER") + self.password = _get_config_str(config, "password", "ROCKETCHAT_PASSWORD") + self.rest = RocketChatREST(self.base_url) + self.ddp: Optional[DDPClient] = None + self._auth_token: Optional[str] = None + self._user_id: Optional[str] = None + self._rooms: List[dict] = [] + self._subscribed_rooms: set = set() + self._listen_task: Optional[asyncio.Task] = None + self._status_timer: Optional[threading.Timer] = None + self._last_activity = 0.0 + self._shutdown_event = threading.Event() + self._room_info: Dict[str, dict] = {} + # Clarify-Queue: tracks pending button questions per chat_id + # so incoming replies can be correlated with the original question. + self._pending_clarifies: Dict[str, dict] = {} + # Option C: user-based room mapping for virtual chat_id translation. + # Key: "user:", Value: list of real room_ids for that user. + # Built during connect() from REST get_rooms. + self._user_rooms: Dict[str, List[str]] = {} + # Health-check state + self._last_server_activity = 0.0 # ts of last DDP ping/pong or message + self._health_check_timer: Optional[threading.Timer] = None + self._last_ddp_ping_ok = False + self._running = False + # Archivar: Embedding-basierte Nachrichten-Klassifikation + self.archivar = ArchivarMessageHandler() + + async def connect(self) -> bool: + if not self.base_url or not self.user or not self.password: + logger.error("[rocketchat] Missing configuration") + return False + if not self.rest.login(self.user, self.password): + logger.error("[rocketchat] REST login failed") + return False + self._auth_token = self.rest.auth_token + self._user_id = self.rest.user_id + host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0] + self.ddp = DDPClient( + host=host, + on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None, + ) + if not self.ddp.connect_and_login(self._auth_token): + logger.error("[rocketchat] DDP connect/login failed") + return False + self._rooms = self.rest.get_rooms() + logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms)) + for room in self._rooms: + sub_id = self.ddp.subscribe_room(room["id"]) + if sub_id: + self._subscribed_rooms.add(room["id"]) + self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]} + logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"]) + logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms)) + # Option C: Build user→rooms map for virtual chat_id translation. + # Each Rocket.Chat user gets a synthetic "user:" chat_id that + # maps to all rooms they participate in. This ensures Hermes creates ONE + # session per user across all rooms, enabling shared context. + self._user_rooms.clear() + for room in self._rooms: + rid = room["id"] + t = room["type"] + if t == "d": + usernames = [u.lower() for u in room.get("usernames", [])] + for uname in usernames: + if uname != (self.user or "").lower(): + virt = f"user:{uname}" + if virt not in self._user_rooms: + self._user_rooms[virt] = [] + if rid not in self._user_rooms[virt]: + self._user_rooms[virt].append(rid) + else: + # For groups/channels: query members via REST to build mappings. + # Fallback: use a generic group-based virtual chat_id. + # We still track the room so proaktive sends have a target. + pass # Group mapping handled on-demand in send() + logger.info("[rocketchat] Built user-room map: %d users, %s", + len(self._user_rooms), + {k: f"{len(v)} rooms" for k, v in self._user_rooms.items()}) + # Archivar initialisieren (Embedding-basierte Klassifikation) + try: + await self.archivar.initialize() + logger.info("[rocketchat] Archivar initialisiert — Embedding-basierte Nachrichten-Klassifikation aktiv") + except Exception as e: + logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e) + self._mark_connected() + self._running = True + self._listen_task = asyncio.create_task(self._listen_loop()) + self._last_activity = time.time() + logger.info("[rocketchat] Listen loop started, _running=%s", self._running) + logger.info("[rocketchat] Connected to %s", self.base_url) + return True + + def _schedule_idle_timer(self) -> None: + """Schedule idle timer to mark bot as away when inactive.""" + if self._status_timer: + self._status_timer.cancel() + + def _set_away(): + if self.ddp: + self.ddp.set_status("away") + + self._status_timer = threading.Timer(300.0, _set_away) # 5 minutes + self._status_timer.daemon = True + self._status_timer.start() + + async def _process_incoming(self, msg_obj) -> None: + """Process an incoming message from the DDP queue.""" + if not isinstance(msg_obj, dict): + return + + # Check if this is a button click response by looking for specific fields + is_button_response = ( + msg_obj.get("triggerId") and + msg_obj.get("actions") and + msg_obj.get("params", {}).get("triggerSender") and + msg_obj.get("params", {}).get("payload") + ) + + msg_id = msg_obj.get("_id", "") + text = msg_obj.get("msg", "") + room_id = msg_obj.get("rid", "") + user_info = msg_obj.get("u", {}) + username = (user_info.get("username", "") or "").lower() # normalize case + + # NEW: Check for file attachments in the message and enrich the text + file_info = msg_obj.get("file") + attachments = msg_obj.get("attachments", []) + if file_info or attachments: + file_details = [] + seen_ids = set() + base_url = self.base_url.rstrip("/") + # Process file object if present (has precise MIME type) + if file_info and isinstance(file_info, dict): + filename = file_info.get("name", "unknown") + filetype = file_info.get("type", "unknown") + file_id = file_info.get("_id") + if file_id and filename: + seen_ids.add(file_id) + download_url = f"{base_url}/file-upload/{file_id}/{filename}" + file_details.append(f"[FILE] {filename} ({filetype})\nDownload: {download_url}") + # Process attachments if present (skip duplicates already covered by file_info) + if attachments and isinstance(attachments, list): + for attachment in attachments: + if isinstance(attachment, dict) and attachment.get("type") == "file": + title = attachment.get("title", "unknown") + title_link = attachment.get("title_link", "") + if title_link: + if title_link.startswith("/"): + download_url = f"{base_url}{title_link}" + else: + download_url = f"{base_url}/{title_link}" + # Extract file_id from title_link to detect duplicates + link_id = title_link.split("/")[2] if title_link.startswith("/file-upload/") else None + if link_id and link_id in seen_ids: + continue # Already covered by precise file_info + file_details.append(f"[FILE] {title} (file)\nDownload: {download_url}") + # Add file information to message text + if file_details: + file_info_text = "\n".join(file_details) + if text: + text = f"{text}\n\n{file_info_text}" + else: + text = file_info_text + msg_obj["msg"] = text + + # Skip own messages (case-insensitive comparison) + if username == (self.user or "").lower() or not text or not room_id: + return + # Skip system messages + if msg_obj.get("t"): + return + + # Update activity + self._last_activity = time.time() + room_name = self._room_info.get(room_id, {}).get("name", room_id) + room_type = self._room_info.get(room_id, {}).get("type", "unknown") + logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80]) + + # ── Option C: Virtual Room Translation ───────────────────────── + # Replace room-based chat_id with user-based virtual chat_id. + # This collapses all rooms per user into ONE Hermes session: + # DM with andreas: room_id=ABC123 → chat_id="user:andreas" + # #BAT-Team: room_id=XYZ789 → chat_id="user:andreas" + # Both get the same session key: agent:main:rocketchat:dm:user:andreas + virtual_chat_id = f"user:{username}" + # Track the REAL room for send() to route the response back + _CURRENT_ORIGIN_ROOM.set(room_id) + + # Ensure this user→room mapping is recorded for proaktive sends + if virtual_chat_id not in self._user_rooms: + self._user_rooms[virtual_chat_id] = [] + if room_id not in self._user_rooms[virtual_chat_id]: + self._user_rooms[virtual_chat_id].append(room_id) + + # Dispatch to gateway handler via base-class handle_message + try: + from datetime import datetime + + message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT + source = SessionSource( + platform=Platform("rocketchat"), + chat_id=virtual_chat_id, # ← user-based instead of room-based + chat_name=f"{room_name} (via @{username})", # real origin visible in system prompt + user_id=username, + user_name=username, + chat_type="dm", # ← force DM to bypass group isolation in Core + ) + event = MessageEvent( + text=text, + message_type=message_type, + message_id=msg_id, + timestamp=datetime.fromtimestamp(time.time()), + raw_message=msg_obj, + ) + event.source = source + await self.handle_message(event) + except Exception as e: + logger.error("[rocketchat] handle_message error: %s", e) + + async def disconnect(self) -> None: + self._mark_disconnected() + self._shutdown_event.set() + if self._status_timer: + self._status_timer.cancel() + if self._listen_task and not self._listen_task.done(): + self._listen_task.cancel() + try: + await self._listen_task + except asyncio.CancelledError: + pass + if self.ddp: + self.ddp.disconnect() + self.ddp = None + logger.info("[rocketchat] Disconnected") + + async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None) -> SendResult: + if not self.rest.auth_token: + return SendResult(success=False, error="Not authenticated") + + # ── Option C: Virtual → Real Room Translation ───────────────── + # chat_id from Hermes session is virtual (e.g. "user:andreas"). + # We must resolve it to a real Rocket.Chat room_id for REST API. + real_room_id = chat_id + if chat_id.startswith("user:"): + # Priority 1: ContextVar from the message that triggered this turn + origin = _CURRENT_ORIGIN_ROOM.get() + if origin: + real_room_id = origin + logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) + else: + # Priority 2: proaktive Nachricht — use most recent room for this user + rooms = self._user_rooms.get(chat_id, []) + if rooms: + real_room_id = rooms[-1] # last room user was active in + logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) + else: + logger.error("[rocketchat] No real room for %s, cannot send", chat_id) + return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") + + # ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ── + # This allows the agent to request buttons by embedding markup in its + # response text, without requiring the gateway to pass metadata. + # Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]] + # [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]] + _btn_re = re.compile( + r'\[\[BUTTONS:(?P