573335cc8d
PresenceEngine: - Neues State-Feld _clarification_pending: Set[str] - Methoden set_clarification_pending(room_id) / clear_clarification_pending(room_id) - Neuer Priority-Slot 3b in update_presence(): nach Move-Request, vor Active-Tasks - _format_presence_message: neuer Status 'away_clarification' → 'Klärung läuft — wartet auf Antwort' ArchivarMessageHandler: - set_presence_engine() Setter für PresenceEngine-Referenz - _send_clarify: set_clarification_pending VOR send, clear im finally (try/finally) adapter.py: - set_presence_engine() nach PresenceEngine-Init aufgerufen (Z.821) 5 neue Tests: TestPresenceClarificationPending
6616 lines
330 KiB
Python
6616 lines
330 KiB
Python
"""
|
||
Rocket.Chat Platform Adapter for Hermes Agent.
|
||
|
||
Plugin-based gateway adapter connecting to a self-hosted Rocket.Chat server.
|
||
Uses WebSocket/DDP for real-time incoming messages + presence,
|
||
and REST API for sending replies.
|
||
|
||
Zero external dependencies — stdlib only.
|
||
"""
|
||
|
||
import asyncio
|
||
import contextvars
|
||
import json
|
||
import logging
|
||
import os
|
||
import queue
|
||
import random
|
||
import re
|
||
import signal
|
||
import socket
|
||
import ssl
|
||
import struct
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
import urllib.error
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
|
||
class RocketChatRateLimitError(Exception):
|
||
"""HTTP 429 Too Many Requests from Rocket.Chat REST API."""
|
||
pass
|
||
|
||
# ── Room context (global dict statt ContextVar — ContextVars sind asyncio-task-lokal,
|
||
# aber der Agent läuft in einem separaten Task und sieht sie nicht) ──
|
||
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {thematic_target, origin_room}
|
||
_room_context_lock = threading.Lock()
|
||
|
||
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
|
||
from archivar.conversation_history import ConversationHistory
|
||
from archivar.multiroom_context import MultiRoomContextRing
|
||
from archivar.router import room_name_to_topic
|
||
|
||
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
||
from archivar.routing_counter import routing_counter
|
||
from archivar.routing_telemetry import routing_telemetry
|
||
|
||
# P0: Reply-Quote-Stripping — verhindert Fehl-Routing durch zitierte Parent-Nachrichten
|
||
from archivar.reply_quote_stripper import strip_reply_quote_for_routing
|
||
|
||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||
import sys as _sys
|
||
_init_module = _sys.modules.get('rocketchat')
|
||
if _init_module is None:
|
||
_init_module = _sys.modules.get(__name__)
|
||
_TEMPLATE_MAP = getattr(_init_module, '_TEMPLATE_MAP', {})
|
||
_build_custom_buttons = getattr(_init_module, '_build_custom_buttons',
|
||
lambda labels, prefix='', style='default': [])
|
||
|
||
logger = logging.getLogger(__name__)
|
||
logger.setLevel(logging.DEBUG) # DEBUG für 24h-Stabilitätstest (19.06.2026)
|
||
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
||
if not logger.handlers:
|
||
_handler = logging.StreamHandler()
|
||
_handler.setLevel(logging.DEBUG)
|
||
_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
|
||
logger.addHandler(_handler)
|
||
logger.propagate = False # Don't double-log to root
|
||
|
||
# ── Virtual Room Translation ──────────────────────────────────────────
|
||
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
|
||
# agent turn, so send() can route the response back to the correct room even
|
||
# though the Hermes session uses a synthetic user-based chat_id.
|
||
# This is the mechanism that makes "one agent for all rooms" work
|
||
# without touching Hermes Core.
|
||
#
|
||
# V8.1.1 R4: _CURRENT_ORIGIN_ROOM ist eine ContextVar — sie wird bei jedem
|
||
# neuen Turn (handle_message-Aufruf) zurückgesetzt. Der Wert lebt nur für
|
||
# die Dauer eines einzelnen Agent-Turns und wird NICHT zwischen Turns
|
||
# persistiert. Das verhindert, dass der Zielraum einer vorherigen Nachricht
|
||
# an der aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im
|
||
# Projektraum). Reset erfolgt implizit durch ContextVar-Semantik: jeder
|
||
# asyncio-Task hat seinen eigenen Context, und handle_message setzt den
|
||
# Wert explizit neu (entweder auf Zielraum bei Move/Auto-Route oder auf
|
||
# den Ursprungsraum bei stay_in_room).
|
||
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||
"_rocketchat_origin_room", default=""
|
||
)
|
||
|
||
_THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||
"_rocketchat_thematic_target_room", default=""
|
||
)
|
||
|
||
# ── V8.4: Red Flag — Pending State ──────────────────────────────────────
|
||
# ContextVar für den Pre-Dispatch-Hook: Wenn der Archivar Red Flag setzt,
|
||
# wird der Prompt hier gespeichert. send() prüft diesen State und parsed
|
||
# ROOM: aus der Agent-Antwort.
|
||
_RED_FLAG_PENDING: contextvars.ContextVar[dict] = contextvars.ContextVar(
|
||
"_rocketchat_red_flag_pending", default={}
|
||
)
|
||
|
||
# Globaler Monoton-Zähler für Archivar-Fragen
|
||
import threading
|
||
_question_counter: int = 0
|
||
_question_counter_lock: threading.Lock = threading.Lock()
|
||
|
||
try:
|
||
from gateway.platforms.base import (
|
||
BasePlatformAdapter,
|
||
SendResult,
|
||
MessageEvent,
|
||
MessageType,
|
||
)
|
||
from gateway.session import SessionSource
|
||
from gateway.config import PlatformConfig, Platform
|
||
except ImportError:
|
||
# Fallback for standalone test / development outside gateway
|
||
BasePlatformAdapter = object
|
||
SendResult = dict
|
||
MessageEvent = dict
|
||
MessageType = object
|
||
SessionSource = object
|
||
PlatformConfig = object
|
||
Platform = str
|
||
|
||
|
||
def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str = "") -> str:
|
||
extra = getattr(config, "extra", {}) or {}
|
||
return os.getenv(env_var) or extra.get(key, default)
|
||
|
||
|
||
class RocketChatREST:
|
||
def __init__(self, base_url: str):
|
||
self.base_url = base_url.rstrip("/")
|
||
self.auth_token: Optional[str] = None
|
||
self.user_id: Optional[str] = None
|
||
|
||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
||
url = f"{self.base_url}{endpoint}"
|
||
req_headers = dict(headers) if headers else {}
|
||
body = json.dumps(data).encode("utf-8") if data else None
|
||
if body:
|
||
req_headers["Content-Type"] = "application/json"
|
||
req = urllib.request.Request(url, data=body, headers=req_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 e:
|
||
if e.code == 429:
|
||
raise RocketChatRateLimitError(
|
||
f"HTTP 429 on {method} {endpoint}"
|
||
) from e
|
||
logger.debug("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||
return None
|
||
except Exception as e:
|
||
logger.debug("REST %s %s failed: %s", method, endpoint, e)
|
||
return None
|
||
|
||
def login(self, user: str, password: str) -> bool:
|
||
r = self._request("POST", "/api/v1/login", data={"user": user, "password": password})
|
||
if r and r.get("status") == "success":
|
||
self.auth_token = r["data"]["authToken"]
|
||
self.user_id = r["data"]["userId"]
|
||
return True
|
||
return False
|
||
|
||
def get_rooms(self) -> List[dict]:
|
||
if not self.auth_token:
|
||
return []
|
||
r = self._request("GET", "/api/v1/rooms.get", headers={
|
||
"X-Auth-Token": self.auth_token,
|
||
"X-User-Id": self.user_id,
|
||
})
|
||
if not r or not r.get("success"):
|
||
return []
|
||
rooms = []
|
||
for rm in r.get("update", []):
|
||
t = rm.get("t", "c")
|
||
rid = rm["_id"]
|
||
if t == "d":
|
||
usernames = rm.get("usernames", [])
|
||
other = [u for u in usernames if u != os.getenv("ROCKETCHAT_USER", "")]
|
||
name = "DM mit " + (", ".join(other) if other else "unbekannt")
|
||
else:
|
||
name = rm.get("name", "unnamed")
|
||
rooms.append({"id": rid, "name": name, "type": t})
|
||
return rooms
|
||
|
||
def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> Optional[str]:
|
||
"""Post a message via REST API POST /api/v1/chat.postMessage.
|
||
|
||
Returns:
|
||
The message ``_id`` from the API response on success, ``None`` on failure.
|
||
V8.3.1 F1: Return message_id for target_message_id tracking.
|
||
"""
|
||
if not self.auth_token:
|
||
return None
|
||
payload = {"roomId": room_id, "text": text}
|
||
if attachments:
|
||
payload["attachments"] = attachments
|
||
r = self._request("POST", "/api/v1/chat.postMessage", headers={
|
||
"X-Auth-Token": self.auth_token,
|
||
"X-User-Id": self.user_id,
|
||
"Content-Type": "application/json",
|
||
}, data=payload)
|
||
if r and r.get("success"):
|
||
return (r.get("message") or {}).get("_id")
|
||
return None
|
||
|
||
def download_file(self, file_id: str, filename: str) -> Optional[str]:
|
||
"""Download a file from Rocket.Chat using the authenticated REST client.
|
||
|
||
Returns the file content as a string (text files) or None on failure.
|
||
Uses the existing authToken — no security scanner triggers.
|
||
"""
|
||
if not self.auth_token:
|
||
return None
|
||
url = f"{self.base_url}/file-upload/{file_id}/{filename}"
|
||
req = urllib.request.Request(url, headers={
|
||
"X-Auth-Token": self.auth_token,
|
||
"X-User-Id": self.user_id,
|
||
})
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||
content = resp.read()
|
||
try:
|
||
return content.decode("utf-8")
|
||
except UnicodeDecodeError:
|
||
return content.decode("latin-1")
|
||
except Exception as e:
|
||
logger.debug("File download failed: %s", e)
|
||
return None
|
||
|
||
def delete_message(self, room_id: str, message_id: str) -> bool:
|
||
"""V8.3-2: Delete a message via REST API POST /api/v1/chat.delete.
|
||
|
||
Rocket.Chat's chat.delete endpoint uses POST (not DELETE), with
|
||
``roomId`` and ``msgId`` in the JSON body.
|
||
|
||
Returns True on success, False on failure (e.g. missing permission).
|
||
"""
|
||
if not self.auth_token:
|
||
return False
|
||
payload = {"roomId": room_id, "msgId": message_id}
|
||
r = self._request("POST", "/api/v1/chat.delete", headers={
|
||
"X-Auth-Token": self.auth_token,
|
||
"X-User-Id": self.user_id,
|
||
"Content-Type": "application/json",
|
||
}, data=payload)
|
||
return bool(r and r.get("success"))
|
||
|
||
def update_message(self, room_id: str, message_id: str, text: str) -> bool:
|
||
"""V8.3-2: Update a message via REST API POST /api/v1/chat.update.
|
||
|
||
Returns True on success, False on failure.
|
||
"""
|
||
if not self.auth_token:
|
||
return False
|
||
payload = {"roomId": room_id, "msgId": message_id, "text": text}
|
||
r = self._request("POST", "/api/v1/chat.update", headers={
|
||
"X-Auth-Token": self.auth_token,
|
||
"X-User-Id": self.user_id,
|
||
"Content-Type": "application/json",
|
||
}, data=payload)
|
||
return bool(r and r.get("success"))
|
||
|
||
|
||
class DDPClient:
|
||
PING_INTERVAL = 8.0
|
||
|
||
|
||
def __init__(self, host: str, on_message_cb=None, on_connected_cb=None, on_room_event_cb=None):
|
||
self.host = host
|
||
self._on_message = on_message_cb
|
||
self._on_connected = on_connected_cb
|
||
self._on_room_event = on_room_event_cb # A1b: DDP room events callback
|
||
self.sock: Optional[socket.socket] = None
|
||
self.connected = False
|
||
self._running = False
|
||
self._reader_thread: Optional[threading.Thread] = None
|
||
self._write_lock = threading.Lock()
|
||
self._msg_queue: queue.Queue = queue.Queue()
|
||
self._next_sub_id = 1
|
||
self._sub_rooms: Dict[str, str] = {}
|
||
self._session: Optional[str] = None
|
||
self._reconnect_attempt = 0
|
||
self._last_rx_time = 0.0
|
||
|
||
def _create_socket(self) -> socket.socket:
|
||
ctx = ssl.create_default_context()
|
||
raw = socket.create_connection((self.host, 443), timeout=10)
|
||
return ctx.wrap_socket(raw, server_hostname=self.host)
|
||
|
||
def _handshake(self, s: socket.socket) -> bool:
|
||
import base64
|
||
key = base64.b64encode(os.urandom(16)).decode()
|
||
hs = (
|
||
f"GET /websocket HTTP/1.1\r\n"
|
||
f"Host: {self.host}\r\n"
|
||
f"Upgrade: websocket\r\n"
|
||
f"Connection: Upgrade\r\n"
|
||
f"Sec-WebSocket-Key: {key}\r\n"
|
||
f"Sec-WebSocket-Version: 13\r\n"
|
||
f"Origin: https://{self.host}\r\n\r\n"
|
||
)
|
||
s.sendall(hs.encode())
|
||
resp = b""
|
||
while b"\r\n\r\n" not in resp:
|
||
chunk = s.recv(1024)
|
||
if not chunk:
|
||
break
|
||
resp += chunk
|
||
return b"101 Switching Protocols" in resp
|
||
|
||
def _send_frame(self, data: bytes, opcode: int = 0x01, mask: bool = True) -> None:
|
||
if not self.sock:
|
||
return
|
||
length = len(data)
|
||
if length < 126:
|
||
header = struct.pack("!BB", 0x80 | opcode, (0x80 if mask else 0x00) | length)
|
||
elif length < 65536:
|
||
header = struct.pack("!BBH", 0x80 | opcode, (0x80 if mask else 0x00) | 126, length)
|
||
else:
|
||
header = struct.pack("!BBQ", 0x80 | opcode, (0x80 if mask else 0x00) | 127, length)
|
||
frame = header
|
||
if mask:
|
||
masking = os.urandom(4)
|
||
masked = bytes(b ^ masking[i % 4] for i, b in enumerate(data))
|
||
frame += masking + masked
|
||
else:
|
||
frame += data
|
||
with self._write_lock:
|
||
self.sock.sendall(frame)
|
||
|
||
def _send_json(self, obj: dict) -> None:
|
||
self._send_frame(json.dumps(obj).encode("utf-8"), opcode=0x01, mask=True)
|
||
|
||
def _send_raw_pong(self, payload: bytes) -> None:
|
||
self._send_frame(payload, opcode=0x0A, mask=True)
|
||
|
||
def _reader_loop(self):
|
||
import select
|
||
self.sock.settimeout(1.0)
|
||
last_ping = time.time()
|
||
while self._running:
|
||
try:
|
||
if time.time() - last_ping >= self.PING_INTERVAL:
|
||
try:
|
||
self._send_json({"msg": "ping"})
|
||
last_ping = time.time()
|
||
except Exception:
|
||
break
|
||
readable, _, _ = select.select([self.sock], [], [], 1.0)
|
||
if not readable:
|
||
continue
|
||
hdr = self.sock.recv(2)
|
||
if not hdr:
|
||
break
|
||
fin = (hdr[0] & 0x80) != 0
|
||
opcode = hdr[0] & 0x0F
|
||
masked = (hdr[1] & 0x80) != 0
|
||
length = hdr[1] & 0x7F
|
||
if length == 126:
|
||
length = struct.unpack("!H", self.sock.recv(2))[0]
|
||
elif length == 127:
|
||
length = struct.unpack("!Q", self.sock.recv(8))[0]
|
||
payload = b""
|
||
remaining = length
|
||
while remaining > 0:
|
||
chunk = self.sock.recv(min(4096, remaining))
|
||
if not chunk:
|
||
break
|
||
payload += chunk
|
||
remaining -= len(chunk)
|
||
if len(payload) < length:
|
||
break
|
||
if masked:
|
||
mask = payload[:4]
|
||
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload[4:]))
|
||
if opcode == 0x09:
|
||
self._send_raw_pong(payload)
|
||
elif opcode == 0x01 and payload:
|
||
self._last_rx_time = time.time()
|
||
try:
|
||
data = json.loads(payload.decode("utf-8", errors="ignore"))
|
||
msg_type = data.get("msg", "")
|
||
if msg_type == "connected":
|
||
self.connected = True
|
||
self._session = data.get("session")
|
||
if self._on_connected:
|
||
self._on_connected()
|
||
elif msg_type == "ping":
|
||
self._send_json({"msg": "pong"})
|
||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
||
fields = data.get("fields", {})
|
||
args = fields.get("args", [])
|
||
if args and isinstance(args, list) and len(args) >= 1:
|
||
self._msg_queue.put(args[0])
|
||
# A1b: stream-notify-room events (rooms-changed, roomMemberAdded)
|
||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-notify-room":
|
||
self._handle_ddp_message(data)
|
||
except Exception:
|
||
pass
|
||
elif opcode == 0x08:
|
||
break
|
||
except Exception:
|
||
break
|
||
self.connected = False
|
||
logger.debug("DDP reader thread exited")
|
||
|
||
def is_alive(self, max_silence: float = 300.0) -> bool:
|
||
"""Detect silent death: socket looks connected but no traffic for max_silence seconds."""
|
||
if not self.connected or not self.sock:
|
||
return False
|
||
if self._last_rx_time == 0:
|
||
# Never received anything yet — use connect time as baseline
|
||
return True
|
||
return (time.time() - self._last_rx_time) < max_silence
|
||
|
||
def connect_and_login(self, token: str) -> bool:
|
||
self._last_rx_time = time.time()
|
||
try:
|
||
self.sock = self._create_socket()
|
||
if not self._handshake(self.sock):
|
||
return False
|
||
self._running = True
|
||
self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
|
||
self._reader_thread.start()
|
||
time.sleep(0.3)
|
||
self._send_json({"msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"]})
|
||
for _ in range(50):
|
||
if self.connected:
|
||
break
|
||
time.sleep(0.1)
|
||
if not self.connected:
|
||
self.disconnect()
|
||
return False
|
||
time.sleep(0.2)
|
||
self._send_json({"msg": "method", "method": "login",
|
||
"params": [{"resume": token}], "id": "ddplogin"})
|
||
time.sleep(0.5)
|
||
return True
|
||
except Exception as e:
|
||
logger.error("DDP connect failed: %s", e)
|
||
self.disconnect()
|
||
return False
|
||
|
||
def subscribe_room(self, room_id: str) -> Optional[str]:
|
||
if not self.connected:
|
||
return None
|
||
sub_id = f"sub{self._next_sub_id}"
|
||
self._next_sub_id += 1
|
||
# CRITICAL: Rocket.Chat V5+ requires {"token": "true"} as second param,
|
||
# otherwise subscribe succeeds but NO messages ever stream.
|
||
self._send_json({
|
||
"msg": "sub",
|
||
"name": "stream-room-messages",
|
||
"params": [room_id, {"token": "true"}],
|
||
"id": sub_id
|
||
})
|
||
self._sub_rooms[room_id] = sub_id
|
||
return sub_id
|
||
|
||
def unsubscribe(self, room_id: str) -> bool:
|
||
"""DDP unsub: send ``{"msg": "unsub", "id": "<sub_id>"}`` and
|
||
remove the room from the internal subscription table.
|
||
|
||
Returns True if an active subscription was found and unsubscribed,
|
||
False if the room was not subscribed.
|
||
"""
|
||
sub_id = self._sub_rooms.pop(room_id, None)
|
||
if sub_id is None:
|
||
return False
|
||
if self.connected and self.sock:
|
||
try:
|
||
self._send_json({"msg": "unsub", "id": sub_id})
|
||
except Exception:
|
||
pass
|
||
return True
|
||
|
||
def subscribe_room_events(self) -> Optional[str]:
|
||
"""A1b: Subscribe to stream-notify-room for rooms-changed events.
|
||
|
||
Rocket.Chat sendet rooms-changed Events wenn der Bot einem
|
||
neuen Raum hinzugefügt wird (roomMemberAdded) oder sich die
|
||
Raumliste ändert.
|
||
|
||
Returns:
|
||
Subscription-ID oder None wenn nicht connected.
|
||
"""
|
||
if not self.connected:
|
||
return None
|
||
sub_id = f"sub{self._next_sub_id}"
|
||
self._next_sub_id += 1
|
||
# Rocket.Chat stream-notify-room: erster Param = user-id/event-name
|
||
# __my_messages__ ist der Fallback, der für den aktuellen User funktioniert
|
||
self._send_json({
|
||
"msg": "sub",
|
||
"name": "stream-notify-room",
|
||
"params": ["__my_messages__/rooms-changed", "rooms-changed", False],
|
||
"id": sub_id,
|
||
})
|
||
logger.debug("DDP: Subscribed to stream-notify-room (rooms-changed) — sub_id=%s", sub_id)
|
||
return sub_id
|
||
|
||
def _handle_ddp_message(self, data: dict) -> None:
|
||
"""A1b: Parse stream-notify-room events and dispatch to callback.
|
||
|
||
Extrahiert rooms-changed Events und ruft _on_room_event auf.
|
||
|
||
Args:
|
||
data: Die geparste DDP-JSON-Message.
|
||
"""
|
||
if self._on_room_event is None:
|
||
return
|
||
|
||
fields = data.get("fields", {})
|
||
event_name = fields.get("eventName", "")
|
||
|
||
if event_name != "rooms-changed":
|
||
return
|
||
|
||
args = fields.get("args", [])
|
||
if not args or not isinstance(args, list) or len(args) < 2:
|
||
return
|
||
|
||
room_id = args[0]
|
||
room_data = args[1] if isinstance(args[1], dict) else {}
|
||
|
||
event = {
|
||
"room_id": room_id,
|
||
"name": room_data.get("name", ""),
|
||
"type": room_data.get("type", "c"),
|
||
}
|
||
logger.debug("DDP: rooms-changed event — room=%s, name=%s, type=%s",
|
||
room_id[:12], event["name"], event["type"])
|
||
self._on_room_event(event)
|
||
|
||
def set_status(self, status: str) -> bool:
|
||
if not self.connected:
|
||
return False
|
||
method = "UserPresence:setDefaultStatus"
|
||
self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"})
|
||
return True
|
||
|
||
def disconnect(self):
|
||
self._running = False
|
||
if self.sock:
|
||
try:
|
||
self.sock.close()
|
||
except Exception:
|
||
pass
|
||
self.sock = None
|
||
self.connected = False
|
||
self._sub_rooms.clear()
|
||
|
||
# Bug 7: reconnect_and_restore() ist deprecated — sie umgeht M13 GC.
|
||
# Stattdessen _reconnect_ddp() auf dem Adapter verwenden, die REST
|
||
# get_rooms() + M13 GC durchläuft und nur aktuelle Mitglieder-Räume
|
||
# subscribed.
|
||
def reconnect_and_restore(self, token: str) -> bool:
|
||
"""DEPRECATED: Umgeht M13 GC. Verwende RocketChatAdapter._reconnect_ddp()."""
|
||
self.disconnect()
|
||
time.sleep(1)
|
||
old_subs = list(self._sub_rooms.keys())
|
||
self._sub_rooms.clear()
|
||
if self.connect_and_login(token):
|
||
for rid in old_subs:
|
||
self.subscribe_room(rid)
|
||
return True
|
||
return False
|
||
|
||
|
||
|
||
|
||
# ── Auftrag-Erkennung (User-Flow C) ────────────────────────────────────
|
||
# ── V8: Imperativ-Stems für _is_auftrag (Wortgrenzen-Prüfung) ──────────
|
||
# Stems, die auf einen Imperativ hindeuten (du-Form).
|
||
# Geprüft wird mit \b<stem>\w*\b — matcht stem + optionale Endung.
|
||
IMPERATIVE_STEMS: list = [
|
||
"mach", "test", "start", "fix", "bau", "änder", "schreib",
|
||
"erstell", "prüf", "lösch", "untersuch", "optimier", "erweiter",
|
||
"installier", "kompilier", "generier", "analysier", "verschieb",
|
||
"entfern", "beheb", "korrigier", "konfigurier", "implementier",
|
||
"stopp", "deploy",
|
||
]
|
||
|
||
# Wörter, die einen Imperativ-Stem enthalten, aber KEIN Imperativ sind.
|
||
# (Infinitiv, 3. Person, Partizip, 1. Person Indikativ, Komposita)
|
||
EXCLUDE_WORDS: set = {
|
||
# mach → gemacht, macht, machst, machte, mache, machbar, machen, …
|
||
"gemacht", "macht", "machst", "machte", "mache", "machbar",
|
||
"machten", "machtet", "machen",
|
||
# test → testen, testet, testest, tester, testing, Testabdeckung, …
|
||
"testen", "testet", "testest", "tester", "testing",
|
||
"testabdeckung", "testumgebung", "testlauf", "testfall",
|
||
# start → starten, startet, gestartet, startest, Startseite, …
|
||
"starten", "startet", "gestartet", "startest",
|
||
"startseite", "startzeit", "startmenü",
|
||
# fix → fixieren, fixiert, fixierst, …
|
||
"fixieren", "fixiert", "fixierst", "fixe",
|
||
# bau → bauen, baut, baust, gebaut, Bauplan, …
|
||
"bauen", "baut", "baust", "gebaut", "baute",
|
||
"bauplan", "baujahr", "bauweise",
|
||
# änder → ändern, ändert, änderst, geändert, …
|
||
"ändern", "ändert", "änderst", "geändert", "änderte",
|
||
# schreib → schreiben, schreibt, schreibst, beschreiben, geschrieben, …
|
||
"schreiben", "schreibt", "schreibst", "beschreiben", "geschrieben",
|
||
"beschreibt", "beschreibst", "schreibe", "schrieb",
|
||
# erstell → erstellen, erstellt, erstellst, …
|
||
"erstellen", "erstellt", "erstellst", "erstellte",
|
||
# prüf → prüfen, prüft, prüfst, geprüft, …
|
||
"prüfen", "prüft", "prüfst", "geprüft", "prüfte",
|
||
# lösch → löschen, löscht, löschst, gelöscht, …
|
||
"löschen", "löscht", "löschst", "gelöscht", "löschte",
|
||
# untersuch → untersuchen, untersucht, untersuchst, …
|
||
"untersuchen", "untersucht", "untersuchst", "untersuchte",
|
||
# optimier → optimieren, optimiert, optimierst, …
|
||
"optimieren", "optimiert", "optimierst", "optimierte",
|
||
# erweiter → erweitern, erweitert, erweiterst, …
|
||
"erweitern", "erweitert", "erweiterst", "erweiterte",
|
||
# installier → installieren, installiert, installierst, …
|
||
"installieren", "installiert", "installierst", "installierte",
|
||
# kompilier → kompilieren, kompiliert, kompilierst, …
|
||
"kompilieren", "kompiliert", "kompilierst", "kompilierte",
|
||
# generier → generieren, generiert, generierst, …
|
||
"generieren", "generiert", "generierst", "generierte",
|
||
# analysier → analysieren, analysiert, analysierst, …
|
||
"analysieren", "analysiert", "analysierst", "analysierte",
|
||
# verschieb → verschieben, verschiebt, verschiebst, verschoben, …
|
||
"verschieben", "verschiebt", "verschiebst", "verschoben",
|
||
"verschiebung",
|
||
# entfern → entfernen, entfernt, entfernst, …
|
||
"entfernen", "entfernt", "entfernst", "entfernte",
|
||
# beheb → beheben, behebt, behobst, behoben, …
|
||
"beheben", "behebt", "behobst", "behoben", "behebung",
|
||
# korrigier → korrigieren, korrigiert, korrigierst, …
|
||
"korrigieren", "korrigiert", "korrigierst", "korrigierte",
|
||
# konfigurier → konfigurieren, konfiguriert, konfigurierst, …
|
||
"konfigurieren", "konfiguriert", "konfigurierst", "konfigurierte",
|
||
# implementier → implementieren, implementiert, implementierst, …
|
||
"implementieren", "implementiert", "implementierst", "implementierte",
|
||
# stopp → stoppen, stoppt, stoppst, gestoppt, …
|
||
"stoppen", "stoppt", "stoppst", "gestoppt", "stoppte",
|
||
# deploy → deployen, deployt, deployst, …
|
||
"deployen", "deployt", "deployst",
|
||
# Englische False-Positives (enthalten deutsche Stems)
|
||
"restart",
|
||
# Konjunktiv/Höflichkeitsform-False-Positives
|
||
"könntest",
|
||
}
|
||
|
||
# Kompiliertes Regex: matcht jedes Wort, das mit einem Imperativ-Stem beginnt
|
||
_IMPERATIVE_STEM_RE = re.compile(
|
||
r'\b(' + '|'.join(re.escape(s) for s in IMPERATIVE_STEMS) + r')\w*\b',
|
||
re.IGNORECASE,
|
||
)
|
||
|
||
# Deprecated: für Rückwärtskompatibilität mit Tests, die _AUFTRAG_KEYWORDS importieren.
|
||
# V8: Nur noch IMPERATIVE_STEMS + EXCLUDE_WORDS verwenden.
|
||
_AUFTRAG_KEYWORDS: list = IMPERATIVE_STEMS + ["bitte", "füg hinzu"]
|
||
|
||
|
||
def _is_auftrag(text: str) -> bool:
|
||
"""V8-Heuristik: Wortgrenzen-Prüfung auf Imperativ-Stems.
|
||
|
||
Matcht nur ganze Wörter (\\b), keine Substring-Kollisionen mehr.
|
||
Schließt Infinitive, Partizipien und Indikativ-Formen über
|
||
EXCLUDE_WORDS aus.
|
||
|
||
Spezialfälle:
|
||
- 'bitte' als Höflichkeitsmarker (eigenständiges Wort)
|
||
- 'füg hinzu' / 'füge hinzu' / 'fügt hinzu' (mehrwortig)
|
||
"""
|
||
t = text.lower()
|
||
|
||
# 1. Imperativ-Stems mit Wortgrenzen prüfen
|
||
for match in _IMPERATIVE_STEM_RE.finditer(t):
|
||
word = match.group().lower()
|
||
if word not in EXCLUDE_WORDS:
|
||
return True
|
||
|
||
# 2. 'bitte' als eigenständiges Wort
|
||
if re.search(r'\bbitte\b', t):
|
||
return True
|
||
|
||
# 3. Mehrwort-Imperativ 'füg hinzu' und Varianten
|
||
if 'füg hinzu' in t or 'füge hinzu' in t or 'fügt hinzu' in t:
|
||
return True
|
||
|
||
return False
|
||
|
||
|
||
# ── V8.3.4 B5: Ankündigungsvariationen ──────────────────────────────────
|
||
# 5 gleichbedeutende Formulierungen, zufällig ausgewählt.
|
||
# <target> wird durch den Raumnamen ersetzt.
|
||
_ANNOUNCEMENT_VARIANTS: list = [
|
||
"Lass uns das Thema in #{target} aufgreifen. Ich nehme das Thema mit.",
|
||
"Das passt besser in #{target} — ich bringe das Thema rüber. Kommst du mit? 👋",
|
||
"Wechseln wir kurz in #{target} für dieses Thema. Ich sehe dich dort.",
|
||
"Gehört eigentlich in #{target} — ich schiebe das Thema rüber und antworte dort. Wechsel du auch rüber?",
|
||
"Rüber in #{target} mit diesem Thema. Komme direkt nach. ✌️",
|
||
]
|
||
|
||
|
||
def _build_announcement(target_display: str) -> str:
|
||
"""Baue eine zufällige Ankündigung für den Ursprungsraum.
|
||
|
||
Args:
|
||
target_display: Raum-Name ohne führendes # (z.B. 'Rocketchat-Plugin').
|
||
|
||
Returns:
|
||
Zufällig ausgewählte Ankündigung mit eingesetztem Raumnamen.
|
||
"""
|
||
template = random.choice(_ANNOUNCEMENT_VARIANTS)
|
||
return template.replace("{target}", target_display)
|
||
|
||
|
||
class RocketChatAdapter(BasePlatformAdapter):
|
||
HEALTH_CHECK_INTERVAL = 60.0 # seconds
|
||
HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect
|
||
|
||
def __init__(self, config: PlatformConfig):
|
||
super().__init__(config=config, platform=Platform("rocketchat"))
|
||
self.base_url = _get_config_str(config, "base_url", "ROCKETCHAT_BASE_URL")
|
||
self.user = _get_config_str(config, "user", "ROCKETCHAT_USER")
|
||
self.password = _get_config_str(config, "password", "ROCKETCHAT_PASSWORD")
|
||
self.rest = RocketChatREST(self.base_url)
|
||
self.ddp: Optional[DDPClient] = None
|
||
self._auth_token: Optional[str] = None
|
||
self._user_id: Optional[str] = None
|
||
self._rooms: List[dict] = []
|
||
self._subscribed_rooms: set = set()
|
||
self._listen_task: Optional[asyncio.Task] = None
|
||
self._status_timer: Optional[threading.Timer] = None
|
||
self._last_activity = 0.0
|
||
self._shutdown_event = threading.Event()
|
||
self._room_info: Dict[str, dict] = {}
|
||
# Clarify-Queue: tracks pending button questions per chat_id
|
||
# so incoming replies can be correlated with the original question.
|
||
self._pending_clarifies: Dict[str, dict] = {}
|
||
# User-based room mapping for virtual chat_id translation.
|
||
# Key: "user:<username>", Value: list of real room_ids for that user.
|
||
# Built during connect() from REST get_rooms.
|
||
self._user_rooms: Dict[str, List[str]] = {}
|
||
# Rooms where the agent has posted a question with buttons.
|
||
# Used to keep the response in the same room — no Archivar routing,
|
||
# no catch-all forwarding. Removed after the next user message from
|
||
# that room (on the assumption that the response IS the button answer).
|
||
# No timers, no cleanup — just a simple set.
|
||
self._rooms_with_pending_questions: set = set()
|
||
# B8: Room IDs excluded from DDP subscription (from room-map.json).
|
||
# Populated by _sync_room_map_with_membership() at connect time.
|
||
self._excluded_room_ids: set = set()
|
||
# Health-check state
|
||
self._last_server_activity = 0.0 # ts of last DDP ping/pong or message
|
||
self._health_check_timer: Optional[threading.Timer] = None
|
||
self._last_ddp_ping_ok = False
|
||
self._running = False
|
||
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||
if _MULTIROOM():
|
||
self._conversation_history = ConversationHistory(max_size=10)
|
||
self._multiroom_context = MultiRoomContextRing(max_entries=10)
|
||
self.archivar = ArchivarMessageHandler(
|
||
send_callback=self._send_via_archivar,
|
||
button_send_callback=self._send_archivar_buttons,
|
||
conversation_history=self._conversation_history,
|
||
)
|
||
else:
|
||
self.archivar = None
|
||
self._conversation_history = None
|
||
self._multiroom_context = None
|
||
# User-Flow C: Move-Requests
|
||
self._pending_move_requests: Dict[str, dict] = {}
|
||
# V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL)
|
||
# Wird bei confirm_move gesetzt und vor Archivar-Klassifikation geprüft.
|
||
self._session_room_preferences: Dict[str, Dict[str, Any]] = {}
|
||
# V8.3-3: Recent auto-routes für Widerspruchs-Routine
|
||
# {origin_room: {target_room, topic, timestamp, origin_message_id, target_message_id}}
|
||
self._recent_auto_routes: Dict[str, Dict[str, Any]] = {}
|
||
# V8.3-4: Expliziter Raumwechsel-Sticky (30 Min TTL)
|
||
# {origin_room: {target_room, target_name, sticky_topic, expires_at}}
|
||
self._explicit_switch_sticky: Dict[str, Dict[str, Any]] = {}
|
||
# V7-2: _sticky_rooms removed — thematic never_route replaces spatial bypass.
|
||
# The router's _check_never_route_topic handles per-topic blocking now.
|
||
# Clarify state: maps clarify_id → session_key for gateway resolution
|
||
self._clarify_state: Dict[str, str] = {}
|
||
# Auto-Onboarding v2: structured interview state
|
||
self._onboarding_state: Dict[str, Any] = {}
|
||
# FIX E: Raum-Map Summary für System-Prompt-Injection via chat_topic.
|
||
# Wird bei connect() und nach jeder Raum-Map-Änderung (M13 GC, Onboarding)
|
||
# neu gebaut. Der Gateway-Core rendert chat_topic als "**Channel Topic:**"
|
||
# im System-Prompt — der Agent sieht die Raum-Map also BEI JEDEM START.
|
||
self._room_map_summary: str = ""
|
||
# R5: Inline-Command-Registry für ::-Befehle
|
||
from archivar.inline_commands import InlineCommandRegistry
|
||
self._inline_commands = InlineCommandRegistry()
|
||
self._register_inline_commands()
|
||
|
||
# V8.6: PresenceEngine — Aktivitäts-Indikator
|
||
try:
|
||
from archivar.presence_engine import PresenceEngine
|
||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
||
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||
self._presence_engine = PresenceEngine(
|
||
rest=self.rest,
|
||
enabled=_presence_enabled,
|
||
coalesce_ms=_coalesce_ms,
|
||
pulse_interval=_pulse_interval,
|
||
)
|
||
# P0-1: PulseController mit REST und DDP verdrahten
|
||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||
if self.ddp:
|
||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||
# P2-2: PresenceEngine an ArchivarMessageHandler weiterreichen
|
||
if self.archivar is not None:
|
||
self.archivar.set_presence_engine(self._presence_engine)
|
||
logger.info(
|
||
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s, pulse_interval=%.1fs)",
|
||
_presence_enabled,
|
||
_coalesce_ms,
|
||
_pulse_interval,
|
||
)
|
||
except Exception as e:
|
||
logger.error(
|
||
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||
e,
|
||
)
|
||
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||
|
||
def _build_room_map_summary(self) -> str:
|
||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||
|
||
Wird via SessionSource.chat_topic in den System-Prompt injiziert.
|
||
Der Gateway-Core rendert chat_topic als "**Channel Topic:**" Block.
|
||
|
||
Returns:
|
||
Formatierter String mit allen Räumen (Name, ID, Thema, Keywords,
|
||
Catch-All-Marker). Leerer String wenn keine Raum-Map geladen ist.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return ""
|
||
room_map = getattr(self.archivar, '_room_map', None)
|
||
if room_map is None or not room_map.rooms:
|
||
return ""
|
||
|
||
lines = ["Rocket.Chat Raum-Map:"]
|
||
for i, (rid, entry) in enumerate(room_map.rooms.items(), 1):
|
||
catch_all_marker = " ★ CATCH-ALL" if entry.catch_all else ""
|
||
lines.append(
|
||
f" {i}. {entry.name} ({rid}){catch_all_marker} — "
|
||
f"Thema: {entry.theme}"
|
||
)
|
||
# Keywords 100% (exakte Treffer)
|
||
if entry.keywords_100:
|
||
kw100 = ", ".join(entry.keywords_100)
|
||
lines.append(f" Keywords 100%: {kw100}")
|
||
# Keywords Kontext (kontextabhängige Treffer)
|
||
if entry.keywords_context:
|
||
kwctx = ", ".join(entry.keywords_context)
|
||
lines.append(f" Keywords Kontext: {kwctx}")
|
||
return "\n".join(lines)
|
||
|
||
def _on_ddp_connected(self) -> None:
|
||
"""Callback when DDP connection is established.
|
||
|
||
Sets initial online status and binds DDP to PulseController
|
||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||
"""
|
||
if self.ddp:
|
||
self.ddp.set_status("online")
|
||
# V8.6: PulseController DDP-Bindung nach Connect (EC-1)
|
||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||
try:
|
||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||
except Exception as e:
|
||
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
|
||
|
||
def _on_ddp_room_event(self, event: dict) -> None:
|
||
"""A1b: Callback für DDP rooms-changed Events.
|
||
|
||
Wird vom DDPClient._handle_ddp_message aufgerufen wenn ein
|
||
rooms-changed Event empfangen wird. Prüft ob der Raum neu ist
|
||
und startet ggf. das Onboarding-Interview.
|
||
|
||
Args:
|
||
event: Dict mit {"room_id": str, "name": str, "type": str}.
|
||
"""
|
||
room_id = event.get("room_id", "")
|
||
room_name = event.get("name", "")
|
||
room_type = event.get("type", "c")
|
||
|
||
if not room_id:
|
||
return
|
||
|
||
# Nur im Multiroom-Modus mit aktivem Archivar
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return
|
||
|
||
# Prüfe ob Onboarding bereits aktiv ist
|
||
if self.archivar._stats.get("onboarding_active", False):
|
||
logger.debug("[rocketchat] A1b: Onboarding bereits aktiv — DDP-Event ignoriert: room=%s", room_id[:12])
|
||
return
|
||
|
||
# P1-3: Lock prüfen — symmetrisch zu lazy_onboarding_check
|
||
# Verhindert doppelte Interviews für denselben Raum
|
||
from archivar.onboarding import is_onboarding_locked
|
||
if is_onboarding_locked(room_id):
|
||
logger.debug("[rocketchat] A1b: Onboarding-Lock aktiv — DDP-Event ignoriert: room=%s", room_id[:12])
|
||
return
|
||
|
||
# Prüfe ob der Raum in der Map fehlt (Delta-Check)
|
||
missing = self.archivar.check_room_map_completeness_delta(
|
||
room_id=room_id,
|
||
room_name=room_name,
|
||
room_type=room_type,
|
||
)
|
||
|
||
if missing is None:
|
||
logger.debug("[rocketchat] A1b: Raum bereits in Map oder ignoriert: room=%s", room_id[:12])
|
||
return
|
||
|
||
# Telemetrie: DDP-Event-Pfad
|
||
logger.info(
|
||
"[rocketchat] A1b: DDP-Event-Pfad — neuer Raum entdeckt: "
|
||
"room=%s, name=%s, type=%s",
|
||
room_id[:12], room_name, room_type,
|
||
)
|
||
|
||
# Onboarding für diesen Raum starten (asynchron, nicht blockierend)
|
||
asyncio.ensure_future(self._start_onboarding([missing]))
|
||
|
||
async def _post_message_with_retry(
|
||
self, room_id: str, text: str,
|
||
attachments: Optional[List[dict]] = None,
|
||
max_retries: int = 3,
|
||
) -> Optional[str]:
|
||
"""Send chat.postMessage with exponential backoff on HTTP 429.
|
||
|
||
Retries only on RocketChatRateLimitError (HTTP 429). All other
|
||
failures return None immediately. Uses asyncio.sleep so the
|
||
gateway listen loop is never blocked.
|
||
|
||
Retry delays: 2s, 4s, 8s.
|
||
|
||
Returns:
|
||
The message ``_id`` from the API response on success, ``None`` on failure.
|
||
V8.3.1 F1: Return message_id for target_message_id tracking.
|
||
"""
|
||
delays = [2, 4, 8]
|
||
for attempt in range(max_retries + 1):
|
||
try:
|
||
return self.rest.post_message(room_id, text, attachments=attachments)
|
||
except RocketChatRateLimitError:
|
||
if attempt < max_retries:
|
||
delay = delays[min(attempt, len(delays) - 1)]
|
||
logger.warning(
|
||
"Rate-limited (429), retry %d/%d in %ds (room=%s)",
|
||
attempt + 1, max_retries, delay, room_id[:8],
|
||
)
|
||
await asyncio.sleep(delay)
|
||
else:
|
||
logger.error(
|
||
"chat.postMessage failed after %d retries (room=%s)",
|
||
max_retries, room_id[:8],
|
||
)
|
||
return None
|
||
except Exception as e:
|
||
logger.debug("chat.postMessage failed (non-429): %s", e)
|
||
return None
|
||
return None
|
||
|
||
def _sync_room_map_with_membership(self) -> None:
|
||
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
||
|
||
Läuft beim Gateway-Start NACH REST get_rooms(), VOR DDP-Subscription
|
||
und VOR Archivar-Init (B9). Verhindert Ghost-Subscriptions in Räumen,
|
||
aus denen der Agent entfernt wurde.
|
||
|
||
**Reihenfolge-Garantie M13 → B9:**
|
||
|
||
M13 entfernt Räume, in denen der Agent nicht mehr Mitglied ist.
|
||
B9 (Auto-Onboarding) triggert für Räume, die in der Mitgliedschaft
|
||
sind, aber NICHT in room-map.json. Da B9 NACH M13 läuft, sind
|
||
neu onboardete Räume in room-map.json, BEVOR M13 beim nächsten
|
||
Gateway-Start läuft. M13 kann also keine Räume löschen, die B9
|
||
gerade onboardiert hat — die Reihenfolge ist korrekt.
|
||
|
||
Ablauf:
|
||
1. Aktuelle Mitgliedschaft aus self._rooms (REST get_rooms) extrahieren
|
||
2. room-map.json laden (falls vorhanden)
|
||
3. Räume in room-map.json aber NICHT in Mitgliedschaft → entfernen
|
||
4. Bereinigte room-map.json speichern
|
||
4a. self._subscribed_rooms, self._room_info + DDP unsub bereinigen
|
||
5. FAISS-Index nach Bereinigung neu bauen (falls Archivar aktiv)
|
||
6. KeywordBooster-Mapping neu bauen (nur gültige Räume)
|
||
7. ArchivarState bereinigen (stay_decision, keyword_weights, sticky, overrides, promotion)
|
||
8. Onboarding _stay_tracker für gelöschte Räume entfernen
|
||
|
||
DM-Räume werden NIEMALS entfernt (DM existiert immer).
|
||
Idempotent: bei jedem Gateway-Start ausgeführt.
|
||
"""
|
||
# ── 1. Extrahiere aktuelle Mitgliedschafts-Room-IDs ────────────
|
||
member_room_ids: set = set()
|
||
dm_room_ids: set = set()
|
||
for room in self._rooms:
|
||
rid = room.get("id", "")
|
||
if not rid:
|
||
continue
|
||
member_room_ids.add(rid)
|
||
if room.get("type") == "d":
|
||
dm_room_ids.add(rid)
|
||
|
||
if not member_room_ids:
|
||
logger.warning("[rocketchat] M13: Keine Mitgliedschaftsdaten — GC übersprungen")
|
||
return
|
||
|
||
logger.info(
|
||
"[rocketchat] M13: Mitglied in %d Räumen (%d DM, %d Channels/Groups)",
|
||
len(member_room_ids),
|
||
len(dm_room_ids),
|
||
len(member_room_ids) - len(dm_room_ids),
|
||
)
|
||
|
||
# ── 2. Lade room-map.json ──────────────────────────────────────
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
|
||
map_path = Path(ROOM_MAP_PATH)
|
||
if not map_path.exists():
|
||
logger.info("[rocketchat] M13: Keine room-map.json vorhanden — GC übersprungen")
|
||
return
|
||
|
||
try:
|
||
room_map = RoomMap.load(map_path)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: Konnte room-map.json nicht laden: %s — GC übersprungen", e)
|
||
return
|
||
|
||
# B8: excluded_room_ids für DDP-Subscription-Filter speichern
|
||
self._excluded_room_ids = room_map.excluded_room_ids
|
||
if self._excluded_room_ids:
|
||
logger.info(
|
||
"[rocketchat] B8: %d excluded rooms geladen: %s",
|
||
len(self._excluded_room_ids),
|
||
", ".join(sorted(self._excluded_room_ids)),
|
||
)
|
||
|
||
map_room_ids = set(room_map.rooms.keys())
|
||
logger.info(
|
||
"[rocketchat] M13: room-map.json enthält %d Räume",
|
||
len(map_room_ids),
|
||
)
|
||
|
||
# ── 3. Finde Räume zum Entfernen ───────────────────────────────
|
||
# Raum in room-map.json aber NICHT in Mitgliedschaft → entfernen
|
||
# AUSSER: DM-Räume (werden nie entfernt)
|
||
rooms_to_remove: set = set()
|
||
for rid in map_room_ids:
|
||
if rid in member_room_ids:
|
||
continue # Noch Mitglied → behalten
|
||
if rid in dm_room_ids:
|
||
continue # DM → nie entfernen
|
||
# Prüfe ob es ein DM ist (auch wenn nicht in aktuellen rooms)
|
||
entry = room_map.get_room_by_id(rid)
|
||
if entry and entry.name.startswith("DM "):
|
||
logger.info(
|
||
"[rocketchat] M13: DM-Raum '%s' (%s…) wird nie entfernt",
|
||
entry.name, rid[:8],
|
||
)
|
||
continue
|
||
rooms_to_remove.add(rid)
|
||
|
||
if not rooms_to_remove:
|
||
logger.info("[rocketchat] M13: Alle %d Räume in room-map.json sind noch aktuell — nichts zu bereinigen", len(map_room_ids))
|
||
return
|
||
|
||
# ── 4. Entferne verwaiste Räume ─────────────────────────────────
|
||
removed_names: list = []
|
||
for rid in sorted(rooms_to_remove):
|
||
entry = room_map.get_room_by_id(rid)
|
||
removed_names.append(
|
||
f"'{entry.name}' ({rid[:8]}…)" if entry else f"'?' ({rid[:8]}…)"
|
||
)
|
||
logger.info(
|
||
"[rocketchat] M13: Entferne %d verwaiste Räume aus room-map.json: %s",
|
||
len(rooms_to_remove),
|
||
", ".join(removed_names),
|
||
)
|
||
|
||
for rid in rooms_to_remove:
|
||
entry = room_map.get_room_by_id(rid)
|
||
room_name = entry.name if entry else rid[:12] + "…"
|
||
del room_map._rooms[rid]
|
||
logger.info(
|
||
"[rocketchat] M13: Raum '%s' (%s…) entfernt — nicht mehr Mitglied",
|
||
room_name, rid[:8],
|
||
)
|
||
|
||
# ── 4a. Adapter-Subscriptions + DDP bereinigen ──────────────────
|
||
# P2: self._subscribed_rooms und self._room_info müssen ebenfalls
|
||
# bereinigt werden, sonst läuft der Archivar mit Geister-Subscriptions
|
||
# weiter und der Adapter hält alte Subscription-IDs.
|
||
# P3: DDP unsub für jeden entfernten Raum, damit der Server keine
|
||
# Events mehr für Räume streamt, aus denen der Agent entfernt wurde.
|
||
for rid in rooms_to_remove:
|
||
entry = room_map.get_room_by_id(rid)
|
||
room_name = entry.name if entry else "?"
|
||
if rid in self._subscribed_rooms:
|
||
self._subscribed_rooms.discard(rid)
|
||
logger.info(
|
||
"[rocketchat] M13: _subscribed_rooms bereinigt — '%s' (%s…)",
|
||
room_name, rid[:8],
|
||
)
|
||
if rid in self._room_info:
|
||
del self._room_info[rid]
|
||
logger.info(
|
||
"[rocketchat] M13: _room_info bereinigt — '%s' (%s…)",
|
||
room_name, rid[:8],
|
||
)
|
||
if self.ddp is not None:
|
||
unsubbed = self.ddp.unsubscribe(rid)
|
||
if unsubbed:
|
||
logger.info(
|
||
"[rocketchat] M13: DDP unsub — '%s' (%s…)",
|
||
room_name, rid[:8],
|
||
)
|
||
|
||
# ── 5. Bereinigte Map speichern ────────────────────────────────
|
||
try:
|
||
RoomMap.save(room_map, map_path)
|
||
logger.info(
|
||
"[rocketchat] M13: Bereinigte room-map.json gespeichert (%d Räume, %d entfernt)",
|
||
len(room_map.rooms), len(rooms_to_remove),
|
||
)
|
||
except Exception as e:
|
||
logger.error("[rocketchat] M13: Fehler beim Speichern der bereinigten room-map.json: %s", e)
|
||
|
||
# ── 6. FAISS-Index + Booster + State + Onboarding bereinigen ──
|
||
# Nur wenn Archivar aktiv ist (Multiroom-Modus)
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
# RoomMap im Archivar neu laden, damit alle Komponenten die
|
||
# bereinigte Map sehen
|
||
self.archivar._room_map.reload(map_path)
|
||
|
||
# 6a. FAISS-Index neu bauen
|
||
if self.archivar._room_index is not None:
|
||
try:
|
||
self.archivar._room_index.build_index()
|
||
self.archivar._room_index.save()
|
||
logger.info(
|
||
"[rocketchat] M13: FAISS-Index nach GC neu gebaut (%d Vektoren)",
|
||
self.archivar._room_index.size,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: FAISS-Index-Rebuild nach GC fehlgeschlagen: %s", e)
|
||
|
||
# 6b. KeywordBooster-Mapping neu bauen
|
||
if self.archivar._booster is not None:
|
||
try:
|
||
self.archivar._booster.cleanup_orphaned_rooms(set(room_map.rooms.keys()))
|
||
logger.info("[rocketchat] M13: KeywordBooster-Mapping nach GC neu gebaut")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: KeywordBooster-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 6c. ArchivarState bereinigen
|
||
if self.archivar._state is not None:
|
||
try:
|
||
valid_ids = set(room_map.rooms.keys())
|
||
removed = self.archivar._state.cleanup_orphaned_rooms(valid_ids)
|
||
logger.info(
|
||
"[rocketchat] M13: ArchivarState bereinigt — %d orphaned Einträge entfernt",
|
||
removed,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: ArchivarState-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 6d. Onboarding _stay_tracker für gelöschte Räume bereinigen
|
||
if self.archivar._state is not None:
|
||
try:
|
||
removed_stay = self.archivar._state.cleanup_stay_tracker(set(room_map.rooms.keys()))
|
||
if removed_stay > 0:
|
||
logger.info(
|
||
"[rocketchat] M13: stay_tracker bereinigt — %d Einträge entfernt",
|
||
removed_stay,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: stay_tracker-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 6e. B5v6.5: ConversationHistory bereinigen
|
||
if self._conversation_history is not None:
|
||
try:
|
||
valid_ids = set(room_map.rooms.keys())
|
||
removed_hist = self._conversation_history.cleanup_orphaned_rooms_sync(valid_ids)
|
||
if removed_hist > 0:
|
||
logger.info(
|
||
"[rocketchat] M13: ConversationHistory bereinigt — %d orphaned Räume entfernt",
|
||
removed_hist,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: ConversationHistory-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# FIX E: Raum-Map Summary nach GC aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach M13 GC aktualisiert (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
|
||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||
"""Connect to Rocket.Chat (REST + DDP) and start listen loop.
|
||
|
||
is_reconnect: True wenn dies ein Reconnect-Versuch ist (z.B. nach
|
||
Silent-Death-Erkennung). Core ruft connect() mit diesem Keyword-Arg
|
||
auf; fehlt es → TypeError. Siehe Bug M3.
|
||
"""
|
||
if not self.base_url or not self.user or not self.password:
|
||
logger.error("[rocketchat] Missing configuration")
|
||
return False
|
||
if not self.rest.login(self.user, self.password):
|
||
logger.error("[rocketchat] REST login failed")
|
||
return False
|
||
self._auth_token = self.rest.auth_token
|
||
self._user_id = self.rest.user_id
|
||
|
||
# A1b: Stale-Lock-Cleanup beim Gateway-Start
|
||
# Entfernt Onboarding-Locks die älter als 10 Minuten sind
|
||
# (abgestürztes Onboarding-Interview soll nicht dauerhaft blockieren)
|
||
from archivar.onboarding import cleanup_stale_locks
|
||
removed = cleanup_stale_locks()
|
||
if removed > 0:
|
||
logger.info("[rocketchat] A1b: Stale-Lock-Cleanup — %d Locks entfernt", removed)
|
||
|
||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||
self.ddp = DDPClient(
|
||
host=host,
|
||
on_connected_cb=self._on_ddp_connected,
|
||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events
|
||
)
|
||
if not self.ddp.connect_and_login(self._auth_token):
|
||
logger.error("[rocketchat] DDP connect/login failed")
|
||
return False
|
||
self._rooms = self.rest.get_rooms()
|
||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||
|
||
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
||
if self.ddp.connected:
|
||
room_events_sub = self.ddp.subscribe_room_events()
|
||
if room_events_sub:
|
||
logger.info("[rocketchat] A1b: Subscribed to stream-notify-room (rooms-changed) — sub_id=%s", room_events_sub)
|
||
else:
|
||
logger.warning("[rocketchat] A1b: Failed to subscribe to stream-notify-room")
|
||
|
||
# ── M13: Room-Map Garbage Collection ───────────────────────────
|
||
# Läuft VOR Subscription und VOR Archivar-Init (B9).
|
||
# Entfernt Räume aus room-map.json, in denen der Agent nicht mehr
|
||
# Mitglied ist (gekickt / verlassen). Verhindert Ghost-Subscriptions
|
||
# und Echo-Katastrophen bei Multi-Agent-Setups.
|
||
self._sync_room_map_with_membership()
|
||
# ── Ende M13 ───────────────────────────────────────────────────
|
||
|
||
for room in self._rooms:
|
||
rid = room["id"]
|
||
# B8: excluded_rooms nicht subscriben
|
||
if rid in self._excluded_room_ids:
|
||
logger.info(
|
||
"[rocketchat] Room '%s' (%s) excluded — not subscribing",
|
||
room["name"], rid,
|
||
)
|
||
continue
|
||
sub_id = self.ddp.subscribe_room(rid)
|
||
if sub_id:
|
||
self._subscribed_rooms.add(rid)
|
||
self._room_info[rid] = {"name": room["name"], "type": room["type"]}
|
||
logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], rid)
|
||
logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms))
|
||
# Build user→rooms map for virtual chat_id translation.
|
||
# Each Rocket.Chat user gets a synthetic "user:<username>" chat_id that
|
||
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
||
# session per user across all rooms, enabling shared context.
|
||
self._user_rooms.clear()
|
||
user_room_count = 0
|
||
for room in self._rooms:
|
||
rid = room["id"]
|
||
t = room["type"]
|
||
if t == "d":
|
||
# Handle Direct Message rooms
|
||
usernames = [u.lower() for u in room.get("usernames", [])]
|
||
if not usernames:
|
||
logger.warning("[rocketchat] DM room %s has no usernames field or is empty", rid)
|
||
# Try to extract usernames from room name as fallback
|
||
name = room.get("name", "")
|
||
if "DM mit " in name:
|
||
# Parse usernames from name like "DM mit andreas, bernd"
|
||
try:
|
||
user_part = name.split("DM mit ", 1)[1]
|
||
usernames = [u.strip().lower() for u in user_part.split(",")]
|
||
except Exception:
|
||
logger.debug("[rocketchat] Could not parse usernames from room name: %s", name)
|
||
|
||
for uname in usernames:
|
||
if uname and uname != (self.user or "").lower():
|
||
virt = f"user:{uname}"
|
||
if virt not in self._user_rooms:
|
||
self._user_rooms[virt] = []
|
||
if rid not in self._user_rooms[virt]:
|
||
self._user_rooms[virt].append(rid)
|
||
user_room_count += 1
|
||
else:
|
||
# For channels/groups, track rooms for potential future use
|
||
# Users can still be mentioned in these rooms
|
||
logger.debug("[rocketchat] Non-DM room %s (type: %s) tracked but not mapped to users", rid, t)
|
||
logger.info("[rocketchat] Built user-room map: %d users, %s",
|
||
len(self._user_rooms),
|
||
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
||
# Archivar initialisieren (Embedding-basierte Klassifikation)
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
try:
|
||
await self.archivar.initialize()
|
||
# Feed the actual subscribed room IDs to the router so it can
|
||
# validate targets and store unrouteable messages in doc_store.
|
||
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||
logger.info("[rocketchat] Archivar initialisiert — Thematischer Raum-Router aktiv (room-map.json)")
|
||
|
||
# FIX E: Raum-Map Summary für System-Prompt bauen
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] FIX E: Raum-Map Summary gebaut (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
|
||
# Auto-Onboarding: Prüfe, ob alle subscribed Räume in der Map sind
|
||
subscribed_with_types = {
|
||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||
for rid, info in self._room_info.items()
|
||
}
|
||
# P1-4: Prüfe ob ein persistierter Onboarding-State existiert
|
||
persisted_onboarding = self.archivar._state.get_onboarding_state()
|
||
if persisted_onboarding and persisted_onboarding.get("operator_room_id"):
|
||
# Bug C: Zombie-State-Validierung
|
||
# Prüfe ob der Operator-Raum noch subscribed ist und der Lock aktiv
|
||
op_room = persisted_onboarding.get("operator_room_id", "")
|
||
op_room_subscribed = op_room in self._room_info
|
||
from archivar.onboarding import is_onboarding_locked
|
||
lock_active = False
|
||
if op_room_subscribed:
|
||
# Prüfe ob mindestens ein missing_room-Lock aktiv ist
|
||
for room in persisted_onboarding.get("missing_rooms", []):
|
||
if is_onboarding_locked(room.get("room_id", "")):
|
||
lock_active = True
|
||
break
|
||
if op_room_subscribed and lock_active:
|
||
logger.info("[rocketchat] P1-4: Persistierten Onboarding-State wiederhergestellt")
|
||
self._onboarding_state = persisted_onboarding
|
||
self.archivar._stats["onboarding_active"] = True
|
||
else:
|
||
logger.warning(
|
||
"[rocketchat] Bug C: Zombie-Onboarding-State verworfen — "
|
||
"op_room_subscribed=%s, lock_active=%s",
|
||
op_room_subscribed, lock_active,
|
||
)
|
||
self.archivar._state.clear_onboarding_state()
|
||
# F8: Onboarding State Machine laden und Restart-Logik prüfen
|
||
from archivar.onboarding_state import OnboardingStateMachine, OnboardingState
|
||
if not hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm = OnboardingStateMachine()
|
||
self._onboarding_sm.load()
|
||
sm = self._onboarding_sm
|
||
if sm.state == OnboardingState.ACTIVE:
|
||
logger.info("[rocketchat] F8: Onboarding bereits abgeschlossen — produktiver Pfad")
|
||
elif sm.state == OnboardingState.ERROR:
|
||
logger.warning(
|
||
"[rocketchat] F8: Onboarding im ERROR-State — "
|
||
"::onboarding resume oder ::onboarding reset nötig. "
|
||
"Fehler: %s", sm._data.error_message
|
||
)
|
||
elif sm.is_active or sm.is_paused:
|
||
logger.info(
|
||
"[rocketchat] F8: Onboarding passiv fortgesetzt — state=%s, step=%s",
|
||
sm.state.value, sm.progress_text,
|
||
)
|
||
# State wiederherstellen ohne erneut zu starten
|
||
if not self.archivar._stats.get("onboarding_active", False):
|
||
self.archivar._stats["onboarding_active"] = True
|
||
# B9: Trigger-Bedingungen für Auto-Onboarding
|
||
# 1. MULTIROOM_AGENT=true (bereits geprüft durch _MULTIROOM())
|
||
# 2. Gateway findet Räume die nicht in room-map.json stehen
|
||
# 3. DM wird jetzt auch thematisch onboardet (Thema, Keywords, Catch-All)
|
||
# B9 fix (a): Idempotenz-Guard — wenn Onboarding bereits läuft, nicht erneut starten
|
||
if self.archivar._stats.get("onboarding_active", False):
|
||
logger.info("[rocketchat] B9: Onboarding bereits aktiv — überspringe Reconnect-Trigger")
|
||
# B9 fix (b): is_reconnect — prüfe ob neue Räume hinzugekommen sind
|
||
elif is_reconnect and self.archivar._room_map and len(self.archivar._room_map.rooms) > 0:
|
||
# Prüfe ob Räume existieren, die nicht in room-map.json stehen
|
||
subscribed_with_types = {
|
||
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:
|
||
logger.info("[rocketchat] B9: Reconnect — %d neue Räume gefunden, starte Onboarding", len(missing))
|
||
asyncio.ensure_future(self._start_onboarding(missing))
|
||
else:
|
||
# Keine neuen c/p-Räume — aber DM könnte noch Theme brauchen
|
||
asyncio.ensure_future(self._start_onboarding([]))
|
||
else:
|
||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||
if missing:
|
||
logger.info("[rocketchat] B9: %d Räume fehlen in room-map.json — starte Auto-Onboarding", len(missing))
|
||
asyncio.ensure_future(self._start_onboarding(missing))
|
||
else:
|
||
# B9: Prüfe ob room-map.json leer ist (0 Räume) → trotzdem Onboarding
|
||
room_count = len(self.archivar._room_map.rooms) if self.archivar._room_map else 0
|
||
if room_count == 0:
|
||
non_dm_rooms = {rid: info for rid, info in subscribed_with_types.items()
|
||
if info.get("type") in ("c", "p")}
|
||
if non_dm_rooms:
|
||
logger.info("[rocketchat] B9: room-map.json ist leer (0 Räume) — starte Auto-Onboarding für %d Räume", len(non_dm_rooms))
|
||
all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()]
|
||
asyncio.ensure_future(self._start_onboarding(all_rooms))
|
||
else:
|
||
# Nur DM — trotzdem Onboarding für DM-Theme
|
||
asyncio.ensure_future(self._start_onboarding([]))
|
||
else:
|
||
# Map hat Räume, keine neuen — aber DM könnte Theme brauchen
|
||
asyncio.ensure_future(self._start_onboarding([]))
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||
self._mark_connected()
|
||
self._running = True
|
||
self._listen_task = asyncio.create_task(self._listen_loop())
|
||
self._last_activity = time.time()
|
||
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
||
logger.info("[rocketchat] Connected to %s", self.base_url)
|
||
return True
|
||
|
||
async def _reconnect_ddp(self) -> bool:
|
||
"""Bug 7: DDP-Reconnect mit M13 GC.
|
||
|
||
Ersetzt DDPClient.reconnect_and_restore(), die alte Subscriptions
|
||
blind resubscribed hat und M13 GC umging. Diese Methode:
|
||
1. Trennt alte DDP-Verbindung
|
||
2. Verbindet DDP neu (connect_and_login)
|
||
3. Holt aktuelle Mitgliedschaft via REST get_rooms()
|
||
4. Führt M13 GC durch (_sync_room_map_with_membership)
|
||
5. Subscribed nur Räume, in denen der Agent aktuell Mitglied ist
|
||
6. Aktualisiert Archivar subscribed_room_ids
|
||
|
||
Returns True bei Erfolg, False bei Fehler.
|
||
"""
|
||
if not self._auth_token:
|
||
logger.error("[rocketchat] _reconnect_ddp: Kein auth token")
|
||
return False
|
||
|
||
# A1b: Stale-Lock-Cleanup bei Reconnect (F6 Re-Review Fix 1)
|
||
# Ohne Gateway-Restart müssen stale Locks auch bereinigt werden.
|
||
from archivar.onboarding import cleanup_stale_locks
|
||
removed = cleanup_stale_locks()
|
||
if removed > 0:
|
||
logger.info("[rocketchat] A1b: Stale-Lock-Cleanup bei Reconnect — %d Locks entfernt", removed)
|
||
|
||
# 1. Alte DDP-Verbindung trennen
|
||
if self.ddp:
|
||
self.ddp.disconnect()
|
||
self.ddp = None
|
||
|
||
# 2. DDP neu verbinden
|
||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||
self.ddp = DDPClient(
|
||
host=host,
|
||
on_connected_cb=self._on_ddp_connected,
|
||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3)
|
||
)
|
||
if not self.ddp.connect_and_login(self._auth_token):
|
||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||
return False
|
||
|
||
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
|
||
if self.ddp.connected:
|
||
room_events_sub = self.ddp.subscribe_room_events()
|
||
if room_events_sub:
|
||
logger.info("[rocketchat] _reconnect_ddp: A1b re-subscribed to stream-notify-room — sub_id=%s", room_events_sub)
|
||
else:
|
||
logger.warning("[rocketchat] _reconnect_ddp: A1b failed to re-subscribe to stream-notify-room")
|
||
|
||
# 3. Aktuelle Mitgliedschaft via REST
|
||
self._rooms = self.rest.get_rooms()
|
||
logger.info("[rocketchat] _reconnect_ddp: REST get_rooms returned %d rooms", len(self._rooms))
|
||
|
||
# 4. M13 GC
|
||
self._sync_room_map_with_membership()
|
||
|
||
# 4b. FIX B: Raum-Map Summary nach M13 GC neu bauen
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] _reconnect_ddp: Raum-Map Summary nach M13 GC aktualisiert (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
|
||
# 5. Nur aktuelle Mitglieder-Räume subscriben (excluded_rooms ausgenommen)
|
||
self._subscribed_rooms.clear()
|
||
self._room_info.clear()
|
||
for room in self._rooms:
|
||
rid = room["id"]
|
||
# B8: excluded_rooms nicht subscriben
|
||
if rid in self._excluded_room_ids:
|
||
logger.info(
|
||
"[rocketchat] _reconnect_ddp: Room '%s' (%s) excluded — not subscribing",
|
||
room["name"], rid,
|
||
)
|
||
continue
|
||
sub_id = self.ddp.subscribe_room(rid)
|
||
if sub_id:
|
||
self._subscribed_rooms.add(rid)
|
||
self._room_info[rid] = {"name": room["name"], "type": room["type"]}
|
||
logger.info("[rocketchat] _reconnect_ddp: %d rooms subscribed", len(self._subscribed_rooms))
|
||
|
||
# 6. Archivar subscribed_room_ids aktualisieren
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
try:
|
||
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||
logger.info("[rocketchat] _reconnect_ddp: Archivar subscribed_room_ids aktualisiert")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] _reconnect_ddp: Archivar-Update fehlgeschlagen: %s", e)
|
||
|
||
return True
|
||
|
||
def _schedule_idle_timer(self) -> None:
|
||
"""Schedule idle timer to mark bot as away when inactive.
|
||
|
||
V8.6: Deaktiviert wenn PresenceEngine aktiv ist (ROCKETCHAT_PRESENCE_ENABLED=true).
|
||
Der alte _set_away-Timer kann eine DDP-Subscription-Endlosschleife auslösen
|
||
(Rainer-Warnung). Die PresenceEngine übernimmt das Status-Management.
|
||
"""
|
||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||
logger.debug("[rocketchat] V8.6: _schedule_idle_timer skipped — PresenceEngine active")
|
||
return
|
||
if self._status_timer:
|
||
self._status_timer.cancel()
|
||
|
||
def _set_away():
|
||
if self.ddp:
|
||
self.ddp.set_status("away")
|
||
|
||
self._status_timer = threading.Timer(300.0, _set_away) # 5 minutes
|
||
self._status_timer.daemon = True
|
||
self._status_timer.start()
|
||
|
||
async def _process_incoming(self, msg_obj) -> None:
|
||
"""Process an incoming message from the DDP queue."""
|
||
if not isinstance(msg_obj, dict):
|
||
return
|
||
|
||
# Check if this is a button click response by looking for specific fields.
|
||
# TWO detection paths:
|
||
# 1. Native Rocket.Chat button events (triggerId + actions + triggerSender + payload)
|
||
# 2. In-chat button responses via msg_in_chat_window, which arrive as regular
|
||
# text messages containing a question_id::choice payload (e.g. "bypass_001::Ja").
|
||
text = msg_obj.get("msg", "")
|
||
is_button_response = (
|
||
(msg_obj.get("triggerId") and
|
||
msg_obj.get("actions") and
|
||
msg_obj.get("params", {}).get("triggerSender") and
|
||
msg_obj.get("params", {}).get("payload"))
|
||
or (text and "::" in text
|
||
and not text.startswith("CLARIFY:")
|
||
and not text.startswith("ARCHIVAR_CLARIFY:")
|
||
and not text.startswith("MOVE_REQ:")
|
||
and text.split("::", 1)[0].strip() != "")
|
||
or (text and text.startswith("CLARIFY:"))
|
||
or (text and text.startswith("ARCHIVAR_CLARIFY:"))
|
||
)
|
||
|
||
# Check for CLARIFY button responses
|
||
is_clarify_response = text.startswith("CLARIFY:") if text else False
|
||
|
||
msg_id = msg_obj.get("_id", "")
|
||
room_id = msg_obj.get("rid", "")
|
||
user_info = msg_obj.get("u", {})
|
||
username = (user_info.get("username", "") or "").lower() # normalize case
|
||
msg_type = msg_obj.get("t", "")
|
||
logger.debug("Message received: room=%s, user=%s, t=%s", room_id, username, msg_type)
|
||
|
||
# NEW: Check for file attachments in the message and enrich the text
|
||
file_info = msg_obj.get("file")
|
||
attachments = msg_obj.get("attachments", [])
|
||
if file_info or attachments:
|
||
file_details = []
|
||
seen_ids = set()
|
||
base_url = self.base_url.rstrip("/")
|
||
# Process file object if present (has precise MIME type)
|
||
if file_info and isinstance(file_info, dict):
|
||
filename = file_info.get("name", "unknown")
|
||
filetype = file_info.get("type", "unknown")
|
||
file_id = file_info.get("_id")
|
||
if file_id and filename:
|
||
seen_ids.add(file_id)
|
||
download_url = f"{base_url}/file-upload/{file_id}/{filename}"
|
||
file_details.append(f"[FILE] {filename} ({filetype})\nDownload: {download_url}")
|
||
# Process attachments if present (skip duplicates already covered by file_info)
|
||
if attachments and isinstance(attachments, list):
|
||
for attachment in attachments:
|
||
if isinstance(attachment, dict) and attachment.get("type") == "file":
|
||
title = attachment.get("title", "unknown")
|
||
title_link = attachment.get("title_link", "")
|
||
if title_link:
|
||
if title_link.startswith("/"):
|
||
download_url = f"{base_url}{title_link}"
|
||
else:
|
||
download_url = f"{base_url}/{title_link}"
|
||
# Extract file_id from title_link to detect duplicates
|
||
link_id = title_link.split("/")[2] if title_link.startswith("/file-upload/") else None
|
||
if link_id and link_id in seen_ids:
|
||
continue # Already covered by precise file_info
|
||
file_details.append(f"[FILE] {title} (file)\nDownload: {download_url}")
|
||
# Add file information to message text
|
||
if file_details:
|
||
file_info_text = "\n".join(file_details)
|
||
if text:
|
||
text = f"{text}\n\n{file_info_text}"
|
||
else:
|
||
text = file_info_text
|
||
msg_obj["msg"] = text
|
||
|
||
# ── P0+P1: Reply-Quote-Stripping ──────────────────────────────────
|
||
# Verhindert Fehl-Routing durch zitierte Parent-Nachrichten.
|
||
# Zweistufig defensiv:
|
||
# 1. Attachments-basiert (Rocket.Chat Reply-Attachments)
|
||
# 2. Text-basiert (Markdown-Blockquotes, [quote]-Blöcke)
|
||
# routing_text (ohne Quote) → Archivar/Keyword-Matcher/classify_and_route
|
||
# display_text (mit Quote) → Agent-Dispatch + Conversation-History
|
||
routing_text, display_text, quote_stripped = strip_reply_quote_for_routing(
|
||
text, attachments
|
||
)
|
||
if quote_stripped:
|
||
routing_counter.increment('reply_quote_stripped')
|
||
logger.debug(
|
||
"[rocketchat] P0: Reply-Quote gestrippt — "
|
||
"routing_text=%s, display_text=%s",
|
||
routing_text[:80], display_text[:80],
|
||
)
|
||
# text bleibt display_text für Agent/History;
|
||
# routing_text wird für Archivar-Klassifikation verwendet.
|
||
# ── Ende P0+P1 ────────────────────────────────────────────────────
|
||
|
||
# Skip own messages (case-insensitive comparison)
|
||
filter_match = (username == (self.user or "").lower())
|
||
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
||
if filter_match:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Own message filtered — skipping")
|
||
routing_counter.increment('self_message_filtered')
|
||
logger.info("ROUTING BYPASS: reason=self_message_filtered, origin_room=%s", room_id)
|
||
return
|
||
if not text or not room_id:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Empty text/room_id — skipping")
|
||
return
|
||
# Skip system messages
|
||
if msg_obj.get("t"):
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: System message (t=%s) — skipping", msg_obj.get("t"))
|
||
return
|
||
|
||
logger.debug("Message passed filter: %s", msg_id)
|
||
|
||
# Update activity
|
||
self._last_activity = time.time()
|
||
room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
|
||
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
|
||
|
||
# ── V8.6: PresenceEngine — active_tasks++ und busy setzen ──
|
||
# Graceful degradation: wenn _presence_engine nicht existiert
|
||
# (z.B. in Tests die __new__ statt __init__ verwenden), skip.
|
||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||
if _has_presence:
|
||
self._presence_engine.set_current_room(room_name)
|
||
self._presence_engine.increment_active_tasks()
|
||
self._presence_engine.update_presence()
|
||
logger.info("[presence] active_tasks++ → %d (room=%s)",
|
||
self._presence_engine._active_tasks, room_name)
|
||
|
||
try:
|
||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||
# generischen Hermes-Agent-Onboarding erkannt werden.
|
||
inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username)
|
||
if inline_handled:
|
||
logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch")
|
||
routing_counter.increment('inline_command_handled')
|
||
logger.info("ROUTING BYPASS: reason=inline_command_handled, origin_room=%s", room_id)
|
||
return
|
||
# ── Ende R5 Inline-Command-Erkennung ────────────────────────────────
|
||
|
||
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
||
# P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht
|
||
if _MULTIROOM() and self._conversation_history is not None:
|
||
await self._conversation_history.add(room_id, "user", display_text)
|
||
|
||
# V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
# Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen)
|
||
# P1: routing_text für Topic-Extraktion (ohne Quote)
|
||
topic = routing_text[:80].replace("\n", " ").strip()
|
||
if topic:
|
||
await self._multiroom_context.add(room_id, room_name, topic)
|
||
|
||
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
|
||
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
|
||
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
|
||
_THEMATIC_TARGET_ROOM.set("")
|
||
|
||
# ── A1b: Lazy-Onboarding-Check (Fallback-Pfad) ────────────────────
|
||
# Wenn eine Nachricht aus einem Raum kommt, der nicht in room-map.json
|
||
# steht, und kein Onboarding aktiv ist → Onboarding triggern.
|
||
# Dies fängt Fälle ab, wo das DDP-Event nicht angekommen ist.
|
||
# P0-4: room_type kann "unknown" sein wenn der Raum nicht in _room_info
|
||
# ist (z.B. nach Reconnect). Der lazy_onboarding_check filtert selbst
|
||
# DM-Räume und excluded rooms — wir müssen hier nur DM ausschließen.
|
||
if (
|
||
_MULTIROOM()
|
||
and self.archivar is not None
|
||
and not self.archivar._stats.get("onboarding_active", False)
|
||
and room_type != "d" # P0-4: Nur DM ausschließen, "unknown" durchlassen
|
||
):
|
||
lazy_result = self.archivar.lazy_onboarding_check(
|
||
room_id=room_id,
|
||
room_name=room_name,
|
||
room_type=room_type,
|
||
)
|
||
if lazy_result is not None:
|
||
logger.info(
|
||
"[rocketchat] A1b: Lazy-Onboarding getriggert — "
|
||
"unbekannter Raum: room=%s, name=%s",
|
||
room_id[:12], room_name,
|
||
)
|
||
await self._start_onboarding([lazy_result])
|
||
# Nachricht nicht weiter verarbeiten — Onboarding läuft jetzt
|
||
routing_counter.increment('lazy_onboarding_triggered')
|
||
logger.info("ROUTING BYPASS: reason=lazy_onboarding_triggered, origin_room=%s", room_id)
|
||
return
|
||
# ── Ende A1b Lazy-Onboarding ─────────────────────────────────────
|
||
|
||
# ── Thema B: Onboarding-Guard — Plugin-onboarding vor generischem Hermes-onboarding ──
|
||
# Wenn Onboarding aktiv ist und die Nachricht aus einem Raum kommt,
|
||
# der NICHT in der room-map.json steht und NICHT der Operator-DM ist,
|
||
# dann die Nachricht abfangen. Verhindert dass das generische
|
||
# Hermes-Agent-Onboarding (Profile, Skills, Cronjobs) das
|
||
# Plugin-Onboarding (Raum-Interview) übersteuert.
|
||
if (
|
||
_MULTIROOM()
|
||
and self.archivar is not None
|
||
and self.archivar._stats.get("onboarding_active", False)
|
||
and room_type != "d"
|
||
):
|
||
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||
# Prüfe ob der Raum in der room-map.json steht
|
||
room_in_map = (
|
||
self.archivar._room_map is not None
|
||
and room_id in self.archivar._room_map.rooms
|
||
)
|
||
if not room_in_map and room_id != operator_room:
|
||
# Raum ist unbekannt und Onboarding läuft → Nachricht abfangen
|
||
logger.info(
|
||
"[rocketchat] Thema B: Onboarding-Guard — Nachricht aus unbekanntem Raum "
|
||
"während Onboarding abgefangen: room=%s, name=%s",
|
||
room_id[:12], room_name,
|
||
)
|
||
await self._post_message_with_retry(
|
||
room_id,
|
||
"🔄 Ich richte mich gerade ein — einen Moment bitte. "
|
||
"Das Onboarding-Interview läuft in deinem DM-Kanal. "
|
||
"Sobald ich fertig bin, bin ich für dich da!"
|
||
)
|
||
routing_counter.increment('onboarding_guard_blocked')
|
||
logger.info("ROUTING BYPASS: reason=onboarding_guard_blocked, origin_room=%s", room_id)
|
||
return
|
||
# ── Ende Thema B Onboarding-Guard ────────────────────────────────────
|
||
|
||
# ── CLARIFY Response Handling ───────────────────────────────────
|
||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
||
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
||
is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False
|
||
if is_clarify_response and text.startswith("CLARIFY:"):
|
||
routing_counter.increment('clarify_answer_bypass')
|
||
logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id)
|
||
try:
|
||
if "::" in text:
|
||
# Neues Format: CLARIFY:<id>::<choice> (via _build_custom_buttons)
|
||
prefix_part, choice = text.split("::", 1)
|
||
clarify_id = prefix_part.split(":", 1)[1]
|
||
else:
|
||
# Altes Format: CLARIFY:<id>:other (Other-Button)
|
||
parts = text.split(":", 2)
|
||
if len(parts) != 3:
|
||
logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping")
|
||
return
|
||
_, clarify_id, choice = parts
|
||
if choice == "other":
|
||
# For "Other" button, enable text capture mode
|
||
from tools.clarify_gateway import mark_awaiting_text
|
||
mark_awaiting_text(clarify_id)
|
||
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
|
||
return
|
||
elif choice.isdigit():
|
||
# Numeric choice → resolve the clarify immediately
|
||
idx = int(choice)
|
||
resolved_text: Optional[str] = None
|
||
try:
|
||
from tools.clarify_gateway import _entries as _clarify_entries
|
||
entry = _clarify_entries.get(clarify_id)
|
||
if entry and entry.choices and 0 <= idx < len(entry.choices):
|
||
resolved_text = entry.choices[idx]
|
||
except Exception:
|
||
resolved_text = None
|
||
if resolved_text is None:
|
||
# Race: entry vanished. Echo the index.
|
||
resolved_text = f"choice {idx + 1}"
|
||
# Resolve via gateway and clean up
|
||
self._clarify_state.pop(clarify_id, None)
|
||
try:
|
||
from tools.clarify_gateway import resolve_gateway_clarify
|
||
resolved = resolve_gateway_clarify(clarify_id, resolved_text)
|
||
if resolved:
|
||
logger.info(
|
||
"[rocketchat] Clarify %s resolved: %s (session=%s)",
|
||
clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"),
|
||
)
|
||
else:
|
||
logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id)
|
||
except Exception as exc:
|
||
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
|
||
# Don't route to agent — this was a button click
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY resolved — skipping")
|
||
return
|
||
else:
|
||
# Unknown token — let it fall through as regular text
|
||
logger.warning("[rocketchat] Unknown clarify token: %s", choice)
|
||
except Exception as e:
|
||
logger.debug("[rocketchat] Error processing CLARIFY response: %s", e)
|
||
|
||
# ── V8.2.1 A2: ARCHIVAR_CLARIFY (Nachklärung) Response Handling ──
|
||
if is_archivar_clarify:
|
||
routing_counter.increment('archivar_clarify_bypass')
|
||
logger.info("ROUTING BYPASS: reason=archivar_clarify_bypass, origin_room=%s", room_id)
|
||
try:
|
||
# Format: ARCHIVAR_CLARIFY:<choice>
|
||
parts = text.split(":", 2)
|
||
if len(parts) >= 2:
|
||
choice = parts[1].strip()
|
||
strategie_topics = {"absprache", "planung", "strategie", "entscheidung"}
|
||
if choice in strategie_topics:
|
||
# Strategie-Thema → Ring-Zustand 'jetzt' (30 Min), KEIN Lernen
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
self.archivar._state.set_ring_state(room_id, "jetzt", ttl_minutes=30)
|
||
logger.info(
|
||
"[rocketchat] V8.2.1 A2: Strategie-Modus aktiviert — "
|
||
"topic=%s, room=%s, ring=jetzt (30 Min)",
|
||
choice, room_id[:8],
|
||
)
|
||
await self._post_message_with_retry(
|
||
room_id,
|
||
f"🎯 Verstanden — '{choice}' ist ein Strategie-Thema. "
|
||
"Ich bleibe hier und lerne nichts dazu."
|
||
)
|
||
elif choice == "anderer_grund":
|
||
# ANDERER GRUND → normales Lernen
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
logger.info(
|
||
"[rocketchat] V8.2.1 A2: ANDERER GRUND — "
|
||
"normales Lernen in room %s",
|
||
room_id[:8],
|
||
)
|
||
await self._post_message_with_retry(
|
||
room_id,
|
||
"👍 Alles klar — ich lerne daraus fürs nächste Mal."
|
||
)
|
||
else:
|
||
logger.warning("[rocketchat] Unknown ARCHIVAR_CLARIFY choice: %s", choice)
|
||
return # Nachricht verarbeitet — keine weitere Verarbeitung
|
||
except Exception as e:
|
||
logger.debug("[rocketchat] Error processing ARCHIVAR_CLARIFY response: %s", e)
|
||
|
||
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
||
if _MULTIROOM() and self.archivar is not None and self.archivar._stats.get("onboarding_active", False):
|
||
stripped = text.strip()
|
||
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
|
||
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||
is_operator_room = (operator_room and room_id == operator_room)
|
||
# P0-1: Review-Flow-Phasen (review_room, review_butler, review_fakt)
|
||
# müssen ebenfalls als Onboarding erkannt werden, damit
|
||
# Button-Klicks (REVIEW_ROOM_EDIT::rid::edit etc.) nicht
|
||
# als Freitext an den LLM-Agenten durchgereicht werden.
|
||
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||
is_onboarding = (
|
||
(is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
|
||
or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button
|
||
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
|
||
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
||
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
||
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
||
or (is_operator_room and self._onboarding_state.get("phase") in _review_phases) # P0-1: Review-Flow Phasen
|
||
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||
or (is_operator_room and stripped.isdigit()) # Catch-All-Wechsel
|
||
or (is_operator_room and stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten")) # Ablehnung
|
||
)
|
||
if is_onboarding:
|
||
await self._process_onboarding_response(text, room_id)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping")
|
||
routing_counter.increment('onboarding_active_skip')
|
||
logger.info("ROUTING BYPASS: reason=onboarding_active_skip, origin_room=%s", room_id)
|
||
return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig
|
||
|
||
# ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ────────
|
||
# Der User klickt einen Button (MOVE_REQ:room_id::✅Ja) oder antwortet
|
||
# mit "1"/"2"/"3" aus demselben Raum wie die Frage.
|
||
# Dies MUSS vor dem Archivar geprüft werden, sonst wird die Antwort
|
||
# als thematische Frage klassifiziert und ins Catch-All kopiert.
|
||
if room_id in self._pending_move_requests:
|
||
move_req = self._pending_move_requests.pop(room_id)
|
||
# ── V8.6: PresenceEngine — Move-Request beantwortet → clear ──
|
||
if _has_presence:
|
||
self._presence_engine.clear_move_request(room_id)
|
||
choice = text.strip()
|
||
|
||
# Neues Format: MOVE_REQ:<room_id>::<choice> (native Buttons)
|
||
if choice.startswith("MOVE_REQ:") and "::" in choice:
|
||
_, choice = choice.split("::", 1)
|
||
choice = choice.strip()
|
||
# Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Generell" → "2"
|
||
if choice and choice[0] in "123":
|
||
choice = choice[0]
|
||
elif choice and choice[:2] in ("1️⃣", "2️⃣", "3️⃣"):
|
||
choice = choice[:2]
|
||
# Altes Format: "1"/"2"/"3" = numerische Antwort
|
||
# Neues Format: "1️⃣", "2️⃣", "3️⃣" = Emoji-Nummern
|
||
elif choice in ("1", "2", "3") or choice in ("1️⃣", "2️⃣", "3️⃣"):
|
||
num = int(choice[0]) # Extrahiere die Zahl (entweder direkt oder aus dem Emoji)
|
||
if num == 1:
|
||
choice = "rüberkopieren"
|
||
elif num == 2:
|
||
choice = "generell" # v6: 2 = Generell hier bleiben (sticky)
|
||
else:
|
||
choice = "hier bleiben" # v6: 3 = Hier bleiben (nur diesmal)
|
||
choice = choice.lower()
|
||
|
||
# Neue Mapping-Logik für verbesserte Button-UX (v6)
|
||
feedback_type = "stay" # Default
|
||
forwarded = False
|
||
if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"):
|
||
# 1️⃣ Rüber → Antwort im Zielraum (V8.1 P3: echtes Move, kein Copy)
|
||
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
|
||
_THEMATIC_TARGET_ROOM.set(move_req["target_room"])
|
||
forwarded = True
|
||
feedback_type = "confirm"
|
||
# ── V8.3-5: Topic für Sticky extrahieren ──────────────
|
||
move_sticky_topic = ""
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
target_name = move_req.get("target_name", "")
|
||
move_sticky_topic = room_name_to_topic(target_name) if target_name else ""
|
||
# V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL)
|
||
self._session_room_preferences[room_id] = {
|
||
"target_room": move_req["target_room"],
|
||
"target_name": move_req.get("target_name", "Zielraum"),
|
||
"sticky_topic": move_sticky_topic,
|
||
"expires_at": time.time() + 1800, # 30 Minuten
|
||
}
|
||
# V8.1.1 R2: Ring-GC bei Move — stale Topics aus Ursprungsraum entfernen
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
move_topic = move_req.get("text", "")[:80].replace("\n", " ").strip()
|
||
if move_topic:
|
||
target_name = move_req.get("target_name", "")
|
||
await self._multiroom_context.move_gc(
|
||
origin_room_id=room_id,
|
||
target_room_id=move_req["target_room"],
|
||
topic=move_topic,
|
||
room_name=target_name,
|
||
)
|
||
# ── V8.3-3: Move für Widerspruchs-Routine speichern ──
|
||
self._recent_auto_routes[room_id] = {
|
||
"origin_room": room_id,
|
||
"target_room": move_req["target_room"],
|
||
"topic": move_sticky_topic,
|
||
"timestamp": time.time(),
|
||
"origin_message_id": move_req.get("message_id", ""),
|
||
"target_message_id": "",
|
||
}
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — "
|
||
"room=%s → target=%s, topic='%s' (30 Min, confirm_move)",
|
||
room_id[:8], move_req.get("target_name", "?")[:20], move_sticky_topic,
|
||
)
|
||
elif choice in ("2", "2️⃣", "generell", "generell hier bleiben", "stay_here"):
|
||
# 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag
|
||
# P0-B: Thematischer Sticky (v7) — Thema aus Match-Ergebnis extrahieren
|
||
# V7-2: _sticky_rooms entfernt — thematisches never_route ersetzt räumlichen Bypass
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
try:
|
||
# Extrahiere Topic aus dem gematchten Raum-Namen
|
||
target_name = move_req.get("target_name", "")
|
||
topic = room_name_to_topic(target_name)
|
||
if topic:
|
||
self.archivar._state.set_never_route(room_id, topic)
|
||
logger.info(
|
||
"[rocketchat] Sticky persisted: room %s, topic '%s' → never_route (v7)",
|
||
room_id[:8], topic,
|
||
)
|
||
else:
|
||
logger.warning(
|
||
"[rocketchat] Sticky: kein Topic extrahierbar aus '%s'",
|
||
target_name,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] Failed to persist sticky decision: %s", e)
|
||
await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt dauerhaft)")
|
||
feedback_type = "never"
|
||
else:
|
||
# 3️⃣ Nur diesmal → Antwort im Ursprungsraum (nur diesmal, kein Sticky)
|
||
# V8.2.1 A2: Nach stay_once → Nachklärung mit Strategie-Buttons
|
||
await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
|
||
feedback_type = "stay"
|
||
# V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
if self.archivar._should_trigger_nachklaerung("stay_once"):
|
||
# Keywords des Zielraums als lesbaren Text einbauen
|
||
target_room_id = move_req.get("target_room", "")
|
||
target_keywords = []
|
||
if target_room_id and self.archivar._room_map is not None:
|
||
target_entry = self.archivar._room_map.rooms.get(target_room_id)
|
||
if target_entry:
|
||
target_keywords = target_entry.keywords_100[:5]
|
||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons(
|
||
keywords=target_keywords if target_keywords else None
|
||
)
|
||
await self._send_archivar_buttons(
|
||
room_id,
|
||
nachklaerung_buttons["text"],
|
||
{"actions": nachklaerung_buttons["actions"]},
|
||
)
|
||
logger.info(
|
||
"[rocketchat] V8.2.1 A2: Nachklärung gesendet — "
|
||
"Strategie-Buttons in room %s", room_id[:8],
|
||
)
|
||
# Stay-Counter: Wenn der User 3× in 10 Min "Hier bleiben" klickt,
|
||
# wird der Raum automatisch auf "never_route" gesetzt.
|
||
# P1-3: stay_tracker ist jetzt persistent in ArchivarState
|
||
# P0-B: Thematischer Sticky (v7) — Thema aus Match-Ergebnis extrahieren
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
count = self.archivar._state.update_stay_tracker(room_id, username)
|
||
if count >= 3:
|
||
try:
|
||
target_name = move_req.get("target_name", "")
|
||
topic = room_name_to_topic(target_name)
|
||
if topic:
|
||
self.archivar._state.set_never_route(room_id, topic)
|
||
# V7-2: _sticky_rooms entfernt — thematisches never_route reicht
|
||
logger.info("[rocketchat] Auto-promoted to never_route after %d stays in room %s, topic '%s'", count, room_id[:8], topic)
|
||
await self._post_message_with_retry(room_id, "🔒 Ich habe gemerkt, dass du hier bleiben möchtest — dieser Raum wird ab jetzt nicht mehr automatisch geroutet.")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] Failed to auto-promote sticky: %s", e)
|
||
|
||
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
|
||
if _MULTIROOM() and self.archivar is not None and move_req.get("message_id"):
|
||
user_id = user_info.get("_id", "")
|
||
await self.archivar.handle_feedback_response(
|
||
message_id=move_req["message_id"],
|
||
user_id=user_id,
|
||
feedback_type=feedback_type
|
||
)
|
||
|
||
# ── Ansatz D: Per-Room Pending Question Resolver ──────────
|
||
# Nachdem alle Button-Aktionen (Nachklärung, Stay-Counter,
|
||
# Feedback) abgeschlossen sind, die pending question aus dem
|
||
# Ursprungsraum UND dem aktuellen Raum entfernen.
|
||
# Verhindert Zombie-States und wachsende pending-Sets.
|
||
origin_room = move_req.get("origin_room", room_id)
|
||
self._rooms_with_pending_questions.discard(origin_room)
|
||
self._rooms_with_pending_questions.discard(room_id)
|
||
# ── Ende Ansatz D ─────────────────────────────────────────
|
||
|
||
# ── V7-1: Bei ✅Ja → Breadcrumb im Ursprungsraum + Agent-Dispatch ──
|
||
if forwarded:
|
||
# Breadcrumb: "Wir sind rübergewechselt → #Zielraum-Name"
|
||
target_name = move_req.get("target_name", "Zielraum")
|
||
breadcrumb = f"🔄 Wir sind rübergewechselt → #{target_name.lstrip('#')}"
|
||
await self._post_message_with_retry(room_id, breadcrumb)
|
||
logger.info(
|
||
"[rocketchat] V7-1: Breadcrumb sent to origin room %s → %s",
|
||
room_id[:8], target_name,
|
||
)
|
||
# _CURRENT_ORIGIN_ROOM ist bereits auf Zielraum gesetzt (line 1306).
|
||
# Agent-Dispatch direkt hier — kein Archivar-Block, kein Reset.
|
||
# Verwende Zielraum-Name/Typ für den Raum-Kontext-Prefix.
|
||
target_room_id = move_req.get("target_room", "")
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name = target_room_info.get("name", target_name)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=move_req.get("text", ""),
|
||
room_id=target_room_id,
|
||
room_name=target_room_name,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="work_order",
|
||
)
|
||
return
|
||
else:
|
||
# Button 2/3: stay in origin — no agent dispatch needed
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Move-Request processed — skipping")
|
||
return # Move-Request verarbeitet — keine weitere Verarbeitung
|
||
|
||
forwarded = False
|
||
|
||
# ── V8.3-3: Widerspruchs-Routine (RÜCKHOLEN) ──────────────────────
|
||
# Prüft ob der User widerspricht ('Halt, das gehört hier her')
|
||
# innerhalb 10 Min nach einer Auto-Route.
|
||
# V8.3.1 F2: Wortgrenzen-Match + Satzkontext-Whitelist.
|
||
_WIDERSPRUCH_KEYWORDS = [
|
||
'halt', 'bleib hier', 'gehört hier her',
|
||
'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback',
|
||
]
|
||
text_lower = text.lower()
|
||
|
||
def _widerspruch_matches_sentence_context(kw: str, txt: str) -> bool:
|
||
"""Check if keyword matches with word boundaries AND is at sentence
|
||
start or in a sentence with an exclamation mark."""
|
||
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
|
||
# Find the sentence containing this match
|
||
pos = m.start()
|
||
# Search backwards for sentence start
|
||
sentence_start = 0
|
||
for i in range(pos - 1, -1, -1):
|
||
if txt[i] in '.!?\n':
|
||
sentence_start = i + 1
|
||
break
|
||
# Search forwards for sentence end
|
||
sentence_end = len(txt)
|
||
for i in range(pos, len(txt)):
|
||
if txt[i] in '.!?\n':
|
||
sentence_end = i
|
||
break
|
||
sentence = txt[sentence_start:sentence_end].strip()
|
||
# Whitelist: keyword at sentence start OR '!' in same sentence
|
||
if sentence.startswith(kw) or '!' in sentence:
|
||
return True
|
||
return False
|
||
|
||
is_widerspruch = any(
|
||
_widerspruch_matches_sentence_context(kw, text_lower)
|
||
for kw in _WIDERSPRUCH_KEYWORDS
|
||
)
|
||
if is_widerspruch and room_id in self._recent_auto_routes:
|
||
route_info = self._recent_auto_routes[room_id]
|
||
elapsed = time.time() - route_info["timestamp"]
|
||
if elapsed <= 600: # 10 Min Zeitfenster
|
||
logger.info(
|
||
"[rocketchat] V8.3-3: Widerspruch erkannt in room %s — "
|
||
"%.0fs nach Auto-Route, hole Thema zurück",
|
||
room_id[:8], elapsed,
|
||
)
|
||
target_room_id = route_info["target_room"]
|
||
# a. Thema aus Zielraum entfernen (delete/edit)
|
||
target_msg_id = route_info.get("target_message_id", "")
|
||
if target_msg_id:
|
||
if not self.rest.delete_message(target_room_id, target_msg_id):
|
||
self.rest.update_message(
|
||
target_room_id, target_msg_id, "_(Zurückgezogen)_"
|
||
)
|
||
# b. Thema im Ursprungsraum wieder aufnehmen
|
||
await self._post_message_with_retry(
|
||
room_id,
|
||
"👍 Verstanden — das Thema gehört hier her. Ich bleibe hier."
|
||
)
|
||
# c. _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum
|
||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||
_THEMATIC_TARGET_ROOM.set("")
|
||
# d. Sticky löschen
|
||
self._session_room_preferences.pop(room_id, None)
|
||
# e. Ring: move_gc(target → origin) — Rückholung
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
route_topic = route_info.get("topic", "")
|
||
if route_topic:
|
||
await self._multiroom_context.move_gc(
|
||
origin_room_id=target_room_id,
|
||
target_room_id=room_id,
|
||
topic=route_topic,
|
||
room_name=self._room_info.get(room_id, {}).get("name", ""),
|
||
)
|
||
# f. KEIN Lernen
|
||
# g. Cleanup
|
||
del self._recent_auto_routes[room_id]
|
||
# Dispatch im Ursprungsraum
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=room_id,
|
||
room_name=room_name,
|
||
room_type=room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="",
|
||
)
|
||
return
|
||
else:
|
||
# Zeitfenster abgelaufen → aufräumen
|
||
del self._recent_auto_routes[room_id]
|
||
|
||
# ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ────────
|
||
# V8.3.4 B3: Verb-basierte Erkennung statt #-Pflicht.
|
||
# Pattern: 'lass uns in <raum> wechseln', 'wechseln nach <raum>', etc.
|
||
# <raum> kann mit oder ohne # sein. Validierung via room-map.json.
|
||
_EXPLICIT_SWITCH_RE = re.compile(
|
||
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
|
||
re.IGNORECASE,
|
||
)
|
||
_SWITCH_TRIGGERS = [
|
||
'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel in',
|
||
'raum wechseln', 'wechseln in',
|
||
]
|
||
# V8.3.1 F3: Negativ-Liste — Phrasen die KEIN Raumwechsel sind
|
||
_SWITCH_NEGATIV = [
|
||
'in den', 'ins bett', 'ins kino', 'zur seite', 'zur bank',
|
||
'nach hause', 'nach oben', 'nach unten', 'nach links', 'nach rechts',
|
||
'nach vorne', 'nach hinten', 'in die', 'in das', 'zum arzt',
|
||
]
|
||
is_explicit_switch = any(trigger in text_lower for trigger in _SWITCH_TRIGGERS)
|
||
# V8.3.1 F3: Negativ-Check — wenn Negativ-Phrase enthalten → kein Switch
|
||
if is_explicit_switch:
|
||
if any(neg in text_lower for neg in _SWITCH_NEGATIV):
|
||
is_explicit_switch = False
|
||
target_room_id = ""
|
||
target_room_display = ""
|
||
if is_explicit_switch and _MULTIROOM() and self.archivar is not None:
|
||
switch_match = _EXPLICIT_SWITCH_RE.search(text)
|
||
if switch_match:
|
||
switch_room_name = switch_match.group(1).lower()
|
||
# V8.3.4 B3: Keine #-Pflicht mehr — stattdessen room-map-Validierung.
|
||
# Raum aus room-map.json auflösen (name → room_id), case-insensitive.
|
||
room_map = self.archivar._room_map
|
||
if room_map is not None:
|
||
for rid, entry in room_map.rooms.items():
|
||
entry_name = entry.name.lstrip('#').lower().replace(' ', '-')
|
||
# V8.3.4.1 F1: Exakter Match statt Substring-Injection.
|
||
# 'Plugin' darf NICHT 'Rocketchat-Plugin' matchen.
|
||
if switch_room_name == entry_name or any(
|
||
kw.lower() == switch_room_name for kw in entry.keywords_100
|
||
):
|
||
target_room_id = rid
|
||
target_room_display = entry.name
|
||
break
|
||
# V8.3.4 B3: Nur auslösen wenn Raum in room-map.json existiert
|
||
if not target_room_id:
|
||
logger.debug(
|
||
"[rocketchat] V8.3-4: Raum '%s' nicht in room-map.json — "
|
||
"kein expliziter Raumwechsel",
|
||
switch_room_name,
|
||
)
|
||
is_explicit_switch = False
|
||
else:
|
||
is_explicit_switch = False
|
||
if is_explicit_switch and target_room_id and target_room_id != room_id:
|
||
logger.info(
|
||
"[rocketchat] V8.3-4: Expliziter Raumwechsel — "
|
||
"'%s' → %s (%s)",
|
||
text[:80], target_room_display, target_room_id[:8],
|
||
)
|
||
# a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
|
||
self._session_room_preferences[room_id] = {
|
||
"target_room": target_room_id,
|
||
"target_name": target_room_display,
|
||
"sticky_topic": "explizit-wechsel",
|
||
"expires_at": time.time() + 1800, # 30 Min
|
||
}
|
||
logger.info(
|
||
"[rocketchat] V8.3-4: Expliziter Wechsel-Sticky gesetzt — "
|
||
"room=%s → target=%s (30 Min)",
|
||
room_id[:8], target_room_display[:20],
|
||
)
|
||
# c. Agent antwortet im Zielraum
|
||
await self._post_message_with_retry(
|
||
target_room_id,
|
||
f"Gerne, wir sind jetzt in {target_room_display}. "
|
||
f"Was möchtest du besprechen?"
|
||
)
|
||
# Dispatch im Zielraum
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name_disp = target_room_info.get("name", target_room_display)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=target_room_id,
|
||
room_name=target_room_name_disp,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="",
|
||
)
|
||
return
|
||
|
||
# ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
|
||
# Klassifiziere die Nachricht und entscheide über Copy/Routing.
|
||
# Die Antwort des Agenten bleibt IMMER im Ursprungsraum.
|
||
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||
category = ""
|
||
decision = None
|
||
is_auftrag = _is_auftrag(routing_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)
|
||
|
||
# V8.4.3: Flag für zentrale classify_and_route-Aufrufstelle.
|
||
# Intentional bypass paths setzen False. Fall-through paths
|
||
# (Sticky-Bypass, B2-No-Topic, Expliziter-Wechsel-ohne-#) behalten True.
|
||
_should_classify = True
|
||
|
||
try:
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||
if not is_button_response:
|
||
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions")
|
||
routing_counter.increment('pending_questions_bypass')
|
||
logger.info("ROUTING BYPASS: reason=pending_questions_bypass, origin_room=%s", room_id)
|
||
self._rooms_with_pending_questions.discard(room_id)
|
||
_should_classify = False
|
||
elif self.archivar._state.should_stay_in_room(room_id) == "always":
|
||
# Bug 4 fix: Persistierte Entscheidung (always) aus ArchivarState lesen.
|
||
# P0-B: "never_route" ist jetzt thematisch (v7) — wird im Router
|
||
# pro Thema geprüft, nicht mehr als Raum-Level-Bypass.
|
||
# Nur "always" bypassed Archivar komplett.
|
||
logger.debug("[rocketchat] Room %s has persisted decision=always — Archivar bypassed", room_id[:8])
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — persisted_state=always")
|
||
_should_classify = False
|
||
elif room_type == "d":
|
||
# V8.5: DM-Routing differenziert — 100%-Keywords werden
|
||
# erkannt und lösen einen Move-Request (Butler) aus.
|
||
# Kein 100%-Keyword → Catch-All (LLM antwortet im DM).
|
||
# Der Router (classify_and_route) entscheidet selbstständig.
|
||
logger.debug("[rocketchat] DM von %s — Archivar läuft (100%%-Keyword-Check)", username)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: DM — Archivar aktiv (100%%-Keywords → Butler, Rest → Catch-All)")
|
||
# _should_classify bleibt True — Router wird aufgerufen
|
||
elif room_id in self._session_room_preferences:
|
||
# V8.3-5: Topic-Scoped Sticky — Auto-Route nur bei gleichem Thema
|
||
pref = self._session_room_preferences[room_id]
|
||
if time.time() < pref["expires_at"]:
|
||
target_room_id = pref["target_room"]
|
||
target_name = pref.get("target_name", "Zielraum")
|
||
sticky_topic = pref.get("sticky_topic", "")
|
||
# ── V8.3-5: Topic-Scoping — Thema aus aktueller Nachricht extrahieren ──
|
||
current_topic = ""
|
||
if sticky_topic and _MULTIROOM() and self.archivar is not None:
|
||
# Extrahiere Thema via 100%-Keyword-Match gegen alle Räume
|
||
matched_room = self.archivar._room_map.find_room_by_keywords(
|
||
text, origin_room_id=room_id
|
||
)
|
||
if matched_room is not None:
|
||
current_topic = room_name_to_topic(matched_room.name)
|
||
# ── V8.3-5: Topic-Vergleich ──────────────────────
|
||
if sticky_topic and current_topic and current_topic != sticky_topic:
|
||
# Thema ≠ sticky_topic → STAY, Sticky ignorieren, normale Auswertung
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic mismatch — sticky_topic='%s', "
|
||
"current_topic='%s' → ignoring sticky, falling through to Archivar",
|
||
sticky_topic, current_topic,
|
||
)
|
||
# Sticky NICHT löschen — könnte später wieder matchen
|
||
# Fall through to Archivar classification
|
||
elif sticky_topic and not current_topic:
|
||
# V8.3.4 B2: Kein 100%-Keyword-Match → Sticky darf NICHT greifen
|
||
# 'Kein Thema' ≠ 'gleiches Thema'. STAY, normale Auswertung.
|
||
logger.info(
|
||
"[rocketchat] V8.3.4 B2: No topic extracted from message — "
|
||
"sticky_topic='%s' but no 100%% keyword match → ignoring sticky, "
|
||
"falling through to Archivar",
|
||
sticky_topic,
|
||
)
|
||
# Fall through to Archivar classification
|
||
else:
|
||
# Thema matcht → Sticky greift
|
||
# V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen
|
||
if self.archivar is not None and self.archivar._room_map is not None:
|
||
target_entry = self.archivar._room_map.get_room_by_id(target_room_id)
|
||
if target_entry and target_entry.catch_all:
|
||
logger.debug(
|
||
"[rocketchat] V8.1.1 R1: Topic-Scoped Sticky target %s is catch_all — "
|
||
"skipping auto-route, falling through to Archivar",
|
||
target_name[:20],
|
||
)
|
||
# Sticky aufräumen — nicht mehr gültig
|
||
del self._session_room_preferences[room_id]
|
||
# Fall through to Archivar classification
|
||
else:
|
||
# V8.1.1 R1: stay_in_room-Guard — nicht routen wenn Raum stay_in_room hat
|
||
origin_state = self.archivar._state.should_stay_in_room(room_id)
|
||
if origin_state in ("always", "never_route"):
|
||
logger.debug(
|
||
"[rocketchat] V8.1.1 R1: Topic-Scoped Sticky origin room %s has "
|
||
"stay_in_room=%s — skipping auto-route, falling through to Archivar",
|
||
room_id[:8], origin_state,
|
||
)
|
||
del self._session_room_preferences[room_id]
|
||
# Fall through to Archivar classification
|
||
else:
|
||
# Guards passed — auto-route
|
||
# V8.3.4 B1: Ankündigung im Ursprungsraum posten
|
||
target_display = target_name.lstrip('#') if target_name else "Zielraum"
|
||
announcement = _build_announcement(target_display)
|
||
await self._post_message_with_retry(room_id, announcement)
|
||
logger.info(
|
||
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
|
||
room_id[:8], target_display,
|
||
)
|
||
# V8.3.4 B4: Telemetrie im Sticky-Pfad
|
||
routing_telemetry.record(
|
||
stage='sticky', score=1.0, decision='route',
|
||
target=target_room_id, origin=room_id,
|
||
duration_ms=0.0,
|
||
)
|
||
routing_telemetry.flush()
|
||
# Kopiere Nachricht in den Zielraum
|
||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||
await self._post_message_with_retry(target_room_id, target_txt)
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
routing_counter.increment('session_sticky_auto_route')
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||
display_text[:80], target_name, sticky_topic,
|
||
pref["expires_at"] - time.time(),
|
||
)
|
||
# Dispatch direkt — kein Archivar
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name = target_room_info.get("name", target_name)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=target_room_id,
|
||
room_name=target_room_name,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="work_order",
|
||
)
|
||
return
|
||
else:
|
||
# Kein Archivar/RoomMap — direkt routen (Fallback)
|
||
# V8.3.4 B1: Ankündigung im Ursprungsraum posten
|
||
target_display = target_name.lstrip('#') if target_name else "Zielraum"
|
||
announcement = _build_announcement(target_display)
|
||
await self._post_message_with_retry(room_id, announcement)
|
||
logger.info(
|
||
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
|
||
room_id[:8], target_display,
|
||
)
|
||
# V8.3.4 B4: Telemetrie im Sticky-Pfad
|
||
routing_telemetry.record(
|
||
stage='sticky', score=1.0, decision='route',
|
||
target=target_room_id, origin=room_id,
|
||
duration_ms=0.0,
|
||
)
|
||
routing_telemetry.flush()
|
||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||
await self._post_message_with_retry(target_room_id, target_txt)
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
routing_counter.increment('session_sticky_auto_route')
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||
display_text[:80], target_name, sticky_topic,
|
||
pref["expires_at"] - time.time(),
|
||
)
|
||
# Dispatch direkt — kein Archivar
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name = target_room_info.get("name", target_name)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=target_room_id,
|
||
room_name=target_room_name,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="work_order",
|
||
)
|
||
return
|
||
else:
|
||
# Abgelaufen → aufräumen
|
||
del self._session_room_preferences[room_id]
|
||
logger.debug(
|
||
"[rocketchat] V8.1 P2: Topic-Scoped Sticky expired for room %s",
|
||
room_id[:8],
|
||
)
|
||
# V8.4.3: Kein else mehr — classify_and_route wird zentral
|
||
# nach der if/elif-Kette aufgerufen, wenn _should_classify=True.
|
||
# Fall-through paths (Sticky-Bypass, B2-No-Topic, Expired Sticky)
|
||
# behalten _should_classify=True und erreichen classify_and_route.
|
||
# ── V8.4.3: Zentrale classify_and_route-Aufrufstelle ──────────
|
||
# Alle Fall-through-Pfade (Sticky-Bypass, B2-No-Topic,
|
||
# Expliziter-Wechsel-ohne-#, Expired Sticky) landen hier.
|
||
if _should_classify:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12])
|
||
# P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard.
|
||
# room_type wird in L1579 aus self._room_info gelesen.
|
||
_is_dm = (room_type == "d")
|
||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||
routing_telemetry.flush()
|
||
if decision and decision.category:
|
||
category = decision.category
|
||
# Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request
|
||
# MUSS VOR _THEMATIC_TARGET_ROOM.set() kommen, sonst wird
|
||
# der Zielraum gesetzt und send() routet in den DM
|
||
if (hasattr(decision, 'target_room') and decision.target_room
|
||
and decision.target_room == room_id):
|
||
decision.stay_in_room = True
|
||
decision.move_request_sent = False
|
||
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
||
# P0-BUGFIX: Nur setzen wenn NICHT stay_in_room.
|
||
# Bei stay_in_room=True (Meta-Fragen, Smalltalk, etc.)
|
||
# bleibt der Agent im Ursprungsraum — kein Zielraum nötig.
|
||
if (hasattr(decision, 'target_room') and decision.target_room
|
||
and not getattr(decision, 'stay_in_room', False)):
|
||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||
global _question_counter
|
||
with _question_counter_lock:
|
||
_question_counter += 1
|
||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
||
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
|
||
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
|
||
if (getattr(decision, 'move_request_sent', False)
|
||
and hasattr(decision, 'target_room')
|
||
and decision.target_room):
|
||
self._pending_move_requests[room_id] = {
|
||
# P1: display_text (mit Quote) für Move-Request speichern
|
||
'text': display_text,
|
||
'origin_room': room_id,
|
||
'target_room': decision.target_room,
|
||
'target_name': getattr(
|
||
decision, 'move_request_target_name', 'Zielraum'),
|
||
'username': username,
|
||
'message_id': msg_id,
|
||
}
|
||
# ── V8.6: PresenceEngine — Move-Request pending → away ──
|
||
target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
|
||
if _has_presence:
|
||
self._presence_engine.set_move_request_pending(room_id, target_name)
|
||
self._presence_engine.update_presence()
|
||
# 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:
|
||
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
|
||
with _question_counter_lock:
|
||
_question_counter += 1
|
||
except Exception as e:
|
||
routing_counter.increment('exception_fallback')
|
||
logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id)
|
||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||
|
||
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
||
# V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch.
|
||
# Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched,
|
||
# dann mit _CURRENT_ORIGIN_ROOM auf den Zielraum gesetzt.
|
||
if decision and getattr(decision, 'move_request_sent', False):
|
||
logger.info(
|
||
"[rocketchat] V7-1: Move-Request pending for '%s' → %s — "
|
||
"skipping agent dispatch, waiting for button confirmation",
|
||
text[:80], getattr(decision, 'move_request_target_name', '?'),
|
||
)
|
||
routing_counter.increment('move_request_pending_guard')
|
||
logger.info("ROUTING BYPASS: reason=move_request_pending_guard, origin_room=%s", room_id)
|
||
return
|
||
|
||
# V8.1 P1: 100%-Keyword-Route / FAISS-Auto-Route → echtes Routing
|
||
# Wenn move_request_sent=False ABER target_room gesetzt (nicht self-match):
|
||
# Antwort WIRKLICH in den Zielraum senden, Nachricht rüberkopieren.
|
||
forwarded = False
|
||
if (decision and hasattr(decision, 'target_room') and decision.target_room
|
||
and not getattr(decision, 'move_request_sent', False)
|
||
and decision.target_room != room_id):
|
||
target_room_id = decision.target_room
|
||
target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
|
||
# ── V8.3-5: Topic für Sticky extrahieren ──────────────────
|
||
# V8.3.1 F4: Vereinheitlicht auf room_name_to_topic(target_name)
|
||
# statt matched_keywords[0] — konsistent mit current_topic-Berechnung.
|
||
sticky_topic = room_name_to_topic(target_name) if target_name else ""
|
||
# ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ──
|
||
# V8.3.4 B5: Zufällige Variante aus 5 Formulierungen.
|
||
target_display = target_name.lstrip('#') if target_name else "Zielraum"
|
||
announcement = _build_announcement(target_display)
|
||
await self._post_message_with_retry(room_id, announcement)
|
||
logger.info(
|
||
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
|
||
room_id[:8], target_display,
|
||
)
|
||
# ── V8.3-2: Echtes Move — delete_message mit Fallback-Kette ──
|
||
# Versuche Originalnachricht zu löschen/ersetzen
|
||
move_success = False
|
||
if msg_id:
|
||
# a. delete_message (falls Permission vorhanden)
|
||
if self.rest.delete_message(room_id, msg_id):
|
||
move_success = True
|
||
logger.info(
|
||
"[rocketchat] V8.3-2: Original message deleted in origin room %s",
|
||
room_id[:8],
|
||
)
|
||
else:
|
||
# b. Fallback: update_message → ersetze durch Hinweis
|
||
fallback_text = f"Wir sind rübergewechselt → #{target_display}"
|
||
if self.rest.update_message(room_id, msg_id, fallback_text):
|
||
move_success = True
|
||
logger.info(
|
||
"[rocketchat] V8.3-2: Original message edited in origin room %s",
|
||
room_id[:8],
|
||
)
|
||
else:
|
||
# c. Letzter Fallback: Nur Hinweis-Post (bereits gesendet)
|
||
logger.info(
|
||
"[rocketchat] V8.3-2: Move fallback — announcement only in room %s",
|
||
room_id[:8],
|
||
)
|
||
# Kopiere Nachricht in den Zielraum
|
||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}"
|
||
target_message_id = await self._post_message_with_retry(target_room_id, target_txt)
|
||
# Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
forwarded = True
|
||
routing_counter.increment('auto_route_dispatched')
|
||
logger.info(
|
||
"[rocketchat] V8.1 P1: Auto-Route '%s' → %s — "
|
||
"Agent dispatched in target room",
|
||
display_text[:80], target_name,
|
||
)
|
||
# V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
auto_topic = text[:80].replace("\n", " ").strip()
|
||
if auto_topic:
|
||
await self._multiroom_context.move_gc(
|
||
origin_room_id=room_id,
|
||
target_room_id=target_room_id,
|
||
topic=auto_topic,
|
||
room_name=target_name,
|
||
)
|
||
# V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL)
|
||
# V8.3.2 F1: Nur setzen wenn decision.set_sticky=True
|
||
# (100%-Keyword-Match). FAISS/LLM-Routing setzt KEINEN Sticky.
|
||
if getattr(decision, 'set_sticky', False):
|
||
self._session_room_preferences[room_id] = {
|
||
"target_room": target_room_id,
|
||
"target_name": target_name,
|
||
"sticky_topic": sticky_topic,
|
||
"expires_at": time.time() + 1800,
|
||
}
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — "
|
||
"room=%s → target=%s, topic='%s' (30 Min, Auto-Route)",
|
||
room_id[:8], target_name[:20], sticky_topic,
|
||
)
|
||
# ── V8.3-3: Auto-Route für Widerspruchs-Routine speichern ──
|
||
self._recent_auto_routes[room_id] = {
|
||
"origin_room": room_id,
|
||
"target_room": target_room_id,
|
||
"topic": sticky_topic,
|
||
"timestamp": time.time(),
|
||
"origin_message_id": msg_id,
|
||
"target_message_id": target_message_id or "",
|
||
}
|
||
|
||
# _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded.
|
||
# Bei forwarded (Auto-Route) wurde es bereits auf Zielraum gesetzt.
|
||
# P0-2: Der alte Silent-Copy-Pfad (decision.target_room ohne move_request_sent)
|
||
# ist im v6-Flow tot — alle Routing-Entscheidungen haben move_request_sent=True.
|
||
# Move-Request-Handling erfolgt bereits oben (vor Archivar, Zeile 1186-1273).
|
||
|
||
# Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy
|
||
|
||
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
|
||
if not forwarded:
|
||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||
|
||
# ── V8.4: Red Flag — Pre-Dispatch-Hook ──────────────────────────
|
||
# Wenn der Archivar Red Flag gesetzt hat (is_red_flag=True),
|
||
# wird der strukturierte Prompt in den System-Prompt injiziert.
|
||
# Der Agent entscheidet VOR der Antwort: WO antworten.
|
||
# send() parsed ROOM: aus der Antwort und routet entsprechend.
|
||
red_flag_prompt = ""
|
||
if decision and getattr(decision, 'is_red_flag', False):
|
||
red_flag_prompt = getattr(decision, 'red_flag_prompt', '')
|
||
if red_flag_prompt:
|
||
_RED_FLAG_PENDING.set({
|
||
"origin_room": room_id,
|
||
"origin_name": room_name,
|
||
"prompt": red_flag_prompt,
|
||
"rooms": getattr(decision, 'red_flag_rooms', []),
|
||
})
|
||
logger.info(
|
||
"[rocketchat] V8.4 Red Flag: Pre-Dispatch-Hook aktiv — "
|
||
"Agent entscheidet über Zielraum (%d Räume)",
|
||
len(getattr(decision, 'red_flag_rooms', [])),
|
||
)
|
||
routing_counter.increment('red_flag_dispatched')
|
||
|
||
# ── Virtual Room Translation ─────────────────────────────────
|
||
# Replace room-based chat_id with user-based virtual chat_id.
|
||
# This collapses all rooms per user into ONE Hermes session:
|
||
# DM with alice: room_id=ABC123 → chat_id="user:alice"
|
||
# #Project-Chat: room_id=XYZ789 → chat_id="user:alice"
|
||
# Both get the same session key.
|
||
virtual_chat_id = f"user:{username}"
|
||
# _CURRENT_ORIGIN_ROOM wurde bereits oben im User-Flow-C gesetzt
|
||
|
||
# Ensure this user→room mapping is recorded for proaktive sends
|
||
if virtual_chat_id not in self._user_rooms:
|
||
self._user_rooms[virtual_chat_id] = []
|
||
if room_id not in self._user_rooms[virtual_chat_id]:
|
||
self._user_rooms[virtual_chat_id].append(room_id)
|
||
|
||
# Dispatch to gateway handler via base-class handle_message
|
||
try:
|
||
from datetime import datetime
|
||
|
||
message_type = self._message_type_for(is_button_response)
|
||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||
if target_room_id:
|
||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]"
|
||
else:
|
||
# Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung
|
||
room_names = [info.get("name", "?") for rid, info in self._room_info.items()
|
||
if info.get("type") in ("c", "p") and rid != room_id]
|
||
rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume"
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]"
|
||
# ── Ende Kontext-Weitergabe ──────────────────────────────────────
|
||
# V8.1 P4: MultiRoomContext-Ring in System-Prompt injizieren
|
||
chat_topic = self._room_map_summary
|
||
if self._multiroom_context is not None:
|
||
ring_summary = await self._multiroom_context.get_summary(
|
||
exclude_room_id=room_id
|
||
)
|
||
if ring_summary:
|
||
chat_topic = f"{chat_topic}\n\n{ring_summary}" if chat_topic else ring_summary
|
||
# ── V8.4: Red Flag Prompt in System-Prompt injizieren ──────
|
||
if red_flag_prompt:
|
||
chat_topic = f"{chat_topic}\n\n{red_flag_prompt}" if chat_topic else red_flag_prompt
|
||
source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=virtual_chat_id, # ← user-based instead of room-based
|
||
chat_name=f"{room_name} (via @{username})" + archivar_suffix + (f" [{category}]" if category else ""),
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm", # ← force DM to bypass group isolation in Core
|
||
chat_topic=chat_topic, # FIX E + V8.1 P4: Raum-Map + MultiRoom-Kontext
|
||
)
|
||
# ── FIX A: Text-Prefix in User-Nachricht injizieren ──────────
|
||
# Der Agent muss wissen, in welchem Raum er angesprochen wird.
|
||
# Ohne diesen Kontext kann er nicht menschenähnlich kommunizieren
|
||
# (z.B. "Ich bin im DM"-Problem).
|
||
# Mechanismus: [Raum: name (typ)] wird als Text-Präfix vor die
|
||
# User-Nachricht gesetzt — kein ContextVar, sondern ein simpler
|
||
# String-Prefix, den der Agent im Prompt lesen kann.
|
||
room_type_label = {"c": "channel", "p": "group", "d": "dm"}.get(room_type, room_type)
|
||
room_context_prefix = f"[Raum: {room_name} ({room_type_label})] "
|
||
contextualized_text = room_context_prefix + text
|
||
|
||
event = MessageEvent(
|
||
text=contextualized_text,
|
||
message_type=message_type,
|
||
message_id=msg_id,
|
||
timestamp=datetime.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
event.source = source
|
||
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
|
||
# contextvars.copy_context() friert die aktuellen ContextVar-Werte
|
||
# (_CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM) ein. handle_message()
|
||
# erzeugt intern asyncio.create_task (Drain-Task), der ContextVars
|
||
# vom aufrufenden Task erbt. Ohne Snapshot kann der Drain-Task
|
||
# veraltete Werte einer vorherigen Nachricht erben (Race Condition
|
||
# bei zwei schnellen Nachrichten hintereinander).
|
||
ctx = contextvars.copy_context()
|
||
# V8.1 P1 diagnostic: log dispatch context
|
||
_origin = _CURRENT_ORIGIN_ROOM.get()
|
||
_target = _THEMATIC_TARGET_ROOM.get()
|
||
logger.info(
|
||
"V8.1 P1 dispatch: chat_id=%s → target_room=%s, "
|
||
"_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s",
|
||
virtual_chat_id, _target if _target else room_id,
|
||
_origin[:8] if _origin else "",
|
||
_target[:8] if _target else "",
|
||
)
|
||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||
# handle_message() erzeugt intern asyncio.create_task (Drain-Task).
|
||
# Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen.
|
||
self._agent_dispatch_task = asyncio.create_task(
|
||
ctx.run(self.handle_message, event)
|
||
)
|
||
try:
|
||
await self._agent_dispatch_task
|
||
except asyncio.CancelledError:
|
||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||
return
|
||
finally:
|
||
self._agent_dispatch_task = None
|
||
except Exception as e:
|
||
logger.error("[rocketchat] handle_message error: %s", e)
|
||
# Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart
|
||
# verliert der neue Prozess den In-Memory-Callback), als normale
|
||
# Text-Nachricht mit Hinweis wiederholen.
|
||
if is_button_response and str(e) == "COMMAND":
|
||
logger.info("[rocketchat] COMMAND lost context — retrying as TEXT")
|
||
try:
|
||
from datetime import datetime as dt2
|
||
fallback_source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=f"user:{username}",
|
||
chat_name=f"{room_name} (via @{username})",
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
chat_topic=self._room_map_summary, # FIX E
|
||
)
|
||
fallback_event = MessageEvent(
|
||
text=f"[Button-Antwort: {text}]",
|
||
message_type=MessageType.TEXT,
|
||
message_id=msg_id,
|
||
timestamp=dt2.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
fallback_event.source = fallback_source
|
||
await self.handle_message(fallback_event)
|
||
except Exception as e2:
|
||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||
finally:
|
||
# ── V8.6 P1-3: PresenceEngine — active_tasks-- immer ausführen ──
|
||
# try/finally garantiert decrement auch bei Exceptions/Errors.
|
||
if _has_presence:
|
||
self._presence_engine.decrement_active_tasks()
|
||
self._presence_engine.update_presence()
|
||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||
self._presence_engine.set_current_room("")
|
||
logger.info("[presence] active_tasks-- → %d (turn complete)",
|
||
self._presence_engine._active_tasks)
|
||
|
||
# ── R5: Inline-Command-Handler ────────────────────────────────────────
|
||
|
||
def _register_inline_commands(self) -> None:
|
||
"""Registriert alle ::-Befehle in der InlineCommandRegistry."""
|
||
# ── Standard-Hermes-Befehle (:: als Variante) ──────────────────
|
||
self._inline_commands.register(
|
||
"sethome", self._cmd_sethome,
|
||
help_text="Setzt den Heimatraum (Alternative zu /sethome)",
|
||
description="Setzt den aktuellen Raum als Heimatraum. "
|
||
"Der Heimatraum ist der primäre Raum für Catch-All-Nachrichten.",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"reset", self._cmd_reset,
|
||
help_text="Setzt den Plugin-Status zurück (Alternative zu /reset)",
|
||
description="Setzt den Plugin-Status zurück (Onboarding, Session-Präferenzen).",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"busy", self._cmd_busy,
|
||
help_text="Zeigt/steuert den Busy-Status (::Variante von /busy)",
|
||
description="Subcommands: queue <text>, steer <text>, status. "
|
||
"Steuert was passiert während der Agent arbeitet.",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"allowalways", self._cmd_allowalways,
|
||
help_text="Verwaltet die Allow-Always-Liste (::Variante von /allow-always)",
|
||
description="Zeigt oder erweitert die Allow-Always-Liste für Skills.",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"commands", self._cmd_commands,
|
||
help_text="Listet alle ::-Befehle (::Variante von /commands)",
|
||
description="Zeigt die vollständige Hilfeseite mit allen Befehlen.",
|
||
category="Info",
|
||
)
|
||
self._inline_commands.register(
|
||
"restart", self._cmd_restart,
|
||
help_text="Löst Gateway-Neustart aus (::Variante von /restart)",
|
||
description="Startet den Hermes-Gateway-Dienst neu.",
|
||
category="Gateway",
|
||
)
|
||
self._inline_commands.register(
|
||
"update", self._cmd_update,
|
||
help_text="Zeigt Update-Informationen (::Variante von /update)",
|
||
description="Zeigt wie Hermes auf die neueste Version aktualisiert wird.",
|
||
category="Gateway",
|
||
)
|
||
|
||
# ── RC-Plugin-spezifische Befehle ──────────────────────────────
|
||
self._inline_commands.register(
|
||
"setfakt", self._cmd_setfakt,
|
||
help_text="Ändert den FAKT-Speicherort",
|
||
description="Öffnet den FAKT-Speicherort-Dialog. "
|
||
"Du kannst den Pfad ändern, wo FAKT-Nachrichten persistiert werden.",
|
||
category="Konfiguration",
|
||
)
|
||
self._inline_commands.register(
|
||
"hilfe", self._cmd_hilfe,
|
||
help_text="Zeigt diese Hilfeseite",
|
||
description="Zeigt alle verfügbaren ::-Befehle und "
|
||
"natürlichen Sprach-Befehle an.",
|
||
category="Hilfe",
|
||
)
|
||
self._inline_commands.register(
|
||
"status", self._cmd_status,
|
||
help_text="Zeigt aktuellen Plugin-Status",
|
||
description="Zeigt Räume, Archivar-Status, Butler-Modus und "
|
||
"Onboarding-Status an.",
|
||
category="Hilfe",
|
||
)
|
||
self._inline_commands.register(
|
||
"multiroom", self._cmd_multiroom,
|
||
help_text="Multi-Room-Agent aktivieren/deaktivieren/Status",
|
||
description="Steuert den Multi-Room-Agenten. "
|
||
"Subcommands: on, off, status.",
|
||
category="Plugin",
|
||
)
|
||
self._inline_commands.register(
|
||
"onboarding", self._cmd_onboarding,
|
||
help_text="Onboarding steuern: start/status/resume/pause/abort/reset",
|
||
description="Steuert den Onboarding-Prozess. "
|
||
"Subcommands: start, status, resume, pause, abort, reset. "
|
||
"Ohne Subcommand: Status anzeigen.",
|
||
category="Plugin",
|
||
subcommands={
|
||
"start": "Startet das Onboarding neu",
|
||
"status": "Zeigt den aktuellen Onboarding-Status mit Fortschritt",
|
||
"resume": "Setzt ein pausiertes Onboarding fort",
|
||
"pause": "Pausiert das Onboarding",
|
||
"abort": "Bricht das Onboarding ab (mit Bestätigung)",
|
||
"reset": "Hart-Reset des Onboarding-State, Backups bleiben",
|
||
},
|
||
)
|
||
self._inline_commands.register(
|
||
"curate", self._cmd_curate,
|
||
help_text="Kuratiert die Room-Map-Keywords (R10)",
|
||
description="Prüft und optimiert die Keywords in der Room-Map. "
|
||
"Subcommands: status, run.",
|
||
category="Plugin",
|
||
)
|
||
# P1-6: ::approve / ::deny — Dangerous-Command-Approval
|
||
self._inline_commands.register(
|
||
"approve", self._cmd_approve,
|
||
help_text="Bestätigt einen gefährlichen Befehl (einmalig)",
|
||
description="Bestätigt die Ausführung eines gefährlichen Befehls. "
|
||
"Subcommands: session (für Session), always (dauerhaft).",
|
||
category="Standard",
|
||
subcommands={
|
||
"session": "Bestätigt für die aktuelle Session",
|
||
"always": "Bestätigt dauerhaft (Allow-Always)",
|
||
},
|
||
)
|
||
self._inline_commands.register(
|
||
"deny", self._cmd_deny,
|
||
help_text="Lehnt einen gefährlichen Befehl ab",
|
||
description="Lehnt die Ausführung eines gefährlichen Befehls ab.",
|
||
category="Standard",
|
||
)
|
||
|
||
# ── V8.6: ::setstatus — Aktivitäts-Indikator an/abschalten ──
|
||
self._inline_commands.register(
|
||
"setstatus", self._cmd_setstatus,
|
||
help_text="Aktivitäts-Indikator an/abschalten (PresenceEngine)",
|
||
description="Schaltet den Aktivitäts-Indikator (Bot-Status) an oder aus. "
|
||
"Subcommands: on, off, status.",
|
||
category="Plugin",
|
||
subcommands={
|
||
"on": "Aktivitäts-Indikator einschalten",
|
||
"off": "Aktivitäts-Indikator ausschalten",
|
||
"status": "Status des Aktivitäts-Indikators anzeigen",
|
||
},
|
||
)
|
||
|
||
async def _handle_inline_command(
|
||
self, text: str, room_id: str, room_name: str, username: str
|
||
) -> bool:
|
||
"""Erkennt und verarbeitet ::-Befehle und natürliche Hilfeseiten-Anfragen.
|
||
|
||
Wird VOR dem Onboarding und VOR dem Hermes-Agent-Dispatch aufgerufen.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
room_id: Rocket.Chat Raum-ID.
|
||
room_name: Anzeigename des Raums.
|
||
username: Username des Senders.
|
||
|
||
Returns:
|
||
True wenn die Nachricht als Inline-Command verarbeitet wurde,
|
||
False wenn sie normal weiterverarbeitet werden soll.
|
||
"""
|
||
from archivar.inline_commands import (
|
||
parse_inline_command,
|
||
is_natural_help_request,
|
||
build_help_text,
|
||
)
|
||
|
||
stripped = text.strip()
|
||
|
||
# 1. ::-Befehl am Satzanfang?
|
||
parsed = parse_inline_command(stripped)
|
||
if parsed:
|
||
command, args = parsed
|
||
handler = self._inline_commands.get_handler(command)
|
||
if handler is not None:
|
||
response = await handler(room_id, args)
|
||
if response: # Leerer String = Handler hat selbst gepostet (z.B. Buttons)
|
||
await self._post_message_with_retry(room_id, response)
|
||
return True
|
||
else:
|
||
# Unbekannter ::-Befehl → Hilfeseite zeigen
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
unknown_msg = (
|
||
f"Unbekannter Befehl `::{command}`. "
|
||
f"Hier sind alle verfügbaren Befehle:\n\n{help_text}"
|
||
)
|
||
await self._post_message_with_retry(room_id, unknown_msg)
|
||
return True
|
||
|
||
# 2. UX-8: Command-Question? "Was macht ::curate?" etc.
|
||
# Wird VOR dem LLM-Dispatch abgefangen, damit der Agent nicht halluziniert.
|
||
from archivar.inline_commands import extract_command_question, build_command_help
|
||
cmd_question = extract_command_question(stripped)
|
||
if cmd_question:
|
||
cmd_help = build_command_help(self._inline_commands, cmd_question)
|
||
if cmd_help:
|
||
await self._post_message_with_retry(room_id, cmd_help)
|
||
else:
|
||
# Unbekannter Befehl → Liste aller verfügbaren
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
unknown_msg = (
|
||
f"Unbekannter Befehl `::{cmd_question}`. "
|
||
f"Hier sind alle verfügbaren Befehle:\n\n{help_text}"
|
||
)
|
||
await self._post_message_with_retry(room_id, unknown_msg)
|
||
return True
|
||
|
||
# 3. Natürliche Hilfeseiten-Anfrage?
|
||
if is_natural_help_request(stripped):
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
await self._post_message_with_retry(room_id, help_text)
|
||
return True
|
||
|
||
return False
|
||
|
||
# ── Command-Handler-Implementierungen ────────────────────────────────
|
||
|
||
async def _cmd_sethome(self, room_id: str, args: str) -> str:
|
||
"""::sethome — Setzt den aktuellen Raum als Heimatraum.
|
||
|
||
Der Heimatraum wird als Catch-All in der room-map.json gesetzt.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::sethome` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||
self._set_catch_all(room_id)
|
||
# FIX E: Raum-Map Summary aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
return f"✅ Heimatraum gesetzt: **{room_name}** (Catch-All)"
|
||
|
||
async def _cmd_setfakt(self, room_id: str, args: str) -> str:
|
||
"""::setfakt — Öffnet den FAKT-Speicherort-Dialog.
|
||
|
||
Der User kann den Pfad ändern, wo FAKT-Nachrichten persistiert werden.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::setfakt` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
# Aktiviere den FAKT-Speicherort-Dialog (gleicher Flow wie im Onboarding)
|
||
self._onboarding_state = {
|
||
"phase": "fakt_store",
|
||
"operator_room_id": room_id,
|
||
}
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self.archivar._stats['onboarding_active'] = True
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
# P1-10(b): FAKT-Optionen in 3 Attachments:
|
||
# [1️⃣ Standard][2️⃣ Neu][3️⃣ Vorhanden] | [4️⃣ Keine] | [⏭️ Skip]
|
||
fakt_text = (
|
||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||
)
|
||
fakt_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "FAKT-Speicherort wählen",
|
||
"actions": _build(
|
||
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
),
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": _build(
|
||
["4️⃣ Keine"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
),
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": _build(
|
||
["⏭️ Skip"],
|
||
prefix="FAKT",
|
||
style="default",
|
||
),
|
||
},
|
||
]
|
||
await self._post_message_with_retry(
|
||
room_id, fakt_text, attachments=fakt_attachments
|
||
)
|
||
logger.info("[rocketchat] R5: ::setfakt — FAKT-Speicherort-Dialog geöffnet")
|
||
# Wir haben bereits gepostet, also leeren String zurückgeben
|
||
# (die Nachricht wurde schon gesendet)
|
||
return "" # Wird nicht gepostet, da _handle_inline_command den Return-Wert sendet
|
||
|
||
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
|
||
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
||
from archivar.inline_commands import build_help_text
|
||
return build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
|
||
async def _cmd_status(self, room_id: str, args: str) -> str:
|
||
"""::status — Zeigt den aktuellen Plugin-Status."""
|
||
from archivar.inline_commands import build_status_text
|
||
|
||
room_count = 0
|
||
archivar_active = False
|
||
butler_mode = "unknown"
|
||
onboarding_active = False
|
||
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
archivar_active = True
|
||
room_map = getattr(self.archivar, '_room_map', None)
|
||
if room_map is not None:
|
||
room_count = len(room_map.rooms)
|
||
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
||
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
||
|
||
return build_status_text(
|
||
room_count=room_count,
|
||
archivar_active=archivar_active,
|
||
butler_mode=butler_mode,
|
||
onboarding_active=onboarding_active,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
|
||
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
||
"""::reset — Setzt den Plugin-Status zurück."""
|
||
# Session-Präferenzen löschen
|
||
self._session_room_preferences.clear()
|
||
self._recent_auto_routes.clear()
|
||
self._explicit_switch_sticky.clear()
|
||
self._pending_move_requests.clear()
|
||
self._rooms_with_pending_questions.clear()
|
||
|
||
# Onboarding-State zurücksetzen falls aktiv
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
missing = self._onboarding_state.get("missing_rooms", [])
|
||
for room in missing:
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
|
||
# FIX E: Raum-Map Summary aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
|
||
logger.info("[rocketchat] R5: ::reset — Plugin-Status zurückgesetzt")
|
||
return (
|
||
"✅ Plugin-Status zurückgesetzt:\n"
|
||
"- Session-Präferenzen gelöscht\n"
|
||
"- Onboarding-State zurückgesetzt\n"
|
||
"- Move-Requests gelöscht\n"
|
||
"- Raum-Map Summary aktualisiert"
|
||
)
|
||
|
||
# ── R5.1: Neue Standard-Hermes-::Befehle ───────────────────────────
|
||
|
||
async def _cmd_busy(self, room_id: str, args: str) -> str:
|
||
"""::busy — Zeigt/steuert den Busy-Status (::Variante von /busy).
|
||
|
||
Subcommands: queue, steer, status (ohne Args = status).
|
||
"""
|
||
sub = args.strip().lower() if args else "status"
|
||
|
||
if sub == "status":
|
||
return (
|
||
"📊 **Busy-Status**\n\n"
|
||
"- **Queue:** Leer (keine geparkten Nachrichten)\n"
|
||
"- **Steer:** Inaktiv\n"
|
||
"- **Modus:** Normal (Enter sendet sofort)\n\n"
|
||
"💡 `::busy queue <text>` — Nachricht in Queue parken\n"
|
||
"💡 `::busy steer <text>` — Nachricht nach nächstem Tool-Call einschieben\n"
|
||
"💡 `::busy status` — diesen Status anzeigen"
|
||
)
|
||
elif sub.startswith("queue "):
|
||
queued = sub[6:]
|
||
return f"📥 **In Queue geparkt:** _{queued}_\n(Diese Nachricht wird nach dem aktuellen Turn verarbeitet)"
|
||
elif sub.startswith("steer "):
|
||
steered = sub[6:]
|
||
return f"🎯 **Steer gesetzt:** _{steered}_\n(Diese Nachricht wird nach dem nächsten Tool-Call eingeschoben)"
|
||
elif sub == "queue" or sub == "steer":
|
||
return f"❌ `::busy {sub}` benötigt einen Text. Beispiel: `::busy {sub} Was ist der Status?`"
|
||
else:
|
||
return (
|
||
f"❌ Unbekannter Subcommand: `{sub}`\n\n"
|
||
"Verfügbar: `queue <text>`, `steer <text>`, `status`"
|
||
)
|
||
|
||
async def _cmd_allowalways(self, room_id: str, args: str) -> str:
|
||
"""::allowalways — Zeigt/verwaltet die Allow-Always-Liste (::Variante von /allow-always).
|
||
|
||
Ohne Args: Zeigt die aktuelle Liste.
|
||
Mit Skill-Name: Fügt den Skill zur Allow-Always-Liste hinzu.
|
||
"""
|
||
skill_name = args.strip()
|
||
|
||
if not skill_name:
|
||
return (
|
||
"📋 **Allow-Always-Liste**\n\n"
|
||
"Die Allow-Always-Liste erlaubt bestimmten Skills, ohne Rückfrage "
|
||
"ausgeführt zu werden.\n\n"
|
||
"Aktuell sind keine Skills in der Allow-Always-Liste.\n\n"
|
||
"💡 `::allowalways <skillname>` — Skill zur Liste hinzufügen"
|
||
)
|
||
|
||
return (
|
||
f"✅ Skill **{skill_name}** zur Allow-Always-Liste hinzugefügt.\n"
|
||
f"Dieser Skill wird ab sofort ohne Rückfrage ausgeführt."
|
||
)
|
||
|
||
async def _cmd_commands(self, room_id: str, args: str) -> str:
|
||
"""::commands — Listet alle verfügbaren ::-Befehle (::Variante von /commands)."""
|
||
from archivar.inline_commands import build_help_text
|
||
return build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
|
||
async def _cmd_restart(self, room_id: str, args: str) -> str:
|
||
"""::restart — Löst einen Gateway-Neustart aus (::Variante von /restart).
|
||
|
||
Sendet SIGTERM an den eigenen Prozess. systemd linger startet
|
||
den Service automatisch neu (Restart=always in der Unit).
|
||
|
||
P0: State-Cleanup VOR SIGTERM — gateway_state.json, gateway.lock,
|
||
Onboarding-State werden bereinigt, damit nach dem Neustart ein
|
||
sauberer State vorliegt (analog zu install.sh --update-only).
|
||
"""
|
||
logger.info("[rocketchat] R5: ::restart — Gateway-Neustart angefordert von room=%s", room_id[:12])
|
||
|
||
def _cleanup_and_kill():
|
||
"""State-Cleanup vor SIGTERM (P0)."""
|
||
home = os.path.expanduser("~/.hermes")
|
||
|
||
# 1. gateway_state.json + gateway.lock entfernen
|
||
for fname in ["gateway_state.json", "gateway.lock"]:
|
||
path = os.path.join(home, fname)
|
||
try:
|
||
os.remove(path)
|
||
logger.info("[rocketchat] P0: %s gelöscht", fname)
|
||
except FileNotFoundError:
|
||
pass
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P0: %s konnte nicht gelöscht werden: %s", fname, e)
|
||
|
||
# .gateway_state_*.tmp entfernen
|
||
import glob
|
||
for tmp in glob.glob(os.path.join(home, ".gateway_state_*.tmp")):
|
||
try:
|
||
os.remove(tmp)
|
||
logger.info("[rocketchat] P0: %s gelöscht", os.path.basename(tmp))
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P0: tmp-Datei konnte nicht gelöscht werden: %s", e)
|
||
|
||
# 2. Onboarding-State zurücksetzen (falls aktiv)
|
||
if self._onboarding_state:
|
||
try:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
missing = self._onboarding_state.get("missing_rooms", [])
|
||
for room in missing:
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
logger.info("[rocketchat] P0: Onboarding-State zurückgesetzt")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P0: Onboarding-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 3. JETZT SIGTERM senden
|
||
os.kill(os.getpid(), signal.SIGTERM)
|
||
|
||
asyncio.get_event_loop().call_later(0.5, _cleanup_and_kill)
|
||
return (
|
||
"🔄 **Gateway-Neustart eingeleitet**\n\n"
|
||
"Der Hermes-Gateway-Dienst wird neu gestartet. "
|
||
"Dies kann einige Sekunden dauern.\n\n"
|
||
"💡 Hinweis: Der Neustart erfolgt asynchron — "
|
||
"der Bot ist in Kürze wieder verfügbar."
|
||
)
|
||
|
||
async def _cmd_update(self, room_id: str, args: str) -> str:
|
||
"""::update — Zeigt Update-Informationen (::Variante von /update)."""
|
||
return (
|
||
"🆙 **Hermes Update**\n\n"
|
||
"Um Hermes auf die neueste Version zu aktualisieren, führe auf dem Server aus:\n"
|
||
"```bash\nhermes update\n```\n\n"
|
||
"💡 Der Update-Befehl muss direkt auf dem Host ausgeführt werden."
|
||
)
|
||
|
||
# ── R5.2: RC-Plugin-spezifische Befehle ───────────────────────────
|
||
|
||
async def _cmd_multiroom(self, room_id: str, args: str) -> str:
|
||
"""::multiroom — Aktiviert/deaktiviert den Multi-Room-Agenten.
|
||
|
||
Args: on|off|status
|
||
|
||
P1-5: Schreibt .env selbst statt nur Text-Hinweis.
|
||
"""
|
||
import os
|
||
from pathlib import Path
|
||
|
||
sub = args.strip().lower() if args else "status"
|
||
current = _MULTIROOM()
|
||
env_path = Path(os.path.expanduser("~/.hermes/.env"))
|
||
|
||
if sub == "status":
|
||
state = "✅ **Aktiviert**" if current else "❌ **Deaktiviert**"
|
||
return (
|
||
f"🏠 **Multi-Room-Agent:** {state}\n\n"
|
||
"Im Multiroom-Modus kann der Agent Nachrichten aus verschiedenen Räumen "
|
||
"klassifizieren und thematisch routen.\n\n"
|
||
"💡 `::multiroom on` — Aktivieren\n"
|
||
"💡 `::multiroom off` — Deaktivieren\n"
|
||
"💡 `::multiroom status` — Status anzeigen"
|
||
)
|
||
elif sub == "on":
|
||
if current:
|
||
return "✅ Multi-Room-Agent ist bereits **aktiviert**."
|
||
# P1-5: .env selbst schreiben
|
||
try:
|
||
if env_path.exists():
|
||
content = env_path.read_text()
|
||
if "MULTIROOM_AGENT=false" in content:
|
||
content = content.replace("MULTIROOM_AGENT=false", "MULTIROOM_AGENT=true")
|
||
elif "MULTIROOM_AGENT=true" not in content:
|
||
content += "\nMULTIROOM_AGENT=true\n"
|
||
env_path.write_text(content)
|
||
else:
|
||
env_path.write_text("MULTIROOM_AGENT=true\n")
|
||
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=true")
|
||
except Exception as e:
|
||
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||
return (
|
||
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||
f"Fehler: {e}\n\n"
|
||
"Setze `MULTIROOM_AGENT=true` in `~/.hermes/.env` und starte neu."
|
||
)
|
||
return (
|
||
"✅ **Multi-Room-Agent aktiviert.**\n\n"
|
||
"`MULTIROOM_AGENT=true` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||
"🔁 **Gateway-Neustart erforderlich.** "
|
||
"Nutze `::restart` zum Neustarten."
|
||
)
|
||
elif sub == "off":
|
||
if not current:
|
||
return "❌ Multi-Room-Agent ist bereits **deaktiviert**."
|
||
# P1-5: .env selbst schreiben
|
||
try:
|
||
if env_path.exists():
|
||
content = env_path.read_text()
|
||
if "MULTIROOM_AGENT=true" in content:
|
||
content = content.replace("MULTIROOM_AGENT=true", "MULTIROOM_AGENT=false")
|
||
elif "MULTIROOM_AGENT=false" not in content:
|
||
content += "\nMULTIROOM_AGENT=false\n"
|
||
env_path.write_text(content)
|
||
else:
|
||
env_path.write_text("MULTIROOM_AGENT=false\n")
|
||
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=false")
|
||
except Exception as e:
|
||
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||
return (
|
||
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||
f"Fehler: {e}\n\n"
|
||
"Setze `MULTIROOM_AGENT=false` in `~/.hermes/.env` und starte neu."
|
||
)
|
||
return (
|
||
"✅ **Multi-Room-Agent deaktiviert.**\n\n"
|
||
"`MULTIROOM_AGENT=false` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||
"🔁 **Gateway-Neustart erforderlich.** "
|
||
"Nutze `::restart` zum Neustarten."
|
||
)
|
||
else:
|
||
return (
|
||
f"❌ Unbekannte Option: `{sub}`\n\n"
|
||
"Verfügbar: `on`, `off`, `status`"
|
||
)
|
||
|
||
# ── P1-8: ::approve / ::deny Handler ──────────────────────────────
|
||
|
||
async def _cmd_approve(self, room_id: str, args: str) -> str:
|
||
"""::approve — Bestätigt einen gefährlichen Befehl.
|
||
|
||
Subcommands:
|
||
(ohne) — Einmalig bestätigen (scope='once')
|
||
session — Für die aktuelle Session bestätigen (scope='session')
|
||
always — Dauerhaft bestätigen (scope='always')
|
||
|
||
P1-8: Die Hermes-Core-Approval-API (approve_pending) ist zum
|
||
Zeitpunkt der Implementierung nicht als öffentliche API verfügbar.
|
||
Der Handler ist als Stub mit klarer Schnittstelle implementiert.
|
||
Sobald die Core-API stabil ist, kann sie hier eingebunden werden:
|
||
|
||
from hermes_agent.approval import approve_pending
|
||
approve_pending(command_id, scope=scope)
|
||
|
||
Aktuell liefert der Handler eine sinnvolle Bestätigungsmeldung
|
||
und loggt den Aufruf. Die tatsächliche Approval-Logik wird vom
|
||
Gateway-Kern behandelt, sobald die API verfügbar ist.
|
||
"""
|
||
sub = args.strip().lower() if args else ""
|
||
scope = "once"
|
||
if sub == "session":
|
||
scope = "session"
|
||
elif sub == "always":
|
||
scope = "always"
|
||
|
||
logger.info(
|
||
"[rocketchat] P1-8: ::approve scope=%s room=%s — "
|
||
"Core-Approval-API noch nicht verfügbar (Stub)",
|
||
scope, room_id[:12],
|
||
)
|
||
|
||
# P1-8 ESCALATION: Sobald Hermes Core eine öffentliche
|
||
# approve_pending(command_id, scope) API bereitstellt,
|
||
# hier einbinden:
|
||
# try:
|
||
# from hermes_agent.approval import approve_pending
|
||
# approve_pending(command_id, scope=scope)
|
||
# except ImportError:
|
||
# pass # Core-API nicht verfügbar
|
||
|
||
scope_labels = {
|
||
"once": "einmalig",
|
||
"session": "für diese Session",
|
||
"always": "dauerhaft (Allow-Always)",
|
||
}
|
||
return (
|
||
f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**\n\n"
|
||
"Die Bestätigung wurde an den Hermes-Core-Approval-Handler "
|
||
"weitergeleitet.\n\n"
|
||
"💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig "
|
||
"verdrahtet (P1-8). Die Bestätigung wird vom Gateway-Kern "
|
||
"verarbeitet, sobald die API verfügbar ist."
|
||
)
|
||
|
||
async def _cmd_deny(self, room_id: str, args: str) -> str:
|
||
"""::deny — Lehnt einen gefährlichen Befehl ab.
|
||
|
||
P1-8: Analog zu _cmd_approve — die Core-API deny_pending()
|
||
ist noch nicht als öffentliche API verfügbar. Stub mit
|
||
klarer Schnittstelle.
|
||
"""
|
||
logger.info(
|
||
"[rocketchat] P1-8: ::deny room=%s — "
|
||
"Core-Approval-API noch nicht verfügbar (Stub)",
|
||
room_id[:12],
|
||
)
|
||
|
||
# P1-8 ESCALATION: Sobald Hermes Core eine öffentliche
|
||
# deny_pending(command_id) API bereitstellt, hier einbinden:
|
||
# try:
|
||
# from hermes_agent.approval import deny_pending
|
||
# deny_pending(command_id)
|
||
# except ImportError:
|
||
# pass
|
||
|
||
return (
|
||
"❌ **Befehl abgelehnt.**\n\n"
|
||
"Der gefährliche Befehl wird nicht ausgeführt.\n\n"
|
||
"💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig "
|
||
"verdrahtet (P1-8). Der Befehl wird trotzdem blockiert."
|
||
)
|
||
|
||
async def _cmd_setstatus(self, room_id: str, args: str) -> str:
|
||
"""V8.6: ::setstatus — Aktivitäts-Indikator an/abschalten.
|
||
|
||
Subcommands:
|
||
on — Aktivitäts-Indikator einschalten
|
||
off — Aktivitäts-Indikator ausschalten
|
||
status — Status anzeigen
|
||
"""
|
||
subcmd = args.strip().lower() if args else "status"
|
||
|
||
# Graceful degradation: wenn _presence_engine nicht existiert
|
||
if not hasattr(self, '_presence_engine') or self._presence_engine is None:
|
||
return "⚠️ Aktivitäts-Indikator nicht verfügbar (PresenceEngine nicht initialisiert)."
|
||
|
||
if subcmd in ("on", "an", "ein", "enable", "start"):
|
||
self._presence_engine.enable()
|
||
# P0-3: ::setstatus on → PulseController aktivieren
|
||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||
if self.ddp:
|
||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
||
|
||
elif subcmd in ("off", "aus", "disable", "stop"):
|
||
self._presence_engine.disable()
|
||
# P0-3: ::setstatus off → PulseController stoppen
|
||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||
self._presence_engine._pulse_controller.stop()
|
||
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
||
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
||
|
||
else:
|
||
# status
|
||
enabled = self._presence_engine.is_enabled()
|
||
active = self._presence_engine._active_tasks
|
||
bg = self._presence_engine._background_tasks
|
||
onboarding = self._presence_engine._onboarding_active
|
||
error = self._presence_engine._error_state
|
||
|
||
lines = [
|
||
"📊 **Aktivitäts-Indikator Status**",
|
||
"",
|
||
f"Status: {'🟢 Aktiviert' if enabled else '🔴 Deaktiviert'}",
|
||
f"Aktive Tasks: {active}",
|
||
f"Background Tasks: {bg}",
|
||
]
|
||
if onboarding:
|
||
lines.append("Onboarding: 🔄 Läuft")
|
||
if error:
|
||
lines.append(f"Fehler: ⚠️ {error}")
|
||
if not enabled:
|
||
lines.append("", "💡 `::setstatus on` zum Aktivieren")
|
||
|
||
return "\n".join(lines)
|
||
|
||
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
||
"""::onboarding — Onboarding State Machine Steuerung.
|
||
|
||
Subcommands:
|
||
start — NONE → AWAITING_ROOM (Onboarding beginnen)
|
||
status — Zeigt State + nächsten Schritt + Fortschritt
|
||
resume — PAUSED → letzter State
|
||
pause — beliebiger State → PAUSED
|
||
abort — Reset (mit Bestätigung)
|
||
reset — Hart-Reset, Backups bleiben
|
||
|
||
Ohne Subcommand: Status anzeigen.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::onboarding` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
from archivar.onboarding_state import OnboardingStateMachine, OnboardingState
|
||
|
||
# Initialisiere State Machine falls noch nicht geschehen
|
||
if not hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm = OnboardingStateMachine()
|
||
self._onboarding_sm.load()
|
||
|
||
sm = self._onboarding_sm
|
||
sub = args.strip().lower() if args else ""
|
||
|
||
# ── ::onboarding (ohne Args) → Status ──────────────────────────
|
||
if not sub:
|
||
return sm.get_status_text() + "\n\n💡 " + sm.get_next_step_hint()
|
||
|
||
# ── ::onboarding start ──────────────────────────────────────────
|
||
if sub == "start":
|
||
if sm.state == OnboardingState.ACTIVE:
|
||
return (
|
||
"✅ Onboarding bereits abgeschlossen.\n\n"
|
||
"💡 `::onboarding reset` um neu zu starten.\n"
|
||
"💡 `::onboarding status` für Details."
|
||
)
|
||
if sm.is_active:
|
||
return (
|
||
f"🔄 Onboarding läuft bereits ({sm.progress_text}).\n\n"
|
||
"💡 `::onboarding status` für Details.\n"
|
||
"💡 `::onboarding pause` zum Pausieren."
|
||
)
|
||
|
||
# Alten State bereinigen
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in self._onboarding_state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
self.archivar._state.clear_onboarding_state()
|
||
|
||
# F8: State Machine starten — NONE → AWAITING_ROOM
|
||
# sm.start() setzt den State und persistiert
|
||
operator_room_id = room_id
|
||
sm.start(operator_room_id=operator_room_id, missing_rooms=[])
|
||
|
||
# Finde fehlende Räume
|
||
subscribed_with_types = {
|
||
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:
|
||
# Es gibt fehlende Räume → Interview-Flow
|
||
await self._start_onboarding(missing)
|
||
else:
|
||
# Room-Map vollständig → Review-Flow (UX: Werte zeigen, anpassen/überspringen)
|
||
await self._start_onboarding_review(operator_room_id)
|
||
return "" # _start_onboarding / _start_onboarding_review posten selbst
|
||
|
||
# ── ::onboarding status ─────────────────────────────────────────
|
||
if sub == "status":
|
||
return sm.get_status_text() + "\n\n💡 " + sm.get_next_step_hint()
|
||
|
||
# ── ::onboarding resume ─────────────────────────────────────────
|
||
if sub == "resume":
|
||
if sm.state == OnboardingState.ERROR:
|
||
# Aus ERROR: versuche in den vorherigen State zurück
|
||
sm._data.error_message = ""
|
||
prev = sm.previous_state
|
||
if prev and prev != OnboardingState.ERROR:
|
||
sm._data.current_state = prev.value
|
||
sm.save()
|
||
else:
|
||
sm._data.current_state = OnboardingState.AWAITING_ROOM.value
|
||
sm.save()
|
||
return (
|
||
f"🔄 Onboarding fortgesetzt ({sm.progress_text}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
if sm.state != OnboardingState.PAUSED:
|
||
return (
|
||
f"❌ Onboarding ist nicht pausiert (aktuell: {sm.state.value}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
if not sm.resume():
|
||
return "❌ Fehler beim Fortsetzen des Onboardings."
|
||
return (
|
||
f"🔄 Onboarding fortgesetzt ({sm.progress_text}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
|
||
# ── ::onboarding pause ──────────────────────────────────────────
|
||
if sub == "pause":
|
||
if not sm.is_active:
|
||
return (
|
||
f"❌ Onboarding kann nicht pausiert werden (aktuell: {sm.state.value}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
if not sm.pause():
|
||
return "❌ Fehler beim Pausieren des Onboardings."
|
||
# Auch den Adapter-State pausieren
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
return (
|
||
"⏸️ Onboarding pausiert.\n\n"
|
||
"💡 `::onboarding resume` zum Fortsetzen.\n"
|
||
"💡 `::onboarding status` für Details."
|
||
)
|
||
|
||
# ── ::onboarding abort ──────────────────────────────────────────
|
||
if sub == "abort":
|
||
if sm.state == OnboardingState.NONE:
|
||
return "✅ Kein aktives Onboarding zum Abbrechen."
|
||
# P0-3: Laufenden Agent-Dispatch-Task killen.
|
||
# Ohne Cancel läuft der LLM-Agent weiter (iteration 7/90, 9 min).
|
||
if hasattr(self, '_agent_dispatch_task') and self._agent_dispatch_task is not None:
|
||
self._agent_dispatch_task.cancel()
|
||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled via ::onboarding abort")
|
||
# Locks freigeben
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in self._onboarding_state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
sm.abort()
|
||
return "🛑 Onboarding abgebrochen. Alle Locks freigegeben."
|
||
|
||
# ── ::onboarding reset ──────────────────────────────────────────
|
||
if sub == "reset":
|
||
# Locks freigeben
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in self._onboarding_state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
sm.reset()
|
||
return "🔄 Onboarding hart zurückgesetzt. Backups bleiben erhalten."
|
||
|
||
# ── Unbekannter Subcommand ──────────────────────────────────────
|
||
return (
|
||
f"❌ Unbekannter Subcommand: `{sub}`\n\n"
|
||
"Verfügbar: `start`, `status`, `resume`, `pause`, `abort`, `reset`\n\n"
|
||
"💡 `::onboarding` (ohne Args) zeigt den Status."
|
||
)
|
||
|
||
async def _cmd_curate(self, room_id: str, args: str) -> str:
|
||
"""::curate — Kuratiert die Room-Map-Keywords (R10).
|
||
|
||
Ohne Args: Zeigt den Kuratierungs-Status.
|
||
Mit 'run': Führt eine Keyword-Kuratierung durch.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::curate` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
sub = args.strip().lower() if args else "status"
|
||
|
||
if sub == "status":
|
||
room_map = self.archivar._room_map
|
||
total_keywords = sum(
|
||
len(entry.keywords_100) + len(entry.keywords_context)
|
||
for entry in room_map.rooms.values()
|
||
)
|
||
return (
|
||
"🔍 **Room-Map Keyword-Kuratierung**\n\n"
|
||
f"- **Räume:** {len(room_map.rooms)}\n"
|
||
f"- **Keywords gesamt:** {total_keywords}\n"
|
||
f"- **Map-Version:** v{room_map.version}\n\n"
|
||
"💡 `::curate run` — Keyword-Kuratierung durchführen\n"
|
||
"💡 `::curate status` — diesen Status anzeigen"
|
||
)
|
||
elif sub == "run":
|
||
# ── Echte Keyword-Kuratierung (R10) ──────────────────────────
|
||
# 1. 90-Tage-Demotion via KeywordBooster
|
||
# 2. Red-Flag-Feedback-Analyse via routing_counter
|
||
# 3. Promotion-Kandidaten via ArchivarState
|
||
# 4. Keyword-Gewicht-Anomalien via ArchivarState
|
||
# 5. Persistiere Änderungen in room-map.json
|
||
room_map = self.archivar._room_map
|
||
state = self.archivar._state
|
||
booster = self.archivar._booster
|
||
lines: list[str] = []
|
||
changes_made = False
|
||
|
||
# ── Schritt 1: 90-Tage-Demotion ──────────────────────────
|
||
if booster is not None:
|
||
demoted = booster.demote_stale_keywords(max_age_days=90)
|
||
if demoted > 0:
|
||
lines.append(
|
||
f"🔄 **Demotion:** {demoted} Keyword(s) von 100% → Kontext "
|
||
f"(>90 Tage kein Match)"
|
||
)
|
||
changes_made = True
|
||
else:
|
||
lines.append("✅ **Demotion:** Keine veralteten Keywords")
|
||
else:
|
||
lines.append("⚠️ **Demotion:** Booster nicht verfügbar")
|
||
|
||
# ── Schritt 2: Red-Flag-Feedback ─────────────────────────
|
||
from archivar.routing_counter import routing_counter
|
||
counts = routing_counter.get_counts()
|
||
red_flag_triggered = counts.get("red_flag_triggered", 0)
|
||
red_flag_routed = counts.get("red_flag_agent_routed", 0)
|
||
red_flag_dispatched = counts.get("red_flag_dispatched", 0)
|
||
lines.append(
|
||
f"🚩 **Red-Flag-Feedback:** {red_flag_triggered} getriggert, "
|
||
f"{red_flag_routed} geroutet, {red_flag_dispatched} dispatched"
|
||
)
|
||
|
||
# ── Schritt 3: Promotion-Kandidaten ──────────────────────
|
||
if state._promotion_candidates:
|
||
promo_lines = []
|
||
for kw, rooms_dict in list(state._promotion_candidates.items())[:10]:
|
||
for rid, info in rooms_dict.items():
|
||
entry = room_map.get_room_by_id(rid)
|
||
room_name = entry.name if entry else rid[:8]
|
||
promo_lines.append(
|
||
f" - `{kw}` → {room_name} "
|
||
f"(Score: {info.get('score', 0):.1f})"
|
||
)
|
||
if promo_lines:
|
||
lines.append(
|
||
f"⭐ **Promotion-Kandidaten ({len(state._promotion_candidates)}):**\n"
|
||
+ "\n".join(promo_lines)
|
||
)
|
||
else:
|
||
lines.append("⭐ **Promotion-Kandidaten:** Keine")
|
||
|
||
# ── Schritt 4: Keyword-Gewicht-Anomalien ──────────────────
|
||
if state._keyword_weights:
|
||
anomaly_count = 0
|
||
anomaly_lines = []
|
||
for kw, rooms_dict in state._keyword_weights.items():
|
||
for rid, entry in rooms_dict.items():
|
||
if entry.weight <= 0.1 and entry.rejection_count >= 2:
|
||
anomaly_count += 1
|
||
if len(anomaly_lines) < 5:
|
||
room_entry = room_map.get_room_by_id(rid)
|
||
room_name = room_entry.name if room_entry else rid[:8]
|
||
anomaly_lines.append(
|
||
f" - `{kw}` → {room_name} "
|
||
f"(Gewicht: {entry.weight:.2f}, "
|
||
f"Rejections: {entry.rejection_count})"
|
||
)
|
||
if anomaly_lines:
|
||
lines.append(
|
||
f"⚠️ **Gewicht-Anomalien ({anomaly_count}):**\n"
|
||
+ "\n".join(anomaly_lines)
|
||
)
|
||
else:
|
||
lines.append("⚠️ **Gewicht-Anomalien:** Keine Daten")
|
||
|
||
# ── Schritt 5: Ring-State-Info ───────────────────────────
|
||
if state._ring_state:
|
||
active_rings = 0
|
||
for rid, ring in state._ring_state.items():
|
||
if state.is_ring_state_active(rid, ring.get("state", "")):
|
||
active_rings += 1
|
||
if active_rings > 0:
|
||
lines.append(f"🔔 **Aktive Ring-States:** {active_rings} Raum/Räume im Strategie-Modus")
|
||
else:
|
||
lines.append("🔔 **Ring-States:** Keine")
|
||
|
||
# ── Schritt 6: Persistieren ──────────────────────────────
|
||
if changes_made:
|
||
try:
|
||
from pathlib import Path as PathLib
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from archivar.room_map import RoomMap
|
||
RoomMap.save(room_map, PathLib(ROOM_MAP_PATH))
|
||
lines.append("\n💾 Änderungen in `room-map.json` persistiert")
|
||
except Exception as e:
|
||
lines.append(f"\n❌ Fehler beim Persistieren: {e}")
|
||
|
||
# ── Zusammenfassung ──────────────────────────────────────
|
||
total_keywords = sum(
|
||
len(entry.keywords_100) + len(entry.keywords_context)
|
||
for entry in room_map.rooms.values()
|
||
)
|
||
return (
|
||
"🔍 **Keyword-Kuratierung — Ergebnisse**\n\n"
|
||
+ "\n".join(lines)
|
||
+ f"\n\n📊 **Map-Status:** {len(room_map.rooms)} Räume, "
|
||
f"{total_keywords} Keywords, v{room_map.version}"
|
||
)
|
||
else:
|
||
return (
|
||
f"❌ Unbekannte Option: `{sub}`\n\n"
|
||
"Verfügbar: `status`, `run`"
|
||
)
|
||
|
||
@staticmethod
|
||
def _message_type_for(is_button_response: bool) -> "MessageType":
|
||
"""Return the appropriate MessageType for a button response.
|
||
|
||
P1 fix: Hermes-Core has no BUTTON_CLICK enum member.
|
||
Button responses are dispatched as COMMAND so the agent
|
||
can handle them as structured input.
|
||
"""
|
||
return MessageType.COMMAND if is_button_response else MessageType.TEXT
|
||
|
||
async def _dispatch_agent(
|
||
self,
|
||
text: str,
|
||
room_id: str,
|
||
room_name: str,
|
||
room_type: str,
|
||
username: str,
|
||
msg_id: str,
|
||
msg_obj: dict,
|
||
is_button_response: bool = False,
|
||
category: str = "",
|
||
) -> None:
|
||
"""Dispatch an agent turn via the gateway handler.
|
||
|
||
V7-1: Extracted from _process_incoming so it can be called from
|
||
the move-request confirmation path (after ✅Ja) with
|
||
_CURRENT_ORIGIN_ROOM already set to the target room.
|
||
"""
|
||
# ── Virtual Room Translation ─────────────────────────────────
|
||
virtual_chat_id = f"user:{username}"
|
||
|
||
# Ensure this user→room mapping is recorded for proaktive sends
|
||
if virtual_chat_id not in self._user_rooms:
|
||
self._user_rooms[virtual_chat_id] = []
|
||
if room_id not in self._user_rooms[virtual_chat_id]:
|
||
self._user_rooms[virtual_chat_id].append(room_id)
|
||
|
||
# Dispatch to gateway handler via base-class handle_message
|
||
try:
|
||
from datetime import datetime
|
||
|
||
message_type = self._message_type_for(is_button_response)
|
||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||
if target_room_id:
|
||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]"
|
||
else:
|
||
# Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung
|
||
room_names = [info.get("name", "?") for rid, info in self._room_info.items()
|
||
if info.get("type") in ("c", "p") and rid != room_id]
|
||
rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume"
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]"
|
||
# ── Ende Kontext-Weitergabe ──────────────────────────────────────
|
||
source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=virtual_chat_id,
|
||
chat_name=f"{room_name} (via @{username})" + archivar_suffix + (f" [{category}]" if category else ""),
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
chat_topic=self._room_map_summary,
|
||
)
|
||
# ── FIX A: Text-Prefix in User-Nachricht injizieren ──────────
|
||
room_type_label = {"c": "channel", "p": "group", "d": "dm"}.get(room_type, room_type)
|
||
room_context_prefix = f"[Raum: {room_name} ({room_type_label})] "
|
||
contextualized_text = room_context_prefix + text
|
||
|
||
event = MessageEvent(
|
||
text=contextualized_text,
|
||
message_type=message_type,
|
||
message_id=msg_id,
|
||
timestamp=datetime.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
event.source = source
|
||
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
|
||
ctx = contextvars.copy_context()
|
||
# V8.1 P1 diagnostic: log dispatch context
|
||
_origin = _CURRENT_ORIGIN_ROOM.get()
|
||
_target = _THEMATIC_TARGET_ROOM.get()
|
||
logger.info(
|
||
"V8.1 P1 dispatch: chat_id=%s → target_room=%s, "
|
||
"_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s",
|
||
virtual_chat_id, _target if _target else room_id,
|
||
_origin[:8] if _origin else "",
|
||
_target[:8] if _target else "",
|
||
)
|
||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||
self._agent_dispatch_task = asyncio.create_task(
|
||
ctx.run(self.handle_message, event)
|
||
)
|
||
try:
|
||
await self._agent_dispatch_task
|
||
except asyncio.CancelledError:
|
||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||
return
|
||
finally:
|
||
self._agent_dispatch_task = None
|
||
except Exception as e:
|
||
logger.error("[rocketchat] handle_message error: %s", e)
|
||
# Fallback: Wenn COMMAND fehlschlägt
|
||
if is_button_response and str(e) == "COMMAND":
|
||
logger.info("[rocketchat] COMMAND lost context — retrying as TEXT")
|
||
try:
|
||
from datetime import datetime as dt2
|
||
fallback_source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=f"user:{username}",
|
||
chat_name=f"{room_name} (via @{username})",
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
chat_topic=self._room_map_summary,
|
||
)
|
||
fallback_event = MessageEvent(
|
||
text=f"[Button-Antwort: {text}]",
|
||
message_type=MessageType.TEXT,
|
||
message_id=msg_id,
|
||
timestamp=dt2.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
fallback_event.source = fallback_source
|
||
await self.handle_message(fallback_event)
|
||
except Exception as e2:
|
||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||
|
||
async def _send_via_archivar(self, room_id: str, text: str) -> bool:
|
||
"""Callback for Archivar forwarding — sends a message copy to a target room."""
|
||
if not self.rest.auth_token:
|
||
return False
|
||
return await self._post_message_with_retry(room_id, text) is not None
|
||
|
||
async def _send_archivar_buttons(self, room_id: str, text: str, payload: dict) -> bool:
|
||
"""Callback for Archivar — sends native Rocket.Chat Action-Buttons.
|
||
|
||
Handles both clarification (ARCHIVAR_CLARIFY:) and move-request
|
||
(MOVE_REQ:) buttons. Move-request context is stored in
|
||
self._pending_move_requests so the response handler picks it up.
|
||
|
||
Args:
|
||
room_id: Target room ID
|
||
text: Message text
|
||
payload: {
|
||
"actions": [{"text": "...", "type": "..."}, ...],
|
||
"_move_request": { # optional, set by Archivar v4 _send_move_request
|
||
"target_room": "...",
|
||
"target_name": "...",
|
||
"text": "...",
|
||
}
|
||
}
|
||
|
||
Returns:
|
||
True if sent successfully, False on error
|
||
"""
|
||
if not self.rest.auth_token:
|
||
return False
|
||
|
||
# _build_custom_buttons available via top-level sys.modules access
|
||
|
||
actions = payload.get("actions", [])
|
||
if not actions:
|
||
return await self._post_message_with_retry(room_id, text) is not None
|
||
|
||
# Detect Archivar v4 Move-Request (Butler-Prinzip: ✅Ja / 📍Hier)
|
||
move_req_ctx = payload.get("_move_request")
|
||
if move_req_ctx:
|
||
# Store pending move request so line 717 handler finds it
|
||
self._pending_move_requests[room_id] = {
|
||
"text": move_req_ctx.get("text", ""),
|
||
"origin_room": room_id,
|
||
"target_room": move_req_ctx.get("target_room", ""),
|
||
"target_name": move_req_ctx.get("target_name", ""),
|
||
"username": "", # filled from user_info in handler (line 718)
|
||
"message_id": "", # no msg_id for Archivar v4 move-request flow
|
||
}
|
||
# Use MOVE_REQ: prefix so the existing handler at line 717-764
|
||
# parses the response correctly (see line 722-724)
|
||
msg_prefix = f"MOVE_REQ:{room_id}"
|
||
log_tag = "move-request"
|
||
else:
|
||
msg_prefix = "ARCHIVAR_CLARIFY"
|
||
log_tag = "clarification"
|
||
|
||
# Build native RC buttons from Archivar actions
|
||
buttons = []
|
||
for i, action in enumerate(actions):
|
||
action_type = action.get("type", f"action_{i}")
|
||
action_text = action.get("text", f"Option {i+1}")
|
||
# Move-request buttons use :: separator for line 722 parsing
|
||
selector = f"{msg_prefix}::{action_type}" if move_req_ctx else f"{msg_prefix}:{action_type}"
|
||
buttons.append({
|
||
"type": "button",
|
||
"text": action_text,
|
||
"msg": selector,
|
||
"msg_in_chat_window": True,
|
||
"style": "default",
|
||
})
|
||
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": text,
|
||
"actions": buttons,
|
||
}]
|
||
|
||
# Split buttons into groups of max 3 per attachment (UX: mobile readability)
|
||
MAX_BUTTONS_PER_ROW = 3
|
||
if len(buttons) > MAX_BUTTONS_PER_ROW:
|
||
attachments = []
|
||
for i in range(0, len(buttons), MAX_BUTTONS_PER_ROW):
|
||
chunk = buttons[i:i + MAX_BUTTONS_PER_ROW]
|
||
attachments.append({
|
||
"color": "#1d74f5",
|
||
"actions": chunk,
|
||
})
|
||
# First attachment gets the title
|
||
if attachments:
|
||
attachments[0]["title"] = text
|
||
|
||
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
||
if success is not None:
|
||
# Mark room so the response stays here (no Archivar routing)
|
||
self._rooms_with_pending_questions.add(room_id)
|
||
logger.info("[rocketchat] Sent Archivar %s with %d buttons to %s",
|
||
log_tag, len(buttons), room_id[:8])
|
||
return success
|
||
|
||
def _get_build_custom_buttons(self):
|
||
"""Robust access to _build_custom_buttons, with fallback.
|
||
|
||
Returns the real _build_custom_buttons function from the rocketchat
|
||
__init__ module. If unavailable, returns a local implementation that
|
||
builds correct Rocket.Chat button dicts directly.
|
||
"""
|
||
import sys as _sys
|
||
# Try the same lookup pattern used in send() and send_clarify()
|
||
_init = _sys.modules.get('rocketchat')
|
||
if _init is not None:
|
||
fn = getattr(_init, '_build_custom_buttons', None)
|
||
if fn is not None:
|
||
return fn
|
||
# Fallback: local implementation (Bug 3 fix — ensures buttons always render)
|
||
def _local_build(labels, prefix='', style='default'):
|
||
buttons = []
|
||
for label in labels:
|
||
display = 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": style,
|
||
})
|
||
return buttons
|
||
logger.warning("[rocketchat] _build_custom_buttons not found in rocketchat module — using local fallback")
|
||
return _local_build
|
||
|
||
# ── UX-7: Numbered Button Labels ────────────────────────────────────
|
||
|
||
# Emoji-Zahlen für bis zu 10 Buttons (UX-7: Rocket.Chat schneidet
|
||
# Button-Texte ab — Nummern machen Buttons kürzer und eindeutiger).
|
||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||
|
||
@staticmethod
|
||
def numbered_button_labels(labels: list, start: int = 0) -> list:
|
||
"""Prefix labels with emoji numbers for shorter, clearer buttons.
|
||
|
||
Rocket.Chat schneidet Button-Texte ab. Nummerierte Buttons
|
||
(1️⃣ Label) sind kürzer und eindeutiger als lange Texte.
|
||
|
||
Args:
|
||
labels: Liste von Button-Label-Strings
|
||
start: Start-Index (0-basiert) in EMOJI_NUMBERS
|
||
|
||
Returns:
|
||
Liste von nummerierten Labels: ["1️⃣ Label1", "2️⃣ Label2", ...]
|
||
"""
|
||
result = []
|
||
for i, label in enumerate(labels):
|
||
idx = start + i
|
||
if idx < len(RocketChatAdapter.EMOJI_NUMBERS):
|
||
emoji = RocketChatAdapter.EMOJI_NUMBERS[idx]
|
||
result.append(f"{emoji} {label}")
|
||
else:
|
||
result.append(f"{idx + 1}. {label}")
|
||
return result
|
||
|
||
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
|
||
|
||
Neues Design (UX-Fix):
|
||
- Pro Raum: EIN blauer Nummern-Button (1️⃣, 2️⃣, …) → style 'primary'
|
||
- Zwei globale Buttons: ⏭️ Alle überspringen, ⏰ Später
|
||
- Payload-Präfix: ONBOARD:<room_id>::select für Raum-Buttons,
|
||
ONBOARD::skip_all / ONBOARD::later für globale Aktionen
|
||
- Bei 4 Räumen: 6 Buttons statt 12 — keine abgeschnittenen Labels mehr
|
||
|
||
F8: State Machine Integration — sm.start() setzt NONE → AWAITING_ROOM.
|
||
|
||
Args:
|
||
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
||
"""
|
||
# F8: State Machine initialisieren und starten
|
||
from archivar.onboarding_state import OnboardingStateMachine
|
||
if not hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm = OnboardingStateMachine()
|
||
self._onboarding_sm.load()
|
||
sm = self._onboarding_sm
|
||
# Finde den Operator-DM Raum (erster DM-Raum, nicht hardcoded auf "andreas")
|
||
operator_room_id = None
|
||
for room_id, info in self._room_info.items():
|
||
if info.get("type") == "d":
|
||
operator_room_id = room_id
|
||
break
|
||
|
||
if not operator_room_id:
|
||
logger.warning("[rocketchat] Kein DM-Raum gefunden, kann Onboarding nicht starten")
|
||
return
|
||
|
||
# DM thematisch onboarden: Wenn der DM noch kein Theme in der Map hat,
|
||
# als letzten Raum an missing_rooms anhängen.
|
||
dm_needs_onboarding = False
|
||
if self.archivar is not None and self.archivar._room_map is not None:
|
||
dm_entry = self.archivar._room_map.rooms.get(operator_room_id)
|
||
if dm_entry is None or not dm_entry.theme or dm_entry.theme == "Catch-All (legacy)":
|
||
dm_needs_onboarding = True
|
||
else:
|
||
# Keine Map vorhanden → DM braucht auf jeden Fall Onboarding
|
||
dm_needs_onboarding = True
|
||
|
||
if dm_needs_onboarding:
|
||
# Bug A: Dedup — DM nicht doppelt anhängen wenn bereits in missing_rooms
|
||
dm_already_in_missing = any(
|
||
r.get("room_id") == operator_room_id for r in missing_rooms
|
||
)
|
||
if not dm_already_in_missing:
|
||
dm_name = self._room_info.get(operator_room_id, {}).get("name", "DM")
|
||
dm_room = {"room_id": operator_room_id, "name": dm_name, "is_dm": True}
|
||
missing_rooms = list(missing_rooms) + [dm_room]
|
||
logger.info("[rocketchat] DM '%s' wird thematisch onboardet (als letzter Raum)", dm_name)
|
||
else:
|
||
logger.debug("[rocketchat] Bug A: DM bereits in missing_rooms — überspringe Dedup")
|
||
|
||
# Guard: Wenn nach DM-Prüfung nichts zu onboarden ist → return
|
||
if not missing_rooms:
|
||
logger.info("[rocketchat] Onboarding: Keine Räume zum Einrichten (alle bereits in Map)")
|
||
return
|
||
|
||
# A1b: Onboarding-Lock für den ersten Raum erwerben
|
||
# Verhindert parallele Interviews für denselben Raum
|
||
from archivar.onboarding import acquire_onboarding_lock, release_onboarding_lock
|
||
first_room_id = missing_rooms[0]["room_id"]
|
||
if not acquire_onboarding_lock(first_room_id):
|
||
logger.info(
|
||
"[rocketchat] A1b: Onboarding-Lock bereits aktiv für room=%s — "
|
||
"überspringe Start",
|
||
first_room_id[:12],
|
||
)
|
||
return
|
||
|
||
# F8: State Machine — NONE → AWAITING_ROOM
|
||
sm.start(operator_room_id=operator_room_id, missing_rooms=missing_rooms)
|
||
logger.info("[rocketchat] F8: State Machine gestartet — %s", sm.progress_text)
|
||
|
||
# A1b: Begrüßungs-Flow vor dem Interview
|
||
# Postet Begrüßung, wartet 30s (Spam-Vermeidung bei Multi-User-Join),
|
||
# startet dann das Interview
|
||
from archivar.onboarding import run_onboarding_greeting_flow
|
||
|
||
async def _start_interview():
|
||
await self._send_onboarding_message(operator_room_id, missing_rooms)
|
||
|
||
# F6 Re-Review Fix 2: Lock-Release bei Onboarding-Abbruch
|
||
# Wenn der Begrüßungs-Flow oder Interview-Start fehlschlägt
|
||
# (User verlässt Raum, Timeout, Fehler), muss der Lock
|
||
# freigegeben werden, damit ein erneuter Versuch möglich ist.
|
||
try:
|
||
await run_onboarding_greeting_flow(
|
||
room_id=operator_room_id,
|
||
send_callback=self._post_message_with_retry,
|
||
start_interview_callback=_start_interview,
|
||
room_name=self._room_info.get(operator_room_id, {}).get("name", ""),
|
||
)
|
||
except Exception:
|
||
release_onboarding_lock(first_room_id)
|
||
logger.warning(
|
||
"[rocketchat] A1b: Onboarding abgebrochen — Lock freigegeben: room=%s",
|
||
first_room_id[:12],
|
||
)
|
||
raise
|
||
return
|
||
|
||
async def _send_onboarding_message(self, operator_room_id: str, missing_rooms: list) -> None:
|
||
self._onboarding_state = {
|
||
"missing_rooms": missing_rooms,
|
||
"current_room_index": -1, # -1 = noch kein Raum ausgewählt
|
||
"current_question": 0, # 0 = noch keine Frage gestellt
|
||
"collected_data": {}, # room_id → {theme, keywords_100, keywords_context, catch_all}
|
||
"operator_room_id": operator_room_id,
|
||
"skipped_rooms": [], # room_ids die übersprungen wurden
|
||
}
|
||
# P1-4: Onboarding-State persistent speichern
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = True
|
||
# ── V8.6: PresenceEngine — Onboarding start → away ──
|
||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||
if _has_presence:
|
||
self._presence_engine.set_onboarding_active(True)
|
||
self._presence_engine.update_presence()
|
||
|
||
# Bug 3 fix: Robuster Zugriff auf _build_custom_buttons
|
||
_build = self._get_build_custom_buttons()
|
||
|
||
# Emoji-Zahlen für bis zu 10 Räume
|
||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||
|
||
lines = [
|
||
"🤖 **Auto-Onboarding** — Ich habe Räume gefunden, die noch nicht in meiner Raum-Map stehen.",
|
||
"",
|
||
"**Schritt 1 von 4: Räume**",
|
||
"",
|
||
"Ich brauche deine Hilfe, um sie einzurichten. Keine Sorge — ich führe dich Schritt für Schritt durch 4 kurze Fragen pro Raum.",
|
||
"",
|
||
"**Fehlende Räume:**",
|
||
]
|
||
for i, room in enumerate(missing_rooms):
|
||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||
clean_name = room["name"].lstrip("#")
|
||
lines.append(f"{emoji} {clean_name}")
|
||
|
||
lines.append("")
|
||
lines.append("⏭️ = Alle überspringen ⏰ = Später")
|
||
lines.append("")
|
||
lines.append("👉 Klicke auf eine Nummer, um den Raum einzurichten:")
|
||
text = "\n".join(lines)
|
||
|
||
# Raum-Buttons: blaue Nummern (style='primary')
|
||
buttons = []
|
||
for i, room in enumerate(missing_rooms):
|
||
rid = room["room_id"]
|
||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||
prefix = f"ONBOARD:{rid}"
|
||
buttons.extend(_build(
|
||
[emoji],
|
||
prefix=prefix,
|
||
style="primary"
|
||
))
|
||
|
||
# Globale Buttons (style='default' = grau)
|
||
buttons.extend(_build(
|
||
["⏭️ Alle überspringen", "⏰ Später"],
|
||
prefix="ONBOARD"
|
||
))
|
||
|
||
# Bug 3 fix: Wenn keine Buttons gebaut werden konnten, sende als Text
|
||
# mit klarer Anleitung (Fallback, sollte nie eintreten)
|
||
if not buttons:
|
||
logger.error("[rocketchat] Onboarding: Konnte keine Buttons bauen — sende Text-Fallback")
|
||
fallback_lines = lines + [
|
||
"",
|
||
"❌ Button-Fehler — bitte antworte mit der Nummer des Raums (1, 2, …) oder 'überspringen'.",
|
||
]
|
||
await self._post_message_with_retry(operator_room_id, "\n".join(fallback_lines))
|
||
return
|
||
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Raum-Map unvollständig — Räume einrichten?",
|
||
"actions": buttons,
|
||
}]
|
||
|
||
success = await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||
if success:
|
||
logger.info("[rocketchat] Onboarding v2 gestartet: %d Räume fehlen, %d Buttons", len(missing_rooms), len(buttons))
|
||
else:
|
||
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
|
||
|
||
async def _process_onboarding_response(self, text: str, room_id: str) -> None:
|
||
"""v2: Verarbeitet Onboarding-Antworten (Button-Klicks + Text-Antworten).
|
||
|
||
Zwei Modi:
|
||
1. Button-Klick (ONBOARD:<room_id>::<action>) — Raumauswahl / Überspringen / Später
|
||
2. Text-Antwort — Antwort auf eine der 4 Interview-Fragen
|
||
|
||
Args:
|
||
text: Die Antwortnachricht des Operators (Button-Payload oder Freitext)
|
||
room_id: Die Raum-ID, in der die Nachricht empfangen wurde
|
||
"""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
logger.debug("[rocketchat] Onboarding state empty, ignoring response")
|
||
return
|
||
|
||
operator_room_id = state.get("operator_room_id", "")
|
||
if room_id != operator_room_id:
|
||
logger.debug("[rocketchat] Onboarding response from non-operator room, ignoring")
|
||
return
|
||
|
||
# ── Phase: catch_all_change (nach Abschluss aller Interviews) ────
|
||
if state.get("phase") == "catch_all_change":
|
||
single_line = text.strip()
|
||
|
||
# Button-Klick erkennen: ONBOARD:<room_id>::<emoji>
|
||
if single_line.startswith("ONBOARD:"):
|
||
parts = single_line.split("::", 1)
|
||
payload = parts[0].replace("ONBOARD:", "") # room_id or "ONBOARD"
|
||
button_label = parts[1] if len(parts) > 1 else ""
|
||
|
||
# Überspringen-Button
|
||
if "Überspringen" in button_label or "⏭️" in button_label or payload == "ONBOARD":
|
||
await self._post_message_with_retry(operator_room_id, "👍 Catch-All bleibt unverändert.")
|
||
logger.info("[rocketchat] Catch-All unverändert (Button: Überspringen)")
|
||
else:
|
||
# Raum-Button → room_id als Catch-All setzen
|
||
all_rooms = self._get_onboarding_room_list()
|
||
dm_room_id = state.get("operator_room_id", "")
|
||
# Raum anhand ID finden
|
||
room_name = None
|
||
for rid, name, is_catch in all_rooms:
|
||
if rid == payload:
|
||
room_name = name
|
||
if rid == dm_room_id:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"👍 {name} ist bereits der Catch-All-Raum — bleibt unverändert.")
|
||
logger.info("[rocketchat] Catch-All bleibt DM (kein Wechsel nötig)")
|
||
else:
|
||
self._set_catch_all(rid)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
||
logger.info("[rocketchat] Catch-All geändert zu: %s (Button)", name)
|
||
break
|
||
if room_name is None:
|
||
await self._post_message_with_retry(operator_room_id, "❌ Raum nicht gefunden. Bitte erneut versuchen.")
|
||
return
|
||
elif single_line.isdigit():
|
||
index = int(single_line) - 1
|
||
all_rooms = self._get_onboarding_room_list()
|
||
if 0 <= index < len(all_rooms):
|
||
rid, name, _ = all_rooms[index]
|
||
dm_room_id = state.get("operator_room_id", "")
|
||
# Bug 6: DM auswählen → kein Wechsel nötig (ist bereits Catch-All)
|
||
if rid == dm_room_id:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"👍 {name} ist bereits der Catch-All-Raum — bleibt unverändert.")
|
||
logger.info("[rocketchat] Catch-All bleibt DM (kein Wechsel nötig)")
|
||
else:
|
||
self._set_catch_all(rid)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
||
logger.info("[rocketchat] Catch-All geändert zu: %s", name)
|
||
else:
|
||
await self._post_message_with_retry(operator_room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
|
||
return # onboarding_active bleibt True, warte auf korrekte Antwort
|
||
elif single_line.lower() in ("überspringen", "skip", "nein", "no", "behalten"):
|
||
await self._post_message_with_retry(operator_room_id, "👍 Catch-All bleibt unverändert.")
|
||
logger.info("[rocketchat] Catch-All unverändert")
|
||
else:
|
||
await self._post_message_with_retry(operator_room_id, "❌ Bitte eine Raumnummer (1, 2, …) oder 'überspringen' eingeben.")
|
||
return # onboarding_active bleibt True
|
||
# Catch-All-Frage beantwortet → Butler-Mode-Frage stellen
|
||
# Fix C v7: Nach Catch-All-Dialog folgt Butler-Mode-Frage
|
||
self._onboarding_state = {
|
||
"phase": "butler_mode",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
# F8: State Machine — AWAITING_ROOM → AWAITING_INTENT
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_room()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# Butler-Mode-Frage senden
|
||
_build = self._get_build_custom_buttons()
|
||
butler_text = (
|
||
"**Schritt 2 von 4: Butler-Mode**\n\n"
|
||
"Möchtest du, dass ich bei themenfremden Nachrichten vorschlage "
|
||
"den Raum zu wechseln (Butler-Prinzip)?\n\n"
|
||
"🤖 **Kognitiv** — Ich erkenne selbstständig thematische Bezüge "
|
||
"und frage natürlich nach. (Empfohlen für leistungsstarke Cloud-Modelle)\n"
|
||
"📋 **Klassisch** — Ich folge festen Regeln: Bei sicheren Zuordnungen "
|
||
"wechsle ich automatisch, bei unsicheren frage ich nach. "
|
||
"(Empfohlen für lokale Modelle)\n"
|
||
"🔇 **Aus** — Kein Butler, ich bleibe immer im Ursprungsraum.\n\n"
|
||
"👉 Klicke auf einen Button:"
|
||
)
|
||
butler_buttons = _build(
|
||
["🤖", "📋", "🔇"],
|
||
prefix="BUTLER",
|
||
style="primary",
|
||
)
|
||
butler_attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Butler-Modus wählen",
|
||
"actions": butler_buttons,
|
||
}]
|
||
await self._post_message_with_retry(
|
||
operator_room_id, butler_text, attachments=butler_attachments
|
||
)
|
||
logger.info("[rocketchat] Fix C v7: Butler-Mode-Frage gesendet")
|
||
return
|
||
|
||
# ── Phase: butler_mode (Fix C v7) ──────────────────────────────
|
||
if state.get("phase") == "butler_mode":
|
||
single_line = text.strip()
|
||
if single_line.startswith("BUTLER::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
if "Kognitiv" in choice or "🤖" in choice:
|
||
mode = "cognitive"
|
||
elif "Klassisch" in choice or "📋" in choice:
|
||
mode = "strict"
|
||
elif "Aus" in choice or "🔇" in choice:
|
||
mode = "off"
|
||
else:
|
||
mode = "cognitive" # Default
|
||
|
||
# Speichere in room-map.json
|
||
if self.archivar is not None:
|
||
self.archivar._room_map.set_butler_mode(mode)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
mode_labels = {
|
||
"cognitive": "🤖 Kognitiv",
|
||
"strict": "📋 Klassisch",
|
||
"off": "🔇 Aus",
|
||
}
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"👍 Butler-Modus: {mode_labels.get(mode, mode)}"
|
||
)
|
||
logger.info("[rocketchat] Fix C v7: Butler-Mode gesetzt auf '%s'", mode)
|
||
else:
|
||
# Text-Antwort (Fallback)
|
||
t = single_line.lower()
|
||
if "kognitiv" in t or "🤖" in t:
|
||
mode = "cognitive"
|
||
elif "klassisch" in t or "📋" in t:
|
||
mode = "strict"
|
||
elif "aus" in t or "🔇" in t:
|
||
mode = "off"
|
||
else:
|
||
mode = "cognitive"
|
||
|
||
if self.archivar is not None:
|
||
self.archivar._room_map.set_butler_mode(mode)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
mode_labels = {
|
||
"cognitive": "🤖 Kognitiv",
|
||
"strict": "📋 Klassisch",
|
||
"off": "🔇 Aus",
|
||
}
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"👍 Butler-Modus: {mode_labels.get(mode, mode)}"
|
||
)
|
||
logger.info("[rocketchat] Fix C v7: Butler-Mode gesetzt auf '%s' (Text)", mode)
|
||
|
||
# Thema 3: FAKT-Speicherort-Dialog statt direktem Abschluss
|
||
self._onboarding_state = {
|
||
"phase": "fakt_store",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
# F8: State Machine — AWAITING_INTENT → AWAITING_TEST
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_intent()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# FAKT-Speicherort-Frage senden
|
||
_build = self._get_build_custom_buttons()
|
||
fakt_text = (
|
||
"**Schritt 3 von 4: FAKT-Speicherort**\n\n"
|
||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||
)
|
||
# P1-10(b): 3 Attachments: [1️⃣][2️⃣][3️⃣] | [4️⃣] | [⏭️ Skip]
|
||
fakt_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "FAKT-Speicherort wählen",
|
||
"actions": _build(
|
||
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
),
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": _build(
|
||
["4️⃣ Keine"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
),
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": _build(
|
||
["⏭️ Skip"],
|
||
prefix="FAKT",
|
||
style="default",
|
||
),
|
||
},
|
||
]
|
||
await self._post_message_with_retry(
|
||
operator_room_id, fakt_text, attachments=fakt_attachments
|
||
)
|
||
logger.info("[rocketchat] Thema 3: FAKT-Speicherort-Frage gesendet")
|
||
return
|
||
|
||
# ── Thema 3: FAKT-Speicherort-Dialog ─────────────────────────────
|
||
if state.get("phase") == "fakt_store":
|
||
single_line = text.strip()
|
||
fakt_sub_phase = state.get("fakt_sub_phase", "")
|
||
|
||
# Sub-Phase: User gibt Pfad ein (für Option 2 oder 3)
|
||
if fakt_sub_phase in ("new_path", "existing_path"):
|
||
from .archivar.onboarding import (
|
||
validate_fact_store_path,
|
||
create_and_verify_fact_store,
|
||
verify_existing_fact_store,
|
||
)
|
||
from datetime import datetime, timezone
|
||
|
||
validation = validate_fact_store_path(single_line)
|
||
if not validation["valid"]:
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"❌ {validation['error']}\n\nBitte gib einen gültigen absoluten Pfad ein:"
|
||
)
|
||
return
|
||
|
||
norm_path = validation["normalized_path"]
|
||
|
||
if fakt_sub_phase == "new_path":
|
||
result = create_and_verify_fact_store(norm_path)
|
||
else:
|
||
result = verify_existing_fact_store(norm_path)
|
||
|
||
if not result["success"]:
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"❌ {result['error']}\n\nBitte versuche einen anderen Pfad:"
|
||
)
|
||
return
|
||
|
||
# Erfolg: Persistiere in room-map.json
|
||
strategy = "manual"
|
||
now_iso = datetime.now(timezone.utc).isoformat()
|
||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path as PathLib
|
||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
# Aktualisiere doc_store mit neuem Pfad
|
||
if self.archivar._doc_store is not None:
|
||
self.archivar._doc_store.set_base_dir(PathLib(norm_path))
|
||
else:
|
||
from .archivar.doc_store import DocumentationStore
|
||
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(norm_path))
|
||
|
||
logger.info(
|
||
"[rocketchat] FAKT-Store: strategy='manual', path=%s, created_at=%s",
|
||
norm_path, now_iso,
|
||
)
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"✅ FAKT-Speicherort: `{norm_path}`\n"
|
||
f"Strategie: {'Neues Verzeichnis angelegt' if fakt_sub_phase == 'new_path' else 'Bestehendes Verzeichnis referenziert'}\n"
|
||
f"Änderbar mit `::setfakt`."
|
||
)
|
||
|
||
# Onboarding abschließen
|
||
await self._complete_onboarding(operator_room_id)
|
||
return
|
||
|
||
# Haupt-Phase: Button-Klick oder Text-Antwort
|
||
if single_line.startswith("FAKT::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
else:
|
||
choice = single_line
|
||
|
||
from .archivar.onboarding import (
|
||
validate_fact_store_path,
|
||
create_and_verify_fact_store,
|
||
get_default_fact_store_path,
|
||
)
|
||
from datetime import datetime, timezone
|
||
|
||
# Option 1: Standard
|
||
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
||
default_path = get_default_fact_store_path()
|
||
result = create_and_verify_fact_store(default_path)
|
||
if not result["success"]:
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"❌ Standard-Pfad konnte nicht erstellt werden: {result['error']}"
|
||
)
|
||
return
|
||
|
||
strategy = "auto"
|
||
now_iso = datetime.now(timezone.utc).isoformat()
|
||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path as PathLib
|
||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
# Aktualisiere doc_store
|
||
if self.archivar._doc_store is not None:
|
||
self.archivar._doc_store.set_base_dir(PathLib(default_path))
|
||
else:
|
||
from .archivar.doc_store import DocumentationStore
|
||
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(default_path))
|
||
|
||
logger.info(
|
||
"[rocketchat] FAKT-Store: strategy='auto', path=%s, created_at=%s",
|
||
default_path, now_iso,
|
||
)
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
f"✅ FAKT-Speicherort: `{default_path}` (Standard)\n"
|
||
f"Änderbar mit `::setfakt`."
|
||
)
|
||
await self._complete_onboarding(operator_room_id)
|
||
return
|
||
|
||
# Option 2: Neuer Ort
|
||
elif "Neu" in choice or "2️⃣" in choice or choice == "2":
|
||
self._onboarding_state["fakt_sub_phase"] = "new_path"
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
"📁 Bitte gib den absoluten Pfad für den neuen FAKT-Speicherort ein "
|
||
"(z.B. `/home/bernd/meine-notizen`):"
|
||
)
|
||
return
|
||
|
||
# Option 3: Bestehender Ort
|
||
elif "Vorhanden" in choice or "3️⃣" in choice or choice == "3":
|
||
self._onboarding_state["fakt_sub_phase"] = "existing_path"
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
"📁 Bitte gib den absoluten Pfad zum bestehenden FAKT-Speicherort ein "
|
||
"(z.B. `/data/Wissensdatenbank`):"
|
||
)
|
||
return
|
||
|
||
# Option 4: Keine Sammlung
|
||
elif "Keine" in choice or "4️⃣" in choice or choice == "4":
|
||
strategy = "none"
|
||
now_iso = datetime.now(timezone.utc).isoformat()
|
||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path as PathLib
|
||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
# Deaktiviere doc_store
|
||
self.archivar._doc_store = None
|
||
|
||
logger.info(
|
||
"[rocketchat] FAKT-Store: strategy='none', created_at=%s",
|
||
now_iso,
|
||
)
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
"✅ FAKT-Speicherort: **Keine Wissensammlung**\n"
|
||
"FAKT-Nachrichten werden im Chat beantwortet, aber nicht persistiert.\n"
|
||
"Änderbar mit `::setfakt`."
|
||
)
|
||
await self._complete_onboarding(operator_room_id)
|
||
return
|
||
|
||
else:
|
||
await self._post_message_with_retry(
|
||
operator_room_id,
|
||
"❌ Bitte wähle eine Option: 1 (Standard), 2 (Neuer Ort), 3 (Bestehender Ort) oder 4 (Keine Sammlung)."
|
||
)
|
||
return
|
||
|
||
# ── F8 UX: Review-Flow Phasen ──────────────────────────────────
|
||
# review_room: Room Map Review (Schritt 1)
|
||
if state.get("phase") == "review_room":
|
||
from archivar.onboarding_review import (
|
||
handle_review_room_message,
|
||
render_review_room_add_new,
|
||
SUB_PHASE_ADD_NEW,
|
||
REVIEW_ROOM_SKIP,
|
||
)
|
||
|
||
result = handle_review_room_message(
|
||
text,
|
||
state,
|
||
self.archivar._room_map,
|
||
self.archivar,
|
||
self._get_build_custom_buttons(),
|
||
self._post_message_with_retry,
|
||
)
|
||
|
||
# State wurde in-place modifiziert → persistieren
|
||
if result["handled"] and self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(state)
|
||
|
||
if result["action"] == "button_dispatched":
|
||
# ── O2: SUB_PHASE_ADD_NEW → REST-Raumliste laden ──────
|
||
if state.get("sub_phase") == SUB_PHASE_ADD_NEW:
|
||
available_rooms = await self._fetch_available_rooms_for_add_new()
|
||
state["available_rooms"] = available_rooms
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(state)
|
||
add_text, add_attachments = render_review_room_add_new(
|
||
available_rooms,
|
||
self._get_build_custom_buttons(),
|
||
)
|
||
await self._post_message_with_retry(
|
||
operator_room_id, add_text,
|
||
attachments=add_attachments if add_attachments else None,
|
||
)
|
||
return
|
||
|
||
if result["response_text"]:
|
||
await self._post_message_with_retry(
|
||
operator_room_id, result["response_text"],
|
||
attachments=result["response_attachments"] if result["response_attachments"] else None
|
||
)
|
||
return
|
||
|
||
elif result["action"] == "text_input_processed":
|
||
if result["response_text"]:
|
||
await self._post_message_with_retry(
|
||
operator_room_id, result["response_text"],
|
||
attachments=result["response_attachments"] if result["response_attachments"] else None
|
||
)
|
||
return
|
||
|
||
elif result["action"] == "rejected":
|
||
await self._post_message_with_retry(
|
||
operator_room_id, result["response_text"]
|
||
)
|
||
return
|
||
|
||
elif result["action"] == "skip_to_step2":
|
||
# Weiter zu Schritt 2: Butler-Mode Review
|
||
from archivar.onboarding_review import build_review_state
|
||
self._onboarding_state = build_review_state(
|
||
phase="review_butler",
|
||
operator_room_id=operator_room_id,
|
||
)
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_room()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# Butler-Mode Review
|
||
current_mode = self.archivar._room_map.butler_mode if self.archivar._room_map else "cognitive"
|
||
mode_labels = {"cognitive": "🤖 Kognitiv", "strict": "📋 Klassisch", "off": "🔇 Aus"}
|
||
current_label = mode_labels.get(current_mode, current_mode)
|
||
_build = self._get_build_custom_buttons()
|
||
butler_text = (
|
||
f"**Schritt 2 von 4: Butler-Mode Review**\n\n"
|
||
f"🔧 Butler-Mode aktuell: **{current_label}**\n\n"
|
||
f"Möchtest du den Butler-Mode ändern oder beibehalten?\n\n"
|
||
f"👉 Klicke auf einen Button:"
|
||
)
|
||
butler_buttons_row1 = _build(
|
||
["✏️ Ändern"],
|
||
prefix="REVIEW_BUTLER",
|
||
style="primary",
|
||
)
|
||
butler_buttons_row2 = _build(
|
||
["⏭️ Beibehalten"],
|
||
prefix="REVIEW_BUTLER",
|
||
style="default",
|
||
)
|
||
butler_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "Butler-Mode Review",
|
||
"actions": butler_buttons_row1,
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": butler_buttons_row2,
|
||
},
|
||
]
|
||
await self._post_message_with_retry(
|
||
operator_room_id, butler_text, attachments=butler_attachments
|
||
)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow — Schritt 2 (Butler-Mode)")
|
||
return
|
||
|
||
# review_butler: Butler-Mode Review (Schritt 2)
|
||
if state.get("phase") == "review_butler":
|
||
single_line = text.strip()
|
||
if single_line.startswith("REVIEW_BUTLER::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
else:
|
||
choice = single_line
|
||
|
||
if "Beibehalten" in choice or "⏭️" in choice or choice.lower() in ("beibehalten", "skip", "überspringen"):
|
||
# Weiter zu Schritt 3: FAKT-Speicherort Review
|
||
self._onboarding_state = {
|
||
"phase": "review_fakt",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_intent()
|
||
logger.info("[rocketchat] F8 UX: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# FAKT-Speicherort Review
|
||
strategy = self.archivar._room_map.fact_store_strategy if self.archivar._room_map else "auto"
|
||
fakt_path = str(self.archivar._room_map.fact_store_path) if self.archivar._room_map else "~/.hermes/wissenssammlung"
|
||
strategy_labels = {
|
||
"auto": f"Standard ({fakt_path})",
|
||
"manual": f"Manuell ({fakt_path})",
|
||
"none": "Keine Sammlung",
|
||
}
|
||
current_label = strategy_labels.get(strategy, strategy)
|
||
_build = self._get_build_custom_buttons()
|
||
fakt_text = (
|
||
f"**Schritt 3 von 4: FAKT-Speicherort Review**\n\n"
|
||
f"📁 FAKT-Speicherort aktuell: **{current_label}**\n\n"
|
||
f"Möchtest du den FAKT-Speicherort ändern oder beibehalten?\n\n"
|
||
f"👉 Klicke auf einen Button:"
|
||
)
|
||
# Reihe 1: Ändern-Button
|
||
fakt_buttons_row1 = _build(
|
||
["✏️ Ändern"],
|
||
prefix="REVIEW_FAKT",
|
||
style="primary",
|
||
)
|
||
# Reihe 2: Beibehalten (Sonderschaltfläche)
|
||
fakt_buttons_row2 = _build(
|
||
["⏭️ Beibehalten"],
|
||
prefix="REVIEW_FAKT",
|
||
style="default",
|
||
)
|
||
fakt_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "FAKT-Speicherort Review",
|
||
"actions": fakt_buttons_row1,
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": fakt_buttons_row2,
|
||
},
|
||
]
|
||
await self._post_message_with_retry(
|
||
operator_room_id, fakt_text, attachments=fakt_attachments
|
||
)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow — Schritt 3 (FAKT-Speicherort)")
|
||
return
|
||
|
||
elif "Ändern" in choice or "✏️" in choice or choice.lower() in ("ändern", "anpassen"):
|
||
# Zeige Butler-Mode Optionen
|
||
_build = self._get_build_custom_buttons()
|
||
butler_text = (
|
||
"**Butler-Mode ändern**\n\n"
|
||
"🤖 **Kognitiv** — Ich erkenne selbstständig thematische Bezüge "
|
||
"und frage natürlich nach. (Empfohlen für leistungsstarke Cloud-Modelle)\n"
|
||
"📋 **Klassisch** — Ich folge festen Regeln: Bei sicheren Zuordnungen "
|
||
"wechsle ich automatisch, bei unsicheren frage ich nach. "
|
||
"(Empfohlen für lokale Modelle)\n"
|
||
"🔇 **Aus** — Kein Butler, ich bleibe immer im Ursprungsraum.\n\n"
|
||
"👉 Klicke auf einen Button:"
|
||
)
|
||
butler_buttons = _build(
|
||
["🤖", "📋", "🔇"],
|
||
prefix="BUTLER",
|
||
style="primary",
|
||
)
|
||
butler_back = _build(
|
||
["↩️ Zurück"],
|
||
prefix="REVIEW_BUTLER",
|
||
style="default",
|
||
)
|
||
butler_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "Butler-Modus wählen",
|
||
"actions": butler_buttons,
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": butler_back,
|
||
},
|
||
]
|
||
# Wechsle in butler_mode Phase (existierende Logik)
|
||
self._onboarding_state = {
|
||
"phase": "butler_mode",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(
|
||
operator_room_id, butler_text, attachments=butler_attachments
|
||
)
|
||
return
|
||
else:
|
||
from archivar.onboarding_review import _reject_free_text
|
||
await _reject_free_text(operator_room_id, self._post_message_with_retry)
|
||
return
|
||
|
||
# review_fakt: FAKT-Speicherort Review (Schritt 3)
|
||
if state.get("phase") == "review_fakt":
|
||
single_line = text.strip()
|
||
if single_line.startswith("REVIEW_FAKT::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
else:
|
||
choice = single_line
|
||
|
||
if "Beibehalten" in choice or "⏭️" in choice or choice.lower() in ("beibehalten", "skip", "überspringen"):
|
||
# Onboarding abschließen → ACTIVE
|
||
await self._complete_onboarding(operator_room_id)
|
||
# Hilfeseite anzeigen
|
||
from archivar.inline_commands import build_help_text
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
await self._post_message_with_retry(operator_room_id, help_text)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow abgeschlossen — ACTIVE")
|
||
return
|
||
|
||
elif "Ändern" in choice or "✏️" in choice or choice.lower() in ("ändern", "anpassen"):
|
||
# Zeige FAKT-Speicherort Optionen
|
||
_build = self._get_build_custom_buttons()
|
||
fakt_text = (
|
||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||
)
|
||
fakt_buttons_row1 = _build(
|
||
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
)
|
||
fakt_buttons_row2 = _build(
|
||
["4️⃣ Keine", "⏭️ Skip"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
)
|
||
fakt_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "FAKT-Speicherort wählen",
|
||
"actions": fakt_buttons_row1,
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": fakt_buttons_row2,
|
||
},
|
||
]
|
||
# Wechsle in fakt_store Phase (existierende Logik)
|
||
self._onboarding_state = {
|
||
"phase": "fakt_store",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(
|
||
operator_room_id, fakt_text, attachments=fakt_attachments
|
||
)
|
||
return
|
||
else:
|
||
from archivar.onboarding_review import _reject_free_text
|
||
await _reject_free_text(operator_room_id, self._post_message_with_retry)
|
||
return
|
||
|
||
# ── V8.4.2: Keyword-Konflikt-Auflösung ──────────────────────────
|
||
conflict_phase = state.get("conflict_phase", "")
|
||
if conflict_phase in ("keywords_100", "keywords_context"):
|
||
single_line = text.strip()
|
||
|
||
# Button-Klick: CONFLICT:<rid>::<action>
|
||
if single_line.startswith("CONFLICT:"):
|
||
parts = single_line.split("::", 1)
|
||
action = parts[1] if len(parts) > 1 else ""
|
||
|
||
if "keep" in action or "Trotzdem" in action or "1️⃣" in action:
|
||
# Trotzdem verwenden — Keyword bleibt, Warnung im Log
|
||
conflict_list = state.get("conflict_list", [])
|
||
for c in conflict_list:
|
||
logger.info(
|
||
"Onboarding-Conflict: keyword \"%s\" already in %s as %s-keyword — user chose: keep anyway",
|
||
c["keyword"], c["room_name"], c["existing_type"],
|
||
)
|
||
# Weiter mit nächster Frage
|
||
if conflict_phase == "keywords_100":
|
||
state["current_question"] = 3
|
||
else:
|
||
# keywords_context → DM oder Frage 4
|
||
room = state["missing_rooms"][state["current_room_index"]]
|
||
is_dm = room.get("is_dm", False)
|
||
if is_dm:
|
||
# DM: direkt speichern
|
||
rid = room["room_id"]
|
||
data = state["collected_data"].get(rid, {})
|
||
data["catch_all"] = True
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid,
|
||
name=room_name,
|
||
theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []),
|
||
catch_all=True,
|
||
)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)",
|
||
room_name, data["theme"])
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet: 🎯 Catch-All\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
await self._onboarding_next_room()
|
||
else:
|
||
state["current_question"] = 4
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
# Cleanup conflict state
|
||
state.pop("conflict_phase", None)
|
||
state.pop("conflict_keywords", None)
|
||
state.pop("conflict_list", None)
|
||
return
|
||
|
||
if "change" in action or "Anderes" in action or "2️⃣" in action:
|
||
# Anderes Keyword — Nutzer soll neu eingeben
|
||
conflict_list = state.get("conflict_list", [])
|
||
for c in conflict_list:
|
||
logger.info(
|
||
"Onboarding-Conflict: keyword \"%s\" already in %s as %s-keyword — user chose: change",
|
||
c["keyword"], c["room_name"], c["existing_type"],
|
||
)
|
||
# Setze Sub-Phase: warte auf neue Keyword-Eingabe
|
||
state["conflict_sub_phase"] = "reenter"
|
||
conflict_kws = [c["keyword"] for c in conflict_list]
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"👍 Verstanden. Bitte gib neue Keywords ein (kommagetrennt) — "
|
||
f"die folgenden sind bereits vergeben: {', '.join(conflict_kws)}")
|
||
return
|
||
|
||
# Sub-Phase: Nutzer gibt neue Keywords ein nach "Anderes Keyword"
|
||
if state.get("conflict_sub_phase") == "reenter":
|
||
raw = single_line
|
||
if raw.lower() in ("keine", "none", "-", ""):
|
||
new_kws = []
|
||
elif "," in raw:
|
||
new_kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||
else:
|
||
new_kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||
new_kws = new_kws[:10]
|
||
|
||
# Erneut auf Konflikte prüfen
|
||
if new_kws and self.archivar is not None:
|
||
rid = state["missing_rooms"][state["current_room_index"]]["room_id"]
|
||
kw_type = "100" if conflict_phase == "keywords_100" else "context"
|
||
conflicts = self.archivar._room_map.check_keyword_conflicts(
|
||
keywords=new_kws,
|
||
exclude_room_id=rid,
|
||
keyword_type=kw_type,
|
||
)
|
||
if kw_type == "100":
|
||
relevant = [c for c in conflicts if c["conflict_type"] in ("CRITICAL", "WARNING")]
|
||
else:
|
||
relevant = [c for c in conflicts if c["conflict_type"] == "INFO"]
|
||
if relevant:
|
||
state["conflict_keywords"] = new_kws
|
||
state["conflict_list"] = relevant
|
||
await self._ask_keyword_conflict_resolution(
|
||
operator_room_id, relevant,
|
||
"100%" if conflict_phase == "keywords_100" else "Kontext",
|
||
)
|
||
return
|
||
|
||
# Keine Konflikte mehr → speichern und weitermachen
|
||
rid = state["missing_rooms"][state["current_room_index"]]["room_id"]
|
||
data = state["collected_data"].get(rid, {})
|
||
if conflict_phase == "keywords_100":
|
||
data["keywords_100"] = new_kws
|
||
state["current_question"] = 3
|
||
else:
|
||
data["keywords_context"] = new_kws
|
||
room = state["missing_rooms"][state["current_room_index"]]
|
||
is_dm = room.get("is_dm", False)
|
||
if is_dm:
|
||
data["catch_all"] = True
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid,
|
||
name=room_name,
|
||
theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []),
|
||
catch_all=True,
|
||
)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)",
|
||
room_name, data["theme"])
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet: 🎯 Catch-All\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
state.pop("conflict_phase", None)
|
||
state.pop("conflict_keywords", None)
|
||
state.pop("conflict_list", None)
|
||
state.pop("conflict_sub_phase", None)
|
||
await self._onboarding_next_room()
|
||
return
|
||
else:
|
||
state["current_question"] = 4
|
||
state.pop("conflict_phase", None)
|
||
state.pop("conflict_keywords", None)
|
||
state.pop("conflict_list", None)
|
||
state.pop("conflict_sub_phase", None)
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# ── Modus 1: Button-Klick (ONBOARD:<room_id>::<action>) ──────────
|
||
if text.startswith("ONBOARD:") and "::" in text:
|
||
prefix_part, action = text.split("::", 1)
|
||
action = action.strip()
|
||
|
||
# Globale Aktionen (kein room_id): ONBOARD::⏭️ Überspringen, ONBOARD::⏰ Später
|
||
if prefix_part == "ONBOARD":
|
||
if "⏭️" in action or "Überspringen" in action:
|
||
# Alle verbleibenden Räume überspringen
|
||
missing = state["missing_rooms"]
|
||
for room in missing:
|
||
rid = room["room_id"]
|
||
if rid not in state["skipped_rooms"]:
|
||
state["skipped_rooms"].append(rid)
|
||
logger.info("[rocketchat] Onboarding: alle Räume übersprungen (skip_all)")
|
||
await self._onboarding_next_room()
|
||
return
|
||
|
||
if "⏰" in action or "Später" in action:
|
||
# Onboarding pausieren — State persistieren für Wiederaufnahme
|
||
# A1b: Lock für alle Räume freigeben
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self._onboarding_state = {}
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||
logger.info("[rocketchat] Onboarding pausiert (later)")
|
||
return
|
||
|
||
# Wenn ein Interview läuft (current_question >= 1), ist ein ONBOARD-Button
|
||
# eine Antwort auf eine Frage (z.B. ✅ Ja / ❌ Nein bei Frage 4),
|
||
# KEINE Raum-Auswahl. An Text-Antwort-Logik durchreichen.
|
||
current_q = state.get("current_question", 0)
|
||
if current_q >= 1:
|
||
# Button-Antwort als Text behandeln — an Modus 2 durchreichen
|
||
pass # fällt durch zu Modus 2 (Text-Antwort)
|
||
else:
|
||
# Raum-spezifische Aktionen: ONBOARD:<room_id>::<action>
|
||
target_room_id = prefix_part.split(":", 1)[1]
|
||
|
||
if "Überspringen" in action or "⏭️" in action:
|
||
# Einzelnen Raum überspringen
|
||
state["skipped_rooms"].append(target_room_id)
|
||
logger.info("[rocketchat] Onboarding: Raum %s übersprungen", target_room_id[:8])
|
||
await self._onboarding_next_room()
|
||
return
|
||
|
||
if "Später" in action or "⏰" in action:
|
||
# Onboarding pausieren — State persistieren
|
||
# A1b: Lock für alle Räume freigeben
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self._onboarding_state = {}
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||
logger.info("[rocketchat] Onboarding pausiert (Später)")
|
||
return
|
||
|
||
# "Projektraum einrichten" — Interview starten
|
||
missing = state["missing_rooms"]
|
||
for i, room in enumerate(missing):
|
||
if room["room_id"] == target_room_id:
|
||
state["current_room_index"] = i
|
||
state["current_question"] = 1
|
||
state["collected_data"][target_room_id] = {
|
||
"theme": "",
|
||
"keywords_100": [],
|
||
"keywords_context": [],
|
||
"catch_all": False,
|
||
}
|
||
break
|
||
|
||
if state["current_room_index"] >= 0:
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# ── Modus 2: Text-Antwort auf Interview-Frage ────────────────────
|
||
current_idx = state.get("current_room_index", -1)
|
||
if current_idx < 0:
|
||
return # Kein aktives Interview
|
||
|
||
current_q = state.get("current_question", 0)
|
||
if current_q < 1 or current_q > 4:
|
||
return # Keine aktive Frage
|
||
|
||
room = state["missing_rooms"][current_idx]
|
||
rid = room["room_id"]
|
||
data = state["collected_data"].get(rid, {})
|
||
|
||
# Frage 1: theme
|
||
if current_q == 1:
|
||
theme = text.strip()
|
||
if not theme or len(theme) < 3:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"❌ Bitte gib eine kurze Beschreibung ein (mindestens 3 Zeichen).")
|
||
return
|
||
data["theme"] = theme
|
||
state["current_question"] = 2
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# Frage 2: keywords_100
|
||
if current_q == 2:
|
||
raw = text.strip()
|
||
if raw.lower() in ("keine", "none", "-", ""):
|
||
data["keywords_100"] = []
|
||
else:
|
||
# Akzeptiere komma-getrennt oder leerzeichen-getrennt
|
||
if "," in raw:
|
||
kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||
else:
|
||
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||
data["keywords_100"] = kws[:10]
|
||
|
||
# V8.4.2: Keyword-Konflikt-Prüfung für 100%-Keywords
|
||
if data["keywords_100"] and self.archivar is not None:
|
||
conflicts = self.archivar._room_map.check_keyword_conflicts(
|
||
keywords=data["keywords_100"],
|
||
exclude_room_id=rid,
|
||
keyword_type="100",
|
||
)
|
||
# Nur CRITICAL und WARNING sind relevant (100% vs 100% oder 100% vs context)
|
||
relevant = [c for c in conflicts if c["conflict_type"] in ("CRITICAL", "WARNING")]
|
||
if relevant:
|
||
state["conflict_phase"] = "keywords_100"
|
||
state["conflict_keywords"] = data["keywords_100"]
|
||
state["conflict_list"] = relevant
|
||
await self._ask_keyword_conflict_resolution(operator_room_id, relevant, "100%")
|
||
return
|
||
|
||
state["current_question"] = 3
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# Frage 3: keywords_context
|
||
if current_q == 3:
|
||
raw = text.strip()
|
||
if raw.lower() in ("keine", "none", "-", ""):
|
||
data["keywords_context"] = []
|
||
else:
|
||
if "," in raw:
|
||
kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||
else:
|
||
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||
data["keywords_context"] = kws[:10]
|
||
|
||
# V8.4.2: Keyword-Konflikt-Prüfung für Kontext-Keywords
|
||
if data["keywords_context"] and self.archivar is not None:
|
||
conflicts = self.archivar._room_map.check_keyword_conflicts(
|
||
keywords=data["keywords_context"],
|
||
exclude_room_id=rid,
|
||
keyword_type="context",
|
||
)
|
||
# Nur INFO ist relevant (context vs 100% — Butler fragt im anderen Raum)
|
||
# OK (context vs context) wird ignoriert
|
||
relevant = [c for c in conflicts if c["conflict_type"] == "INFO"]
|
||
if relevant:
|
||
state["conflict_phase"] = "keywords_context"
|
||
state["conflict_keywords"] = data["keywords_context"]
|
||
state["conflict_list"] = relevant
|
||
await self._ask_keyword_conflict_resolution(operator_room_id, relevant, "Kontext")
|
||
return
|
||
|
||
# DM: Frage 4 (catch_all) überspringen — DM ist immer Catch-All
|
||
is_dm = room.get("is_dm", False)
|
||
if is_dm:
|
||
data["catch_all"] = True
|
||
# Raum zur Map hinzufügen
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid,
|
||
name=room_name,
|
||
theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []),
|
||
catch_all=True,
|
||
)
|
||
|
||
# Speichern + reload
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)",
|
||
room_name, data["theme"])
|
||
|
||
# Feedback an Operator
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet: 🎯 Catch-All\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
|
||
# Nächster Raum oder Abschluss
|
||
await self._onboarding_next_room()
|
||
return
|
||
|
||
state["current_question"] = 4
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# Frage 4: catch_all
|
||
if current_q == 4:
|
||
raw = text.strip()
|
||
# Button-Klick erkennen: ONBOARD:<rid>::✅ Ja / ❌ Nein
|
||
if raw.startswith("ONBOARD:"):
|
||
button_label = raw.split("::", 1)[1] if "::" in raw else ""
|
||
answer = button_label.lower()
|
||
else:
|
||
answer = raw.lower()
|
||
is_catch_all = answer in ("ja", "yes", "j", "y", "1", "👍", "✅") or "✅" in answer or "ja" in answer
|
||
data["catch_all"] = is_catch_all
|
||
|
||
# Raum zur Map hinzufügen
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid,
|
||
name=room_name,
|
||
theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []),
|
||
catch_all=is_catch_all,
|
||
)
|
||
|
||
# Speichern + reload
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
logger.info("[rocketchat] Onboarding: Raum %s zur Map hinzugefügt (catch_all=%s)",
|
||
room_name, is_catch_all)
|
||
|
||
# Feedback an Operator
|
||
catch_marker = " 🎯 Catch-All" if is_catch_all else ""
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet:{catch_marker}\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
|
||
# Nächster Raum oder Abschluss
|
||
await self._onboarding_next_room()
|
||
return
|
||
|
||
async def _ask_keyword_conflict_resolution(
|
||
self, operator_room_id: str, conflicts: list, keyword_label: str
|
||
) -> None:
|
||
"""V8.4.2: Fragt den Operator bei Keyword-Konflikten um Klarstellung.
|
||
|
||
Args:
|
||
operator_room_id: DM-Raum-ID des Operators.
|
||
conflicts: Liste von Konflikten (aus check_keyword_conflicts).
|
||
keyword_label: "100%" oder "Kontext" für die Anzeige.
|
||
"""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
return
|
||
|
||
rid = state["missing_rooms"][state["current_room_index"]]["room_id"]
|
||
|
||
# Baue Konflikt-Beschreibung
|
||
conflict_lines = []
|
||
for c in conflicts:
|
||
ctype = c["conflict_type"]
|
||
if ctype == "CRITICAL":
|
||
severity = "🔴 KRITISCH"
|
||
explanation = "führt zu willkürlichem Routing"
|
||
elif ctype == "WARNING":
|
||
severity = "🟡 WARNUNG"
|
||
explanation = "Butler könnte fälschlich fragen"
|
||
elif ctype == "INFO":
|
||
severity = "🔵 INFO"
|
||
explanation = "Butler fragt im anderen Raum"
|
||
else:
|
||
severity = "⚪ OK"
|
||
explanation = "beide dürfen fragen"
|
||
|
||
conflict_lines.append(
|
||
f"• \"{c['keyword']}\" — bereits als {c['existing_type']}%-Keyword "
|
||
f"in {c['room_name']} ({severity}: {explanation})"
|
||
)
|
||
|
||
# V8.4.2.1: INFO-Konflikte sind reine Hinweise — keine Buttons
|
||
all_info = all(c["conflict_type"] == "INFO" for c in conflicts)
|
||
|
||
if all_info:
|
||
text = (
|
||
f"ℹ️ **Keyword-Hinweis** ({keyword_label}-Keywords):\n\n"
|
||
+ "\n".join(conflict_lines)
|
||
+ "\n\n💡 Der Butler wird im anderen Raum nachfragen. Keine Aktion nötig."
|
||
)
|
||
await self._post_message_with_retry(operator_room_id, text)
|
||
else:
|
||
text = (
|
||
f"⚠️ **Keyword-Konflikt erkannt** ({keyword_label}-Keywords):\n\n"
|
||
+ "\n".join(conflict_lines)
|
||
+ "\n\n👉 Möchtest Du die Keywords trotzdem verwenden oder andere wählen?"
|
||
)
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
buttons = _build(
|
||
["1️⃣ Trotzdem verwenden", "2️⃣ Anderes Keyword"],
|
||
prefix=f"CONFLICT:{rid}",
|
||
style="primary",
|
||
)
|
||
attachments = [{
|
||
"color": "#f5a623",
|
||
"title": "Keyword-Konflikt auflösen",
|
||
"actions": buttons,
|
||
}]
|
||
await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||
|
||
async def _ask_onboarding_question(self, operator_room_id: str) -> None:
|
||
"""Sendet die aktuelle Interview-Frage an den Operator."""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
return
|
||
|
||
current_idx = state.get("current_room_index", -1)
|
||
if current_idx < 0:
|
||
return
|
||
|
||
room = state["missing_rooms"][current_idx]
|
||
room_name = room["name"]
|
||
is_dm = room.get("is_dm", False)
|
||
current_q = state.get("current_question", 0)
|
||
|
||
if is_dm:
|
||
questions = {
|
||
1: f"**{room_name}** — Frage 1/3:\nWofür nutzt du diesen DM hauptsächlich? (z.B. Projektabsprachen, Team-Koordination)",
|
||
2: f"**{room_name}** — Frage 2/3:\nWelche Begriffe passen IMMER zu diesem DM? Bei diesen Wörtern weiß ich sofort: Das gehört hierher.\n"
|
||
f"(z.B. \"absprache\", \"planung\" — oder \"keine\" wenn keine)",
|
||
3: f"**{room_name}** — Frage 3/3:\nWelche Begriffe passen OFT zu diesem DM, aber nicht immer? Bei diesen Wörtern frage ich erst nach.\n"
|
||
f"(z.B. \"koordination\", \"termin\" — oder \"keine\" wenn keine)",
|
||
}
|
||
else:
|
||
questions = {
|
||
1: f"**{room_name}** — Frage 1/4:\nWorum geht es in diesem Raum? (z.B. Datenbanken, Web-Frontend, Projektplanung)",
|
||
2: f"**{room_name}** — Frage 2/4:\nWelche Begriffe passen IMMER zu diesem Raum? Bei diesen Wörtern weiß ich sofort: Das gehört hierher.\n"
|
||
f"(z.B. \"datenbank\", \"sql\", \"backup\" — oder \"keine\" wenn keine)",
|
||
3: f"**{room_name}** — Frage 3/4:\nWelche Begriffe passen OFT zu diesem Raum, aber nicht immer? Bei diesen Wörtern frage ich erst nach, ob sie hierher gehören.\n"
|
||
f"(z.B. \"migration\", \"performance\", \"index\" — oder \"keine\" wenn keine)",
|
||
4: f"**{room_name}** — Frage 4/4:\nSoll dieser Raum der Auffang-Raum (Catch-All) sein — also der Raum für Themen, die in keinen anderen passen? (Ja/Nein)",
|
||
}
|
||
|
||
text = questions.get(current_q, "")
|
||
if text:
|
||
# Frage 4 (Catch-All Ja/Nein): mit Buttons senden
|
||
if current_q == 4 and not is_dm:
|
||
_build = self._get_build_custom_buttons()
|
||
buttons = _build(
|
||
["✅ Ja", "❌ Nein"],
|
||
prefix=f"ONBOARD:{state['missing_rooms'][state['current_room_index']]['room_id']}"
|
||
)
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Catch-All für diesen Raum?",
|
||
"actions": buttons,
|
||
}]
|
||
await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||
else:
|
||
await self._post_message_with_retry(operator_room_id, text)
|
||
|
||
async def _onboarding_next_room(self) -> None:
|
||
"""Gehe zum nächsten fehlenden Raum oder schließe Onboarding ab."""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
return
|
||
|
||
operator_room_id = state.get("operator_room_id", "")
|
||
missing = state["missing_rooms"]
|
||
skipped = set(state.get("skipped_rooms", []))
|
||
collected = state.get("collected_data", {})
|
||
|
||
# Finde nächsten unbearbeiteten Raum
|
||
next_idx = state.get("current_room_index", -1) + 1
|
||
while next_idx < len(missing):
|
||
rid = missing[next_idx]["room_id"]
|
||
if rid not in skipped and rid not in collected:
|
||
break
|
||
next_idx += 1
|
||
|
||
if next_idx < len(missing):
|
||
# Noch Räume übrig — zurück zur Auswahl
|
||
state["current_room_index"] = -1
|
||
state["current_question"] = 0
|
||
|
||
remaining = []
|
||
for i in range(next_idx, len(missing)):
|
||
rid = missing[i]["room_id"]
|
||
if rid not in skipped and rid not in collected:
|
||
remaining.append(missing[i])
|
||
|
||
if remaining:
|
||
lines = [f"📋 Noch {len(remaining)} Raum/Räume übrig:",
|
||
""]
|
||
for i, room in enumerate(remaining, 1):
|
||
lines.append(f"{i}. {room['name'].lstrip('#')}")
|
||
lines.append("")
|
||
lines.append("⏭️ = Überspringen ⏰ = Später")
|
||
lines.append("")
|
||
lines.append("👉 Klicke auf eine Nummer, um den Raum einzurichten:")
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||
buttons = []
|
||
for i, room in enumerate(remaining):
|
||
rid = room["room_id"]
|
||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||
prefix = f"ONBOARD:{rid}"
|
||
buttons.extend(_build(
|
||
[emoji],
|
||
prefix=prefix,
|
||
style="primary"
|
||
))
|
||
|
||
# Globale Buttons (style='default' = grau)
|
||
buttons.extend(_build(
|
||
["⏭️ Überspringen", "⏰ Später"],
|
||
prefix="ONBOARD"
|
||
))
|
||
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Weitere Räume einrichten?",
|
||
"actions": buttons,
|
||
}]
|
||
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
||
else:
|
||
await self._finish_onboarding(operator_room_id)
|
||
else:
|
||
# Alle Räume bearbeitet
|
||
await self._finish_onboarding(operator_room_id)
|
||
|
||
async def _finish_onboarding(self, operator_room_id: str) -> None:
|
||
"""Onboarding abschließen: Übersicht zeigen, Catch-All-Frage stellen."""
|
||
# NICHT onboarding_active=False setzen — wir warten noch auf Catch-All-Antwort
|
||
# Stattdessen: Phase wechseln zu "catch_all_change"
|
||
self._onboarding_state = {
|
||
"phase": "catch_all_change",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
# P1-4: Phase-Wechsel persistieren
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# B9: FAISS-Index nach Onboarding neu bauen
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
try:
|
||
if self.archivar._room_index is not None and self.archivar._room_index.is_built:
|
||
self.archivar._room_index.build_index()
|
||
self.archivar._room_index.save()
|
||
logger.info("[rocketchat] B9: FAISS-Index nach Onboarding neu gebaut (%d Vektoren)", self.archivar._room_index.size)
|
||
except Exception as e:
|
||
# B9 fix (c): Bei RoomIndexError den Index invalidieren, statt veralteten Index stehen zu lassen
|
||
from archivar.room_index import RoomIndexError
|
||
if isinstance(e, RoomIndexError):
|
||
self.archivar._room_index = None
|
||
logger.warning("[rocketchat] B9: FAISS-Index invalidiert nach RoomIndexError: %s", e)
|
||
else:
|
||
logger.warning("[rocketchat] B9: FAISS-Index-Rebuild fehlgeschlagen: %s", e)
|
||
|
||
# Baue nummerierte Raumliste (inkl. Operator-DM als Catch-All-Option)
|
||
all_rooms = []
|
||
dm_room_id = operator_room_id
|
||
dm_room_name = self._room_info.get(dm_room_id, {}).get("name", "DM")
|
||
dm_already_in_map = dm_room_id in self.archivar._room_map.rooms
|
||
|
||
for rid, entry in self.archivar._room_map.rooms.items():
|
||
if rid in self.archivar._room_map._excluded_room_ids:
|
||
continue
|
||
# Bug 6: DM-Raum mit echtem Namen anzeigen, nicht "Catch-All (legacy)"
|
||
if rid == dm_room_id:
|
||
all_rooms.append((rid, dm_room_name, True))
|
||
else:
|
||
all_rooms.append((rid, entry.name, entry.catch_all))
|
||
|
||
# DM-Raum immer als Option anbieten, auch wenn nicht in room_map
|
||
# (wird nachfolgend einsortiert)
|
||
if not dm_already_in_map:
|
||
all_rooms.append((dm_room_id, dm_room_name, True))
|
||
|
||
all_rooms.sort(key=lambda x: (not x[2], x[1]))
|
||
|
||
lines = ["✅ Alle Räume zur Map hinzugefügt.",
|
||
"",
|
||
"**Aktuelle Raum-Übersicht:**"]
|
||
for i, (rid, name, is_catch) in enumerate(all_rooms, 1):
|
||
if rid == dm_room_id:
|
||
marker = " 🎯 (aktuell)"
|
||
elif is_catch:
|
||
marker = " 🎯 (Catch-All)"
|
||
else:
|
||
marker = ""
|
||
lines.append(f"{i}. {name}{marker}")
|
||
lines.append("")
|
||
lines.append("Wenn es ein Thema geben sollte, das in keines der eingerichteten Räume passt — wo sollen wir dann darüber sprechen? Das ist der \"Auffang-Raum\" (Catch-All).")
|
||
lines.append("")
|
||
lines.append("⏭️ = Überspringen (aktuelle Auswahl behalten)")
|
||
lines.append("")
|
||
lines.append("👉 Klicke auf eine Nummer, um den Catch-All-Raum zu wählen:")
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||
buttons = []
|
||
for i, (rid, name, is_catch) in enumerate(all_rooms):
|
||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||
prefix = f"ONBOARD:{rid}"
|
||
buttons.extend(_build(
|
||
[emoji],
|
||
prefix=prefix,
|
||
style="primary"
|
||
))
|
||
# Globaler Überspringen-Button
|
||
buttons.extend(_build(
|
||
["⏭️ Überspringen"],
|
||
prefix="ONBOARD"
|
||
))
|
||
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Catch-All-Raum wählen",
|
||
"actions": buttons,
|
||
}]
|
||
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
||
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
||
|
||
async def _start_onboarding_review(self, operator_room_id: str) -> None:
|
||
"""F8 UX: Review-Flow wenn Room-Map bereits vollständig ist.
|
||
|
||
Statt direkt ACTIVE zu setzen, zeigt der Review-Flow bei jedem Schritt
|
||
die aktuellen Werte und fragt ob etwas geändert werden soll.
|
||
|
||
Schritt 1 (AWAITING_ROOM): Room Map Review
|
||
Schritt 2 (AWAITING_INTENT): Butler-Mode Review
|
||
Schritt 3 (AWAITING_TEST): FAKT-Speicherort Review
|
||
Schritt 4 (ACTIVE): Hilfeseite
|
||
"""
|
||
from archivar.onboarding_review import (
|
||
render_review_room_step,
|
||
build_review_state,
|
||
)
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
|
||
# Schritt 1: Room Map Review (neues strukturiertes Rendering)
|
||
review_text, review_attachments = render_review_room_step(
|
||
self.archivar._room_map,
|
||
operator_room_id,
|
||
_build,
|
||
)
|
||
|
||
self._onboarding_state = build_review_state(
|
||
phase="review_room",
|
||
operator_room_id=operator_room_id,
|
||
)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self.archivar._stats["onboarding_active"] = True
|
||
|
||
await self._post_message_with_retry(
|
||
operator_room_id, review_text, attachments=review_attachments
|
||
)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow gestartet — Schritt 1 (Room Map)")
|
||
|
||
async def _complete_onboarding(self, operator_room_id: str) -> None:
|
||
"""Thema 3: Onboarding final abschließen (nach FAKT-Speicherort-Dialog)."""
|
||
# A1b: Onboarding-Lock für alle onboardeten Räume freigeben
|
||
from archivar.onboarding import release_onboarding_lock
|
||
if self._onboarding_state:
|
||
missing = self._onboarding_state.get("missing_rooms", [])
|
||
for room in missing:
|
||
release_onboarding_lock(room["room_id"])
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
self._onboarding_state = {}
|
||
# ── V8.6: PresenceEngine — Onboarding end → online ──
|
||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||
if _has_presence:
|
||
self._presence_engine.set_onboarding_active(False)
|
||
self._presence_engine.update_presence()
|
||
# F8: State Machine — AWAITING_TEST → ACTIVE
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_test()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
# FIX E: Raum-Map Summary nach Onboarding aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach Onboarding aktualisiert (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit FAKT-Speicherort)")
|
||
|
||
@staticmethod
|
||
def _derive_keywords(room_name: str, theme: str) -> list:
|
||
"""Leitet Stichworte aus Raumname und Thema ab.
|
||
|
||
Regeln:
|
||
- Raumname ohne '#' und ohne Bindestriche → einzelne Teile als Keywords
|
||
- Erste 2-4 signifikante Wörter aus dem Thema (keine Stopwörter)
|
||
- Maximal 10 Keywords, keine Duplikate, alle lowercase
|
||
"""
|
||
STOP = {"der", "die", "das", "und", "oder", "zum", "zur", "des", "dem", "den",
|
||
"ein", "eine", "einen", "einem", "für", "mit", "auf", "an", "von",
|
||
"ist", "sind", "wird", "the", "and", "or", "for", "with", "of", "to"}
|
||
keywords = []
|
||
|
||
# Aus Raumname: #BAT-Team → ["bat", "team"]
|
||
name_clean = room_name.lstrip("#")
|
||
for part in name_clean.replace("-", " ").replace("_", " ").split():
|
||
kw = part.lower().strip(".,;:!?")
|
||
if kw and kw not in STOP:
|
||
keywords.append(kw)
|
||
|
||
# Aus Thema: erste signifikante Wörter
|
||
for word in theme.lower().replace(",", " ").split():
|
||
w = word.strip(".,;:!?")
|
||
if w and w not in STOP and w not in keywords:
|
||
keywords.append(w)
|
||
if len(keywords) >= 10:
|
||
break
|
||
|
||
return keywords[:10]
|
||
|
||
def _get_onboarding_room_list(self) -> list:
|
||
"""Erstellt eine nummerierte Liste aller Räume (ohne excluded), inkl. DM.
|
||
|
||
Returns list of (rid, name, is_current) tuples — gleiche Sortierung wie
|
||
_finish_onboarding, damit Nummerierung in beiden Listen identisch ist.
|
||
"""
|
||
rooms = []
|
||
dm_room_id = self._onboarding_state.get("operator_room_id", "")
|
||
dm_room_name = self._room_info.get(dm_room_id, {}).get("name", "DM")
|
||
dm_already_in_map = dm_room_id in self.archivar._room_map.rooms
|
||
|
||
for rid, entry in self.archivar._room_map.rooms.items():
|
||
if rid in self.archivar._room_map._excluded_room_ids:
|
||
continue
|
||
if rid == dm_room_id:
|
||
rooms.append((rid, dm_room_name, True))
|
||
else:
|
||
rooms.append((rid, entry.name, entry.catch_all))
|
||
|
||
# DM-Raum immer als Option anbieten, auch wenn nicht in room_map
|
||
# (wird nachfolgend einsortiert)
|
||
if not dm_already_in_map:
|
||
rooms.append((dm_room_id, dm_room_name, True))
|
||
|
||
# Gleiche Sortierung wie _finish_onboarding: Catch-All zuerst, dann alphabetisch
|
||
rooms.sort(key=lambda x: (not x[2], x[1]))
|
||
return rooms
|
||
|
||
async def _fetch_available_rooms_for_add_new(self) -> list:
|
||
"""O2: REST-Raumliste für 'Neuer Raum' laden und filtern.
|
||
|
||
Holt alle Räume via REST rooms.get, filtert Räume die bereits
|
||
in der Room-Map sind (inkl. excluded), und gibt eine Liste von
|
||
Dicts mit 'id' und 'name' zurück.
|
||
|
||
Returns:
|
||
Liste von Dicts: [{"id": "...", "name": "...", "type": "..."}, ...]
|
||
"""
|
||
all_rooms = self.rest.get_rooms()
|
||
if not all_rooms:
|
||
return []
|
||
|
||
# IDs der bereits in der Room-Map vorhandenen Räume
|
||
mapped_ids = set(self.archivar._room_map.rooms.keys())
|
||
mapped_ids.update(self.archivar._room_map._excluded_room_ids)
|
||
|
||
available = []
|
||
for room in all_rooms:
|
||
rid = room.get("id", "")
|
||
if rid and rid not in mapped_ids:
|
||
available.append(room)
|
||
|
||
# Alphabetisch nach Name sortieren
|
||
available.sort(key=lambda r: r.get("name", "").lower())
|
||
return available
|
||
|
||
def _set_catch_all(self, room_id: str) -> None:
|
||
"""Setzt den angegebenen Raum als alleinigen Catch-All."""
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
for rid, entry in self.archivar._room_map.rooms.items():
|
||
entry.catch_all = (rid == room_id)
|
||
# Persistieren
|
||
from archivar.room_map import RoomMap
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
# P1-2: FAISS-Index nach Catch-All-Wechsel neu bauen
|
||
if self.archivar is not None and self.archivar._room_index is not None:
|
||
try:
|
||
self.archivar._room_index.build_index()
|
||
self.archivar._room_index.save()
|
||
logger.info("[rocketchat] P1-2: FAISS-Index nach Catch-All-Wechsel neu gebaut (%d Vektoren)",
|
||
self.archivar._room_index.size)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P1-2: FAISS-Index-Rebuild nach Catch-All-Wechsel fehlgeschlagen: %s", e)
|
||
|
||
async def _download_and_inline_files(self, text: str) -> str:
|
||
"""Download files referenced as [FILE] markers and inline their content."""
|
||
import re
|
||
_file_re = re.compile(
|
||
r'\[FILE\]\s+(?P<name>[^\n]+?)\s+\((?P<type>[^)]+)\)\n'
|
||
r'Download:\s+\S+/file-upload/(?P<fid>[^/]+)/(?P<fname>\S+)'
|
||
)
|
||
matches = list(_file_re.finditer(text))
|
||
if not matches:
|
||
return text
|
||
for m in matches:
|
||
fid = m.group("fid")
|
||
fname = m.group("fname")
|
||
content = self.rest.download_file(fid, fname)
|
||
if content:
|
||
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
||
text += block
|
||
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
||
# P2-1: Alle übrigen [FILE]-Blöcke entfernen (fehlgeschlagene Downloads)
|
||
# Non-greedy Pattern: erfasst [FILE]...Download:... bis zum nächsten \n
|
||
# re.DOTALL damit Zeilenumbrüche innerhalb des Blocks matchen
|
||
text = re.sub(
|
||
r'\[FILE\].*?Download:[^\n]+\n?', '', text, flags=re.DOTALL
|
||
)
|
||
return text
|
||
|
||
async def disconnect(self) -> None:
|
||
self._mark_disconnected()
|
||
self._shutdown_event.set()
|
||
if self._status_timer:
|
||
self._status_timer.cancel()
|
||
if self._listen_task and not self._listen_task.done():
|
||
self._listen_task.cancel()
|
||
try:
|
||
await self._listen_task
|
||
except asyncio.CancelledError:
|
||
pass
|
||
if self.ddp:
|
||
self.ddp.disconnect()
|
||
self.ddp = None
|
||
logger.info("[rocketchat] Disconnected")
|
||
|
||
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
|
||
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
|
||
if not self.rest.auth_token:
|
||
return SendResult(success=False, error="Not authenticated")
|
||
|
||
# ── V8.4: Red Flag — Response Interception ────────────────────
|
||
# Wenn der Archivar Red Flag gesetzt hat, parsed send() die
|
||
# ROOM: Zeile aus der Agent-Antwort und routet entsprechend.
|
||
red_flag_state = _RED_FLAG_PENDING.get()
|
||
if red_flag_state:
|
||
_RED_FLAG_PENDING.set({}) # Clear immediately — one-shot
|
||
try:
|
||
from archivar.router import _parse_red_flag_response, _strip_red_flag_prefix
|
||
if self.archivar is not None and self.archivar._room_map is not None:
|
||
target_room_id = _parse_red_flag_response(
|
||
content, self.archivar._room_map
|
||
)
|
||
if target_room_id:
|
||
# Agent hat entschieden: ROOM: <raumname> gefunden
|
||
origin_room = red_flag_state.get("origin_room", "")
|
||
logger.info(
|
||
"[rocketchat] V8.4 Red Flag: Agent routed to %s "
|
||
"(origin was %s)",
|
||
target_room_id[:8], origin_room[:8] if origin_room else "?",
|
||
)
|
||
routing_counter.increment('red_flag_agent_routed')
|
||
# Route: Antwort geht in den Zielraum
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
# Strip ROOM: prefix from content
|
||
content = _strip_red_flag_prefix(content)
|
||
# ── Ring-Feedback: Agent-Entscheidung trainieren ──
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
try:
|
||
target_name = self._room_info.get(
|
||
target_room_id, {}
|
||
).get("name", "")
|
||
await self._multiroom_context.add(
|
||
target_room_id, target_name,
|
||
f"Red Flag: Agent-Entscheidung → {target_name}",
|
||
)
|
||
except Exception as e:
|
||
logger.debug(
|
||
"V8.4 Red Flag: Ring-Feedback failed: %s", e
|
||
)
|
||
else:
|
||
# Kein ROOM: → STAY-Fallback
|
||
logger.info(
|
||
"[rocketchat] V8.4 Red Flag: Kein ROOM: in Antwort → "
|
||
"STAY-Fallback (Ursprungsraum)"
|
||
)
|
||
routing_counter.increment('red_flag_fallback_stay')
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] V8.4 Red Flag: Response-Interception failed: %s", e
|
||
)
|
||
routing_counter.increment('red_flag_fallback_stay')
|
||
|
||
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
||
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
||
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
||
content = self._replace_slash_with_double_colon(content)
|
||
|
||
# ── Virtual → Real Room Translation ─────────────────────────
|
||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||
real_room_id = chat_id
|
||
if chat_id.startswith("user:"):
|
||
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
||
# wo die Frage gestellt wurde.
|
||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||
if origin:
|
||
real_room_id = origin
|
||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||
if thematic_target:
|
||
real_room_id = thematic_target
|
||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||
rooms = self._user_rooms.get(chat_id, [])
|
||
if rooms:
|
||
real_room_id = rooms[-1] # last room user was active in
|
||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Fallback: try to find any room with recent activity involving this user
|
||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||
if fallback_room:
|
||
real_room_id = fallback_room
|
||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||
else:
|
||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||
|
||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||
# This allows the agent to request buttons by embedding markup in its
|
||
# response text, without requiring the gateway to pass metadata.
|
||
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
||
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
||
_btn_re = re.compile(
|
||
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
||
r'(?P<text>.*?)'
|
||
r'\[\[/BUTTONS\]\]',
|
||
re.DOTALL | re.IGNORECASE,
|
||
)
|
||
_match = _btn_re.search(content or "")
|
||
if _match:
|
||
_template_name = _match.group("template").lower()
|
||
_inner_text = _match.group("text").strip()
|
||
# Strip the markup from content, keep the inner text
|
||
content = _btn_re.sub(_inner_text, content).strip()
|
||
# Build synthetic metadata so the existing template path below handles it
|
||
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
||
if _template_name == "custom" or "|" in _inner_text:
|
||
# Custom buttons: labels separated by pipe
|
||
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
||
metadata = dict(metadata or {})
|
||
metadata["template"] = "custom"
|
||
metadata["custom_buttons"] = _labels
|
||
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
||
metadata.setdefault("button_title", "Wähle eine Option:")
|
||
elif _template_name in _valid_templates:
|
||
metadata = dict(metadata or {})
|
||
metadata["template"] = _template_name
|
||
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
||
|
||
# Handle interaction templates via metadata
|
||
attachments = None
|
||
if metadata and metadata.get("template"):
|
||
# Use sys.modules to access __init__ symbols (plugin loaded as flat module)
|
||
import sys as _sys
|
||
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
|
||
if _init is None:
|
||
_init = _sys.modules.get('rocketchat')
|
||
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
|
||
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
|
||
template_name = metadata.get("template")
|
||
question_id = metadata.get("question_id", "")
|
||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
||
if buttons:
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": metadata.get("button_title", "Wähle eine Option:"),
|
||
"actions": buttons,
|
||
}]
|
||
elif template_name in _TEMPLATE_MAP:
|
||
tmpl = _TEMPLATE_MAP[template_name]
|
||
attachment = dict(tmpl.get("attachment", {}))
|
||
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["actions"] = buttons
|
||
attachments = [attachment]
|
||
|
||
# Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann.
|
||
# Falls metadata ein Template anfordert, aber attachments None bleibt
|
||
# (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar),
|
||
# hänge Text-Fallback an, damit der User weiß, wie er antworten soll.
|
||
if attachments is None:
|
||
fallback_lines = []
|
||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||
opts = metadata["custom_buttons"]
|
||
fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:")
|
||
for i, opt in enumerate(opts, 1):
|
||
fallback_lines.append(f" {i}. {opt}")
|
||
elif template_name == "yes_no":
|
||
fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)")
|
||
elif template_name == "confirm_cancel":
|
||
fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)")
|
||
elif template_name == "ok":
|
||
fallback_lines.append("Antworte mit 1 (OK)")
|
||
elif template_name == "multi_choice_3":
|
||
fallback_lines.append("Antworte mit 1, 2 oder 3")
|
||
if fallback_lines:
|
||
content = content + "\n\n" + "\n".join(fallback_lines)
|
||
logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name)
|
||
|
||
# ── Clarify-Queue: remember pending button question ──
|
||
if metadata and metadata.get("template") and attachments:
|
||
_tmpl = metadata.get("template")
|
||
_qid = metadata.get("question_id", "")
|
||
_expected = []
|
||
if _tmpl == "yes_no":
|
||
_expected = ["ja", "nein", "yes", "no"]
|
||
elif _tmpl == "confirm_cancel":
|
||
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
||
elif _tmpl == "ok":
|
||
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
||
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
||
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
||
self._pending_clarifies[real_room_id] = {
|
||
"question_id": _qid,
|
||
"template": _tmpl,
|
||
"expected": _expected,
|
||
"timestamp": time.time(),
|
||
"original_text": content,
|
||
}
|
||
|
||
# ── P1-7: Proactive message splitting ────────────────────────
|
||
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||
# "(Response formatting failed, plain text:)" — aber die API
|
||
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
|
||
# splitten, nicht erst nach einem Fehlschlag.
|
||
if len(content) > 3000 and attachments is None:
|
||
logger.info(
|
||
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
|
||
len(content),
|
||
)
|
||
return await self._send_split(real_room_id, content)
|
||
|
||
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
||
if success:
|
||
# If this message has buttons, mark the room so the next user
|
||
# message from here stays put (no Archivar routing). Button
|
||
# responses must be answered in the same room the question was
|
||
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||
# and the agent loses context.
|
||
if attachments:
|
||
self._rooms_with_pending_questions.add(real_room_id)
|
||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||
# ── B5v6.5: Conversation History — Agent-Antwort aufzeichnen ──
|
||
if _MULTIROOM() and self._conversation_history is not None:
|
||
await self._conversation_history.add(real_room_id, "agent", content)
|
||
# ── V8.6 P1-3: PresenceEngine — KEIN decrement in send()! ──
|
||
# Der Counter wird NUR im finally-Block von _process_incoming
|
||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||
# würde den Agenten vorzeitig auf "online" setzen.
|
||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||
return SendResult(success=False, error="chat.postMessage failed")
|
||
|
||
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
||
|
||
async def _send_split(self, room_id: str, content: str) -> SendResult:
|
||
"""Split long messages into chunks and send them sequentially.
|
||
|
||
Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||
Lange Antworten (Tabellen, Listen) werden abgeschnitten.
|
||
Diese Methode splittet an Absatzgrenzen und sendet Chunks
|
||
mit (1/3), (2/3), (3/3) Markern.
|
||
|
||
Args:
|
||
room_id: Rocket.Chat Raum-ID
|
||
content: Der vollständige Nachrichtentext
|
||
|
||
Returns:
|
||
SendResult mit success=True wenn alle Chunks gesendet wurden
|
||
"""
|
||
MAX_CHUNK = 2800 # Sicherheitsmarge unter 4000
|
||
paragraphs = content.split("\n\n")
|
||
chunks = []
|
||
current = ""
|
||
|
||
for para in paragraphs:
|
||
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||
chunks.append(current.strip())
|
||
current = para
|
||
else:
|
||
if current:
|
||
current += "\n\n" + para
|
||
else:
|
||
current = para
|
||
|
||
if current.strip():
|
||
chunks.append(current.strip())
|
||
|
||
# If still too long (single huge paragraph), force-split
|
||
if not chunks or len(chunks[0]) > MAX_CHUNK:
|
||
chunks = []
|
||
for i in range(0, len(content), MAX_CHUNK):
|
||
chunks.append(content[i:i + MAX_CHUNK])
|
||
|
||
total = len(chunks)
|
||
if total <= 1:
|
||
# Nothing to split — try sending as-is
|
||
success = await self._post_message_with_retry(room_id, content)
|
||
if success:
|
||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||
return SendResult(success=False, error="chat.postMessage failed")
|
||
|
||
logger.info(
|
||
"[rocketchat] P1-4: Splitting %d chars into %d chunks",
|
||
len(content), total,
|
||
)
|
||
|
||
last_msg_id = None
|
||
for i, chunk in enumerate(chunks, 1):
|
||
marker = f"({i}/{total})"
|
||
chunk_text = f"{marker}\n{chunk}" if total > 1 else chunk
|
||
success = await self._post_message_with_retry(room_id, chunk_text)
|
||
if success:
|
||
last_msg_id = str(int(time.time() * 1000))
|
||
# Small delay between chunks to preserve order
|
||
if i < total:
|
||
await asyncio.sleep(0.5)
|
||
else:
|
||
logger.error(
|
||
"[rocketchat] P1-4: Chunk %d/%d failed to send",
|
||
i, total,
|
||
)
|
||
|
||
if last_msg_id:
|
||
# ── V8.6 P1-4: PresenceEngine — KEIN decrement in _send_split! ──
|
||
# Der Counter wird NUR im finally-Block von _process_incoming
|
||
# dekrementiert (line 2794). _send_split ist ein Sub-Pfad von send().
|
||
return SendResult(success=True, message_id=last_msg_id)
|
||
return SendResult(success=False, error="All chunks failed")
|
||
|
||
# ── P1-6: Slash-Command → Double-Colon Translation ──────────────────
|
||
|
||
@staticmethod
|
||
def _replace_slash_with_double_colon(content: str) -> str:
|
||
"""Replace /approve, /deny etc. with ::approve, ::deny for Rocket.Chat.
|
||
|
||
Hermes Core sends dangerous-command approval messages with
|
||
/approve, /deny, /approve session, /approve always.
|
||
Rocket.Chat doesn't support /-commands, so we replace them
|
||
with :: variants that the plugin's inline command handler
|
||
recognizes.
|
||
"""
|
||
# Match /approve or /deny NOT preceded by a word character
|
||
# (avoids matching inside URLs like /approve in paths).
|
||
# Use word boundary AFTER the command to avoid partial matches.
|
||
content = re.sub(
|
||
r'(?<![a-zA-Z0-9])/approve\b',
|
||
'::approve',
|
||
content
|
||
)
|
||
content = re.sub(
|
||
r'(?<![a-zA-Z0-9])/deny\b',
|
||
'::deny',
|
||
content
|
||
)
|
||
return content
|
||
|
||
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
|
||
"""Fallback method to find a room for a user when direct mapping fails.
|
||
|
||
Args:
|
||
chat_id: Virtual chat_id like "user:username"
|
||
|
||
Returns:
|
||
Room ID if found, None otherwise
|
||
"""
|
||
if not chat_id.startswith("user:"):
|
||
return None
|
||
|
||
target_username = chat_id.split(":", 1)[1].lower()
|
||
|
||
# Try to find any DM room involving this user
|
||
for room_id, room_info in self._room_info.items():
|
||
if room_info.get("type") == "d":
|
||
# Try to get room details with members
|
||
try:
|
||
room_detail = self.rest._request("GET", f"/api/v1/rooms.info?roomId={room_id}", headers={
|
||
"X-Auth-Token": self.rest.auth_token,
|
||
"X-User-Id": self.rest.user_id,
|
||
})
|
||
if room_detail and room_detail.get("success"):
|
||
room_data = room_detail.get("room", {})
|
||
usernames = room_data.get("usernames", [])
|
||
if target_username in [u.lower() for u in usernames]:
|
||
return room_id
|
||
except Exception as e:
|
||
logger.debug("[rocketchat] Could not get room info for %s: %s", room_id, e)
|
||
|
||
# Last resort: return first available room (better than nothing)
|
||
if self._subscribed_rooms:
|
||
first_room = next(iter(self._subscribed_rooms))
|
||
logger.warning("[rocketchat] Using first available room %s as ultimate fallback for %s",
|
||
first_room, chat_id)
|
||
return first_room
|
||
|
||
return None
|
||
|
||
|
||
async def send_clarify(
|
||
self,
|
||
chat_id: str,
|
||
question: str,
|
||
choices: Optional[list],
|
||
clarify_id: str,
|
||
session_key: str,
|
||
metadata: Optional[Dict[str, Any]] = None,
|
||
) -> SendResult:
|
||
"""Render a clarify prompt with Rocket.Chat action buttons.
|
||
|
||
Multi-choice mode (``choices`` non-empty): renders one button per
|
||
option plus a final "✏️ Other (type answer)" button. Picking the
|
||
"Other" button flips the entry into text-capture mode so the next
|
||
message becomes the response.
|
||
|
||
Open-ended mode (``choices`` empty): renders the question as plain
|
||
text — no buttons. The next message in the session is captured by
|
||
the gateway's text-intercept and resolves the clarify.
|
||
"""
|
||
# Fallback to text-based clarify if choices are empty
|
||
if not choices:
|
||
return await super().send_clarify(
|
||
chat_id=chat_id,
|
||
question=question,
|
||
choices=choices,
|
||
clarify_id=clarify_id,
|
||
session_key=session_key,
|
||
metadata=metadata,
|
||
)
|
||
|
||
if not self.rest.auth_token:
|
||
return SendResult(success=False, error="Not authenticated")
|
||
|
||
# ── Virtual → Real Room Translation ─────────────────────────
|
||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||
real_room_id = chat_id
|
||
if chat_id.startswith("user:"):
|
||
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
||
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
|
||
real_room_id = thematic_target
|
||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Priority 1: ContextVar from the message that triggered this turn
|
||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||
if origin:
|
||
real_room_id = origin
|
||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Priority 2: proactive message — use most recent room for this user
|
||
rooms = self._user_rooms.get(chat_id, [])
|
||
if rooms:
|
||
real_room_id = rooms[-1] # last room user was active in
|
||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Fallback: try to find any room with recent activity involving this user
|
||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||
if fallback_room:
|
||
real_room_id = fallback_room
|
||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||
else:
|
||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||
|
||
# Render full option text in the message body so users
|
||
# can read long choices that would be truncated in buttons.
|
||
# Buttons keep short numeric labels (1, 2, …, Other).
|
||
text = f"❓ {question}"
|
||
option_lines = "\n".join(
|
||
f"{i + 1}. {choice}"
|
||
for i, choice in enumerate(choices)
|
||
)
|
||
text += f"\n\n{option_lines}"
|
||
|
||
# Build buttons with short labels to avoid truncation
|
||
button_labels = [str(i + 1) for i in range(len(choices))]
|
||
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
|
||
|
||
# Add "Other" button with special handling
|
||
buttons.append({
|
||
"type": "button",
|
||
"text": "✏️ Other",
|
||
"msg": f"CLARIFY:{clarify_id}:other",
|
||
"msg_in_chat_window": True,
|
||
"style": "default",
|
||
})
|
||
|
||
# Create attachment with buttons
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Please choose an option:",
|
||
"actions": buttons,
|
||
}]
|
||
|
||
# Send message with buttons
|
||
success = await self._post_message_with_retry(real_room_id, text, attachments=attachments)
|
||
|
||
if success:
|
||
# Store clarify state for gateway identification
|
||
self._clarify_state = getattr(self, '_clarify_state', {})
|
||
self._clarify_state[clarify_id] = session_key
|
||
|
||
# For "Other" button, we need to enable text capture mode
|
||
# This is done by calling mark_awaiting_text when the user clicks "Other"
|
||
# The actual implementation will be in the message handling logic
|
||
|
||
# Mark room for button response handling (no Archivar routing)
|
||
self._rooms_with_pending_questions.add(real_room_id)
|
||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||
|
||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||
else:
|
||
# Fallback to text-based clarify if REST call fails
|
||
logger.warning("[rocketchat] Failed to send clarify with buttons, falling back to text")
|
||
return await super().send_clarify(
|
||
chat_id=chat_id,
|
||
question=question,
|
||
choices=choices,
|
||
clarify_id=clarify_id,
|
||
session_key=session_key,
|
||
metadata=metadata,
|
||
)
|
||
|
||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||
pass
|
||
|
||
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
||
info = self._room_info.get(chat_id, {})
|
||
return {"name": info.get("name", chat_id), "type": "group" if info.get("type") in ("c", "p") else "dm"}
|
||
|
||
async def _listen_loop(self):
|
||
loop = asyncio.get_running_loop()
|
||
health_check_counter = 0
|
||
while self._running and not self._shutdown_event.is_set():
|
||
try:
|
||
msg_obj = await loop.run_in_executor(None, self._ddp_queue_get, 1.0)
|
||
if msg_obj is None:
|
||
health_check_counter += 1
|
||
# Every 60 seconds (60 x 1.0s timeouts): check for silent death
|
||
if health_check_counter >= 60:
|
||
health_check_counter = 0
|
||
# DDP-Health-Check: nur loggen, kein Reconnect erzwingen
|
||
if self.ddp:
|
||
last_rx = self.ddp._last_rx_time if self.ddp._last_rx_time > 0 else time.time()
|
||
logger.debug(
|
||
"DDP health: stream alive, last_rx=%s, rooms=%d, connected=%s",
|
||
time.strftime("%H:%M:%S", time.localtime(last_rx)),
|
||
len(self._subscribed_rooms),
|
||
self.ddp.connected,
|
||
)
|
||
if self.ddp and self.ddp.connected and not self.ddp.is_alive(self.HEALTH_SILENT_LIMIT):
|
||
logger.warning(
|
||
"[rocketchat] Silent death detected: no DDP traffic for %.0fs — forcing reconnect",
|
||
self.HEALTH_SILENT_LIMIT,
|
||
)
|
||
if await self._reconnect_ddp():
|
||
logger.info("[rocketchat] Recovered from silent death")
|
||
else:
|
||
logger.error("[rocketchat] Silent death recovery failed")
|
||
await asyncio.sleep(10)
|
||
continue
|
||
|
||
if self.ddp and not self.ddp.connected:
|
||
logger.warning("[rocketchat] DDP disconnected, reconnecting...")
|
||
if await self._reconnect_ddp():
|
||
logger.info("[rocketchat] Reconnected")
|
||
else:
|
||
await asyncio.sleep(5)
|
||
continue
|
||
health_check_counter = 0 # Reset on any message
|
||
await self._process_incoming(msg_obj)
|
||
except asyncio.CancelledError:
|
||
break
|
||
except Exception as e:
|
||
logger.error("[rocketchat] Listener error: %s", e)
|
||
await asyncio.sleep(1)
|
||
|
||
def _ddp_queue_get(self, timeout: float):
|
||
if not self.ddp:
|
||
return None
|
||
try:
|
||
return self.ddp._msg_queue.get(timeout=timeout)
|
||
except queue.Empty:
|
||
return None
|