Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a614071ac4 | |||
| 198487bfc7 | |||
| 72e748f4e7 | |||
| d14ee2d069 | |||
| 5994024d7d | |||
| cb9e913cf5 | |||
| c755d88a90 | |||
| 369f617bdf | |||
| 923c76a6be | |||
| 7872d4a47f |
+22
-5
@@ -23,9 +23,12 @@
|
|||||||
|
|
||||||
Dieses Plugin verwandelt Hermes Agent in einen **nativen Rocket.Chat-Benutzer** — mit Echtzeit-Nachrichten über das Hermes Gateway, Präsenz-Status und interaktiven Buttons.
|
Dieses Plugin verwandelt Hermes Agent in einen **nativen Rocket.Chat-Benutzer** — mit Echtzeit-Nachrichten über das Hermes Gateway, Präsenz-Status und interaktiven Buttons.
|
||||||
|
|
||||||
|
**Das Besondere:** Ein einziger Agent kann in beliebig vielen Räumen gleichzeitig präsent sein — Kanäle, Gruppen, DMs — und behält trotzdem den Überblick. Inhalte landen automatisch im richtigen Raum, Themen bleiben sauber getrennt, und nichts geht im Multi-Room-Chaos unter.
|
||||||
|
|
||||||
- **Eingehend**: WebSocket/DDP (`stream-room-messages`) für sofortige Nachrichten
|
- **Eingehend**: WebSocket/DDP (`stream-room-messages`) für sofortige Nachrichten
|
||||||
- **Ausgehend**: REST-API für Antworten, Buttons, Dateien
|
- **Ausgehend**: REST-API für Antworten, Buttons, Dateien
|
||||||
- **Gateway-nativ**: Registriert sich als `rocketchat-platform` im Hermes Gateway — kein Standalone-Daemon mehr
|
- **Gateway-nativ**: Registriert sich als `rocketchat-platform` im Hermes Gateway — kein Standalone-Daemon mehr
|
||||||
|
- **Multi-Room-fähig**: Ein Agent-Session für alle Räume mit geteiltem Kontext
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -35,11 +38,13 @@ Dieses Plugin verwandelt Hermes Agent in einen **nativen Rocket.Chat-Benutzer**
|
|||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| 🚀 Echtzeit-Streaming | DDP/WebSocket für instant eingehende Nachrichten |
|
| 🚀 Echtzeit-Streaming | DDP/WebSocket für instant eingehende Nachrichten |
|
||||||
| 🟢 Präsenz | Grüner Online-Status im Rocket.Chat |
|
| 🟢 Präsenz | Grüner Online-Status im Rocket.Chat |
|
||||||
|
| 🌐 Multi-Room | Ein Agent über alle Räume — Kanäle, Gruppen, DMs. Geteilter Kontext, kein Kontext-Verlust beim Raumwechsel |
|
||||||
|
| 🧭 Smart Room Routing | Der Agent lernt beim ersten Start, welche Themen in welchen Raum gehören. Kein manuelles Konfigurieren — ein kurzes Interview, danach landet alles automatisch am richtigen Ort |
|
||||||
| ✍️ Markdown | Fett, kursiv, `Code`, Blöcke, Links |
|
| ✍️ Markdown | Fett, kursiv, `Code`, Blöcke, Links |
|
||||||
| 🔘 Interaktive Buttons | Ja/Nein, Bestätigen/Abbrechen, Mehrfachauswahl |
|
| 🔘 Interaktive Buttons | Ja/Nein, Bestätigen/Abbrechen, Mehrfachauswahl |
|
||||||
| 🔌 REST-Tools | `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send` |
|
| 🔌 7 REST-Tools | `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send`, `rocketchat_upload`, `rocketchat_download`, `rocketchat_files` |
|
||||||
| 📢 Räume | Kanäle, private Gruppen, Direktnachrichten |
|
| 📎 Datei-Anhänge | Upload, Download, Datei-Listing — nativ im Rocket.Chat gerendert |
|
||||||
| 🌍 Bilingual | Installer auf Deutsch & Englisch (`--lang de|en`) |
|
| 🌍 Bilingual | Installer auf Deutsch & Englisch (`--lang de|en`), Agent erkennt Systemsprache automatisch |
|
||||||
| 📦 Zero-Dependency | Nutzt ausschließlich Python-Standardbibliothek |
|
| 📦 Zero-Dependency | Nutzt ausschließlich Python-Standardbibliothek |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -99,7 +104,7 @@ Nach der Installation gibt der Gateway einen **Pairing-Code** aus. Diesen im Hom
|
|||||||
|-------|-------|----------|
|
|-------|-------|----------|
|
||||||
| `plugin/adapter.py` | ~27 KB | DDP-Client, Session-Handling, Nachrichten-Parsing, Reconnect, Button-Rendering |
|
| `plugin/adapter.py` | ~27 KB | DDP-Client, Session-Handling, Nachrichten-Parsing, Reconnect, Button-Rendering |
|
||||||
| `plugin/__init__.py` | ~4,5 KB | Plugin-Registrierung, Interaction Templates |
|
| `plugin/__init__.py` | ~4,5 KB | Plugin-Registrierung, Interaction Templates |
|
||||||
| `plugin/tools.py` | ~32 KB | 4 Rocket.Chat REST-Tools für Agent-Kontext |
|
| `plugin/tools.py` | ~43 KB | 7 Rocket.Chat REST-Tools für Agent-Kontext |
|
||||||
| `plugin/plugin.yaml` | 0,8 KB | Metadaten, Env-Vars |
|
| `plugin/plugin.yaml` | 0,8 KB | Metadaten, Env-Vars |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -162,7 +167,7 @@ GATEWAY_ALLOW_ALL_USERS=true
|
|||||||
|
|
||||||
## Aktueller Status
|
## Aktueller Status
|
||||||
|
|
||||||
- **Version**: 2.0.0
|
- **Version**: 2.3.0
|
||||||
- **Stabilität**: Produktiv im Einsatz (seit Mai 2026)
|
- **Stabilität**: Produktiv im Einsatz (seit Mai 2026)
|
||||||
- **Getestet mit**: Rocket.Chat v5.x, Hermes Agent Gateway
|
- **Getestet mit**: Rocket.Chat v5.x, Hermes Agent Gateway
|
||||||
- **Lizenz**: [Unlicense](LICENSE) — Public Domain
|
- **Lizenz**: [Unlicense](LICENSE) — Public Domain
|
||||||
@@ -171,6 +176,18 @@ GATEWAY_ALLOW_ALL_USERS=true
|
|||||||
|
|
||||||
## Changelog
|
## Changelog
|
||||||
|
|
||||||
|
### v2.3.0 (30. Mai 2026)
|
||||||
|
- **Attachment-Tools:** `rocketchat_upload`, `rocketchat_download`, `rocketchat_files`
|
||||||
|
- **Upload-Fix:** 2-Step-Flow für RC 8.4.1 — `rooms.media` + `chat.postMessage` mit `title_link`
|
||||||
|
- **DDP-Adapter:** Erkennt eingehende Attachments automatisch (`file`/`attachments` im Event)
|
||||||
|
|
||||||
|
### v2.2.0 (30. Mai 2026)
|
||||||
|
- **Room Topic Discipline:** Agent trennt Inhalte strikt nach Raum-Thema
|
||||||
|
- **Catch-All-Raum:** Interaktive Erstinitialisierung bei >1 Raum
|
||||||
|
|
||||||
|
### v2.1.0 (29. Mai 2026)
|
||||||
|
- **Cross-Room Session Sharing:** Ein Agent über alle Räume, gemeinsamer Kontext. Zero Core Changes — rein plugin-basiert
|
||||||
|
|
||||||
### v2.0.0 (Mai 2026)
|
### v2.0.0 (Mai 2026)
|
||||||
- Gateway-natives Plugin (kein Standalone-Daemon mehr)
|
- Gateway-natives Plugin (kein Standalone-Daemon mehr)
|
||||||
- `tools.py`: 4 Rocket.Chat REST-Tools für Agent-Kontext
|
- `tools.py`: 4 Rocket.Chat REST-Tools für Agent-Kontext
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ This plugin is maintained independently. Use at your own risk. See [LICENSE](LIC
|
|||||||
|
|
||||||
- 🟢 **Real-time messaging** via DDP/WebSocket (`stream-room-messages`)
|
- 🟢 **Real-time messaging** via DDP/WebSocket (`stream-room-messages`)
|
||||||
- 💬 **Interactive buttons** — Native Rocket.Chat attachments with `question_id::choice` correlation
|
- 💬 **Interactive buttons** — Native Rocket.Chat attachments with `question_id::choice` correlation
|
||||||
- 🔌 **4 REST tools** — `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send`
|
- 🔌 **7 REST tools** — `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send`, `rocketchat_upload`, `rocketchat_download`, `rocketchat_files`
|
||||||
|
- 🧭 **Smart Room Routing** — Automatically learns which topics belong in which rooms. Keeps conversations organized across channels, groups, and DMs. One agent, many rooms, zero confusion.
|
||||||
|
- 📎 **File Attachments** — Upload, download, and list files with native Rocket.Chat rendering
|
||||||
|
- 🌐 **Multi-Room Presence** — One agent session across all rooms. Shared context, clean delivery.
|
||||||
- 🟢 **Online presence** — Green dot via DDP `UserPresence`
|
- 🟢 **Online presence** — Green dot via DDP `UserPresence`
|
||||||
- ♻️ **Auto-reconnect** with exponential backoff
|
- ♻️ **Auto-reconnect** with exponential backoff
|
||||||
- 🌍 **Bilingual installer** — German & English (`--lang de|en`)
|
- 🌍 **Bilingual installer** — German & English (`--lang de|en`)
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# Option C: Cross-Room Session Sharing
|
||||||
|
|
||||||
|
> Implementiert 28.05.2026 | Commit: `0972f19`
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Andreas' DM und der
|
||||||
|
#BAT-Team-Raum hatten zwei unabhängige Bernd-Instanzen — doppeltes
|
||||||
|
Informations-Management, kein gemeinsamer Kontext.
|
||||||
|
|
||||||
|
## Lösung: Virtuelle Raum-Übersetzung (Plugin-only)
|
||||||
|
|
||||||
|
Der Adapter übersetzt transparent zwischen Rocket.Chat-Räumen und
|
||||||
|
user-basierten virtuellen Chat-IDs. Keine Hermes-Core-Änderungen.
|
||||||
|
|
||||||
|
### Datenfluss
|
||||||
|
|
||||||
|
```
|
||||||
|
EINGANG: RC-Raum (DM / #BAT-Team)
|
||||||
|
↓
|
||||||
|
_adapter._process_incoming():
|
||||||
|
room_id → user:<username> als chat_id
|
||||||
|
ContextVar merkt echten room_id
|
||||||
|
chat_type=dm (umgeht group isolation in Core)
|
||||||
|
↓
|
||||||
|
Hermes Core: build_session_key()
|
||||||
|
→ agent:main:rocketchat:dm:user:andreas ← EIN Key für alle Räume!
|
||||||
|
↓
|
||||||
|
Agent antwortet mit chat_id="user:andreas"
|
||||||
|
↓
|
||||||
|
_adapter.send():
|
||||||
|
ContextVar lesen → echter room_id
|
||||||
|
→ REST API an richtigen Raum
|
||||||
|
```
|
||||||
|
|
||||||
|
### Technische Details
|
||||||
|
|
||||||
|
- **ContextVar** `_CURRENT_ORIGIN_ROOM`: Thread-safe, async-safe Rückkanal
|
||||||
|
- **User-Room-Map** `_user_rooms: Dict[str, List[str]]`: Fallback für proaktive Nachrichten
|
||||||
|
(wenn kein ContextVar gesetzt ist — z.B. Cron-Jobs)
|
||||||
|
- **Clarify-Queue**: `_pending_clarifies` verwendet echten `room_id` (Korrelation
|
||||||
|
Button-Click → Frage funktioniert weiter)
|
||||||
|
|
||||||
|
### Edge Cases
|
||||||
|
|
||||||
|
| Szenario | Behandlung |
|
||||||
|
|---|---|
|
||||||
|
| Antwort auf eingehende Nachricht | ContextVar → präzises Routing |
|
||||||
|
| Proaktive Nachricht (Cron) | User-Map → letzter aktiver Raum |
|
||||||
|
| Button-Click (Clarify) | reale room_id in _pending_clarifies |
|
||||||
|
| Gateway-Neustart | User-Map wird in connect() neu aufgebaut |
|
||||||
|
|
||||||
|
## Keine Risiken bei Hermes-Updates
|
||||||
|
|
||||||
|
Alle Änderungen sind im Plugin-Adapter — Null Core-Änderungen.
|
||||||
|
Hermes-Updates überschreiben den Adapter nicht, solange das Plugin
|
||||||
|
installiert ist.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Rainer Review: Room Topic Discipline
|
||||||
|
|
||||||
|
**Datum:** 31. Mai 2026
|
||||||
|
**Review-Gegenstand:** Skill `rocket-chat` — neue Sektion "Room Topic Discipline" + `references/room-topic-map.md`
|
||||||
|
**Reviewer:** Rainer (Architekt)
|
||||||
|
**Auftraggeber:** Andreas
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Review-Ergebnis
|
||||||
|
|
||||||
|
| Kriterium | Bewertung | Anmerkung |
|
||||||
|
|---|---|---|
|
||||||
|
| **F1 — Architektur-Konsistenz** | ✅ Bestanden | Rein dokumentarische Skill-Änderung. Kein Eingriff in Adapter/Plugin-Logik. Kein neuer Code. |
|
||||||
|
| **F2 — Vollständigkeit** | ✅ Bestanden | Alle Pfade abgedeckt: 1 Raum, 2+ Räume, bestehende Map, neue Map, Catch-All, virtuelle Keys, Override. Entscheidungsbaum lückenlos. |
|
||||||
|
| **F3 — Sprachunabhängigkeit** | ✅ Bestanden | `$LANG`-basiert. `de_DE`/`de` → Deutsch, sonst Englisch. Bilinguale Texte. Kein Hardcode. |
|
||||||
|
| **F4 — Sicherheit** | ✅ Bestanden | Keine Sicherheitsimplikationen. Rein verhaltenssteuernd. |
|
||||||
|
| **F5 — Dokumentation** | ✅ Bestanden | Skill bilingual dokumentiert. Map als Referenzdatei. Trigger im Plugin-Lifecycle verankert. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architektur-Entscheidung: Trigger
|
||||||
|
|
||||||
|
**Problem:** Skill beschreibt WAS der Agent tun soll, aber nicht WANN.
|
||||||
|
|
||||||
|
**Lösung:** Trigger ist im Plugin-Lifecycle verankert — nach `Adapter.connect()`, sobald Räume subscribed sind. Der Skill dokumentiert diesen Trigger als bilingualen Header. Kein Memory-Hack, kein manueller Check nötig.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Update (31. Mai 2026, nach Andreas-Korrektur)
|
||||||
|
|
||||||
|
**Finding:** Virtuelle Keys waren als "niemals Catch-All" markiert, aber nicht als "nie in der Raumliste zeigen, nie abfragen". Ein Catch-All auf dem Multi-Raum-Präsenz-Key würde in ALLE Räume broadcasten und die gesamte Thementrennung aushebeln.
|
||||||
|
|
||||||
|
**Fix:** Beide Stellen im Skill geschärft. Virtuelle Keys werden jetzt explizit von der Raumliste ausgeschlossen und nie Teil der interaktiven Map-Anlage.
|
||||||
|
|
||||||
|
**Ergebnis:** F1-F5 weiterhin bestanden. Schärfung ist rein dokumentarisch, keine Architektur-Änderung.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Room Topic Map — rocket.chat.thomander.de
|
||||||
|
|
||||||
|
**Stand:** 31. Mai 2026 (wiederhergestellt nach Server-Rollback)
|
||||||
|
**Catch-All:** DM andreas/Bernd (`69f4e777f06dba03be82dce7`)
|
||||||
|
|
||||||
|
## Gemappte Räume
|
||||||
|
|
||||||
|
| Raum | Typ | Thema |
|
||||||
|
|---|---|---|
|
||||||
|
| `#BAT-Team` | channel | BAT-Trading-Plattform (Docker-Stack, Commits, Agent-Health, Entwicklerteam) |
|
||||||
|
| `Rocketchat-Plugin` | group | Hermes Rocket.Chat Plugin (Gateway, Upload, Buttons, Adapter) |
|
||||||
|
| `Protonbridge-Plugin` | group | ProtonMail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
||||||
|
| `DM andreas/Bernd` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
||||||
|
| `DM mit Bernd, Thomas` | dm | 🔇 Inaktiv — nur bei expliziter Aufforderung |
|
||||||
|
| `DM mit Bernd, Susi` | dm | Bot-zu-Bot-Kommunikation & Training — NUR auf explizite Aufforderung des Auftraggebers. Niemals ungefragt nutzen. |
|
||||||
|
|
||||||
|
## Virtuelle Keys (keine echten Räume — IMMER herausfiltern)
|
||||||
|
|
||||||
|
- `user:bernd` — Option-C-Session-Key, kein Raum. Darf NICHT Catch-All werden.
|
||||||
|
|
||||||
|
## Override-Regel
|
||||||
|
|
||||||
|
Der Nutzer kann die Map jederzeit überschreiben: *„Antworte mir in Raum Y hierzu"* — dann gilt Raum Y für diese eine Antwort, unabhängig von der Map.
|
||||||
@@ -478,6 +478,47 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
user_info = msg_obj.get("u", {})
|
user_info = msg_obj.get("u", {})
|
||||||
username = (user_info.get("username", "") or "").lower() # normalize case
|
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)
|
# Skip own messages (case-insensitive comparison)
|
||||||
if username == (self.user or "").lower() or not text or not room_id:
|
if username == (self.user or "").lower() or not text or not room_id:
|
||||||
return
|
return
|
||||||
|
|||||||
+256
@@ -16,6 +16,7 @@ import os
|
|||||||
import time
|
import time
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
from tools.registry import tool_error, tool_result
|
from tools.registry import tool_error, tool_result
|
||||||
|
|
||||||
@@ -167,6 +168,95 @@ class RocketChatAPI:
|
|||||||
payload["attachments"] = attachments
|
payload["attachments"] = attachments
|
||||||
return self._request("POST", "/api/v1/chat.postMessage", payload) or {}
|
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
|
@classmethod
|
||||||
def login(cls, base_url: str, user: str, password: str) -> Optional["RocketChatAPI"]:
|
def login(cls, base_url: str, user: str, password: str) -> Optional["RocketChatAPI"]:
|
||||||
"""Authenticate and return an API client, or None if login fails."""
|
"""Authenticate and return an API client, or None if login fails."""
|
||||||
@@ -591,6 +681,115 @@ def _handle_rocketchat_send(args: dict, **kw) -> str:
|
|||||||
return tool_error(f"rocketchat_send failed: {type(exc).__name__}: {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)
|
# Tool schemas (OpenAI function-calling format)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -705,6 +904,60 @@ ROCKETCHAT_SEND_SCHEMA = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Registration helpers for the plugin register() function
|
# Registration helpers for the plugin register() function
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -714,6 +967,9 @@ _TOOLS = (
|
|||||||
("rocketchat_users", ROCKETCHAT_USERS_SCHEMA, _handle_rocketchat_users, "👤"),
|
("rocketchat_users", ROCKETCHAT_USERS_SCHEMA, _handle_rocketchat_users, "👤"),
|
||||||
("rocketchat_dm", ROCKETCHAT_DM_SCHEMA, _handle_rocketchat_dm, "💬"),
|
("rocketchat_dm", ROCKETCHAT_DM_SCHEMA, _handle_rocketchat_dm, "💬"),
|
||||||
("rocketchat_send", ROCKETCHAT_SEND_SCHEMA, _handle_rocketchat_send, "✉️"),
|
("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, "📁"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user