3940 lines
198 KiB
Python
3940 lines
198 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 socket
|
||
import ssl
|
||
import struct
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
import urllib.error
|
||
import urllib.request
|
||
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
|
||
|
||
# ── 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):
|
||
self.host = host
|
||
self._on_message = on_message_cb
|
||
self._on_connected = on_connected_cb
|
||
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])
|
||
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 set_status(self, status: str) -> bool:
|
||
if not self.connected:
|
||
return False
|
||
method = f"UserPresence:{status}"
|
||
self._send_json({"msg": "method", "method": method, "params": [], "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 = ""
|
||
|
||
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, 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}"
|
||
)
|
||
return "\n".join(lines)
|
||
|
||
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
|
||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||
self.ddp = DDPClient(
|
||
host=host,
|
||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||
)
|
||
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))
|
||
|
||
# ── 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"):
|
||
logger.info("[rocketchat] P1-4: Persistierten Onboarding-State wiederhergestellt")
|
||
self._onboarding_state = persisted_onboarding
|
||
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))
|
||
await self._start_onboarding(missing)
|
||
else:
|
||
# Keine neuen c/p-Räume — aber DM könnte noch Theme brauchen
|
||
await 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))
|
||
await 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()]
|
||
await self._start_onboarding(all_rooms)
|
||
else:
|
||
# Nur DM — trotzdem Onboarding für DM-Theme
|
||
await self._start_onboarding([])
|
||
else:
|
||
# Map hat Räume, keine neuen — aber DM könnte Theme brauchen
|
||
await 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
|
||
|
||
# 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=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||
)
|
||
if not self.ddp.connect_and_login(self._auth_token):
|
||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||
return False
|
||
|
||
# 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."""
|
||
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 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
|
||
|
||
# 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])
|
||
|
||
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
||
if _MULTIROOM() and self._conversation_history is not None:
|
||
await self._conversation_history.add(room_id, "user", 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)
|
||
topic = 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("")
|
||
|
||
# ── 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)
|
||
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 "=" 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)
|
||
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"):
|
||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons()
|
||
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
|
||
)
|
||
|
||
# ── 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=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=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(text)
|
||
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
||
|
||
try:
|
||
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)
|
||
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")
|
||
elif room_type == "d":
|
||
# V8: DM-Bypass bleibt, weil DM kein Multiroom-Routing braucht.
|
||
# is_auftrag wird NICHT mehr als Gate verwendet — die
|
||
# Auftragserkennung dient nur noch Telemetrie/Counter.
|
||
logger.debug("[rocketchat] DM von %s — kein Multiroom-Routing", username)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — DM (no multiroom)")
|
||
routing_counter.increment('dm_routing_skipped')
|
||
logger.info("ROUTING BYPASS: reason=dm_routing_skipped, origin_room=%s", room_id)
|
||
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
|
||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{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)",
|
||
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=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()
|
||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{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)",
|
||
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=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],
|
||
)
|
||
else:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12])
|
||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||
# 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] = {
|
||
'text': 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,
|
||
}
|
||
# 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
|
||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{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",
|
||
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 = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
|
||
# ── 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
|
||
await self.handle_message(event)
|
||
except Exception as e:
|
||
logger.error("[rocketchat] handle_message error: %s", e)
|
||
# Fallback: Wenn BUTTON_CLICK 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) == "BUTTON_CLICK":
|
||
logger.info("[rocketchat] BUTTON_CLICK 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] BUTTON_CLICK text fallback also failed: %s", e2)
|
||
|
||
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 = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
|
||
# ── 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
|
||
await self.handle_message(event)
|
||
except Exception as e:
|
||
logger.error("[rocketchat] handle_message error: %s", e)
|
||
# Fallback: Wenn BUTTON_CLICK fehlschlägt
|
||
if is_button_response and str(e) == "BUTTON_CLICK":
|
||
logger.info("[rocketchat] BUTTON_CLICK 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] BUTTON_CLICK 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,
|
||
}]
|
||
|
||
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
|
||
|
||
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
|
||
|
||
Args:
|
||
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
||
"""
|
||
# 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:
|
||
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)
|
||
|
||
# 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
|
||
|
||
# Initialisiere Onboarding-State
|
||
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
|
||
|
||
# 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.",
|
||
"",
|
||
"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,
|
||
}
|
||
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 = (
|
||
"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)
|
||
|
||
# Onboarding abschließen
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
self._onboarding_state = {}
|
||
# 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 Butler-Mode)")
|
||
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
|
||
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
|
||
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]
|
||
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]
|
||
|
||
# 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_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")
|
||
|
||
@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
|
||
|
||
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))
|
||
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')
|
||
|
||
# ── 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,
|
||
}
|
||
|
||
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)
|
||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||
return SendResult(success=False, error="chat.postMessage failed")
|
||
|
||
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
|