7859 lines
390 KiB
Python
7859 lines
390 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 concurrent.futures
|
||
import contextvars
|
||
import datetime
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
import os
|
||
import queue
|
||
import random
|
||
import re
|
||
import signal
|
||
import socket
|
||
import ssl
|
||
import struct
|
||
import threading
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
import urllib.error
|
||
import uuid
|
||
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) ──
|
||
# P1: Cross-Contamination-Fix — Task-Token + TTL-Sweep
|
||
# Jeder Eintrag hat: origin_room, task_token (UUID4), timestamp (ISO)
|
||
# send() validiert: Token-Match → verwenden; kein Token (Stream-Retry) → TTL-Check;
|
||
# Token-Mismatch → Cross-Contamination → ignorieren.
|
||
_ROOM_CONTEXT_TTL_SECONDS = 30 * 60 # 30 Minuten
|
||
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {origin_room, task_token, timestamp}
|
||
_room_context_lock = threading.Lock()
|
||
|
||
# ContextVar für das aktuelle Task-Token — wird in _set_room_context_origin gesetzt,
|
||
# in _dispatch_agent via copy_context() eingefroren und in send() verglichen.
|
||
_CURRENT_TASK_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||
"_rocketchat_task_token", default=""
|
||
)
|
||
|
||
|
||
def _set_room_context_origin(chat_id: str, room_id: str) -> str:
|
||
"""Atomar _room_context[chat_id]["origin_room"] = room_id setzen.
|
||
|
||
Generiert ein neues Task-Token (UUID4) und setzt den Timestamp.
|
||
Gibt das generierte Token zurück, damit der Aufrufer es in
|
||
_CURRENT_TASK_TOKEN setzen kann.
|
||
|
||
Helper-Funktion für alle 9 Stellen, die _CURRENT_ORIGIN_ROOM.set()
|
||
aufrufen. Stellt sicher, dass der persistente Fallback (_room_context)
|
||
immer synchron mit der ContextVar gesetzt wird — keine Race-Condition
|
||
durch getrenntes setdefault + Index-Zuweisung.
|
||
"""
|
||
token = str(uuid.uuid4())
|
||
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||
with _room_context_lock:
|
||
ctx = _room_context.setdefault(chat_id, {})
|
||
ctx["origin_room"] = room_id
|
||
ctx["task_token"] = token
|
||
ctx["timestamp"] = now
|
||
_CURRENT_TASK_TOKEN.set(token)
|
||
return token
|
||
|
||
|
||
def _get_room_context_origin(chat_id: str) -> str:
|
||
"""Liest _room_context[chat_id]["origin_room"] mit Task-Token-Validierung.
|
||
|
||
Priorität:
|
||
1. Task-Token-Match (_CURRENT_TASK_TOKEN == task_token) → verwenden
|
||
2. Kein Task-Token im ContextVar (Stream-Retry) → TTL-Check
|
||
- TTL gültig (< 30 Min) → verwenden (gleicher Task, anderer asyncio-Task)
|
||
- TTL abgelaufen → ignorieren, log Warning
|
||
3. Task-Token-Mismatch → Cross-Contamination → ignorieren, log Warning
|
||
|
||
Returns:
|
||
origin_room wenn gültig, sonst "".
|
||
"""
|
||
current_token = _CURRENT_TASK_TOKEN.get()
|
||
with _room_context_lock:
|
||
ctx = _room_context.get(chat_id, {})
|
||
stored_token = ctx.get("task_token", "")
|
||
stored_ts = ctx.get("timestamp", "")
|
||
origin = ctx.get("origin_room", "")
|
||
|
||
if not origin:
|
||
return ""
|
||
|
||
# Fall 1: Exakter Token-Match — gleicher Task, direkt verwenden
|
||
if current_token and stored_token and current_token == stored_token:
|
||
return origin
|
||
|
||
# Fall 2: Kein Token im ContextVar (Stream-Retry in neuem asyncio-Task)
|
||
# → TTL-Check: wenn Eintrag noch frisch (< 30 Min), ist es der gleiche Task
|
||
if not current_token:
|
||
if stored_ts:
|
||
try:
|
||
stored_dt = datetime.datetime.fromisoformat(stored_ts)
|
||
age = (datetime.datetime.now(datetime.timezone.utc) - stored_dt).total_seconds()
|
||
if age < _ROOM_CONTEXT_TTL_SECONDS:
|
||
logger.debug(
|
||
"[rocketchat] _room_context TTL valid (age=%.0fs): %s → %s",
|
||
age, chat_id, origin,
|
||
)
|
||
return origin
|
||
else:
|
||
logger.warning(
|
||
"[rocketchat] stale room_context entry for %s (age=%.0fs > %ds TTL) — ignoring",
|
||
chat_id, age, _ROOM_CONTEXT_TTL_SECONDS,
|
||
)
|
||
return ""
|
||
except (ValueError, TypeError):
|
||
logger.warning(
|
||
"[rocketchat] unparseable timestamp in _room_context for %s: %s",
|
||
chat_id, stored_ts,
|
||
)
|
||
return ""
|
||
# Kein Timestamp (alter Eintrag vor diesem Fix) → TTL unbekannt, trotzdem verwenden
|
||
# (Backward-Kompatibilität: alte Einträge ohne timestamp/task_token)
|
||
return origin
|
||
|
||
# Fall 3: Token-Mismatch — Cross-Contamination!
|
||
# Ein anderer Task hat _room_context[chat_id] überschrieben.
|
||
logger.warning(
|
||
"[rocketchat] _room_context token mismatch for %s — cross-contamination detected, ignoring entry",
|
||
chat_id,
|
||
)
|
||
return ""
|
||
|
||
def _MULTIROOM() -> bool:
|
||
"""Laufzeit-Auswertung von MULTIROOM_AGENT (nicht beim Import, da .env via systemd EnvironmentFile erst später geladen wird)."""
|
||
return os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
|
||
|
||
if _MULTIROOM():
|
||
from archivar.adapter_integration import ArchivarMessageHandler
|
||
from archivar.conversation_history import ConversationHistory
|
||
from archivar.multiroom_context import MultiRoomContextRing
|
||
from archivar.router import room_name_to_topic
|
||
|
||
# Routing-Counter: immer importieren (keine schweren Abhängigkeiten)
|
||
from archivar.routing_counter import routing_counter
|
||
from archivar.routing_telemetry import routing_telemetry
|
||
|
||
# P0: Reply-Quote-Stripping — verhindert Fehl-Routing durch zitierte Parent-Nachrichten
|
||
from archivar.reply_quote_stripper import strip_reply_quote_for_routing
|
||
|
||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||
import sys as _sys
|
||
_init_module = _sys.modules.get('rocketchat')
|
||
if _init_module is None:
|
||
_init_module = _sys.modules.get(__name__)
|
||
_TEMPLATE_MAP = getattr(_init_module, '_TEMPLATE_MAP', {})
|
||
_build_custom_buttons = getattr(_init_module, '_build_custom_buttons',
|
||
lambda labels, prefix='', style='default': [])
|
||
|
||
logger = logging.getLogger(__name__)
|
||
logger.setLevel(logging.DEBUG) # DEBUG für 24h-Stabilitätstest (19.06.2026)
|
||
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
||
if not logger.handlers:
|
||
_handler = logging.StreamHandler()
|
||
_handler.setLevel(logging.DEBUG)
|
||
_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
|
||
logger.addHandler(_handler)
|
||
logger.propagate = False # Don't double-log to root
|
||
|
||
# ── Virtual Room Translation ──────────────────────────────────────────
|
||
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
|
||
# agent turn, so send() can route the response back to the correct room even
|
||
# though the Hermes session uses a synthetic user-based chat_id.
|
||
# This is the mechanism that makes "one agent for all rooms" work
|
||
# without touching Hermes Core.
|
||
#
|
||
# V8.1.1 R4: _CURRENT_ORIGIN_ROOM ist eine ContextVar — sie wird bei jedem
|
||
# neuen Turn (handle_message-Aufruf) zurückgesetzt. Der Wert lebt nur für
|
||
# die Dauer eines einzelnen Agent-Turns und wird NICHT zwischen Turns
|
||
# persistiert. Das verhindert, dass der Zielraum einer vorherigen Nachricht
|
||
# an der aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im
|
||
# Projektraum). Reset erfolgt implizit durch ContextVar-Semantik: jeder
|
||
# asyncio-Task hat seinen eigenen Context, und handle_message setzt den
|
||
# Wert explizit neu (entweder auf Zielraum bei Move/Auto-Route oder auf
|
||
# den Ursprungsraum bei stay_in_room).
|
||
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||
"_rocketchat_origin_room", default=""
|
||
)
|
||
|
||
_THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||
"_rocketchat_thematic_target_room", default=""
|
||
)
|
||
|
||
# ── V8.4: Red Flag — Pending State ──────────────────────────────────────
|
||
# ContextVar für den Pre-Dispatch-Hook: Wenn der Archivar Red Flag setzt,
|
||
# wird der Prompt hier gespeichert. send() prüft diesen State und parsed
|
||
# ROOM: aus der Agent-Antwort.
|
||
_RED_FLAG_PENDING: contextvars.ContextVar[dict] = contextvars.ContextVar(
|
||
"_rocketchat_red_flag_pending", default={}
|
||
)
|
||
|
||
# Globaler Monoton-Zähler für Archivar-Fragen
|
||
import threading
|
||
_question_counter: int = 0
|
||
_question_counter_lock: threading.Lock = threading.Lock()
|
||
|
||
try:
|
||
from gateway.platforms.base import (
|
||
BasePlatformAdapter,
|
||
SendResult,
|
||
MessageEvent,
|
||
MessageType,
|
||
)
|
||
from gateway.session import SessionSource
|
||
from gateway.config import PlatformConfig, Platform
|
||
except ImportError:
|
||
# Fallback for standalone test / development outside gateway
|
||
BasePlatformAdapter = object
|
||
SendResult = dict
|
||
MessageEvent = dict
|
||
MessageType = object
|
||
SessionSource = object
|
||
PlatformConfig = object
|
||
Platform = str
|
||
|
||
|
||
def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str = "") -> str:
|
||
extra = getattr(config, "extra", {}) or {}
|
||
return os.getenv(env_var) or extra.get(key, default)
|
||
|
||
|
||
# P1 FB-08: File path component sanitizer for download_file
|
||
# Reduces a string to only safe characters: alphanumeric, dot, underscore, hyphen.
|
||
# Returns empty string if nothing remains after sanitization.
|
||
_FILE_PATH_SAFE_RE = re.compile(r'[^a-zA-Z0-9._-]')
|
||
|
||
|
||
def _sanitize_file_path_component(value: str) -> str:
|
||
"""Sanitize a file path component for use in URL construction.
|
||
|
||
Removes all characters except [a-zA-Z0-9._-] to prevent path traversal
|
||
attacks (e.g. '../etc/passwd' → 'etcpasswd').
|
||
|
||
Args:
|
||
value: Raw file_id or filename from user input.
|
||
|
||
Returns:
|
||
Sanitized string, or empty string if nothing remains.
|
||
"""
|
||
return _FILE_PATH_SAFE_RE.sub('', value)
|
||
|
||
|
||
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
|
||
# P2-Fix: HTTP 4xx als warning, 5xx als error (vorher nur debug)
|
||
if 400 <= e.code < 500:
|
||
logger.warning("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||
else:
|
||
logger.error("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||
return None
|
||
except Exception as e:
|
||
logger.warning("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, max_size: int = 10 * 1024 * 1024) -> 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.
|
||
|
||
P1 Security (FB-08): Sanitizes file_id and filename to prevent path
|
||
traversal, URL-encodes path components, and caps response size to
|
||
prevent DoS via oversized downloads.
|
||
"""
|
||
if not self.auth_token:
|
||
return None
|
||
|
||
# P1 FB-08: Sanitize file_id and filename — allow only safe characters
|
||
file_id = _sanitize_file_path_component(file_id)
|
||
filename = _sanitize_file_path_component(filename)
|
||
if not file_id or not filename:
|
||
logger.warning("File download rejected: invalid file_id or filename after sanitization")
|
||
return None
|
||
|
||
# P1 FB-08: URL-encode path components to prevent traversal
|
||
safe_fid = urllib.parse.quote(file_id, safe='')
|
||
safe_fname = urllib.parse.quote(filename, safe='')
|
||
url = f"{self.base_url}/file-upload/{safe_fid}/{safe_fname}"
|
||
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:
|
||
# P1 FB-08: Response size cap — read in chunks, stop at max_size
|
||
chunks = []
|
||
total = 0
|
||
while True:
|
||
chunk = resp.read(min(65536, max_size - total))
|
||
if not chunk:
|
||
break
|
||
chunks.append(chunk)
|
||
total += len(chunk)
|
||
if total >= max_size:
|
||
logger.warning(
|
||
"File download truncated at %d bytes (max_size=%d): %s",
|
||
total, max_size, filename,
|
||
)
|
||
break
|
||
content = b"".join(chunks)
|
||
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 DDPTimeout(Exception):
|
||
"""Raised when a DDP method call times out waiting for a result message."""
|
||
pass
|
||
|
||
|
||
class DDPServerError(Exception):
|
||
"""Raised when the DDP server returns an error for a method call."""
|
||
|
||
def __init__(self, error_data: dict):
|
||
self.error_data = error_data
|
||
super().__init__(f"DDP server error: {error_data}")
|
||
|
||
|
||
class DDPNotConnected(Exception):
|
||
"""Raised when a DDP method is called but the client is not connected."""
|
||
pass
|
||
|
||
|
||
class DDPClient:
|
||
PING_INTERVAL = 8.0
|
||
|
||
|
||
def __init__(self, host: str, on_message_cb=None, on_connected_cb=None, on_room_event_cb=None):
|
||
self.host = host
|
||
self._on_message = on_message_cb
|
||
self._on_connected = on_connected_cb
|
||
self._on_room_event = on_room_event_cb # A1b: DDP room events callback
|
||
self.sock: Optional[socket.socket] = None
|
||
self.connected = False
|
||
self._running = False
|
||
self._reader_thread: Optional[threading.Thread] = None
|
||
self._write_lock = threading.Lock()
|
||
self._msg_queue: queue.Queue = queue.Queue()
|
||
self._next_sub_id = 1
|
||
self._sub_rooms: Dict[str, str] = {}
|
||
self._session: Optional[str] = None
|
||
self._reconnect_attempt = 0
|
||
self._last_rx_time = 0.0
|
||
# P1-2 O-2: Future-Store für await-Semantik
|
||
self._pending_results: Dict[str, concurrent.futures.Future] = {}
|
||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||
self._result_lock = threading.Lock()
|
||
self._msg_seq: int = 0
|
||
# P0: Resolved RC username from DDP login response (not from env)
|
||
self._rc_username: Optional[str] = None
|
||
|
||
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()
|
||
last_sweep = 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
|
||
# P1-2 O-2: Periodic sweep of stale pending results (every 5s)
|
||
if time.time() - last_sweep >= 5.0:
|
||
self._sweep_pending_results()
|
||
last_sweep = time.time()
|
||
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"})
|
||
# P1-2 O-2: Handle DDP result messages (resolve pending Futures)
|
||
elif msg_type == "result":
|
||
self._handle_result_message(data)
|
||
# P1-2 O-2: Handle DDP updated messages (log only, result follows)
|
||
elif msg_type == "updated":
|
||
logger.debug(
|
||
"DDP: updated message received (id=%s)",
|
||
data.get("id", "?"),
|
||
)
|
||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
||
fields = data.get("fields", {})
|
||
args = fields.get("args", [])
|
||
if args and isinstance(args, list) and len(args) >= 1:
|
||
self._msg_queue.put(args[0])
|
||
# A1b: stream-notify-room events (rooms-changed, roomMemberAdded)
|
||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-notify-room":
|
||
self._handle_ddp_message(data)
|
||
except Exception:
|
||
pass
|
||
elif opcode == 0x08:
|
||
break
|
||
except Exception:
|
||
break
|
||
self.connected = False
|
||
# B1: Reader loop exited — cancel all pending Futures so callers
|
||
# (e.g. PulseController) get DDPNotConnected and can fall back to REST.
|
||
self._cancel_pending_results()
|
||
logger.debug("DDP reader thread exited")
|
||
|
||
def is_alive(self, max_silence: float = 300.0) -> bool:
|
||
"""Detect silent death: socket looks connected but no traffic for max_silence seconds."""
|
||
if not self.connected or not self.sock:
|
||
return False
|
||
if self._last_rx_time == 0:
|
||
# Never received anything yet — use connect time as baseline
|
||
return True
|
||
return (time.time() - self._last_rx_time) < max_silence
|
||
|
||
def connect_and_login(self, token: str) -> bool:
|
||
self._last_rx_time = time.time()
|
||
try:
|
||
self.sock = self._create_socket()
|
||
if not self._handshake(self.sock):
|
||
return False
|
||
self._running = True
|
||
self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
|
||
self._reader_thread.start()
|
||
time.sleep(0.3)
|
||
self._send_json({"msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"]})
|
||
for _ in range(50):
|
||
if self.connected:
|
||
break
|
||
time.sleep(0.1)
|
||
if not self.connected:
|
||
self.disconnect()
|
||
return False
|
||
time.sleep(0.2)
|
||
self._send_json({"msg": "method", "method": "login",
|
||
"params": [{"resume": token}], "id": "ddplogin"})
|
||
time.sleep(0.5)
|
||
return True
|
||
except Exception as e:
|
||
logger.error("DDP connect failed: %s", e)
|
||
self.disconnect()
|
||
return False
|
||
|
||
def subscribe_room(self, room_id: str) -> Optional[str]:
|
||
if not self.connected:
|
||
return None
|
||
sub_id = f"sub{self._next_sub_id}"
|
||
self._next_sub_id += 1
|
||
# CRITICAL: Rocket.Chat V5+ requires {"token": "true"} as second param,
|
||
# otherwise subscribe succeeds but NO messages ever stream.
|
||
self._send_json({
|
||
"msg": "sub",
|
||
"name": "stream-room-messages",
|
||
"params": [room_id, {"token": "true"}],
|
||
"id": sub_id
|
||
})
|
||
self._sub_rooms[room_id] = sub_id
|
||
return sub_id
|
||
|
||
def unsubscribe(self, room_id: str) -> bool:
|
||
"""DDP unsub: send ``{"msg": "unsub", "id": "<sub_id>"}`` and
|
||
remove the room from the internal subscription table.
|
||
|
||
Returns True if an active subscription was found and unsubscribed,
|
||
False if the room was not subscribed.
|
||
"""
|
||
sub_id = self._sub_rooms.pop(room_id, None)
|
||
if sub_id is None:
|
||
return False
|
||
if self.connected and self.sock:
|
||
try:
|
||
self._send_json({"msg": "unsub", "id": sub_id})
|
||
except Exception:
|
||
pass
|
||
return True
|
||
|
||
def subscribe_room_events(self) -> Optional[str]:
|
||
"""A1b: Subscribe to stream-notify-room for rooms-changed events.
|
||
|
||
Rocket.Chat sendet rooms-changed Events wenn der Bot einem
|
||
neuen Raum hinzugefügt wird (roomMemberAdded) oder sich die
|
||
Raumliste ändert.
|
||
|
||
Returns:
|
||
Subscription-ID oder None wenn nicht connected.
|
||
"""
|
||
if not self.connected:
|
||
return None
|
||
sub_id = f"sub{self._next_sub_id}"
|
||
self._next_sub_id += 1
|
||
# Rocket.Chat stream-notify-room: erster Param = user-id/event-name
|
||
# __my_messages__ ist der Fallback, der für den aktuellen User funktioniert
|
||
self._send_json({
|
||
"msg": "sub",
|
||
"name": "stream-notify-room",
|
||
"params": ["__my_messages__/rooms-changed", "rooms-changed", False],
|
||
"id": sub_id,
|
||
})
|
||
logger.debug("DDP: Subscribed to stream-notify-room (rooms-changed) — sub_id=%s", sub_id)
|
||
return sub_id
|
||
|
||
def _handle_ddp_message(self, data: dict) -> None:
|
||
"""A1b: Parse stream-notify-room events and dispatch to callback.
|
||
|
||
Extrahiert rooms-changed Events und ruft _on_room_event auf.
|
||
|
||
Args:
|
||
data: Die geparste DDP-JSON-Message.
|
||
"""
|
||
if self._on_room_event is None:
|
||
return
|
||
|
||
fields = data.get("fields", {})
|
||
event_name = fields.get("eventName", "")
|
||
|
||
if event_name != "rooms-changed":
|
||
return
|
||
|
||
args = fields.get("args", [])
|
||
if not args or not isinstance(args, list) or len(args) < 2:
|
||
return
|
||
|
||
room_id = args[0]
|
||
room_data = args[1] if isinstance(args[1], dict) else {}
|
||
|
||
event = {
|
||
"room_id": room_id,
|
||
"name": room_data.get("name", ""),
|
||
"type": room_data.get("type", "c"),
|
||
}
|
||
logger.debug("DDP: rooms-changed event — room=%s, name=%s, type=%s",
|
||
room_id[:12], event["name"], event["type"])
|
||
self._on_room_event(event)
|
||
|
||
def _handle_result_message(self, data: dict) -> None:
|
||
"""P1-2 O-2: Resolve pending Futures when a DDP result message arrives.
|
||
|
||
Called from the reader thread (PURE SYNC — no asyncio calls here).
|
||
Looks up the msg_id in _pending_results and resolves the Future
|
||
with the result or error.
|
||
|
||
Args:
|
||
data: The parsed DDP JSON message with msg='result'.
|
||
"""
|
||
msg_id = data.get("id", "")
|
||
if not msg_id:
|
||
return
|
||
|
||
with self._result_lock:
|
||
future = self._pending_results.pop(msg_id, None)
|
||
|
||
if future is None:
|
||
# No pending future for this msg_id — likely a result for
|
||
# a fire-and-forget call (legacy set_status) or already timed out
|
||
return
|
||
|
||
if future.done():
|
||
# Already resolved (e.g., by timeout sweep)
|
||
return
|
||
|
||
if "error" in data:
|
||
future.set_exception(DDPServerError(data["error"]))
|
||
else:
|
||
result = data.get("result", True)
|
||
future.set_result(result)
|
||
|
||
# P0: Extract RC username from DDP login response
|
||
# The login result contains {"id": <userId>, "username": <rcUsername>, ...}
|
||
# We need the real RC username (not the env email) for the own-message filter.
|
||
if msg_id == "ddplogin" and isinstance(result, dict):
|
||
resolved = result.get("username")
|
||
if resolved:
|
||
self._rc_username = resolved
|
||
logger.info("[ddp] Resolved RC username from login: %s", resolved)
|
||
|
||
def get_logged_in_username(self) -> Optional[str]:
|
||
"""Return the RC username resolved from the DDP login response.
|
||
|
||
Returns None if the login response has not been processed yet
|
||
(e.g., during reconnect with resume token, or before the first
|
||
result message arrives).
|
||
|
||
Returns:
|
||
The resolved RC username string, or None.
|
||
"""
|
||
return self._rc_username
|
||
|
||
def set_status(self, status: str) -> bool:
|
||
"""Set the user presence status via DDP (fire-and-forget, no await).
|
||
|
||
.. deprecated::
|
||
Use :meth:`set_status_async` for await-semantics with timeout
|
||
and error handling. This method remains for legacy callers
|
||
(on_connected callback, idle timer) that don't need the result.
|
||
|
||
Returns:
|
||
True if the frame was sent, False if not connected.
|
||
"""
|
||
if not self.connected:
|
||
return False
|
||
method = "UserPresence:setDefaultStatus"
|
||
self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"})
|
||
return True
|
||
|
||
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||
"""Bind the asyncio event loop for async operations.
|
||
|
||
Called by the adapter after the event loop is running.
|
||
The loop reference is used by set_status_async to bridge
|
||
between the DDP reader thread and the asyncio world.
|
||
|
||
Args:
|
||
loop: The running asyncio event loop.
|
||
"""
|
||
self._loop = loop
|
||
|
||
async def set_status_async(self, status: str, timeout: float = 2.0) -> bool:
|
||
"""Set the user presence status via DDP with await-semantics.
|
||
|
||
Sends a DDP method call and waits for the corresponding result
|
||
message from the server. Uses a Future registered in
|
||
_pending_results that the reader thread resolves when the
|
||
result message arrives.
|
||
|
||
Args:
|
||
status: Rocket.Chat status ('online', 'away', 'busy').
|
||
timeout: Maximum seconds to wait for the result (default 2.0).
|
||
|
||
Returns:
|
||
True if the server confirmed the status change.
|
||
|
||
Raises:
|
||
DDPNotConnected: If the DDP client is not connected.
|
||
DDPTimeout: If no result message arrives within timeout.
|
||
DDPServerError: If the server returns an error for the call.
|
||
"""
|
||
if not self.connected:
|
||
raise DDPNotConnected("DDP client is not connected")
|
||
|
||
# Generate unique msg_id with sequence counter to prevent collisions
|
||
with self._result_lock:
|
||
self._msg_seq += 1
|
||
msg_id = f"st{int(time.time() * 1000)}_{self._msg_seq}"
|
||
|
||
# Create Future and register it
|
||
future: concurrent.futures.Future = concurrent.futures.Future()
|
||
with self._result_lock:
|
||
self._pending_results[msg_id] = future
|
||
|
||
try:
|
||
# Send the DDP method call
|
||
method = "UserPresence:setDefaultStatus"
|
||
self._send_json({
|
||
"msg": "method",
|
||
"method": method,
|
||
"params": [status],
|
||
"id": msg_id,
|
||
})
|
||
|
||
# Await the future — bridge concurrent.Future to asyncio with timeout
|
||
result = await asyncio.wait_for(
|
||
asyncio.wrap_future(future),
|
||
timeout=timeout,
|
||
)
|
||
|
||
# If we get here, the reader thread resolved the future
|
||
if result is False:
|
||
raise DDPServerError({"error": "server returned false"})
|
||
return True
|
||
|
||
except asyncio.TimeoutError:
|
||
# Clean up the pending future
|
||
with self._result_lock:
|
||
self._pending_results.pop(msg_id, None)
|
||
raise DDPTimeout(
|
||
f"setDefaultStatus('{status}') timed out after {timeout}s"
|
||
)
|
||
except (DDPTimeout, DDPServerError, DDPNotConnected):
|
||
# Re-raise our own exceptions without wrapping
|
||
with self._result_lock:
|
||
self._pending_results.pop(msg_id, None)
|
||
raise
|
||
except Exception:
|
||
# Clean up on any other exception
|
||
with self._result_lock:
|
||
self._pending_results.pop(msg_id, None)
|
||
raise
|
||
|
||
def _sweep_pending_results(self) -> None:
|
||
"""Sweep through _pending_results and cancel Futures older than 2s.
|
||
|
||
Called periodically from the reader loop to prevent memory leaks
|
||
from method calls whose result messages never arrive.
|
||
"""
|
||
now = time.time()
|
||
stale_ids = []
|
||
with self._result_lock:
|
||
for msg_id, future in list(self._pending_results.items()):
|
||
# msg_id format: st<TIMESTAMP_MS>_<SEQ>
|
||
# Extract timestamp from msg_id
|
||
try:
|
||
ts_part = msg_id[2:].split("_")[0] # strip 'st' prefix
|
||
ts_ms = int(ts_part)
|
||
ts_s = ts_ms / 1000.0
|
||
if now - ts_s > 2.0:
|
||
stale_ids.append(msg_id)
|
||
except (ValueError, IndexError):
|
||
# Malformed msg_id — clean it up
|
||
stale_ids.append(msg_id)
|
||
|
||
for msg_id in stale_ids:
|
||
future = self._pending_results.pop(msg_id, None)
|
||
if future is not None and not future.done():
|
||
future.cancel()
|
||
|
||
if stale_ids:
|
||
logger.debug(
|
||
"DDP: Swept %d stale pending results (age > 2s)",
|
||
len(stale_ids),
|
||
)
|
||
|
||
def _cancel_pending_results(self) -> None:
|
||
"""B1: Resolve all pending Futures with DDPNotConnected and clear the store.
|
||
|
||
Called on disconnect and reader-loop exit to prevent memory leaks
|
||
from Futures that would otherwise hang forever waiting for a result
|
||
message that will never arrive.
|
||
"""
|
||
with self._result_lock:
|
||
for msg_id, future in list(self._pending_results.items()):
|
||
if not future.done():
|
||
future.set_exception(
|
||
DDPNotConnected("DDP connection closed — pending result cancelled")
|
||
)
|
||
self._pending_results.clear()
|
||
|
||
def disconnect(self):
|
||
self._running = False
|
||
if self.sock:
|
||
try:
|
||
self.sock.close()
|
||
except Exception:
|
||
pass
|
||
self.sock = None
|
||
self.connected = False
|
||
# B1: Cancel all pending Futures so callers (e.g. PulseController)
|
||
# get DDPNotConnected and can fall back to REST instead of hanging.
|
||
self._cancel_pending_results()
|
||
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
|
||
# B2: Exponential backoff state for reconnect attempts
|
||
self._reconnect_backoff = 0 # number of consecutive failures
|
||
# 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] = {}
|
||
# FIX 2 (P0): ISSUE 3 — Pending Clarify Dispatch Slot
|
||
# {room_id: {text, username, msg_id, msg_obj, is_button_response}}
|
||
self._pending_clarify_dispatch: Dict[str, dict] = {}
|
||
# Auto-Onboarding v2: structured interview state
|
||
self._onboarding_state: Dict[str, Any] = {}
|
||
# FIX E: Raum-Map Summary für System-Prompt-Injection via chat_topic.
|
||
# Wird bei connect() und nach jeder Raum-Map-Änderung (M13 GC, Onboarding)
|
||
# neu gebaut. Der Gateway-Core rendert chat_topic als "**Channel Topic:**"
|
||
# im System-Prompt — der Agent sieht die Raum-Map also BEI JEDEM START.
|
||
self._room_map_summary: str = ""
|
||
# R5: Inline-Command-Registry für ::-Befehle
|
||
from archivar.inline_commands import InlineCommandRegistry
|
||
self._inline_commands = InlineCommandRegistry()
|
||
self._register_inline_commands()
|
||
# R5: Username des letzten Inline-Command-Aufrufs (für ::reasoning
|
||
# Session-Key-Ableitung). Wird in _handle_inline_command gesetzt.
|
||
self._last_inline_username: str = ""
|
||
# R5: Raum-Name des letzten Inline-Command-Aufrufs (für ::compress
|
||
# SessionSource-Aufbau). Wird in _handle_inline_command gesetzt.
|
||
self._last_inline_room_name: str = ""
|
||
|
||
# Post-Crash-Forensik: Flag verhindert Doppel-Aufrufe bei Reconnects
|
||
self._crash_forensic_done = False
|
||
|
||
# V9: PresenceEngine — Schachuhr-Architektur (Hook-basiert)
|
||
try:
|
||
from archivar.presence_engine import PresenceEngine
|
||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||
_away_grace_s = float(os.getenv("ROCKETCHAT_PRESENCE_AWAY_GRACE_S", "2.0"))
|
||
self._presence_engine = PresenceEngine(
|
||
rest=self.rest,
|
||
enabled=_presence_enabled,
|
||
away_grace_s=_away_grace_s,
|
||
use_ddp=True,
|
||
adapter=self,
|
||
)
|
||
# V9: Kein PulseController, kein DDP, kein DetectionTimer mehr.
|
||
# Hook-Registrierung erfolgt in plugin/__init__.py via ctx.register_hook().
|
||
if self.archivar is not None:
|
||
self.archivar.set_presence_engine(self._presence_engine)
|
||
logger.info(
|
||
"[rocketchat] V9: PresenceEngine initialisiert (enabled=%s, away_grace=%.1fs)",
|
||
_presence_enabled,
|
||
_away_grace_s,
|
||
)
|
||
except Exception as e:
|
||
logger.error(
|
||
"[rocketchat] V9: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||
e,
|
||
)
|
||
self._presence_engine = None # Graceful degradation
|
||
|
||
def _build_room_map_summary(self) -> str:
|
||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||
|
||
Wird via SessionSource.chat_topic in den System-Prompt injiziert.
|
||
Der Gateway-Core rendert chat_topic als "**Channel Topic:**" Block.
|
||
|
||
Returns:
|
||
Formatierter String mit allen Räumen (Name, ID, Thema, Keywords,
|
||
Catch-All-Marker). Leerer String wenn keine Raum-Map geladen ist.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return ""
|
||
room_map = getattr(self.archivar, '_room_map', None)
|
||
if room_map is None or not room_map.rooms:
|
||
return ""
|
||
|
||
lines = ["Rocket.Chat Raum-Map:"]
|
||
for i, (rid, entry) in enumerate(room_map.rooms.items(), 1):
|
||
catch_all_marker = " ★ CATCH-ALL" if entry.catch_all else ""
|
||
lines.append(
|
||
f" {i}. {entry.name} ({rid}){catch_all_marker} — "
|
||
f"Thema: {entry.theme}"
|
||
)
|
||
# Keywords 100% (exakte Treffer)
|
||
if entry.keywords_100:
|
||
kw100 = ", ".join(entry.keywords_100)
|
||
lines.append(f" Keywords 100%: {kw100}")
|
||
# Keywords Kontext (kontextabhängige Treffer)
|
||
if entry.keywords_context:
|
||
kwctx = ", ".join(entry.keywords_context)
|
||
lines.append(f" Keywords Kontext: {kwctx}")
|
||
return "\n".join(lines)
|
||
|
||
def _on_ddp_connected(self) -> None:
|
||
"""Callback when DDP connection is established.
|
||
|
||
Sets initial online status and binds DDP to PulseController
|
||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||
|
||
P1b: Starts DetectionTimer after DDP connection is established
|
||
to prevent race condition with gateway_state.json.
|
||
|
||
P-063 (STETS-GELB Fix 1): Der Initial-Message-Reset wurde hier
|
||
entfernt und an das ENDE von connect() verschoben. Grund: dieser
|
||
Callback feuert im DDP-Reader-Thread, aber der REST-Login
|
||
(rest.login()) ist zu diesem Zeitpunkt bereits abgeschlossen —
|
||
trotzdem war der Reset hier falsch platziert, weil er VOR dem
|
||
vollständigen connect()-Abschluss (PresenceEngine-Init, Hook-
|
||
Registrierung) lief. Der Reset läuft jetzt deterministisch am
|
||
Ende von connect(), NACH rest.login() und NACH DDP-Connect.
|
||
"""
|
||
if self.ddp:
|
||
# B3: Bewusst sync — first status after connect does not need
|
||
# await-confirmation. PulseController takes over with
|
||
# set_status_async on the next tick (1.5s). This avoids a
|
||
# 2s-await-wait during the critical connect path.
|
||
self.ddp.set_status("online")
|
||
|
||
# V10: DDP-Bindung erfolgt intern via DDPFirstSender in PresenceEngine.__init__.
|
||
# Kein externes bind_ddp/start_detection mehr nötig (V9-Refactor).
|
||
|
||
def _on_ddp_room_event(self, event: dict) -> None:
|
||
"""A1b: Callback für DDP rooms-changed Events.
|
||
|
||
Wird vom DDPClient._handle_ddp_message aufgerufen wenn ein
|
||
rooms-changed Event empfangen wird. Prüft ob der Raum neu ist
|
||
und startet ggf. das Onboarding-Interview.
|
||
|
||
Args:
|
||
event: Dict mit {"room_id": str, "name": str, "type": str}.
|
||
"""
|
||
room_id = event.get("room_id", "")
|
||
room_name = event.get("name", "")
|
||
room_type = event.get("type", "c")
|
||
|
||
if not room_id:
|
||
return
|
||
|
||
# Nur im Multiroom-Modus mit aktivem Archivar
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return
|
||
|
||
# Prüfe ob Onboarding bereits läuft (P-065: _is_onboarding_running)
|
||
if self._is_onboarding_running()[0]:
|
||
logger.debug("[rocketchat] A1b: Onboarding bereits aktiv — DDP-Event ignoriert: room=%s", room_id[:12])
|
||
return
|
||
|
||
# P1-3: Lock prüfen — symmetrisch zu lazy_onboarding_check
|
||
# Verhindert doppelte Interviews für denselben Raum
|
||
from archivar.onboarding import is_onboarding_locked
|
||
if is_onboarding_locked(room_id):
|
||
logger.debug("[rocketchat] A1b: Onboarding-Lock aktiv — DDP-Event ignoriert: room=%s", room_id[:12])
|
||
return
|
||
|
||
# Prüfe ob der Raum in der Map fehlt (Delta-Check)
|
||
missing = self.archivar.check_room_map_completeness_delta(
|
||
room_id=room_id,
|
||
room_name=room_name,
|
||
room_type=room_type,
|
||
)
|
||
|
||
if missing is None:
|
||
logger.debug("[rocketchat] A1b: Raum bereits in Map oder ignoriert: room=%s", room_id[:12])
|
||
return
|
||
|
||
# Telemetrie: DDP-Event-Pfad
|
||
logger.info(
|
||
"[rocketchat] A1b: DDP-Event-Pfad — neuer Raum entdeckt: "
|
||
"room=%s, name=%s, type=%s",
|
||
room_id[:12], room_name, room_type,
|
||
)
|
||
|
||
# Onboarding für diesen Raum starten (asynchron, nicht blockierend)
|
||
asyncio.ensure_future(self._start_onboarding([missing]))
|
||
|
||
async def _post_message_with_retry(
|
||
self, room_id: str, text: str,
|
||
attachments: Optional[List[dict]] = None,
|
||
max_retries: int = 3,
|
||
) -> Optional[str]:
|
||
"""Send chat.postMessage with exponential backoff on HTTP 429.
|
||
|
||
Retries only on RocketChatRateLimitError (HTTP 429). All other
|
||
failures return None immediately. Uses asyncio.sleep so the
|
||
gateway listen loop is never blocked.
|
||
|
||
Retry delays: 2s, 4s, 8s.
|
||
|
||
Returns:
|
||
The message ``_id`` from the API response on success, ``None`` on failure.
|
||
V8.3.1 F1: Return message_id for target_message_id tracking.
|
||
"""
|
||
delays = [2, 4, 8]
|
||
for attempt in range(max_retries + 1):
|
||
try:
|
||
return self.rest.post_message(room_id, text, attachments=attachments)
|
||
except RocketChatRateLimitError:
|
||
if attempt < max_retries:
|
||
delay = delays[min(attempt, len(delays) - 1)]
|
||
logger.warning(
|
||
"Rate-limited (429), retry %d/%d in %ds (room=%s)",
|
||
attempt + 1, max_retries, delay, room_id[:8],
|
||
)
|
||
await asyncio.sleep(delay)
|
||
else:
|
||
logger.error(
|
||
"chat.postMessage failed after %d retries (room=%s)",
|
||
max_retries, room_id[:8],
|
||
)
|
||
return None
|
||
except Exception as e:
|
||
logger.debug("chat.postMessage failed (non-429): %s", e)
|
||
return None
|
||
return None
|
||
|
||
def _sync_room_map_with_membership(self) -> None:
|
||
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
||
|
||
Läuft beim Gateway-Start NACH REST get_rooms(), VOR DDP-Subscription
|
||
und VOR Archivar-Init (B9). Verhindert Ghost-Subscriptions in Räumen,
|
||
aus denen der Agent entfernt wurde.
|
||
|
||
**Reihenfolge-Garantie M13 → B9:**
|
||
|
||
M13 entfernt Räume, in denen der Agent nicht mehr Mitglied ist.
|
||
B9 (Auto-Onboarding) triggert für Räume, die in der Mitgliedschaft
|
||
sind, aber NICHT in room-map.json. Da B9 NACH M13 läuft, sind
|
||
neu onboardete Räume in room-map.json, BEVOR M13 beim nächsten
|
||
Gateway-Start läuft. M13 kann also keine Räume löschen, die B9
|
||
gerade onboardiert hat — die Reihenfolge ist korrekt.
|
||
|
||
Ablauf:
|
||
1. Aktuelle Mitgliedschaft aus self._rooms (REST get_rooms) extrahieren
|
||
2. room-map.json laden (falls vorhanden)
|
||
3. Räume in room-map.json aber NICHT in Mitgliedschaft → entfernen
|
||
4. Bereinigte room-map.json speichern
|
||
4a. self._subscribed_rooms, self._room_info + DDP unsub bereinigen
|
||
5. FAISS-Index nach Bereinigung neu bauen (falls Archivar aktiv)
|
||
6. KeywordBooster-Mapping neu bauen (nur gültige Räume)
|
||
7. ArchivarState bereinigen (stay_decision, keyword_weights, sticky, overrides, promotion)
|
||
8. Onboarding _stay_tracker für gelöschte Räume entfernen
|
||
|
||
DM-Räume werden NIEMALS entfernt (DM existiert immer).
|
||
Idempotent: bei jedem Gateway-Start ausgeführt.
|
||
"""
|
||
# ── 1. Extrahiere aktuelle Mitgliedschafts-Room-IDs ────────────
|
||
member_room_ids: set = set()
|
||
dm_room_ids: set = set()
|
||
for room in self._rooms:
|
||
rid = room.get("id", "")
|
||
if not rid:
|
||
continue
|
||
member_room_ids.add(rid)
|
||
if room.get("type") == "d":
|
||
dm_room_ids.add(rid)
|
||
|
||
if not member_room_ids:
|
||
logger.warning("[rocketchat] M13: Keine Mitgliedschaftsdaten — GC übersprungen")
|
||
return
|
||
|
||
logger.info(
|
||
"[rocketchat] M13: Mitglied in %d Räumen (%d DM, %d Channels/Groups)",
|
||
len(member_room_ids),
|
||
len(dm_room_ids),
|
||
len(member_room_ids) - len(dm_room_ids),
|
||
)
|
||
|
||
# ── 2. Lade room-map.json ──────────────────────────────────────
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
|
||
map_path = Path(ROOM_MAP_PATH)
|
||
if not map_path.exists():
|
||
logger.info("[rocketchat] M13: Keine room-map.json vorhanden — GC übersprungen")
|
||
return
|
||
|
||
try:
|
||
room_map = RoomMap.load(map_path)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: Konnte room-map.json nicht laden: %s — GC übersprungen", e)
|
||
return
|
||
|
||
# B8: excluded_room_ids für DDP-Subscription-Filter speichern
|
||
self._excluded_room_ids = room_map.excluded_room_ids
|
||
if self._excluded_room_ids:
|
||
logger.info(
|
||
"[rocketchat] B8: %d excluded rooms geladen: %s",
|
||
len(self._excluded_room_ids),
|
||
", ".join(sorted(self._excluded_room_ids)),
|
||
)
|
||
|
||
map_room_ids = set(room_map.rooms.keys())
|
||
logger.info(
|
||
"[rocketchat] M13: room-map.json enthält %d Räume",
|
||
len(map_room_ids),
|
||
)
|
||
|
||
# ── 3. Finde Räume zum Entfernen ───────────────────────────────
|
||
# Raum in room-map.json aber NICHT in Mitgliedschaft → entfernen
|
||
# AUSSER: DM-Räume (werden nie entfernt)
|
||
rooms_to_remove: set = set()
|
||
for rid in map_room_ids:
|
||
if rid in member_room_ids:
|
||
continue # Noch Mitglied → behalten
|
||
if rid in dm_room_ids:
|
||
continue # DM → nie entfernen
|
||
# Prüfe ob es ein DM ist (auch wenn nicht in aktuellen rooms)
|
||
entry = room_map.get_room_by_id(rid)
|
||
if entry and entry.name.startswith("DM "):
|
||
logger.info(
|
||
"[rocketchat] M13: DM-Raum '%s' (%s…) wird nie entfernt",
|
||
entry.name, rid[:8],
|
||
)
|
||
continue
|
||
rooms_to_remove.add(rid)
|
||
|
||
if not rooms_to_remove:
|
||
logger.info("[rocketchat] M13: Alle %d Räume in room-map.json sind noch aktuell — nichts zu bereinigen", len(map_room_ids))
|
||
return
|
||
|
||
# ── 4. Entferne verwaiste Räume ─────────────────────────────────
|
||
removed_names: list = []
|
||
for rid in sorted(rooms_to_remove):
|
||
entry = room_map.get_room_by_id(rid)
|
||
removed_names.append(
|
||
f"'{entry.name}' ({rid[:8]}…)" if entry else f"'?' ({rid[:8]}…)"
|
||
)
|
||
logger.info(
|
||
"[rocketchat] M13: Entferne %d verwaiste Räume aus room-map.json: %s",
|
||
len(rooms_to_remove),
|
||
", ".join(removed_names),
|
||
)
|
||
|
||
for rid in rooms_to_remove:
|
||
entry = room_map.get_room_by_id(rid)
|
||
room_name = entry.name if entry else rid[:12] + "…"
|
||
del room_map._rooms[rid]
|
||
logger.info(
|
||
"[rocketchat] M13: Raum '%s' (%s…) entfernt — nicht mehr Mitglied",
|
||
room_name, rid[:8],
|
||
)
|
||
|
||
# ── 4a. Adapter-Subscriptions + DDP bereinigen ──────────────────
|
||
# P2: self._subscribed_rooms und self._room_info müssen ebenfalls
|
||
# bereinigt werden, sonst läuft der Archivar mit Geister-Subscriptions
|
||
# weiter und der Adapter hält alte Subscription-IDs.
|
||
# P3: DDP unsub für jeden entfernten Raum, damit der Server keine
|
||
# Events mehr für Räume streamt, aus denen der Agent entfernt wurde.
|
||
for rid in rooms_to_remove:
|
||
entry = room_map.get_room_by_id(rid)
|
||
room_name = entry.name if entry else "?"
|
||
if rid in self._subscribed_rooms:
|
||
self._subscribed_rooms.discard(rid)
|
||
logger.info(
|
||
"[rocketchat] M13: _subscribed_rooms bereinigt — '%s' (%s…)",
|
||
room_name, rid[:8],
|
||
)
|
||
if rid in self._room_info:
|
||
del self._room_info[rid]
|
||
logger.info(
|
||
"[rocketchat] M13: _room_info bereinigt — '%s' (%s…)",
|
||
room_name, rid[:8],
|
||
)
|
||
if self.ddp is not None:
|
||
unsubbed = self.ddp.unsubscribe(rid)
|
||
if unsubbed:
|
||
logger.info(
|
||
"[rocketchat] M13: DDP unsub — '%s' (%s…)",
|
||
room_name, rid[:8],
|
||
)
|
||
|
||
# ── 5. Bereinigte Map speichern ────────────────────────────────
|
||
try:
|
||
RoomMap.save(room_map, map_path)
|
||
logger.info(
|
||
"[rocketchat] M13: Bereinigte room-map.json gespeichert (%d Räume, %d entfernt)",
|
||
len(room_map.rooms), len(rooms_to_remove),
|
||
)
|
||
except Exception as e:
|
||
logger.error("[rocketchat] M13: Fehler beim Speichern der bereinigten room-map.json: %s", e)
|
||
|
||
# ── 6. FAISS-Index + Booster + State + Onboarding bereinigen ──
|
||
# Nur wenn Archivar aktiv ist (Multiroom-Modus)
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
# RoomMap im Archivar neu laden, damit alle Komponenten die
|
||
# bereinigte Map sehen
|
||
self.archivar._room_map.reload(map_path)
|
||
|
||
# 6a. FAISS-Index neu bauen
|
||
if self.archivar._room_index is not None:
|
||
try:
|
||
self.archivar._room_index.build_index()
|
||
self.archivar._room_index.save()
|
||
logger.info(
|
||
"[rocketchat] M13: FAISS-Index nach GC neu gebaut (%d Vektoren)",
|
||
self.archivar._room_index.size,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: FAISS-Index-Rebuild nach GC fehlgeschlagen: %s", e)
|
||
|
||
# 6b. KeywordBooster-Mapping neu bauen
|
||
if self.archivar._booster is not None:
|
||
try:
|
||
self.archivar._booster.cleanup_orphaned_rooms(set(room_map.rooms.keys()))
|
||
logger.info("[rocketchat] M13: KeywordBooster-Mapping nach GC neu gebaut")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: KeywordBooster-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 6c. ArchivarState bereinigen
|
||
if self.archivar._state is not None:
|
||
try:
|
||
valid_ids = set(room_map.rooms.keys())
|
||
removed = self.archivar._state.cleanup_orphaned_rooms(valid_ids)
|
||
logger.info(
|
||
"[rocketchat] M13: ArchivarState bereinigt — %d orphaned Einträge entfernt",
|
||
removed,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: ArchivarState-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 6d. Onboarding _stay_tracker für gelöschte Räume bereinigen
|
||
if self.archivar._state is not None:
|
||
try:
|
||
removed_stay = self.archivar._state.cleanup_stay_tracker(set(room_map.rooms.keys()))
|
||
if removed_stay > 0:
|
||
logger.info(
|
||
"[rocketchat] M13: stay_tracker bereinigt — %d Einträge entfernt",
|
||
removed_stay,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: stay_tracker-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 6e. B5v6.5: ConversationHistory bereinigen
|
||
if self._conversation_history is not None:
|
||
try:
|
||
valid_ids = set(room_map.rooms.keys())
|
||
removed_hist = self._conversation_history.cleanup_orphaned_rooms_sync(valid_ids)
|
||
if removed_hist > 0:
|
||
logger.info(
|
||
"[rocketchat] M13: ConversationHistory bereinigt — %d orphaned Räume entfernt",
|
||
removed_hist,
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] M13: ConversationHistory-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# FIX E: Raum-Map Summary nach GC aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach M13 GC aktualisiert (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
|
||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||
"""Connect to Rocket.Chat (REST + DDP) and start listen loop.
|
||
|
||
is_reconnect: True wenn dies ein Reconnect-Versuch ist (z.B. nach
|
||
Silent-Death-Erkennung). Core ruft connect() mit diesem Keyword-Arg
|
||
auf; fehlt es → TypeError. Siehe Bug M3.
|
||
"""
|
||
# ── Post-Crash-Forensik: ALS ALLERERSTES vor REST-Login, vor DDP ──
|
||
# Läuft nur beim initialen Connect (nicht bei Reconnects).
|
||
# try/except — Forensik-Fehler blockieren NIEMALS den Gateway-Start.
|
||
if not self._crash_forensic_done and not is_reconnect:
|
||
self._crash_forensic_done = True
|
||
try:
|
||
# P-073: crash_forensics liegt als Flat-Modul im Plugin-Verzeichnis
|
||
# (Sibling von adapter.py, NICHT in archivar/). Im Gateway-Kontext
|
||
# ist das Plugin-Verzeichnis nicht zuverlässig auf sys.path — der
|
||
# bare Import `from crash_forensics import ...` schlägt mit
|
||
# ModuleNotFoundError fehl (P-022/P-023-Muster). Expliziter
|
||
# sys.path-Eintrag stellt sicher, dass das Modul auffindbar ist.
|
||
import sys as _sys
|
||
import os as _os
|
||
_plugin_dir = _os.path.dirname(_os.path.abspath(__file__))
|
||
if _plugin_dir not in _sys.path:
|
||
_sys.path.insert(0, _plugin_dir)
|
||
from crash_forensics import check_for_predecessor_crash
|
||
report = await check_for_predecessor_crash()
|
||
if report:
|
||
for line in report.splitlines():
|
||
logger.info(line)
|
||
except Exception as _forensic_exc:
|
||
logger.warning(
|
||
"[rocketchat] Crash-Forensik fehlgeschlagen (nicht blockierend): %s",
|
||
_forensic_exc,
|
||
)
|
||
# ── Ende Post-Crash-Forensik ─────────────────────────────────────
|
||
|
||
if not self.base_url or not self.user or not self.password:
|
||
logger.error("[rocketchat] Missing configuration")
|
||
return False
|
||
if not self.rest.login(self.user, self.password):
|
||
logger.error("[rocketchat] REST login failed")
|
||
return False
|
||
self._auth_token = self.rest.auth_token
|
||
self._user_id = self.rest.user_id
|
||
|
||
# A1b: Stale-Lock-Cleanup beim Gateway-Start
|
||
# Entfernt Onboarding-Locks die älter als 10 Minuten sind
|
||
# (abgestürztes Onboarding-Interview soll nicht dauerhaft blockieren)
|
||
from archivar.onboarding import cleanup_stale_locks
|
||
removed = cleanup_stale_locks()
|
||
if removed > 0:
|
||
logger.info("[rocketchat] A1b: Stale-Lock-Cleanup — %d Locks entfernt", removed)
|
||
|
||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||
self.ddp = DDPClient(
|
||
host=host,
|
||
on_connected_cb=self._on_ddp_connected,
|
||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events
|
||
)
|
||
if not self.ddp.connect_and_login(self._auth_token):
|
||
logger.error("[rocketchat] DDP connect/login failed")
|
||
return False
|
||
|
||
# P0: Resolve self.user from DDP login response (not blind from env).
|
||
# connect_and_login() returns before the async result message arrives,
|
||
# so we retry briefly until the DDP reader thread processes it.
|
||
for _retry in range(10):
|
||
resolved = self.ddp.get_logged_in_username()
|
||
if resolved:
|
||
self.user = resolved.lower()
|
||
logger.info("[rocketchat] Resolved self.user from login: %s", self.user)
|
||
break
|
||
time.sleep(0.1)
|
||
else:
|
||
# Fallback: keep the env value (ROCKETCHAT_USER)
|
||
logger.info("[rocketchat] Login username not resolved — keeping env value: %s", self.user)
|
||
|
||
self._rooms = self.rest.get_rooms()
|
||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||
|
||
# P1-2 O-2: Bind asyncio loop to DDPClient
|
||
# V10: PresenceEngine braucht kein externes bind_loop mehr (DDPFirstSender intern)
|
||
try:
|
||
loop = asyncio.get_running_loop()
|
||
self.ddp.bind_loop(loop)
|
||
logger.info(
|
||
"[rocketchat] P1-2 O-2: DDPClient async-bound (loop=%s)",
|
||
id(loop),
|
||
)
|
||
except RuntimeError:
|
||
# No running event loop (e.g., in tests) — graceful degradation
|
||
logger.info(
|
||
"[rocketchat] P1-2 O-2: DDPClient async-bound: no "
|
||
"(no running event loop)"
|
||
)
|
||
|
||
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
||
if self.ddp.connected:
|
||
room_events_sub = self.ddp.subscribe_room_events()
|
||
if room_events_sub:
|
||
logger.info("[rocketchat] A1b: Subscribed to stream-notify-room (rooms-changed) — sub_id=%s", room_events_sub)
|
||
else:
|
||
logger.warning("[rocketchat] A1b: Failed to subscribe to stream-notify-room")
|
||
|
||
# ── M13: Room-Map Garbage Collection ───────────────────────────
|
||
# Läuft VOR Subscription und VOR Archivar-Init (B9).
|
||
# Entfernt Räume aus room-map.json, in denen der Agent nicht mehr
|
||
# Mitglied ist (gekickt / verlassen). Verhindert Ghost-Subscriptions
|
||
# und Echo-Katastrophen bei Multi-Agent-Setups.
|
||
self._sync_room_map_with_membership()
|
||
# ── Ende M13 ───────────────────────────────────────────────────
|
||
|
||
for room in self._rooms:
|
||
rid = room["id"]
|
||
# B8: excluded_rooms nicht subscriben
|
||
if rid in self._excluded_room_ids:
|
||
logger.info(
|
||
"[rocketchat] Room '%s' (%s) excluded — not subscribing",
|
||
room["name"], rid,
|
||
)
|
||
continue
|
||
sub_id = self.ddp.subscribe_room(rid)
|
||
if sub_id:
|
||
self._subscribed_rooms.add(rid)
|
||
self._room_info[rid] = {"name": room["name"], "type": room["type"]}
|
||
logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], rid)
|
||
logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms))
|
||
# Build user→rooms map for virtual chat_id translation.
|
||
# Each Rocket.Chat user gets a synthetic "user:<username>" chat_id that
|
||
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
||
# session per user across all rooms, enabling shared context.
|
||
self._user_rooms.clear()
|
||
user_room_count = 0
|
||
for room in self._rooms:
|
||
rid = room["id"]
|
||
t = room["type"]
|
||
if t == "d":
|
||
# Handle Direct Message rooms
|
||
usernames = [u.lower() for u in room.get("usernames", [])]
|
||
if not usernames:
|
||
logger.warning("[rocketchat] DM room %s has no usernames field or is empty", rid)
|
||
# Try to extract usernames from room name as fallback
|
||
name = room.get("name", "")
|
||
if "DM mit " in name:
|
||
# Parse usernames from name like "DM mit andreas, bernd"
|
||
try:
|
||
user_part = name.split("DM mit ", 1)[1]
|
||
usernames = [u.strip().lower() for u in user_part.split(",")]
|
||
except Exception:
|
||
logger.debug("[rocketchat] Could not parse usernames from room name: %s", name)
|
||
|
||
for uname in usernames:
|
||
if uname and uname != (self.user or "").lower():
|
||
virt = f"user:{uname}"
|
||
if virt not in self._user_rooms:
|
||
self._user_rooms[virt] = []
|
||
if rid not in self._user_rooms[virt]:
|
||
self._user_rooms[virt].append(rid)
|
||
user_room_count += 1
|
||
else:
|
||
# For channels/groups, track rooms for potential future use
|
||
# Users can still be mentioned in these rooms
|
||
logger.debug("[rocketchat] Non-DM room %s (type: %s) tracked but not mapped to users", rid, t)
|
||
logger.info("[rocketchat] Built user-room map: %d users, %s",
|
||
len(self._user_rooms),
|
||
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
||
# Archivar initialisieren (Embedding-basierte Klassifikation)
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
try:
|
||
await self.archivar.initialize()
|
||
# Feed the actual subscribed room IDs to the router so it can
|
||
# validate targets and store unrouteable messages in doc_store.
|
||
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||
logger.info("[rocketchat] Archivar initialisiert — Thematischer Raum-Router aktiv (room-map.json)")
|
||
|
||
# FIX E: Raum-Map Summary für System-Prompt bauen
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] FIX E: Raum-Map Summary gebaut (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
|
||
# Auto-Onboarding: Prüfe, ob alle subscribed Räume in der Map sind
|
||
subscribed_with_types = {
|
||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||
for rid, info in self._room_info.items()
|
||
}
|
||
# F8: Onboarding State Machine laden (vor Bug-C-Check, damit SM-State verfügbar)
|
||
from archivar.onboarding_state import OnboardingStateMachine, OnboardingState
|
||
if not hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm = OnboardingStateMachine()
|
||
self._onboarding_sm.load()
|
||
sm = self._onboarding_sm
|
||
|
||
# P1-4: Prüfe ob ein persistierter Onboarding-State existiert
|
||
persisted_onboarding = self.archivar._state.get_onboarding_state()
|
||
if persisted_onboarding and persisted_onboarding.get("operator_room_id"):
|
||
# Bug C: Zombie-State-Validierung
|
||
# Prüfe ob der Operator-Raum noch subscribed ist und der Lock aktiv
|
||
op_room = persisted_onboarding.get("operator_room_id", "")
|
||
op_room_subscribed = op_room in self._room_info
|
||
from archivar.onboarding import is_onboarding_locked
|
||
lock_active = False
|
||
if op_room_subscribed:
|
||
# Prüfe ob mindestens ein missing_room-Lock aktiv ist
|
||
for room in persisted_onboarding.get("missing_rooms", []):
|
||
if is_onboarding_locked(room.get("room_id", "")):
|
||
lock_active = True
|
||
break
|
||
if op_room_subscribed and lock_active:
|
||
logger.info("[rocketchat] P1-4: Persistierten Onboarding-State wiederhergestellt")
|
||
self._onboarding_state = persisted_onboarding
|
||
self.archivar._stats["onboarding_active"] = True
|
||
elif sm.state == OnboardingState.ACTIVE:
|
||
# Fix 1: ACTIVE-Phase — Onboarding ist permanent fertig.
|
||
# archivar_state._onboarding_state darf leer bleiben
|
||
# (= kein laufendes Interview) — konsistent mit produktivem Pfad.
|
||
logger.info(
|
||
"[rocketchat] Bug C: Onboarding ACTIVE — archivar_state bleibt leer "
|
||
"(produktiver Pfad, kein laufendes Interview)"
|
||
)
|
||
else:
|
||
# Echte Zombie-Situation: Lock weg, Op-Raum weg,
|
||
# State noch nicht ACTIVE → State war mid-Interview.
|
||
logger.warning(
|
||
"[rocketchat] Bug C: Zombie-Onboarding-State verworfen — "
|
||
"op_room_subscribed=%s, lock_active=%s",
|
||
op_room_subscribed, lock_active,
|
||
)
|
||
self.archivar._state.clear_onboarding_state()
|
||
if sm.state == OnboardingState.ACTIVE:
|
||
logger.info("[rocketchat] F8: Onboarding bereits abgeschlossen — produktiver Pfad")
|
||
# P-054 / P-025: archivar_state.json bei Onboarding-Abschluss
|
||
# aufräumen. Verhindert stale _onboarding_state (missing_rooms,
|
||
# current_room_index) nach Gateway-Restart.
|
||
self.archivar._state.clear_onboarding_state()
|
||
elif sm.state == OnboardingState.ERROR:
|
||
logger.warning(
|
||
"[rocketchat] F8: Onboarding im ERROR-State — "
|
||
"::onboarding resume oder ::onboarding reset nötig. "
|
||
"Fehler: %s", sm._data.error_message
|
||
)
|
||
elif sm.is_active or sm.is_paused:
|
||
logger.info(
|
||
"[rocketchat] F8: Onboarding passiv fortgesetzt — state=%s, step=%s",
|
||
sm.state.value, sm.progress_text,
|
||
)
|
||
# State wiederherstellen ohne erneut zu starten
|
||
if not self.archivar._stats.get("onboarding_active", False):
|
||
self.archivar._stats["onboarding_active"] = True
|
||
# B9: Trigger-Bedingungen für Auto-Onboarding
|
||
# 1. MULTIROOM_AGENT=true (bereits geprüft durch _MULTIROOM())
|
||
# 2. Gateway findet Räume die nicht in room-map.json stehen
|
||
# 3. DM wird jetzt auch thematisch onboardet (Thema, Keywords, Catch-All)
|
||
# B9 fix (a): Idempotenz-Guard — wenn Onboarding bereits läuft, nicht erneut starten
|
||
# P-065: Verwende _is_onboarding_running() für Guard-Check
|
||
if self._is_onboarding_running()[0]:
|
||
logger.info("[rocketchat] B9: Onboarding bereits aktiv — überspringe Reconnect-Trigger")
|
||
# B9 fix (b): is_reconnect — prüfe ob neue Räume hinzugekommen sind
|
||
elif is_reconnect and self.archivar._room_map and len(self.archivar._room_map.rooms) > 0:
|
||
# Prüfe ob Räume existieren, die nicht in room-map.json stehen
|
||
subscribed_with_types = {
|
||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||
for rid, info in self._room_info.items()
|
||
}
|
||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||
if missing:
|
||
logger.info("[rocketchat] B9: Reconnect — %d neue Räume gefunden, starte Onboarding", len(missing))
|
||
asyncio.ensure_future(self._start_onboarding(missing))
|
||
else:
|
||
# Keine neuen c/p-Räume — DM könnte noch Theme brauchen
|
||
# FIX: Wenn Onboarding bereits ACTIVE, nicht erneut starten
|
||
# (verhindert Reset von onboarding.yaml bei Gateway-Neustart)
|
||
if sm.state != OnboardingState.ACTIVE:
|
||
asyncio.ensure_future(self._start_onboarding([]))
|
||
else:
|
||
logger.info("[rocketchat] Onboarding bereits ACTIVE — überspringe DM-Theme-Check")
|
||
else:
|
||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||
if missing:
|
||
logger.info("[rocketchat] B9: %d Räume fehlen in room-map.json — starte Auto-Onboarding", len(missing))
|
||
asyncio.ensure_future(self._start_onboarding(missing))
|
||
else:
|
||
# B9: Prüfe ob room-map.json leer ist (0 Räume) → trotzdem Onboarding
|
||
room_count = len(self.archivar._room_map.rooms) if self.archivar._room_map else 0
|
||
if room_count == 0:
|
||
non_dm_rooms = {rid: info for rid, info in subscribed_with_types.items()
|
||
if info.get("type") in ("c", "p")}
|
||
if non_dm_rooms:
|
||
logger.info("[rocketchat] B9: room-map.json ist leer (0 Räume) — starte Auto-Onboarding für %d Räume", len(non_dm_rooms))
|
||
all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()]
|
||
asyncio.ensure_future(self._start_onboarding(all_rooms))
|
||
else:
|
||
# Nur DM — Onboarding für DM-Theme nur wenn nicht bereits ACTIVE
|
||
if sm.state != OnboardingState.ACTIVE:
|
||
asyncio.ensure_future(self._start_onboarding([]))
|
||
else:
|
||
logger.info("[rocketchat] Onboarding bereits ACTIVE — überspringe DM-Theme-Check (leere Map)")
|
||
else:
|
||
# Map hat Räume, keine neuen — DM könnte Theme brauchen
|
||
# FIX: Wenn Onboarding bereits ACTIVE, nicht erneut starten
|
||
if sm.state != OnboardingState.ACTIVE:
|
||
asyncio.ensure_future(self._start_onboarding([]))
|
||
else:
|
||
logger.info("[rocketchat] Onboarding bereits ACTIVE — überspringe DM-Theme-Check (Map hat Räume)")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||
# ── P-064: Hook-Registrierung + _active_adapter setzen ──────────
|
||
# _register_presence_hooks() war definiert aber wurde NIE aufgerufen.
|
||
# _active_adapter war deklariert aber wurde NIE auf self gesetzt.
|
||
# Folge: PresenceEngine lief mit sync_hooks=true aber ohne Hooks.
|
||
import sys
|
||
try:
|
||
plugin_mod = sys.modules.get(__name__.rsplit(".", 1)[0])
|
||
if plugin_mod is not None:
|
||
plugin_mod._active_adapter = self
|
||
plugin_mod._register_presence_hooks()
|
||
logger.info("[rocketchat] P-064: Presence-Hooks registriert + _active_adapter gesetzt")
|
||
else:
|
||
logger.warning("[rocketchat] P-064: plugin-Modul nicht in sys.modules — Hook-Registrierung übersprungen")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P-064: Hook-Registrierung fehlgeschlagen: %s", 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)
|
||
|
||
# ── STETS-GELB Fix 1 + Fix 2 + Fix 3 ─────────────────────────────
|
||
# Läuft NACH rest.login(), NACH DDP-Connect, NACH PresenceEngine-Init
|
||
# und NACH Hook-Registrierung. auth_token + user_id sind hier garantiert
|
||
# gesetzt (rest.login() lief in Zeile 1701). Der P-063-Reset lief vorher
|
||
# im __init__/frühen Connect-Pfad mit auth_token=None → stillschweigend
|
||
# übersprungen → RC cached Bot-Default 'away' → GELB permanent.
|
||
self._reset_initial_message_and_presence()
|
||
return True
|
||
|
||
def _reset_initial_message_and_presence(self) -> None:
|
||
"""STETS-GELB Fix 1 + Fix 2: Initial-Reset + Presence-Online nach Connect.
|
||
|
||
Fix 1 (P-063-Verschiebung): Expliziter REST-Call users.setStatus mit
|
||
leerer Message, um alte Custom-Status-Messages vom vorherigen
|
||
Gateway-Prozess zu löschen. Läuft jetzt NACH rest.login() — auth_token
|
||
und user_id sind garantiert gesetzt. Das _initial_message_reset_sent-Flag
|
||
wird NUR bei erfolgreichem Call gesetzt (nicht vorher), damit ein
|
||
fehlgeschlagener Reset beim nächsten Lifecycle erneut versucht wird.
|
||
|
||
Fix 2 (setPresence): Sendet UserPresence:online (temporäre Presence)
|
||
via DDP, um RC's Idle-Detection explizit zu überschreiben. RC setzt
|
||
die Presence sonst auf 'away', weil der Bot keine Nachrichten-Aktivität
|
||
zeigt — obwohl die Engine intern GREEN_STATIC (online) meldet.
|
||
|
||
Fix 3 (Heartbeat): Startet den periodischen Presence-Heartbeat, der
|
||
bei GREEN_STATIC alle 60s UserPresence:online nachsendet, damit der
|
||
Bot nicht nach Inaktivität auf 'away' zurückfällt.
|
||
"""
|
||
engine = getattr(self, '_presence_engine', None)
|
||
if engine is None or not engine.is_enabled():
|
||
return
|
||
|
||
mediator = getattr(engine, '_mediator', None)
|
||
|
||
# ── Fix 1: P-063 Initial-Message-Reset (nur 1x pro Lifecycle) ──
|
||
if mediator is not None and not mediator._initial_message_reset_sent:
|
||
try:
|
||
if self.rest.auth_token and self.rest.user_id:
|
||
self.rest._request(
|
||
"POST",
|
||
"/api/v1/users.setStatus",
|
||
headers={
|
||
"X-Auth-Token": self.rest.auth_token,
|
||
"X-User-Id": self.rest.user_id,
|
||
},
|
||
data={"status": "online", "message": ""},
|
||
)
|
||
# Flag NUR bei Erfolg setzen (Fix 1, Punkt 4)
|
||
mediator._initial_message_reset_sent = True
|
||
logger.info(
|
||
"[rocketchat] P-063: Initial-Message-Reset gesendet "
|
||
"(users.setStatus mit leerer message, nach login)"
|
||
)
|
||
else:
|
||
logger.warning(
|
||
"[rocketchat] P-063: Initial-Message-Reset übersprungen — "
|
||
"auth_token/user_id fehlen (auth_token=%s, user_id=%s)",
|
||
bool(self.rest.auth_token), bool(self.rest.user_id),
|
||
)
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] P-063: Initial-Message-Reset fehlgeschlagen: %s", e
|
||
)
|
||
|
||
# ── Fix 2: setPresence online (Idle-Detection-Override) ──────────
|
||
try:
|
||
sent = engine.send_presence_online()
|
||
logger.debug(
|
||
"[rocketchat] STETS-GELB Fix 2: setPresence online nach Connect "
|
||
"(sent=%s)", sent,
|
||
)
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] STETS-GELB Fix 2: setPresence online fehlgeschlagen: %s", e
|
||
)
|
||
|
||
# ── Fix 3: Presence-Heartbeat starten ────────────────────────────
|
||
try:
|
||
engine.start_heartbeat()
|
||
logger.debug("[rocketchat] STETS-GELB Fix 3: Presence-Heartbeat gestartet")
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] STETS-GELB Fix 3: Heartbeat-Start fehlgeschlagen: %s", e
|
||
)
|
||
|
||
def _is_onboarding_phase_active(self) -> tuple:
|
||
"""P-054: Zentrale Property für Onboarding-Phasen-Erkennung.
|
||
|
||
Kombiniert ALLE State-Quellen:
|
||
- onboarding.yaml (OnboardingStateMachine)
|
||
- archivar._stats['onboarding_active'] (In-Memory)
|
||
- archivar_state._onboarding_state (Disk-State)
|
||
|
||
Returns:
|
||
(is_active: bool, operator_room_id: str, reason: str)
|
||
is_active = True wenn Onboarding läuft (IN_PROGRESS/PAUSED)
|
||
oder abgeschlossen ist (ACTIVE).
|
||
|
||
P-065: Diese Methode ist jetzt ein Legacy-Wrapper.
|
||
Verwende _is_onboarding_running() für Guard-Checks
|
||
und _is_onboarding_completed() für ONBOARD:-Prefix-Erkennung.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return (False, "", "no_multiroom_or_archivar")
|
||
|
||
# Lokaler Import — OnboardingState wird in connect() importiert
|
||
from archivar.onboarding_state import OnboardingState
|
||
|
||
# Quelle 1: OnboardingStateMachine (onboarding.yaml)
|
||
sm = getattr(self, '_onboarding_sm', None)
|
||
sm_active = False
|
||
sm_operator_room = ""
|
||
if sm is not None:
|
||
try:
|
||
sm_state = sm.state
|
||
# P-065: ACTIVE ist NICHT mehr in sm_active enthalten.
|
||
# _is_onboarding_running() ist der korrekte Guard.
|
||
sm_active = sm_state in (
|
||
OnboardingState.AWAITING_ROOM,
|
||
OnboardingState.AWAITING_INTENT,
|
||
OnboardingState.AWAITING_TEST,
|
||
OnboardingState.PAUSED,
|
||
)
|
||
sm_operator_room = getattr(sm._data, 'operator_room_id', '') or ''
|
||
except Exception:
|
||
pass
|
||
|
||
# Quelle 2: archivar._stats (In-Memory, nur True bei mid-Interview)
|
||
stats_active = self.archivar._stats.get("onboarding_active", False)
|
||
|
||
# Kombiniert: aktiv wenn SM aktiv ODER stats aktiv
|
||
is_active = sm_active or stats_active
|
||
|
||
# operator_room_id: Priorität SM (YAML) > In-Memory
|
||
operator_room_id = sm_operator_room or self._onboarding_state.get("operator_room_id", "")
|
||
|
||
reason = "sm_active" if sm_active else ("stats_active" if stats_active else "inactive")
|
||
return (is_active, operator_room_id, reason)
|
||
|
||
def _is_onboarding_running(self) -> tuple:
|
||
"""P-065: Guard-Check — läuft gerade ein Onboarding-Interview?
|
||
|
||
Returns True NUR bei aktiven Interview-Phasen:
|
||
IN_PROGRESS, AWAITING_ROOM, AWAITING_INTENT, AWAITING_TEST, PAUSED
|
||
|
||
Returns False bei: ACTIVE (abgeschlossen), COMPLETED, ERROR, NONE
|
||
|
||
Verwendung: Nachrichten-Guards, DDP-Event-Blocker,
|
||
Lazy-Onboarding-Trigger — überall wo Nachrichten blockiert
|
||
werden sollen, solange ein Interview läuft.
|
||
|
||
Returns:
|
||
(is_running: bool, operator_room_id: str, reason: str)
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return (False, "", "no_multiroom_or_archivar")
|
||
|
||
from archivar.onboarding_state import OnboardingState
|
||
|
||
sm = getattr(self, '_onboarding_sm', None)
|
||
sm_running = False
|
||
sm_operator_room = ""
|
||
if sm is not None:
|
||
try:
|
||
sm_state = sm.state
|
||
sm_running = sm_state in (
|
||
OnboardingState.AWAITING_ROOM,
|
||
OnboardingState.AWAITING_INTENT,
|
||
OnboardingState.AWAITING_TEST,
|
||
OnboardingState.PAUSED,
|
||
)
|
||
sm_operator_room = getattr(sm._data, 'operator_room_id', '') or ''
|
||
except Exception:
|
||
pass
|
||
|
||
stats_active = self.archivar._stats.get("onboarding_active", False)
|
||
is_running = sm_running or stats_active
|
||
operator_room_id = sm_operator_room or self._onboarding_state.get("operator_room_id", "")
|
||
reason = "sm_running" if sm_running else ("stats_active" if stats_active else "not_running")
|
||
return (is_running, operator_room_id, reason)
|
||
|
||
def _is_onboarding_completed(self) -> tuple:
|
||
"""P-065: ONBOARD:-Prefix-Erkennung — ist Onboarding abgeschlossen?
|
||
|
||
Returns True NUR bei: ACTIVE, COMPLETED
|
||
(Onboarding wurde durchlaufen, ONBOARD:-Prefix soll erkannt werden)
|
||
|
||
Returns False bei: IN_PROGRESS, AWAITING_ROOM, AWAITING_INTENT,
|
||
AWAITING_TEST, PAUSED, ERROR, NONE
|
||
|
||
Verwendung: ONBOARD:-Prefix-Erkennung nach Gateway-Restart,
|
||
wenn onboarding.yaml auf ACTIVE steht aber kein Interview läuft.
|
||
|
||
Returns:
|
||
(is_completed: bool, operator_room_id: str, reason: str)
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return (False, "", "no_multiroom_or_archivar")
|
||
|
||
from archivar.onboarding_state import OnboardingState
|
||
|
||
sm = getattr(self, '_onboarding_sm', None)
|
||
sm_completed = False
|
||
sm_operator_room = ""
|
||
if sm is not None:
|
||
try:
|
||
sm_state = sm.state
|
||
sm_completed = sm_state in (
|
||
OnboardingState.ACTIVE,
|
||
)
|
||
sm_operator_room = getattr(sm._data, 'operator_room_id', '') or ''
|
||
except Exception:
|
||
pass
|
||
|
||
operator_room_id = sm_operator_room or self._onboarding_state.get("operator_room_id", "")
|
||
reason = "sm_completed" if sm_completed else "not_completed"
|
||
return (sm_completed, operator_room_id, reason)
|
||
|
||
async def _reconnect_ddp(self) -> bool:
|
||
"""Bug 7: DDP-Reconnect mit M13 GC.
|
||
|
||
Ersetzt DDPClient.reconnect_and_restore(), die alte Subscriptions
|
||
blind resubscribed hat und M13 GC umging. Diese Methode:
|
||
1. Trennt alte DDP-Verbindung
|
||
2. Verbindet DDP neu (connect_and_login)
|
||
3. Holt aktuelle Mitgliedschaft via REST get_rooms()
|
||
4. Führt M13 GC durch (_sync_room_map_with_membership)
|
||
5. Subscribed nur Räume, in denen der Agent aktuell Mitglied ist
|
||
6. Aktualisiert Archivar subscribed_room_ids
|
||
|
||
Returns True bei Erfolg, False bei Fehler.
|
||
"""
|
||
if not self._auth_token:
|
||
logger.error("[rocketchat] _reconnect_ddp: Kein auth token")
|
||
return False
|
||
|
||
# A1b: Stale-Lock-Cleanup bei Reconnect (F6 Re-Review Fix 1)
|
||
# Ohne Gateway-Restart müssen stale Locks auch bereinigt werden.
|
||
from archivar.onboarding import cleanup_stale_locks
|
||
removed = cleanup_stale_locks()
|
||
if removed > 0:
|
||
logger.info("[rocketchat] A1b: Stale-Lock-Cleanup bei Reconnect — %d Locks entfernt", removed)
|
||
|
||
# 1. Alte DDP-Verbindung trennen
|
||
if self.ddp:
|
||
self.ddp.disconnect()
|
||
self.ddp = None
|
||
|
||
# 2. DDP neu verbinden
|
||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||
self.ddp = DDPClient(
|
||
host=host,
|
||
on_connected_cb=self._on_ddp_connected,
|
||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3)
|
||
)
|
||
if not self.ddp.connect_and_login(self._auth_token):
|
||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||
return False
|
||
|
||
# P0: On reconnect, only update self.user if a new username was resolved.
|
||
# Resume-token reconnects don't produce a new result message, so
|
||
# get_logged_in_username() returns None — keep the existing self.user.
|
||
resolved = self.ddp.get_logged_in_username()
|
||
if resolved:
|
||
self.user = resolved.lower()
|
||
logger.info("[rocketchat] Resolved self.user from login (reconnect): %s", self.user)
|
||
|
||
# P1-2 O-2: Re-bind asyncio loop to new DDPClient
|
||
# V10: PresenceEngine braucht kein externes bind_loop mehr (DDPFirstSender intern)
|
||
try:
|
||
loop = asyncio.get_running_loop()
|
||
self.ddp.bind_loop(loop)
|
||
logger.info(
|
||
"[rocketchat] P1-2 O-2: DDPClient async-bound (reconnect, loop=%s)",
|
||
id(loop),
|
||
)
|
||
except RuntimeError:
|
||
logger.info(
|
||
"[rocketchat] P1-2 O-2: DDPClient async-bound: no "
|
||
"(reconnect, no running event loop)"
|
||
)
|
||
|
||
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
|
||
if self.ddp.connected:
|
||
room_events_sub = self.ddp.subscribe_room_events()
|
||
if room_events_sub:
|
||
logger.info("[rocketchat] _reconnect_ddp: A1b re-subscribed to stream-notify-room — sub_id=%s", room_events_sub)
|
||
else:
|
||
logger.warning("[rocketchat] _reconnect_ddp: A1b failed to re-subscribe to stream-notify-room")
|
||
|
||
# 3. Aktuelle Mitgliedschaft via REST
|
||
self._rooms = self.rest.get_rooms()
|
||
logger.info("[rocketchat] _reconnect_ddp: REST get_rooms returned %d rooms", len(self._rooms))
|
||
|
||
# 4. M13 GC
|
||
self._sync_room_map_with_membership()
|
||
|
||
# 4b. FIX B: Raum-Map Summary nach M13 GC neu bauen
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] _reconnect_ddp: Raum-Map Summary nach M13 GC aktualisiert (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
|
||
# 5. Nur aktuelle Mitglieder-Räume subscriben (excluded_rooms ausgenommen)
|
||
self._subscribed_rooms.clear()
|
||
self._room_info.clear()
|
||
for room in self._rooms:
|
||
rid = room["id"]
|
||
# B8: excluded_rooms nicht subscriben
|
||
if rid in self._excluded_room_ids:
|
||
logger.info(
|
||
"[rocketchat] _reconnect_ddp: Room '%s' (%s) excluded — not subscribing",
|
||
room["name"], rid,
|
||
)
|
||
continue
|
||
sub_id = self.ddp.subscribe_room(rid)
|
||
if sub_id:
|
||
self._subscribed_rooms.add(rid)
|
||
self._room_info[rid] = {"name": room["name"], "type": room["type"]}
|
||
logger.info("[rocketchat] _reconnect_ddp: %d rooms subscribed", len(self._subscribed_rooms))
|
||
|
||
# 6. Archivar subscribed_room_ids aktualisieren
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
try:
|
||
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||
logger.info("[rocketchat] _reconnect_ddp: Archivar subscribed_room_ids aktualisiert")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] _reconnect_ddp: Archivar-Update fehlgeschlagen: %s", e)
|
||
|
||
return True
|
||
|
||
def _schedule_idle_timer(self) -> None:
|
||
"""Schedule idle timer to mark bot as away when inactive.
|
||
|
||
V8.6: Deaktiviert wenn PresenceEngine aktiv ist (ROCKETCHAT_PRESENCE_ENABLED=true).
|
||
Der alte _set_away-Timer kann eine DDP-Subscription-Endlosschleife auslösen
|
||
(Rainer-Warnung). Die PresenceEngine übernimmt das Status-Management.
|
||
"""
|
||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||
logger.debug("[rocketchat] V8.6: _schedule_idle_timer skipped — PresenceEngine active")
|
||
return
|
||
if self._status_timer:
|
||
self._status_timer.cancel()
|
||
|
||
def _set_away():
|
||
if self.ddp:
|
||
self.ddp.set_status("away")
|
||
|
||
self._status_timer = threading.Timer(300.0, _set_away) # 5 minutes
|
||
self._status_timer.daemon = True
|
||
self._status_timer.start()
|
||
|
||
async def _process_incoming(self, msg_obj) -> None:
|
||
"""Process an incoming message from the DDP queue."""
|
||
if not isinstance(msg_obj, dict):
|
||
return
|
||
|
||
# Check if this is a button click response by looking for specific fields.
|
||
# TWO detection paths:
|
||
# 1. Native Rocket.Chat button events (triggerId + actions + triggerSender + payload)
|
||
# 2. In-chat button responses via msg_in_chat_window, which arrive as regular
|
||
# text messages containing a question_id::choice payload (e.g. "bypass_001::Ja").
|
||
text = msg_obj.get("msg", "")
|
||
is_button_response = (
|
||
(msg_obj.get("triggerId") and
|
||
msg_obj.get("actions") and
|
||
msg_obj.get("params", {}).get("triggerSender") and
|
||
msg_obj.get("params", {}).get("payload"))
|
||
or (text and "::" in text
|
||
and not text.startswith("CLARIFY:")
|
||
and not text.startswith("ARCHIVAR_CLARIFY:")
|
||
and not text.startswith("MOVE_REQ:")
|
||
and text.split("::", 1)[0].strip() != "")
|
||
or (text and text.startswith("CLARIFY:"))
|
||
or (text and text.startswith("ARCHIVAR_CLARIFY:"))
|
||
)
|
||
|
||
# Check for CLARIFY button responses
|
||
is_clarify_response = text.startswith("CLARIFY:") if text else False
|
||
|
||
msg_id = msg_obj.get("_id", "")
|
||
room_id = msg_obj.get("rid", "")
|
||
user_info = msg_obj.get("u", {})
|
||
username = (user_info.get("username", "") or "").lower() # normalize case
|
||
msg_type = msg_obj.get("t", "")
|
||
logger.debug("Message received: room=%s, user=%s, t=%s", room_id, username, msg_type)
|
||
|
||
# NEW: Check for file attachments in the message and enrich the text
|
||
file_info = msg_obj.get("file")
|
||
attachments = msg_obj.get("attachments", [])
|
||
if file_info or attachments:
|
||
file_details = []
|
||
seen_ids = set()
|
||
base_url = self.base_url.rstrip("/")
|
||
# Process file object if present (has precise MIME type)
|
||
if file_info and isinstance(file_info, dict):
|
||
filename = file_info.get("name", "unknown")
|
||
filetype = file_info.get("type", "unknown")
|
||
file_id = file_info.get("_id")
|
||
if file_id and filename:
|
||
seen_ids.add(file_id)
|
||
download_url = f"{base_url}/file-upload/{file_id}/{filename}"
|
||
file_details.append(f"[FILE] {filename} ({filetype})\nDownload: {download_url}")
|
||
# Process attachments if present (skip duplicates already covered by file_info)
|
||
if attachments and isinstance(attachments, list):
|
||
for attachment in attachments:
|
||
if isinstance(attachment, dict) and attachment.get("type") == "file":
|
||
title = attachment.get("title", "unknown")
|
||
title_link = attachment.get("title_link", "")
|
||
if title_link:
|
||
if title_link.startswith("/"):
|
||
download_url = f"{base_url}{title_link}"
|
||
else:
|
||
download_url = f"{base_url}/{title_link}"
|
||
# Extract file_id from title_link to detect duplicates
|
||
link_id = title_link.split("/")[2] if title_link.startswith("/file-upload/") else None
|
||
if link_id and link_id in seen_ids:
|
||
continue # Already covered by precise file_info
|
||
file_details.append(f"[FILE] {title} (file)\nDownload: {download_url}")
|
||
# Add file information to message text
|
||
if file_details:
|
||
file_info_text = "\n".join(file_details)
|
||
if text:
|
||
text = f"{text}\n\n{file_info_text}"
|
||
else:
|
||
text = file_info_text
|
||
msg_obj["msg"] = text
|
||
|
||
# ── P0+P1: Reply-Quote-Stripping ──────────────────────────────────
|
||
# Verhindert Fehl-Routing durch zitierte Parent-Nachrichten.
|
||
# Zweistufig defensiv:
|
||
# 1. Attachments-basiert (Rocket.Chat Reply-Attachments)
|
||
# 2. Text-basiert (Markdown-Blockquotes, [quote]-Blöcke)
|
||
# routing_text (ohne Quote) → Archivar/Keyword-Matcher/classify_and_route
|
||
# display_text (mit Quote) → Agent-Dispatch + Conversation-History
|
||
routing_text, display_text, quote_stripped = strip_reply_quote_for_routing(
|
||
text, attachments
|
||
)
|
||
if quote_stripped:
|
||
routing_counter.increment('reply_quote_stripped')
|
||
logger.debug(
|
||
"[rocketchat] P0: Reply-Quote gestrippt — "
|
||
"routing_text=%s, display_text=%s",
|
||
routing_text[:80], display_text[:80],
|
||
)
|
||
# text bleibt display_text für Agent/History;
|
||
# routing_text wird für Archivar-Klassifikation verwendet.
|
||
# ── Ende P0+P1 ────────────────────────────────────────────────────
|
||
|
||
# Skip own messages (case-insensitive comparison)
|
||
filter_match = (username == (self.user or "").lower())
|
||
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
||
if filter_match:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Own message filtered — skipping")
|
||
routing_counter.increment('self_message_filtered')
|
||
logger.info("ROUTING BYPASS: reason=self_message_filtered, origin_room=%s", room_id)
|
||
return
|
||
if not text or not room_id:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Empty text/room_id — skipping")
|
||
return
|
||
# Skip system messages
|
||
if msg_obj.get("t"):
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: System message (t=%s) — skipping", msg_obj.get("t"))
|
||
return
|
||
|
||
logger.debug("Message passed filter: %s", msg_id)
|
||
|
||
# Update activity
|
||
self._last_activity = time.time()
|
||
room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
|
||
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
|
||
|
||
# ── P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset) ──
|
||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||
# geht _CURRENT_ORIGIN_ROOM verloren. _room_context (global dict) überlebt.
|
||
virtual_chat_id = f"user:{username}"
|
||
_set_room_context_origin(virtual_chat_id, room_id)
|
||
|
||
# ── B7: Natürliche Sprache als Hilfetrigger ──────────────────────
|
||
# Prüft VOR dem ::-Parsing und VOR dem Archivar-Routing, ob der
|
||
# Nutzer in natürlicher Sprache die Hilfeseite anfordert.
|
||
# "Ich brauche Hilfe", "Hilf mir", "help" etc. zeigen die ::hilfe-Seite.
|
||
from archivar.inline_commands import is_natural_help_request, build_help_text
|
||
if is_natural_help_request(routing_text):
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
await self._post_message_with_retry(room_id, help_text)
|
||
routing_counter.increment('natural_help_triggered')
|
||
logger.info(
|
||
"ROUTING BYPASS: reason=natural_help_triggered, origin_room=%s, text=%s",
|
||
room_id, routing_text[:60],
|
||
)
|
||
return
|
||
# ── Ende B7 Natürliche Sprache ──────────────────────────────────
|
||
|
||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||
# generischen Hermes-Agent-Onboarding erkannt werden.
|
||
inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username)
|
||
if inline_handled:
|
||
logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch")
|
||
routing_counter.increment('inline_command_handled')
|
||
logger.info("ROUTING BYPASS: reason=inline_command_handled, origin_room=%s", room_id)
|
||
return
|
||
# ── Ende R5 Inline-Command-Erkennung ────────────────────────────────
|
||
|
||
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
||
# P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht
|
||
if _MULTIROOM() and self._conversation_history is not None:
|
||
await self._conversation_history.add(room_id, "user", display_text)
|
||
|
||
# V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
# Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen)
|
||
# P1: routing_text für Topic-Extraktion (ohne Quote)
|
||
topic = routing_text[:80].replace("\n", " ").strip()
|
||
if topic:
|
||
await self._multiroom_context.add(room_id, room_name, topic)
|
||
|
||
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
|
||
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
|
||
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
|
||
_THEMATIC_TARGET_ROOM.set("")
|
||
|
||
# ── A1b: Lazy-Onboarding-Check (Fallback-Pfad) ────────────────────
|
||
# Wenn eine Nachricht aus einem Raum kommt, der nicht in room-map.json
|
||
# steht, und kein Onboarding aktiv ist → Onboarding triggern.
|
||
# Dies fängt Fälle ab, wo das DDP-Event nicht angekommen ist.
|
||
# P0-4: room_type kann "unknown" sein wenn der Raum nicht in _room_info
|
||
# ist (z.B. nach Reconnect). Der lazy_onboarding_check filtert selbst
|
||
# DM-Räume und excluded rooms — wir müssen hier nur DM ausschließen.
|
||
if (
|
||
_MULTIROOM()
|
||
and self.archivar is not None
|
||
and not self._is_onboarding_running()[0]
|
||
and room_type != "d" # P0-4: Nur DM ausschließen, "unknown" durchlassen
|
||
):
|
||
lazy_result = self.archivar.lazy_onboarding_check(
|
||
room_id=room_id,
|
||
room_name=room_name,
|
||
room_type=room_type,
|
||
)
|
||
if lazy_result is not None:
|
||
logger.info(
|
||
"[rocketchat] A1b: Lazy-Onboarding getriggert — "
|
||
"unbekannter Raum: room=%s, name=%s",
|
||
room_id[:12], room_name,
|
||
)
|
||
await self._start_onboarding([lazy_result])
|
||
# Nachricht nicht weiter verarbeiten — Onboarding läuft jetzt
|
||
routing_counter.increment('lazy_onboarding_triggered')
|
||
logger.info("ROUTING BYPASS: reason=lazy_onboarding_triggered, origin_room=%s", room_id)
|
||
return
|
||
# ── Ende A1b Lazy-Onboarding ─────────────────────────────────────
|
||
|
||
# ── Thema B: Onboarding-Guard — Plugin-onboarding vor generischem Hermes-onboarding ──
|
||
# Wenn Onboarding aktiv ist und die Nachricht aus einem Raum kommt,
|
||
# der NICHT in der room-map.json steht und NICHT der Operator-DM ist,
|
||
# dann die Nachricht abfangen. Verhindert dass das generische
|
||
# Hermes-Agent-Onboarding (Profile, Skills, Cronjobs) das
|
||
# Plugin-Onboarding (Raum-Interview) übersteuert.
|
||
if (
|
||
_MULTIROOM()
|
||
and self.archivar is not None
|
||
and self._is_onboarding_running()[0]
|
||
and room_type != "d"
|
||
):
|
||
# P-054: operator_room_id mit Fallback-Kette
|
||
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||
if not operator_room:
|
||
sm = getattr(self, '_onboarding_sm', None)
|
||
if sm is not None:
|
||
operator_room = getattr(sm._data, 'operator_room_id', '') or ''
|
||
if not operator_room:
|
||
dm_rooms = [rid for rid, info in self._room_info.items()
|
||
if info.get("type") == "d"]
|
||
if len(dm_rooms) == 1:
|
||
operator_room = dm_rooms[0]
|
||
# Prüfe ob der Raum in der room-map.json steht
|
||
room_in_map = (
|
||
self.archivar._room_map is not None
|
||
and room_id in self.archivar._room_map.rooms
|
||
)
|
||
if not room_in_map and room_id != operator_room:
|
||
# Raum ist unbekannt und Onboarding läuft → Nachricht abfangen
|
||
logger.info(
|
||
"[rocketchat] Thema B: Onboarding-Guard — Nachricht aus unbekanntem Raum "
|
||
"während Onboarding abgefangen: room=%s, name=%s",
|
||
room_id[:12], room_name,
|
||
)
|
||
await self._post_message_with_retry(
|
||
room_id,
|
||
"🔄 Ich richte mich gerade ein — einen Moment bitte. "
|
||
"Das Onboarding-Interview läuft in deinem DM-Kanal. "
|
||
"Sobald ich fertig bin, bin ich für dich da!"
|
||
)
|
||
routing_counter.increment('onboarding_guard_blocked')
|
||
logger.info("ROUTING BYPASS: reason=onboarding_guard_blocked, origin_room=%s", room_id)
|
||
return
|
||
# ── Ende Thema B Onboarding-Guard ────────────────────────────────────
|
||
|
||
# ── CLARIFY Response Handling ───────────────────────────────────
|
||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
||
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
||
is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False
|
||
if is_clarify_response and text.startswith("CLARIFY:"):
|
||
routing_counter.increment('clarify_answer_bypass')
|
||
logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id)
|
||
try:
|
||
if "::" in text:
|
||
# Neues Format: CLARIFY:<id>::<choice> (via _build_custom_buttons)
|
||
prefix_part, choice = text.split("::", 1)
|
||
clarify_id = prefix_part.split(":", 1)[1]
|
||
else:
|
||
# Altes Format: CLARIFY:<id>:other (Other-Button)
|
||
parts = text.split(":", 2)
|
||
if len(parts) != 3:
|
||
logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping")
|
||
return
|
||
_, clarify_id, choice = parts
|
||
if choice == "other":
|
||
# For "Other" button, enable text capture mode
|
||
from tools.clarify_gateway import mark_awaiting_text
|
||
mark_awaiting_text(clarify_id)
|
||
logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY other — awaiting text")
|
||
# P-067: Clear Clarify-Modal pulse (user responded)
|
||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||
self._presence_engine.clear_clarify_modal()
|
||
# 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)
|
||
# P-067: Clear Clarify-Modal pulse (user responded with choice)
|
||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||
self._presence_engine.clear_clarify_modal()
|
||
# 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)
|
||
# ── FIX 2 (P0): ISSUE 3 — Pending Dispatch nach Klärung ──
|
||
# Nach der Klärung (Strategie/anderer_grund) den
|
||
# ursprünglichen Auftrag an den Agenten dispatchen.
|
||
pending = self._pending_clarify_dispatch.pop(room_id, None)
|
||
if pending:
|
||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||
_THEMATIC_TARGET_ROOM.set("")
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{pending['username']}", room_id)
|
||
routing_counter.increment('archivar_clarify_dispatched')
|
||
logger.info(
|
||
"[rocketchat] FIX 2: Clarify dispatch — "
|
||
"room=%s, text=%s",
|
||
room_id[:8], pending["text"][:80],
|
||
)
|
||
await self._dispatch_agent(
|
||
text=pending["text"],
|
||
room_id=room_id,
|
||
room_name=room_name,
|
||
room_type=room_type,
|
||
username=pending["username"],
|
||
msg_id=pending["msg_id"],
|
||
msg_obj=pending["msg_obj"],
|
||
is_button_response=pending.get("is_button_response", False),
|
||
category="",
|
||
)
|
||
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
|
||
# P-065: Kombiniere _is_onboarding_running() (Interview läuft) +
|
||
# _is_onboarding_completed() (ONBOARD:-Prefix nach Gateway-Restart).
|
||
# Beide liefern operator_room_id — wir nehmen die erste nicht-leere.
|
||
is_running, running_op_room, running_reason = self._is_onboarding_running()
|
||
is_completed, completed_op_room, completed_reason = self._is_onboarding_completed()
|
||
is_onboarding_phase = is_running or is_completed
|
||
_onb_op_room = running_op_room or completed_op_room
|
||
_onb_reason = running_reason if is_running else (completed_reason if is_completed else "inactive")
|
||
if _MULTIROOM() and self.archivar is not None and is_onboarding_phase:
|
||
stripped = text.strip()
|
||
# P-054: is_operator_room mit Fallback-Kette aus drei Quellen:
|
||
# 1. In-Memory (mid-Interview)
|
||
# 2. OnboardingStateMachine._data.operator_room_id (YAML, persistent)
|
||
# 3. (Notfall) Heuristik: einziger DM-Raum
|
||
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||
if not operator_room:
|
||
# Fallback: OnboardingStateMachine (onboarding.yaml)
|
||
sm = getattr(self, '_onboarding_sm', None)
|
||
if sm is not None:
|
||
operator_room = getattr(sm._data, 'operator_room_id', '') or ''
|
||
if not operator_room:
|
||
# Notfall-Heuristik: einziger DM-Raum
|
||
dm_rooms = [rid for rid, info in self._room_info.items()
|
||
if info.get("type") == "d"]
|
||
if len(dm_rooms) == 1:
|
||
operator_room = dm_rooms[0]
|
||
is_operator_room = (operator_room and room_id == operator_room)
|
||
# P0-1: Review-Flow-Phasen (review_room, review_butler, review_fakt)
|
||
# müssen ebenfalls als Onboarding erkannt werden, damit
|
||
# Button-Klicks (REVIEW_ROOM_EDIT::rid::edit etc.) nicht
|
||
# als Freitext an den LLM-Agenten durchgereicht werden.
|
||
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||
is_onboarding = (
|
||
# P0-3: Prefix-Checks VOR Phase-Inspektion (Defense in Depth)
|
||
# Fängt FAKT::/REVIEW_*/⏰ auch bei State-Verlust ab
|
||
(is_operator_room and stripped.startswith("FAKT::"))
|
||
or (is_operator_room and stripped.startswith("REVIEW_BUTLER::"))
|
||
or (is_operator_room and stripped.startswith("REVIEW_FAKT::"))
|
||
or (is_operator_room and stripped.startswith("REVIEW_ROOM"))
|
||
or (is_operator_room and "⏰" in stripped)
|
||
or (is_operator_room and stripped.lower() == "später")
|
||
or (is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
|
||
or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button
|
||
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
|
||
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
||
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
||
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
||
or (is_operator_room and self._onboarding_state.get("phase") in _review_phases) # P0-1: Review-Flow Phasen
|
||
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||
or (is_operator_room and stripped.isdigit()) # Catch-All-Wechsel
|
||
or (is_operator_room and stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten")) # Ablehnung
|
||
)
|
||
if is_onboarding:
|
||
await self._process_onboarding_response(text, room_id)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping")
|
||
routing_counter.increment('onboarding_response_routed')
|
||
logger.info("ROUTING BYPASS: reason=onboarding_response_routed, 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 "1234":
|
||
choice = choice[0]
|
||
elif choice and choice[:2] in ("1️⃣", "2️⃣", "3️⃣", "4️⃣"):
|
||
choice = choice[:2]
|
||
# Altes Format: "1"/"2"/"3"/"4" = numerische Antwort
|
||
# Neues Format: "1️⃣", "2️⃣", "3️⃣", "4️⃣" = Emoji-Nummern
|
||
elif choice in ("1", "2", "3", "4") or choice in ("1️⃣", "2️⃣", "3️⃣", "4️⃣"):
|
||
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)
|
||
elif num == 3:
|
||
choice = "hier bleiben" # v6: 3 = Hier bleiben (nur diesmal)
|
||
else:
|
||
choice = "falsch" # v6: 4 = Falsch geroutet (reject)
|
||
choice = choice.lower()
|
||
|
||
# Neue Mapping-Logik für verbesserte Button-UX (v6)
|
||
feedback_type = "stay" # Default
|
||
forwarded = False
|
||
# P-055: Flag für Direkt-Dispatch-Unterdrückung bei Nachklärung.
|
||
# Wird im stay_once-Branch auf True gesetzt wenn
|
||
# Nachklärungs-Buttons gesendet wurden.
|
||
skip_direct_dispatch = 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"])
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", 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": "",
|
||
"source": "confirm", # FIX 4: confirm_move vs auto-route
|
||
}
|
||
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,
|
||
)
|
||
# ── FIX 1 (P0): ISSUE 4 — Nachricht in Zielraum kopieren ──
|
||
# V8.1 hatte den Copy-Schritt fälschlich entfernt.
|
||
# P0-Fix: DM-Guard entfernt — Copy läuft jetzt auch bei DM-Origins.
|
||
try:
|
||
prefix = f"*(Auftrag von @{username}, hierher kopiert)*\n"
|
||
target_copy_id = await self._post_message_with_retry(
|
||
move_req["target_room"],
|
||
prefix + move_req["text"],
|
||
)
|
||
if target_copy_id:
|
||
self._recent_auto_routes[room_id]["target_message_id"] = target_copy_id
|
||
routing_counter.increment('confirm_move_copied')
|
||
if room_type == "d":
|
||
routing_counter.increment('confirm_move_dm_origin')
|
||
logger.info(
|
||
"[rocketchat] FIX 1: confirm_move copy → %s, "
|
||
"target_msg_id=%s",
|
||
move_req.get("target_name", "?")[:20],
|
||
target_copy_id or "N/A",
|
||
)
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] FIX 1: confirm_move copy failed — %s", e
|
||
)
|
||
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 — dieses Thema bleibt jetzt hier im Raum. (Themenbezogen, verfällt nach 24h oder Themenwechsel)")
|
||
feedback_type = "never"
|
||
elif choice in ("3", "3️⃣", "hier bleiben", "nur diesmal", "stay_once"):
|
||
# 3️⃣ Nur diesmal → Antwort im Ursprungsraum (nur diesmal, kein Sticky)
|
||
# V8.2.1 A2: Nach stay_once → Nachklärung mit Strategie-Buttons
|
||
# P-057: feedback_type='neutral' statt 'stay' — stay_once
|
||
# meint semantisch: 'Vorschlag war richtig, Ausführung nur
|
||
# diesmal hier'. Kein negatives Feedback, kein Gewicht-Verlust.
|
||
await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
|
||
feedback_type = "neutral"
|
||
# P-055: Flag, um Direkt-Dispatch zu unterdrücken wenn
|
||
# Nachklärungs-Buttons gesendet wurden. Verhindert
|
||
# Clarify-Dispatch-Schleife (zwei Wahrheitsquellen).
|
||
skip_direct_dispatch = False
|
||
# V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden
|
||
# P-057 Folgefix: Bei feedback_type='neutral' wird nicht
|
||
# gelernt → Nachklärung ist sinnlos. Überspringen.
|
||
if _MULTIROOM() and self.archivar is not None and feedback_type != "neutral":
|
||
if self.archivar._should_trigger_nachklaerung("stay_once"):
|
||
# Keywords des Zielraums als lesbaren Text einbauen
|
||
target_room_id = move_req.get("target_room", "")
|
||
target_keywords = []
|
||
if target_room_id and self.archivar._room_map is not None:
|
||
target_entry = self.archivar._room_map.rooms.get(target_room_id)
|
||
if target_entry:
|
||
target_keywords = target_entry.keywords_100[:5]
|
||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons(
|
||
keywords=target_keywords if target_keywords else None
|
||
)
|
||
await self._send_archivar_buttons(
|
||
room_id,
|
||
nachklaerung_buttons["text"],
|
||
{"actions": nachklaerung_buttons["actions"]},
|
||
)
|
||
logger.info(
|
||
"[rocketchat] V8.2.1 A2: Nachklärung gesendet — "
|
||
"Strategie-Buttons in room %s", room_id[:8],
|
||
)
|
||
# P-055: Direkt-Dispatch unterdrücken — die
|
||
# Nachricht wird erst nach Klärung via
|
||
# ARCHIVAR_CLARIFY-Handler dispatched.
|
||
skip_direct_dispatch = True
|
||
# FIX 2 (P0): ISSUE 3 — Persistenter Pending-Dispatch-Slot
|
||
# Speichere move_req-Daten für ARCHIVAR_CLARIFY-Handler.
|
||
self._pending_clarify_dispatch[room_id] = {
|
||
"text": move_req.get("text", ""),
|
||
"username": username,
|
||
"msg_id": msg_id,
|
||
"msg_obj": msg_obj,
|
||
"is_button_response": is_button_response,
|
||
}
|
||
logger.info(
|
||
"[rocketchat] FIX 2: Pending clarify dispatch saved — "
|
||
"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 and feedback_type != "neutral":
|
||
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, "🔒 Gut erkannt — dieses Thema bleibt ab jetzt hier. (Verfällt nach 24h oder Themenwechsel)")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] Failed to auto-promote sticky: %s", e)
|
||
elif choice in ("4", "4️⃣", "falsch", "falsch geroutet", "reject"):
|
||
# 4️⃣ Falsch geroutet → Zielraum war FALSCH, Ursprungsraum
|
||
# war RICHTIG. Lerne aktiv um: Zielraum-Gewicht drastisch
|
||
# reduzieren, Ursprungsraum-Gewicht erhöhen.
|
||
# P-058: Eigenständiger feedback_type='reject'.
|
||
# KEIN set_never_route — Themenring wäre falsch.
|
||
# KEIN _room_context-Cleanup — Ursprungsraum IST Zielraum.
|
||
# P-040: DM-Ausschluss — wenn origin==target möglich,
|
||
# Button 4 nicht anbieten (wird in _send_move_request geprüft).
|
||
await self._post_message_with_retry(
|
||
room_id,
|
||
"📌 Korrigiert — das Thema wird ab jetzt dauerhaft hier geroutet."
|
||
)
|
||
feedback_type = "reject"
|
||
# Kein Dispatch — der User hat den Vorschlag abgelehnt,
|
||
# die Nachricht bleibt im Ursprungsraum und wird normal
|
||
# vom Agenten verarbeitet (kein skip_direct_dispatch nötig).
|
||
logger.info(
|
||
"[rocketchat] P-058: reject feedback — origin_room=%s, "
|
||
"target_room=%s → Zielraum-Gewicht wird reduziert, "
|
||
"Ursprungsraum-Gewicht erhöht",
|
||
room_id[:8], move_req.get("target_room", "?")[:8],
|
||
)
|
||
|
||
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
|
||
if _MULTIROOM() and self.archivar is not None and move_req.get("message_id"):
|
||
user_id = user_info.get("_id", "")
|
||
await self.archivar.handle_feedback_response(
|
||
message_id=move_req["message_id"],
|
||
user_id=user_id,
|
||
feedback_type=feedback_type
|
||
)
|
||
|
||
# ── Ansatz D: Per-Room Pending Question Resolver ──────────
|
||
# Nachdem alle Button-Aktionen (Nachklärung, Stay-Counter,
|
||
# Feedback) abgeschlossen sind, die pending question aus dem
|
||
# Ursprungsraum UND dem aktuellen Raum entfernen.
|
||
# Verhindert Zombie-States und wachsende pending-Sets.
|
||
origin_room = move_req.get("origin_room", room_id)
|
||
self._rooms_with_pending_questions.discard(origin_room)
|
||
self._rooms_with_pending_questions.discard(room_id)
|
||
# ── Ende Ansatz D ─────────────────────────────────────────
|
||
|
||
# ── V7-1: Bei ✅Ja → Breadcrumb im Ursprungsraum + Agent-Dispatch ──
|
||
if forwarded:
|
||
# Breadcrumb: "Wir sind rübergewechselt → #Zielraum-Name"
|
||
target_name = move_req.get("target_name", "Zielraum")
|
||
breadcrumb = f"🔄 Wir sind rübergewechselt → #{target_name.lstrip('#')}"
|
||
await self._post_message_with_retry(room_id, breadcrumb)
|
||
logger.info(
|
||
"[rocketchat] V7-1: Breadcrumb sent to origin room %s → %s",
|
||
room_id[:8], target_name,
|
||
)
|
||
# _CURRENT_ORIGIN_ROOM ist bereits auf Zielraum gesetzt (line 1306).
|
||
# Agent-Dispatch direkt hier — kein Archivar-Block, kein Reset.
|
||
# Verwende Zielraum-Name/Typ für den Raum-Kontext-Prefix.
|
||
target_room_id = move_req.get("target_room", "")
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name = target_room_info.get("name", target_name)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=move_req.get("text", ""),
|
||
room_id=target_room_id,
|
||
room_name=target_room_name,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="work_order",
|
||
)
|
||
return
|
||
else:
|
||
# Button 2/3: stay_here / stay_once — dispatch original message
|
||
# to agent in the origin room (P0 fix: data loss prevention)
|
||
# P-055: Wenn Nachklärungs-Buttons gesendet wurden,
|
||
# Direkt-Dispatch überspringen — die Nachricht wird
|
||
# erst nach Klärung via ARCHIVAR_CLARIFY-Handler dispatched.
|
||
if skip_direct_dispatch:
|
||
logger.info(
|
||
"[rocketchat] P-055: Direkt-Dispatch übersprungen — "
|
||
"Nachklärung aktiv, Dispatch via ARCHIVAR_CLARIFY-Handler "
|
||
"room=%s", room_id[:8],
|
||
)
|
||
return
|
||
origin_text = move_req.get("text", "")
|
||
if not origin_text:
|
||
logger.warning(
|
||
"[rocketchat] P0: stay_here/stay_once without origin text — "
|
||
"skipping dispatch (room=%s)", room_id[:8]
|
||
)
|
||
return
|
||
# _CURRENT_ORIGIN_ROOM: User stays HERE (origin room)
|
||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", room_id)
|
||
# _THEMATIC_TARGET_ROOM: NOT set — no topic change
|
||
await self._dispatch_agent(
|
||
text=origin_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="work_order",
|
||
)
|
||
routing_counter.increment("stay_here_dispatched")
|
||
logger.info(
|
||
"[rocketchat] P0: stay_here dispatch — origin_room=%s, "
|
||
"text=[:80]%s", room_id[:8], origin_text[:80]
|
||
)
|
||
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, 30 Min nach confirm_move.
|
||
# V8.3.1 F2: Wortgrenzen-Match + Satzkontext-Whitelist.
|
||
# FIX 4: Erweiterte Keywords + confirm_move-Support.
|
||
_WIDERSPRUCH_KEYWORDS = [
|
||
'halt', 'bleib hier', 'gehört hier her',
|
||
'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback',
|
||
'passt hier nicht', 'gehört nicht hier', 'falsch', 'doch nicht',
|
||
]
|
||
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
|
||
)
|
||
|
||
# ── FIX 4: Erweiterte Widerspruchs-Erkennung ──────────────────
|
||
# Auto-Route: room_id == origin_room (direkter Lookup)
|
||
# confirm_move: room_id == target_room (inverser Lookup)
|
||
route_info = None
|
||
route_source = None
|
||
if is_widerspruch and room_id in self._recent_auto_routes:
|
||
route_info = self._recent_auto_routes[room_id]
|
||
route_source = route_info.get("source", "auto")
|
||
elif is_widerspruch:
|
||
# Inverser Lookup: Suche nach confirm_move-Route,
|
||
# deren target_room == room_id (Rainer Architektur-Detail)
|
||
for origin_rid, entry in list(self._recent_auto_routes.items()):
|
||
if entry.get("target_room") == room_id and entry.get("source") == "confirm":
|
||
route_info = entry
|
||
route_source = "confirm"
|
||
# room_id ist der Zielraum, origin_room ist der Ursprungsraum
|
||
break
|
||
|
||
if is_widerspruch and route_info is not None:
|
||
elapsed = time.time() - route_info["timestamp"]
|
||
# Auto-Route: 10 Min, confirm_move: 30 Min
|
||
max_window = 1800 if route_source == "confirm" else 600
|
||
if elapsed <= max_window:
|
||
logger.info(
|
||
"[rocketchat] V8.3-3: Widerspruch erkannt in room %s — "
|
||
"%.0fs nach %s-Route, hole Thema zurück",
|
||
room_id[:8], elapsed, route_source,
|
||
)
|
||
target_room_id = route_info["target_room"]
|
||
origin_room_id = route_info["origin_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
|
||
if route_source == "confirm":
|
||
# FIX 4: Bei confirm_move — Rückhol-Text mit Original
|
||
origin_name = self._room_info.get(origin_room_id, {}).get("name", "Ursprungsraum")
|
||
target_name = self._room_info.get(target_room_id, {}).get("name", "Zielraum")
|
||
rueckhol_text = (
|
||
f"↩️ Zurückgeholt aus #{target_name.lstrip('#')}\n"
|
||
f"{display_text}"
|
||
)
|
||
await self._post_message_with_retry(origin_room_id, rueckhol_text)
|
||
routing_counter.increment('widerspruch_confirm_move_route')
|
||
else:
|
||
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(origin_room_id)
|
||
_THEMATIC_TARGET_ROOM.set("")
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", origin_room_id)
|
||
# d. Sticky löschen
|
||
self._session_room_preferences.pop(origin_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=origin_room_id,
|
||
topic=route_topic,
|
||
room_name=self._room_info.get(origin_room_id, {}).get("name", ""),
|
||
)
|
||
# f. KEIN Lernen
|
||
# g. Cleanup
|
||
del self._recent_auto_routes[origin_room_id]
|
||
# Dispatch im Ursprungsraum
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=origin_room_id,
|
||
room_name=self._room_info.get(origin_room_id, {}).get("name", room_name),
|
||
room_type=self._room_info.get(origin_room_id, {}).get("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
|
||
origin_rid = route_info.get("origin_room", room_id)
|
||
self._recent_auto_routes.pop(origin_rid, None)
|
||
|
||
# ── 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)
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", target_room_id)
|
||
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
|
||
self._session_room_preferences[room_id] = {
|
||
"target_room": target_room_id,
|
||
"target_name": target_room_display,
|
||
"sticky_topic": "explizit-wechsel",
|
||
"expires_at": time.time() + 1800, # 30 Min
|
||
}
|
||
logger.info(
|
||
"[rocketchat] V8.3-4: Expliziter Wechsel-Sticky gesetzt — "
|
||
"room=%s → target=%s (30 Min)",
|
||
room_id[:8], target_room_display[:20],
|
||
)
|
||
# c. Agent antwortet im Zielraum
|
||
await self._post_message_with_retry(
|
||
target_room_id,
|
||
f"Gerne, wir sind jetzt in {target_room_display}. "
|
||
f"Was möchtest du besprechen?"
|
||
)
|
||
# Dispatch im Zielraum
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name_disp = target_room_info.get("name", target_room_display)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=target_room_id,
|
||
room_name=target_room_name_disp,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="",
|
||
)
|
||
return
|
||
|
||
# ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
|
||
# Klassifiziere die Nachricht und entscheide über Copy/Routing.
|
||
# Die Antwort des Agenten bleibt IMMER im Ursprungsraum.
|
||
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||
category = ""
|
||
decision = None
|
||
is_auftrag = _is_auftrag(routing_text)
|
||
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
||
|
||
# V8.4.3: Flag für zentrale classify_and_route-Aufrufstelle.
|
||
# Intentional bypass paths setzen False. Fall-through paths
|
||
# (Sticky-Bypass, B2-No-Topic, Expliziter-Wechsel-ohne-#) behalten True.
|
||
_should_classify = True
|
||
|
||
try:
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||
if not is_button_response:
|
||
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions")
|
||
routing_counter.increment('pending_questions_bypass')
|
||
logger.info("ROUTING BYPASS: reason=pending_questions_bypass, origin_room=%s", room_id)
|
||
self._rooms_with_pending_questions.discard(room_id)
|
||
_should_classify = False
|
||
elif self.archivar._state.should_stay_in_room(room_id) == "always":
|
||
# Bug 4 fix: Persistierte Entscheidung (always) aus ArchivarState lesen.
|
||
# P0-B: "never_route" ist jetzt thematisch (v7) — wird im Router
|
||
# pro Thema geprüft, nicht mehr als Raum-Level-Bypass.
|
||
# Nur "always" bypassed Archivar komplett.
|
||
logger.debug("[rocketchat] Room %s has persisted decision=always — Archivar bypassed", room_id[:8])
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — persisted_state=always")
|
||
_should_classify = False
|
||
elif room_type == "d":
|
||
# V8.5: DM-Routing differenziert — 100%-Keywords werden
|
||
# erkannt und lösen einen Move-Request (Butler) aus.
|
||
# Kein 100%-Keyword → Catch-All (LLM antwortet im DM).
|
||
# Der Router (classify_and_route) entscheidet selbstständig.
|
||
logger.debug("[rocketchat] DM von %s — Archivar läuft (100%%-Keyword-Check)", username)
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: DM — Archivar aktiv (100%%-Keywords → Butler, Rest → Catch-All)")
|
||
# _should_classify bleibt True — Router wird aufgerufen
|
||
elif room_id in self._session_room_preferences:
|
||
# V8.3-5: Topic-Scoped Sticky — Auto-Route nur bei gleichem Thema
|
||
pref = self._session_room_preferences[room_id]
|
||
if time.time() < pref["expires_at"]:
|
||
target_room_id = pref["target_room"]
|
||
target_name = pref.get("target_name", "Zielraum")
|
||
sticky_topic = pref.get("sticky_topic", "")
|
||
# ── V8.3-5: Topic-Scoping — Thema aus aktueller Nachricht extrahieren ──
|
||
current_topic = ""
|
||
if sticky_topic and _MULTIROOM() and self.archivar is not None:
|
||
# Extrahiere Thema via 100%-Keyword-Match gegen alle Räume
|
||
matched_room = self.archivar._room_map.find_room_by_keywords(
|
||
text, origin_room_id=room_id
|
||
)
|
||
if matched_room is not None:
|
||
current_topic = room_name_to_topic(matched_room.name)
|
||
# ── V8.3-5: Topic-Vergleich ──────────────────────
|
||
if sticky_topic and current_topic and current_topic != sticky_topic:
|
||
# Thema ≠ sticky_topic → STAY, Sticky ignorieren, normale Auswertung
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic mismatch — sticky_topic='%s', "
|
||
"current_topic='%s' → ignoring sticky, falling through to Archivar",
|
||
sticky_topic, current_topic,
|
||
)
|
||
# Sticky NICHT löschen — könnte später wieder matchen
|
||
# Fall through to Archivar classification
|
||
elif sticky_topic and not current_topic:
|
||
# V8.3.4 B2: Kein 100%-Keyword-Match → Sticky darf NICHT greifen
|
||
# 'Kein Thema' ≠ 'gleiches Thema'. STAY, normale Auswertung.
|
||
logger.info(
|
||
"[rocketchat] V8.3.4 B2: No topic extracted from message — "
|
||
"sticky_topic='%s' but no 100%% keyword match → ignoring sticky, "
|
||
"falling through to Archivar",
|
||
sticky_topic,
|
||
)
|
||
# Fall through to Archivar classification
|
||
else:
|
||
# Thema matcht → Sticky greift
|
||
# V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen
|
||
if self.archivar is not None and self.archivar._room_map is not None:
|
||
target_entry = self.archivar._room_map.get_room_by_id(target_room_id)
|
||
if target_entry and target_entry.catch_all:
|
||
logger.debug(
|
||
"[rocketchat] V8.1.1 R1: Topic-Scoped Sticky target %s is catch_all — "
|
||
"skipping auto-route, falling through to Archivar",
|
||
target_name[:20],
|
||
)
|
||
# Sticky aufräumen — nicht mehr gültig
|
||
del self._session_room_preferences[room_id]
|
||
# Fall through to Archivar classification
|
||
else:
|
||
# V8.1.1 R1: stay_in_room-Guard — nicht routen wenn Raum stay_in_room hat
|
||
origin_state = self.archivar._state.should_stay_in_room(room_id)
|
||
if origin_state in ("always", "never_route"):
|
||
logger.debug(
|
||
"[rocketchat] V8.1.1 R1: Topic-Scoped Sticky origin room %s has "
|
||
"stay_in_room=%s — skipping auto-route, falling through to Archivar",
|
||
room_id[:8], origin_state,
|
||
)
|
||
del self._session_room_preferences[room_id]
|
||
# Fall through to Archivar classification
|
||
else:
|
||
# Guards passed — auto-route
|
||
# V8.3.4 B1: Ankündigung im Ursprungsraum posten
|
||
target_display = target_name.lstrip('#') if target_name else "Zielraum"
|
||
announcement = _build_announcement(target_display)
|
||
await self._post_message_with_retry(room_id, announcement)
|
||
logger.info(
|
||
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
|
||
room_id[:8], target_display,
|
||
)
|
||
# V8.3.4 B4: Telemetrie im Sticky-Pfad
|
||
routing_telemetry.record(
|
||
stage='sticky', score=1.0, decision='route',
|
||
target=target_room_id, origin=room_id,
|
||
duration_ms=0.0,
|
||
)
|
||
routing_telemetry.flush()
|
||
# Kopiere Nachricht in den Zielraum
|
||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||
await self._post_message_with_retry(target_room_id, target_txt)
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", target_room_id)
|
||
routing_counter.increment('session_sticky_auto_route')
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||
display_text[:80], target_name, sticky_topic,
|
||
pref["expires_at"] - time.time(),
|
||
)
|
||
# Dispatch direkt — kein Archivar
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name = target_room_info.get("name", target_name)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=target_room_id,
|
||
room_name=target_room_name,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="work_order",
|
||
)
|
||
return
|
||
else:
|
||
# Kein Archivar/RoomMap — direkt routen (Fallback)
|
||
# V8.3.4 B1: Ankündigung im Ursprungsraum posten
|
||
target_display = target_name.lstrip('#') if target_name else "Zielraum"
|
||
announcement = _build_announcement(target_display)
|
||
await self._post_message_with_retry(room_id, announcement)
|
||
logger.info(
|
||
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
|
||
room_id[:8], target_display,
|
||
)
|
||
# V8.3.4 B4: Telemetrie im Sticky-Pfad
|
||
routing_telemetry.record(
|
||
stage='sticky', score=1.0, decision='route',
|
||
target=target_room_id, origin=room_id,
|
||
duration_ms=0.0,
|
||
)
|
||
routing_telemetry.flush()
|
||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||
await self._post_message_with_retry(target_room_id, target_txt)
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", target_room_id)
|
||
routing_counter.increment('session_sticky_auto_route')
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||
display_text[:80], target_name, sticky_topic,
|
||
pref["expires_at"] - time.time(),
|
||
)
|
||
# Dispatch direkt — kein Archivar
|
||
target_room_info = self._room_info.get(target_room_id, {})
|
||
target_room_name = target_room_info.get("name", target_name)
|
||
target_room_type = target_room_info.get("type", "c")
|
||
await self._dispatch_agent(
|
||
text=display_text,
|
||
room_id=target_room_id,
|
||
room_name=target_room_name,
|
||
room_type=target_room_type,
|
||
username=username,
|
||
msg_id=msg_id,
|
||
msg_obj=msg_obj,
|
||
is_button_response=is_button_response,
|
||
category="work_order",
|
||
)
|
||
return
|
||
else:
|
||
# Abgelaufen → aufräumen
|
||
del self._session_room_preferences[room_id]
|
||
logger.debug(
|
||
"[rocketchat] V8.1 P2: Topic-Scoped Sticky expired for room %s",
|
||
room_id[:8],
|
||
)
|
||
# V8.4.3: Kein else mehr — classify_and_route wird zentral
|
||
# nach der if/elif-Kette aufgerufen, wenn _should_classify=True.
|
||
# Fall-through paths (Sticky-Bypass, B2-No-Topic, Expired Sticky)
|
||
# behalten _should_classify=True und erreichen classify_and_route.
|
||
# ── V8.4.3: Zentrale classify_and_route-Aufrufstelle ──────────
|
||
# Alle Fall-through-Pfade (Sticky-Bypass, B2-No-Topic,
|
||
# Expliziter-Wechsel-ohne-#, Expired Sticky) landen hier.
|
||
if _should_classify:
|
||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12])
|
||
# P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard.
|
||
# room_type wird in L1579 aus self._room_info gelesen.
|
||
_is_dm = (room_type == "d")
|
||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||
routing_telemetry.flush()
|
||
if decision and decision.category:
|
||
category = decision.category
|
||
# Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request
|
||
# MUSS VOR _THEMATIC_TARGET_ROOM.set() kommen, sonst wird
|
||
# der Zielraum gesetzt und send() routet in den DM
|
||
if (hasattr(decision, 'target_room') and decision.target_room
|
||
and decision.target_room == room_id):
|
||
decision.stay_in_room = True
|
||
decision.move_request_sent = False
|
||
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
||
# P0-BUGFIX: Nur setzen wenn NICHT stay_in_room.
|
||
# Bei stay_in_room=True (Meta-Fragen, Smalltalk, etc.)
|
||
# bleibt der Agent im Ursprungsraum — kein Zielraum nötig.
|
||
if (hasattr(decision, 'target_room') and decision.target_room
|
||
and not getattr(decision, 'stay_in_room', False)):
|
||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||
global _question_counter
|
||
with _question_counter_lock:
|
||
_question_counter += 1
|
||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
||
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
|
||
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
|
||
if (getattr(decision, 'move_request_sent', False)
|
||
and hasattr(decision, 'target_room')
|
||
and decision.target_room):
|
||
self._pending_move_requests[room_id] = {
|
||
# P1: display_text (mit Quote) für Move-Request speichern
|
||
'text': display_text,
|
||
'origin_room': room_id,
|
||
'target_room': decision.target_room,
|
||
'target_name': getattr(
|
||
decision, 'move_request_target_name', 'Zielraum'),
|
||
'username': username,
|
||
'message_id': msg_id,
|
||
}
|
||
# 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,
|
||
"origin_room": room_id, # P-058: für reject-Feedback benötigt
|
||
"timestamp": time.time()
|
||
}
|
||
except asyncio.TimeoutError:
|
||
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
|
||
with _question_counter_lock:
|
||
_question_counter += 1
|
||
except Exception as e:
|
||
routing_counter.increment('exception_fallback')
|
||
logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id)
|
||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||
|
||
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
||
# V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch.
|
||
# Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched,
|
||
# dann mit _CURRENT_ORIGIN_ROOM auf den Zielraum gesetzt.
|
||
if decision and getattr(decision, 'move_request_sent', False):
|
||
logger.info(
|
||
"[rocketchat] V7-1: Move-Request pending for '%s' → %s — "
|
||
"skipping agent dispatch, waiting for button confirmation",
|
||
text[:80], getattr(decision, 'move_request_target_name', '?'),
|
||
)
|
||
routing_counter.increment('move_request_pending_guard')
|
||
logger.info("ROUTING BYPASS: reason=move_request_pending_guard, origin_room=%s", room_id)
|
||
return
|
||
|
||
# V8.1 P1: 100%-Keyword-Route / FAISS-Auto-Route → echtes Routing
|
||
# Wenn move_request_sent=False ABER target_room gesetzt (nicht self-match):
|
||
# Antwort WIRKLICH in den Zielraum senden, Nachricht rüberkopieren.
|
||
forwarded = False
|
||
if (decision and hasattr(decision, 'target_room') and decision.target_room
|
||
and not getattr(decision, 'move_request_sent', False)
|
||
and decision.target_room != room_id):
|
||
target_room_id = decision.target_room
|
||
target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
|
||
# ── V8.3-5: Topic für Sticky extrahieren ──────────────────
|
||
# V8.3.1 F4: Vereinheitlicht auf room_name_to_topic(target_name)
|
||
# statt matched_keywords[0] — konsistent mit current_topic-Berechnung.
|
||
sticky_topic = room_name_to_topic(target_name) if target_name else ""
|
||
# ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ──
|
||
# V8.3.4 B5: Zufällige Variante aus 5 Formulierungen.
|
||
target_display = target_name.lstrip('#') if target_name else "Zielraum"
|
||
announcement = _build_announcement(target_display)
|
||
await self._post_message_with_retry(room_id, announcement)
|
||
logger.info(
|
||
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
|
||
room_id[:8], target_display,
|
||
)
|
||
# ── V8.3-2: Echtes Move — delete_message mit Fallback-Kette ──
|
||
# Versuche Originalnachricht zu löschen/ersetzen
|
||
move_success = False
|
||
if msg_id:
|
||
# a. delete_message (falls Permission vorhanden)
|
||
if self.rest.delete_message(room_id, msg_id):
|
||
move_success = True
|
||
logger.info(
|
||
"[rocketchat] V8.3-2: Original message deleted in origin room %s",
|
||
room_id[:8],
|
||
)
|
||
else:
|
||
# b. Fallback: update_message → ersetze durch Hinweis
|
||
fallback_text = f"Wir sind rübergewechselt → #{target_display}"
|
||
if self.rest.update_message(room_id, msg_id, fallback_text):
|
||
move_success = True
|
||
logger.info(
|
||
"[rocketchat] V8.3-2: Original message edited in origin room %s",
|
||
room_id[:8],
|
||
)
|
||
else:
|
||
# c. Letzter Fallback: Nur Hinweis-Post (bereits gesendet)
|
||
logger.info(
|
||
"[rocketchat] V8.3-2: Move fallback — announcement only in room %s",
|
||
room_id[:8],
|
||
)
|
||
# Kopiere Nachricht in den Zielraum
|
||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}"
|
||
target_message_id = await self._post_message_with_retry(target_room_id, target_txt)
|
||
# Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort
|
||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", target_room_id)
|
||
forwarded = True
|
||
routing_counter.increment('auto_route_dispatched')
|
||
logger.info(
|
||
"[rocketchat] V8.1 P1: Auto-Route '%s' → %s — "
|
||
"Agent dispatched in target room",
|
||
display_text[:80], target_name,
|
||
)
|
||
# V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
auto_topic = text[:80].replace("\n", " ").strip()
|
||
if auto_topic:
|
||
await self._multiroom_context.move_gc(
|
||
origin_room_id=room_id,
|
||
target_room_id=target_room_id,
|
||
topic=auto_topic,
|
||
room_name=target_name,
|
||
)
|
||
# V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL)
|
||
# V8.3.2 F1: Nur setzen wenn decision.set_sticky=True
|
||
# (100%-Keyword-Match). FAISS/LLM-Routing setzt KEINEN Sticky.
|
||
if getattr(decision, 'set_sticky', False):
|
||
self._session_room_preferences[room_id] = {
|
||
"target_room": target_room_id,
|
||
"target_name": target_name,
|
||
"sticky_topic": sticky_topic,
|
||
"expires_at": time.time() + 1800,
|
||
}
|
||
logger.info(
|
||
"[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — "
|
||
"room=%s → target=%s, topic='%s' (30 Min, Auto-Route)",
|
||
room_id[:8], target_name[:20], sticky_topic,
|
||
)
|
||
# ── V8.3-3: Auto-Route für Widerspruchs-Routine speichern ──
|
||
self._recent_auto_routes[room_id] = {
|
||
"origin_room": room_id,
|
||
"target_room": target_room_id,
|
||
"topic": sticky_topic,
|
||
"timestamp": time.time(),
|
||
"origin_message_id": msg_id,
|
||
"target_message_id": target_message_id or "",
|
||
"source": "auto", # FIX 4: confirm_move vs auto-route
|
||
}
|
||
|
||
# _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)
|
||
# P1: _room_context als persistenter Fallback
|
||
_set_room_context_origin(f"user:{username}", 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:
|
||
message_type = self._message_type_for(is_button_response)
|
||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||
if target_room_id:
|
||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]"
|
||
else:
|
||
# Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung
|
||
room_names = [info.get("name", "?") for rid, info in self._room_info.items()
|
||
if info.get("type") in ("c", "p") and rid != room_id]
|
||
rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume"
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]"
|
||
# ── Ende Kontext-Weitergabe ──────────────────────────────────────
|
||
# V8.1 P4: MultiRoomContext-Ring in System-Prompt injizieren
|
||
chat_topic = self._room_map_summary
|
||
if self._multiroom_context is not None:
|
||
ring_summary = await self._multiroom_context.get_summary(
|
||
exclude_room_id=room_id
|
||
)
|
||
if ring_summary:
|
||
chat_topic = f"{chat_topic}\n\n{ring_summary}" if chat_topic else ring_summary
|
||
# ── V8.4: Red Flag Prompt in System-Prompt injizieren ──────
|
||
if red_flag_prompt:
|
||
chat_topic = f"{chat_topic}\n\n{red_flag_prompt}" if chat_topic else red_flag_prompt
|
||
source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=virtual_chat_id, # ← user-based instead of room-based
|
||
chat_name=f"{room_name} (via @{username})" + archivar_suffix + (f" [{category}]" if category else ""),
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm", # ← force DM to bypass group isolation in Core
|
||
chat_topic=chat_topic, # FIX E + V8.1 P4: Raum-Map + MultiRoom-Kontext
|
||
)
|
||
# ── FIX A: Text-Prefix in User-Nachricht injizieren ──────────
|
||
# Der Agent muss wissen, in welchem Raum er angesprochen wird.
|
||
# Ohne diesen Kontext kann er nicht menschenähnlich kommunizieren
|
||
# (z.B. "Ich bin im DM"-Problem).
|
||
# Mechanismus: [Raum: name (typ)] wird als Text-Präfix vor die
|
||
# User-Nachricht gesetzt — kein ContextVar, sondern ein simpler
|
||
# String-Prefix, den der Agent im Prompt lesen kann.
|
||
room_type_label = {"c": "channel", "p": "group", "d": "dm"}.get(room_type, room_type)
|
||
room_context_prefix = f"[Raum: {room_name} ({room_type_label})] "
|
||
contextualized_text = room_context_prefix + text
|
||
|
||
event = MessageEvent(
|
||
text=contextualized_text,
|
||
message_type=message_type,
|
||
message_id=msg_id,
|
||
timestamp=datetime.datetime.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
event.source = source
|
||
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
|
||
# contextvars.copy_context() friert die aktuellen ContextVar-Werte
|
||
# (_CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM) ein. handle_message()
|
||
# erzeugt intern asyncio.create_task (Drain-Task), der ContextVars
|
||
# vom aufrufenden Task erbt. Ohne Snapshot kann der Drain-Task
|
||
# veraltete Werte einer vorherigen Nachricht erben (Race Condition
|
||
# bei zwei schnellen Nachrichten hintereinander).
|
||
ctx = contextvars.copy_context()
|
||
# V8.1 P1 diagnostic: log dispatch context
|
||
_origin = _CURRENT_ORIGIN_ROOM.get()
|
||
_target = _THEMATIC_TARGET_ROOM.get()
|
||
logger.info(
|
||
"V8.1 P1 dispatch: chat_id=%s → target_room=%s, "
|
||
"_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s",
|
||
virtual_chat_id, _target if _target else room_id,
|
||
_origin[:8] if _origin else "",
|
||
_target[:8] if _target else "",
|
||
)
|
||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||
# handle_message() erzeugt intern asyncio.create_task (Drain-Task).
|
||
# Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen.
|
||
self._agent_dispatch_task = asyncio.create_task(
|
||
ctx.run(self.handle_message, event)
|
||
)
|
||
try:
|
||
await self._agent_dispatch_task
|
||
except asyncio.CancelledError:
|
||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||
return
|
||
finally:
|
||
self._agent_dispatch_task = None
|
||
except Exception as e:
|
||
logger.error("[rocketchat] handle_message error: %s", e)
|
||
# Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart
|
||
# verliert der neue Prozess den In-Memory-Callback), als normale
|
||
# Text-Nachricht mit Hinweis wiederholen.
|
||
if is_button_response and str(e) == "COMMAND":
|
||
logger.info("[rocketchat] COMMAND lost context — retrying as TEXT")
|
||
try:
|
||
from datetime import datetime as dt2
|
||
fallback_source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=f"user:{username}",
|
||
chat_name=f"{room_name} (via @{username})",
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
chat_topic=self._room_map_summary, # FIX E
|
||
)
|
||
fallback_event = MessageEvent(
|
||
text=f"[Button-Antwort: {text}]",
|
||
message_type=MessageType.TEXT,
|
||
message_id=msg_id,
|
||
timestamp=dt2.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
fallback_event.source = fallback_source
|
||
await self.handle_message(fallback_event)
|
||
except Exception as e2:
|
||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||
# ── R5: Inline-Command-Handler ────────────────────────────────────────
|
||
|
||
def _register_inline_commands(self) -> None:
|
||
"""Registriert alle ::-Befehle in der InlineCommandRegistry."""
|
||
# ── Standard-Hermes-Befehle (:: als Variante) ──────────────────
|
||
self._inline_commands.register(
|
||
"sethome", self._cmd_sethome,
|
||
help_text="Setzt den Heimatraum (Alternative zu /sethome)",
|
||
description="Setzt den aktuellen Raum als Heimatraum. "
|
||
"Der Heimatraum ist der primäre Raum für Catch-All-Nachrichten.",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"reset", self._cmd_reset,
|
||
help_text="Setzt den Plugin-Status zurück (Alternative zu /reset)",
|
||
description="Setzt den Plugin-Status zurück (Onboarding, Session-Präferenzen).",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"busy", self._cmd_busy,
|
||
help_text="Zeigt/steuert den Busy-Status (::Variante von /busy)",
|
||
description="Subcommands: queue <text>, steer <text>, status. "
|
||
"Steuert was passiert während der Agent arbeitet.",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"allowalways", self._cmd_allowalways,
|
||
help_text="Verwaltet die Allow-Always-Liste (::Variante von /allow-always)",
|
||
description="Zeigt oder erweitert die Allow-Always-Liste für Skills.",
|
||
category="Standard",
|
||
)
|
||
self._inline_commands.register(
|
||
"commands", self._cmd_commands,
|
||
help_text="Listet alle ::-Befehle (::Variante von /commands)",
|
||
description="Zeigt die vollständige Hilfeseite mit allen Befehlen.",
|
||
category="Info",
|
||
)
|
||
self._inline_commands.register(
|
||
"restart", self._cmd_restart,
|
||
help_text="Löst Gateway-Neustart aus (::Variante von /restart)",
|
||
description="Startet den Hermes-Gateway-Dienst neu.",
|
||
category="Gateway",
|
||
)
|
||
self._inline_commands.register(
|
||
"update", self._cmd_update,
|
||
help_text="Zeigt Update-Informationen (::Variante von /update)",
|
||
description="Zeigt wie Hermes auf die neueste Version aktualisiert wird.",
|
||
category="Gateway",
|
||
)
|
||
|
||
# ── RC-Plugin-spezifische Befehle ──────────────────────────────
|
||
self._inline_commands.register(
|
||
"setfakt", self._cmd_setfakt,
|
||
help_text="Ändert den FAKT-Speicherort",
|
||
description="Öffnet den FAKT-Speicherort-Dialog. "
|
||
"Du kannst den Pfad ändern, wo FAKT-Nachrichten persistiert werden.",
|
||
category="Konfiguration",
|
||
)
|
||
self._inline_commands.register(
|
||
"hilfe", self._cmd_hilfe,
|
||
help_text="Zeigt diese Hilfeseite",
|
||
description="Zeigt alle verfügbaren ::-Befehle und "
|
||
"natürlichen Sprach-Befehle an.",
|
||
category="Hilfe",
|
||
)
|
||
self._inline_commands.register(
|
||
"status", self._cmd_status,
|
||
help_text="Zeigt aktuellen Plugin-Status",
|
||
description="Zeigt Räume, Archivar-Status, Butler-Modus und "
|
||
"Onboarding-Status an.",
|
||
category="Hilfe",
|
||
)
|
||
self._inline_commands.register(
|
||
"multiroom", self._cmd_multiroom,
|
||
help_text="Multi-Room-Agent aktivieren/deaktivieren/Status",
|
||
description="Steuert den Multi-Room-Agenten. "
|
||
"Subcommands: on, off, status.",
|
||
category="Plugin",
|
||
)
|
||
self._inline_commands.register(
|
||
"onboarding", self._cmd_onboarding,
|
||
help_text="Onboarding steuern: start/status/resume/pause/abort/reset",
|
||
description="Steuert den Onboarding-Prozess. "
|
||
"Subcommands: start, status, resume, pause, abort, reset. "
|
||
"Ohne Subcommand: Status anzeigen.",
|
||
category="Plugin",
|
||
subcommands={
|
||
"start": "Startet das Onboarding neu",
|
||
"status": "Zeigt den aktuellen Onboarding-Status mit Fortschritt",
|
||
"resume": "Setzt ein pausiertes Onboarding fort",
|
||
"pause": "Pausiert das Onboarding",
|
||
"abort": "Bricht das Onboarding ab (mit Bestätigung)",
|
||
"reset": "Hart-Reset des Onboarding-State, Backups bleiben",
|
||
},
|
||
)
|
||
self._inline_commands.register(
|
||
"curate", self._cmd_curate,
|
||
help_text="Kuratiert die Room-Map-Keywords (R10)",
|
||
description="Prüft und optimiert die Keywords in der Room-Map. "
|
||
"Subcommands: status, run.",
|
||
category="Plugin",
|
||
)
|
||
# P1-6: ::approve / ::deny — Dangerous-Command-Approval
|
||
self._inline_commands.register(
|
||
"approve", self._cmd_approve,
|
||
help_text="Bestätigt einen gefährlichen Befehl (einmalig)",
|
||
description="Bestätigt die Ausführung eines gefährlichen Befehls. "
|
||
"Subcommands: session (für Session), always (dauerhaft).",
|
||
category="Standard",
|
||
subcommands={
|
||
"session": "Bestätigt für die aktuelle Session",
|
||
"always": "Bestätigt dauerhaft (Allow-Always)",
|
||
},
|
||
)
|
||
self._inline_commands.register(
|
||
"deny", self._cmd_deny,
|
||
help_text="Lehnt einen gefährlichen Befehl ab",
|
||
description="Lehnt die Ausführung eines gefährlichen Befehls ab.",
|
||
category="Standard",
|
||
)
|
||
|
||
# ── V8.6: ::setstatus — Aktivitäts-Indikator an/abschalten ──
|
||
self._inline_commands.register(
|
||
"setstatus", self._cmd_setstatus,
|
||
help_text="Aktivitäts-Indikator an/abschalten (PresenceEngine)",
|
||
description="Schaltet den Aktivitäts-Indikator (Bot-Status) an oder aus. "
|
||
"Subcommands: on, off, status.",
|
||
category="Plugin",
|
||
subcommands={
|
||
"on": "Aktivitäts-Indikator einschalten",
|
||
"off": "Aktivitäts-Indikator ausschalten",
|
||
"status": "Status des Aktivitäts-Indikators anzeigen",
|
||
},
|
||
)
|
||
|
||
# ::reasoning — Reasoning-Level steuern (::Variante von /reasoning)
|
||
self._inline_commands.register(
|
||
"reasoning", self._cmd_reasoning,
|
||
help_text="Reasoning-Level steuern (::Variante von /reasoning)",
|
||
description="Steuert den Reasoning-Aufwand des Modells. "
|
||
"Subcommands: none|minimal|low|medium|high|xhigh, "
|
||
"show|hide, reset, --global für permanent.",
|
||
category="Konfiguration",
|
||
subcommands={
|
||
"none": "Reasoning komplett abschalten",
|
||
"low": "Kurzes, fokussiertes Reasoning",
|
||
"medium": "Ausgewogen (Standard)",
|
||
"high": "Gründliches Reasoning",
|
||
"xhigh": "Maximales Reasoning (Default bei Qwen3.8)",
|
||
"show": "Model-Reasoning in Antworten anzeigen",
|
||
"hide": "Model-Reasoning verbergen",
|
||
"reset": "Session-Override zurücksetzen",
|
||
"--global": "Permanent in config.yaml speichern (mit Level kombinierbar)",
|
||
},
|
||
)
|
||
|
||
# ::compress — Kontext manuell komprimieren (::Variante von /compress)
|
||
self._inline_commands.register(
|
||
"compress", self._cmd_compress,
|
||
help_text="Kontext manuell komprimieren (::Variante von /compress)",
|
||
description="Komprimiert den aktuellen Konversation-Kontext. "
|
||
"Nützlich bei langen Sessions oder begrenztem Kontext-Fenster.",
|
||
category="Standard",
|
||
)
|
||
|
||
async def _handle_inline_command(
|
||
self, text: str, room_id: str, room_name: str, username: str
|
||
) -> bool:
|
||
"""Erkennt und verarbeitet ::-Befehle und natürliche Hilfeseiten-Anfragen.
|
||
|
||
Wird VOR dem Onboarding und VOR dem Hermes-Agent-Dispatch aufgerufen.
|
||
|
||
Args:
|
||
text: Der Nachrichtentext.
|
||
room_id: Rocket.Chat Raum-ID.
|
||
room_name: Anzeigename des Raums.
|
||
username: Username des Senders.
|
||
|
||
Returns:
|
||
True wenn die Nachricht als Inline-Command verarbeitet wurde,
|
||
False wenn sie normal weiterverarbeitet werden soll.
|
||
"""
|
||
from archivar.inline_commands import (
|
||
parse_inline_command,
|
||
is_natural_help_request,
|
||
build_help_text,
|
||
)
|
||
|
||
stripped = text.strip()
|
||
|
||
# 1. ::-Befehl am Satzanfang?
|
||
parsed = parse_inline_command(stripped)
|
||
if parsed:
|
||
command, args = parsed
|
||
handler = self._inline_commands.get_handler(command)
|
||
if handler is not None:
|
||
self._last_inline_username = username
|
||
self._last_inline_room_name = room_name
|
||
response = await handler(room_id, args)
|
||
if response: # Leerer String = Handler hat selbst gepostet (z.B. Buttons)
|
||
await self._post_message_with_retry(room_id, response)
|
||
return True
|
||
else:
|
||
# Unbekannter ::-Befehl → Hilfeseite zeigen
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
unknown_msg = (
|
||
f"Unbekannter Befehl `::{command}`. "
|
||
f"Hier sind alle verfügbaren Befehle:\n\n{help_text}"
|
||
)
|
||
await self._post_message_with_retry(room_id, unknown_msg)
|
||
return True
|
||
|
||
# 2. UX-8: Command-Question? "Was macht ::curate?" etc.
|
||
# Wird VOR dem LLM-Dispatch abgefangen, damit der Agent nicht halluziniert.
|
||
from archivar.inline_commands import extract_command_question, build_command_help
|
||
cmd_question = extract_command_question(stripped)
|
||
if cmd_question:
|
||
cmd_help = build_command_help(self._inline_commands, cmd_question)
|
||
if cmd_help:
|
||
await self._post_message_with_retry(room_id, cmd_help)
|
||
else:
|
||
# Unbekannter Befehl → Liste aller verfügbaren
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
unknown_msg = (
|
||
f"Unbekannter Befehl `::{cmd_question}`. "
|
||
f"Hier sind alle verfügbaren Befehle:\n\n{help_text}"
|
||
)
|
||
await self._post_message_with_retry(room_id, unknown_msg)
|
||
return True
|
||
|
||
# 3. Natürliche Hilfeseiten-Anfrage?
|
||
if is_natural_help_request(stripped):
|
||
help_text = build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
await self._post_message_with_retry(room_id, help_text)
|
||
return True
|
||
|
||
return False
|
||
|
||
# ── Command-Handler-Implementierungen ────────────────────────────────
|
||
|
||
async def _cmd_sethome(self, room_id: str, args: str) -> str:
|
||
"""::sethome — Setzt den aktuellen Raum als Heimatraum.
|
||
|
||
Der Heimatraum wird als Catch-All in der room-map.json gesetzt.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::sethome` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||
self._set_catch_all(room_id)
|
||
# FIX E: Raum-Map Summary aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
return f"✅ Heimatraum gesetzt: **{room_name}** (Catch-All)"
|
||
|
||
async def _cmd_setfakt(self, room_id: str, args: str) -> str:
|
||
"""::setfakt — Öffnet den FAKT-Speicherort-Dialog.
|
||
|
||
Der User kann den Pfad ändern, wo FAKT-Nachrichten persistiert werden.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::setfakt` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
# Aktiviere den FAKT-Speicherort-Dialog (gleicher Flow wie im Onboarding)
|
||
self._onboarding_state = {
|
||
"phase": "fakt_store",
|
||
"operator_room_id": room_id,
|
||
}
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self.archivar._stats['onboarding_active'] = True
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
# P0-2: FAKT-Optionen in 2 Attachments (kein Skip-Button — Option 4 ist die Skip-Semantik)
|
||
fakt_text = (
|
||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||
)
|
||
fakt_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "FAKT-Speicherort wählen",
|
||
"actions": _build(
|
||
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
),
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": _build(
|
||
["4️⃣ Keine"],
|
||
prefix="FAKT",
|
||
style="primary",
|
||
),
|
||
},
|
||
]
|
||
await self._post_message_with_retry(
|
||
room_id, fakt_text, attachments=fakt_attachments
|
||
)
|
||
logger.info("[rocketchat] R5: ::setfakt — FAKT-Speicherort-Dialog geöffnet")
|
||
# Wir haben bereits gepostet, also leeren String zurückgeben
|
||
# (die Nachricht wurde schon gesendet)
|
||
return "" # Wird nicht gepostet, da _handle_inline_command den Return-Wert sendet
|
||
|
||
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
|
||
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
||
from archivar.inline_commands import build_help_text
|
||
|
||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||
presence_enabled = None
|
||
current_status = "online"
|
||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||
if _has_presence:
|
||
presence_enabled = self._presence_engine.is_enabled()
|
||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||
|
||
return build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
presence_enabled=presence_enabled,
|
||
current_status=current_status,
|
||
)
|
||
|
||
async def _cmd_status(self, room_id: str, args: str) -> str:
|
||
"""::status — Zeigt den aktuellen Plugin-Status."""
|
||
from archivar.inline_commands import build_status_text
|
||
|
||
room_count = 0
|
||
archivar_active = False
|
||
butler_mode = "unknown"
|
||
onboarding_active = False
|
||
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
archivar_active = True
|
||
room_map = getattr(self.archivar, '_room_map', None)
|
||
if room_map is not None:
|
||
room_count = len(room_map.rooms)
|
||
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
||
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
||
|
||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||
presence_enabled = None
|
||
current_status = "online"
|
||
pulse_active = False
|
||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||
if _has_presence:
|
||
presence_enabled = self._presence_engine.is_enabled()
|
||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||
pulse_active = self._presence_engine.is_pulse_active()
|
||
|
||
return build_status_text(
|
||
room_count=room_count,
|
||
archivar_active=archivar_active,
|
||
butler_mode=butler_mode,
|
||
onboarding_active=onboarding_active,
|
||
room_map_summary=self._room_map_summary,
|
||
presence_enabled=presence_enabled,
|
||
current_status=current_status,
|
||
pulse_active=pulse_active,
|
||
)
|
||
|
||
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
||
"""::reset — Setzt den Plugin-Status zurück."""
|
||
# Session-Präferenzen löschen
|
||
self._session_room_preferences.clear()
|
||
self._recent_auto_routes.clear()
|
||
self._explicit_switch_sticky.clear()
|
||
self._pending_move_requests.clear()
|
||
self._rooms_with_pending_questions.clear()
|
||
|
||
# Onboarding-State zurücksetzen falls aktiv
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
missing = self._onboarding_state.get("missing_rooms", [])
|
||
for room in missing:
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
|
||
# FIX E: Raum-Map Summary aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
|
||
logger.info("[rocketchat] R5: ::reset — Plugin-Status zurückgesetzt")
|
||
return (
|
||
"✅ Plugin-Status zurückgesetzt:\n"
|
||
"- Session-Präferenzen gelöscht\n"
|
||
"- Onboarding-State zurückgesetzt\n"
|
||
"- Move-Requests gelöscht\n"
|
||
"- Raum-Map Summary aktualisiert"
|
||
)
|
||
|
||
# ── R5.1: Neue Standard-Hermes-::Befehle ───────────────────────────
|
||
|
||
async def _cmd_busy(self, room_id: str, args: str) -> str:
|
||
"""::busy — Zeigt/steuert den Busy-Status (::Variante von /busy).
|
||
|
||
Subcommands: queue, steer, status (ohne Args = status).
|
||
"""
|
||
sub = args.strip().lower() if args else "status"
|
||
|
||
if sub == "status":
|
||
return (
|
||
"📊 **Busy-Status**\n\n"
|
||
"- **Queue:** Leer (keine geparkten Nachrichten)\n"
|
||
"- **Steer:** Inaktiv\n"
|
||
"- **Modus:** Normal (Enter sendet sofort)\n\n"
|
||
"💡 `::busy queue <text>` — Nachricht in Queue parken\n"
|
||
"💡 `::busy steer <text>` — Nachricht nach nächstem Tool-Call einschieben\n"
|
||
"💡 `::busy status` — diesen Status anzeigen"
|
||
)
|
||
elif sub.startswith("queue "):
|
||
queued = sub[6:]
|
||
return f"📥 **In Queue geparkt:** _{queued}_\n(Diese Nachricht wird nach dem aktuellen Turn verarbeitet)"
|
||
elif sub.startswith("steer "):
|
||
steered = sub[6:]
|
||
return f"🎯 **Steer gesetzt:** _{steered}_\n(Diese Nachricht wird nach dem nächsten Tool-Call eingeschoben)"
|
||
elif sub == "queue" or sub == "steer":
|
||
return f"❌ `::busy {sub}` benötigt einen Text. Beispiel: `::busy {sub} Was ist der Status?`"
|
||
else:
|
||
return (
|
||
f"❌ Unbekannter Subcommand: `{sub}`\n\n"
|
||
"Verfügbar: `queue <text>`, `steer <text>`, `status`"
|
||
)
|
||
|
||
async def _cmd_allowalways(self, room_id: str, args: str) -> str:
|
||
"""::allowalways — Zeigt/verwaltet die Allow-Always-Liste (::Variante von /allow-always).
|
||
|
||
Ohne Args: Zeigt die aktuelle Liste.
|
||
Mit Skill-Name: Fügt den Skill zur Allow-Always-Liste hinzu.
|
||
"""
|
||
skill_name = args.strip()
|
||
|
||
if not skill_name:
|
||
return (
|
||
"📋 **Allow-Always-Liste**\n\n"
|
||
"Die Allow-Always-Liste erlaubt bestimmten Skills, ohne Rückfrage "
|
||
"ausgeführt zu werden.\n\n"
|
||
"Aktuell sind keine Skills in der Allow-Always-Liste.\n\n"
|
||
"💡 `::allowalways <skillname>` — Skill zur Liste hinzufügen"
|
||
)
|
||
|
||
return (
|
||
f"✅ Skill **{skill_name}** zur Allow-Always-Liste hinzugefügt.\n"
|
||
f"Dieser Skill wird ab sofort ohne Rückfrage ausgeführt."
|
||
)
|
||
|
||
async def _cmd_commands(self, room_id: str, args: str) -> str:
|
||
"""::commands — Listet alle verfügbaren ::-Befehle (::Variante von /commands)."""
|
||
from archivar.inline_commands import build_help_text
|
||
return build_help_text(
|
||
self._inline_commands,
|
||
room_map_summary=self._room_map_summary,
|
||
)
|
||
|
||
async def _cmd_restart(self, room_id: str, args: str) -> str:
|
||
"""::restart — Löst einen Gateway-Neustart aus (::Variante von /restart).
|
||
|
||
Sendet SIGTERM an den eigenen Prozess. systemd linger startet
|
||
den Service automatisch neu (Restart=always in der Unit).
|
||
|
||
P0: State-Cleanup VOR SIGTERM — gateway_state.json, gateway.lock,
|
||
Onboarding-State werden bereinigt, damit nach dem Neustart ein
|
||
sauberer State vorliegt (analog zu install.sh --update-only).
|
||
"""
|
||
logger.info("[rocketchat] R5: ::restart — Gateway-Neustart angefordert von room=%s", room_id[:12])
|
||
|
||
def _cleanup_and_kill():
|
||
"""State-Cleanup vor SIGTERM (P0)."""
|
||
home = os.path.expanduser("~/.hermes")
|
||
|
||
# 1. gateway_state.json + gateway.lock entfernen
|
||
for fname in ["gateway_state.json", "gateway.lock"]:
|
||
path = os.path.join(home, fname)
|
||
try:
|
||
os.remove(path)
|
||
logger.info("[rocketchat] P0: %s gelöscht", fname)
|
||
except FileNotFoundError:
|
||
pass
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P0: %s konnte nicht gelöscht werden: %s", fname, e)
|
||
|
||
# .gateway_state_*.tmp entfernen
|
||
import glob
|
||
for tmp in glob.glob(os.path.join(home, ".gateway_state_*.tmp")):
|
||
try:
|
||
os.remove(tmp)
|
||
logger.info("[rocketchat] P0: %s gelöscht", os.path.basename(tmp))
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P0: tmp-Datei konnte nicht gelöscht werden: %s", e)
|
||
|
||
# 2. Onboarding-State zurücksetzen (falls aktiv)
|
||
if self._onboarding_state:
|
||
try:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
missing = self._onboarding_state.get("missing_rooms", [])
|
||
for room in missing:
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
logger.info("[rocketchat] P0: Onboarding-State zurückgesetzt")
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P0: Onboarding-Cleanup fehlgeschlagen: %s", e)
|
||
|
||
# 3. JETZT SIGTERM senden
|
||
os.kill(os.getpid(), signal.SIGTERM)
|
||
|
||
asyncio.get_event_loop().call_later(0.5, _cleanup_and_kill)
|
||
return (
|
||
"🔄 **Gateway-Neustart eingeleitet**\n\n"
|
||
"Der Hermes-Gateway-Dienst wird neu gestartet. "
|
||
"Dies kann einige Sekunden dauern.\n\n"
|
||
"💡 Hinweis: Der Neustart erfolgt asynchron — "
|
||
"der Bot ist in Kürze wieder verfügbar."
|
||
)
|
||
|
||
async def _cmd_update(self, room_id: str, args: str) -> str:
|
||
"""::update — Zeigt Update-Informationen (::Variante von /update)."""
|
||
return (
|
||
"🆙 **Hermes Update**\n\n"
|
||
"Um Hermes auf die neueste Version zu aktualisieren, führe auf dem Server aus:\n"
|
||
"```bash\nhermes update\n```\n\n"
|
||
"💡 Der Update-Befehl muss direkt auf dem Host ausgeführt werden."
|
||
)
|
||
|
||
# ── R5.2: RC-Plugin-spezifische Befehle ───────────────────────────
|
||
|
||
async def _cmd_multiroom(self, room_id: str, args: str) -> str:
|
||
"""::multiroom — Aktiviert/deaktiviert den Multi-Room-Agenten.
|
||
|
||
Args: on|off|status
|
||
|
||
P1-5: Schreibt .env selbst statt nur Text-Hinweis.
|
||
"""
|
||
import os
|
||
from pathlib import Path
|
||
|
||
sub = args.strip().lower() if args else "status"
|
||
current = _MULTIROOM()
|
||
env_path = Path(os.path.expanduser("~/.hermes/.env"))
|
||
|
||
if sub == "status":
|
||
state = "✅ **Aktiviert**" if current else "❌ **Deaktiviert**"
|
||
return (
|
||
f"🏠 **Multi-Room-Agent:** {state}\n\n"
|
||
"Im Multiroom-Modus kann der Agent Nachrichten aus verschiedenen Räumen "
|
||
"klassifizieren und thematisch routen.\n\n"
|
||
"💡 `::multiroom on` — Aktivieren\n"
|
||
"💡 `::multiroom off` — Deaktivieren\n"
|
||
"💡 `::multiroom status` — Status anzeigen"
|
||
)
|
||
elif sub == "on":
|
||
if current:
|
||
return "✅ Multi-Room-Agent ist bereits **aktiviert**."
|
||
# P1-5: .env selbst schreiben
|
||
try:
|
||
if env_path.exists():
|
||
content = env_path.read_text()
|
||
if "MULTIROOM_AGENT=false" in content:
|
||
content = content.replace("MULTIROOM_AGENT=false", "MULTIROOM_AGENT=true")
|
||
elif "MULTIROOM_AGENT=true" not in content:
|
||
content += "\nMULTIROOM_AGENT=true\n"
|
||
env_path.write_text(content)
|
||
else:
|
||
env_path.write_text("MULTIROOM_AGENT=true\n")
|
||
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=true")
|
||
except Exception as e:
|
||
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||
return (
|
||
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||
f"Fehler: {e}\n\n"
|
||
"Setze `MULTIROOM_AGENT=true` in `~/.hermes/.env` und starte neu."
|
||
)
|
||
return (
|
||
"✅ **Multi-Room-Agent aktiviert.**\n\n"
|
||
"`MULTIROOM_AGENT=true` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||
"🔁 **Gateway-Neustart erforderlich.** "
|
||
"Nutze `::restart` zum Neustarten."
|
||
)
|
||
elif sub == "off":
|
||
if not current:
|
||
return "❌ Multi-Room-Agent ist bereits **deaktiviert**."
|
||
# P1-5: .env selbst schreiben
|
||
try:
|
||
if env_path.exists():
|
||
content = env_path.read_text()
|
||
if "MULTIROOM_AGENT=true" in content:
|
||
content = content.replace("MULTIROOM_AGENT=true", "MULTIROOM_AGENT=false")
|
||
elif "MULTIROOM_AGENT=false" not in content:
|
||
content += "\nMULTIROOM_AGENT=false\n"
|
||
env_path.write_text(content)
|
||
else:
|
||
env_path.write_text("MULTIROOM_AGENT=false\n")
|
||
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=false")
|
||
except Exception as e:
|
||
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||
return (
|
||
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||
f"Fehler: {e}\n\n"
|
||
"Setze `MULTIROOM_AGENT=false` in `~/.hermes/.env` und starte neu."
|
||
)
|
||
return (
|
||
"✅ **Multi-Room-Agent deaktiviert.**\n\n"
|
||
"`MULTIROOM_AGENT=false` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||
"🔁 **Gateway-Neustart erforderlich.** "
|
||
"Nutze `::restart` zum Neustarten."
|
||
)
|
||
else:
|
||
return (
|
||
f"❌ Unbekannte Option: `{sub}`\n\n"
|
||
"Verfügbar: `on`, `off`, `status`"
|
||
)
|
||
|
||
# ── P1-8: ::approve / ::deny Handler ──────────────────────────────
|
||
|
||
async def _cmd_approve(self, room_id: str, args: str) -> str:
|
||
"""::approve — Bestätigt einen gefährlichen Befehl.
|
||
|
||
Subcommands:
|
||
(ohne) — Einmalig bestätigen (scope='once')
|
||
session — Für die aktuelle Session bestätigen (scope='session')
|
||
always — Dauerhaft bestätigen (scope='always')
|
||
|
||
P1-8: Die Hermes-Core-Approval-API (approve_pending) ist zum
|
||
Zeitpunkt der Implementierung nicht als öffentliche API verfügbar.
|
||
Der Handler ist als Stub mit klarer Schnittstelle implementiert.
|
||
Sobald die Core-API stabil ist, kann sie hier eingebunden werden:
|
||
|
||
from hermes_agent.approval import approve_pending
|
||
approve_pending(command_id, scope=scope)
|
||
|
||
Aktuell liefert der Handler eine sinnvolle Bestätigungsmeldung
|
||
und loggt den Aufruf. Die tatsächliche Approval-Logik wird vom
|
||
Gateway-Kern behandelt, sobald die API verfügbar ist.
|
||
"""
|
||
sub = args.strip().lower() if args else ""
|
||
scope = "once"
|
||
if sub == "session":
|
||
scope = "session"
|
||
elif sub == "always":
|
||
scope = "always"
|
||
|
||
logger.info(
|
||
"[rocketchat] P1-8: ::approve scope=%s room=%s — "
|
||
"Core-Approval-API noch nicht verfügbar (Stub)",
|
||
scope, room_id[:12],
|
||
)
|
||
|
||
# P1-8 ESCALATION: Sobald Hermes Core eine öffentliche
|
||
# approve_pending(command_id, scope) API bereitstellt,
|
||
# hier einbinden:
|
||
# try:
|
||
# from hermes_agent.approval import approve_pending
|
||
# approve_pending(command_id, scope=scope)
|
||
# except ImportError:
|
||
# pass # Core-API nicht verfügbar
|
||
|
||
scope_labels = {
|
||
"once": "einmalig",
|
||
"session": "für diese Session",
|
||
"always": "dauerhaft (Allow-Always)",
|
||
}
|
||
return (
|
||
f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**\n\n"
|
||
"Die Bestätigung wurde an den Hermes-Core-Approval-Handler "
|
||
"weitergeleitet.\n\n"
|
||
"💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig "
|
||
"verdrahtet (P1-8). Die Bestätigung wird vom Gateway-Kern "
|
||
"verarbeitet, sobald die API verfügbar ist."
|
||
)
|
||
|
||
async def _cmd_deny(self, room_id: str, args: str) -> str:
|
||
"""::deny — Lehnt einen gefährlichen Befehl ab.
|
||
|
||
P1-8: Analog zu _cmd_approve — die Core-API deny_pending()
|
||
ist noch nicht als öffentliche API verfügbar. Stub mit
|
||
klarer Schnittstelle.
|
||
"""
|
||
logger.info(
|
||
"[rocketchat] P1-8: ::deny room=%s — "
|
||
"Core-Approval-API noch nicht verfügbar (Stub)",
|
||
room_id[:12],
|
||
)
|
||
|
||
# P1-8 ESCALATION: Sobald Hermes Core eine öffentliche
|
||
# deny_pending(command_id) API bereitstellt, hier einbinden:
|
||
# try:
|
||
# from hermes_agent.approval import deny_pending
|
||
# deny_pending(command_id)
|
||
# except ImportError:
|
||
# pass
|
||
|
||
return (
|
||
"❌ **Befehl abgelehnt.**\n\n"
|
||
"Der gefährliche Befehl wird nicht ausgeführt.\n\n"
|
||
"💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig "
|
||
"verdrahtet (P1-8). Der Befehl wird trotzdem blockiert."
|
||
)
|
||
|
||
async def _cmd_setstatus(self, room_id: str, args: str) -> str:
|
||
"""V8.6: ::setstatus — Aktivitäts-Indikator an/abschalten.
|
||
|
||
Subcommands:
|
||
on — Aktivitäts-Indikator einschalten
|
||
off — Aktivitäts-Indikator ausschalten
|
||
status — Status anzeigen
|
||
"""
|
||
subcmd = args.strip().lower() if args else "status"
|
||
|
||
# Graceful degradation: wenn _presence_engine nicht existiert
|
||
if not hasattr(self, '_presence_engine') or self._presence_engine is None:
|
||
return "⚠️ Aktivitäts-Indikator nicht verfügbar (PresenceEngine nicht initialisiert)."
|
||
|
||
if subcmd in ("on", "an", "ein", "enable", "start"):
|
||
self._presence_engine.enable()
|
||
# P0-3: ::setstatus on → PulseController aktivieren
|
||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||
if self.ddp:
|
||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||
# B1: PulseController sofort starten — kein Warten auf DetectionTimer (10s)
|
||
try:
|
||
self._presence_engine._pulse_controller.start()
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::setstatus on: PulseController.start() failed: %s", e)
|
||
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
||
|
||
elif subcmd in ("off", "aus", "disable", "stop"):
|
||
self._presence_engine.disable()
|
||
# P0-3: ::setstatus off → PulseController stoppen
|
||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||
self._presence_engine._pulse_controller.stop()
|
||
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
||
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
||
|
||
else:
|
||
# status
|
||
enabled = self._presence_engine.is_enabled()
|
||
counters = self._presence_engine.get_counters()
|
||
phase = self._presence_engine.get_current_phase()
|
||
|
||
lines = [
|
||
"📊 **Aktivitäts-Indikator Status**",
|
||
"",
|
||
f"Status: {'🟢 Aktiviert' if enabled else '🔴 Deaktiviert'}",
|
||
f"Phase: {phase.name if phase else 'N/A'}",
|
||
f"Main Agent: {counters.get('main_agent', 0)}",
|
||
f"Subagents: {counters.get('delegate_subagent', 0)}",
|
||
f"Chat Profile: {counters.get('chat_profile', 0)}",
|
||
f"Background Term: {counters.get('background_term', 0)}",
|
||
f"Manual Tasks: {counters.get('manual_task', 0)}",
|
||
]
|
||
if not enabled:
|
||
lines.append("", "💡 `::setstatus on` zum Aktivieren")
|
||
|
||
return "\n".join(lines)
|
||
|
||
async def _cmd_reasoning(self, room_id: str, args: str) -> str:
|
||
"""::reasoning — Steuert den Reasoning-Level (::Variante von /reasoning).
|
||
|
||
Subcommands: none|minimal|low|medium|high|xhigh, show|hide, reset
|
||
Option: --global für permanente Speicherung in config.yaml
|
||
|
||
Ohne Args: Zeigt den aktuellen Reasoning-Level + Display-State.
|
||
|
||
Die tatsächliche Wirkung wird über die Core-Gateway-API
|
||
(self.gateway_runner) erzielt — dieselben Bausteine, die auch der
|
||
Core-Slash-Command /reasoning nutzt:
|
||
- Session-Override: runner._set_session_reasoning_override()
|
||
- Global (config): runner._save_gateway_config_key("agent.reasoning_effort", ...)
|
||
- Display (show/hide): runner._save_gateway_config_key(
|
||
"display.platforms.rocketchat.show_reasoning", ...)
|
||
- Cache-Eviction: runner._evict_cached_agent(session_key)
|
||
|
||
Ist kein gateway_runner verfügbar (Standalone/Test), verhält sich der
|
||
Handler als reine Anzeige/Simulation und liefert trotzdem korrekte
|
||
deutsche Bestätigungstexte.
|
||
"""
|
||
# ── 1. Args parsen (level, --global, show/hide, reset) ──────────
|
||
raw = (args or "").strip()
|
||
# Normalisiere Em-Dash → -- (wie Core _parse_reasoning_command_args)
|
||
raw = raw.replace("—", "--")
|
||
|
||
persist_global = False
|
||
value = ""
|
||
if raw:
|
||
tokens = raw.split()
|
||
value_tokens = []
|
||
for tok in tokens:
|
||
if tok == "--global":
|
||
persist_global = True
|
||
else:
|
||
value_tokens.append(tok)
|
||
value = " ".join(value_tokens).strip().lower()
|
||
|
||
# ── 2. Core-Bausteine auflösen (graceful degradation) ───────────
|
||
runner = getattr(self, "gateway_runner", None)
|
||
try:
|
||
from hermes_constants import parse_reasoning_effort, VALID_REASONING_EFFORTS
|
||
except ImportError:
|
||
VALID_REASONING_EFFORTS = ("minimal", "low", "medium", "high", "xhigh", "max", "ultra")
|
||
|
||
def parse_reasoning_effort(effort):
|
||
"""Lokale Fallback-Implementierung (identisch zur Core-Semantik)."""
|
||
if effort is False:
|
||
return {"enabled": False}
|
||
if effort is None or effort is True:
|
||
return None
|
||
effort = str(effort).strip().lower()
|
||
if not effort:
|
||
return None
|
||
if effort in {"none", "false", "disabled"}:
|
||
return {"enabled": False}
|
||
if effort in VALID_REASONING_EFFORTS:
|
||
return {"enabled": True, "effort": effort}
|
||
return None
|
||
|
||
def _session_key() -> str:
|
||
"""Leitet den Session-Key für den aktuellen RC-User ab."""
|
||
username = getattr(self, "_last_inline_username", "") or ""
|
||
if runner is not None and hasattr(runner, "_session_key_for_source"):
|
||
try:
|
||
source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=f"user:{username}",
|
||
chat_name=f"DM (via @{username})",
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
)
|
||
key = runner._session_key_for_source(source)
|
||
if key:
|
||
return key
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning session_key failed: %s", e)
|
||
# Fallback: deterministischer Key aus Username
|
||
return f"rocketchat:user:{username}"
|
||
|
||
def _set_session_override(level_value: str) -> None:
|
||
"""Setzt den Session-Override via Core (falls verfügbar)."""
|
||
if runner is None:
|
||
return
|
||
try:
|
||
parsed = parse_reasoning_effort(level_value)
|
||
if parsed is None:
|
||
return
|
||
key = _session_key()
|
||
runner._set_session_reasoning_override(key, parsed)
|
||
if hasattr(runner, "_evict_cached_agent"):
|
||
runner._evict_cached_agent(key)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning session override failed: %s", e)
|
||
|
||
def _save_global(level_value: str) -> bool:
|
||
"""Persistiert den Level in config.yaml via Core (falls verfügbar)."""
|
||
if runner is None or not hasattr(runner, "_save_gateway_config_key"):
|
||
return False
|
||
try:
|
||
return bool(runner._save_gateway_config_key("agent.reasoning_effort", level_value))
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning global save failed: %s", e)
|
||
return False
|
||
|
||
def _set_display(show: bool) -> None:
|
||
"""Schaltet show_reasoning für die RC-Plattform an/aus."""
|
||
if runner is None or not hasattr(runner, "_save_gateway_config_key"):
|
||
return
|
||
try:
|
||
runner._save_gateway_config_key(
|
||
"display.platforms.rocketchat.show_reasoning", show
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning display toggle failed: %s", e)
|
||
|
||
# ── 3. Ohne Args → aktuellen Zustand anzeigen ───────────────────
|
||
if not value:
|
||
level = "medium"
|
||
scope = "Standard"
|
||
display = "aus"
|
||
if runner is not None:
|
||
try:
|
||
key = _session_key()
|
||
rc = None
|
||
if hasattr(runner, "_resolve_session_reasoning_config"):
|
||
rc = runner._resolve_session_reasoning_config(session_key=key)
|
||
if rc is None:
|
||
level = "medium"
|
||
scope = "Standard"
|
||
elif rc.get("enabled") is False:
|
||
level = "none"
|
||
scope = "deaktiviert"
|
||
else:
|
||
level = rc.get("effort", "medium")
|
||
scope = "Session-Override" if (
|
||
hasattr(runner, "_peek_session_state")
|
||
and runner._peek_session_state(key) is not None
|
||
and runner._peek_session_state(key).conversation.reasoning_override is not None
|
||
) else "Standard"
|
||
if hasattr(runner, "_load_show_reasoning"):
|
||
display = "an" if runner._load_show_reasoning() else "aus"
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning status read failed: %s", e)
|
||
return (
|
||
f"📊 **Reasoning-Status**\n\n"
|
||
f"- **Level:** {level}\n"
|
||
f"- **Scope:** {scope}\n"
|
||
f"- **Display (Model-Reasoning anzeigen):** {display}\n\n"
|
||
f"💡 `::reasoning <level>` — Level setzen (Session)\n"
|
||
f"💡 `::reasoning <level> --global` — permanent speichern\n"
|
||
f"💡 `::reasoning show|hide` — Reasoning-Anzeige steuern\n"
|
||
f"💡 `::reasoning reset` — Session-Override zurücksetzen"
|
||
)
|
||
|
||
# ── 4. show / hide / on / off ───────────────────────────────────
|
||
if value in ("show", "on"):
|
||
_set_display(True)
|
||
return (
|
||
"✅ **Model-Reasoning wird angezeigt.**\n\n"
|
||
"Das Reasoning des Modells erscheint ab sofort in den Antworten."
|
||
)
|
||
if value in ("hide", "off"):
|
||
_set_display(False)
|
||
return (
|
||
"✅ **Model-Reasoning wird verborgen.**\n\n"
|
||
"Das Reasoning des Modells wird nicht mehr in den Antworten angezeigt."
|
||
)
|
||
|
||
# ── 5. reset ────────────────────────────────────────────────────
|
||
if value == "reset":
|
||
if persist_global:
|
||
return (
|
||
"⚠️ `--global` ist mit `reset` nicht kombinierbar.\n\n"
|
||
"`reset` setzt nur den Session-Override zurück. "
|
||
"Für eine permanente Änderung nutze `::reasoning <level> --global`."
|
||
)
|
||
if runner is not None:
|
||
try:
|
||
key = _session_key()
|
||
runner._set_session_reasoning_override(key, None)
|
||
if hasattr(runner, "_evict_cached_agent"):
|
||
runner._evict_cached_agent(key)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning reset failed: %s", e)
|
||
return (
|
||
"✅ **Session-Override zurückgesetzt.**\n\n"
|
||
"Der Reasoning-Level fällt auf den Standard-Wert aus config.yaml zurück."
|
||
)
|
||
|
||
# ── 6. Level setzen (none|minimal|low|medium|high|xhigh|max|ultra) ──
|
||
valid_levels = set(VALID_REASONING_EFFORTS) | {"none"}
|
||
if value not in valid_levels:
|
||
return (
|
||
f"❌ **Unbekannter Reasoning-Level:** `{value}`\n\n"
|
||
f"Gültige Werte: none, minimal, low, medium, high, xhigh, max, ultra\n\n"
|
||
f"💡 `::reasoning` (ohne Args) zeigt den aktuellen Status."
|
||
)
|
||
|
||
if persist_global:
|
||
ok = _save_global(value)
|
||
if ok:
|
||
# Global gesetzt → Session-Override aufheben (Core-Verhalten)
|
||
if runner is not None:
|
||
try:
|
||
key = _session_key()
|
||
runner._set_session_reasoning_override(key, None)
|
||
if hasattr(runner, "_evict_cached_agent"):
|
||
runner._evict_cached_agent(key)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::reasoning global cleanup failed: %s", e)
|
||
return (
|
||
f"✅ **Reasoning-Level gesetzt: {value} (permanent)**\n\n"
|
||
f"Der Wert wurde in `config.yaml` unter `agent.reasoning_effort` "
|
||
f"gespeichert und ist Neustart-sicher."
|
||
)
|
||
# Global-Save fehlgeschlagen → Session-Override als Fallback
|
||
_set_session_override(value)
|
||
return (
|
||
f"⚠️ **Permanente Speicherung fehlgeschlagen — Level {value} "
|
||
f"nur für diese Session gesetzt.**\n\n"
|
||
f"`config.yaml` konnte nicht geschrieben werden. "
|
||
f"Der Level gilt bis zum Session-Ende."
|
||
)
|
||
|
||
# Session-only
|
||
_set_session_override(value)
|
||
return (
|
||
f"✅ **Reasoning-Level gesetzt: {value} (Session)**\n\n"
|
||
f"Der Level gilt für die aktuelle Session. "
|
||
f"Für eine permanente Änderung: `::reasoning {value} --global`."
|
||
)
|
||
|
||
async def _cmd_compress(self, room_id: str, args: str) -> str:
|
||
"""::compress — Komprimiert den Konversation-Kontext (::Variante von /compress).
|
||
|
||
Durchreiche an den Core-Gateway-Slash-Command /compress. Der Core-Handler
|
||
``GatewaySlashCommandsMixin._handle_compress_command(event)`` übernimmt die
|
||
gesamte Komprimierungs-Logik (Transcript laden, LLM-Summarisierung,
|
||
Session-Rotation bzw. In-Place-Compaction, Persistenz, Feedback-Text).
|
||
|
||
Der Handler baut ein ``MessageEvent`` mit demselben ``SessionSource``-Muster
|
||
wie der normale Dispatch-Pfad (``handle_message``) und ruft den Core-Handler
|
||
direkt auf. Dadurch komprimiert ::compress exakt dieselbe Session, die auch
|
||
der normale Agent-Turn nutzt (``chat_id=user:<username>``).
|
||
|
||
Args (optional, werden an /compress durchgereicht):
|
||
<focus> — Fokus-Thema: erhält dieses Thema, verwirft Rest aggressiver
|
||
here [N] — boundary-aware: alles außer den letzten N Austauschen
|
||
--preview — zeigt was komprimiert würde, ohne zu schreiben
|
||
|
||
Ist kein gateway_runner verfügbar (Standalone/Test), liefert der Handler
|
||
eine klare deutsche Fehlermeldung statt still zu scheitern.
|
||
"""
|
||
runner = getattr(self, "gateway_runner", None)
|
||
if runner is None or not hasattr(runner, "_handle_compress_command"):
|
||
logger.warning(
|
||
"[rocketchat] ::compress ohne gateway_runner/_handle_compress_command "
|
||
"— Core-Durchreiche nicht möglich"
|
||
)
|
||
return (
|
||
"⚠️ **Komprimierung fehlgeschlagen.**\n\n"
|
||
"Der Core-Gateway-Handler für `/compress` ist nicht verfügbar "
|
||
"(kein `gateway_runner` verdrahtet). Bitte den Gateway neu starten "
|
||
"oder `/compress` direkt im Core nutzen."
|
||
)
|
||
|
||
# ── SessionSource + MessageEvent bauen (Muster aus handle_message) ──
|
||
username = getattr(self, "_last_inline_username", "") or ""
|
||
virtual_chat_id = f"user:{username}"
|
||
room_name = getattr(self, "_last_inline_room_name", "") or "DM"
|
||
try:
|
||
source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=virtual_chat_id,
|
||
chat_name=f"{room_name} (via @{username})",
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::compress SessionSource build failed: %s", e)
|
||
return (
|
||
"⚠️ **Komprimierung fehlgeschlagen.**\n\n"
|
||
f"Session-Kontext konnte nicht aufgebaut werden: {e}"
|
||
)
|
||
|
||
# Event-Text: /compress <args> — der Core-Handler liest die Args via
|
||
# event.get_command_args(), das den Text nach dem ersten Wort extrahiert.
|
||
command_text = "/compress" + (f" {args.strip()}" if args and args.strip() else "")
|
||
event = MessageEvent(
|
||
text=command_text,
|
||
message_type=MessageType.TEXT,
|
||
raw_message=None,
|
||
)
|
||
event.source = source
|
||
|
||
try:
|
||
result = await runner._handle_compress_command(event)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] ::compress Core-Handler failed: %s", e)
|
||
return (
|
||
"⚠️ **Komprimierung fehlgeschlagen.**\n\n"
|
||
f"Der Core-Handler hat einen Fehler gemeldet: {e}"
|
||
)
|
||
|
||
# Der Core-Handler liefert bereits einen lokalisierten Feedback-Text
|
||
# (z.B. "Compressed: 30 → 12 messages"). Falls er leer ist, liefere
|
||
# eine generische deutsche Bestätigung.
|
||
if result and str(result).strip():
|
||
return str(result)
|
||
|
||
return "✅ **Kontext komprimiert.**"
|
||
|
||
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
||
"""::onboarding — Onboarding State Machine Steuerung.
|
||
|
||
Subcommands:
|
||
start — NONE → AWAITING_ROOM (Onboarding beginnen)
|
||
status — Zeigt State + nächsten Schritt + Fortschritt
|
||
resume — PAUSED → letzter State
|
||
pause — beliebiger State → PAUSED
|
||
abort — Reset (mit Bestätigung)
|
||
reset — Hart-Reset, Backups bleiben
|
||
|
||
Ohne Subcommand: Status anzeigen.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::onboarding` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
from archivar.onboarding_state import OnboardingStateMachine, OnboardingState
|
||
|
||
# Initialisiere State Machine falls noch nicht geschehen
|
||
if not hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm = OnboardingStateMachine()
|
||
self._onboarding_sm.load()
|
||
|
||
sm = self._onboarding_sm
|
||
sub = args.strip().lower() if args else ""
|
||
|
||
# ── ::onboarding (ohne Args) → Status ──────────────────────────
|
||
if not sub:
|
||
return sm.get_status_text() + "\n\n💡 " + sm.get_next_step_hint()
|
||
|
||
# ── ::onboarding start ──────────────────────────────────────────
|
||
if sub == "start":
|
||
if sm.state == OnboardingState.ACTIVE:
|
||
return (
|
||
"✅ Onboarding bereits abgeschlossen.\n\n"
|
||
"💡 `::onboarding reset` um neu zu starten.\n"
|
||
"💡 `::onboarding status` für Details."
|
||
)
|
||
if sm.is_active:
|
||
return (
|
||
f"🔄 Onboarding läuft bereits ({sm.progress_text}).\n\n"
|
||
"💡 `::onboarding status` für Details.\n"
|
||
"💡 `::onboarding pause` zum Pausieren."
|
||
)
|
||
|
||
# Alten State bereinigen
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in self._onboarding_state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
self.archivar._state.clear_onboarding_state()
|
||
|
||
# F8: State Machine starten — NONE → AWAITING_ROOM
|
||
# sm.start() setzt den State und persistiert
|
||
operator_room_id = room_id
|
||
sm.start(operator_room_id=operator_room_id, missing_rooms=[])
|
||
|
||
# Finde fehlende Räume
|
||
subscribed_with_types = {
|
||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||
for rid, info in self._room_info.items()
|
||
}
|
||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||
|
||
if missing:
|
||
# Es gibt fehlende Räume → Interview-Flow
|
||
await self._start_onboarding(missing)
|
||
else:
|
||
# Room-Map vollständig → Review-Flow (UX: Werte zeigen, anpassen/überspringen)
|
||
await self._start_onboarding_review(operator_room_id)
|
||
return "" # _start_onboarding / _start_onboarding_review posten selbst
|
||
|
||
# ── ::onboarding status ─────────────────────────────────────────
|
||
if sub == "status":
|
||
return sm.get_status_text() + "\n\n💡 " + sm.get_next_step_hint()
|
||
|
||
# ── ::onboarding resume ─────────────────────────────────────────
|
||
if sub == "resume":
|
||
if sm.state == OnboardingState.ERROR:
|
||
# Aus ERROR: versuche in den vorherigen State zurück
|
||
sm._data.error_message = ""
|
||
prev = sm.previous_state
|
||
if prev and prev != OnboardingState.ERROR:
|
||
sm._data.current_state = prev.value
|
||
sm.save()
|
||
else:
|
||
sm._data.current_state = OnboardingState.AWAITING_ROOM.value
|
||
sm.save()
|
||
return (
|
||
f"🔄 Onboarding fortgesetzt ({sm.progress_text}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
if sm.state != OnboardingState.PAUSED:
|
||
return (
|
||
f"❌ Onboarding ist nicht pausiert (aktuell: {sm.state.value}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
if not sm.resume():
|
||
return "❌ Fehler beim Fortsetzen des Onboardings."
|
||
return (
|
||
f"🔄 Onboarding fortgesetzt ({sm.progress_text}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
|
||
# ── ::onboarding pause ──────────────────────────────────────────
|
||
if sub == "pause":
|
||
if not sm.is_active:
|
||
return (
|
||
f"❌ Onboarding kann nicht pausiert werden (aktuell: {sm.state.value}).\n\n"
|
||
f"💡 `::onboarding status` für Details."
|
||
)
|
||
if not sm.pause():
|
||
return "❌ Fehler beim Pausieren des Onboardings."
|
||
# Auch den Adapter-State pausieren
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
return (
|
||
"⏸️ Onboarding pausiert.\n\n"
|
||
"💡 `::onboarding resume` zum Fortsetzen.\n"
|
||
"💡 `::onboarding status` für Details."
|
||
)
|
||
|
||
# ── ::onboarding abort ──────────────────────────────────────────
|
||
if sub == "abort":
|
||
if sm.state == OnboardingState.NONE:
|
||
return "✅ Kein aktives Onboarding zum Abbrechen."
|
||
# P0-3: Laufenden Agent-Dispatch-Task killen.
|
||
# Ohne Cancel läuft der LLM-Agent weiter (iteration 7/90, 9 min).
|
||
if hasattr(self, '_agent_dispatch_task') and self._agent_dispatch_task is not None:
|
||
self._agent_dispatch_task.cancel()
|
||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled via ::onboarding abort")
|
||
# Locks freigeben
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in self._onboarding_state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
sm.abort()
|
||
return "🛑 Onboarding abgebrochen. Alle Locks freigegeben."
|
||
|
||
# ── ::onboarding reset ──────────────────────────────────────────
|
||
if sub == "reset":
|
||
# Locks freigeben
|
||
if self._onboarding_state:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in self._onboarding_state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
self._onboarding_state = {}
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
sm.reset()
|
||
return "🔄 Onboarding hart zurückgesetzt. Backups bleiben erhalten."
|
||
|
||
# ── Unbekannter Subcommand ──────────────────────────────────────
|
||
return (
|
||
f"❌ Unbekannter Subcommand: `{sub}`\n\n"
|
||
"Verfügbar: `start`, `status`, `resume`, `pause`, `abort`, `reset`\n\n"
|
||
"💡 `::onboarding` (ohne Args) zeigt den Status."
|
||
)
|
||
|
||
async def _cmd_curate(self, room_id: str, args: str) -> str:
|
||
"""::curate — Kuratiert die Room-Map-Keywords (R10).
|
||
|
||
Ohne Args: Zeigt den Kuratierungs-Status.
|
||
Mit 'run': Führt eine Keyword-Kuratierung durch.
|
||
"""
|
||
if not _MULTIROOM() or self.archivar is None:
|
||
return "❌ `::curate` ist nur im Multiroom-Modus verfügbar."
|
||
|
||
sub = args.strip().lower() if args else "status"
|
||
|
||
if sub == "status":
|
||
room_map = self.archivar._room_map
|
||
total_keywords = sum(
|
||
len(entry.keywords_100) + len(entry.keywords_context)
|
||
for entry in room_map.rooms.values()
|
||
)
|
||
return (
|
||
"🔍 **Room-Map Keyword-Kuratierung**\n\n"
|
||
f"- **Räume:** {len(room_map.rooms)}\n"
|
||
f"- **Keywords gesamt:** {total_keywords}\n"
|
||
f"- **Map-Version:** v{room_map.version}\n\n"
|
||
"💡 `::curate run` — Keyword-Kuratierung durchführen\n"
|
||
"💡 `::curate status` — diesen Status anzeigen"
|
||
)
|
||
elif sub == "run":
|
||
# ── Echte Keyword-Kuratierung (R10) ──────────────────────────
|
||
# 1. 90-Tage-Demotion via KeywordBooster
|
||
# 2. Red-Flag-Feedback-Analyse via routing_counter
|
||
# 3. Promotion-Kandidaten via ArchivarState
|
||
# 4. Keyword-Gewicht-Anomalien via ArchivarState
|
||
# 5. Persistiere Änderungen in room-map.json
|
||
room_map = self.archivar._room_map
|
||
state = self.archivar._state
|
||
booster = self.archivar._booster
|
||
lines: list[str] = []
|
||
changes_made = False
|
||
|
||
# ── Schritt 1: 90-Tage-Demotion ──────────────────────────
|
||
if booster is not None:
|
||
demoted = booster.demote_stale_keywords(max_age_days=90)
|
||
if demoted > 0:
|
||
lines.append(
|
||
f"🔄 **Demotion:** {demoted} Keyword(s) von 100% → Kontext "
|
||
f"(>90 Tage kein Match)"
|
||
)
|
||
changes_made = True
|
||
else:
|
||
lines.append("✅ **Demotion:** Keine veralteten Keywords")
|
||
else:
|
||
lines.append("⚠️ **Demotion:** Booster nicht verfügbar")
|
||
|
||
# ── Schritt 2: Red-Flag-Feedback ─────────────────────────
|
||
from archivar.routing_counter import routing_counter
|
||
counts = routing_counter.get_counts()
|
||
red_flag_triggered = counts.get("red_flag_triggered", 0)
|
||
red_flag_routed = counts.get("red_flag_agent_routed", 0)
|
||
red_flag_dispatched = counts.get("red_flag_dispatched", 0)
|
||
lines.append(
|
||
f"🚩 **Red-Flag-Feedback:** {red_flag_triggered} getriggert, "
|
||
f"{red_flag_routed} geroutet, {red_flag_dispatched} dispatched"
|
||
)
|
||
|
||
# ── Schritt 3: Promotion-Kandidaten ──────────────────────
|
||
if state._promotion_candidates:
|
||
promo_lines = []
|
||
for kw, rooms_dict in list(state._promotion_candidates.items())[:10]:
|
||
for rid, info in rooms_dict.items():
|
||
entry = room_map.get_room_by_id(rid)
|
||
room_name = entry.name if entry else rid[:8]
|
||
promo_lines.append(
|
||
f" - `{kw}` → {room_name} "
|
||
f"(Score: {info.get('score', 0):.1f})"
|
||
)
|
||
if promo_lines:
|
||
lines.append(
|
||
f"⭐ **Promotion-Kandidaten ({len(state._promotion_candidates)}):**\n"
|
||
+ "\n".join(promo_lines)
|
||
)
|
||
else:
|
||
lines.append("⭐ **Promotion-Kandidaten:** Keine")
|
||
|
||
# ── Schritt 4: Keyword-Gewicht-Anomalien ──────────────────
|
||
if state._keyword_weights:
|
||
anomaly_count = 0
|
||
anomaly_lines = []
|
||
for kw, rooms_dict in state._keyword_weights.items():
|
||
for rid, entry in rooms_dict.items():
|
||
if entry.weight <= 0.1 and entry.rejection_count >= 2:
|
||
anomaly_count += 1
|
||
if len(anomaly_lines) < 5:
|
||
room_entry = room_map.get_room_by_id(rid)
|
||
room_name = room_entry.name if room_entry else rid[:8]
|
||
anomaly_lines.append(
|
||
f" - `{kw}` → {room_name} "
|
||
f"(Gewicht: {entry.weight:.2f}, "
|
||
f"Rejections: {entry.rejection_count})"
|
||
)
|
||
if anomaly_lines:
|
||
lines.append(
|
||
f"⚠️ **Gewicht-Anomalien ({anomaly_count}):**\n"
|
||
+ "\n".join(anomaly_lines)
|
||
)
|
||
else:
|
||
lines.append("⚠️ **Gewicht-Anomalien:** Keine Daten")
|
||
|
||
# ── Schritt 5: Ring-State-Info ───────────────────────────
|
||
if state._ring_state:
|
||
active_rings = 0
|
||
for rid, ring in state._ring_state.items():
|
||
if state.is_ring_state_active(rid, ring.get("state", "")):
|
||
active_rings += 1
|
||
if active_rings > 0:
|
||
lines.append(f"🔔 **Aktive Ring-States:** {active_rings} Raum/Räume im Strategie-Modus")
|
||
else:
|
||
lines.append("🔔 **Ring-States:** Keine")
|
||
|
||
# ── Schritt 6: Persistieren ──────────────────────────────
|
||
if changes_made:
|
||
try:
|
||
from pathlib import Path as PathLib
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from archivar.room_map import RoomMap
|
||
RoomMap.save(room_map, PathLib(ROOM_MAP_PATH))
|
||
lines.append("\n💾 Änderungen in `room-map.json` persistiert")
|
||
except Exception as e:
|
||
lines.append(f"\n❌ Fehler beim Persistieren: {e}")
|
||
|
||
# ── Zusammenfassung ──────────────────────────────────────
|
||
total_keywords = sum(
|
||
len(entry.keywords_100) + len(entry.keywords_context)
|
||
for entry in room_map.rooms.values()
|
||
)
|
||
return (
|
||
"🔍 **Keyword-Kuratierung — Ergebnisse**\n\n"
|
||
+ "\n".join(lines)
|
||
+ f"\n\n📊 **Map-Status:** {len(room_map.rooms)} Räume, "
|
||
f"{total_keywords} Keywords, v{room_map.version}"
|
||
)
|
||
else:
|
||
return (
|
||
f"❌ Unbekannte Option: `{sub}`\n\n"
|
||
"Verfügbar: `status`, `run`"
|
||
)
|
||
|
||
@staticmethod
|
||
def _message_type_for(is_button_response: bool) -> "MessageType":
|
||
"""Return the appropriate MessageType for a button response.
|
||
|
||
P1 fix: Hermes-Core has no BUTTON_CLICK enum member.
|
||
Button responses are dispatched as COMMAND so the agent
|
||
can handle them as structured input.
|
||
"""
|
||
return MessageType.COMMAND if is_button_response else MessageType.TEXT
|
||
|
||
async def _dispatch_agent(
|
||
self,
|
||
text: str,
|
||
room_id: str,
|
||
room_name: str,
|
||
room_type: str,
|
||
username: str,
|
||
msg_id: str,
|
||
msg_obj: dict,
|
||
is_button_response: bool = False,
|
||
category: str = "",
|
||
) -> None:
|
||
"""Dispatch an agent turn via the gateway handler.
|
||
|
||
V7-1: Extracted from _process_incoming so it can be called from
|
||
the move-request confirmation path (after ✅Ja) with
|
||
_CURRENT_ORIGIN_ROOM already set to the target room.
|
||
"""
|
||
# ── Virtual Room Translation ─────────────────────────────────
|
||
virtual_chat_id = f"user:{username}"
|
||
|
||
# Ensure this user→room mapping is recorded for proaktive sends
|
||
if virtual_chat_id not in self._user_rooms:
|
||
self._user_rooms[virtual_chat_id] = []
|
||
if room_id not in self._user_rooms[virtual_chat_id]:
|
||
self._user_rooms[virtual_chat_id].append(room_id)
|
||
|
||
# Dispatch to gateway handler via base-class handle_message
|
||
try:
|
||
message_type = self._message_type_for(is_button_response)
|
||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||
if target_room_id:
|
||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]"
|
||
else:
|
||
# Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung
|
||
room_names = [info.get("name", "?") for rid, info in self._room_info.items()
|
||
if info.get("type") in ("c", "p") and rid != room_id]
|
||
rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume"
|
||
with _question_counter_lock:
|
||
archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]"
|
||
# ── Ende Kontext-Weitergabe ──────────────────────────────────────
|
||
source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=virtual_chat_id,
|
||
chat_name=f"{room_name} (via @{username})" + archivar_suffix + (f" [{category}]" if category else ""),
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
chat_topic=self._room_map_summary,
|
||
)
|
||
# ── FIX A: Text-Prefix in User-Nachricht injizieren ──────────
|
||
room_type_label = {"c": "channel", "p": "group", "d": "dm"}.get(room_type, room_type)
|
||
room_context_prefix = f"[Raum: {room_name} ({room_type_label})] "
|
||
contextualized_text = room_context_prefix + text
|
||
|
||
event = MessageEvent(
|
||
text=contextualized_text,
|
||
message_type=message_type,
|
||
message_id=msg_id,
|
||
timestamp=datetime.datetime.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
event.source = source
|
||
# ── P1: Cross-Contamination-Fix — Task-Token vor copy_context setzen ──
|
||
# _set_room_context_origin generiert ein frisches Token und setzt
|
||
# _CURRENT_TASK_TOKEN. copy_context() friert es ein, sodass send()
|
||
# später den Token-Match validieren kann.
|
||
_set_room_context_origin(virtual_chat_id, room_id)
|
||
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
|
||
ctx = contextvars.copy_context()
|
||
# V8.1 P1 diagnostic: log dispatch context
|
||
_origin = _CURRENT_ORIGIN_ROOM.get()
|
||
_target = _THEMATIC_TARGET_ROOM.get()
|
||
logger.info(
|
||
"V8.1 P1 dispatch: chat_id=%s → target_room=%s, "
|
||
"_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s",
|
||
virtual_chat_id, _target if _target else room_id,
|
||
_origin[:8] if _origin else "",
|
||
_target[:8] if _target else "",
|
||
)
|
||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||
self._agent_dispatch_task = asyncio.create_task(
|
||
ctx.run(self.handle_message, event)
|
||
)
|
||
try:
|
||
await self._agent_dispatch_task
|
||
except asyncio.CancelledError:
|
||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||
return
|
||
finally:
|
||
self._agent_dispatch_task = None
|
||
except Exception as e:
|
||
logger.error("[rocketchat] handle_message error: %s", e)
|
||
# Fallback: Wenn COMMAND fehlschlägt
|
||
if is_button_response and str(e) == "COMMAND":
|
||
logger.info("[rocketchat] COMMAND lost context — retrying as TEXT")
|
||
try:
|
||
from datetime import datetime as dt2
|
||
fallback_source = SessionSource(
|
||
platform=Platform("rocketchat"),
|
||
chat_id=f"user:{username}",
|
||
chat_name=f"{room_name} (via @{username})",
|
||
user_id=username,
|
||
user_name=username,
|
||
chat_type="dm",
|
||
chat_topic=self._room_map_summary,
|
||
)
|
||
fallback_event = MessageEvent(
|
||
text=f"[Button-Antwort: {text}]",
|
||
message_type=MessageType.TEXT,
|
||
message_id=msg_id,
|
||
timestamp=dt2.fromtimestamp(time.time()),
|
||
raw_message=msg_obj,
|
||
)
|
||
fallback_event.source = fallback_source
|
||
await self.handle_message(fallback_event)
|
||
except Exception as e2:
|
||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||
|
||
async def _send_via_archivar(self, room_id: str, text: str) -> bool:
|
||
"""Callback for Archivar forwarding — sends a message copy to a target room."""
|
||
if not self.rest.auth_token:
|
||
return False
|
||
return await self._post_message_with_retry(room_id, text) is not None
|
||
|
||
async def _send_archivar_buttons(self, room_id: str, text: str, payload: dict) -> bool:
|
||
"""Callback for Archivar — sends native Rocket.Chat Action-Buttons.
|
||
|
||
Handles both clarification (ARCHIVAR_CLARIFY:) and move-request
|
||
(MOVE_REQ:) buttons. Move-request context is stored in
|
||
self._pending_move_requests so the response handler picks it up.
|
||
|
||
Args:
|
||
room_id: Target room ID
|
||
text: Message text
|
||
payload: {
|
||
"actions": [{"text": "...", "type": "..."}, ...],
|
||
"_move_request": { # optional, set by Archivar v4 _send_move_request
|
||
"target_room": "...",
|
||
"target_name": "...",
|
||
"text": "...",
|
||
}
|
||
}
|
||
|
||
Returns:
|
||
True if sent successfully, False on error
|
||
"""
|
||
if not self.rest.auth_token:
|
||
return False
|
||
|
||
# _build_custom_buttons available via top-level sys.modules access
|
||
|
||
actions = payload.get("actions", [])
|
||
if not actions:
|
||
return await self._post_message_with_retry(room_id, text) is not None
|
||
|
||
# Detect Archivar v4 Move-Request (Butler-Prinzip: ✅Ja / 📍Hier)
|
||
move_req_ctx = payload.get("_move_request")
|
||
if move_req_ctx:
|
||
# Store pending move request so line 717 handler finds it
|
||
self._pending_move_requests[room_id] = {
|
||
"text": move_req_ctx.get("text", ""),
|
||
"origin_room": room_id,
|
||
"target_room": move_req_ctx.get("target_room", ""),
|
||
"target_name": move_req_ctx.get("target_name", ""),
|
||
"username": "", # filled from user_info in handler (line 718)
|
||
"message_id": "", # no msg_id for Archivar v4 move-request flow
|
||
}
|
||
# Use MOVE_REQ: prefix so the existing handler at line 717-764
|
||
# parses the response correctly (see line 722-724)
|
||
msg_prefix = f"MOVE_REQ:{room_id}"
|
||
log_tag = "move-request"
|
||
else:
|
||
msg_prefix = "ARCHIVAR_CLARIFY"
|
||
log_tag = "clarification"
|
||
|
||
# Build native RC buttons from Archivar actions
|
||
buttons = []
|
||
for i, action in enumerate(actions):
|
||
action_type = action.get("type", f"action_{i}")
|
||
action_text = action.get("text", f"Option {i+1}")
|
||
# Move-request buttons use :: separator for line 722 parsing
|
||
selector = f"{msg_prefix}::{action_type}" if move_req_ctx else f"{msg_prefix}:{action_type}"
|
||
buttons.append({
|
||
"type": "button",
|
||
"text": action_text,
|
||
"msg": selector,
|
||
"msg_in_chat_window": True,
|
||
"style": "default",
|
||
})
|
||
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": text,
|
||
"actions": buttons,
|
||
}]
|
||
|
||
# Split buttons into groups of max 3 per attachment (UX: mobile readability)
|
||
MAX_BUTTONS_PER_ROW = 3
|
||
if len(buttons) > MAX_BUTTONS_PER_ROW:
|
||
attachments = []
|
||
for i in range(0, len(buttons), MAX_BUTTONS_PER_ROW):
|
||
chunk = buttons[i:i + MAX_BUTTONS_PER_ROW]
|
||
attachments.append({
|
||
"color": "#1d74f5",
|
||
"actions": chunk,
|
||
})
|
||
# First attachment gets the title
|
||
if attachments:
|
||
attachments[0]["title"] = text
|
||
|
||
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
||
if success is not None:
|
||
# Mark room so the response stays here (no Archivar routing)
|
||
self._rooms_with_pending_questions.add(room_id)
|
||
logger.info("[rocketchat] Sent Archivar %s with %d buttons to %s",
|
||
log_tag, len(buttons), room_id[:8])
|
||
return success
|
||
|
||
def _get_build_custom_buttons(self):
|
||
"""Robust access to _build_custom_buttons, with fallback.
|
||
|
||
Returns the real _build_custom_buttons function from the rocketchat
|
||
__init__ module. If unavailable, returns a local implementation that
|
||
builds correct Rocket.Chat button dicts directly.
|
||
"""
|
||
import sys as _sys
|
||
# Try the same lookup pattern used in send() and send_clarify()
|
||
_init = _sys.modules.get('rocketchat')
|
||
if _init is not None:
|
||
fn = getattr(_init, '_build_custom_buttons', None)
|
||
if fn is not None:
|
||
return fn
|
||
# Fallback: local implementation (Bug 3 fix — ensures buttons always render)
|
||
def _local_build(labels, prefix='', style='default'):
|
||
buttons = []
|
||
for label in labels:
|
||
display = label.strip()
|
||
msg_payload = display
|
||
if prefix:
|
||
msg_payload = f"{prefix}::{msg_payload}"
|
||
buttons.append({
|
||
"type": "button",
|
||
"text": display,
|
||
"msg": msg_payload,
|
||
"msg_in_chat_window": True,
|
||
"style": style,
|
||
})
|
||
return buttons
|
||
logger.warning("[rocketchat] _build_custom_buttons not found in rocketchat module — using local fallback")
|
||
return _local_build
|
||
|
||
# ── UX-7: Numbered Button Labels ────────────────────────────────────
|
||
|
||
# Emoji-Zahlen für bis zu 10 Buttons (UX-7: Rocket.Chat schneidet
|
||
# Button-Texte ab — Nummern machen Buttons kürzer und eindeutiger).
|
||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||
|
||
@staticmethod
|
||
def numbered_button_labels(labels: list, start: int = 0) -> list:
|
||
"""Prefix labels with emoji numbers for shorter, clearer buttons.
|
||
|
||
Rocket.Chat schneidet Button-Texte ab. Nummerierte Buttons
|
||
(1️⃣ Label) sind kürzer und eindeutiger als lange Texte.
|
||
|
||
Args:
|
||
labels: Liste von Button-Label-Strings
|
||
start: Start-Index (0-basiert) in EMOJI_NUMBERS
|
||
|
||
Returns:
|
||
Liste von nummerierten Labels: ["1️⃣ Label1", "2️⃣ Label2", ...]
|
||
"""
|
||
result = []
|
||
for i, label in enumerate(labels):
|
||
idx = start + i
|
||
if idx < len(RocketChatAdapter.EMOJI_NUMBERS):
|
||
emoji = RocketChatAdapter.EMOJI_NUMBERS[idx]
|
||
result.append(f"{emoji} {label}")
|
||
else:
|
||
result.append(f"{idx + 1}. {label}")
|
||
return result
|
||
|
||
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
|
||
|
||
Neues Design (UX-Fix):
|
||
- Pro Raum: EIN blauer Nummern-Button (1️⃣, 2️⃣, …) → style 'primary'
|
||
- Zwei globale Buttons: ⏭️ Alle überspringen, ⏰ Später
|
||
- Payload-Präfix: ONBOARD:<room_id>::select für Raum-Buttons,
|
||
ONBOARD::skip_all / ONBOARD::later für globale Aktionen
|
||
- Bei 4 Räumen: 6 Buttons statt 12 — keine abgeschnittenen Labels mehr
|
||
|
||
F8: State Machine Integration — sm.start() setzt NONE → AWAITING_ROOM.
|
||
|
||
Args:
|
||
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
||
"""
|
||
# F8: State Machine initialisieren und starten
|
||
from archivar.onboarding_state import OnboardingStateMachine
|
||
if not hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm = OnboardingStateMachine()
|
||
self._onboarding_sm.load()
|
||
sm = self._onboarding_sm
|
||
# Finde den Operator-DM Raum (erster DM-Raum, nicht hardcoded auf "andreas")
|
||
operator_room_id = None
|
||
for room_id, info in self._room_info.items():
|
||
if info.get("type") == "d":
|
||
operator_room_id = room_id
|
||
break
|
||
|
||
if not operator_room_id:
|
||
logger.warning("[rocketchat] Kein DM-Raum gefunden, kann Onboarding nicht starten")
|
||
return
|
||
|
||
# DM thematisch onboarden: Wenn der DM noch kein Theme in der Map hat,
|
||
# als letzten Raum an missing_rooms anhängen.
|
||
dm_needs_onboarding = False
|
||
if self.archivar is not None and self.archivar._room_map is not None:
|
||
dm_entry = self.archivar._room_map.rooms.get(operator_room_id)
|
||
if dm_entry is None or not dm_entry.theme or dm_entry.theme == "Catch-All (legacy)":
|
||
dm_needs_onboarding = True
|
||
else:
|
||
# Keine Map vorhanden → DM braucht auf jeden Fall Onboarding
|
||
dm_needs_onboarding = True
|
||
|
||
if dm_needs_onboarding:
|
||
# Bug A: Dedup — DM nicht doppelt anhängen wenn bereits in missing_rooms
|
||
dm_already_in_missing = any(
|
||
r.get("room_id") == operator_room_id for r in missing_rooms
|
||
)
|
||
if not dm_already_in_missing:
|
||
dm_name = self._room_info.get(operator_room_id, {}).get("name", "DM")
|
||
dm_room = {"room_id": operator_room_id, "name": dm_name, "is_dm": True}
|
||
missing_rooms = list(missing_rooms) + [dm_room]
|
||
logger.info("[rocketchat] DM '%s' wird thematisch onboardet (als letzter Raum)", dm_name)
|
||
else:
|
||
logger.debug("[rocketchat] Bug A: DM bereits in missing_rooms — überspringe Dedup")
|
||
|
||
# Guard: Wenn nach DM-Prüfung nichts zu onboarden ist → return
|
||
if not missing_rooms:
|
||
logger.info("[rocketchat] Onboarding: Keine Räume zum Einrichten (alle bereits in Map)")
|
||
return
|
||
|
||
# A1b: Onboarding-Lock für den ersten Raum erwerben
|
||
# Verhindert parallele Interviews für denselben Raum
|
||
from archivar.onboarding import acquire_onboarding_lock, release_onboarding_lock
|
||
first_room_id = missing_rooms[0]["room_id"]
|
||
if not acquire_onboarding_lock(first_room_id):
|
||
logger.info(
|
||
"[rocketchat] A1b: Onboarding-Lock bereits aktiv für room=%s — "
|
||
"überspringe Start",
|
||
first_room_id[:12],
|
||
)
|
||
return
|
||
|
||
# F8: State Machine — NONE → AWAITING_ROOM
|
||
sm.start(operator_room_id=operator_room_id, missing_rooms=missing_rooms)
|
||
logger.info("[rocketchat] F8: State Machine gestartet — %s", sm.progress_text)
|
||
|
||
# A1b: Begrüßungs-Flow vor dem Interview
|
||
# Postet Begrüßung, wartet 30s (Spam-Vermeidung bei Multi-User-Join),
|
||
# startet dann das Interview
|
||
from archivar.onboarding import run_onboarding_greeting_flow
|
||
|
||
async def _start_interview():
|
||
await self._send_onboarding_message(operator_room_id, missing_rooms)
|
||
|
||
# F6 Re-Review Fix 2: Lock-Release bei Onboarding-Abbruch
|
||
# Wenn der Begrüßungs-Flow oder Interview-Start fehlschlägt
|
||
# (User verlässt Raum, Timeout, Fehler), muss der Lock
|
||
# freigegeben werden, damit ein erneuter Versuch möglich ist.
|
||
try:
|
||
await run_onboarding_greeting_flow(
|
||
room_id=operator_room_id,
|
||
send_callback=self._post_message_with_retry,
|
||
start_interview_callback=_start_interview,
|
||
room_name=self._room_info.get(operator_room_id, {}).get("name", ""),
|
||
)
|
||
except Exception:
|
||
release_onboarding_lock(first_room_id)
|
||
logger.warning(
|
||
"[rocketchat] A1b: Onboarding abgebrochen — Lock freigegeben: room=%s",
|
||
first_room_id[:12],
|
||
)
|
||
raise
|
||
return
|
||
|
||
async def _send_onboarding_message(self, operator_room_id: str, missing_rooms: list) -> None:
|
||
self._onboarding_state = {
|
||
"missing_rooms": missing_rooms,
|
||
"current_room_index": -1, # -1 = noch kein Raum ausgewählt
|
||
"current_question": 0, # 0 = noch keine Frage gestellt
|
||
"collected_data": {}, # room_id → {theme, keywords_100, keywords_context, catch_all}
|
||
"operator_room_id": operator_room_id,
|
||
"skipped_rooms": [], # room_ids die übersprungen wurden
|
||
}
|
||
# P1-4: Onboarding-State persistent speichern
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
if _MULTIROOM() and self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = True
|
||
|
||
# Bug 3 fix: Robuster Zugriff auf _build_custom_buttons
|
||
_build = self._get_build_custom_buttons()
|
||
|
||
# P0-1: build_button_attachments aus gemeinsamem Modul nutzen
|
||
from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
|
||
|
||
lines = [
|
||
"🤖 **Auto-Onboarding** — Ich habe Räume gefunden, die noch nicht in meiner Raum-Map stehen.",
|
||
"",
|
||
"**Schritt 1 von 4: Räume**",
|
||
"",
|
||
"Ich brauche deine Hilfe, um sie einzurichten. Keine Sorge — ich führe dich Schritt für Schritt durch 4 kurze Fragen pro Raum.",
|
||
"",
|
||
"**Fehlende Räume:**",
|
||
]
|
||
for i, room in enumerate(missing_rooms):
|
||
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
|
||
clean_name = room["name"].lstrip("#")
|
||
lines.append(f"{emoji} {clean_name}")
|
||
|
||
lines.append("")
|
||
lines.append("⏭️ = Alle überspringen ⏰ = Später")
|
||
lines.append("")
|
||
lines.append("👉 Klicke auf eine Nummer, um den Raum einzurichten:")
|
||
text = "\n".join(lines)
|
||
|
||
# Raum-Buttons via build_button_attachments (3er-Chunking)
|
||
num_buttons = []
|
||
for room in missing_rooms:
|
||
rid = room["room_id"]
|
||
clean_name = room["name"].lstrip("#")
|
||
num_buttons.append((clean_name, f"ONBOARD:{rid}", f"select_{rid}"))
|
||
|
||
special_buttons = [
|
||
("⏭️ Alle überspringen", "ONBOARD", "default"),
|
||
("⏰ Später", "ONBOARD", "default"),
|
||
]
|
||
|
||
attachments = build_button_attachments(
|
||
num_buttons,
|
||
special_buttons,
|
||
color="#1d74f5",
|
||
title="Raum-Map unvollständig — Räume einrichten?",
|
||
)
|
||
|
||
# Bug 3 fix: Wenn keine Buttons gebaut werden konnten, sende als Text
|
||
# mit klarer Anleitung (Fallback, sollte nie eintreten)
|
||
if not attachments:
|
||
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
|
||
|
||
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), sum(len(a.get("actions", [])) for a in attachments))
|
||
else:
|
||
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════
|
||
# P1-2: Zentraler Dialog-Dispatcher — 700-Zeilen if-Kette in Handler
|
||
# extrahiert. Jede Phase = eine eigene Methode mit einheitlicher
|
||
# Signatur: _handle_onboarding_<phase>(text, state, operator_room_id)
|
||
# ═══════════════════════════════════════════════════════════════════════
|
||
|
||
# ── Phase → Handler Mapping ──────────────────────────────────────────
|
||
_ONBOARDING_PHASE_HANDLERS = {
|
||
"catch_all_change": "_handle_onboarding_catch_all_change",
|
||
"butler_mode": "_handle_onboarding_butler_mode",
|
||
"fakt_store": "_handle_onboarding_fakt_store",
|
||
"review_room": "_handle_onboarding_review_room",
|
||
"review_butler": "_handle_onboarding_review_butler",
|
||
"review_fakt": "_handle_onboarding_review_fakt",
|
||
}
|
||
|
||
async def _process_onboarding_response(self, text: str, room_id: str) -> None:
|
||
"""v2: Verarbeitet Onboarding-Antworten (Button-Klicks + Text-Antworten).
|
||
|
||
P1-2 Refactoring: Dispatcher delegiert an phasenspezifische Handler.
|
||
"""
|
||
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-Dispatch (P1-2) ──────────────────────────────────────
|
||
phase = state.get("phase", "")
|
||
handler_name = self._ONBOARDING_PHASE_HANDLERS.get(phase)
|
||
if handler_name:
|
||
handler = getattr(self, handler_name)
|
||
await handler(text, state, operator_room_id)
|
||
return
|
||
|
||
# ── V8.4.2: Keyword-Konflikt-Auflösung ──────────────────────────
|
||
conflict_phase = state.get("conflict_phase", "")
|
||
if conflict_phase in ("keywords_100", "keywords_context"):
|
||
await self._handle_onboarding_keyword_conflict(text, state, operator_room_id)
|
||
return
|
||
|
||
# ── Modus 1: Button-Klick (ONBOARD:<room_id>::<action>) ──────────
|
||
if text.startswith("ONBOARD:") and "::" in text:
|
||
await self._handle_onboarding_button_click(text, state, operator_room_id)
|
||
return
|
||
|
||
# ── Modus 2: Text-Antwort auf Interview-Frage ────────────────────
|
||
await self._handle_onboarding_interview_answer(text, state, operator_room_id)
|
||
|
||
# ── Phase-Handler: catch_all_change ─────────────────────────────────
|
||
async def _handle_onboarding_catch_all_change(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Phase: catch_all_change — Catch-All-Raum-Auswahl nach Abschluss aller Interviews."""
|
||
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", "")
|
||
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", "")
|
||
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
|
||
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
|
||
|
||
# Catch-All-Frage beantwortet → Butler-Mode-Frage stellen
|
||
self._onboarding_state = {
|
||
"phase": "butler_mode",
|
||
"operator_room_id": operator_room_id,
|
||
}
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_room()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# Butler-Mode-Frage senden
|
||
_build = self._get_build_custom_buttons()
|
||
butler_text = (
|
||
"**Schritt 2 von 4: Butler-Mode**\n\n"
|
||
"Möchtest du, dass ich bei themenfremden Nachrichten vorschlage "
|
||
"den Raum zu wechseln (Butler-Prinzip)?\n\n"
|
||
"🤖 **Kognitiv** — Ich erkenne selbstständig thematische Bezüge "
|
||
"und frage natürlich nach. (Empfohlen für leistungsstarke Cloud-Modelle)\n"
|
||
"📋 **Klassisch** — Ich folge festen Regeln: Bei sicheren Zuordnungen "
|
||
"wechsle ich automatisch, bei unsicheren frage ich nach. "
|
||
"(Empfohlen für lokale Modelle)\n"
|
||
"🔇 **Aus** — Kein Butler, ich bleibe immer im Ursprungsraum.\n\n"
|
||
"👉 Klicke auf einen Button:"
|
||
)
|
||
butler_buttons = _build(
|
||
["🤖", "📋", "🔇"],
|
||
prefix="BUTLER",
|
||
style="primary",
|
||
)
|
||
butler_attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Butler-Modus wählen",
|
||
"actions": butler_buttons,
|
||
}]
|
||
await self._post_message_with_retry(
|
||
operator_room_id, butler_text, attachments=butler_attachments
|
||
)
|
||
logger.info("[rocketchat] Fix C v7: Butler-Mode-Frage gesendet")
|
||
|
||
# ── Phase-Handler: butler_mode ──────────────────────────────────────
|
||
async def _handle_onboarding_butler_mode(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Phase: butler_mode — Butler-Mode-Auswahl (Fix C v7)."""
|
||
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"
|
||
self._save_butler_mode(mode)
|
||
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:
|
||
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"
|
||
self._save_butler_mode(mode)
|
||
mode_labels = {"cognitive": "🤖 Kognitiv", "strict": "📋 Klassisch", "off": "🔇 Aus"}
|
||
await self._post_message_with_retry(operator_room_id, f"👍 Butler-Modus: {mode_labels.get(mode, mode)}")
|
||
logger.info("[rocketchat] Fix C v7: Butler-Mode gesetzt auf '%s' (Text)", mode)
|
||
|
||
# Thema 3: FAKT-Speicherort-Dialog
|
||
self._onboarding_state = {"phase": "fakt_store", "operator_room_id": operator_room_id}
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_intent()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
# FAKT-Speicherort-Frage senden
|
||
_build = self._get_build_custom_buttons()
|
||
fakt_text = (
|
||
"**Schritt 3 von 4: FAKT-Speicherort**\n\n"
|
||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||
)
|
||
fakt_attachments = [
|
||
{
|
||
"color": "#1d74f5",
|
||
"title": "FAKT-Speicherort wählen",
|
||
"actions": _build(["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"], prefix="FAKT", style="primary"),
|
||
},
|
||
{
|
||
"color": "#1d74f5",
|
||
"actions": _build(["4️⃣ Keine"], prefix="FAKT", style="primary"),
|
||
},
|
||
]
|
||
await self._post_message_with_retry(operator_room_id, fakt_text, attachments=fakt_attachments)
|
||
logger.info("[rocketchat] Thema 3: FAKT-Speicherort-Frage gesendet")
|
||
|
||
def _save_butler_mode(self, mode: str) -> None:
|
||
"""Hilfsfunktion: Butler-Mode in room-map.json speichern."""
|
||
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()
|
||
|
||
# ── Phase-Handler: fakt_store ───────────────────────────────────────
|
||
async def _handle_onboarding_fakt_store(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Phase: fakt_store — FAKT-Speicherort-Dialog (Thema 3)."""
|
||
single_line = text.strip()
|
||
fakt_sub_phase = state.get("fakt_sub_phase", "")
|
||
|
||
# Sub-Phase: User gibt Pfad ein (für Option 2 oder 3)
|
||
if fakt_sub_phase in ("new_path", "existing_path"):
|
||
await self._handle_fakt_store_path_input(single_line, fakt_sub_phase, operator_room_id)
|
||
return
|
||
|
||
# Haupt-Phase: Button-Klick oder Text-Antwort
|
||
if single_line.startswith("FAKT::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
else:
|
||
choice = single_line
|
||
|
||
from .archivar.onboarding import (
|
||
validate_fact_store_path,
|
||
create_and_verify_fact_store,
|
||
get_default_fact_store_path,
|
||
)
|
||
|
||
# Option 1: Standard
|
||
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
||
default_path = get_default_fact_store_path()
|
||
result = create_and_verify_fact_store(default_path)
|
||
if not result["success"]:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"❌ Standard-Pfad konnte nicht erstellt werden: {result['error']}")
|
||
return
|
||
self._save_fakt_store("auto", default_path, operator_room_id)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ FAKT-Speicherort: `{default_path}` (Standard)\nÄnderbar mit `::setfakt`.")
|
||
await self._complete_onboarding(operator_room_id)
|
||
return
|
||
|
||
# Option 2: Neuer Ort
|
||
elif "Neu" in choice or "2️⃣" in choice or choice == "2":
|
||
self._onboarding_state["fakt_sub_phase"] = "new_path"
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"📁 Bitte gib den absoluten Pfad für den neuen FAKT-Speicherort ein "
|
||
"(z.B. `/home/bernd/meine-notizen`):")
|
||
return
|
||
|
||
# Option 3: Bestehender Ort
|
||
elif "Vorhanden" in choice or "3️⃣" in choice or choice == "3":
|
||
self._onboarding_state["fakt_sub_phase"] = "existing_path"
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"📁 Bitte gib den absoluten Pfad zum bestehenden FAKT-Speicherort ein "
|
||
"(z.B. `/data/Wissensdatenbank`):")
|
||
return
|
||
|
||
# Option 4: Keine Sammlung
|
||
elif "Keine" in choice or "4️⃣" in choice or choice == "4":
|
||
strategy = "none"
|
||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path as PathLib
|
||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
self.archivar._doc_store = None
|
||
logger.info("[rocketchat] FAKT-Store: strategy='none', created_at=%s", now_iso)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"✅ FAKT-Speicherort: **Keine Wissensammlung**\n"
|
||
"FAKT-Nachrichten werden im Chat beantwortet, aber nicht persistiert.\n"
|
||
"Änderbar mit `::setfakt`.")
|
||
await self._complete_onboarding(operator_room_id)
|
||
return
|
||
|
||
else:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"❌ Bitte wähle eine Option: 1 (Standard), 2 (Neuer Ort), 3 (Bestehender Ort) oder 4 (Keine Sammlung).")
|
||
return
|
||
|
||
async def _handle_fakt_store_path_input(
|
||
self, single_line: str, fakt_sub_phase: str, operator_room_id: str
|
||
) -> None:
|
||
"""Sub-Phase: Pfad-Eingabe für FAKT-Speicherort (Option 2/3)."""
|
||
from .archivar.onboarding import (
|
||
validate_fact_store_path,
|
||
create_and_verify_fact_store,
|
||
verify_existing_fact_store,
|
||
)
|
||
|
||
validation = validate_fact_store_path(single_line)
|
||
if not validation["valid"]:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"❌ {validation['error']}\n\nBitte gib einen gültigen absoluten Pfad ein:")
|
||
return
|
||
|
||
norm_path = validation["normalized_path"]
|
||
if fakt_sub_phase == "new_path":
|
||
result = create_and_verify_fact_store(norm_path)
|
||
else:
|
||
result = verify_existing_fact_store(norm_path)
|
||
|
||
if not result["success"]:
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"❌ {result['error']}\n\nBitte versuche einen anderen Pfad:")
|
||
return
|
||
|
||
strategy = "manual"
|
||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path as PathLib
|
||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
|
||
if self.archivar._doc_store is not None:
|
||
self.archivar._doc_store.set_base_dir(PathLib(norm_path))
|
||
else:
|
||
from .archivar.doc_store import DocumentationStore
|
||
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(norm_path))
|
||
|
||
logger.info("[rocketchat] FAKT-Store: strategy='manual', path=%s, created_at=%s", norm_path, now_iso)
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ FAKT-Speicherort: `{norm_path}`\n"
|
||
f"Strategie: {'Neues Verzeichnis angelegt' if fakt_sub_phase == 'new_path' else 'Bestehendes Verzeichnis referenziert'}\n"
|
||
f"Änderbar mit `::setfakt`.")
|
||
await self._complete_onboarding(operator_room_id)
|
||
|
||
def _save_fakt_store(self, strategy: str, path: str, operator_room_id: str) -> None:
|
||
"""Hilfsfunktion: FAKT-Store in room-map.json speichern + doc_store aktualisieren."""
|
||
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path as PathLib
|
||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
if self.archivar._doc_store is not None:
|
||
self.archivar._doc_store.set_base_dir(PathLib(path))
|
||
else:
|
||
from .archivar.doc_store import DocumentationStore
|
||
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(path))
|
||
logger.info("[rocketchat] FAKT-Store: strategy='%s', path=%s, created_at=%s", strategy, path, now_iso)
|
||
|
||
# ── Phase-Handler: review_room ──────────────────────────────────────
|
||
async def _handle_onboarding_review_room(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Phase: review_room — Room Map Review (Schritt 1)."""
|
||
from archivar.onboarding_review import (
|
||
handle_review_room_message,
|
||
render_review_room_add_new,
|
||
SUB_PHASE_ADD_NEW,
|
||
REVIEW_ROOM_SKIP,
|
||
)
|
||
|
||
result = handle_review_room_message(
|
||
text, state, self.archivar._room_map, self.archivar,
|
||
self._get_build_custom_buttons(), self._post_message_with_retry,
|
||
)
|
||
|
||
if result["handled"] and self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(state)
|
||
|
||
if result["action"] == "button_dispatched":
|
||
if state.get("sub_phase") == SUB_PHASE_ADD_NEW:
|
||
available_rooms = await self._fetch_available_rooms_for_add_new()
|
||
state["available_rooms"] = available_rooms
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(state)
|
||
add_text, add_attachments = render_review_room_add_new(
|
||
available_rooms, self._get_build_custom_buttons(),
|
||
)
|
||
await self._post_message_with_retry(operator_room_id, add_text,
|
||
attachments=add_attachments if add_attachments else None)
|
||
return
|
||
if result["response_text"]:
|
||
await self._post_message_with_retry(operator_room_id, result["response_text"],
|
||
attachments=result["response_attachments"] if result["response_attachments"] else None)
|
||
return
|
||
|
||
elif result["action"] == "text_input_processed":
|
||
if result["response_text"]:
|
||
await self._post_message_with_retry(operator_room_id, result["response_text"],
|
||
attachments=result["response_attachments"] if result["response_attachments"] else None)
|
||
return
|
||
|
||
elif result["action"] == "rejected":
|
||
await self._post_message_with_retry(operator_room_id, result["response_text"])
|
||
return
|
||
|
||
elif result["action"] == "skip_to_step2":
|
||
from archivar.onboarding_review import build_review_state
|
||
self._onboarding_state = build_review_state(phase="review_butler", operator_room_id=operator_room_id)
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_room()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
current_mode = self.archivar._room_map.butler_mode if self.archivar._room_map else "cognitive"
|
||
mode_labels = {"cognitive": "🤖 Kognitiv", "strict": "📋 Klassisch", "off": "🔇 Aus"}
|
||
current_label = mode_labels.get(current_mode, current_mode)
|
||
_build = self._get_build_custom_buttons()
|
||
butler_text = (
|
||
f"**Schritt 2 von 4: Butler-Mode Review**\n\n"
|
||
f"🔧 Butler-Mode aktuell: **{current_label}**\n\n"
|
||
f"Möchtest du den Butler-Mode ändern oder beibehalten?\n\n"
|
||
f"👉 Klicke auf einen Button:"
|
||
)
|
||
butler_attachments = [
|
||
{"color": "#1d74f5", "title": "Butler-Mode Review",
|
||
"actions": _build(["✏️ Ändern"], prefix="REVIEW_BUTLER", style="primary")},
|
||
{"color": "#1d74f5",
|
||
"actions": _build(["⏭️ Beibehalten"], prefix="REVIEW_BUTLER", style="default")},
|
||
]
|
||
await self._post_message_with_retry(operator_room_id, butler_text, attachments=butler_attachments)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow — Schritt 2 (Butler-Mode)")
|
||
|
||
# ── Phase-Handler: review_butler ────────────────────────────────────
|
||
async def _handle_onboarding_review_butler(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Phase: review_butler — Butler-Mode Review (Schritt 2)."""
|
||
single_line = text.strip()
|
||
if single_line.startswith("REVIEW_BUTLER::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
else:
|
||
choice = single_line
|
||
|
||
if "Beibehalten" in choice or "⏭️" in choice or choice.lower() in ("beibehalten", "skip", "überspringen"):
|
||
self._onboarding_state = {"phase": "review_fakt", "operator_room_id": operator_room_id}
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_intent()
|
||
logger.info("[rocketchat] F8 UX: State Machine → %s", self._onboarding_sm.progress_text)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
|
||
strategy = self.archivar._room_map.fact_store_strategy if self.archivar._room_map else "auto"
|
||
fakt_path = str(self.archivar._room_map.fact_store_path) if self.archivar._room_map else "~/.hermes/wissenssammlung"
|
||
strategy_labels = {"auto": f"Standard ({fakt_path})", "manual": f"Manuell ({fakt_path})", "none": "Keine Sammlung"}
|
||
current_label = strategy_labels.get(strategy, strategy)
|
||
_build = self._get_build_custom_buttons()
|
||
fakt_text = (
|
||
f"**Schritt 3 von 4: FAKT-Speicherort Review**\n\n"
|
||
f"📁 FAKT-Speicherort aktuell: **{current_label}**\n\n"
|
||
f"Möchtest du den FAKT-Speicherort ändern oder beibehalten?\n\n"
|
||
f"👉 Klicke auf einen Button:"
|
||
)
|
||
fakt_attachments = [
|
||
{"color": "#1d74f5", "title": "FAKT-Speicherort Review",
|
||
"actions": _build(["✏️ Ändern"], prefix="REVIEW_FAKT", style="primary")},
|
||
{"color": "#1d74f5",
|
||
"actions": _build(["⏭️ Beibehalten"], prefix="REVIEW_FAKT", style="default")},
|
||
]
|
||
await self._post_message_with_retry(operator_room_id, fakt_text, attachments=fakt_attachments)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow — Schritt 3 (FAKT-Speicherort)")
|
||
return
|
||
|
||
elif "Ändern" in choice or "✏️" in choice or choice.lower() in ("ändern", "anpassen"):
|
||
_build = self._get_build_custom_buttons()
|
||
butler_text = (
|
||
"**Butler-Mode ändern**\n\n"
|
||
"🤖 **Kognitiv** — Ich erkenne selbstständig thematische Bezüge "
|
||
"und frage natürlich nach. (Empfohlen für leistungsstarke Cloud-Modelle)\n"
|
||
"📋 **Klassisch** — Ich folge festen Regeln: Bei sicheren Zuordnungen "
|
||
"wechsle ich automatisch, bei unsicheren frage ich nach. "
|
||
"(Empfohlen für lokale Modelle)\n"
|
||
"🔇 **Aus** — Kein Butler, ich bleibe immer im Ursprungsraum.\n\n"
|
||
"👉 Klicke auf einen Button:"
|
||
)
|
||
butler_attachments = [
|
||
{"color": "#1d74f5", "title": "Butler-Modus wählen",
|
||
"actions": _build(["🤖", "📋", "🔇"], prefix="BUTLER", style="primary")},
|
||
{"color": "#1d74f5",
|
||
"actions": _build(["↩️ Zurück"], prefix="REVIEW_BUTLER", style="default")},
|
||
]
|
||
self._onboarding_state = {"phase": "butler_mode", "operator_room_id": operator_room_id}
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(operator_room_id, butler_text, attachments=butler_attachments)
|
||
return
|
||
else:
|
||
from archivar.onboarding_review import _reject_free_text
|
||
await _reject_free_text(operator_room_id, self._post_message_with_retry)
|
||
return
|
||
|
||
# ── Phase-Handler: review_fakt ───────────────────────────────────────
|
||
async def _handle_onboarding_review_fakt(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Phase: review_fakt — FAKT-Speicherort Review (Schritt 3)."""
|
||
single_line = text.strip()
|
||
if single_line.startswith("REVIEW_FAKT::"):
|
||
_, choice = single_line.split("::", 1)
|
||
choice = choice.strip()
|
||
else:
|
||
choice = single_line
|
||
|
||
if "Beibehalten" in choice or "⏭️" in choice or choice.lower() in ("beibehalten", "skip", "überspringen"):
|
||
await self._complete_onboarding(operator_room_id)
|
||
from archivar.inline_commands import build_help_text
|
||
presence_enabled = None
|
||
current_status = "online"
|
||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||
if _has_presence:
|
||
presence_enabled = self._presence_engine.is_enabled()
|
||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||
help_text = build_help_text(self._inline_commands, room_map_summary=self._room_map_summary,
|
||
presence_enabled=presence_enabled, current_status=current_status)
|
||
await self._post_message_with_retry(operator_room_id, help_text)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow abgeschlossen — ACTIVE")
|
||
return
|
||
|
||
elif "Ändern" in choice or "✏️" in choice or choice.lower() in ("ändern", "anpassen"):
|
||
_build = self._get_build_custom_buttons()
|
||
fakt_text = (
|
||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||
)
|
||
fakt_attachments = [
|
||
{"color": "#1d74f5", "title": "FAKT-Speicherort wählen",
|
||
"actions": _build(["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"], prefix="FAKT", style="primary")},
|
||
{"color": "#1d74f5",
|
||
"actions": _build(["4️⃣ Keine"], prefix="FAKT", style="primary")},
|
||
]
|
||
self._onboarding_state = {"phase": "fakt_store", "operator_room_id": operator_room_id}
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
await self._post_message_with_retry(operator_room_id, fakt_text, attachments=fakt_attachments)
|
||
return
|
||
else:
|
||
from archivar.onboarding_review import _reject_free_text
|
||
await _reject_free_text(operator_room_id, self._post_message_with_retry)
|
||
return
|
||
|
||
# ── Keyword-Konflikt-Auflösung ───────────────────────────────────────
|
||
async def _handle_onboarding_keyword_conflict(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""V8.4.2: Keyword-Konflikt-Auflösung."""
|
||
conflict_phase = state.get("conflict_phase", "")
|
||
single_line = text.strip()
|
||
|
||
if single_line.startswith("CONFLICT:"):
|
||
parts = single_line.split("::", 1)
|
||
action = parts[1] if len(parts) > 1 else ""
|
||
|
||
if "keep" in action or "Trotzdem" in action or "1️⃣" in action:
|
||
conflict_list = state.get("conflict_list", [])
|
||
for c in conflict_list:
|
||
logger.info("Onboarding-Conflict: keyword \"%s\" already in %s as %s-keyword — user chose: keep anyway",
|
||
c["keyword"], c["room_name"], c["existing_type"])
|
||
if conflict_phase == "keywords_100":
|
||
state["current_question"] = 3
|
||
else:
|
||
room = state["missing_rooms"][state["current_room_index"]]
|
||
is_dm = room.get("is_dm", False)
|
||
if is_dm:
|
||
rid = room["room_id"]
|
||
data = state["collected_data"].get(rid, {})
|
||
data["catch_all"] = True
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid, name=room_name, theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []), catch_all=True)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)",
|
||
room_name, data["theme"])
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet: 🎯 Catch-All\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
await self._onboarding_next_room()
|
||
else:
|
||
state["current_question"] = 4
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
state.pop("conflict_phase", None)
|
||
state.pop("conflict_keywords", None)
|
||
state.pop("conflict_list", None)
|
||
return
|
||
|
||
if "change" in action or "Anderes" in action or "2️⃣" in action:
|
||
conflict_list = state.get("conflict_list", [])
|
||
for c in conflict_list:
|
||
logger.info("Onboarding-Conflict: keyword \"%s\" already in %s as %s-keyword — user chose: change",
|
||
c["keyword"], c["room_name"], c["existing_type"])
|
||
state["conflict_sub_phase"] = "reenter"
|
||
conflict_kws = [c["keyword"] for c in conflict_list]
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"👍 Verstanden. Bitte gib neue Keywords ein (kommagetrennt) — "
|
||
f"die folgenden sind bereits vergeben: {', '.join(conflict_kws)}")
|
||
return
|
||
|
||
# Sub-Phase: Nutzer gibt neue Keywords ein
|
||
if state.get("conflict_sub_phase") == "reenter":
|
||
raw = single_line
|
||
if raw.lower() in ("keine", "none", "-", ""):
|
||
new_kws = []
|
||
elif "," in raw:
|
||
new_kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||
else:
|
||
new_kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||
new_kws = new_kws[:10]
|
||
|
||
if new_kws and self.archivar is not None:
|
||
rid = state["missing_rooms"][state["current_room_index"]]["room_id"]
|
||
kw_type = "100" if conflict_phase == "keywords_100" else "context"
|
||
conflicts = self.archivar._room_map.check_keyword_conflicts(
|
||
keywords=new_kws, exclude_room_id=rid, keyword_type=kw_type)
|
||
if kw_type == "100":
|
||
relevant = [c for c in conflicts if c["conflict_type"] in ("CRITICAL", "WARNING")]
|
||
else:
|
||
relevant = [c for c in conflicts if c["conflict_type"] == "INFO"]
|
||
if relevant:
|
||
state["conflict_keywords"] = new_kws
|
||
state["conflict_list"] = relevant
|
||
await self._ask_keyword_conflict_resolution(
|
||
operator_room_id, relevant, "100%" if conflict_phase == "keywords_100" else "Kontext")
|
||
return
|
||
|
||
rid = state["missing_rooms"][state["current_room_index"]]["room_id"]
|
||
data = state["collected_data"].get(rid, {})
|
||
if conflict_phase == "keywords_100":
|
||
data["keywords_100"] = new_kws
|
||
state["current_question"] = 3
|
||
else:
|
||
data["keywords_context"] = new_kws
|
||
room = state["missing_rooms"][state["current_room_index"]]
|
||
is_dm = room.get("is_dm", False)
|
||
if is_dm:
|
||
data["catch_all"] = True
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid, name=room_name, theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []), catch_all=True)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)",
|
||
room_name, data["theme"])
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet: 🎯 Catch-All\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
state.pop("conflict_phase", None)
|
||
state.pop("conflict_keywords", None)
|
||
state.pop("conflict_list", None)
|
||
state.pop("conflict_sub_phase", None)
|
||
await self._onboarding_next_room()
|
||
return
|
||
else:
|
||
state["current_question"] = 4
|
||
state.pop("conflict_phase", None)
|
||
state.pop("conflict_keywords", None)
|
||
state.pop("conflict_list", None)
|
||
state.pop("conflict_sub_phase", None)
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# ── Modus 1: Button-Klick ───────────────────────────────────────────
|
||
async def _handle_onboarding_button_click(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Modus 1: ONBOARD:<room_id>::<action> Button-Klick."""
|
||
prefix_part, action = text.split("::", 1)
|
||
action = action.strip()
|
||
|
||
# Globale Aktionen
|
||
if prefix_part == "ONBOARD":
|
||
if "⏭️" in action or "Überspringen" in action:
|
||
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:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self._onboarding_state = {}
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||
logger.info("[rocketchat] Onboarding pausiert (later)")
|
||
return
|
||
|
||
# Wenn ein Interview läuft → an Text-Antwort-Logik durchreichen
|
||
current_q = state.get("current_question", 0)
|
||
if current_q >= 1:
|
||
await self._handle_onboarding_interview_answer(text, state, operator_room_id)
|
||
return
|
||
|
||
# Raum-spezifische Aktionen
|
||
target_room_id = prefix_part.split(":", 1)[1]
|
||
|
||
if "Überspringen" in action or "⏭️" in action:
|
||
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:
|
||
from archivar.onboarding import release_onboarding_lock
|
||
for room in state.get("missing_rooms", []):
|
||
release_onboarding_lock(room["room_id"])
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self._onboarding_state = {}
|
||
await self._post_message_with_retry(operator_room_id,
|
||
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||
logger.info("[rocketchat] Onboarding pausiert (Später)")
|
||
return
|
||
|
||
# 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)
|
||
|
||
# ── Modus 2: Text-Antwort auf Interview-Frage ────────────────────────
|
||
async def _handle_onboarding_interview_answer(
|
||
self, text: str, state: dict, operator_room_id: str
|
||
) -> None:
|
||
"""Modus 2: Text-Antwort auf eine der 4 Interview-Fragen."""
|
||
current_idx = state.get("current_room_index", -1)
|
||
if current_idx < 0:
|
||
return
|
||
|
||
current_q = state.get("current_question", 0)
|
||
if current_q < 1 or current_q > 4:
|
||
return
|
||
|
||
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:
|
||
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]
|
||
|
||
if data["keywords_100"] and self.archivar is not None:
|
||
conflicts = self.archivar._room_map.check_keyword_conflicts(
|
||
keywords=data["keywords_100"], exclude_room_id=rid, keyword_type="100")
|
||
relevant = [c for c in conflicts if c["conflict_type"] in ("CRITICAL", "WARNING")]
|
||
if relevant:
|
||
state["conflict_phase"] = "keywords_100"
|
||
state["conflict_keywords"] = data["keywords_100"]
|
||
state["conflict_list"] = relevant
|
||
await self._ask_keyword_conflict_resolution(operator_room_id, relevant, "100%")
|
||
return
|
||
|
||
state["current_question"] = 3
|
||
await self._ask_onboarding_question(operator_room_id)
|
||
return
|
||
|
||
# Frage 3: keywords_context
|
||
if current_q == 3:
|
||
raw = text.strip()
|
||
if raw.lower() in ("keine", "none", "-", ""):
|
||
data["keywords_context"] = []
|
||
else:
|
||
if "," in raw:
|
||
kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||
else:
|
||
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||
data["keywords_context"] = kws[:10]
|
||
|
||
if data["keywords_context"] and self.archivar is not None:
|
||
conflicts = self.archivar._room_map.check_keyword_conflicts(
|
||
keywords=data["keywords_context"], exclude_room_id=rid, keyword_type="context")
|
||
relevant = [c for c in conflicts if c["conflict_type"] == "INFO"]
|
||
if relevant:
|
||
state["conflict_phase"] = "keywords_context"
|
||
state["conflict_keywords"] = data["keywords_context"]
|
||
state["conflict_list"] = relevant
|
||
await self._ask_keyword_conflict_resolution(operator_room_id, relevant, "Kontext")
|
||
return
|
||
|
||
is_dm = room.get("is_dm", False)
|
||
if is_dm:
|
||
data["catch_all"] = True
|
||
room_name = room["name"]
|
||
self.archivar._room_map.add_or_update_room(
|
||
room_id=rid, name=room_name, theme=data["theme"],
|
||
keywords_100=data.get("keywords_100", []),
|
||
keywords_context=data.get("keywords_context", []), catch_all=True)
|
||
from archivar.room_map import RoomMap
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)",
|
||
room_name, data["theme"])
|
||
await self._post_message_with_retry(operator_room_id,
|
||
f"✅ {room_name} eingerichtet: 🎯 Catch-All\n"
|
||
f"Thema: {data['theme']}\n"
|
||
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||
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()
|
||
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
|
||
|
||
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)
|
||
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)
|
||
|
||
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'}")
|
||
await self._onboarding_next_room()
|
||
return
|
||
|
||
async def _ask_keyword_conflict_resolution(
|
||
self, operator_room_id: str, conflicts: list, keyword_label: str
|
||
) -> None:
|
||
"""V8.4.2: Fragt den Operator bei Keyword-Konflikten um Klarstellung.
|
||
|
||
Args:
|
||
operator_room_id: DM-Raum-ID des Operators.
|
||
conflicts: Liste von Konflikten (aus check_keyword_conflicts).
|
||
keyword_label: "100%" oder "Kontext" für die Anzeige.
|
||
"""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
return
|
||
|
||
rid = state["missing_rooms"][state["current_room_index"]]["room_id"]
|
||
|
||
# Baue Konflikt-Beschreibung
|
||
conflict_lines = []
|
||
for c in conflicts:
|
||
ctype = c["conflict_type"]
|
||
if ctype == "CRITICAL":
|
||
severity = "🔴 KRITISCH"
|
||
explanation = "führt zu willkürlichem Routing"
|
||
elif ctype == "WARNING":
|
||
severity = "🟡 WARNUNG"
|
||
explanation = "Butler könnte fälschlich fragen"
|
||
elif ctype == "INFO":
|
||
severity = "🔵 INFO"
|
||
explanation = "Butler fragt im anderen Raum"
|
||
else:
|
||
severity = "⚪ OK"
|
||
explanation = "beide dürfen fragen"
|
||
|
||
conflict_lines.append(
|
||
f"• \"{c['keyword']}\" — bereits als {c['existing_type']}%-Keyword "
|
||
f"in {c['room_name']} ({severity}: {explanation})"
|
||
)
|
||
|
||
# V8.4.2.1: INFO-Konflikte sind reine Hinweise — keine Buttons
|
||
all_info = all(c["conflict_type"] == "INFO" for c in conflicts)
|
||
|
||
if all_info:
|
||
text = (
|
||
f"ℹ️ **Keyword-Hinweis** ({keyword_label}-Keywords):\n\n"
|
||
+ "\n".join(conflict_lines)
|
||
+ "\n\n💡 Der Butler wird im anderen Raum nachfragen. Keine Aktion nötig."
|
||
)
|
||
await self._post_message_with_retry(operator_room_id, text)
|
||
else:
|
||
text = (
|
||
f"⚠️ **Keyword-Konflikt erkannt** ({keyword_label}-Keywords):\n\n"
|
||
+ "\n".join(conflict_lines)
|
||
+ "\n\n👉 Möchtest Du die Keywords trotzdem verwenden oder andere wählen?"
|
||
)
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
buttons = _build(
|
||
["1️⃣ Trotzdem verwenden", "2️⃣ Anderes Keyword"],
|
||
prefix=f"CONFLICT:{rid}",
|
||
style="primary",
|
||
)
|
||
attachments = [{
|
||
"color": "#f5a623",
|
||
"title": "Keyword-Konflikt auflösen",
|
||
"actions": buttons,
|
||
}]
|
||
await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||
|
||
async def _ask_onboarding_question(self, operator_room_id: str) -> None:
|
||
"""Sendet die aktuelle Interview-Frage an den Operator."""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
return
|
||
|
||
current_idx = state.get("current_room_index", -1)
|
||
if current_idx < 0:
|
||
return
|
||
|
||
room = state["missing_rooms"][current_idx]
|
||
room_name = room["name"]
|
||
is_dm = room.get("is_dm", False)
|
||
current_q = state.get("current_question", 0)
|
||
|
||
if is_dm:
|
||
questions = {
|
||
1: f"**{room_name}** — Frage 1/3:\nWofür nutzt du diesen DM hauptsächlich? (z.B. Projektabsprachen, Team-Koordination)",
|
||
2: f"**{room_name}** — Frage 2/3:\nWelche Begriffe passen IMMER zu diesem DM? Bei diesen Wörtern weiß ich sofort: Das gehört hierher.\n"
|
||
f"(z.B. \"absprache\", \"planung\" — oder \"keine\" wenn keine)",
|
||
3: f"**{room_name}** — Frage 3/3:\nWelche Begriffe passen OFT zu diesem DM, aber nicht immer? Bei diesen Wörtern frage ich erst nach.\n"
|
||
f"(z.B. \"koordination\", \"termin\" — oder \"keine\" wenn keine)",
|
||
}
|
||
else:
|
||
questions = {
|
||
1: f"**{room_name}** — Frage 1/4:\nWorum geht es in diesem Raum? (z.B. Datenbanken, Web-Frontend, Projektplanung)",
|
||
2: f"**{room_name}** — Frage 2/4:\nWelche Begriffe passen IMMER zu diesem Raum? Bei diesen Wörtern weiß ich sofort: Das gehört hierher.\n"
|
||
f"(z.B. \"datenbank\", \"sql\", \"backup\" — oder \"keine\" wenn keine)",
|
||
3: f"**{room_name}** — Frage 3/4:\nWelche Begriffe passen OFT zu diesem Raum, aber nicht immer? Bei diesen Wörtern frage ich erst nach, ob sie hierher gehören.\n"
|
||
f"(z.B. \"migration\", \"performance\", \"index\" — oder \"keine\" wenn keine)",
|
||
4: f"**{room_name}** — Frage 4/4:\nSoll dieser Raum der Auffang-Raum (Catch-All) sein — also der Raum für Themen, die in keinen anderen passen? (Ja/Nein)",
|
||
}
|
||
|
||
text = questions.get(current_q, "")
|
||
if text:
|
||
# Frage 4 (Catch-All Ja/Nein): mit Buttons senden
|
||
if current_q == 4 and not is_dm:
|
||
_build = self._get_build_custom_buttons()
|
||
buttons = _build(
|
||
["✅ Ja", "❌ Nein"],
|
||
prefix=f"ONBOARD:{state['missing_rooms'][state['current_room_index']]['room_id']}"
|
||
)
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": "Catch-All für diesen Raum?",
|
||
"actions": buttons,
|
||
}]
|
||
await self._post_message_with_retry(operator_room_id, text, attachments=attachments)
|
||
else:
|
||
await self._post_message_with_retry(operator_room_id, text)
|
||
|
||
async def _onboarding_next_room(self) -> None:
|
||
"""Gehe zum nächsten fehlenden Raum oder schließe Onboarding ab."""
|
||
state = self._onboarding_state
|
||
if not state:
|
||
return
|
||
|
||
operator_room_id = state.get("operator_room_id", "")
|
||
missing = state["missing_rooms"]
|
||
skipped = set(state.get("skipped_rooms", []))
|
||
collected = state.get("collected_data", {})
|
||
|
||
# Finde nächsten unbearbeiteten Raum
|
||
next_idx = state.get("current_room_index", -1) + 1
|
||
while next_idx < len(missing):
|
||
rid = missing[next_idx]["room_id"]
|
||
if rid not in skipped and rid not in collected:
|
||
break
|
||
next_idx += 1
|
||
|
||
if next_idx < len(missing):
|
||
# Noch Räume übrig — zurück zur Auswahl
|
||
state["current_room_index"] = -1
|
||
state["current_question"] = 0
|
||
|
||
remaining = []
|
||
for i in range(next_idx, len(missing)):
|
||
rid = missing[i]["room_id"]
|
||
if rid not in skipped and rid not in collected:
|
||
remaining.append(missing[i])
|
||
|
||
if remaining:
|
||
lines = [f"📋 Noch {len(remaining)} Raum/Räume übrig:",
|
||
""]
|
||
for i, room in enumerate(remaining, 1):
|
||
lines.append(f"{i}. {room['name'].lstrip('#')}")
|
||
lines.append("")
|
||
lines.append("⏭️ = Überspringen ⏰ = Später")
|
||
lines.append("")
|
||
lines.append("👉 Klicke auf eine Nummer, um den Raum einzurichten:")
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
# P1-4: build_button_attachments für 3er-Chunking
|
||
from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
|
||
num_buttons = []
|
||
for room in remaining:
|
||
rid = room["room_id"]
|
||
clean_name = room["name"].lstrip("#")
|
||
num_buttons.append((clean_name, f"ONBOARD:{rid}", f"select_{rid}"))
|
||
|
||
special_buttons = [
|
||
("⏭️ Überspringen", "ONBOARD", "default"),
|
||
("⏰ Später", "ONBOARD", "default"),
|
||
]
|
||
|
||
attachments = build_button_attachments(
|
||
num_buttons,
|
||
special_buttons,
|
||
color="#1d74f5",
|
||
title="Weitere Räume einrichten?",
|
||
)
|
||
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()
|
||
# P1-5: build_button_attachments für 3er-Chunking
|
||
from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
|
||
num_buttons = []
|
||
for rid, name, is_catch in all_rooms:
|
||
num_buttons.append((name, f"ONBOARD:{rid}", f"select_{rid}"))
|
||
|
||
special_buttons = [
|
||
("⏭️ Überspringen", "ONBOARD", "default"),
|
||
]
|
||
|
||
attachments = build_button_attachments(
|
||
num_buttons,
|
||
special_buttons,
|
||
color="#1d74f5",
|
||
title="Catch-All-Raum wählen",
|
||
)
|
||
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
||
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
||
|
||
async def _start_onboarding_review(self, operator_room_id: str) -> None:
|
||
"""F8 UX: Review-Flow wenn Room-Map bereits vollständig ist.
|
||
|
||
Statt direkt ACTIVE zu setzen, zeigt der Review-Flow bei jedem Schritt
|
||
die aktuellen Werte und fragt ob etwas geändert werden soll.
|
||
|
||
Schritt 1 (AWAITING_ROOM): Room Map Review
|
||
Schritt 2 (AWAITING_INTENT): Butler-Mode Review
|
||
Schritt 3 (AWAITING_TEST): FAKT-Speicherort Review
|
||
Schritt 4 (ACTIVE): Hilfeseite
|
||
"""
|
||
from archivar.onboarding_review import (
|
||
render_review_room_step,
|
||
build_review_state,
|
||
)
|
||
|
||
_build = self._get_build_custom_buttons()
|
||
|
||
# Schritt 1: Room Map Review (neues strukturiertes Rendering)
|
||
review_text, review_attachments = render_review_room_step(
|
||
self.archivar._room_map,
|
||
operator_room_id,
|
||
_build,
|
||
)
|
||
|
||
self._onboarding_state = build_review_state(
|
||
phase="review_room",
|
||
operator_room_id=operator_room_id,
|
||
)
|
||
if self.archivar is not None:
|
||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||
self.archivar._stats["onboarding_active"] = True
|
||
|
||
await self._post_message_with_retry(
|
||
operator_room_id, review_text, attachments=review_attachments
|
||
)
|
||
logger.info("[rocketchat] F8 UX: Review-Flow gestartet — Schritt 1 (Room Map)")
|
||
|
||
async def _complete_onboarding(self, operator_room_id: str) -> None:
|
||
"""Thema 3: Onboarding final abschließen (nach FAKT-Speicherort-Dialog)."""
|
||
# A1b: Onboarding-Lock für alle onboardeten Räume freigeben
|
||
from archivar.onboarding import release_onboarding_lock
|
||
if self._onboarding_state:
|
||
missing = self._onboarding_state.get("missing_rooms", [])
|
||
for room in missing:
|
||
release_onboarding_lock(room["room_id"])
|
||
if self.archivar is not None:
|
||
self.archivar._stats["onboarding_active"] = False
|
||
self.archivar._state.clear_onboarding_state()
|
||
self._onboarding_state = {}
|
||
# F8: State Machine — AWAITING_TEST → ACTIVE
|
||
if hasattr(self, '_onboarding_sm'):
|
||
self._onboarding_sm.advance_test()
|
||
logger.info("[rocketchat] F8: State Machine → %s", self._onboarding_sm.progress_text)
|
||
# FIX E: Raum-Map Summary nach Onboarding aktualisieren
|
||
self._room_map_summary = self._build_room_map_summary()
|
||
if self._room_map_summary:
|
||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach Onboarding aktualisiert (%d Räume)",
|
||
len(self._room_map_summary.splitlines()) - 1)
|
||
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit FAKT-Speicherort)")
|
||
|
||
@staticmethod
|
||
def _derive_keywords(room_name: str, theme: str) -> list:
|
||
"""Leitet Stichworte aus Raumname und Thema ab.
|
||
|
||
Regeln:
|
||
- Raumname ohne '#' und ohne Bindestriche → einzelne Teile als Keywords
|
||
- Erste 2-4 signifikante Wörter aus dem Thema (keine Stopwörter)
|
||
- Maximal 10 Keywords, keine Duplikate, alle lowercase
|
||
"""
|
||
STOP = {"der", "die", "das", "und", "oder", "zum", "zur", "des", "dem", "den",
|
||
"ein", "eine", "einen", "einem", "für", "mit", "auf", "an", "von",
|
||
"ist", "sind", "wird", "the", "and", "or", "for", "with", "of", "to"}
|
||
keywords = []
|
||
|
||
# Aus Raumname: #BAT-Team → ["bat", "team"]
|
||
name_clean = room_name.lstrip("#")
|
||
for part in name_clean.replace("-", " ").replace("_", " ").split():
|
||
kw = part.lower().strip(".,;:!?")
|
||
if kw and kw not in STOP:
|
||
keywords.append(kw)
|
||
|
||
# Aus Thema: erste signifikante Wörter
|
||
for word in theme.lower().replace(",", " ").split():
|
||
w = word.strip(".,;:!?")
|
||
if w and w not in STOP and w not in keywords:
|
||
keywords.append(w)
|
||
if len(keywords) >= 10:
|
||
break
|
||
|
||
return keywords[:10]
|
||
|
||
def _get_onboarding_room_list(self) -> list:
|
||
"""Erstellt eine nummerierte Liste aller Räume (ohne excluded), inkl. DM.
|
||
|
||
Returns list of (rid, name, is_current) tuples — gleiche Sortierung wie
|
||
_finish_onboarding, damit Nummerierung in beiden Listen identisch ist.
|
||
"""
|
||
rooms = []
|
||
dm_room_id = self._onboarding_state.get("operator_room_id", "")
|
||
dm_room_name = self._room_info.get(dm_room_id, {}).get("name", "DM")
|
||
dm_already_in_map = dm_room_id in self.archivar._room_map.rooms
|
||
|
||
for rid, entry in self.archivar._room_map.rooms.items():
|
||
if rid in self.archivar._room_map._excluded_room_ids:
|
||
continue
|
||
if rid == dm_room_id:
|
||
rooms.append((rid, dm_room_name, True))
|
||
else:
|
||
rooms.append((rid, entry.name, entry.catch_all))
|
||
|
||
# DM-Raum immer als Option anbieten, auch wenn nicht in room_map
|
||
# (wird nachfolgend einsortiert)
|
||
if not dm_already_in_map:
|
||
rooms.append((dm_room_id, dm_room_name, True))
|
||
|
||
# Gleiche Sortierung wie _finish_onboarding: Catch-All zuerst, dann alphabetisch
|
||
rooms.sort(key=lambda x: (not x[2], x[1]))
|
||
return rooms
|
||
|
||
async def _fetch_available_rooms_for_add_new(self) -> list:
|
||
"""O2: REST-Raumliste für 'Neuer Raum' laden und filtern.
|
||
|
||
Holt alle Räume via REST rooms.get, filtert Räume die bereits
|
||
in der Room-Map sind (inkl. excluded), und gibt eine Liste von
|
||
Dicts mit 'id' und 'name' zurück.
|
||
|
||
Returns:
|
||
Liste von Dicts: [{"id": "...", "name": "...", "type": "..."}, ...]
|
||
"""
|
||
all_rooms = self.rest.get_rooms()
|
||
if not all_rooms:
|
||
return []
|
||
|
||
# IDs der bereits in der Room-Map vorhandenen Räume
|
||
mapped_ids = set(self.archivar._room_map.rooms.keys())
|
||
mapped_ids.update(self.archivar._room_map._excluded_room_ids)
|
||
|
||
available = []
|
||
for room in all_rooms:
|
||
rid = room.get("id", "")
|
||
if rid and rid not in mapped_ids:
|
||
available.append(room)
|
||
|
||
# Alphabetisch nach Name sortieren
|
||
available.sort(key=lambda r: r.get("name", "").lower())
|
||
return available
|
||
|
||
def _set_catch_all(self, room_id: str) -> None:
|
||
"""Setzt den angegebenen Raum als alleinigen Catch-All."""
|
||
from archivar.config import ROOM_MAP_PATH
|
||
from pathlib import Path
|
||
for rid, entry in self.archivar._room_map.rooms.items():
|
||
entry.catch_all = (rid == room_id)
|
||
# Persistieren
|
||
from archivar.room_map import RoomMap
|
||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||
self.archivar._room_map.reload()
|
||
# P1-2: FAISS-Index nach Catch-All-Wechsel neu bauen
|
||
if self.archivar is not None and self.archivar._room_index is not None:
|
||
try:
|
||
self.archivar._room_index.build_index()
|
||
self.archivar._room_index.save()
|
||
logger.info("[rocketchat] P1-2: FAISS-Index nach Catch-All-Wechsel neu gebaut (%d Vektoren)",
|
||
self.archivar._room_index.size)
|
||
except Exception as e:
|
||
logger.warning("[rocketchat] P1-2: FAISS-Index-Rebuild nach Catch-All-Wechsel fehlgeschlagen: %s", e)
|
||
|
||
async def _download_and_inline_files(self, text: str) -> str:
|
||
"""Download files referenced as [FILE] markers and inline their content."""
|
||
import re
|
||
_file_re = re.compile(
|
||
r'\[FILE\]\s+(?P<name>[^\n]+?)\s+\((?P<type>[^)]+)\)\n'
|
||
r'Download:\s+\S+/file-upload/(?P<fid>[^/]+)/(?P<fname>\S+)'
|
||
)
|
||
matches = list(_file_re.finditer(text))
|
||
if not matches:
|
||
return text
|
||
for m in matches:
|
||
fid = m.group("fid")
|
||
fname = m.group("fname")
|
||
content = self.rest.download_file(fid, fname)
|
||
if content:
|
||
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
||
text += block
|
||
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
||
# P2-1: Alle übrigen [FILE]-Blöcke entfernen (fehlgeschlagene Downloads)
|
||
# Non-greedy Pattern: erfasst [FILE]...Download:... bis zum nächsten \n
|
||
# re.DOTALL damit Zeilenumbrüche innerhalb des Blocks matchen
|
||
text = re.sub(
|
||
r'\[FILE\].*?Download:[^\n]+\n?', '', text, flags=re.DOTALL
|
||
)
|
||
return text
|
||
|
||
async def disconnect(self) -> None:
|
||
self._mark_disconnected()
|
||
self._shutdown_event.set()
|
||
if self._status_timer:
|
||
self._status_timer.cancel()
|
||
# STETS-GELB Fix 3: Presence-Heartbeat bei Disconnect stoppen.
|
||
# Der Timer darf nicht weiterlaufen, wenn DDP getrennt ist.
|
||
engine = getattr(self, '_presence_engine', None)
|
||
if engine is not None:
|
||
try:
|
||
engine.stop_heartbeat()
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] STETS-GELB Fix 3: Heartbeat-Stop fehlgeschlagen: %s", e
|
||
)
|
||
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)
|
||
# P1: _room_context als persistenter Fallback
|
||
if chat_id.startswith("user:"):
|
||
_set_room_context_origin(chat_id, target_room_id)
|
||
# Strip ROOM: prefix from content
|
||
content = _strip_red_flag_prefix(content)
|
||
# ── Ring-Feedback: Agent-Entscheidung trainieren ──
|
||
if _MULTIROOM() and self._multiroom_context is not None:
|
||
try:
|
||
target_name = self._room_info.get(
|
||
target_room_id, {}
|
||
).get("name", "")
|
||
await self._multiroom_context.add(
|
||
target_room_id, target_name,
|
||
f"Red Flag: Agent-Entscheidung → {target_name}",
|
||
)
|
||
except Exception as e:
|
||
logger.debug(
|
||
"V8.4 Red Flag: Ring-Feedback failed: %s", e
|
||
)
|
||
else:
|
||
# Kein ROOM: → STAY-Fallback
|
||
logger.info(
|
||
"[rocketchat] V8.4 Red Flag: Kein ROOM: in Antwort → "
|
||
"STAY-Fallback (Ursprungsraum)"
|
||
)
|
||
routing_counter.increment('red_flag_fallback_stay')
|
||
except Exception as e:
|
||
logger.warning(
|
||
"[rocketchat] V8.4 Red Flag: Response-Interception failed: %s", e
|
||
)
|
||
routing_counter.increment('red_flag_fallback_stay')
|
||
|
||
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
||
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
||
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
||
content = self._replace_slash_with_double_colon(content)
|
||
|
||
# ── Virtual → Real Room Translation ─────────────────────────
|
||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||
real_room_id = chat_id
|
||
if chat_id.startswith("user:"):
|
||
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
||
# wo die Frage gestellt wurde.
|
||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||
# verhindern.
|
||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||
if origin:
|
||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||
current_token = _CURRENT_TASK_TOKEN.get()
|
||
ctx_entry = _room_context.get(chat_id, {})
|
||
stored_token = ctx_entry.get("task_token", "")
|
||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||
# normale ContextVar-Logik weiterlaufen lassen
|
||
if current_token and stored_token and current_token != stored_token:
|
||
routing_counter.increment('priority0_token_mismatch_skip')
|
||
logger.info(
|
||
"[rocketchat] send Priority 0 token mismatch for %s — "
|
||
"skipping stale ContextVar, falling through to _room_context",
|
||
chat_id,
|
||
)
|
||
origin = "" # Force fallthrough
|
||
if origin:
|
||
real_room_id = origin
|
||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||
fallback_origin = _get_room_context_origin(chat_id)
|
||
if fallback_origin:
|
||
real_room_id = fallback_origin
|
||
routing_counter.increment('contextvar_reset_fallback')
|
||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||
if thematic_target:
|
||
real_room_id = thematic_target
|
||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||
rooms = self._user_rooms.get(chat_id, [])
|
||
if rooms:
|
||
real_room_id = rooms[-1] # last room user was active in
|
||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# Fallback: try to find any room with recent activity involving this user
|
||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||
if fallback_room:
|
||
real_room_id = fallback_room
|
||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||
else:
|
||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||
|
||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||
# This allows the agent to request buttons by embedding markup in its
|
||
# response text, without requiring the gateway to pass metadata.
|
||
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
||
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
||
_btn_re = re.compile(
|
||
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
||
r'(?P<text>.*?)'
|
||
r'\[\[/BUTTONS\]\]',
|
||
re.DOTALL | re.IGNORECASE,
|
||
)
|
||
_match = _btn_re.search(content or "")
|
||
if _match:
|
||
_template_name = _match.group("template").lower()
|
||
_inner_text = _match.group("text").strip()
|
||
# Strip the markup from content, keep the inner text
|
||
content = _btn_re.sub(_inner_text, content).strip()
|
||
# Build synthetic metadata so the existing template path below handles it
|
||
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
||
if _template_name == "custom" or "|" in _inner_text:
|
||
# Custom buttons: labels separated by pipe
|
||
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
||
metadata = dict(metadata or {})
|
||
metadata["template"] = "custom"
|
||
metadata["custom_buttons"] = _labels
|
||
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
||
metadata.setdefault("button_title", "Wähle eine Option:")
|
||
elif _template_name in _valid_templates:
|
||
metadata = dict(metadata or {})
|
||
metadata["template"] = _template_name
|
||
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
||
|
||
# Handle interaction templates via metadata
|
||
attachments = None
|
||
if metadata and metadata.get("template"):
|
||
# Use sys.modules to access __init__ symbols (plugin loaded as flat module)
|
||
import sys as _sys
|
||
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
|
||
if _init is None:
|
||
_init = _sys.modules.get('rocketchat')
|
||
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
|
||
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
|
||
template_name = metadata.get("template")
|
||
question_id = metadata.get("question_id", "")
|
||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
||
if buttons:
|
||
attachments = [{
|
||
"color": "#1d74f5",
|
||
"title": metadata.get("button_title", "Wähle eine Option:"),
|
||
"actions": buttons,
|
||
}]
|
||
elif template_name in _TEMPLATE_MAP:
|
||
tmpl = _TEMPLATE_MAP[template_name]
|
||
attachment = dict(tmpl.get("attachment", {}))
|
||
raw_buttons = tmpl.get("buttons", [])
|
||
buttons = []
|
||
for btn in raw_buttons:
|
||
msg_payload = btn.get("msg", "")
|
||
if question_id:
|
||
msg_payload = f"{question_id}::{msg_payload}"
|
||
buttons.append({
|
||
"type": "button",
|
||
"text": btn.get("text", "?"),
|
||
"msg": msg_payload,
|
||
"msg_in_chat_window": True,
|
||
"style": btn.get("style", "default"),
|
||
})
|
||
attachment["actions"] = buttons
|
||
attachments = [attachment]
|
||
|
||
# Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann.
|
||
# Falls metadata ein Template anfordert, aber attachments None bleibt
|
||
# (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar),
|
||
# hänge Text-Fallback an, damit der User weiß, wie er antworten soll.
|
||
if attachments is None:
|
||
fallback_lines = []
|
||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||
opts = metadata["custom_buttons"]
|
||
fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:")
|
||
for i, opt in enumerate(opts, 1):
|
||
fallback_lines.append(f" {i}. {opt}")
|
||
elif template_name == "yes_no":
|
||
fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)")
|
||
elif template_name == "confirm_cancel":
|
||
fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)")
|
||
elif template_name == "ok":
|
||
fallback_lines.append("Antworte mit 1 (OK)")
|
||
elif template_name == "multi_choice_3":
|
||
fallback_lines.append("Antworte mit 1, 2 oder 3")
|
||
if fallback_lines:
|
||
content = content + "\n\n" + "\n".join(fallback_lines)
|
||
logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name)
|
||
|
||
# ── Clarify-Queue: remember pending button question ──
|
||
if metadata and metadata.get("template") and attachments:
|
||
_tmpl = metadata.get("template")
|
||
_qid = metadata.get("question_id", "")
|
||
_expected = []
|
||
if _tmpl == "yes_no":
|
||
_expected = ["ja", "nein", "yes", "no"]
|
||
elif _tmpl == "confirm_cancel":
|
||
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
||
elif _tmpl == "ok":
|
||
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
||
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
||
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
||
self._pending_clarifies[real_room_id] = {
|
||
"question_id": _qid,
|
||
"template": _tmpl,
|
||
"expected": _expected,
|
||
"timestamp": time.time(),
|
||
"original_text": content,
|
||
}
|
||
|
||
# ── P1-7: Proactive message splitting ────────────────────────
|
||
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||
# "(Response formatting failed, plain text:)" — aber die API
|
||
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
|
||
# splitten, nicht erst nach einem Fehlschlag.
|
||
if len(content) > 3000 and attachments is None:
|
||
logger.info(
|
||
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
|
||
len(content),
|
||
)
|
||
return await self._send_split(real_room_id, content)
|
||
|
||
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
||
if success:
|
||
# If this message has buttons, mark the room so the next user
|
||
# message from here stays put (no Archivar routing). Button
|
||
# responses must be answered in the same room the question was
|
||
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||
# and the agent loses context.
|
||
if attachments:
|
||
self._rooms_with_pending_questions.add(real_room_id)
|
||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||
# ── B5v6.5: Conversation History — Agent-Antwort aufzeichnen ──
|
||
if _MULTIROOM() and self._conversation_history is not None:
|
||
await self._conversation_history.add(real_room_id, "agent", content)
|
||
# ── V8.6 P1-3: PresenceEngine — KEIN decrement in send()! ──
|
||
# Der Counter wird NUR im finally-Block von _process_incoming
|
||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||
# würde den Agenten vorzeitig auf "online" setzen.
|
||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||
return SendResult(success=False, error="chat.postMessage failed")
|
||
|
||
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
||
|
||
async def _send_split(self, room_id: str, content: str) -> SendResult:
|
||
"""Split long messages into chunks and send them sequentially.
|
||
|
||
Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||
Lange Antworten (Tabellen, Listen) werden abgeschnitten.
|
||
Diese Methode splittet an Absatzgrenzen und sendet Chunks
|
||
mit (1/3), (2/3), (3/3) Markern.
|
||
|
||
Args:
|
||
room_id: Rocket.Chat Raum-ID
|
||
content: Der vollständige Nachrichtentext
|
||
|
||
Returns:
|
||
SendResult mit success=True wenn alle Chunks gesendet wurden
|
||
"""
|
||
MAX_CHUNK = 2800 # Sicherheitsmarge unter 4000
|
||
paragraphs = content.split("\n\n")
|
||
chunks = []
|
||
current = ""
|
||
|
||
for para in paragraphs:
|
||
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||
chunks.append(current.strip())
|
||
current = para
|
||
else:
|
||
if current:
|
||
current += "\n\n" + para
|
||
else:
|
||
current = para
|
||
|
||
if current.strip():
|
||
chunks.append(current.strip())
|
||
|
||
# If still too long (single huge paragraph), force-split
|
||
if not chunks or len(chunks[0]) > MAX_CHUNK:
|
||
chunks = []
|
||
for i in range(0, len(content), MAX_CHUNK):
|
||
chunks.append(content[i:i + MAX_CHUNK])
|
||
|
||
total = len(chunks)
|
||
if total <= 1:
|
||
# Nothing to split — try sending as-is
|
||
success = await self._post_message_with_retry(room_id, content)
|
||
if success:
|
||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||
return SendResult(success=False, error="chat.postMessage failed")
|
||
|
||
logger.info(
|
||
"[rocketchat] P1-4: Splitting %d chars into %d chunks",
|
||
len(content), total,
|
||
)
|
||
|
||
last_msg_id = None
|
||
for i, chunk in enumerate(chunks, 1):
|
||
marker = f"({i}/{total})"
|
||
chunk_text = f"{marker}\n{chunk}" if total > 1 else chunk
|
||
success = await self._post_message_with_retry(room_id, chunk_text)
|
||
if success:
|
||
last_msg_id = str(int(time.time() * 1000))
|
||
# Small delay between chunks to preserve order
|
||
if i < total:
|
||
await asyncio.sleep(0.5)
|
||
else:
|
||
logger.error(
|
||
"[rocketchat] P1-4: Chunk %d/%d failed to send",
|
||
i, total,
|
||
)
|
||
|
||
if last_msg_id:
|
||
# ── V8.6 P1-4: PresenceEngine — KEIN decrement in _send_split! ──
|
||
# Der Counter wird NUR im finally-Block von _process_incoming
|
||
# dekrementiert (line 2794). _send_split ist ein Sub-Pfad von send().
|
||
return SendResult(success=True, message_id=last_msg_id)
|
||
return SendResult(success=False, error="All chunks failed")
|
||
|
||
# ── P1-6: Slash-Command → Double-Colon Translation ──────────────────
|
||
|
||
@staticmethod
|
||
def _replace_slash_with_double_colon(content: str) -> str:
|
||
"""Replace /approve, /deny etc. with ::approve, ::deny for Rocket.Chat.
|
||
|
||
Hermes Core sends dangerous-command approval messages with
|
||
/approve, /deny, /approve session, /approve always.
|
||
Rocket.Chat doesn't support /-commands, so we replace them
|
||
with :: variants that the plugin's inline command handler
|
||
recognizes.
|
||
"""
|
||
# Match /approve or /deny NOT preceded by a word character
|
||
# (avoids matching inside URLs like /approve in paths).
|
||
# Use word boundary AFTER the command to avoid partial matches.
|
||
content = re.sub(
|
||
r'(?<![a-zA-Z0-9])/approve\b',
|
||
'::approve',
|
||
content
|
||
)
|
||
content = re.sub(
|
||
r'(?<![a-zA-Z0-9])/deny\b',
|
||
'::deny',
|
||
content
|
||
)
|
||
return content
|
||
|
||
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
|
||
"""Fallback method to find a room for a user when direct mapping fails.
|
||
|
||
Args:
|
||
chat_id: Virtual chat_id like "user:username"
|
||
|
||
Returns:
|
||
Room ID if found, None otherwise
|
||
"""
|
||
if not chat_id.startswith("user:"):
|
||
return None
|
||
|
||
target_username = chat_id.split(":", 1)[1].lower()
|
||
|
||
# Try to find any DM room involving this user
|
||
for room_id, room_info in self._room_info.items():
|
||
if room_info.get("type") == "d":
|
||
# Try to get room details with members
|
||
try:
|
||
room_detail = self.rest._request("GET", f"/api/v1/rooms.info?roomId={room_id}", headers={
|
||
"X-Auth-Token": self.rest.auth_token,
|
||
"X-User-Id": self.rest.user_id,
|
||
})
|
||
if room_detail and room_detail.get("success"):
|
||
room_data = room_detail.get("room", {})
|
||
usernames = room_data.get("usernames", [])
|
||
if target_username in [u.lower() for u in usernames]:
|
||
return room_id
|
||
except Exception as e:
|
||
logger.debug("[rocketchat] Could not get room info for %s: %s", room_id, e)
|
||
|
||
# Last resort: return first available room (better than nothing)
|
||
if self._subscribed_rooms:
|
||
first_room = next(iter(self._subscribed_rooms))
|
||
logger.warning("[rocketchat] Using first available room %s as ultimate fallback for %s",
|
||
first_room, chat_id)
|
||
return first_room
|
||
|
||
return None
|
||
|
||
|
||
async def send_clarify(
|
||
self,
|
||
chat_id: str,
|
||
question: str,
|
||
choices: Optional[list],
|
||
clarify_id: str,
|
||
session_key: str,
|
||
metadata: Optional[Dict[str, Any]] = None,
|
||
) -> SendResult:
|
||
"""Render a clarify prompt with Rocket.Chat action buttons.
|
||
|
||
Multi-choice mode (``choices`` non-empty): renders one button per
|
||
option plus a final "✏️ Other (type answer)" button. Picking the
|
||
"Other" button flips the entry into text-capture mode so the next
|
||
message becomes the response.
|
||
|
||
Open-ended mode (``choices`` empty): renders the question as plain
|
||
text — no buttons. The next message in the session is captured by
|
||
the gateway's text-intercept and resolves the clarify.
|
||
"""
|
||
# Fallback to text-based clarify if choices are empty
|
||
if not choices:
|
||
return await super().send_clarify(
|
||
chat_id=chat_id,
|
||
question=question,
|
||
choices=choices,
|
||
clarify_id=clarify_id,
|
||
session_key=session_key,
|
||
metadata=metadata,
|
||
)
|
||
|
||
if not self.rest.auth_token:
|
||
return SendResult(success=False, error="Not authenticated")
|
||
|
||
# ── Virtual → Real Room Translation ─────────────────────────
|
||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||
real_room_id = chat_id
|
||
if chat_id.startswith("user:"):
|
||
# Priority 0: ContextVar from the message that triggered this turn
|
||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||
# verhindern.
|
||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||
if origin:
|
||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||
current_token = _CURRENT_TASK_TOKEN.get()
|
||
ctx_entry = _room_context.get(chat_id, {})
|
||
stored_token = ctx_entry.get("task_token", "")
|
||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||
# normale ContextVar-Logik weiterlaufen lassen
|
||
if current_token and stored_token and current_token != stored_token:
|
||
routing_counter.increment('priority0_token_mismatch_skip')
|
||
logger.info(
|
||
"[rocketchat] send_clarify Priority 0 token mismatch for %s — "
|
||
"skipping stale ContextVar, falling through to _room_context",
|
||
chat_id,
|
||
)
|
||
origin = "" # Force fallthrough
|
||
if origin:
|
||
real_room_id = origin
|
||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||
else:
|
||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||
fallback_origin = _get_room_context_origin(chat_id)
|
||
if fallback_origin:
|
||
real_room_id = fallback_origin
|
||
routing_counter.increment('contextvar_reset_fallback')
|
||
logger.info("[rocketchat] send_clarify via _room_context fallback: %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_clarify via Archivar target: %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_clarify 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}"
|
||
|
||
# P-066-Follow-up: Nutze button_builder-Pipeline statt manueller Buttons.
|
||
# build_button_attachments liefert Emoji-Nummern (1️⃣2️⃣3️⃣),
|
||
# Chunking (max 3 pro Attachment) und action_id pro Button.
|
||
# Wir nutzen das ALTE Payload-Format CLARIFY:<id>:<idx> (ohne ::),
|
||
# weil der ::-Handler in _handle_message ein No-Op ist (P-066-Follow-up).
|
||
from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
|
||
|
||
num_buttons = []
|
||
for i, choice_text in enumerate(choices):
|
||
idx = i + 1 # 1-basierte Indizes (kompatibel mit CLARIFY-Handler)
|
||
num_buttons.append((choice_text, f"CLARIFY:{clarify_id}:{idx}"))
|
||
|
||
attachments = build_button_attachments(
|
||
num_buttons,
|
||
special_buttons=[], # Other-Button manuell (altes Format)
|
||
color="#1d74f5",
|
||
title="Bitte wähle eine Option:",
|
||
number_buttons=True,
|
||
button_style="primary",
|
||
)
|
||
|
||
# Other-Button als separates Attachment (altes Format CLARIFY:<id>:other)
|
||
other_payload = f"CLARIFY:{clarify_id}:other"
|
||
other_attachment = {
|
||
"color": "#1d74f5",
|
||
"actions": [{
|
||
"type": "button",
|
||
"text": "✏️ Andere (Freitext)",
|
||
"msg": other_payload,
|
||
"msg_in_chat_window": True,
|
||
"style": "default",
|
||
"action_id": hashlib.sha1(f"{other_payload}:0".encode()).hexdigest()[:12],
|
||
}],
|
||
}
|
||
attachments.append(other_attachment)
|
||
|
||
# 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)
|
||
|
||
# P-067: Activate Clarify-Modal pulse (busy↔offline toggle)
|
||
if self._presence_engine and self._presence_engine.is_enabled():
|
||
self._presence_engine.set_clarify_modal("Hauptagent wartet auf Antwort")
|
||
|
||
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 _reconnect_backoff_sleep(self) -> None:
|
||
"""B2: Sleep with exponential backoff, capped at 5 minutes.
|
||
|
||
Increments the backoff counter and sleeps for
|
||
min(300, 5 * 2^backoff) seconds. Logs the backoff duration
|
||
at INFO level so operators can see the reconnect cadence
|
||
without per-attempt spam.
|
||
"""
|
||
self._reconnect_backoff += 1
|
||
delay = min(300, 5 * (2 ** self._reconnect_backoff))
|
||
logger.info(
|
||
"[rocketchat] Reconnect backoff: attempt %d, sleeping %.0fs",
|
||
self._reconnect_backoff, delay,
|
||
)
|
||
await asyncio.sleep(delay)
|
||
|
||
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():
|
||
self._reconnect_backoff = 0 # B2: reset on success
|
||
logger.info("[rocketchat] Recovered from silent death")
|
||
else:
|
||
logger.error("[rocketchat] Silent death recovery failed")
|
||
await self._reconnect_backoff_sleep() # B2: exponential backoff
|
||
continue
|
||
|
||
if self.ddp and not self.ddp.connected:
|
||
logger.warning("[rocketchat] DDP disconnected, reconnecting...")
|
||
if await self._reconnect_ddp():
|
||
self._reconnect_backoff = 0 # B2: reset on success
|
||
logger.info("[rocketchat] Reconnected")
|
||
else:
|
||
await self._reconnect_backoff_sleep() # B2: exponential backoff
|
||
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
|