Compare commits
10 Commits
4d6fae6bf7
...
9be9e616d1
| Author | SHA1 | Date | |
|---|---|---|---|
| 9be9e616d1 | |||
| bc7b05d768 | |||
| 6f47885b1c | |||
| 572bc89205 | |||
| 54de0d1b69 | |||
| 868ee153ac | |||
| 40563864ac | |||
| 5c8026c0f0 | |||
| 52dd470e00 | |||
| a442e42b4e |
+89
-6
@@ -13,6 +13,7 @@ CHECK_ONLY=false
|
|||||||
UPDATE_MODE=false
|
UPDATE_MODE=false
|
||||||
UPDATE_ONLY=false
|
UPDATE_ONLY=false
|
||||||
UPDATE_AVAILABLE=false
|
UPDATE_AVAILABLE=false
|
||||||
|
RC_MULTIROOM="false"
|
||||||
|
|
||||||
# ─── Language packs ─────────────────────────────────────────
|
# ─── Language packs ─────────────────────────────────────────
|
||||||
declare -A T
|
declare -A T
|
||||||
@@ -38,6 +39,8 @@ load_lang() {
|
|||||||
[enter_botuser]="Bot Username (the bot account on the Rocket.Chat server)"
|
[enter_botuser]="Bot Username (the bot account on the Rocket.Chat server)"
|
||||||
[enter_botpass]="Bot Password"
|
[enter_botpass]="Bot Password"
|
||||||
[enter_channel]="Home Channel (name or room ID, e.g. #ki-assistent or 69f4e…)"
|
[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"
|
[current_val]=" Current: %s"
|
||||||
[new_val]=" → "
|
[new_val]=" → "
|
||||||
[summary]="📋 Configuration Summary:"
|
[summary]="📋 Configuration Summary:"
|
||||||
@@ -94,6 +97,8 @@ load_lang() {
|
|||||||
[enter_botuser]="Bot Username (der Bot-Account auf dem Rocket.Chat Server)"
|
[enter_botuser]="Bot Username (der Bot-Account auf dem Rocket.Chat Server)"
|
||||||
[enter_botpass]="Bot Passwort"
|
[enter_botpass]="Bot Passwort"
|
||||||
[enter_channel]="Home Channel (Name oder Raum-ID, z.B. #ki-assistent oder 69f4e…)"
|
[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"
|
[current_val]=" Aktuell: %s"
|
||||||
[new_val]=" → "
|
[new_val]=" → "
|
||||||
[summary]="📋 Zusammenfassung der Konfiguration:"
|
[summary]="📋 Zusammenfassung der Konfiguration:"
|
||||||
@@ -334,7 +339,7 @@ perform_update() {
|
|||||||
hermes_dir=$(find_hermes_dir 2>/dev/null || echo "")
|
hermes_dir=$(find_hermes_dir 2>/dev/null || echo "")
|
||||||
|
|
||||||
if [ -n "$hermes_dir" ]; then
|
if [ -n "$hermes_dir" ]; then
|
||||||
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
local plugin_dir="$hermes_dir/plugins/rocketchat"
|
||||||
local config_file="$HOME/.hermes/config.yaml"
|
local config_file="$HOME/.hermes/config.yaml"
|
||||||
local env_file="$HOME/.config/hermes/rocketchat.env"
|
local env_file="$HOME/.config/hermes/rocketchat.env"
|
||||||
create_backup "$backup_file" "$plugin_dir" "$config_file" "$env_file"
|
create_backup "$backup_file" "$plugin_dir" "$config_file" "$env_file"
|
||||||
@@ -347,7 +352,7 @@ perform_update() {
|
|||||||
git pull origin main 2>&1 || { update_error="Failed to pull from origin main"; return 1; }
|
git pull origin main 2>&1 || { update_error="Failed to pull from origin main"; return 1; }
|
||||||
|
|
||||||
# Copy plugin files directly (lines 448-466)
|
# Copy plugin files directly (lines 448-466)
|
||||||
PLUGIN_DST="$hermes_dir/plugins/platforms/rocketchat"
|
PLUGIN_DST="$hermes_dir/plugins/rocketchat"
|
||||||
mkdir -p "$PLUGIN_DST"
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
||||||
@@ -363,10 +368,24 @@ perform_update() {
|
|||||||
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
msg copied "$copied_count"
|
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
|
# NOTE: room-map.json is MACHINE-SPECIFIC — never deployed
|
||||||
# by the installer. It is created by the RC-Skill onboarding
|
# by the installer. It is created by the RC-Skill onboarding
|
||||||
# flow after gateway start. See RC-Skill: "Room Topic Discipline"
|
# flow after gateway start. See RC-Skill: "Room Topic Discipline"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# ── FIX: numpy/faiss im venv installieren ──────────────────────
|
||||||
|
# Archivar braucht numpy + faiss für FAISS Phase-1 RoomIndex.
|
||||||
|
# Ohne diese Packages crasht der Import beim Gateway-Start.
|
||||||
|
if [ -f "$hermes_dir/venv/bin/pip" ]; then
|
||||||
|
"$hermes_dir/venv/bin/pip" install numpy faiss-cpu 2>&1 | tail -1
|
||||||
|
elif [ -f "$hermes_dir/.venv/bin/pip" ]; then
|
||||||
|
"$hermes_dir/.venv/bin/pip" install numpy faiss-cpu 2>&1 | tail -1
|
||||||
|
fi
|
||||||
|
|
||||||
# Execute backend checks directly (Ollama check from lines 429-446)
|
# Execute backend checks directly (Ollama check from lines 429-446)
|
||||||
msg ollama_check
|
msg ollama_check
|
||||||
@@ -463,7 +482,7 @@ perform_update_only() {
|
|||||||
|
|
||||||
# 2. Backup current state
|
# 2. Backup current state
|
||||||
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
||||||
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
local plugin_dir="$hermes_dir/plugins/rocketchat"
|
||||||
if [ -d "$plugin_dir" ]; then
|
if [ -d "$plugin_dir" ]; then
|
||||||
create_backup "$backup_file" "$plugin_dir" \
|
create_backup "$backup_file" "$plugin_dir" \
|
||||||
"$HOME/.hermes/config.yaml" \
|
"$HOME/.hermes/config.yaml" \
|
||||||
@@ -472,7 +491,7 @@ perform_update_only() {
|
|||||||
|
|
||||||
# 3. Deploy all plugin files
|
# 3. Deploy all plugin files
|
||||||
msg deploying
|
msg deploying
|
||||||
local PLUGIN_DST="$hermes_dir/plugins/platforms/rocketchat"
|
local PLUGIN_DST="$hermes_dir/plugins/rocketchat"
|
||||||
mkdir -p "$PLUGIN_DST"
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
# GUARD 1: Syntax-Check VOR Deployment
|
# GUARD 1: Syntax-Check VOR Deployment
|
||||||
@@ -517,6 +536,11 @@ perform_update_only() {
|
|||||||
local copied_count
|
local copied_count
|
||||||
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
msg deploy_done "$copied_count" "$PLUGIN_DST"
|
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
|
else
|
||||||
msg update_failed "plugin/ directory not found in $script_dir"
|
msg update_failed "plugin/ directory not found in $script_dir"
|
||||||
return 1
|
return 1
|
||||||
@@ -528,6 +552,15 @@ perform_update_only() {
|
|||||||
find "$PLUGIN_DST" -name '*.pyc' -delete 2>/dev/null || true
|
find "$PLUGIN_DST" -name '*.pyc' -delete 2>/dev/null || true
|
||||||
msg cache_cleared
|
msg cache_cleared
|
||||||
|
|
||||||
|
# ── FIX: numpy/faiss im venv installieren ──────────────────────
|
||||||
|
# Archivar braucht numpy + faiss für FAISS Phase-1 RoomIndex.
|
||||||
|
# Ohne diese Packages crasht der Import beim Gateway-Start.
|
||||||
|
if [ -f "$hermes_dir/venv/bin/pip" ]; then
|
||||||
|
"$hermes_dir/venv/bin/pip" install numpy faiss-cpu 2>&1 | tail -1
|
||||||
|
elif [ -f "$hermes_dir/.venv/bin/pip" ]; then
|
||||||
|
"$hermes_dir/.venv/bin/pip" install numpy faiss-cpu 2>&1 | tail -1
|
||||||
|
fi
|
||||||
|
|
||||||
# NOTE: room-map.json is MACHINE-SPECIFIC — never deployed
|
# NOTE: room-map.json is MACHINE-SPECIFIC — never deployed
|
||||||
# by --update-only. It is created by the RC-Skill onboarding
|
# by --update-only. It is created by the RC-Skill onboarding
|
||||||
# flow after gateway start. See RC-Skill: "Room Topic Discipline"
|
# flow after gateway start. See RC-Skill: "Room Topic Discipline"
|
||||||
@@ -674,6 +707,7 @@ if $NONINTERACTIVE; then
|
|||||||
RC_BOT_USER="${RC_BOT_USER:-${ROCKETCHAT_USER:-}}"
|
RC_BOT_USER="${RC_BOT_USER:-${ROCKETCHAT_USER:-}}"
|
||||||
RC_BOT_PASS="${RC_BOT_PASS:-${ROCKETCHAT_PASSWORD:-}}"
|
RC_BOT_PASS="${RC_BOT_PASS:-${ROCKETCHAT_PASSWORD:-}}"
|
||||||
RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-${ROCKETCHAT_ROOM_NAME:-}}"
|
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
|
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
|
||||||
msg env_required; exit 1
|
msg env_required; exit 1
|
||||||
fi
|
fi
|
||||||
@@ -689,11 +723,22 @@ else
|
|||||||
confirm_or_edit RC_BOT_PASS enter_botpass ""
|
confirm_or_edit RC_BOT_PASS enter_botpass ""
|
||||||
confirm_or_edit RC_HOME_CHANNEL enter_channel "$RC_HOME_CHANNEL"
|
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
|
echo
|
||||||
msg summary
|
msg summary
|
||||||
echo " URL: $RC_URL"
|
echo " URL: $RC_URL"
|
||||||
echo " Bot User: $RC_BOT_USER"
|
echo " Bot User: $RC_BOT_USER"
|
||||||
echo " Home Channel: $RC_HOME_CHANNEL"
|
echo " Home Channel: $RC_HOME_CHANNEL"
|
||||||
|
echo " Multi-Room: $RC_MULTIROOM"
|
||||||
echo
|
echo
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -713,9 +758,10 @@ ROCKETCHAT_ALLOW_ALL_USERS=true
|
|||||||
GATEWAY_ALLOW_ALL_USERS=true
|
GATEWAY_ALLOW_ALL_USERS=true
|
||||||
ROCKETCHAT_PING_SEC=8
|
ROCKETCHAT_PING_SEC=8
|
||||||
ROCKETCHAT_IDLE_SEC=900
|
ROCKETCHAT_IDLE_SEC=900
|
||||||
|
RC_MULTIROOM=PLACEHOLDER_RC_MULTIROOM
|
||||||
EOF
|
EOF
|
||||||
# Ersetze Platzhalter mit python3 (sicher für $-Zeichen im Passwort)
|
# Ersetze Platzhalter mit python3 (sicher für $-Zeichen im Passwort)
|
||||||
export RC_URL RC_BOT_USER RC_BOT_PASS RC_HOME_CHANNEL
|
export RC_URL RC_BOT_USER RC_BOT_PASS RC_HOME_CHANNEL RC_MULTIROOM
|
||||||
export ENV_FILE
|
export ENV_FILE
|
||||||
python3 -c "
|
python3 -c "
|
||||||
import os
|
import os
|
||||||
@@ -726,6 +772,7 @@ 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_USER', os.environ.get('RC_BOT_USER', ''))
|
||||||
content = content.replace('PLACEHOLDER_RC_PASS', os.environ.get('RC_BOT_PASS', ''))
|
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_CHANNEL', os.environ.get('RC_HOME_CHANNEL', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_MULTIROOM', os.environ.get('RC_MULTIROOM', 'false'))
|
||||||
with open(env_file, 'w') as f:
|
with open(env_file, 'w') as f:
|
||||||
f.write(content)
|
f.write(content)
|
||||||
"
|
"
|
||||||
@@ -753,7 +800,7 @@ fi
|
|||||||
|
|
||||||
# ─── Copy plugin files ────────────────────────────────────
|
# ─── Copy plugin files ────────────────────────────────────
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
|
PLUGIN_DST="$HERMES_DIR/plugins/rocketchat"
|
||||||
mkdir -p "$PLUGIN_DST"
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
# GUARD 1: Syntax-Check VOR Deployment
|
# GUARD 1: Syntax-Check VOR Deployment
|
||||||
@@ -779,6 +826,11 @@ if [ -d "$SCRIPT_DIR/plugin" ]; then
|
|||||||
done < <(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
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)
|
copied_count=$(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
msg copied "$copied_count"
|
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
|
fi
|
||||||
|
|
||||||
# GUARD 2: Vollständigkeits-Check
|
# GUARD 2: Vollständigkeits-Check
|
||||||
@@ -808,6 +860,26 @@ find "$PLUGIN_DST" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null ||
|
|||||||
find "$PLUGIN_DST" -name '*.pyc' -delete 2>/dev/null || true
|
find "$PLUGIN_DST" -name '*.pyc' -delete 2>/dev/null || true
|
||||||
msg cache_cleared
|
msg cache_cleared
|
||||||
|
|
||||||
|
# ── FIX: numpy/faiss im venv installieren ──────────────────────
|
||||||
|
# Archivar braucht numpy + faiss für FAISS Phase-1 RoomIndex.
|
||||||
|
# Ohne diese Packages crasht der Import beim Gateway-Start.
|
||||||
|
if [ -f "$HERMES_DIR/venv/bin/pip" ]; then
|
||||||
|
"$HERMES_DIR/venv/bin/pip" install numpy faiss-cpu 2>&1 | tail -1
|
||||||
|
elif [ -f "$HERMES_DIR/.venv/bin/pip" ]; then
|
||||||
|
"$HERMES_DIR/.venv/bin/pip" install numpy faiss-cpu 2>&1 | tail -1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ─── FIX: room-map.json bereitstellen ────────────────────────
|
||||||
|
# Der Installer stellt eine minimale room-map.json ins Datenverzeichnis.
|
||||||
|
# Die vollständige, maschinen-spezifische Version wird vom RC-Skill-
|
||||||
|
# Onboarding-Flow nach dem Gateway-Start erstellt.
|
||||||
|
ROOM_MAP_DATA_DIR="$HOME/.hermes/hermes-agent/data"
|
||||||
|
mkdir -p "$ROOM_MAP_DATA_DIR"
|
||||||
|
if [ ! -f "$ROOM_MAP_DATA_DIR/room-map.json" ] && [ -f "$SCRIPT_DIR/templates/room-map.json" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/room-map.json" "$ROOM_MAP_DATA_DIR/room-map.json"
|
||||||
|
msg room_map_deployed "$ROOM_MAP_DATA_DIR/room-map.json"
|
||||||
|
fi
|
||||||
|
|
||||||
# ─── Fix #9: Provision minimal config.yaml + .env ──────────
|
# ─── Fix #9: Provision minimal config.yaml + .env ──────────
|
||||||
# Only when hermes has NO config yet (fresh install, no setup run)
|
# Only when hermes has NO config yet (fresh install, no setup run)
|
||||||
HERMES_HOME="$HOME/.hermes"
|
HERMES_HOME="$HOME/.hermes"
|
||||||
@@ -867,6 +939,17 @@ fi
|
|||||||
# Install / refresh systemd user service
|
# Install / refresh systemd user service
|
||||||
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
|
$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"
|
||||||
|
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 ─────────────
|
# ─── Fix #10: systemd EnvironmentFile drop-in ─────────────
|
||||||
# Gateway needs rocketchat.env + .env — hermes gateway install
|
# Gateway needs rocketchat.env + .env — hermes gateway install
|
||||||
# does not wire them automatically.
|
# does not wire them automatically.
|
||||||
|
|||||||
@@ -102,6 +102,8 @@ def is_connected(config) -> bool:
|
|||||||
|
|
||||||
def register(ctx):
|
def register(ctx):
|
||||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||||
|
_MULTIROOM = os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||||
|
|
||||||
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
||||||
from .tools import register_tools
|
from .tools import register_tools
|
||||||
|
|
||||||
|
|||||||
+99
-67
@@ -35,7 +35,12 @@ class RocketChatRateLimitError(Exception):
|
|||||||
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {thematic_target, origin_room}
|
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {thematic_target, origin_room}
|
||||||
_room_context_lock = threading.Lock()
|
_room_context_lock = threading.Lock()
|
||||||
|
|
||||||
from archivar.adapter_integration import ArchivarMessageHandler
|
def _MULTIROOM() -> bool:
|
||||||
|
"""Laufzeit-Auswertung von MULTIROOM_AGENT (nicht beim Import, da .env via systemd EnvironmentFile erst später geladen wird)."""
|
||||||
|
return os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||||
|
|
||||||
|
if _MULTIROOM():
|
||||||
|
from archivar.adapter_integration import ArchivarMessageHandler
|
||||||
|
|
||||||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||||||
import sys as _sys
|
import sys as _sys
|
||||||
@@ -478,10 +483,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._last_ddp_ping_ok = False
|
self._last_ddp_ping_ok = False
|
||||||
self._running = False
|
self._running = False
|
||||||
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||||||
self.archivar = ArchivarMessageHandler(
|
if _MULTIROOM():
|
||||||
send_callback=self._send_via_archivar,
|
self.archivar = ArchivarMessageHandler(
|
||||||
button_send_callback=self._send_archivar_buttons,
|
send_callback=self._send_via_archivar,
|
||||||
)
|
button_send_callback=self._send_archivar_buttons,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.archivar = None
|
||||||
# User-Flow C: Move-Requests + Sticky Rooms
|
# User-Flow C: Move-Requests + Sticky Rooms
|
||||||
self._pending_move_requests: Dict[str, dict] = {}
|
self._pending_move_requests: Dict[str, dict] = {}
|
||||||
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
||||||
@@ -592,23 +600,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
len(self._user_rooms),
|
len(self._user_rooms),
|
||||||
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
||||||
# Archivar initialisieren (Embedding-basierte Klassifikation)
|
# Archivar initialisieren (Embedding-basierte Klassifikation)
|
||||||
try:
|
if _MULTIROOM() and self.archivar is not None:
|
||||||
await self.archivar.initialize()
|
try:
|
||||||
# Feed the actual subscribed room IDs to the router so it can
|
await self.archivar.initialize()
|
||||||
# validate targets and store unrouteable messages in doc_store.
|
# Feed the actual subscribed room IDs to the router so it can
|
||||||
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
# validate targets and store unrouteable messages in doc_store.
|
||||||
logger.info("[rocketchat] Archivar initialisiert — Thematischer Raum-Router aktiv (room-map.json)")
|
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||||||
|
logger.info("[rocketchat] Archivar initialisiert — Thematischer Raum-Router aktiv (room-map.json)")
|
||||||
# Auto-Onboarding: Prüfe, ob alle subscribed Räume in der Map sind
|
|
||||||
subscribed_with_types = {
|
# Auto-Onboarding: Prüfe, ob alle subscribed Räume in der Map sind
|
||||||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
subscribed_with_types = {
|
||||||
for rid, info in self._room_info.items()
|
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||||||
}
|
for rid, info in self._room_info.items()
|
||||||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
}
|
||||||
if missing:
|
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||||||
await self._start_onboarding(missing)
|
if missing:
|
||||||
except Exception as e:
|
await self._start_onboarding(missing)
|
||||||
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
except Exception as e:
|
||||||
|
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||||||
self._mark_connected()
|
self._mark_connected()
|
||||||
self._running = True
|
self._running = True
|
||||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||||
@@ -704,10 +713,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Skip own messages (case-insensitive comparison)
|
# Skip own messages (case-insensitive comparison)
|
||||||
filter_match = (username == (self.user or "").lower())
|
filter_match = (username == (self.user or "").lower())
|
||||||
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
||||||
if filter_match or not text or not room_id:
|
if filter_match:
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Own message filtered — skipping")
|
||||||
|
return
|
||||||
|
if not text or not room_id:
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Empty text/room_id — skipping")
|
||||||
return
|
return
|
||||||
# Skip system messages
|
# Skip system messages
|
||||||
if msg_obj.get("t"):
|
if msg_obj.get("t"):
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: System message (t=%s) — skipping", msg_obj.get("t"))
|
||||||
return
|
return
|
||||||
|
|
||||||
logger.debug("Message passed filter: %s", msg_id)
|
logger.debug("Message passed filter: %s", msg_id)
|
||||||
@@ -736,6 +750,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
parts = text.split(":", 2)
|
parts = text.split(":", 2)
|
||||||
if len(parts) != 3:
|
if len(parts) != 3:
|
||||||
logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text)
|
logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text)
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping")
|
||||||
return
|
return
|
||||||
_, clarify_id, choice = parts
|
_, clarify_id, choice = parts
|
||||||
if choice == "other":
|
if choice == "other":
|
||||||
@@ -743,6 +758,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
from tools.clarify_gateway import mark_awaiting_text
|
from tools.clarify_gateway import mark_awaiting_text
|
||||||
mark_awaiting_text(clarify_id)
|
mark_awaiting_text(clarify_id)
|
||||||
logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username)
|
logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username)
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY other — awaiting text")
|
||||||
# Don't process further - wait for the next text message
|
# Don't process further - wait for the next text message
|
||||||
return
|
return
|
||||||
elif choice.isdigit():
|
elif choice.isdigit():
|
||||||
@@ -774,6 +790,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
|
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
|
||||||
# Don't route to agent — this was a button click
|
# Don't route to agent — this was a button click
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY resolved — skipping")
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
# Unknown token — let it fall through as regular text
|
# Unknown token — let it fall through as regular text
|
||||||
@@ -782,7 +799,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.debug("[rocketchat] Error processing CLARIFY response: %s", e)
|
logger.debug("[rocketchat] Error processing CLARIFY response: %s", e)
|
||||||
|
|
||||||
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
||||||
if self.archivar._stats.get("onboarding_active", False):
|
if _MULTIROOM() and self.archivar is not None and self.archivar._stats.get("onboarding_active", False):
|
||||||
stripped = text.strip()
|
stripped = text.strip()
|
||||||
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
|
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
|
||||||
operator_room = self._onboarding_state.get("operator_room_id", "")
|
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||||||
@@ -798,6 +815,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
)
|
)
|
||||||
if is_onboarding:
|
if is_onboarding:
|
||||||
await self._process_onboarding_response(text, room_id)
|
await self._process_onboarding_response(text, room_id)
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping")
|
||||||
return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig
|
return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig
|
||||||
|
|
||||||
# ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ────────
|
# ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ────────
|
||||||
@@ -851,13 +869,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
feedback_type = "stay"
|
feedback_type = "stay"
|
||||||
|
|
||||||
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
|
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
|
||||||
if move_req.get("message_id"):
|
if _MULTIROOM() and self.archivar is not None and move_req.get("message_id"):
|
||||||
user_id = user_info.get("_id", "")
|
user_id = user_info.get("_id", "")
|
||||||
await self.archivar.handle_feedback_response(
|
await self.archivar.handle_feedback_response(
|
||||||
message_id=move_req["message_id"],
|
message_id=move_req["message_id"],
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
feedback_type=feedback_type
|
feedback_type=feedback_type
|
||||||
)
|
)
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Move-Request processed — skipping")
|
||||||
return # Move-Request verarbeitet — keine weitere Verarbeitung
|
return # Move-Request verarbeitet — keine weitere Verarbeitung
|
||||||
|
|
||||||
forwarded = False
|
forwarded = False
|
||||||
@@ -870,53 +889,66 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
decision = None
|
decision = None
|
||||||
is_auftrag = _is_auftrag(text)
|
is_auftrag = _is_auftrag(text)
|
||||||
|
|
||||||
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if is_button_response or room_id in self._rooms_with_pending_questions:
|
if _MULTIROOM() and self.archivar is not None:
|
||||||
if not is_button_response:
|
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||||||
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
if not is_button_response:
|
||||||
self._rooms_with_pending_questions.discard(room_id)
|
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||||||
elif room_id in self._sticky_rooms:
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions")
|
||||||
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
|
self._rooms_with_pending_questions.discard(room_id)
|
||||||
elif room_type == "d" and is_auftrag:
|
elif room_id in self._sticky_rooms:
|
||||||
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
|
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
|
||||||
else:
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — sticky_room=%s", room_id[:8])
|
||||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
elif room_type == "d" and is_auftrag:
|
||||||
if decision and decision.category:
|
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
|
||||||
category = decision.category
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — DM-Auftrag")
|
||||||
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
else:
|
||||||
if hasattr(decision, 'target_room') and decision.target_room:
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12])
|
||||||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||||
global _question_counter
|
if decision and decision.category:
|
||||||
with _question_counter_lock:
|
category = decision.category
|
||||||
_question_counter += 1
|
# Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request
|
||||||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
# MUSS VOR _THEMATIC_TARGET_ROOM.set() kommen, sonst wird
|
||||||
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
# der Zielraum gesetzt und send() routet in den DM
|
||||||
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
|
if (hasattr(decision, 'target_room') and decision.target_room
|
||||||
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
|
and decision.target_room == room_id):
|
||||||
if (getattr(decision, 'move_request_sent', False)
|
decision.stay_in_room = True
|
||||||
and hasattr(decision, 'target_room')
|
decision.move_request_sent = False
|
||||||
and decision.target_room):
|
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
||||||
self._pending_move_requests[room_id] = {
|
if hasattr(decision, 'target_room') and decision.target_room:
|
||||||
'text': text,
|
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||||||
'origin_room': room_id,
|
global _question_counter
|
||||||
'target_room': decision.target_room,
|
with _question_counter_lock:
|
||||||
'target_name': getattr(
|
_question_counter += 1
|
||||||
decision, 'move_request_target_name', 'Zielraum'),
|
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||||||
'username': username,
|
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
||||||
'message_id': msg_id,
|
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
|
||||||
}
|
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
|
||||||
# Lernsystem: Keywords für Feedback-Loop speichern
|
if (getattr(decision, 'move_request_sent', False)
|
||||||
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
|
and hasattr(decision, 'target_room')
|
||||||
self.archivar._routed_messages[msg_id] = {
|
and decision.target_room):
|
||||||
"keywords": decision.matched_keywords,
|
self._pending_move_requests[room_id] = {
|
||||||
"target_room": decision.target_room,
|
'text': text,
|
||||||
"timestamp": time.time()
|
'origin_room': room_id,
|
||||||
}
|
'target_room': decision.target_room,
|
||||||
|
'target_name': getattr(
|
||||||
|
decision, 'move_request_target_name', 'Zielraum'),
|
||||||
|
'username': username,
|
||||||
|
'message_id': msg_id,
|
||||||
|
}
|
||||||
|
# Lernsystem: Keywords für Feedback-Loop speichern
|
||||||
|
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
|
||||||
|
self.archivar._routed_messages[msg_id] = {
|
||||||
|
"keywords": decision.matched_keywords,
|
||||||
|
"target_room": decision.target_room,
|
||||||
|
"timestamp": time.time()
|
||||||
|
}
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
|
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
|
||||||
with _question_counter_lock:
|
with _question_counter_lock:
|
||||||
_question_counter += 1
|
_question_counter += 1
|
||||||
# _THEMATIC_TARGET_ROOM bleibt leer → Prompt sagt "Timeout"
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||||
|
|
||||||
|
|||||||
@@ -93,13 +93,6 @@ except ImportError:
|
|||||||
from .seed_data import SEED_DATA
|
from .seed_data import SEED_DATA
|
||||||
from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult
|
from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult
|
||||||
|
|
||||||
# ── _room_context import from adapter.py ─────────────────────────────
|
|
||||||
# Needed by handle_feedback_response to clear thematic_target on 'stay'.
|
|
||||||
try:
|
|
||||||
from adapter import _room_context, _room_context_lock
|
|
||||||
except ImportError:
|
|
||||||
from ..adapter import _room_context, _room_context_lock
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
# Ensure adapter_integration logs are visible by adding a stderr handler
|
# Ensure adapter_integration logs are visible by adding a stderr handler
|
||||||
@@ -898,6 +891,12 @@ class ArchivarMessageHandler:
|
|||||||
# geleert werden, damit der nächste Send nicht auf den falschen
|
# geleert werden, damit der nächste Send nicht auf den falschen
|
||||||
# (Archivar-vorgeschlagenen) Zielraum fällt.
|
# (Archivar-vorgeschlagenen) Zielraum fällt.
|
||||||
if feedback_type == "stay" and username:
|
if feedback_type == "stay" and username:
|
||||||
|
# Lazy import to break circular dependency with adapter.py
|
||||||
|
try:
|
||||||
|
from adapter import _room_context, _room_context_lock
|
||||||
|
except ImportError:
|
||||||
|
from ..adapter import _room_context, _room_context_lock
|
||||||
|
|
||||||
virtual_chat_id = f"user:{username}"
|
virtual_chat_id = f"user:{username}"
|
||||||
with _room_context_lock:
|
with _room_context_lock:
|
||||||
ctx = _room_context.setdefault(virtual_chat_id, {})
|
ctx = _room_context.setdefault(virtual_chat_id, {})
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {},
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": "/data/Wissensdatenbank/0100 Inbox"
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user