"""Rocket.Chat REST API tools for the Hermes Agent. Lightweight wrappers calling the Rocket.Chat REST API directly. Uses only stdlib (urllib) — no external dependencies. These tools are registered by the rocketchat-platform plugin and are available whenever ROCKETCHAT_BASE_URL, ROCKETCHAT_USER and ROCKETCHAT_PASSWORD are set in the environment. """ from __future__ import annotations import json import logging import os import time import urllib.request from typing import Any, Dict, List, Optional import urllib.parse # Inlined from tools.registry — avoids import conflict with the plugin's # own rc_tools.py module (which used to shadow the core tools/ package when # the plugin directory is on sys.path). def tool_error(message, **extra) -> str: result = {"error": str(message)} if extra: result.update(extra) return json.dumps(result, ensure_ascii=False) def tool_result(data=None, **kwargs) -> str: if data is not None: return json.dumps(data, ensure_ascii=False) return json.dumps(kwargs, ensure_ascii=False) logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Rocket.Chat REST API client (lightweight, stdlib-only) # --------------------------------------------------------------------------- class RocketChatAPI: """Thin REST client for Rocket.Chat stdlib only.""" def __init__(self, base_url: str, auth_token: str, user_id: str): self.base_url = base_url.rstrip("/") self.auth_token = auth_token self.user_id = user_id # -- internal helpers ---------------------------------------------------- def _request(self, method: str, endpoint: str, data: Optional[dict] = None) -> Optional[dict]: url = f"{self.base_url}{endpoint}" headers: Dict[str, str] = { "X-Auth-Token": self.auth_token, "X-User-Id": self.user_id, } body: Optional[bytes] = None if data is not None: headers["Content-Type"] = "application/json" body = json.dumps(data).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=30) as resp: return json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: msg = f"HTTP {exc.code} on {method} {endpoint}" try: detail = json.loads(exc.read().decode("utf-8")) msg += f": {detail}" except Exception: pass logger.debug("RocketChatAPI %s", msg) return {"success": False, "error": msg} except Exception as exc: logger.debug("RocketChatAPI request failed: %s", exc) return {"success": False, "error": str(exc)} # -- rooms --------------------------------------------------------------- def get_rooms(self) -> List[dict]: r = self._request("GET", "/api/v1/rooms.get") if r and r.get("success"): return r.get("update", []) return [] def get_channels(self) -> List[dict]: r = self._request("GET", "/api/v1/channels.list.joined") if r and r.get("success"): return r.get("channels", []) return [] def get_groups(self) -> List[dict]: r = self._request("GET", "/api/v1/groups.list") if r and r.get("success"): return r.get("groups", []) return [] def get_dm_rooms(self) -> List[dict]: r = self._request("GET", "/api/v1/im.list") if r and r.get("success"): return r.get("ims", []) return [] def create_channel(self, name: str, members: Optional[List[str]] = None) -> dict: payload: Dict[str, Any] = {"name": name} if members: payload["members"] = members return self._request("POST", "/api/v1/channels.create", payload) or {} def create_group(self, name: str, members: Optional[List[str]] = None) -> dict: payload: Dict[str, Any] = {"name": name} if members: payload["members"] = members return self._request("POST", "/api/v1/groups.create", payload) or {} def archive_room(self, room_id: str, room_type: str = "c") -> dict: if room_type == "c": return self._request("POST", "/api/v1/channels.archive", {"roomId": room_id}) or {} return self._request("POST", "/api/v1/groups.archive", {"roomId": room_id}) or {} def delete_room(self, room_id: str, room_type: str = "c") -> dict: if room_type == "c": return self._request("POST", "/api/v1/channels.delete", {"roomId": room_id}) or {} return self._request("POST", "/api/v1/groups.delete", {"roomId": room_id}) or {} def room_info(self, room_id: str, room_type: str = "c") -> dict: if room_type == "c": return self._request("GET", f"/api/v1/channels.info?roomId={room_id}") or {} if room_type == "p": return self._request("GET", f"/api/v1/groups.info?roomId={room_id}") or {} return self._request("GET", f"/api/v1/rooms.info?roomId={room_id}") or {} def room_history(self, room_id: str, count: int = 20) -> List[dict]: r = self._request("GET", f"/api/v1/channels.history?roomId={room_id}&count={count}") if r and r.get("success"): return r.get("messages", []) # Fallback for groups / DMs r2 = self._request("GET", f"/api/v1/groups.history?roomId={room_id}&count={count}") if r2 and r2.get("success"): return r2.get("messages", []) return [] def invite_user(self, room_id: str, user_id: str, room_type: str = "c") -> dict: if room_type == "c": return self._request("POST", "/api/v1/channels.invite", {"roomId": room_id, "userId": user_id}) or {} return self._request("POST", "/api/v1/groups.invite", {"roomId": room_id, "userId": user_id}) or {} def kick_user(self, room_id: str, user_id: str, room_type: str = "c") -> dict: if room_type == "c": return self._request("POST", "/api/v1/channels.kick", {"roomId": room_id, "userId": user_id}) or {} return self._request("POST", "/api/v1/groups.kick", {"roomId": room_id, "userId": user_id}) or {} # -- users --------------------------------------------------------------- def get_users(self, query: Optional[str] = None, count: int = 50) -> List[dict]: endpoint = f"/api/v1/users.list?count={count}" if query: endpoint += f"&query={{\"name\":{{\"$regex\":\"{query}\",\"$options\":\"i\"}}}}" r = self._request("GET", endpoint) if r and r.get("success"): return r.get("users", []) return [] def get_user_info(self, user_id: Optional[str] = None, username: Optional[str] = None) -> dict: if user_id: return self._request("GET", f"/api/v1/users.info?userId={user_id}") or {} if username: return self._request("GET", f"/api/v1/users.info?username={username}") or {} return {"success": False, "error": "Either user_id or username is required for users.info"} # -- direct messages ----------------------------------------------------- def create_dm(self, username: str) -> dict: return self._request("POST", "/api/v1/im.create", {"username": username}) or {} def send_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> dict: payload: Dict[str, Any] = {"roomId": room_id, "text": text} if attachments: payload["attachments"] = attachments return self._request("POST", "/api/v1/chat.postMessage", payload) or {} def download_file(self, file_id: str, filename: str) -> bytes: """Download a file from Rocket.Chat.""" url = f"{self.base_url}/file-upload/{file_id}/{filename}" headers: Dict[str, str] = { "X-Auth-Token": self.auth_token, "X-User-Id": self.user_id, } req = urllib.request.Request(url, headers=headers, method="GET") with urllib.request.urlopen(req, timeout=30) as resp: return resp.read() def get_room_files(self, room_id: str, count: int = 50, offset: int = 0) -> dict: """Get list of files in a room with pagination.""" endpoint = f"/api/v1/channels.files?roomId={room_id}&count={count}&offset={offset}" return self._request("GET", endpoint) or {} def upload_file(self, room_id: str, file_path: str, message: str = "", description: str = "") -> dict: """Upload a file to a Rocket.Chat room using multipart/form-data.""" import mimetypes if not os.path.exists(file_path): return {"success": False, "error": f"File not found: {file_path}"} content_type, _ = mimetypes.guess_type(file_path) if content_type is None: content_type = "application/octet-stream" boundary = "----HermesAgentUploadBoundary" body_parts: List[bytes] = [] with open(file_path, "rb") as f: file_data = f.read() filename = os.path.basename(file_path) # Add file field body_parts.append(f"--{boundary}\r\n".encode()) body_parts.append(f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'.encode()) body_parts.append(f"Content-Type: {content_type}\r\n\r\n".encode()) body_parts.append(file_data) body_parts.append(b"\r\n") if message: body_parts.append(f"--{boundary}\r\n".encode()) body_parts.append(b'Content-Disposition: form-data; name="msg"\r\n\r\n') body_parts.append(message.encode()) body_parts.append(b"\r\n") if description: body_parts.append(f"--{boundary}\r\n".encode()) body_parts.append(b'Content-Disposition: form-data; name="description"\r\n\r\n') body_parts.append(description.encode()) body_parts.append(b"\r\n") body_parts.append(f"--{boundary}--\r\n".encode()) body = b"".join(body_parts) url = f"{self.base_url}/api/v1/rooms.media/{room_id}" headers: Dict[str, str] = { "X-Auth-Token": self.auth_token, "X-User-Id": self.user_id, "Content-Type": f"multipart/form-data; boundary={boundary}", } req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=60) as resp: upload_result = json.loads(resp.read().decode("utf-8")) if not upload_result.get("success"): return upload_result # Step 2: Post message with the uploaded file as attachment file_info = upload_result.get("file") or {} file_id = file_info.get("_id") if file_id: attachment: dict = { "title": filename, "title_link": f"/file-upload/{file_id}/{filename}", "title_link_download": True, "type": "file", } if description: attachment["description"] = description post_result = self.send_message( room_id=room_id, text=message or "", attachments=[attachment], ) return {"success": True, "upload": upload_result, "post_message": post_result} return upload_result except urllib.error.HTTPError as exc: msg = f"Upload HTTP {exc.code}" try: detail = json.loads(exc.read().decode("utf-8")) msg += f": {detail}" except Exception: pass return {"success": False, "error": msg} except Exception as exc: return {"success": False, "error": str(exc)} @classmethod def login(cls, base_url: str, user: str, password: str) -> Optional["RocketChatAPI"]: """Authenticate and return an API client, or None if login fails.""" url = base_url.rstrip("/") req = urllib.request.Request( f"{url}/api/v1/login", data=json.dumps({"user": user, "password": password}).encode("utf-8"), headers={"Content-Type": "application/json"}, method="POST", ) try: with urllib.request.urlopen(req, timeout=30) as resp: data = json.loads(resp.read().decode("utf-8")) if data.get("status") == "success": return cls(url, data["data"]["authToken"], data["data"]["userId"]) except Exception: pass return None # --------------------------------------------------------------------------- # Module-level cached client (avoids re-auth on every tool call) # --------------------------------------------------------------------------- _cached_client: Optional[RocketChatAPI] = None _cached_login_ts: float = 0.0 _CACHE_TTL: float = 900.0 # 15 minutes def _rc_client() -> Optional[RocketChatAPI]: """Return a logged-in RocketChatAPI client, or None if not configured.""" global _cached_client, _cached_login_ts base_url = os.getenv("ROCKETCHAT_BASE_URL", "").strip() user = os.getenv("ROCKETCHAT_USER", "").strip() password = os.getenv("ROCKETCHAT_PASSWORD", "").strip() if not base_url or not user or not password: return None if _cached_client and (time.time() - _cached_login_ts) < _CACHE_TTL: return _cached_client client = RocketChatAPI.login(base_url, user, password) if client: _cached_client = client _cached_login_ts = time.time() return client def _rc_error() -> str: return tool_error( "Rocket.Chat is not configured. Set ROCKETCHAT_BASE_URL, " "ROCKETCHAT_USER and ROCKETCHAT_PASSWORD in your environment." ) def _normalize_room(room_raw: dict) -> dict: """Normalize heterogeneous Rocket.Chat room objects to a common schema.""" t = room_raw.get("t", "c") rid = room_raw.get("_id", "") if t == "d": usernames = room_raw.get("usernames", []) bot_user = os.getenv("ROCKETCHAT_USER", "") other = [u for u in usernames if u != bot_user] name = "DM mit " + (", ".join(other[:3]) if other else "unbekannt") else: name = room_raw.get("name", "") return { "id": rid, "name": name, "type": t, "fname": room_raw.get("fname", ""), "num_msgs": room_raw.get("msgs", 0), "num_users": room_raw.get("usersCount", 0), "readonly": room_raw.get("ro", False), "archived": room_raw.get("archived", False), "is_default": room_raw.get("default", False), } # --------------------------------------------------------------------------- # Tool handlers # --------------------------------------------------------------------------- def _handle_rocketchat_rooms(args: dict, **kw) -> str: action = str(args.get("action") or "").strip().lower() client = _rc_client() if not client: return _rc_error() try: if action == "list": room_type = str(args.get("room_type") or "all").strip().lower() all_rooms: List[dict] = [] if room_type in ("all", "channel", "c"): all_rooms.extend(client.get_channels()) if room_type in ("all", "group", "p"): all_rooms.extend(client.get_groups()) if room_type in ("all", "dm", "d"): all_rooms.extend(client.get_dm_rooms()) return tool_result({ "success": True, "action": action, "room_type": room_type, "count": len(all_rooms), "rooms": [_normalize_room(r) for r in all_rooms], }) if action == "create": name = str(args.get("name") or "").strip() if not name: return tool_error("name is required for action='create'") members = args.get("members") if isinstance(members, str): members = [m.strip() for m in members.split(",") if m.strip()] room_type = str(args.get("room_type") or "channel").strip().lower() if room_type in ("group", "p"): result = client.create_group(name, members=members) else: result = client.create_channel(name, members=members) return tool_result({"success": result.get("success", False), "action": action, "result": result}) if action == "info": room_id = str(args.get("room_id") or "").strip() if not room_id: return tool_error("room_id is required for action='info'") room_type = str(args.get("room_type") or "c").strip().lower() result = client.room_info(room_id, room_type) return tool_result({"success": result.get("success", False), "action": action, "data": result.get("channel") or result.get("group") or result.get("room")}) if action == "history": room_id = str(args.get("room_id") or "").strip() if not room_id: return tool_error("room_id is required for action='history'") count = int(args.get("count", 20)) msgs = client.room_history(room_id, count=count) return tool_result({"success": True, "action": action, "count": len(msgs), "messages": msgs}) if action == "archive": room_id = str(args.get("room_id") or "").strip() if not room_id: return tool_error("room_id is required for action='archive'") room_type = str(args.get("room_type") or "c").strip().lower() result = client.archive_room(room_id, room_type) return tool_result({"success": result.get("success", False), "action": action}) if action == "delete": room_id = str(args.get("room_id") or "").strip() if not room_id: return tool_error("room_id is required for action='delete'") room_type = str(args.get("room_type") or "c").strip().lower() result = client.delete_room(room_id, room_type) return tool_result({"success": result.get("success", False), "action": action}) if action == "invite": room_id = str(args.get("room_id") or "").strip() username = str(args.get("username") or "").strip() if not room_id or not username: return tool_error("room_id and username are required for action='invite'") # Resolve username -> user_id user_info = client.get_user_info(username=username) user_id = user_info.get("user", {}).get("_id") if user_info.get("success") else None if not user_id: return tool_error(f"Could not resolve username '{username}' to a user ID.") room_type = str(args.get("room_type") or "c").strip().lower() result = client.invite_user(room_id, user_id, room_type) return tool_result({"success": result.get("success", False), "action": action}) if action == "kick": room_id = str(args.get("room_id") or "").strip() username = str(args.get("username") or "").strip() if not room_id or not username: return tool_error("room_id and username are required for action='kick'") user_info = client.get_user_info(username=username) user_id = user_info.get("user", {}).get("_id") if user_info.get("success") else None if not user_id: return tool_error(f"Could not resolve username '{username}' to a user ID.") room_type = str(args.get("room_type") or "c").strip().lower() result = client.kick_user(room_id, user_id, room_type) return tool_result({"success": result.get("success", False), "action": action}) return tool_error(f"Unknown rocketchat_rooms action: {action}") except Exception as exc: return tool_error(f"rocketchat_rooms failed: {type(exc).__name__}: {exc}") def _handle_rocketchat_users(args: dict, **kw) -> str: action = str(args.get("action") or "").strip().lower() client = _rc_client() if not client: return _rc_error() try: if action == "list": query = str(args.get("query") or "").strip() or None count = int(args.get("count", 50)) users = client.get_users(query=query, count=count) return tool_result({ "success": True, "action": action, "count": len(users), "users": [ { "id": u.get("_id"), "username": u.get("username"), "name": u.get("name"), "status": u.get("status"), "email": (u.get("emails") or [{}])[0].get("address"), "active": u.get("active"), "roles": u.get("roles", []), } for u in users ], }) if action == "info": user_id = str(args.get("user_id") or "").strip() or None username = str(args.get("username") or "").strip() or None if not user_id and not username: return tool_error("user_id or username is required for action='info'") result = client.get_user_info(user_id=user_id, username=username) user = result.get("user", {}) if result.get("success") else {} return tool_result({ "success": result.get("success", False), "action": action, "user": { "id": user.get("_id"), "username": user.get("username"), "name": user.get("name"), "status": user.get("status"), "statusConnection": user.get("statusConnection"), "email": (user.get("emails") or [{}])[0].get("address"), "roles": user.get("roles", []), "active": user.get("active"), "utcOffset": user.get("utcOffset"), "avatarUrl": user.get("avatarUrl"), } if user else None, }) if action == "search": query = str(args.get("query") or "").strip() if not query: return tool_error("query is required for action='search'") count = int(args.get("count", 20)) users = client.get_users(query=query, count=count) return tool_result({ "success": True, "action": action, "query": query, "count": len(users), "users": [ { "id": u.get("_id"), "username": u.get("username"), "name": u.get("name"), "status": u.get("status"), } for u in users ], }) return tool_error(f"Unknown rocketchat_users action: {action}") except Exception as exc: return tool_error(f"rocketchat_users failed: {type(exc).__name__}: {exc}") def _handle_rocketchat_dm(args: dict, **kw) -> str: action = str(args.get("action") or "").strip().lower() client = _rc_client() if not client: return _rc_error() try: if action == "open": username = str(args.get("username") or "").strip() if not username: return tool_error("username is required for action='open'") result = client.create_dm(username) room = result.get("room", {}) if result.get("success") else {} return tool_result({ "success": result.get("success", False), "action": action, "room_id": room.get("_id"), "room": _normalize_room(room) if room else None, }) if action == "send": username = str(args.get("username") or "").strip() user_id = str(args.get("user_id") or "").strip() or None text = str(args.get("text") or "").strip() if not text: return tool_error("text is required for action='send'") # Need a room_id. If user_id or username provided, create/open DM first. room_id = str(args.get("room_id") or "").strip() or None if not room_id: if username: dm_result = client.create_dm(username) if dm_result.get("success"): room_id = dm_result.get("room", {}).get("_id") elif user_id: # Try looking up user info and creating DM by username uinfo = client.get_user_info(user_id=user_id) uname = uinfo.get("user", {}).get("username") if uinfo.get("success") else None if uname: dm_result = client.create_dm(uname) if dm_result.get("success"): room_id = dm_result.get("room", {}).get("_id") if not room_id: return tool_error("Could not resolve room_id for DM. Provide room_id, username, or user_id.") result = client.send_message(room_id, text) return tool_result({"success": result.get("success", False), "action": action, "result": result}) if action == "list": dms = client.get_dm_rooms() return tool_result({ "success": True, "action": action, "count": len(dms), "rooms": [_normalize_room(r) for r in dms], }) return tool_error(f"Unknown rocketchat_dm action: {action}") except Exception as exc: return tool_error(f"rocketchat_dm failed: {type(exc).__name__}: {exc}") def _handle_rocketchat_send(args: dict, **kw) -> str: """Send a message (with optional native Rocket.Chat attachments/buttons).""" client = _rc_client() if not client: return _rc_error() room_id = str(args.get("room_id") or "").strip() text = str(args.get("text") or "").strip() if not room_id or not text: return tool_error("room_id and text are required for rocketchat_send") # Build attachments if button template requested attachments: Optional[List[dict]] = None template = str(args.get("button_template") or "none").strip().lower() if template and template != "none": # Replicate templates locally to avoid circular import from __init__.py _TMPL_MAP = { "yes_no": { "attachment": {"color": "#1d74f5", "title": "Bitte bestätigen:"}, "buttons": [ {"text": "✅ Ja", "msg": "ja", "style": "primary"}, {"text": "❌ Nein", "msg": "nein", "style": "danger"}, ], }, "confirm_cancel": { "attachment": {"color": "#1d74f5", "title": "Aktion bestätigen:"}, "buttons": [ {"text": "✅ Bestätigen", "msg": "bestätigen", "style": "primary"}, {"text": "🚫 Abbrechen", "msg": "abbrechen", "style": "danger"}, ], }, "ok": { "attachment": {"color": "#1d74f5", "title": "Hinweis:"}, "buttons": [ {"text": "👍 OK", "msg": "ok", "style": "primary"}, ], }, "multi_choice_3": { "attachment": {"color": "#1d74f5", "title": "Wähle eine Option:"}, "buttons": [ {"text": "1._Links", "msg": "links", "style": "default"}, {"text": "2._Rechts", "msg": "rechts", "style": "default"}, {"text": "3._Zwei_Runden", "msg": "zwei_runden", "style": "default"}, ], }, } def _build_buttons(labels: list, prefix: str = "") -> list: buttons = [] for label in labels: display = str(label).strip() msg_payload = display if prefix: msg_payload = f"{prefix}::{msg_payload}" buttons.append({ "type": "button", "text": display, "msg": msg_payload, "msg_in_chat_window": True, "style": "default", }) return buttons question_id = str(args.get("question_id") or "").strip() if template == "custom" and args.get("custom_buttons"): labels = args["custom_buttons"] if isinstance(labels, str): labels = [l.strip() for l in labels.split(",") if l.strip()] buttons = _build_buttons(labels, prefix=question_id) attachments = [{ "color": "#1d74f5", "title": str(args.get("button_title") or "Wähle eine Option:"), "actions": buttons, }] elif template in _TMPL_MAP: tmpl = _TMPL_MAP[template] raw_buttons = tmpl.get("buttons", []) buttons = [] for btn in raw_buttons: msg_payload = btn.get("msg", "") if question_id: msg_payload = f"{question_id}::{msg_payload}" buttons.append({ "type": "button", "text": btn.get("text", "?"), "msg": msg_payload, "msg_in_chat_window": True, "style": btn.get("style", "default"), }) attachment = dict(tmpl.get("attachment", {})) attachment["actions"] = buttons attachments = [attachment] try: result = client.send_message(room_id, text, attachments=attachments) return tool_result({"success": result.get("success", False), "result": result}) except Exception as exc: return tool_error(f"rocketchat_send failed: {type(exc).__name__}: {exc}") def _handle_rocketchat_upload(args: dict, **kw) -> str: """Upload a file to a Rocket.Chat room.""" client = _rc_client() if not client: return _rc_error() room_id = str(args.get("room_id") or "").strip() file_path = str(args.get("file_path") or "").strip() message = str(args.get("message") or "").strip() description = str(args.get("description") or "").strip() if not room_id or not file_path: return tool_error("room_id and file_path are required for rocketchat_upload") # RocketChatAPI.upload_file() already handles rooms.media + chat.postMessage try: result = client.upload_file(room_id, file_path, message, description) return tool_result(result) except Exception as exc: return tool_error(f"rocketchat_upload failed: {type(exc).__name__}: {exc}") def _handle_rocketchat_download(args: dict, **kw) -> str: """Download a file from Rocket.Chat and save it locally.""" client = _rc_client() if not client: return _rc_error() file_id = str(args.get("file_id") or "").strip() filename = str(args.get("filename") or "").strip() if not file_id or not filename: return tool_error("file_id and filename are required for rocketchat_download") try: # Download the file file_content = client.download_file(file_id, filename) # Create download directory if it doesn't exist download_dir = os.path.expanduser("~/.hermes/cache/downloads") os.makedirs(download_dir, exist_ok=True) # Save file locally file_path = os.path.join(download_dir, filename) with open(file_path, "wb") as f: f.write(file_content) return tool_result({ "success": True, "file_id": file_id, "filename": filename, "saved_path": file_path, "size": len(file_content) }) except Exception as exc: return tool_error(f"rocketchat_download failed: {type(exc).__name__}: {exc}") def _handle_rocketchat_files(args: dict, **kw) -> str: """List files in a Rocket.Chat room with pagination.""" client = _rc_client() if not client: return _rc_error() room_id = str(args.get("room_id") or "").strip() if not room_id: return tool_error("room_id is required for rocketchat_files") try: count = int(args.get("count", 50)) offset = int(args.get("offset", 0)) # Get files from the room result = client.get_room_files(room_id, count=count, offset=offset) if not result.get("success"): return tool_error(f"Failed to retrieve files: {result.get('error', 'Unknown error')}") files = result.get("files", []) # Normalize file information normalized_files = [] for file_info in files: normalized_files.append({ "_id": file_info.get("_id"), "name": file_info.get("name"), "type": file_info.get("type"), "size": file_info.get("size"), "uploadedAt": file_info.get("uploadedAt"), "url": file_info.get("url"), "user": { "_id": file_info.get("user", {}).get("_id"), "username": file_info.get("user", {}).get("username"), "name": file_info.get("user", {}).get("name") } if file_info.get("user") else None }) return tool_result({ "success": True, "room_id": room_id, "count": len(normalized_files), "files": normalized_files, "offset": offset, "total": result.get("total", 0) }) except Exception as exc: return tool_error(f"rocketchat_files failed: {type(exc).__name__}: {exc}") # --------------------------------------------------------------------------- # Tool schemas (OpenAI function-calling format) # --------------------------------------------------------------------------- _COMMON_STRING = {"type": "string"} ROCKETCHAT_ROOMS_SCHEMA = { "name": "rocketchat_rooms", "description": ( "Manage Rocket.Chat rooms (channels, private groups, DMs): list, create, " "archive, delete, inspect room info, fetch history, invite or kick users." ), "parameters": { "type": "object", "properties": { "action": { "type": "string", "enum": ["list", "create", "info", "history", "archive", "delete", "invite", "kick"], "description": "Operation to perform on the room(s)", }, "room_type": { "type": "string", "enum": ["channel", "group", "dm", "all"], "description": "For list: filter by room type (default: all)", }, "name": {"type": "string", "description": "Room name (required for create)"}, "room_id": {"type": "string", "description": "Room ID (required for info, history, archive, delete, invite, kick)"}, "members": {"type": "array", "items": _COMMON_STRING, "description": "Usernames to invite during room creation"}, "username": {"type": "string", "description": "Username to invite or kick from a room"}, "count": {"type": "integer", "description": "Number of history messages to fetch (default: 20)"}, }, "required": ["action"], }, } ROCKETCHAT_USERS_SCHEMA = { "name": "rocketchat_users", "description": ( "Query Rocket.Chat users: list all, get detailed user info by ID or username, " "or search by name/username." ), "parameters": { "type": "object", "properties": { "action": { "type": "string", "enum": ["list", "info", "search"], "description": "Operation", }, "user_id": {"type": "string", "description": "User ID (for info)"}, "username": {"type": "string", "description": "Username (for info or as alternative target for dm/open)"}, "query": {"type": "string", "description": "Search term (for search/list)"}, "count": {"type": "integer", "description": "Maximum results to return (default: 50 for list, 20 for search)"}, }, "required": ["action"], }, } ROCKETCHAT_DM_SCHEMA = { "name": "rocketchat_dm", "description": ( "Open or send direct messages on Rocket.Chat. Use 'open' to create/lookup a DM room, " "'send' to send text to a DM (by room_id, username, or user_id), 'list' to list DMs." ), "parameters": { "type": "object", "properties": { "action": { "type": "string", "enum": ["open", "send", "list"], "description": "Operation", }, "username": {"type": "string", "description": "Username of the DM partner"}, "user_id": {"type": "string", "description": "User ID of the DM partner (alternative to username)"}, "room_id": {"type": "string", "description": "DM room ID (for send)"}, "text": {"type": "string", "description": "Message text (required for send)"}, }, "required": ["action"], }, } ROCKETCHAT_SEND_SCHEMA = { "name": "rocketchat_send", "description": ( "Send a message to a Rocket.Chat room or DM with optional interactive buttons. " "Use button_template to attach native Rocket.Chat action buttons: 'yes_no', " "'confirm_cancel', 'ok', 'multi_choice_3', or 'custom'. When template='custom', " "provide custom_buttons as an array of short labels (≤10 chars, no spaces — e.g. " "'✅Ja', '❌Nein'). Always provide a unique question_id so the user's click can " "be correlated." ), "parameters": { "type": "object", "properties": { "room_id": {"type": "string", "description": "Target room ID or DM room ID"}, "text": {"type": "string", "description": "Message body text"}, "button_template": { "type": "string", "enum": ["yes_no", "confirm_cancel", "ok", "multi_choice_3", "custom", "none"], "description": "Built-in button template (or 'none' for plain text)", }, "question_id": {"type": "string", "description": "Unique ID for button tracking (e.g. 'freigabe_42')"}, "custom_buttons": { "type": "array", "items": _COMMON_STRING, "description": "Custom button labels, max 3-4 items, short (≤10 chars, no spaces)", }, "button_title": {"type": "string", "description": "Title above the button group"}, }, "required": ["room_id", "text"], }, } ROCKETCHAT_DOWNLOAD_SCHEMA = { "name": "rocketchat_download", "description": ( "Download a file from Rocket.Chat by file ID and filename. " "The file will be saved to ~/.hermes/cache/downloads/ and the local path will be returned." ), "parameters": { "type": "object", "properties": { "file_id": {"type": "string", "description": "Rocket.Chat file ID"}, "filename": {"type": "string", "description": "Filename to save as"}, }, "required": ["file_id", "filename"], }, } ROCKETCHAT_UPLOAD_SCHEMA = { "name": "rocketchat_upload", "description": ( "Upload a file to a Rocket.Chat room with optional message and description. " "Uses multipart/form-data to upload files directly to the Rocket.Chat server." ), "parameters": { "type": "object", "properties": { "room_id": {"type": "string", "description": "Target room ID"}, "file_path": {"type": "string", "description": "Local path to the file to upload"}, "message": {"type": "string", "description": "Optional message to send with the file"}, "description": {"type": "string", "description": "Optional file description"}, }, "required": ["room_id", "file_path"], }, } ROCKETCHAT_FILES_SCHEMA = { "name": "rocketchat_files", "description": ( "List files in a Rocket.Chat room with pagination support. " "Returns structured information about files including ID, name, type, size, and upload date." ), "parameters": { "type": "object", "properties": { "room_id": {"type": "string", "description": "Room ID to list files from"}, "count": {"type": "integer", "description": "Number of files to retrieve (default: 50)"}, "offset": {"type": "integer", "description": "Offset for pagination (default: 0)"}, }, "required": ["room_id"], }, } # ── Proaktiver Raum-Broadcast (B6) ────────────────────────────────────── # Cooldown-Tracking: verhindert Spam bei vielen kleinen Aktionen. # Nur "Fertig"-Markierungen triggern einen Broadcast. _broadcast_cooldowns: Dict[str, float] = {} # room_id → timestamp _BROADCAST_COOLDOWN_SECONDS: float = 300.0 # 5 Minuten def _handle_rocketchat_broadcast(args: dict, **kw) -> str: """Sende einen proaktiven Status-Broadcast in einen Projektraum. Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' Cooldown: 5 Minuten pro Raum — verhindert Spam bei vielen kleinen Aktionen. Nur bei expliziten "Fertig"-Markierungen verwenden, nicht bei jeder kleinen Aktion. Args: room_id: Zielraum-ID (aus room-map.json oder ROCKETCHAT.MAP.md) text: Der Broadcast-Text (menschenähnlich, kein Bot-Ton) """ global _broadcast_cooldowns client = _rc_client() if not client: return _rc_error() room_id = str(args.get("room_id") or "").strip() text = str(args.get("text") or "").strip() if not room_id: return tool_error("room_id is required for rocketchat_broadcast") if not text: return tool_error("text is required for rocketchat_broadcast") # Cooldown-Check now = time.time() last = _broadcast_cooldowns.get(room_id, 0.0) if now - last < _BROADCAST_COOLDOWN_SECONDS: remaining = int(_BROADCAST_COOLDOWN_SECONDS - (now - last)) return tool_result({ "success": False, "cooldown": True, "message": f"Broadcast-Cooldown aktiv: noch {remaining}s für Raum {room_id[:8]}...", }) try: result = client.send_message(room_id, text) if result.get("success"): _broadcast_cooldowns[room_id] = now return tool_result({ "success": True, "room_id": room_id, "text": text[:200], }) else: return tool_error(f"Broadcast failed: {result.get('error', 'unknown error')}") except Exception as exc: return tool_error(f"rocketchat_broadcast failed: {type(exc).__name__}: {exc}") ROCKETCHAT_BROADCAST_SCHEMA = { "name": "rocketchat_broadcast", "description": ( "Send a proactive status broadcast to a project room. " "Use this after completing a task to inform the team. " "Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' " "Cooldown: 5 minutes per room to prevent spam. " "Only use for explicit 'done' markers, not for every small action." ), "parameters": { "type": "object", "properties": { "room_id": {"type": "string", "description": "Target project room ID (from room-map.json)"}, "text": {"type": "string", "description": "Broadcast message (human-like, not bot-like)"}, }, "required": ["room_id", "text"], }, } # --------------------------------------------------------------------------- # F169: rocketchat_reset_timeout — adaptiven LLM-Timeout auf Baseline zurücksetzen # --------------------------------------------------------------------------- def _handle_rocketchat_reset_timeout(args: dict, **kw) -> str: """F169: Setzt die adaptive LLM-Timeout-Kalibrierung auf Baseline zurück. @implements F-169 Setzt Welford-Statistik (Mittelwert + Varianz), Call-Counter und Eskalations-Stufe zurück. Der erste Call nach dem Reset kalibriert neu; bis genug Samples vorliegen, gilt wieder der Failsafe (30s). Nützlich vor Tests (z.B. F172 Human-Tempo-Pacing), damit die Kalibrierung nicht auf Bot-Tempo statt Mensch-Tempo läuft. """ try: from archivar.adaptive_timeout import adaptive_timeout except Exception as exc: return tool_error(f"adaptive_timeout nicht verfügbar: {type(exc).__name__}: {exc}") agent_name = str(args.get("agent_name") or "rocketchat_reset_timeout").strip() result = adaptive_timeout.reset_timeout(agent_name=agent_name) return tool_result({ "success": True, "message": "Adaptive timeout reset to baseline", "calls": result["calls"], "mean": result["mean"], "stddev": result["stddev"], "in_flight": result["in_flight"], }) ROCKETCHAT_RESET_TIMEOUT_SCHEMA = { "name": "rocketchat_reset_timeout", "description": ( "Reset the adaptive LLM timeout calibration to baseline (F169). " "Clears the Welford statistics (mean + variance), the call counter, " "and the escalation level. The first call after the reset recalibrates; " "until enough samples are collected, the failsafe (30s) applies. " "Use this before starting a test so the calibration reflects human " "tempo instead of bot tempo." ), "parameters": { "type": "object", "properties": { "agent_name": { "type": "string", "description": "Name of the agent triggering the reset (for logging).", }, }, "required": [], }, } # --------------------------------------------------------------------------- # Registration helpers for the plugin register() function # --------------------------------------------------------------------------- _TOOLS = ( ("rocketchat_rooms", ROCKETCHAT_ROOMS_SCHEMA, _handle_rocketchat_rooms, "🏢"), ("rocketchat_users", ROCKETCHAT_USERS_SCHEMA, _handle_rocketchat_users, "👤"), ("rocketchat_dm", ROCKETCHAT_DM_SCHEMA, _handle_rocketchat_dm, "💬"), ("rocketchat_send", ROCKETCHAT_SEND_SCHEMA, _handle_rocketchat_send, "✉️"), ("rocketchat_upload", ROCKETCHAT_UPLOAD_SCHEMA, _handle_rocketchat_upload, "📎"), ("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"), ("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"), ("rocketchat_broadcast", ROCKETCHAT_BROADCAST_SCHEMA, _handle_rocketchat_broadcast, "📢"), ("rocketchat_reset_timeout", ROCKETCHAT_RESET_TIMEOUT_SCHEMA, _handle_rocketchat_reset_timeout, "⏱️"), ) def check_rocketchat_tools_available() -> bool: """Return True if Rocket.Chat credentials are available in the environment.""" return bool( os.getenv("ROCKETCHAT_BASE_URL", "").strip() and os.getenv("ROCKETCHAT_USER", "").strip() and os.getenv("ROCKETCHAT_PASSWORD", "").strip() ) def register_tools(ctx) -> None: """Register all Rocket.Chat tools. Called by the platform plugin register().""" for name, schema, handler, emoji in _TOOLS: ctx.register_tool( name=name, toolset="rocketchat", schema=schema, handler=handler, check_fn=check_rocketchat_tools_available, emoji=emoji, )