Compare commits
11 Commits
0972f19d73
..
v2.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d65789295 | |||
| 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.
|
||||
|
||||
**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
|
||||
- **Ausgehend**: REST-API für Antworten, Buttons, Dateien
|
||||
- **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 |
|
||||
| 🟢 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 |
|
||||
| 🔘 Interaktive Buttons | Ja/Nein, Bestätigen/Abbrechen, Mehrfachauswahl |
|
||||
| 🔌 REST-Tools | `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send` |
|
||||
| 📢 Räume | Kanäle, private Gruppen, Direktnachrichten |
|
||||
| 🌍 Bilingual | Installer auf Deutsch & Englisch (`--lang de|en`) |
|
||||
| 🔌 7 REST-Tools | `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send`, `rocketchat_upload`, `rocketchat_download`, `rocketchat_files` |
|
||||
| 📎 Datei-Anhänge | Upload, Download, Datei-Listing — nativ im Rocket.Chat gerendert |
|
||||
| 🌍 Bilingual | Installer auf Deutsch & Englisch (`--lang de|en`), Agent erkennt Systemsprache automatisch |
|
||||
| 📦 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/__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 |
|
||||
|
||||
---
|
||||
@@ -162,7 +167,7 @@ GATEWAY_ALLOW_ALL_USERS=true
|
||||
|
||||
## Aktueller Status
|
||||
|
||||
- **Version**: 2.0.0
|
||||
- **Version**: 2.3.0
|
||||
- **Stabilität**: Produktiv im Einsatz (seit Mai 2026)
|
||||
- **Getestet mit**: Rocket.Chat v5.x, Hermes Agent Gateway
|
||||
- **Lizenz**: [Unlicense](LICENSE) — Public Domain
|
||||
@@ -171,6 +176,18 @@ GATEWAY_ALLOW_ALL_USERS=true
|
||||
|
||||
## 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)
|
||||
- Gateway-natives Plugin (kein Standalone-Daemon mehr)
|
||||
- `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`)
|
||||
- 💬 **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`
|
||||
- ♻️ **Auto-reconnect** with exponential backoff
|
||||
- 🌍 **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.
|
||||
Executable → Regular
+168
-3
@@ -9,6 +9,8 @@ set -euo pipefail
|
||||
LANG="${LANG:-de_DE.UTF-8}"
|
||||
ARG_LANG=""
|
||||
NONINTERACTIVE=false
|
||||
CHECK_ONLY=false
|
||||
UPDATE_MODE=false
|
||||
|
||||
# ─── Language packs ─────────────────────────────────────────
|
||||
declare -A T
|
||||
@@ -44,9 +46,18 @@ load_lang() {
|
||||
[restarting]="🔄 Restarting gateway…"
|
||||
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
|
||||
[dry_info]="ℹ️ Use --help for all options."
|
||||
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Check for updates only\n --update Check for updates and install if available"
|
||||
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||
[param_error]="❌ Unknown option: %s"
|
||||
[check_update]="🔍 Checking for updates…"
|
||||
[update_available]="📦 New version available: %s (current: %s)"
|
||||
[no_update]="✅ Plugin is up to date (%s)"
|
||||
[perform_update]="🔄 Updating plugin to version %s…"
|
||||
[backup_created]="💾 Backup created: %s"
|
||||
[update_success]="✅ Plugin successfully updated to version %s"
|
||||
[rollback]="⏪ Restoring backup: %s"
|
||||
[rollback_success]="✅ Backup successfully restored"
|
||||
[update_failed]="❌ Update failed. Error: %s"
|
||||
)
|
||||
else
|
||||
# German (default)
|
||||
@@ -71,9 +82,18 @@ load_lang() {
|
||||
[restarting]="🔄 Starte Gateway neu…"
|
||||
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
|
||||
[dry_info]="ℹ️ Mit --help alle Optionen anzeigen."
|
||||
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren"
|
||||
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||
[param_error]="❌ Unbekannte Option: %s"
|
||||
[check_update]="🔍 Prüfe auf Updates…"
|
||||
[update_available]="📦 Neue Version verfügbar: %s (aktuell: %s)"
|
||||
[no_update]="✅ Plugin ist auf dem neuesten Stand (%s)"
|
||||
[perform_update]="🔄 Aktualisiere Plugin auf Version %s…"
|
||||
[backup_created]="💾 Backup erstellt: %s"
|
||||
[update_success]="✅ Plugin erfolgreich aktualisiert auf Version %s"
|
||||
[rollback]="⏪ Stelle Backup wieder her: %s"
|
||||
[rollback_success]="✅ Backup erfolgreich wiederhergestellt"
|
||||
[update_failed]="❌ Update fehlgeschlagen. Fehler: %s"
|
||||
)
|
||||
fi
|
||||
}
|
||||
@@ -98,6 +118,133 @@ confirm_or_edit() {
|
||||
fi
|
||||
}
|
||||
|
||||
# ─── Update Functions ──────────────────────────────────────
|
||||
check_for_updates() {
|
||||
msg check_update
|
||||
|
||||
# Get the script directory (repo root)
|
||||
local script_dir
|
||||
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
# Change to repo directory
|
||||
cd "$script_dir"
|
||||
|
||||
# Get local version (latest tag)
|
||||
local local_version
|
||||
local_version=$(git describe --tags 2>/dev/null || echo "unknown")
|
||||
|
||||
# Get remote version (latest tag on origin)
|
||||
local remote_version
|
||||
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
|
||||
|
||||
# If we can't determine versions, exit with error
|
||||
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
|
||||
echo "Could not determine version information"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Compare versions
|
||||
if [ "$local_version" != "$remote_version" ]; then
|
||||
msg update_available "$remote_version" "$local_version"
|
||||
return 1 # Update available
|
||||
else
|
||||
msg no_update "$local_version"
|
||||
return 0 # No update needed
|
||||
fi
|
||||
}
|
||||
|
||||
create_backup() {
|
||||
local backup_file="$1"
|
||||
local plugin_dir="$2"
|
||||
local config_file="$3"
|
||||
local env_file="$4"
|
||||
|
||||
# Create backup of current installation
|
||||
tar -czf "$backup_file" -C "$(dirname "$plugin_dir")" "$(basename "$plugin_dir")" \
|
||||
--exclude="*.pyc" --exclude="__pycache__" \
|
||||
"$config_file" "$env_file" 2>/dev/null || true
|
||||
|
||||
msg backup_created "$backup_file"
|
||||
}
|
||||
|
||||
perform_update() {
|
||||
# Get the script directory (repo root)
|
||||
local script_dir
|
||||
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
# Change to repo directory
|
||||
cd "$script_dir"
|
||||
|
||||
# Get remote version
|
||||
local remote_version
|
||||
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
|
||||
|
||||
if [ "$remote_version" = "unknown" ]; then
|
||||
msg update_failed "Could not determine remote version"
|
||||
return 1
|
||||
fi
|
||||
|
||||
msg perform_update "$remote_version"
|
||||
|
||||
# Create backup before updating
|
||||
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
||||
local hermes_dir
|
||||
hermes_dir=""
|
||||
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
|
||||
if [ -d "$d" ]; then hermes_dir="$d"; break; fi
|
||||
done
|
||||
|
||||
if [ -n "$hermes_dir" ]; then
|
||||
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
||||
local config_file="$HOME/.hermes/config.yaml"
|
||||
local env_file="$HOME/.config/hermes/rocketchat.env"
|
||||
create_backup "$backup_file" "$plugin_dir" "$config_file" "$env_file"
|
||||
fi
|
||||
|
||||
# Perform the update
|
||||
local update_error=""
|
||||
{
|
||||
# Pull latest changes
|
||||
git fetch --tags origin 2>&1 || { update_error="Failed to fetch from remote"; return 1; }
|
||||
git checkout "$remote_version" 2>&1 || { update_error="Failed to checkout version $remote_version"; return 1; }
|
||||
|
||||
# Run the installer to update files
|
||||
HERMES_DIR="$hermes_dir" UPDATE_MODE=true ./install.sh --non-interactive 2>&1
|
||||
} || {
|
||||
# Update failed, rollback
|
||||
if [ -n "$update_error" ]; then
|
||||
msg update_failed "$update_error"
|
||||
else
|
||||
msg update_failed "Installation failed"
|
||||
fi
|
||||
|
||||
if [ -f "$backup_file" ]; then
|
||||
msg rollback "$backup_file"
|
||||
# Extract backup
|
||||
tar -xzf "$backup_file" -C "$HOME" 2>/dev/null || true
|
||||
msg rollback_success
|
||||
# Clean up backup file
|
||||
rm -f "$backup_file"
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Clean up backup file on success
|
||||
rm -f "$backup_file"
|
||||
|
||||
msg update_success "$remote_version"
|
||||
|
||||
# Restart gateway
|
||||
if [ -n "$hermes_dir" ]; then
|
||||
cd "$hermes_dir"
|
||||
systemctl --user daemon-reload 2>/dev/null || true
|
||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# ─── Argument parsing ────────────────────────────────────
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
@@ -110,6 +257,10 @@ while [ $# -gt 0 ]; do
|
||||
ARG_LANG="${1#*=}"; shift ;;
|
||||
--non-interactive)
|
||||
NONINTERACTIVE=true; shift ;;
|
||||
--check)
|
||||
CHECK_ONLY=true; shift ;;
|
||||
--update)
|
||||
UPDATE_MODE=true; shift ;;
|
||||
*)
|
||||
load_lang "${ARG_LANG:-${LANG##*.}}"
|
||||
msg param_error "$1"; echo; exit 1 ;;
|
||||
@@ -121,6 +272,20 @@ load_lang "${ARG_LANG:-${LANG##*.}}"
|
||||
|
||||
echo -e "\n${T[banner]}\n"
|
||||
|
||||
# ─── Update Check/Perform ──────────────────────────────────────
|
||||
if $CHECK_ONLY; then
|
||||
check_for_updates
|
||||
exit $?
|
||||
elif $UPDATE_MODE; then
|
||||
check_for_updates
|
||||
if [ $? -eq 1 ]; then
|
||||
perform_update
|
||||
exit $?
|
||||
else
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# ─── Find Hermes Agent ────────────────────────────────────
|
||||
msg checking
|
||||
HERMES_DIR=""
|
||||
@@ -245,4 +410,4 @@ systemctl --user daemon-reload 2>/dev/null || true
|
||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||
|
||||
msg done
|
||||
echo
|
||||
echo
|
||||
@@ -478,6 +478,47 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
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
|
||||
|
||||
+256
@@ -16,6 +16,7 @@ import os
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
import urllib.parse
|
||||
|
||||
from tools.registry import tool_error, tool_result
|
||||
|
||||
@@ -167,6 +168,95 @@ class RocketChatAPI:
|
||||
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."""
|
||||
@@ -591,6 +681,115 @@ def _handle_rocketchat_send(args: dict, **kw) -> str:
|
||||
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)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -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
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -714,6 +967,9 @@ _TOOLS = (
|
||||
("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, "📁"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user