v2.0: Gateway-Plugin-Architektur + interaktiver bilingualer install.sh

- Legacy-Standalone-Daemon entfernt (__init__.py, adapter.py, _merge_config.py, uninstall.sh)
- Plugin-Dateien in plugin/ strukturiert (von produktiver Susi-Instanz)
- Neuer install.sh: --lang en/de, --help, --non-interactive, Bot Username Prompt, Re-Install-Erkennung
- tools.py: Rocket.Chat REST-Tools fur Rooms, Users, DMs, Send
- BasePlatformAdapter-Vererbung, DDP-added-Events, case-insensitive Filter
This commit is contained in:
Bernd
2026-05-11 06:56:16 +02:00
parent 0a64199329
commit fc13a9ee87
7 changed files with 979 additions and 601 deletions
-156
View File
@@ -1,156 +0,0 @@
#!/usr/bin/env python3
"""
_merge_config.py — Merges Rocket.Chat settings into ~/.hermes/config.yaml.
Adds/updates ALL entries needed:
- plugins.enabled: rocketchat-platform
- gateway.platforms.rocketchat: enabled, extra.base_url, home_channel
- toolsets: rocketchat
Safe: preserves existing structure, comments, and formatting.
Only touches rocketchat-related keys.
"""
import argparse
import os
import sys
try:
import yaml
except ImportError:
print("ERROR: pyyaml required. Run: pip3 install --user pyyaml", file=sys.stderr)
sys.exit(1)
def load_config(path):
"""Load YAML config, return empty dict if file missing/broken."""
if not os.path.exists(path):
return {}
try:
with open(path) as f:
return yaml.safe_load(f) or {}
except Exception:
return {}
def save_config(path, data):
"""Write config preserving basic structure. Keeps existing file intact if possible."""
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
# Post-process: ensure proper blank lines between top-level sections
_reformat_sections(path)
def _reformat_sections(path):
"""Add blank lines between top-level YAML keys for readability."""
with open(path) as f:
lines = f.readlines()
out = []
prev_was_top_key = False
for line in lines:
stripped = line.rstrip()
is_top_key = bool(stripped) and not stripped[0].isspace() and ":" in stripped
if is_top_key and out and prev_was_top_key:
out.append("\n")
elif is_top_key and out:
out.append("\n")
out.append(stripped + "\n")
prev_was_top_key = is_top_key
with open(path, "w") as f:
f.writelines(out)
def remove_rocketchat(config):
"""Remove all rocketchat-related entries from config (in-place)."""
# plugins.enabled
if "plugins" in config and "enabled" in config["plugins"]:
config["plugins"]["enabled"] = [
p for p in config["plugins"]["enabled"] if p != "rocketchat-platform"
]
# gateway.platforms.rocketchat
if "gateway" in config and "platforms" in config["gateway"]:
config["gateway"]["platforms"].pop("rocketchat", None)
# toolsets
if "toolsets" in config and isinstance(config["toolsets"], list):
config["toolsets"] = [t for t in config["toolsets"] if t != "rocketchat"]
# known_plugin_toolsets.cli
if "known_plugin_toolsets" in config and "cli" in config["known_plugin_toolsets"]:
config["known_plugin_toolsets"]["cli"] = [
t for t in config["known_plugin_toolsets"]["cli"] if t != "rocketchat"
]
def merge_config(config, base_url, user, password, room_id, room_name):
"""Merge Rocket.Chat settings into the config dict (in-place)."""
# ── 1. plugins.enabled ──
plugins = config.setdefault("plugins", {})
enabled_plugins = plugins.setdefault("enabled", [])
if "rocketchat-platform" not in enabled_plugins:
enabled_plugins.append("rocketchat-platform")
# ── 2. gateway.platforms.rocketchat ──
gateway = config.setdefault("gateway", {})
platforms = gateway.setdefault("platforms", {})
rc = platforms.setdefault("rocketchat", {})
rc["enabled"] = True
extra = rc.setdefault("extra", {})
extra["base_url"] = base_url
if not rc.get("home_channel") or not rc["home_channel"].get("chat_id"):
hc = {"platform": "rocketchat"}
if room_id:
hc["chat_id"] = room_id
if room_name:
hc["name"] = room_name
rc["home_channel"] = hc
# ── 3. toolsets (agent-level) ──
toolsets = config.setdefault("toolsets", [])
if "rocketchat" not in toolsets:
# Don't insert if it's a complex structure (dict of lists)
if all(isinstance(t, str) for t in toolsets):
toolsets.append("rocketchat")
# ── 4. known_plugin_toolsets.cli ──
# Some Hermes versions auto-manage this; add if missing
known = config.setdefault("known_plugin_toolsets", {})
cli_ts = known.setdefault("cli", [])
if "rocketchat" not in cli_ts:
if all(isinstance(t, str) for t in cli_ts):
cli_ts.append("rocketchat")
def main():
parser = argparse.ArgumentParser(description="Merge Rocket.Chat config into Hermes config.yaml")
parser.add_argument("--config", required=True, help="Path to ~/.hermes/config.yaml")
parser.add_argument("--base-url", default="")
parser.add_argument("--user", default="")
parser.add_argument("--password", default="")
parser.add_argument("--room-id", default="")
parser.add_argument("--room-name", default="")
parser.add_argument("--remove", action="store_true", help="Remove rocketchat entries")
args = parser.parse_args()
if args.remove:
config = load_config(args.config)
remove_rocketchat(config)
save_config(args.config, config)
print("OK (removed)")
return
config = load_config(args.config)
merge_config(config, args.base_url, args.user, args.password, args.room_id, args.room_name)
save_config(args.config, config)
print("OK")
if __name__ == "__main__":
main()
+214 -259
View File
@@ -1,293 +1,248 @@
#!/usr/bin/env bash
# install.sh
# Rocket.Chat Plugin für Hermes Agent — Interaktives Setup
# Voraussetzungen: bash, curl, git, python3
#
# Nutzung:
# ./install.sh → Normale Installation
# ./install.sh --dry-run → Simulation (zeigt alles an, ändert nichts)
# ./install.sh --help → Diese Hilfe anzeigen
# Hermes Rocket.Chat Plugin — Interactive Installer
# https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin
#
set -euo pipefail
# ── Hilfe ──
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
cat <<'EOF'
Rocket.Chat Plugin — Interaktives Setup für Hermes Agent
# ─── Defaults ──────────────────────────────────────────────
LANG="${LANG:-de_DE.UTF-8}"
ARG_LANG=""
NONINTERACTIVE=false
Nutzung:
./install.sh Interaktive Installation mit Verbindungstest
./install.sh --dry-run Vorschau: zeigt alle Schritte an, ändert NICHTS
./install.sh --help Diese Hilfe anzeigen
# ─── Language packs ─────────────────────────────────────────
declare -A T
msg() { local k="$1"; shift; printf "${T[$k]:-$k}\n" "$@"; }
Was install.sh macht:
1. Prüft Voraussetzungen (curl, git, python3)
2. Legt das Plugin-Verzeichnis an
3. Kopiert plugin.yaml, __init__.py, adapter.py
4. Fragt Rocket.Chat-Zugangsdaten interaktiv ab
5. Testet die Verbindung und liest UserID/RoomID aus
6. Schreibt ALLE Einstellungen in ~/.hermes/config.yaml
(nicht nur .env — das ist für API-Keys)
7. Bietet Neustart von Hermes Gateway an
load_lang() {
local lang="${1:-de}"
case "$lang" in
de|de_DE*|de_DE.UTF-8) lang=de ;;
en|en_*) lang=en ;;
*) lang=en ;;
esac
Deinstallation: ./uninstall.sh
EOF
exit 0
fi
# ── Dry-Run Modus ──
DRY_RUN=false
if [[ "${1:-}" == "--dry-run" ]]; then
DRY_RUN=true
echo -e "\n🔍 DRY-RUN MODUS — Es wird NICHTS verändert. Nur Vorschau.\n"
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_NAME="rocketchat"
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
PLUGIN_DEST="$HERMES_HOME/hermes-agent/plugins/platforms/$PLUGIN_NAME"
CONFIG_FILE="$HERMES_HOME/config.yaml"
ECHO_OK() { echo -e " ✅ $1"; }
ECHO_ERR() { echo -e " ❌ $1"; }
ECHO_INFO() { echo -e " ℹ️ $1"; }
ECHO_STEP() { echo -e "\n🔵 $1"; }
ECHO_WARN() { echo -e " ⚠️ $1"; }
ECHO_DRY() { echo -e " 📝 [DRY-RUN] $1"; }
run_or_simulate() {
local desc="$1"
shift
if $DRY_RUN; then
ECHO_DRY "$desc"
echo " → würde ausführen: $*"
if [ "$lang" = "en" ]; then
T=(
[banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes Rocket.Chat Plugin — Installer\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
[checking]="🔍 Checking prerequisites…"
[found_hermes]="✅ Hermes Agent found at: %s"
[no_hermes]="❌ Hermes Agent not found.\n Install it first: https://github.com/nousresearch/hermes-agent\n Expected under: ~/hermes-agent or ~/.hermes/hermes-agent"
[existing]="📋 Existing installation detected:"
[confirm_values]=" Press ENTER to keep a value, or type a new one."
[enter_url]="Rocket.Chat URL"
[enter_botuser]="Bot Username (the bot account on the Rocket.Chat server)"
[enter_botpass]="Bot Password"
[enter_channel]="Home Channel (name or room ID, e.g. #ki-assistent or 69f4e…)"
[current_val]=" Current: %s"
[new_val]=" → "
[summary]="📋 Configuration Summary:"
[copying]="📁 Copying plugin files…"
[env_written]="🔑 Credentials written to %s"
[config_updated]="⚙️ config.yaml updated"
[service_installed]="⚡ Gateway service installed"
[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"
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
[param_error]="❌ Unknown option: %s"
)
else
"$@"
# German (default)
T=(
[banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes Rocket.Chat Plugin — Installer\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
[checking]="🔍 Prüfe Voraussetzungen…"
[found_hermes]="✅ Hermes Agent gefunden unter: %s"
[no_hermes]="❌ Hermes Agent nicht gefunden.\n Bitte zuerst installieren: https://github.com/nousresearch/hermes-agent\n Erwartet unter: ~/hermes-agent oder ~/.hermes/hermes-agent"
[existing]="📋 Bestehende Installation erkannt:"
[confirm_values]=" ENTER = Wert behalten, oder neuen Wert eingeben."
[enter_url]="Rocket.Chat Server URL"
[enter_botuser]="Bot Username (der Bot-Account auf dem Rocket.Chat Server)"
[enter_botpass]="Bot Passwort"
[enter_channel]="Home Channel (Name oder Raum-ID, z.B. #ki-assistent oder 69f4e…)"
[current_val]=" Aktuell: %s"
[new_val]=" → "
[summary]="📋 Zusammenfassung der Konfiguration:"
[copying]="📁 Kopiere Plugin-Dateien…"
[env_written]="🔑 Zugangsdaten gespeichert in %s"
[config_updated]="⚙️ config.yaml aktualisiert"
[service_installed]="⚡ Gateway-Service installiert"
[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"
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
[param_error]="❌ Unbekannte Option: %s"
)
fi
}
# ── Schritt 1: Prerequisites ──
ECHO_STEP "1/7 Prüfe Voraussetzungen"
# ─── Helper ──────────────────────────────────────────────
confirm_or_edit() {
# $1 = env-var name (RC_URL, RC_BOT_USER, …)
# $2 = message key (enter_url, enter_botuser, …)
# $3 = current value (may be empty)
local varname="$1" msgkey="$2" current="$3" input
MISSING=""
for cmd in curl git python3; do
if command -v "$cmd" &>/dev/null; then
ECHO_OK "$cmd installiert"
else
ECHO_ERR "$cmd fehlt"
MISSING="$MISSING $cmd"
if [ -n "$current" ]; then
msg current_val "$current"
msg confirm_values
fi
printf "%s" "${T[$new_val]}"
read -r input
if [ -n "$input" ]; then
printf -v "$varname" '%s' "$input"
fi
}
# ─── Argument parsing ────────────────────────────────────
while [ $# -gt 0 ]; do
case "$1" in
--help|-h)
load_lang "${ARG_LANG:-${LANG##*.}}"
echo; echo -e "${T[help_text]}"; echo; exit 0 ;;
--lang)
ARG_LANG="$2"; shift 2 ;;
--lang=*)
ARG_LANG="${1#*=}"; shift ;;
--non-interactive)
NONINTERACTIVE=true; shift ;;
*)
load_lang "${ARG_LANG:-${LANG##*.}}"
msg param_error "$1"; echo; exit 1 ;;
esac
done
if [[ -n "$MISSING" ]]; then
ECHO_WARN "Folgende Pakete müssen nachinstalliert werden:"
echo " sudo apt update && sudo apt install -y$MISSING"
if ! $DRY_RUN; then
read -rp " Pakete jetzt installieren? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
sudo apt update && sudo apt install -y $MISSING
else
echo "Abbruch. Bitte installiere:$MISSING"
exit 1
fi
else
ECHO_DRY "würde fragen: Pakete jetzt installieren?"
fi
fi
# ─── Load language ────────────────────────────────────────
load_lang "${ARG_LANG:-${LANG##*.}}"
# ── Check: pip pyyaml ──
if ! python3 -c "import yaml" 2>/dev/null; then
if ! $DRY_RUN; then
read -rp " python3-yaml fehlt. Installieren? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
pip3 install --user pyyaml
else
echo "Abbruch. 'pip3 install --user pyyaml' wird benötigt."
exit 1
fi
else
ECHO_DRY "würde pyyaml installieren"
fi
fi
echo -e "\n${T[banner]}\n"
# ── Schritt 2: Zielverzeichnis anlegen ──
ECHO_STEP "2/7 Erstelle Plugin-Verzeichnis"
if [[ -d "$PLUGIN_DEST" ]]; then
ECHO_WARN "Verzeichnis existiert bereits: $PLUGIN_DEST"
if ! $DRY_RUN; then
read -rp " Überschreiben? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
rm -rf "$PLUGIN_DEST"
else
echo "Abbruch."
exit 1
fi
else
ECHO_DRY "würde fragen: Verzeichnis überschreiben?"
fi
fi
run_or_simulate "Verzeichnis anlegen: $PLUGIN_DEST" mkdir -p "$PLUGIN_DEST"
$DRY_RUN || ECHO_OK "Verzeichnis angelegt: $PLUGIN_DEST"
# ── Schritt 3: Dateien kopieren ──
ECHO_STEP "3/7 Kopiere Plugin-Dateien"
for f in plugin.yaml __init__.py adapter.py; do
if [[ -f "$SCRIPT_DIR/$f" ]]; then
run_or_simulate "$f → $PLUGIN_DEST/$f" cp "$SCRIPT_DIR/$f" "$PLUGIN_DEST/"
$DRY_RUN || ECHO_OK "$f kopiert"
else
ECHO_ERR "$f nicht im aktuellen Verzeichnis gefunden"
exit 1
fi
# ─── Find Hermes Agent ────────────────────────────────────
msg checking
HERMES_DIR=""
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
if [ -d "$d" ]; then HERMES_DIR="$d"; break; fi
done
# ── Schritt 4: Konfiguration erfragen ──
ECHO_STEP "4/7 Konfiguration"
if [ -z "$HERMES_DIR" ]; then
msg no_hermes; exit 1
fi
msg found_hermes "$HERMES_DIR"
if $DRY_RUN; then
echo " [DRY-RUN] Beispielwerte werden verwendet"
RC_URL="https://chat.example.com"
RC_USER="bernd"
RC_PASS="geheim"
RC_ROOM="#ki-assistent"
ECHO_DRY "URL = $RC_URL"
ECHO_DRY "User = $RC_USER"
ECHO_DRY "Raum = $RC_ROOM"
# ─── Detect existing installation ─────────────────────────
ENV_FILE="$HOME/.config/hermes/rocketchat.env"
HAVE_EXISTING=false
RC_URL="" RC_BOT_USER="" RC_BOT_PASS="" RC_HOME_CHANNEL=""
if [ -f "$ENV_FILE" ]; then
HAVE_EXISTING=true
# shellcheck disable=SC1090
source "$ENV_FILE" 2>/dev/null || true
RC_URL="${ROCKETCHAT_BASE_URL:-${RC_URL:-}}"
RC_BOT_USER="${ROCKETCHAT_USER:-${RC_BOT_USER:-}}"
RC_HOME_CHANNEL="${ROCKETCHAT_ROOM_NAME:-${RC_HOME_CHANNEL:-}}"
fi
# ─── Non-interactive mode ─────────────────────────────────
if $NONINTERACTIVE; then
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}"
RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
msg env_required; exit 1
fi
else
read -rp " Rocket.Chat Basis-URL (z.B. https://chat.example.com): " RC_URL
[[ -z "$RC_URL" ]] && { ECHO_ERR "URL darf nicht leer sein"; exit 1; }
read -rp " Rocket.Chat Benutzername: " RC_USER
[[ -z "$RC_USER" ]] && { ECHO_ERR "Benutzername darf nicht leer sein"; exit 1; }
read -rsp " Rocket.Chat Passwort: " RC_PASS
# ─── Interactive mode ──────────────────────────────────
if $HAVE_EXISTING; then
msg existing
echo
[[ -z "$RC_PASS" ]] && { ECHO_ERR "Passwort darf nicht leer sein"; exit 1; }
read -rp " Standard-Raumname (z.B. #ki-assistent) [optional]: " RC_ROOM
fi
# ── Schritt 5: Verbindungstest ──
ECHO_STEP "5/7 Teste Verbindung zu Rocket.Chat"
confirm_or_edit RC_URL enter_url "$RC_URL"
confirm_or_edit RC_BOT_USER enter_botuser "$RC_BOT_USER"
confirm_or_edit RC_BOT_PASS enter_botpass ""
confirm_or_edit RC_HOME_CHANNEL enter_channel "$RC_HOME_CHANNEL"
LOGIN_RESP=$(curl -s -H "Content-Type: application/json" \
-d "{\"user\":\"$RC_USER\",\"password\":\"$RC_PASS\"}" \
"${RC_URL%/}/api/v1/login" 2>/dev/null) || true
if [[ -z "$LOGIN_RESP" ]] || ! echo "$LOGIN_RESP" | grep -q '"status":"success"'; then
ECHO_ERR "Login fehlgeschlagen"
echo
msg summary
echo " URL: $RC_URL"
echo " User: $RC_USER"
if ! $DRY_RUN; then
read -rp " Parameter bearbeiten? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
exec "$0"
echo " Bot User: $RC_BOT_USER"
echo " Home Channel: $RC_HOME_CHANNEL"
echo
fi
# ─── Write credentials ────────────────────────────────────
msg copying
mkdir -p "$(dirname "$ENV_FILE")"
cat > "$ENV_FILE" <<EOF
# Hermes Rocket.Chat Plugin — credentials (generated by install.sh)
export ROCKETCHAT_BASE_URL="${RC_URL}"
export ROCKETCHAT_USER="${RC_BOT_USER}"
export ROCKETCHAT_PASSWORD='${RC_BOT_PASS}'
export ROCKETCHAT_ROOM_NAME="${RC_HOME_CHANNEL}"
export ROCKETCHAT_ALLOW_ALL_USERS=true
export GATEWAY_ALLOW_ALL_USERS=true
export ROCKETCHAT_PING_SEC=8
export ROCKETCHAT_IDLE_SEC=900
EOF
chmod 600 "$ENV_FILE"
msg env_written "$ENV_FILE"
# ─── Copy plugin files ────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
mkdir -p "$PLUGIN_DST"
for f in plugin.yaml __init__.py adapter.py tools.py; do
if [ -f "$SCRIPT_DIR/plugin/$f" ]; then
cp "$SCRIPT_DIR/plugin/$f" "$PLUGIN_DST/$f"
fi
done
# ─── Patch config.yaml ────────────────────────────────────
CONFIG="$HOME/.hermes/config.yaml"
if [ -f "$CONFIG" ]; then
# Ensure rocketchat-platform is in plugins.enabled
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
# Simple append — user can refine later
cat >> "$CONFIG" <<'YAML'
# Added by Rocket.Chat Plugin installer
plugins:
enabled:
- rocketchat-platform
YAML
fi
msg config_updated
fi
# ─── Gateway service ──────────────────────────────────────
cd "$HERMES_DIR"
if [ -f "venv/bin/python" ]; then
PYTHON="venv/bin/python"
elif [ -f ".venv/bin/python" ]; then
PYTHON=".venv/bin/python"
else
ECHO_DRY "würde fragen: Parameter bearbeiten?"
fi
exit 1
PYTHON="python3"
fi
AUTH_TOKEN=$(echo "$LOGIN_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['data']['authToken'])")
USER_ID=$(echo "$LOGIN_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['data']['userId'])")
# Install / refresh systemd user service
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
ECHO_OK "Login erfolgreich (UserID: $USER_ID)"
# Ensure lingering is enabled (may need sudo — best-effort)
loginctl enable-linger 2>/dev/null || true
# Raum auflösen, wenn angegeben
ROOM_ID=""
ROOM_NAME="${RC_ROOM:-}"
if [[ -n "$RC_ROOM" ]]; then
ROOM_QUERY="${RC_ROOM/#\#}"
ROOM_RESP=$(curl -s -H "X-Auth-Token: $AUTH_TOKEN" -H "X-User-Id: $USER_ID" \
"${RC_URL%/}/api/v1/rooms.info?roomName=$ROOM_QUERY" 2>/dev/null) || true
msg service_installed
if echo "$ROOM_RESP" | grep -q '"success":true'; then
ROOM_ID=$(echo "$ROOM_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['room']['_id'])")
ROOM_NAME=$(echo "$ROOM_RESP" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['room'].get('fname') or d['room'].get('name', '$ROOM_QUERY'))")
ECHO_OK "Raum gefunden: #$ROOM_QUERY (RoomID: $ROOM_ID)"
else
ECHO_WARN "Raum '#$ROOM_QUERY' nicht gefunden — überspringe"
fi
fi
# ─── Restart gateway ──────────────────────────────────────
msg restarting
systemctl --user daemon-reload 2>/dev/null || true
systemctl --user restart hermes-gateway 2>/dev/null || true
# ── Schritt 6: Config.yaml schreiben ──
ECHO_STEP "6/7 Schreibe Konfiguration in config.yaml"
# Prüfen, ob eine config.yaml existiert
if [[ ! -f "$CONFIG_FILE" ]]; then
if ! $DRY_RUN; then
ECHO_WARN "$CONFIG_FILE nicht gefunden — wird neu erstellt"
else
ECHO_DRY "würde neue config.yaml erstellen"
fi
fi
run_or_simulate "config.yaml aktualisieren" python3 "$SCRIPT_DIR/_merge_config.py" \
--config "$CONFIG_FILE" \
--base-url "$RC_URL" \
--user "$RC_USER" \
--password "$RC_PASS" \
--room-id "${ROOM_ID:-}" \
--room-name "${ROOM_NAME:-}"
$DRY_RUN || ECHO_OK "~/.hermes/config.yaml aktualisiert"
# Zusätzlich .env für API-Keys (Passwort)
if ! $DRY_RUN; then
ENV_FILE="$HERMES_HOME/.env"
mkdir -p "$HERMES_HOME"
# Alte ROCKETCHAT_-Einträge entfernen
if [[ -f "$ENV_FILE" ]]; then
sed -i '/^ROCKETCHAT_/d' "$ENV_FILE" 2>/dev/null || true
fi
cat >> "$ENV_FILE" <<INNEREOF
# Rocket.Chat Plugin — generiert von install.sh am $(date +%Y-%m-%d)
export ROCKETCHAT_BASE_URL="$RC_URL"
export ROCKETCHAT_USER="$RC_USER"
export ROCKETCHAT_PASSWORD="$RC_PASS"
INNEREOF
ECHO_OK "~/.hermes/.env ergänzt"
else
ECHO_DRY "würde ~/.hermes/.env ergänzen"
fi
# ── Schritt 7: Hermes Gateway Neustart ──
ECHO_STEP "7/7 Hermes Gateway Neustart"
if $DRY_RUN; then
ECHO_DRY "würde hermes gateway restart ausführen"
else
if command -v hermes &>/dev/null; then
ECHO_INFO "Gateway wird neu gestartet..."
hermes gateway restart 2>/dev/null || {
hermes gateway stop 2>/dev/null || true
sleep 1
hermes gateway start 2>/dev/null || true
}
ECHO_OK "Hermes Gateway neu gestartet"
else
ECHO_WARN "'hermes' Befehl nicht im PATH gefunden"
echo " Bitte starte Hermes Gateway manuell:"
echo " hermes gateway restart"
fi
fi
if $DRY_RUN; then
ECHO_STEP "🔍 DRY-RUN BEENDET"
ECHO_INFO "Es wurde NICHTS verändert."
ECHO_INFO "Starte ohne --dry-run für echte Installation."
else
ECHO_STEP "✨ Fertig!"
ECHO_OK "Plugin installiert unter: $PLUGIN_DEST"
ECHO_OK "Konfiguration in: $CONFIG_FILE"
ECHO_INFO "Rocket.Chat Plugin ist bereit."
if [[ -n "$ROOM_ID" ]]; then
ECHO_INFO "Monitoring: $ROOM_NAME ($ROOM_ID)"
fi
fi
msg done
echo
+27 -46
View File
@@ -11,7 +11,7 @@ import os
logger = logging.getLogger(__name__)
# ── Interaction Templates (source of truth — zero yaml dependency) ──
# ── Interaction Templates ──
_TEMPLATE_MAP = {
"yes_no": {
"label": "Ja/Nein",
@@ -41,67 +41,47 @@ _TEMPLATE_MAP = {
},
"multi_choice_3": {
"label": "3 Optionen",
"description": "Three-option selection",
"attachment": {"color": "#1d74f5", "title": "Wähle eine Option:"},
"description": "Three choices",
"attachment": {"color": "#1d74f5", "title": "Bitte wählen:"},
"buttons": [
{"text": "1._Links", "msg": "links", "style": "default"},
{"text": "2._Rechts", "msg": "rechts", "style": "default"},
{"text": "3._Zwei_Runden", "msg": "zwei_runden", "style": "default"},
{"text": "1. Links", "msg": "1. Links"},
{"text": "2. Rechts", "msg": "2. Rechts"},
{"text": "3. Zwei Runden", "msg": "3. Zwei Runden"},
],
},
"custom": {
"label": "Custom",
"description": "User-defined buttons",
},
}
def _build_custom_buttons(labels: list, prefix: str = "") -> list:
"""Build Rocket.Chat action buttons from plain label strings.
Rocket.Chat Desktop-App schneidet Button-Text nach ~5-7 Zeichen ab.
Mobile App zeigt vollen Text. NIEMALS Underscores (_) verwenden —
sie zerstören das Button-Rendering komplett.
Empfohlen: nummerierte Kurzreferenzen (1. Links, 2. Rechts).
"""
buttons = []
for idx, label in enumerate(labels):
# Sanitize label for button text (keep short)
display = label.strip()
# Payload may carry question_id prefix for correlation
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
def check_requirements(config=None):
"""Validate that required env vars are set."""
required = ["ROCKETCHAT_BASE_URL", "ROCKETCHAT_USER", "ROCKETCHAT_PASSWORD"]
missing = [v for v in required if not os.environ.get(v)]
return len(missing) == 0, f"Missing env: {', '.join(missing)}" if missing else "Ready"
def check_requirements():
"""Rocket.Chat adapter uses only stdlib (urllib, socket, ssl, threading)."""
return True
def validate_config(config):
"""Validate platform-specific config."""
return True, "OK"
def validate_config(config) -> bool:
"""Check whether the platform is properly configured."""
extra = getattr(config, "extra", {}) or {}
base_url = os.getenv("ROCKETCHAT_BASE_URL") or extra.get("base_url", "")
user = os.getenv("ROCKETCHAT_USER") or extra.get("user", "")
password = os.getenv("ROCKETCHAT_PASSWORD") or extra.get("password", "")
return bool(base_url and user and password)
def is_connected(config) -> bool:
"""Check whether Rocket.Chat is configured (env or config.yaml)."""
return validate_config(config)
def is_connected(adapter):
"""Check if the adapter has an active connection."""
if adapter is None:
return False
return getattr(adapter, "_running", False)
def register(ctx):
"""Plugin entry point — called by the Hermes plugin system at startup."""
from .adapter import RocketChatAdapter # lazy import avoids circular deps
try:
from .tools import register_tools
except ImportError:
register_tools = None
ctx.register_platform(
name="rocketchat",
@@ -126,4 +106,5 @@ def register(ctx):
),
)
if register_tools is not None:
register_tools(ctx)
View File
-3
View File
@@ -11,9 +11,6 @@ requires_env:
- ROCKETCHAT_BASE_URL
- ROCKETCHAT_USER
- ROCKETCHAT_PASSWORD
- name: ROCKETCHAT_ROOM_ID
description: "Default room/channel ID to subscribe (optional if auto-discovery enabled)"
required: false
- name: ROCKETCHAT_ALLOW_ALL_USERS
description: "Set to 'true' to allow all users (default: false = allowlist)"
required: false
+739
View File
@@ -0,0 +1,739 @@
"""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
from tools.registry import tool_error, tool_result
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 {}
@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}")
# ---------------------------------------------------------------------------
# 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"],
},
}
# ---------------------------------------------------------------------------
# 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, "✉️"),
)
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,
)
-138
View File
@@ -1,138 +0,0 @@
#!/usr/bin/env bash
# uninstall.sh
# Rocket.Chat Plugin — Saubere Deinstallation von Hermes Agent
#
# Nutzung:
# ./uninstall.sh → Deinstallieren
# ./uninstall.sh --dry-run → Simulation (zeigt an, ändert nichts)
set -uo pipefail
DRY_RUN=false
if [[ "${1:-}" == "--dry-run" ]]; then
DRY_RUN=true
echo -e "\n🔍 DRY-RUN — Es wird NICHTS entfernt. Nur Vorschau.\n"
fi
PLUGIN_NAME="rocketchat"
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
PLUGIN_DEST="$HERMES_HOME/hermes-agent/plugins/platforms/$PLUGIN_NAME"
ENV_FILE="$HERMES_HOME/.env"
CONFIG_FILE="$HERMES_HOME/config.yaml"
ECHO_OK() { echo -e " ✅ $1"; }
ECHO_ERR() { echo -e " ❌ $1"; }
ECHO_INFO() { echo -e " ℹ️ $1"; }
ECHO_STEP() { echo -e "\n🔵 $1"; }
ECHO_WARN() { echo -e " ⚠️ $1"; }
ECHO_DRY() { echo -e " 📝 [DRY-RUN] $1"; }
run_or_simulate() {
local desc="$1"
shift
if $DRY_RUN; then
ECHO_DRY "$desc"
echo " → würde ausführen: $*"
else
"$@"
fi
}
# ── Schritt 1: Hermes Gateway stoppen ──
ECHO_STEP "1/4 Hermes Gateway stoppen"
if ! $DRY_RUN; then
if command -v hermes &>/dev/null; then
hermes gateway stop 2>/dev/null || true
ECHO_OK "Gateway gestoppt"
else
ECHO_WARN "'hermes' nicht gefunden — Gateway manuell prüfen"
fi
else
ECHO_DRY "würde 'hermes gateway stop' ausführen"
fi
# ── Schritt 2: Plugin-Dateien entfernen ──
ECHO_STEP "2/4 Plugin-Dateien entfernen"
if [[ -d "$PLUGIN_DEST" ]]; then
FILE_COUNT=$(find "$PLUGIN_DEST" -type f 2>/dev/null | wc -l)
ECHO_WARN "Gefunden: $PLUGIN_DEST ($FILE_COUNT Dateien)"
if ! $DRY_RUN; then
read -rp " Wirklich entfernen? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
rm -rf "$PLUGIN_DEST"
ECHO_OK "Plugin-Verzeichnis entfernt"
else
echo "Abbruch."
exit 0
fi
else
ECHO_DRY "würde rm -rf $PLUGIN_DEST ausführen ($FILE_COUNT Dateien)"
fi
else
ECHO_INFO "Plugin-Verzeichnis nicht gefunden — überspringe"
fi
# ── Schritt 3: Env-Variablen & config.yaml bereinigen ──
ECHO_STEP "3/4 Env-Variablen & config.yaml bereinigen"
# Env
if [[ -f "$ENV_FILE" ]]; then
RC_COUNT=$(grep -c "^ROCKETCHAT_" "$ENV_FILE" 2>/dev/null || echo "0")
if [[ "$RC_COUNT" -gt 0 ]]; then
if ! $DRY_RUN; then
read -rp " $RC_COUNT ROCKETCHAT_-Zeilen aus ~/.hermes/.env entfernen? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
sed -i '/^ROCKETCHAT_/d' "$ENV_FILE"
ECHO_OK "$RC_COUNT Einträge entfernt"
else
ECHO_INFO "Env-Einträge belassen"
fi
else
ECHO_DRY "würde $RC_COUNT ROCKETCHAT_-Zeilen aus $ENV_FILE entfernen"
fi
else
ECHO_INFO "Keine ROCKETCHAT_-Einträge in .env gefunden"
fi
fi
# Config.yaml
if [[ -f "$CONFIG_FILE" ]] && grep -q "rocketchat" "$CONFIG_FILE" 2>/dev/null; then
ECHO_WARN "rocketchat-Einträge in config.yaml gefunden"
if ! $DRY_RUN; then
read -rp " rocketchat-Einträge aus config.yaml entfernen? [j/N] " ans
if [[ "$ans" =~ ^[Jj]$ ]]; then
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
python3 "$SCRIPT_DIR/_merge_config.py" --remove --config "$CONFIG_FILE" 2>/dev/null || {
ECHO_WARN "Automatische config.yaml-Bereinigung fehlgeschlagen"
echo " Bitte manuell bereinigen:"
echo " $ nano $CONFIG_FILE"
echo " Suche nach 'rocketchat' und entferne die Einträge."
}
ECHO_OK "config.yaml-Einträge entfernt"
else
ECHO_INFO "config.yaml-Einträge belassen"
fi
else
ECHO_DRY "würde rocketchat-Einträge aus config.yaml entfernen"
fi
else
ECHO_INFO "Keine rocketchat-Einträge in config.yaml"
fi
# ── Schritt 4: Bereinigung abgeschlossen ──
ECHO_STEP "4/4 Bereinigung abgeschlossen"
if $DRY_RUN; then
ECHO_STEP "🔍 DRY-RUN BEENDET"
ECHO_INFO "Es wurde NICHTS entfernt."
ECHO_INFO "Starte ohne --dry-run für echte Deinstallation."
else
ECHO_STEP "✨ Deinstallation abgeschlossen"
ECHO_OK "Plugin ist entfernt"
ECHO_INFO "Zum erneuten Installieren: ./install.sh"
echo ""
ECHO_INFO "Gateway manuell neustarten, falls gewünscht:"
echo " hermes gateway restart"
fi