#!/usr/bin/env bash # # Hermes Rocket.Chat Plugin — Interactive Installer # https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin # set -euo pipefail # ─── Repo-Bootstrap (frische VM: Repo klonen falls fehlt) ── # Auf frisch zurückgesetztem OS existiert das Plugin-Repo noch nicht. # install.sh wird z.B. via curl heruntergeladen und ausgeführt. # Dieser Block klont das Repo mit ssh-keyscan + SSH→HTTP Fallback # und startet das Skript im geklonten Verzeichnis neu (exec). # # U1: ssh-keyscan — Host-Key für Gitea (.47) in known_hosts sicherstellen, # sonst schlägt git clone via SSH mit "Host key verification failed" fehl. # U2: git clone SSH→HTTP Fallback — falls der SSH-Key für Gitea nicht # hinterlegt ist, wird auf HTTPS geklont. Schlägt auch das fehl, klare # Fehlermeldung. _bootstrap_repo() { local script_dir script_dir="$(cd "$(dirname "$0")" && pwd)" # Liegen wir bereits in einem Git-Repo mit plugin/? if [ -d "$script_dir/.git" ] && [ -d "$script_dir/plugin" ]; then return 0 fi # Repo fehlt → klonen local clone_target="$HOME/Hermes_rocket.chat_Plugin" local gitea_host="192.168.180.47" local gitea_port="222" local ssh_url="git@${gitea_host}:Andreas/Hermes_rocket.chat_Plugin.git" local http_url="https://${gitea_host}/Andreas/Hermes_rocket.chat_Plugin.git" # U1: ssh-keyscan — Host-Key für Gitea (.47) in known_hosts sicherstellen mkdir -p "$HOME/.ssh" chmod 700 "$HOME/.ssh" if ! grep -q "${gitea_host}" "$HOME/.ssh/known_hosts" 2>/dev/null; then echo "🔑 Host-Key für ${gitea_host} nicht in known_hosts — ssh-keyscan..." ssh-keyscan -p "${gitea_port}" "${gitea_host}" >> "$HOME/.ssh/known_hosts" 2>/dev/null || true fi # U2: git clone mit SSH→HTTP Fallback echo "📦 Klone Plugin-Repo..." if [ -d "$clone_target/.git" ]; then echo "✅ Repo bereits vorhanden unter $clone_target" elif git clone "$ssh_url" "$clone_target" 2>/dev/null; then echo "✅ Clone via SSH erfolgreich" elif git clone "$http_url" "$clone_target" 2>/dev/null; then echo "✅ Clone via HTTP (Fallback) erfolgreich" else echo "❌ Git clone fehlgeschlagen — SSH-Key für Gitea (${gitea_host}:${gitea_port}) oder HTTP-Zugang nötig" exit 1 fi # Guard: .git vorhanden aber plugin/ fehlt → unvollständiger Clone → fatal (verhindert Endlosschleife) if [ -d "$clone_target/.git" ] && [ ! -d "$clone_target/plugin" ]; then echo "❌ Repo unvollständig: .git vorhanden aber plugin/ fehlt in $clone_target" echo " Bitte $clone_target entfernen und neu ausführen." exit 1 fi # Skript im geklonten Repo neu starten (exec ersetzt Prozess, Argumente bleiben erhalten) exec "$clone_target/install.sh" "$@" } _bootstrap_repo # ─── Defaults ────────────────────────────────────────────── LANG="${LANG:-de_DE.UTF-8}" ARG_LANG="" NONINTERACTIVE=false CHECK_ONLY=false UPDATE_MODE=false UPDATE_ONLY=false UPDATE_AVAILABLE=false RC_MULTIROOM="${RC_MULTIROOM:-false}" # ─── Language packs ───────────────────────────────────────── declare -A T msg() { local k="$1"; shift; printf "${T[$k]:-$k}\n" "$@"; } 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 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…)" [multiroom_ask]="Enable multi-room agent? (y/N)" [multiroom_warn]="⚠️ Multi-room agent requires significant system resources:\n - Local Ollama with embedding model (nomic-embed-text, ~274 MB)\n - FAISS vector index (CPU/RAM)\n - LLM router (e.g. qwen2.5:7b, ~4.7 GB)\n - Recommended: min. 16 GB RAM, 4 CPU cores\n - Without these resources: choose single-room mode (default N)" [current_val]=" Current: %s" [new_val]=" → " [summary]="📋 Configuration Summary:" [copying]="📁 Copying plugin files…" [env_written]="🔑 Credentials written to %s" [config_updated]="⚙️ config.yaml updated" [config_provisioned]="📄 Provisioned minimal config.yaml" [env_provisioned]="🔧 Provisioned .env template" [env_dropin]="🔌 Systemd EnvironmentFile drop-in installed" [copied]="📁 Copied %d plugin files" [ollama_check]="🔍 Checking Ollama..." [ollama_missing]="⚠️ Ollama not found. Install: curl -fsSL https://ollama.com/install.sh | sh" [nomic_pull]="📥 Pulling nomic-embed-text (274 MB)..." [nomic_ok]="✅ nomic-embed-text ready" [nomic_fail]="⚠️ nomic-embed-text pull failed — Archivar will use fallback mode" [ollama_ok]="✅ Ollama ready" [ollama_installing]="📥 Installing Ollama (https://ollama.com)..." [ollama_install_fail]="⚠️ Ollama installation failed — Archivar will use fallback mode (keyword heuristic)" [ollama_wait]="⏳ Waiting for Ollama to start..." [ollama_qwen_pull]="📥 Pulling qwen2.5:7b (4.7 GB) — this may take several minutes..." [ollama_qwen_ok]="✅ qwen2.5:7b ready" [ollama_qwen_fail]="⚠️ qwen2.5:7b pull failed — LLM routing will use fallback" [ollama_sudo_hint]="ℹ️ Ollama install may require sudo — enter your password if prompted" [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\n --check Check for updates only\n --update Check for updates and install if available\n --update-only Emergency deploy: Only deploy plugin files +\n restart gateway. No questions, no config provisioning,\n no Ollama. Uses find_hermes_dir() for path discovery." [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" [update_only_banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes RC Plugin — Emergency Deploy\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" [deploying]="📦 Deploying plugin files (update-only, no questions)..." [deploy_done]="✅ %d files deployed to %s" [room_map_backup]="💾 Backed up existing room-map.json to %s" [room_map_deployed]="📊 Deployed room-map.json to %s" [cache_cleared]="🧹 Cleared __pycache__" [verifying]="🔍 Verifying gateway..." [verify_ok]="✅ Gateway running with Rocket.Chat connected" [verify_fail]="⚠️ Gateway started but Rocket.Chat not detected in logs (check journalctl)" [verify_timeout]="⏳ Waiting for Rocket.Chat handshake..." ) 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…)" [multiroom_ask]="Multi-Room-Agent aktivieren? (y/N)" [multiroom_warn]="⚠️ Multi-Room-Agent benötigt erhebliche Systemressourcen:\n - Lokales Ollama mit Embedding-Modell (nomic-embed-text, ~274 MB)\n - FAISS-Vektorindex (CPU/RAM)\n - LLM-Router (z.B. qwen2.5:7b, ~4.7 GB)\n - Empfohlen: mind. 16 GB RAM, 4 CPU-Kerne\n - Ohne diese Ressourcen: Single-Room-Modus wählen (Default N)" [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" [config_provisioned]="📄 Minimale config.yaml bereitgestellt" [env_provisioned]="🔧 .env-Vorlage bereitgestellt" [env_dropin]="🔌 Systemd EnvironmentFile-Drop-in installiert" [copied]="📁 %d Plugin-Dateien kopiert" [ollama_check]="🔍 Prüfe Ollama..." [ollama_missing]="⚠️ Ollama nicht gefunden. Installation: curl -fsSL https://ollama.com/install.sh | sh" [nomic_pull]="📥 Lade nomic-embed-text herunter (274 MB)..." [nomic_ok]="✅ nomic-embed-text bereit" [nomic_fail]="⚠️ nomic-embed-text Download fehlgeschlagen — Archivar nutzt Fallback-Modus" [ollama_ok]="✅ Ollama bereit" [ollama_installing]="📥 Installiere Ollama (https://ollama.com)..." [ollama_install_fail]="⚠️ Ollama-Installation fehlgeschlagen — Archivar nutzt Fallback-Modus (Keyword-Heuristik)" [ollama_wait]="⏳ Warte auf Ollama-Start..." [ollama_qwen_pull]="📥 Lade qwen2.5:7b herunter (4,7 GB) — dies kann einige Minuten dauern..." [ollama_qwen_ok]="✅ qwen2.5:7b bereit" [ollama_qwen_fail]="⚠️ qwen2.5:7b Download fehlgeschlagen — LLM-Routing nutzt Fallback" [ollama_sudo_hint]="ℹ️ Ollama-Installation benötigt ggf. sudo — Passwort eingeben falls abgefragt" [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\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren\n --update-only Notfall-Deployment: Nur Plugin-Dateien deployen +\n Gateway-Neustart. Keine Fragen, kein Config-Provisioning,\n kein Ollama. Nutzt find_hermes_dir() für Pfad-Ermittlung." [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" [update_only_banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes RC Plugin — Notfall-Deployment\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" [deploying]="📦 Deploye Plugin-Dateien (update-only, ohne Rückfragen)..." [deploy_done]="✅ %d Dateien deployed nach %s" [room_map_backup]="💾 Vorhandene room-map.json gesichert nach %s" [room_map_deployed]="📊 room-map.json deployed nach %s" [cache_cleared]="🧹 __pycache__ gelöscht" [verifying]="🔍 Verifiziere Gateway..." [verify_ok]="✅ Gateway läuft mit Rocket.Chat verbunden" [verify_fail]="⚠️ Gateway gestartet, aber Rocket.Chat nicht im Log erkannt (prüfe journalctl)" [verify_timeout]="⏳ Warte auf Rocket.Chat-Handshake..." ) fi } # ─── 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 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 } # ─── 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" UPDATE_AVAILABLE=false return 0 fi # Compare versions if [ "$local_version" != "$remote_version" ]; then msg update_available "$remote_version" "$local_version" UPDATE_AVAILABLE=true return 0 # Update available else msg no_update "$local_version" UPDATE_AVAILABLE=false return 0 # No update needed fi } find_hermes_dir() { # Priorität 1: --dir Flag (bereits in ARG_DIR gesetzt) if [ -n "${ARG_DIR:-}" ]; then if [ -d "$ARG_DIR" ]; then echo "$ARG_DIR" return 0 fi fi # Priorität 2: Laufenden Gateway via systemd finden if [ -z "${HERMES_DIR:-}" ] && systemctl --user is-active hermes-gateway >/dev/null 2>&1; then set +e EXEC_PATH=$(systemctl --user show hermes-gateway -p ExecStart --value | sed -n 's/.*path=\([^;]*\).*/\1/p' | sed 's|/venv/bin/python.*||' | sed 's|/.venv/bin/python.*||') set -e if [ -n "$EXEC_PATH" ] && [ -d "$EXEC_PATH" ]; then echo "$EXEC_PATH" return 0 fi fi # Priorität 3: Laufenden Prozess via /proc scannen if [ -z "${HERMES_DIR:-}" ]; then set +e PID=$(pgrep -f "hermes_cli.main gateway run" | head -1) set -e if [ -n "$PID" ] && [ -d "/proc/$PID/cwd" ]; then HERMES_DIR=$(readlink -f "/proc/$PID/cwd") if [ -n "$HERMES_DIR" ] && [ -d "$HERMES_DIR" ]; then echo "$HERMES_DIR" return 0 fi fi fi # Priorität 4: command -v hermes → Symlink auflösen → Installationsverzeichnis ableiten if [ -z "${HERMES_DIR:-}" ]; then set +e HERMES_CMD=$(command -v hermes 2>/dev/null) set -e if [ -n "$HERMES_CMD" ]; then # Symlink auflösen if [ -L "$HERMES_CMD" ]; then HERMES_CMD=$(readlink -f "$HERMES_CMD") fi # Installationsverzeichnis ableiten (gehe 2 Ebenen nach oben: bin/hermes → .) HERMES_DIR=$(dirname "$(dirname "$HERMES_CMD")") if [ -n "$HERMES_DIR" ] && [ -d "$HERMES_DIR" ]; then echo "$HERMES_DIR" return 0 fi fi fi # Priorität 5: python3 -c "from hermes_constants import get_hermes_home; print(get_hermes_home())" if [ -z "${HERMES_DIR:-}" ]; then set +e HERMES_HOME=$(python3 -c "from hermes_constants import get_hermes_home; print(get_hermes_home())" 2>/dev/null) set -e if [ -n "$HERMES_HOME" ]; then if [ -d "$HERMES_HOME/hermes-agent" ]; then echo "$HERMES_HOME/hermes-agent" return 0 elif [ -d "$HERMES_HOME" ]; then echo "$HERMES_HOME" return 0 fi fi fi # Priorität 6 (Fallback): Die alte Pfad-Heuristik BEHALTEN, aber um FHS erweitern if [ -z "${HERMES_DIR:-}" ]; then for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent" "/usr/local/lib/hermes-agent"; do if [ -d "$d" ]; then echo "$d" return 0 fi done fi # Kein Hermes-Verzeichnis gefunden return 1 } 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" # Check if we have local changes and stash if needed local stashed=false if ! git diff --quiet; then git stash push -m "Auto-stash before update" stashed=true fi # Get remote version (for display only) 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" # Restore stash if we had changes if $stashed; then git stash pop 2>/dev/null || true fi 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=$(find_hermes_dir 2>/dev/null || echo "") if [ -n "$hermes_dir" ]; then local plugin_dir="$hermes_dir/plugins/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 (instead of checkout) git pull origin main 2>&1 || { update_error="Failed to pull from origin main"; return 1; } # Copy plugin files directly (lines 448-466) PLUGIN_DST="$hermes_dir/plugins/rocketchat" mkdir -p "$PLUGIN_DST" # Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen if [ -d "$script_dir/plugin" ]; then # Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören # Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur) while read -r src; do rel="${src#$script_dir/plugin/}" dst="$PLUGIN_DST/$rel" mkdir -p "$(dirname "$dst")" cp "$src" "$dst" done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc') copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l) msg copied "$copied_count" # Symlink for core plugin loader: archivar must be importable as top-level module if [ -d "$PLUGIN_DST/plugin/archivar" ]; then ln -sfn "$PLUGIN_DST/plugin/archivar" "$hermes_dir/archivar" fi # NOTE: room-map.json is MACHINE-SPECIFIC — never deployed # by the installer. It is created by the RC-Skill onboarding # flow after gateway start. See RC-Skill: "Room Topic Discipline" fi # ── FIX: numpy/faiss im venv installieren ────────────────────── # Archivar braucht numpy + faiss für FAISS Phase-1 RoomIndex. # Nur im Multi-Room-Agent-Modus nötig; Single-Room-Bot bleibt schlank. # M9: numpy ist Pflicht, faiss-cpu best-effort (kann auf ARM fehlen). if [ "$RC_MULTIROOM" = "true" ]; then if [ -f "$hermes_dir/venv/bin/pip" ]; then "$hermes_dir/venv/bin/pip" install numpy 2>&1 | tail -1 "$hermes_dir/venv/bin/pip" install faiss-cpu 2>/dev/null || echo "⚠️ faiss-cpu not available (ARM?) — Archivar uses fallback" elif [ -f "$hermes_dir/.venv/bin/pip" ]; then "$hermes_dir/.venv/bin/pip" install numpy 2>&1 | tail -1 "$hermes_dir/.venv/bin/pip" install faiss-cpu 2>/dev/null || echo "⚠️ faiss-cpu not available (ARM?) — Archivar uses fallback" fi fi # ─── FIX: room-map.json bereitstellen (nur Multi-Room) ───────── # room-map.json ist maschinenspezifisch; nur im Multi-Room-Modus # deployen. Die vollständige Version wird vom RC-Skill-Onboarding # nach dem Gateway-Start erstellt. if [ "$RC_MULTIROOM" = "true" ]; then local room_map_data_dir="$HOME/.hermes/hermes-agent/data" mkdir -p "$room_map_data_dir" local room_map_file="$room_map_data_dir/room-map.json" local template_file="$script_dir/templates/room-map.json" local deploy_template=false if [ ! -f "$room_map_file" ]; then # Keine room-map.json vorhanden → Template deployen deploy_template=true elif [ -f "$room_map_file" ] && [ -f "$template_file" ]; then # Bug 5 fix: Prüfe ob die existierende room-map.json das leere Template ist # (keine echten Räume, nur PLACEHOLDER_VAULT_PATH) # SICHERHEIT: python3-Verfügbarkeit VOR dem Check prüfen. # Falls python3 fehlt → Warnung + Skip (nicht überschreiben!). local room_count if command -v python3 >/dev/null 2>&1; then room_count=$(python3 -c " import json try: with open('$room_map_file') as f: data = json.load(f) rooms = data.get('rooms', {}) print(len(rooms)) except: print(0) " 2>/dev/null || echo "0") else echo " ⚠️ python3 not found — skipping room-map.json check (will NOT overwrite existing data)" room_count="SKIP" fi if [ "$room_count" = "0" ]; then echo " ℹ️ room-map.json is empty template — will deploy fresh" deploy_template=true fi fi if $deploy_template && [ -f "$template_file" ]; then cp "$template_file" "$room_map_file" msg room_map_deployed "$room_map_file" fi fi # M10: Ollama Prerequisites (nur bei MULTIROOM=true) if [ "$RC_MULTIROOM" = "true" ]; then msg ollama_check if command -v ollama >/dev/null 2>&1; then msg ollama_ok # nomic-embed-text laden falls nicht vorhanden if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then msg nomic_pull if ollama pull nomic-embed-text 2>/dev/null; then msg nomic_ok else msg nomic_fail fi else msg nomic_ok fi # Optional: qwen2.5:7b if ! ollama list 2>/dev/null | grep -q "qwen2.5:7b"; then msg ollama_qwen_pull ollama pull qwen2.5:7b 2>/dev/null && msg ollama_qwen_ok || msg ollama_qwen_fail else msg ollama_qwen_ok fi else msg ollama_missing fi fi } || { # 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 # Restore stash if we had changes if $stashed; then git stash pop 2>/dev/null || true fi return 1 } # Clean up backup file on success rm -f "$backup_file" msg update_success "$remote_version" # Restore stash if we had changes if $stashed; then git stash pop 2>/dev/null || true fi # Restart gateway (mit State-Cleanup gegen Discovery-Bug + Auto-Resume-Loop) if [ -n "$hermes_dir" ]; then cd "$hermes_dir" systemctl --user daemon-reload 2>/dev/null || true # State-Cleanup: Verhindert Discovery-Bug + Auto-Resume-Crash-Loop rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" "$HOME/.hermes/.gateway_state_*.tmp" 2>/dev/null || true systemctl --user reset-failed hermes-gateway 2>/dev/null || true systemctl --user enable hermes-gateway 2>/dev/null || true # Gateway stoppen (mit Timeout) systemctl --user stop hermes-gateway 2>/dev/null || true local stop_wait=0 while systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $stop_wait -lt 60 ]; do sleep 2 stop_wait=$((stop_wait + 2)) done # Gateway starten systemctl --user start hermes-gateway 2>/dev/null || true fi return 0 } # ─── Emergency Deploy (update-only) ───────────────────────── perform_update_only() { local script_dir script_dir="$(cd "$(dirname "$0")" && pwd)" echo -e "\n${T[update_only_banner]}\n" # 1. Find hermes directory local hermes_dir hermes_dir=$(find_hermes_dir 2>/dev/null || echo "") if [ -z "$hermes_dir" ]; then msg no_hermes; exit 1 fi msg found_hermes "$hermes_dir" # 2. Backup current state local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz" local plugin_dir="$hermes_dir/plugins/rocketchat" if [ -d "$plugin_dir" ]; then create_backup "$backup_file" "$plugin_dir" \ "$HOME/.hermes/config.yaml" \ "$HOME/.config/hermes/rocketchat.env" fi # 3. Deploy all plugin files msg deploying local PLUGIN_DST="$hermes_dir/plugins/rocketchat" mkdir -p "$PLUGIN_DST" # GUARD 1: Syntax-Check VOR Deployment echo "🔍 Running syntax check on Python files..." while read -r pyfile; do if ! python3 -m py_compile "$pyfile" 2>/dev/null; then echo "❌ Syntax error in $pyfile" echo "Deployment aborted due to syntax errors" return 1 fi done < <(find "$script_dir/plugin" -name "*.py" -type f) echo "✅ All Python files passed syntax check" # GUARD 2: Vollständigkeits-Check echo "🔍 Running completeness check..." local missing_files=() while read -r src; do rel="${src#$script_dir/plugin/}" dst="$PLUGIN_DST/$rel" if [ ! -f "$dst" ]; then missing_files+=("$rel") fi done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc') if [ ${#missing_files[@]} -gt 0 ]; then echo "❌ Missing files detected:" for file in "${missing_files[@]}"; do echo " - $file" done echo "Deployment aborted due to missing files" return 1 fi echo "✅ All files present in destination" if [ -d "$script_dir/plugin" ]; then while read -r src; do rel="${src#$script_dir/plugin/}" dst="$PLUGIN_DST/$rel" mkdir -p "$(dirname "$dst")" cp "$src" "$dst" done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc') local copied_count copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l) msg deploy_done "$copied_count" "$PLUGIN_DST" # Symlink for core plugin loader: archivar must be importable as top-level module if [ -d "$PLUGIN_DST/plugin/archivar" ]; then ln -sfn "$PLUGIN_DST/plugin/archivar" "$hermes_dir/archivar" fi else msg update_failed "plugin/ directory not found in $script_dir" return 1 fi # GUARD 3: Pycache-Löschung NACH Deployment echo "🧹 Cleaning up pycache files..." find "$PLUGIN_DST" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true find "$PLUGIN_DST" -name '*.pyc' -delete 2>/dev/null || true msg cache_cleared # ── FIX: numpy/faiss im venv installieren ────────────────────── # Archivar braucht numpy + faiss für FAISS Phase-1 RoomIndex. # Nur im Multi-Room-Agent-Modus nötig; Single-Room-Bot bleibt schlank. # M9: numpy ist Pflicht, faiss-cpu best-effort (kann auf ARM fehlen). if [ "$RC_MULTIROOM" = "true" ]; then if [ -f "$hermes_dir/venv/bin/pip" ]; then "$hermes_dir/venv/bin/pip" install numpy 2>&1 | tail -1 "$hermes_dir/venv/bin/pip" install faiss-cpu 2>/dev/null || echo "⚠️ faiss-cpu not available (ARM?) — Archivar uses fallback" elif [ -f "$hermes_dir/.venv/bin/pip" ]; then "$hermes_dir/.venv/bin/pip" install numpy 2>&1 | tail -1 "$hermes_dir/.venv/bin/pip" install faiss-cpu 2>/dev/null || echo "⚠️ faiss-cpu not available (ARM?) — Archivar uses fallback" fi fi # ─── FIX: room-map.json bereitstellen (nur Multi-Room) ───────── # room-map.json ist maschinenspezifisch; nur im Multi-Room-Modus # deployen. Die vollständige Version wird vom RC-Skill-Onboarding # nach dem Gateway-Start erstellt. if [ "$RC_MULTIROOM" = "true" ]; then local room_map_data_dir="$HOME/.hermes/hermes-agent/data" mkdir -p "$room_map_data_dir" local room_map_file="$room_map_data_dir/room-map.json" local template_file="$script_dir/templates/room-map.json" local deploy_template=false if [ ! -f "$room_map_file" ]; then deploy_template=true elif [ -f "$room_map_file" ] && [ -f "$template_file" ]; then local room_count if command -v python3 >/dev/null 2>&1; then room_count=$(python3 -c " import json try: with open('$room_map_file') as f: data = json.load(f) rooms = data.get('rooms', {}) print(len(rooms)) except: print(0) " 2>/dev/null || echo "0") else echo " ⚠️ python3 not found — skipping room-map.json check (will NOT overwrite existing data)" room_count="SKIP" fi if [ "$room_count" = "0" ]; then deploy_template=true fi fi if $deploy_template && [ -f "$template_file" ]; then cp "$template_file" "$room_map_file" msg room_map_deployed "$room_map_file" fi fi # 5. Restart gateway (mit State-Cleanup gegen Discovery-Bug + Auto-Resume-Loop) msg restarting systemctl --user daemon-reload 2>/dev/null || true # State-Cleanup: Verhindert Discovery-Bug (Platform-Verlust nach SIGTERM) # und Auto-Resume-Crash-Loop (restart-interrupted sessions triggern Kill) rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" "$HOME/.hermes/.gateway_state_*.tmp" 2>/dev/null || true systemctl --user reset-failed hermes-gateway 2>/dev/null || true systemctl --user enable hermes-gateway 2>/dev/null || true # Gateway stoppen (mit Timeout — kann bis 60s dauern) systemctl --user stop hermes-gateway 2>/dev/null || true local stop_wait=0 while systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $stop_wait -lt 60 ]; do sleep 2 stop_wait=$((stop_wait + 2)) done # Gateway starten systemctl --user start hermes-gateway 2>/dev/null || true # 6. Verify BOTH platforms connected (gateway_state.json — robuster als Journal-Grep) msg verifying local verified=false for i in $(seq 1 24); do sleep 2.5 if [ -f "$HOME/.hermes/gateway_state.json" ]; then local state_check state_check=$(python3 -c " import json, sys try: with open('$HOME/.hermes/gateway_state.json') as f: d = json.load(f) platforms = d.get('platforms', {}) rc = platforms.get('rocketchat', {}).get('state', '') tg = platforms.get('telegram', {}).get('state', '') if rc == 'connected' and tg == 'connected': print('OK') else: print('WAITING: rc={}, tg={}'.format(rc, tg)) except Exception as e: print('ERROR: {}'.format(e)) " 2>/dev/null) if [ "$state_check" = "OK" ]; then verified=true break fi fi if [ $((i % 4)) -eq 0 ]; then msg verify_timeout fi done if $verified; then msg verify_ok rm -f "$backup_file" else msg verify_fail fi return 0 } # ─── 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 ;; --check) CHECK_ONLY=true; shift ;; --update) UPDATE_MODE=true; shift ;; --update-only) UPDATE_ONLY=true; shift ;; *) load_lang "${ARG_LANG:-${LANG##*.}}" msg param_error "$1"; echo; exit 1 ;; esac done # ─── Load language ──────────────────────────────────────── load_lang "${ARG_LANG:-${LANG##*.}}" echo -e "\n${T[banner]}\n" # ─── Update Check/Perform ────────────────────────────────────── if $CHECK_ONLY; then check_for_updates if $UPDATE_AVAILABLE; then exit 1 else exit 0 fi elif $UPDATE_MODE; then check_for_updates if $UPDATE_AVAILABLE; then perform_update exit $? else exit 0 fi elif $UPDATE_ONLY; then perform_update_only exit $? fi msg checking HERMES_DIR=$(find_hermes_dir) if [ -z "$HERMES_DIR" ]; then msg no_hermes; exit 1 fi msg found_hermes "$HERMES_DIR" # ─── Detect existing installation ───────────────────────── ENV_FILE="$HOME/.config/hermes/rocketchat.env" HAVE_EXISTING=false RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}" RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${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 # Read from environment variables (NOT local — respect what install.sh caller exports) RC_URL="${RC_URL:-${ROCKETCHAT_BASE_URL:-}}" RC_BOT_USER="${RC_BOT_USER:-${ROCKETCHAT_USER:-}}" RC_BOT_PASS="${RC_BOT_PASS:-${ROCKETCHAT_PASSWORD:-}}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-${ROCKETCHAT_ROOM_NAME:-}}" RC_MULTIROOM="${RC_MULTIROOM:-false}" if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then msg env_required; exit 1 fi else # ─── Interactive mode ────────────────────────────────── if $HAVE_EXISTING; then msg existing echo fi 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" # Multi-Room-Agent: default N (Single-Room, community-tauglich) echo -e "${T[multiroom_warn]}" echo printf "%s" "${T[multiroom_ask]} " read -r multiroom_input case "${multiroom_input:-}" in y|Y|yes|ja|Yes|Ja|YES|JA) RC_MULTIROOM="true" ;; *) RC_MULTIROOM="false" ;; esac echo msg summary echo " URL: $RC_URL" echo " Bot User: $RC_BOT_USER" echo " Home Channel: $RC_HOME_CHANNEL" echo " Multi-Room: $RC_MULTIROOM" echo fi # ─── Write credentials ──────────────────────────────────── msg copying mkdir -p "$(dirname "$ENV_FILE")" # Bug #12: single-quoted delimiter verhindert $-Expansion im Passwort cat > "$ENV_FILE" <<'EOF' # Hermes Rocket.Chat Plugin — credentials (generated by install.sh) # systemd-compatible: KEY=VALUE (no export prefix!) ROCKETCHAT_BASE_URL=PLACEHOLDER_RC_URL ROCKETCHAT_USER=PLACEHOLDER_RC_USER ROCKETCHAT_PASSWORD=PLACEHOLDER_RC_PASS ROCKETCHAT_ROOM_NAME=PLACEHOLDER_RC_CHANNEL ROCKETCHAT_ALLOW_ALL_USERS=true GATEWAY_ALLOW_ALL_USERS=true ROCKETCHAT_PING_SEC=8 ROCKETCHAT_IDLE_SEC=900 RC_MULTIROOM=PLACEHOLDER_RC_MULTIROOM ARCHIVAR_CATCHALL_ROOM=PLACEHOLDER_ARCHIVAR_CATCHALL_ROOM EOF # Ersetze Platzhalter mit python3 (sicher für $-Zeichen im Passwort) export RC_URL RC_BOT_USER RC_BOT_PASS RC_HOME_CHANNEL RC_MULTIROOM export ENV_FILE python3 -c " import os env_file = os.environ['ENV_FILE'] with open(env_file) as f: content = f.read() content = content.replace('PLACEHOLDER_RC_URL', os.environ.get('RC_URL', '')) content = content.replace('PLACEHOLDER_RC_USER', os.environ.get('RC_BOT_USER', '')) content = content.replace('PLACEHOLDER_RC_PASS', os.environ.get('RC_BOT_PASS', '')) content = content.replace('PLACEHOLDER_RC_CHANNEL', os.environ.get('RC_HOME_CHANNEL', '')) content = content.replace('PLACEHOLDER_RC_MULTIROOM', os.environ.get('RC_MULTIROOM', 'false')) content = content.replace('PLACEHOLDER_ARCHIVAR_CATCHALL_ROOM', os.environ.get('RC_HOME_CHANNEL', '')) with open(env_file, 'w') as f: f.write(content) " chmod 600 "$ENV_FILE" msg env_written "$ENV_FILE" # ─── M10: Ollama Prerequisite (nur bei MULTIROOM=true) ────── # Archivar braucht lokales Ollama für Embeddings (nomic-embed-text) # und optional LLM-Routing (qwen2.5:7b). Bei RC_MULTIROOM=false # wird der gesamte Block übersprungen. if [ "$RC_MULTIROOM" = "true" ]; then msg ollama_check # 1. Prüfe: ist Ollama installiert? if command -v ollama >/dev/null 2>&1; then msg ollama_ok else # 2. Ollama nicht gefunden → installieren msg ollama_installing msg ollama_sudo_hint if curl -fsSL https://ollama.com/install.sh | sh 2>/dev/null; then msg ollama_ok else msg ollama_install_fail fi fi # 3. Warte bis Ollama läuft (falls installiert) if command -v ollama >/dev/null 2>&1; then msg ollama_wait sleep 5 # Prüfe ob Ollama-Server antwortet if ! curl -s http://localhost:11434/api/tags >/dev/null 2>&1; then # Server läuft noch nicht — warte länger for i in $(seq 1 6); do sleep 5 if curl -s http://localhost:11434/api/tags >/dev/null 2>&1; then break fi done fi # 4. nomic-embed-text pullen (Pflicht für FAISS-Embeddings, ~270 MB) if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then msg nomic_pull if ollama pull nomic-embed-text 2>/dev/null; then msg nomic_ok else msg nomic_fail fi else msg nomic_ok fi # 5. Optional: qwen2.5:7b pullen (LLM-Stufe 2, ~4.7 GB) if ! ollama list 2>/dev/null | grep -q "qwen2.5:7b"; then msg ollama_qwen_pull if ollama pull qwen2.5:7b 2>/dev/null; then msg ollama_qwen_ok else msg ollama_qwen_fail fi else msg ollama_qwen_ok fi fi else # RC_MULTIROOM=false: Ollama-Prerequisites überspringen echo "ℹ️ Single-Room-Modus — Ollama-Prerequisites übersprungen" fi # ─── Copy plugin files ──────────────────────────────────── SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" PLUGIN_DST="$HERMES_DIR/plugins/rocketchat" mkdir -p "$PLUGIN_DST" # GUARD 1: Syntax-Check VOR Deployment echo "🔍 Running syntax check on Python files..." while read -r pyfile; do if ! python3 -m py_compile "$pyfile" 2>/dev/null; then echo "❌ Syntax error in $pyfile" echo "Deployment aborted due to syntax errors" exit 1 fi done < <(find "$SCRIPT_DIR/plugin" -name "*.py" -type f) echo "✅ All Python files passed syntax check" # Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen if [ -d "$SCRIPT_DIR/plugin" ]; then # Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören # Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur) while read -r src; do rel="${src#$SCRIPT_DIR/plugin/}" dst="$PLUGIN_DST/$rel" mkdir -p "$(dirname "$dst")" cp "$src" "$dst" done < <(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc') copied_count=$(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l) msg copied "$copied_count" # Symlink for core plugin loader: archivar must be importable as top-level module if [ -d "$PLUGIN_DST/plugin/archivar" ]; then ln -sfn "$PLUGIN_DST/plugin/archivar" "$HERMES_DIR/archivar" fi fi # GUARD 2: Vollständigkeits-Check echo "🔍 Running completeness check..." missing_files=() while read -r src; do rel="${src#$SCRIPT_DIR/plugin/}" dst="$PLUGIN_DST/$rel" if [ ! -f "$dst" ]; then missing_files+=("$rel") fi done < <(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc') if [ ${#missing_files[@]} -gt 0 ]; then echo "❌ Missing files detected:" for file in "${missing_files[@]}"; do echo " - $file" done echo "Deployment aborted due to missing files" exit 1 fi echo "✅ All files present in destination" # GUARD 3: Pycache-Löschung NACH Deployment echo "🧹 Cleaning up pycache files..." find "$PLUGIN_DST" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true find "$PLUGIN_DST" -name '*.pyc' -delete 2>/dev/null || true msg cache_cleared # ── FIX: numpy/faiss im venv installieren ────────────────────── # Archivar braucht numpy + faiss für FAISS Phase-1 RoomIndex. # Nur im Multi-Room-Agent-Modus nötig; Single-Room-Bot bleibt schlank. # M9: numpy ist Pflicht, faiss-cpu best-effort (kann auf ARM fehlen). if [ "$RC_MULTIROOM" = "true" ]; then if [ -f "$HERMES_DIR/venv/bin/pip" ]; then "$HERMES_DIR/venv/bin/pip" install numpy 2>&1 | tail -1 "$HERMES_DIR/venv/bin/pip" install faiss-cpu 2>/dev/null || echo "⚠️ faiss-cpu not available (ARM?) — Archivar uses fallback" elif [ -f "$HERMES_DIR/.venv/bin/pip" ]; then "$HERMES_DIR/.venv/bin/pip" install numpy 2>&1 | tail -1 "$HERMES_DIR/.venv/bin/pip" install faiss-cpu 2>/dev/null || echo "⚠️ faiss-cpu not available (ARM?) — Archivar uses fallback" fi fi # ─── FIX: room-map.json bereitstellen ──────────────────────── # room-map.json ist maschinenspezifisch; nur im Multi-Room-Modus deployen. # Die vollständige, maschinen-spezifische Version wird vom RC-Skill- # Onboarding-Flow nach dem Gateway-Start erstellt. if [ "$RC_MULTIROOM" = "true" ]; then ROOM_MAP_DATA_DIR="$HOME/.hermes/hermes-agent/data" mkdir -p "$ROOM_MAP_DATA_DIR" ROOM_MAP_FILE="$ROOM_MAP_DATA_DIR/room-map.json" TEMPLATE_FILE="$SCRIPT_DIR/templates/room-map.json" DEPLOY_TEMPLATE=false if [ ! -f "$ROOM_MAP_FILE" ]; then DEPLOY_TEMPLATE=true elif [ -f "$ROOM_MAP_FILE" ] && [ -f "$TEMPLATE_FILE" ]; then # Bug 5 fix: Prüfe ob die existierende room-map.json das leere Template ist # SICHERHEIT: python3-Verfügbarkeit VOR dem Check prüfen. if command -v python3 >/dev/null 2>&1; then ROOM_COUNT=$(python3 -c " import json try: with open('$ROOM_MAP_FILE') as f: data = json.load(f) rooms = data.get('rooms', {}) print(len(rooms)) except: print(0) " 2>/dev/null || echo "0") else echo " ⚠️ python3 not found — skipping room-map.json check (will NOT overwrite existing data)" ROOM_COUNT="SKIP" fi if [ "$ROOM_COUNT" = "0" ]; then DEPLOY_TEMPLATE=true fi fi if $DEPLOY_TEMPLATE && [ -f "$TEMPLATE_FILE" ]; then cp "$TEMPLATE_FILE" "$ROOM_MAP_FILE" msg room_map_deployed "$ROOM_MAP_FILE" fi fi # ─── Fix #9: Provision minimal config.yaml + .env ────────── # Only when hermes has NO config yet (fresh install, no setup run) HERMES_HOME="$HOME/.hermes" CONFIG="$HERMES_HOME/config.yaml" ENVFILE="$HERMES_HOME/.env" if [ ! -f "$CONFIG" ]; then mkdir -p "$HERMES_HOME" if [ -f "$SCRIPT_DIR/templates/config.yaml" ]; then cp "$SCRIPT_DIR/templates/config.yaml" "$CONFIG" # Placeholders mit übergebenen Werten ersetzen sed -i "s|PLACEHOLDER_RC_URL|${RC_URL}|g" "$CONFIG" sed -i "s|PLACEHOLDER_RC_HOME_NAME|${RC_HOME_CHANNEL}|g" "$CONFIG" sed -i "s|PLACEHOLDER_RC_HOME_CHAT_ID|${RC_HOME_CHANNEL}|g" "$CONFIG" # Modell-Provider nur ersetzen wenn explizit übergeben if [ -n "${OLLAMA_MODEL:-}" ]; then sed -i "s|PLACEHOLDER_MODEL|${OLLAMA_MODEL}|g" "$CONFIG" fi if [ -n "${OLLAMA_PROVIDER:-}" ]; then sed -i "s|PLACEHOLDER_PROVIDER|${OLLAMA_PROVIDER}|g" "$CONFIG" fi if [ -n "${OLLAMA_BASE_URL:-}" ]; then sed -i "s|PLACEHOLDER_MODEL_BASE_URL|${OLLAMA_BASE_URL}|g" "$CONFIG" fi msg config_provisioned fi fi # ─── Fix M4: Hermes-Installer Default-Konfiguration korrigieren ── # Der offizielle Hermes-Installer (curl install.sh) schreibt in die # config.yaml: model.default=anthropic/claude-opus-4.6, model.provider=auto, # base_url=https://openrouter.ai/api/v1. Auf ollama-cloud existiert dieses # Modell nicht (404). Der Plugin-Installer MUSS die config.yaml nachbessern, # selbst wenn bereits eine existiert (Fall: Hermes zuerst installiert, dann # Plugin-Installer). Defaults: OLLAMA_MODEL=glm-5.2, OLLAMA_PROVIDER=ollama-cloud. if [ -f "$CONFIG" ]; then _RC_MODEL="${OLLAMA_MODEL:-glm-5.2}" _RC_PROVIDER="${OLLAMA_PROVIDER:-ollama-cloud}" if grep -q '^[[:space:]]*default:' "$CONFIG" 2>/dev/null; then sed -i "s|^[[:space:]]*default:.*| default: ${_RC_MODEL}|" "$CONFIG" fi if grep -q '^[[:space:]]*provider:' "$CONFIG" 2>/dev/null; then sed -i "s|^[[:space:]]*provider:.*| provider: ${_RC_PROVIDER}|" "$CONFIG" fi # base_url aus der model-Sektion entfernen (gilt nur für OpenRouter, nicht ollama-cloud) # ABER: Nur löschen wenn provider == ollama-cloud (Default). Wenn User explizit # openrouter nutzen will (OLLAMA_PROVIDER=openrouter), base_url BEHALTEN. if grep -q '^[[:space:]]*base_url:.*openrouter' "$CONFIG" 2>/dev/null; then if [ "$_RC_PROVIDER" = "ollama-cloud" ]; then sed -i '/^[[:space:]]*base_url:.*openrouter/d' "$CONFIG" fi elif [ -n "${OLLAMA_BASE_URL:-}" ]; then # Explizit übergebene OLLAMA_BASE_URL setzen statt entfernen if grep -q '^[[:space:]]*base_url:' "$CONFIG" 2>/dev/null; then sed -i "s|^[[:space:]]*base_url:.*| base_url: ${OLLAMA_BASE_URL}|" "$CONFIG" fi fi fi if [ ! -f "$ENVFILE" ] && [ -f "$SCRIPT_DIR/templates/.env" ]; then cp "$SCRIPT_DIR/templates/.env" "$ENVFILE" chmod 600 "$ENVFILE" msg env_provisioned fi # ─── Fix #9b: OLLAMA_API_KEY in ~/.hermes/.env persistieren ─┘ # Secret gehört NICHT in die systemd-Unit, sondern in die .env-Datei. if [ -n "${OLLAMA_API_KEY:-}" ]; then mkdir -p "$HERMES_HOME" touch "$ENVFILE" chmod 600 "$ENVFILE" if grep -q "^OLLAMA_API_KEY=" "$ENVFILE" 2>/dev/null; then # Bestehenden Wert ersetzen (Inline, ohne Backups) sed -i "s|^OLLAMA_API_KEY=.*|OLLAMA_API_KEY=${OLLAMA_API_KEY}|" "$ENVFILE" else # Neu anhängen echo "OLLAMA_API_KEY=${OLLAMA_API_KEY}" >> "$ENVFILE" fi fi 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" # ─── Fix M1: ExecStart benötigt absoluten Pfad ───────────── # systemd erlaubt KEINE relativen Pfade in ExecStart. Bisher wurde # "venv/bin/python" (relativ) geschrieben → Service-Start schlägt fehl. # Lösung: Absoluten Pfad aus $HERMES_DIR ableiten (liefert z.B. # /home/bernd/.hermes/hermes-agent/venv/bin/python). if [ -f "$HERMES_DIR/venv/bin/python" ]; then PYTHON="$HERMES_DIR/venv/bin/python" elif [ -f "$HERMES_DIR/.venv/bin/python" ]; then PYTHON="$HERMES_DIR/.venv/bin/python" else PYTHON="$(command -v python3 || echo python3)" fi # Install / refresh systemd user service $PYTHON -m hermes_cli.main gateway install 2>/dev/null || true # ─── Fix: overwrite generated unit to use "gateway run" ──── # hermes_cli.main gateway install creates a unit with run_agent.py gateway # (AI-agent only, no platform adapter). For Rocket.Chat we NEED the full # gateway run (hermes_cli.main gateway run) which loads platform plugins. UNIT_FILE="$HOME/.config/systemd/user/hermes-gateway.service" if [ -f "$UNIT_FILE" ]; then # Replace ExecStart to use "gateway run" instead of "run_agent.py gateway" # $PYTHON ist jetzt absolut (siehe Fix M1 oben). sed -i 's|ExecStart=.*|ExecStart='"$PYTHON"' -m hermes_cli.main gateway run|' "$UNIT_FILE" systemctl --user daemon-reload 2>/dev/null || true fi # ─── Fix #10: systemd EnvironmentFile drop-in ───────────── # Gateway needs rocketchat.env + .env — hermes gateway install # does not wire them automatically. DROPDIN_DIR="$HOME/.config/systemd/user/hermes-gateway.service.d" DROPDIN_FILE="$DROPDIN_DIR/env.conf" mkdir -p "$DROPDIN_DIR" if [ -f "$SCRIPT_DIR/templates/hermes-gateway-env.conf" ]; then cp "$SCRIPT_DIR/templates/hermes-gateway-env.conf" "$DROPDIN_FILE" # M7: PYTHONPATH für Plugin-Module (Archivar, RC-Skill etc.) echo "Environment=PYTHONPATH=${HERMES_DIR}/plugins/rocketchat" >> "$DROPDIN_FILE" msg env_dropin fi # Multi-Room-Flag als Environment-Variable im Drop-in setzen # (Drop-in überlebt 'hermes gateway install', Haupt-Unit wird überschrieben) if grep -q "^Environment=MULTIROOM_AGENT=" "$DROPDIN_FILE" 2>/dev/null; then sed -i "s|^Environment=MULTIROOM_AGENT=.*|Environment=MULTIROOM_AGENT=${RC_MULTIROOM}|" "$DROPDIN_FILE" else echo "Environment=MULTIROOM_AGENT=${RC_MULTIROOM}" >> "$DROPDIN_FILE" fi # Ensure lingering is enabled (may need sudo — best-effort) loginctl enable-linger 2>/dev/null || true msg service_installed # ─── Restart gateway (mit State-Cleanup gegen Discovery-Bug + Auto-Resume-Loop) ── msg restarting systemctl --user daemon-reload 2>/dev/null || true # State-Cleanup: Verhindert Discovery-Bug (Platform-Verlust nach SIGTERM) # und Auto-Resume-Crash-Loop (restart-interrupted sessions triggern Kill) rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" "$HOME/.hermes/.gateway_state_*.tmp" 2>/dev/null || true systemctl --user reset-failed hermes-gateway 2>/dev/null || true systemctl --user enable hermes-gateway 2>/dev/null || true # Gateway stoppen (mit Timeout — kann bis 60s dauern) systemctl --user stop hermes-gateway 2>/dev/null || true stop_wait=0 # Fix M2: 'local' removed — not inside a function (Bash-Syntaxfehler) while systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $stop_wait -lt 60 ]; do sleep 2 stop_wait=$((stop_wait + 2)) done # Gateway starten systemctl --user start hermes-gateway 2>/dev/null || true msg done echo