Files
Hermes_rocket.chat_Plugin/plugin/adapter.py
T

1964 lines
91 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Rocket.Chat Platform Adapter for Hermes Agent.
Plugin-based gateway adapter connecting to a self-hosted Rocket.Chat server.
Uses WebSocket/DDP for real-time incoming messages + presence,
and REST API for sending replies.
Zero external dependencies — stdlib only.
"""
import asyncio
import contextvars
import json
import logging
import os
import queue
import re
import socket
import ssl
import struct
import threading
import time
import urllib.request
from typing import Any, Dict, List, Optional
from .archivar.adapter_integration import ArchivarMessageHandler
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# 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.
_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=""
)
# Globaler Monoton-Zähler für Archivar-Fragen
import threading
_question_counter: int = 0
_question_counter_lock: threading.Lock = threading.Lock()
try:
from gateway.platforms.base import (
BasePlatformAdapter,
SendResult,
MessageEvent,
MessageType,
)
from gateway.session import SessionSource
from gateway.config import PlatformConfig, Platform
except ImportError:
# Fallback for standalone test / development outside gateway
BasePlatformAdapter = object
SendResult = dict
MessageEvent = dict
MessageType = object
SessionSource = object
PlatformConfig = object
Platform = str
def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str = "") -> str:
extra = getattr(config, "extra", {}) or {}
return os.getenv(env_var) or extra.get(key, default)
class RocketChatREST:
def __init__(self, base_url: str):
self.base_url = base_url.rstrip("/")
self.auth_token: Optional[str] = None
self.user_id: Optional[str] = None
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
url = f"{self.base_url}{endpoint}"
req_headers = dict(headers) if headers else {}
body = json.dumps(data).encode("utf-8") if data else None
if body:
req_headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=body, headers=req_headers, method=method)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode("utf-8"))
except Exception as e:
logger.debug("REST %s %s failed: %s", method, endpoint, e)
return None
def login(self, user: str, password: str) -> bool:
r = self._request("POST", "/api/v1/login", data={"user": user, "password": password})
if r and r.get("status") == "success":
self.auth_token = r["data"]["authToken"]
self.user_id = r["data"]["userId"]
return True
return False
def get_rooms(self) -> List[dict]:
if not self.auth_token:
return []
r = self._request("GET", "/api/v1/rooms.get", headers={
"X-Auth-Token": self.auth_token,
"X-User-Id": self.user_id,
})
if not r or not r.get("success"):
return []
rooms = []
for rm in r.get("update", []):
t = rm.get("t", "c")
rid = rm["_id"]
if t == "d":
usernames = rm.get("usernames", [])
other = [u for u in usernames if u != os.getenv("ROCKETCHAT_USER", "")]
name = "DM mit " + (", ".join(other) if other else "unbekannt")
else:
name = rm.get("name", "unnamed")
rooms.append({"id": rid, "name": name, "type": t})
return rooms
def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> bool:
if not self.auth_token:
return False
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)
return bool(r and r.get("success"))
def download_file(self, file_id: str, filename: str) -> Optional[str]:
"""Download a file from Rocket.Chat using the authenticated REST client.
Returns the file content as a string (text files) or None on failure.
Uses the existing authToken — no security scanner triggers.
"""
if not self.auth_token:
return None
url = f"{self.base_url}/file-upload/{file_id}/{filename}"
req = urllib.request.Request(url, headers={
"X-Auth-Token": self.auth_token,
"X-User-Id": self.user_id,
})
try:
with urllib.request.urlopen(req, timeout=30) as resp:
content = resp.read()
try:
return content.decode("utf-8")
except UnicodeDecodeError:
return content.decode("latin-1")
except Exception as e:
logger.debug("File download failed: %s", e)
return None
class DDPClient:
PING_INTERVAL = 8.0
RECONNECT_BACKOFFS = [5, 10, 20, 30, 60, 120]
def __init__(self, host: str, on_message_cb=None, on_connected_cb=None):
self.host = host
self._on_message = on_message_cb
self._on_connected = on_connected_cb
self.sock: Optional[socket.socket] = None
self.connected = False
self._running = False
self._reader_thread: Optional[threading.Thread] = None
self._write_lock = threading.Lock()
self._msg_queue: queue.Queue = queue.Queue()
self._next_sub_id = 1
self._sub_rooms: Dict[str, str] = {}
self._session: Optional[str] = None
self._reconnect_attempt = 0
self._last_rx_time = 0.0
def _create_socket(self) -> socket.socket:
ctx = ssl.create_default_context()
raw = socket.create_connection((self.host, 443), timeout=10)
return ctx.wrap_socket(raw, server_hostname=self.host)
def _handshake(self, s: socket.socket) -> bool:
import base64
key = base64.b64encode(os.urandom(16)).decode()
hs = (
f"GET /websocket HTTP/1.1\r\n"
f"Host: {self.host}\r\n"
f"Upgrade: websocket\r\n"
f"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
f"Sec-WebSocket-Version: 13\r\n"
f"Origin: https://{self.host}\r\n\r\n"
)
s.sendall(hs.encode())
resp = b""
while b"\r\n\r\n" not in resp:
chunk = s.recv(1024)
if not chunk:
break
resp += chunk
return b"101 Switching Protocols" in resp
def _send_frame(self, data: bytes, opcode: int = 0x01, mask: bool = True) -> None:
if not self.sock:
return
length = len(data)
if length < 126:
header = struct.pack("!BB", 0x80 | opcode, (0x80 if mask else 0x00) | length)
elif length < 65536:
header = struct.pack("!BBH", 0x80 | opcode, (0x80 if mask else 0x00) | 126, length)
else:
header = struct.pack("!BBQ", 0x80 | opcode, (0x80 if mask else 0x00) | 127, length)
frame = header
if mask:
masking = os.urandom(4)
masked = bytes(b ^ masking[i % 4] for i, b in enumerate(data))
frame += masking + masked
else:
frame += data
with self._write_lock:
self.sock.sendall(frame)
def _send_json(self, obj: dict) -> None:
self._send_frame(json.dumps(obj).encode("utf-8"), opcode=0x01, mask=True)
def _send_raw_pong(self, payload: bytes) -> None:
self._send_frame(payload, opcode=0x0A, mask=True)
def _reader_loop(self):
import select
self.sock.settimeout(1.0)
last_ping = time.time()
while self._running:
try:
if time.time() - last_ping >= self.PING_INTERVAL:
try:
self._send_json({"msg": "ping"})
last_ping = time.time()
except Exception:
break
readable, _, _ = select.select([self.sock], [], [], 1.0)
if not readable:
continue
hdr = self.sock.recv(2)
if not hdr:
break
fin = (hdr[0] & 0x80) != 0
opcode = hdr[0] & 0x0F
masked = (hdr[1] & 0x80) != 0
length = hdr[1] & 0x7F
if length == 126:
length = struct.unpack("!H", self.sock.recv(2))[0]
elif length == 127:
length = struct.unpack("!Q", self.sock.recv(8))[0]
payload = b""
remaining = length
while remaining > 0:
chunk = self.sock.recv(min(4096, remaining))
if not chunk:
break
payload += chunk
remaining -= len(chunk)
if len(payload) < length:
break
if masked:
mask = payload[:4]
payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload[4:]))
if opcode == 0x09:
self._send_raw_pong(payload)
elif opcode == 0x01 and payload:
self._last_rx_time = time.time()
try:
data = json.loads(payload.decode("utf-8", errors="ignore"))
msg_type = data.get("msg", "")
if msg_type == "connected":
self.connected = True
self._session = data.get("session")
if self._on_connected:
self._on_connected()
elif msg_type == "ping":
self._send_json({"msg": "pong"})
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
fields = data.get("fields", {})
args = fields.get("args", [])
if args and isinstance(args, list) and len(args) >= 1:
self._msg_queue.put(args[0])
except Exception:
pass
elif opcode == 0x08:
break
except Exception:
break
self.connected = False
logger.debug("DDP reader thread exited")
def is_alive(self, max_silence: float = 300.0) -> bool:
"""Detect silent death: socket looks connected but no traffic for max_silence seconds."""
if not self.connected or not self.sock:
return False
if self._last_rx_time == 0:
# Never received anything yet — use connect time as baseline
return True
return (time.time() - self._last_rx_time) < max_silence
def connect_and_login(self, token: str) -> bool:
self._last_rx_time = time.time()
try:
self.sock = self._create_socket()
if not self._handshake(self.sock):
return False
self._running = True
self._reader_thread = threading.Thread(target=self._reader_loop, daemon=True)
self._reader_thread.start()
time.sleep(0.3)
self._send_json({"msg": "connect", "version": "1", "support": ["1", "pre2", "pre1"]})
for _ in range(50):
if self.connected:
break
time.sleep(0.1)
if not self.connected:
self.disconnect()
return False
time.sleep(0.2)
self._send_json({"msg": "method", "method": "login",
"params": [{"resume": token}], "id": "ddplogin"})
time.sleep(0.5)
return True
except Exception as e:
logger.error("DDP connect failed: %s", e)
self.disconnect()
return False
def subscribe_room(self, room_id: str) -> Optional[str]:
if not self.connected:
return None
sub_id = f"sub{self._next_sub_id}"
self._next_sub_id += 1
# CRITICAL: Rocket.Chat V5+ requires {"token": "true"} as second param,
# otherwise subscribe succeeds but NO messages ever stream.
self._send_json({
"msg": "sub",
"name": "stream-room-messages",
"params": [room_id, {"token": "true"}],
"id": sub_id
})
self._sub_rooms[room_id] = sub_id
return sub_id
def set_status(self, status: str) -> bool:
if not self.connected:
return False
method = f"UserPresence:{status}"
self._send_json({"msg": "method", "method": method, "params": [], "id": f"st{int(time.time()*1000)}"})
return True
def disconnect(self):
self._running = False
if self.sock:
try:
self.sock.close()
except Exception:
pass
self.sock = None
self.connected = False
self._sub_rooms.clear()
def reconnect_and_restore(self, token: str) -> bool:
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) ────────────────────────────────────
_AUFTRAG_KEYWORDS: list = [
"bitte", "erstell", "mach", "änder", "konfigurier",
"schreib", "bau", "implementier", "test", "deploy",
"start", "stopp", "analysier", "prüf", "untersuch",
"beheb", "fix", "korrigier", "optimier", "erweiter",
"füg hinzu", "entfern", "lösch", "verschieb",
"generier", "kompilier", "installier",
]
def _is_auftrag(text: str) -> bool:
"""Heuristik: Enthält die Nachricht Imperative oder direkte Ansprache?"""
t = text.lower()
for kw in _AUFTRAG_KEYWORDS:
if kw in t:
return True
return False
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()
# Health-check state
self._last_server_activity = 0.0 # ts of last DDP ping/pong or message
self._health_check_timer: Optional[threading.Timer] = None
self._last_ddp_ping_ok = False
self._running = False
# Archivar: Embedding-basierte Nachrichten-Klassifikation
self.archivar = ArchivarMessageHandler(
send_callback=self._send_via_archivar,
button_send_callback=self._send_archivar_buttons,
)
# User-Flow C: Move-Requests + Sticky Rooms
self._pending_move_requests: Dict[str, dict] = {}
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
# Clarify state: maps clarify_id → session_key for gateway resolution
self._clarify_state: Dict[str, str] = {}
# Auto-Onboarding v2: structured interview state
self._onboarding_state: Dict[str, Any] = {}
async def connect(self) -> bool:
if not self.base_url or not self.user or not self.password:
logger.error("[rocketchat] Missing configuration")
return False
if not self.rest.login(self.user, self.password):
logger.error("[rocketchat] REST login failed")
return False
self._auth_token = self.rest.auth_token
self._user_id = self.rest.user_id
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
self.ddp = DDPClient(
host=host,
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
)
if not self.ddp.connect_and_login(self._auth_token):
logger.error("[rocketchat] DDP connect/login failed")
return False
self._rooms = self.rest.get_rooms()
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
for room in self._rooms:
sub_id = self.ddp.subscribe_room(room["id"])
if sub_id:
self._subscribed_rooms.add(room["id"])
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"])
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)
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)")
# 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()
}
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
if missing:
await self._start_onboarding(missing)
except Exception as e:
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
self._mark_connected()
self._running = True
self._listen_task = asyncio.create_task(self._listen_loop())
self._last_activity = time.time()
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
logger.info("[rocketchat] Connected to %s", self.base_url)
return True
def _schedule_idle_timer(self) -> None:
"""Schedule idle timer to mark bot as away when inactive."""
if self._status_timer:
self._status_timer.cancel()
def _set_away():
if self.ddp:
self.ddp.set_status("away")
self._status_timer = threading.Timer(300.0, _set_away) # 5 minutes
self._status_timer.daemon = True
self._status_timer.start()
async def _process_incoming(self, msg_obj) -> None:
"""Process an incoming message from the DDP queue."""
if not isinstance(msg_obj, dict):
return
# Check if this is a button click response by looking for specific fields.
# TWO detection paths:
# 1. Native Rocket.Chat button events (triggerId + actions + triggerSender + payload)
# 2. In-chat button responses via msg_in_chat_window, which arrive as regular
# text messages containing a question_id::choice payload (e.g. "bypass_001::Ja").
text = msg_obj.get("msg", "")
is_button_response = (
(msg_obj.get("triggerId") and
msg_obj.get("actions") and
msg_obj.get("params", {}).get("triggerSender") and
msg_obj.get("params", {}).get("payload"))
or (text and "::" in text and not text.startswith("CLARIFY:") and text.split("::", 1)[0].strip() != "")
or (text and text.startswith("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
# NEW: Check for file attachments in the message and enrich the text
file_info = msg_obj.get("file")
attachments = msg_obj.get("attachments", [])
if file_info or attachments:
file_details = []
seen_ids = set()
base_url = self.base_url.rstrip("/")
# Process file object if present (has precise MIME type)
if file_info and isinstance(file_info, dict):
filename = file_info.get("name", "unknown")
filetype = file_info.get("type", "unknown")
file_id = file_info.get("_id")
if file_id and filename:
seen_ids.add(file_id)
download_url = f"{base_url}/file-upload/{file_id}/{filename}"
file_details.append(f"[FILE] {filename} ({filetype})\nDownload: {download_url}")
# Process attachments if present (skip duplicates already covered by file_info)
if attachments and isinstance(attachments, list):
for attachment in attachments:
if isinstance(attachment, dict) and attachment.get("type") == "file":
title = attachment.get("title", "unknown")
title_link = attachment.get("title_link", "")
if title_link:
if title_link.startswith("/"):
download_url = f"{base_url}{title_link}"
else:
download_url = f"{base_url}/{title_link}"
# Extract file_id from title_link to detect duplicates
link_id = title_link.split("/")[2] if title_link.startswith("/file-upload/") else None
if link_id and link_id in seen_ids:
continue # Already covered by precise file_info
file_details.append(f"[FILE] {title} (file)\nDownload: {download_url}")
# Add file information to message text
if file_details:
file_info_text = "\n".join(file_details)
if text:
text = f"{text}\n\n{file_info_text}"
else:
text = file_info_text
msg_obj["msg"] = text
# Skip own messages (case-insensitive comparison)
if username == (self.user or "").lower() or not text or not room_id:
return
# Skip system messages
if msg_obj.get("t"):
return
# 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])
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
_THEMATIC_TARGET_ROOM.set("")
# ── CLARIFY Response Handling ───────────────────────────────────
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
if is_clarify_response and text.startswith("CLARIFY:"):
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)
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)
# Don't process further - wait for the next text message
return
elif choice.isdigit():
# Numeric choice → resolve the clarify immediately
idx = int(choice)
resolved_text: Optional[str] = None
try:
from tools.clarify_gateway import _entries as _clarify_entries
entry = _clarify_entries.get(clarify_id)
if entry and entry.choices and 0 <= idx < len(entry.choices):
resolved_text = entry.choices[idx]
except Exception:
resolved_text = None
if resolved_text is None:
# Race: entry vanished. Echo the index.
resolved_text = f"choice {idx + 1}"
# Resolve via gateway and clean up
self._clarify_state.pop(clarify_id, None)
try:
from tools.clarify_gateway import resolve_gateway_clarify
resolved = resolve_gateway_clarify(clarify_id, resolved_text)
if resolved:
logger.info(
"[rocketchat] Clarify %s resolved: %s (session=%s)",
clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"),
)
else:
logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id)
except Exception as exc:
logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc)
# Don't route to agent — this was a button click
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)
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
if self.archivar._stats.get("onboarding_active", False):
stripped = text.strip()
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
operator_room = self._onboarding_state.get("operator_room_id", "")
is_operator_room = (operator_room and room_id == operator_room)
is_onboarding = (
(is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
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)
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()
# Altes Format: "1"/"2"/"3" = numerische Antwort
# Neues Format: "1️⃣", "2️⃣", "3️⃣" = Emoji-Nummern
elif choice in ("1", "2", "3") or choice in ("1️⃣", "2️⃣", "3️⃣"):
num = int(choice[0]) # Extrahiere die Zahl (entweder direkt oder aus dem Emoji)
if num == 1:
choice = "rüberkopieren"
elif num == 2:
choice = "hier bleiben"
else:
choice = "generell"
choice = choice.lower()
# Neue Mapping-Logik für verbesserte Button-UX
feedback_type = "stay" # Default
if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"):
# Rüberkopieren
target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}"
if move_req.get("username"):
self.rest.post_message(move_req["target_room"], target_txt)
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
forwarded = True
feedback_type = "confirm"
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
# Nicht mehr fragen / sticky_room setzen
self._sticky_rooms[room_id] = time.time()
self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
feedback_type = "never"
else:
# "Hier bleiben" / "2" / "2️⃣" — Default
self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
feedback_type = "stay"
# Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen
if 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
)
return # Move-Request verarbeitet — keine weitere Verarbeitung
forwarded = False
# ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
# Klassifiziere die Nachricht und entscheide über Copy/Routing.
# Die Antwort des Agenten bleibt IMMER im Ursprungsraum.
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
category = ""
decision = None
is_auftrag = _is_auftrag(text)
try:
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)
self._rooms_with_pending_questions.discard(room_id)
elif room_id in self._sticky_rooms:
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
elif room_type == "d" and is_auftrag:
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
else:
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
if decision and decision.category:
category = decision.category
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
if hasattr(decision, 'target_room') and decision.target_room:
_THEMATIC_TARGET_ROOM.set(decision.target_room)
global _question_counter
with _question_counter_lock:
_question_counter += 1
# ── Ende Kontext-Weitergabe ──────────────────────────────
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
if (getattr(decision, 'move_request_sent', False)
and hasattr(decision, 'target_room')
and decision.target_room):
self._pending_move_requests[room_id] = {
'text': text,
'origin_room': room_id,
'target_room': decision.target_room,
'target_name': getattr(
decision, 'move_request_target_name', 'Zielraum'),
'username': username,
'message_id': msg_id,
}
# Lernsystem: Keywords für Feedback-Loop speichern
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
self.archivar._routed_messages[msg_id] = {
"keywords": decision.matched_keywords,
"target_room": decision.target_room,
"timestamp": time.time()
}
except asyncio.TimeoutError:
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
with _question_counter_lock:
_question_counter += 1
# _THEMATIC_TARGET_ROOM bleibt leer → Prompt sagt "Timeout"
except Exception as e:
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
# _CURRENT_ORIGIN_ROOM wird NIE auf den Zielraum gesetzt.
# Die Agent-Antwort bleibt im Ursprungsraum. Nur die Nachricht
# wird kopiert — mit User-Entscheidung bei Aufträgen.
forwarded = False
if (decision and hasattr(decision, 'target_room') and decision.target_room
and decision.target_room != room_id
and not getattr(decision, 'is_unrouteable', False)
and not getattr(decision, 'stay_in_room', False)
and not getattr(decision, 'move_request_sent', False)): # Archivar v4 hat bereits Buttons gesendet → kein Doppel-Routing
target_name = getattr(decision, 'matched_room_name', None)
if not target_name:
# Fallback: Raum-Name aus room_info oder room_map
target_name = self._room_info.get(decision.target_room, {}).get("name", "")
if not target_name:
# Letzter Fallback: room_map (wenn bekannt)
for rid, entry in self.archivar._room_map.rooms.items():
if rid == decision.target_room:
target_name = entry.name
break
if not target_name:
target_name = decision.target_room[:12] + "…" # ID-Fragment als Notlösung
if is_auftrag:
# Typ 2: Native Action-Buttons (Button-Garantie)
try:
from . import _build_custom_buttons
move_prefix = f"MOVE_REQ:{room_id}"
buttons = _build_custom_buttons(
["1️⃣ Rüber", "2️⃣ Hier", "3️⃣ Nein"],
prefix=move_prefix
)
note = (f"Dein Auftrag passt thematisch besser in **{target_name}**.\n\n"
f"**Was soll ich tun?**\n\n"
f"1️⃣ **Rüberkopieren** = Auftrag verschieben, ich antworte dort\n"
f"2️⃣ **Hier bleiben** = Auftrag bleibt hier, ich kümmere mich drum\n"
f"3️⃣ **Nicht mehr fragen** = Raum wird bis Neustart nicht mehr geroutet\n\n"
f"Wohin soll ich den Auftrag verschieben?")
attachments = [{
"color": "#1d74f5",
"title": "Wohin soll ich den Auftrag verschieben?",
"actions": buttons,
}]
self._pending_move_requests[room_id] = {
"text": text,
"origin_room": room_id,
"target_room": decision.target_room,
"target_name": target_name,
"username": username,
"message_id": msg_id,
}
self.rest.post_message(room_id, note, attachments=attachments)
except Exception:
# Fallback: Textoptionen (wenn Button-Send fehlschlägt)
note = (
f"Dein Auftrag passt thematisch besser in **{target_name}**.\n"
f"Antworte mit einer Zahl:\n"
f"1 = Ja, rüberkopieren und dort abarbeiten\n"
f"2 = Hier bleiben\n"
f"3 = Generell hier bleiben"
)
self._pending_move_requests[room_id] = {
"text": text,
"origin_room": room_id,
"target_room": decision.target_room,
"target_name": target_name,
"username": username,
"message_id": msg_id,
}
self.rest.post_message(room_id, note)
# Kein Forwarding — auf User-Antwort warten
forwarded = True
else:
# Typ 1: Silent Copy — Nachricht in Zielraum kopieren
self.rest.post_message(decision.target_room,
f"*(Thema passt zu {target_name} — von @{username})*\n{text}")
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
self.rest.post_message(room_id, note)
# Agent soll im Zielraum antworten, nicht im Ursprungsraum
_CURRENT_ORIGIN_ROOM.set(decision.target_room)
forwarded = True
# 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)
# ── Virtual Room Translation ─────────────────────────────────
# Replace room-based chat_id with user-based virtual chat_id.
# This collapses all rooms per user into ONE Hermes session:
# DM with alice: room_id=ABC123 → chat_id="user:alice"
# #Project-Chat: room_id=XYZ789 → chat_id="user:alice"
# Both get the same session key.
virtual_chat_id = f"user:{username}"
# _CURRENT_ORIGIN_ROOM wurde bereits oben im User-Flow-C gesetzt
# Ensure this user→room mapping is recorded for proaktive sends
if virtual_chat_id not in self._user_rooms:
self._user_rooms[virtual_chat_id] = []
if room_id not in self._user_rooms[virtual_chat_id]:
self._user_rooms[virtual_chat_id].append(room_id)
# Dispatch to gateway handler via base-class handle_message
try:
from datetime import datetime
message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
target_room_id = _THEMATIC_TARGET_ROOM.get()
if target_room_id:
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
with _question_counter_lock:
archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]"
else:
# Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung
room_names = [info.get("name", "?") for rid, info in self._room_info.items()
if info.get("type") in ("c", "p") and rid != room_id]
rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume"
with _question_counter_lock:
archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]"
# ── Ende Kontext-Weitergabe ──────────────────────────────────────
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
)
event = MessageEvent(
text=text,
message_type=message_type,
message_id=msg_id,
timestamp=datetime.fromtimestamp(time.time()),
raw_message=msg_obj,
)
event.source = source
await self.handle_message(event)
except Exception as e:
logger.error("[rocketchat] handle_message error: %s", e)
# Fallback: Wenn BUTTON_CLICK fehlschlägt (z.B. nach Gateway-Neustart
# verliert der neue Prozess den In-Memory-Callback), als normale
# Text-Nachricht mit Hinweis wiederholen.
if is_button_response and str(e) == "BUTTON_CLICK":
logger.info("[rocketchat] BUTTON_CLICK lost context — retrying as TEXT")
try:
from datetime import datetime as dt2
fallback_source = SessionSource(
platform=Platform("rocketchat"),
chat_id=f"user:{username}",
chat_name=f"{room_name} (via @{username})",
user_id=username,
user_name=username,
chat_type="dm",
)
fallback_event = MessageEvent(
text=f"[Button-Antwort: {text}]",
message_type=MessageType.TEXT,
message_id=msg_id,
timestamp=dt2.fromtimestamp(time.time()),
raw_message=msg_obj,
)
fallback_event.source = fallback_source
await self.handle_message(fallback_event)
except Exception as e2:
logger.error("[rocketchat] BUTTON_CLICK text fallback also failed: %s", e2)
async def _send_via_archivar(self, room_id: str, text: str) -> bool:
"""Callback for Archivar forwarding — sends a message copy to a target room."""
if not self.rest.auth_token:
return False
return self.rest.post_message(room_id, text)
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
from . import _build_custom_buttons
actions = payload.get("actions", [])
if not actions:
return self.rest.post_message(room_id, text)
# Detect Archivar v4 Move-Request (Butler-Prinzip: ✅Ja / 📍Hier)
move_req_ctx = payload.get("_move_request")
if move_req_ctx:
# Store pending move request so line 717 handler finds it
self._pending_move_requests[room_id] = {
"text": move_req_ctx.get("text", ""),
"origin_room": room_id,
"target_room": move_req_ctx.get("target_room", ""),
"target_name": move_req_ctx.get("target_name", ""),
"username": "", # filled from user_info in handler (line 718)
"message_id": "", # no msg_id for Archivar v4 move-request flow
}
# Use MOVE_REQ: prefix so the existing handler at line 717-764
# parses the response correctly (see line 722-724)
msg_prefix = f"MOVE_REQ:{room_id}"
log_tag = "move-request"
else:
msg_prefix = "ARCHIVAR_CLARIFY"
log_tag = "clarification"
# Build native RC buttons from Archivar actions
buttons = []
for i, action in enumerate(actions):
action_type = action.get("type", f"action_{i}")
action_text = action.get("text", f"Option {i+1}")
# Move-request buttons use :: separator for line 722 parsing
selector = f"{msg_prefix}::{action_type}" if move_req_ctx else f"{msg_prefix}:{action_type}"
buttons.append({
"type": "button",
"text": action_text,
"msg": selector,
"msg_in_chat_window": True,
"style": "default",
})
attachments = [{
"color": "#1d74f5",
"title": text,
"actions": buttons,
}]
success = self.rest.post_message(room_id, text, attachments=attachments)
if success:
# 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
async def _start_onboarding(self, missing_rooms: list) -> None:
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
Neues Design (UX-Fix):
- Pro Raum: EIN blauer Nummern-Button (1️⃣, 2️⃣, …) → style 'primary'
- Zwei globale Buttons: ⏭️ Alle überspringen, ⏰ Später
- Payload-Präfix: ONBOARD:<room_id>::select für Raum-Buttons,
ONBOARD::skip_all / ONBOARD::later für globale Aktionen
- Bei 4 Räumen: 6 Buttons statt 12 — keine abgeschnittenen Labels mehr
Args:
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
"""
# Finde den Operator-DM Raum
operator_room_id = None
for room_id, info in self._room_info.items():
if info.get("type") == "d" and "andreas" in info.get("name", "").lower():
operator_room_id = room_id
break
if not operator_room_id:
logger.warning("[rocketchat] Operator-DM-Raum nicht gefunden, kann Onboarding nicht starten")
return
# Initialisiere Onboarding-State
self._onboarding_state = {
"missing_rooms": missing_rooms,
"current_room_index": -1, # -1 = noch kein Raum ausgewählt
"current_question": 0, # 0 = noch keine Frage gestellt
"collected_data": {}, # room_id → {theme, keywords_100, keywords_context, catch_all}
"operator_room_id": operator_room_id,
"skipped_rooms": [], # room_ids die übersprungen wurden
}
self.archivar._stats["onboarding_active"] = True
# Baue Nachricht mit Emoji-Nummern-Referenzen
from . import _build_custom_buttons
# Emoji-Zahlen für bis zu 10 Räume
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
lines = ["Folgende Räume fehlen in der Raum-Map:"]
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("Klicke auf eine Nummer, um den Raum einzurichten:")
text = "\n".join(lines)
# Raum-Buttons: blaue Nummern (style='primary')
buttons = []
for i, room in enumerate(missing_rooms):
rid = room["room_id"]
emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else f"{i+1}."
prefix = f"ONBOARD:{rid}"
buttons.extend(_build_custom_buttons(
[emoji],
prefix=prefix,
style="primary"
))
# Globale Buttons (style='default' = grau)
buttons.extend(_build_custom_buttons(
["⏭️ Alle überspringen", "⏰ Später"],
prefix="ONBOARD"
))
attachments = [{
"color": "#1d74f5",
"title": "Raum-Map unvollständig — Räume einrichten?",
"actions": buttons,
}]
success = self.rest.post_message(operator_room_id, text, attachments=attachments)
if success:
logger.info("[rocketchat] Onboarding v2 gestartet: %d Räume fehlen", len(missing_rooms))
else:
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
async def _process_onboarding_response(self, text: str, room_id: str) -> None:
"""v2: Verarbeitet Onboarding-Antworten (Button-Klicks + Text-Antworten).
Zwei Modi:
1. Button-Klick (ONBOARD:<room_id>::<action>) — Raumauswahl / Überspringen / Später
2. Text-Antwort — Antwort auf eine der 4 Interview-Fragen
Args:
text: Die Antwortnachricht des Operators (Button-Payload oder Freitext)
room_id: Die Raum-ID, in der die Nachricht empfangen wurde
"""
state = self._onboarding_state
if not state:
logger.debug("[rocketchat] Onboarding state empty, ignoring response")
return
operator_room_id = state.get("operator_room_id", "")
if room_id != operator_room_id:
logger.debug("[rocketchat] Onboarding response from non-operator room, ignoring")
return
# ── Phase: catch_all_change (nach Abschluss aller Interviews) ────
if state.get("phase") == "catch_all_change":
single_line = text.strip()
if 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]
self._set_catch_all(rid)
self.rest.post_message(operator_room_id, f"🎯 {name} ist jetzt der Catch-All-Raum.")
logger.info("[rocketchat] Catch-All geändert zu: %s", name)
else:
self.rest.post_message(operator_room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
return # onboarding_active bleibt True, warte auf korrekte Antwort
elif single_line.lower() in ("überspringen", "skip", "nein", "no", "behalten"):
self.rest.post_message(operator_room_id, "👍 Catch-All bleibt unverändert.")
logger.info("[rocketchat] Catch-All unverändert")
else:
self.rest.post_message(operator_room_id, "❌ Bitte eine Raumnummer (1, 2, …) oder 'überspringen' eingeben.")
return # onboarding_active bleibt True
# Catch-All-Frage beantwortet → Onboarding wirklich abschließen
self.archivar._stats["onboarding_active"] = False
self._onboarding_state = {}
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen")
return
# ── Modus 1: Button-Klick (ONBOARD:<room_id>::<action>) ──────────
if text.startswith("ONBOARD:") and "::" in text:
prefix_part, action = text.split("::", 1)
action = action.strip()
# Globale Aktionen (kein room_id): ONBOARD::skip_all, ONBOARD::later
if prefix_part == "ONBOARD":
if "skip_all" in action:
# Alle verbleibenden Räume überspringen
missing = state["missing_rooms"]
for room in missing:
rid = room["room_id"]
if rid not in state["skipped_rooms"]:
state["skipped_rooms"].append(rid)
logger.info("[rocketchat] Onboarding: alle Räume übersprungen (skip_all)")
self._onboarding_next_room()
return
if "later" in action:
# Onboarding pausieren
self.archivar._stats["onboarding_active"] = False
self._onboarding_state = {}
self.rest.post_message(operator_room_id,
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
logger.info("[rocketchat] Onboarding pausiert (later)")
return
# Raum-spezifische Aktionen: ONBOARD:<room_id>::<action>
target_room_id = prefix_part.split(":", 1)[1]
if "Überspringen" in action or "⏭️" in action:
# Einzelnen Raum überspringen
state["skipped_rooms"].append(target_room_id)
logger.info("[rocketchat] Onboarding: Raum %s übersprungen", target_room_id[:8])
self._onboarding_next_room()
return
if "Später" in action or "⏰" in action:
# Onboarding pausieren
self.archivar._stats["onboarding_active"] = False
self._onboarding_state = {}
self.rest.post_message(operator_room_id,
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
logger.info("[rocketchat] Onboarding pausiert (Später)")
return
# "Projektraum einrichten" — Interview starten
missing = state["missing_rooms"]
for i, room in enumerate(missing):
if room["room_id"] == target_room_id:
state["current_room_index"] = i
state["current_question"] = 1
state["collected_data"][target_room_id] = {
"theme": "",
"keywords_100": [],
"keywords_context": [],
"catch_all": False,
}
break
if state["current_room_index"] >= 0:
self._ask_onboarding_question(operator_room_id)
return
# ── Modus 2: Text-Antwort auf Interview-Frage ────────────────────
current_idx = state.get("current_room_index", -1)
if current_idx < 0:
return # Kein aktives Interview
current_q = state.get("current_question", 0)
if current_q < 1 or current_q > 4:
return # Keine aktive Frage
room = state["missing_rooms"][current_idx]
rid = room["room_id"]
data = state["collected_data"].get(rid, {})
# Frage 1: theme
if current_q == 1:
theme = text.strip()
if not theme or len(theme) < 3:
self.rest.post_message(operator_room_id,
"❌ Bitte gib eine kurze Beschreibung ein (mindestens 3 Zeichen).")
return
data["theme"] = theme
state["current_question"] = 2
self._ask_onboarding_question(operator_room_id)
return
# Frage 2: keywords_100
if current_q == 2:
raw = text.strip()
if raw.lower() in ("keine", "none", "-", ""):
data["keywords_100"] = []
else:
# Akzeptiere komma-getrennt oder leerzeichen-getrennt
if "," in raw:
kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
else:
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
data["keywords_100"] = kws[:10]
state["current_question"] = 3
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]
state["current_question"] = 4
self._ask_onboarding_question(operator_room_id)
return
# Frage 4: catch_all
if current_q == 4:
answer = text.strip().lower()
is_catch_all = answer in ("ja", "yes", "j", "y", "1", "👍", "✅")
data["catch_all"] = is_catch_all
# Raum zur Map hinzufügen
room_name = room["name"]
self.archivar._room_map.add_or_update_room(
room_id=rid,
name=room_name,
theme=data["theme"],
keywords_100=data.get("keywords_100", []),
keywords_context=data.get("keywords_context", []),
catch_all=is_catch_all,
)
# Speichern + reload
from .archivar.room_map import RoomMap
from .archivar.config import ROOM_MAP_PATH
from pathlib import Path
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
self.archivar._room_map.reload()
logger.info("[rocketchat] Onboarding: Raum %s zur Map hinzugefügt (catch_all=%s)",
room_name, is_catch_all)
# Feedback an Operator
catch_marker = " 🎯 Catch-All" if is_catch_all else ""
self.rest.post_message(operator_room_id,
f"✅ {room_name} eingerichtet:{catch_marker}\n"
f"Thema: {data['theme']}\n"
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
# Nächster Raum oder Abschluss
self._onboarding_next_room()
return
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"]
current_q = state.get("current_question", 0)
questions = {
1: f"**{room_name}** — Frage 1/4:\nWorum geht es in diesem Raum? (1–2 Sätze)",
2: f"**{room_name}** — Frage 2/4:\nWelche Begriffe treffen SICHER zu? (Sofort-Match, z.B. \"bat\", \"trading\")\n"
f"(Komma-getrennt, oder \"keine\" wenn keine)",
3: f"**{room_name}** — Frage 3/4:\nWelche Begriffe deuten auf das Thema hin? (Kontext-Match, z.B. \"gateway\", \"plugin\")\n"
f"(Komma-getrennt, oder \"keine\" wenn keine)",
4: f"**{room_name}** — Frage 4/4:\nSoll dieser Raum der Catch-All sein? (Ja/Nein)",
}
text = questions.get(current_q, "")
if text:
self.rest.post_message(operator_room_id, text)
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:
from . import _build_custom_buttons
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("Klicke auf einen Button:")
buttons = []
for room in remaining:
rid = room["room_id"]
clean_name = room["name"].lstrip("#")
prefix = f"ONBOARD:{rid}"
buttons.extend(_build_custom_buttons(
[f"📋 {clean_name[:8]}", f"⏭️ Überspringen", f"⏰ Später"],
prefix=prefix
))
attachments = [{
"color": "#1d74f5",
"title": "Weitere Räume einrichten?",
"actions": buttons,
}]
self.rest.post_message(operator_room_id, "\n".join(lines), attachments=attachments)
else:
self._finish_onboarding(operator_room_id)
else:
# Alle Räume bearbeitet
self._finish_onboarding(operator_room_id)
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,
}
# Baue nummerierte Raumliste
all_rooms = []
for rid, entry in self.archivar._room_map.rooms.items():
if rid in self.archivar._room_map._excluded_room_ids:
continue
all_rooms.append((rid, entry.name, entry.catch_all))
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):
marker = " 🎯 (Catch-All)" if is_catch else ""
lines.append(f"{i}. {name}{marker}")
lines.append("")
lines.append("Möchtest du den Catch-All-Raum ändern? Antworte mit der Raumnummer, oder **überspringen** zum Behalten.")
self.rest.post_message(operator_room_id, "\n".join(lines))
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
@staticmethod
def _derive_keywords(room_name: str, theme: str) -> list:
"""Leitet Stichworte aus Raumname und Thema ab.
Regeln:
- Raumname ohne '#' und ohne Bindestriche → einzelne Teile als Keywords
- Erste 2-4 signifikante Wörter aus dem Thema (keine Stopwörter)
- Maximal 10 Keywords, keine Duplikate, alle lowercase
"""
STOP = {"der", "die", "das", "und", "oder", "zum", "zur", "des", "dem", "den",
"ein", "eine", "einen", "einem", "für", "mit", "auf", "an", "von",
"ist", "sind", "wird", "the", "and", "or", "for", "with", "of", "to"}
keywords = []
# Aus Raumname: #BAT-Team → ["bat", "team"]
name_clean = room_name.lstrip("#")
for part in name_clean.replace("-", " ").replace("_", " ").split():
kw = part.lower().strip(".,;:!?")
if kw and kw not in STOP:
keywords.append(kw)
# Aus Thema: erste signifikante Wörter
for word in theme.lower().replace(",", " ").split():
w = word.strip(".,;:!?")
if w and w not in STOP and w not in keywords:
keywords.append(w)
if len(keywords) >= 10:
break
return keywords[:10]
def _get_onboarding_room_list(self) -> list:
"""Erstellt eine nummerierte Liste aller Räume (ohne excluded)."""
rooms = []
for rid, entry in self.archivar._room_map.rooms.items():
if rid in self.archivar._room_map._excluded_room_ids:
continue
rooms.append((rid, entry.name))
rooms.sort(key=lambda x: x[1]) # alphabetisch
return rooms
def _set_catch_all(self, room_id: str) -> None:
"""Setzt den angegebenen Raum als alleinigen Catch-All."""
from .archivar.config import ROOM_MAP_PATH
from pathlib import Path
for rid, entry in self.archivar._room_map.rooms.items():
entry.catch_all = (rid == room_id)
# Persistieren
from .archivar.room_map import RoomMap
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
self.archivar._room_map.reload()
def _is_user_operator(self, username: str) -> bool:
"""Prüft, ob der Benutzer der Operator ist.
Args:
username: Der zu prüfende Benutzername
Returns:
True wenn der Benutzer der Operator ist, sonst False
"""
return username.lower() == "andreas"
async def _download_and_inline_files(self, text: str) -> str:
"""Download files referenced as [FILE] markers and inline their content."""
import re
_file_re = re.compile(
r'\[FILE\]\s+(?P<name>[^\n]+?)\s+\((?P<type>[^)]+)\)\n'
r'Download:\s+\S+/file-upload/(?P<fid>[^/]+)/(?P<fname>\S+)'
)
matches = list(_file_re.finditer(text))
if not matches:
return text
for m in matches:
fid = m.group("fid")
fname = m.group("fname")
content = self.rest.download_file(fid, fname)
if content:
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
text += block
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
return text
async def disconnect(self) -> None:
self._mark_disconnected()
self._shutdown_event.set()
if self._status_timer:
self._status_timer.cancel()
if self._listen_task and not self._listen_task.done():
self._listen_task.cancel()
try:
await self._listen_task
except asyncio.CancelledError:
pass
if self.ddp:
self.ddp.disconnect()
self.ddp = None
logger.info("[rocketchat] Disconnected")
async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None) -> SendResult:
if not self.rest.auth_token:
return SendResult(success=False, error="Not authenticated")
# ── Virtual → Real Room Translation ─────────────────────────
# chat_id from Hermes session is virtual (e.g. "user:alice").
# We must resolve it to a real Rocket.Chat room_id for REST API.
real_room_id = chat_id
if chat_id.startswith("user:"):
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
thematic_target = _THEMATIC_TARGET_ROOM.get()
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
else:
# Priority 1: ContextVar from the message that triggered this turn
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
else:
# Priority 2: 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"):
from . import _TEMPLATE_MAP, _build_custom_buttons
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)
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]
# ── Clarify-Queue: remember pending button question ──
if metadata and metadata.get("template") and attachments:
_tmpl = metadata.get("template")
_qid = metadata.get("question_id", "")
_expected = []
if _tmpl == "yes_no":
_expected = ["ja", "nein", "yes", "no"]
elif _tmpl == "confirm_cancel":
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
elif _tmpl == "ok":
_expected = ["ok", "okay", "verstanden", "alles klar"]
elif _tmpl == "custom" and metadata.get("custom_buttons"):
_expected = [b.lower() for b in metadata["custom_buttons"]]
self._pending_clarifies[real_room_id] = {
"question_id": _qid,
"template": _tmpl,
"expected": _expected,
"timestamp": time.time(),
"original_text": content,
}
success = self.rest.post_message(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)
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
return SendResult(success=False, error="chat.postMessage failed")
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
"""Fallback method to find a room for a user when direct mapping fails.
Args:
chat_id: Virtual chat_id like "user:username"
Returns:
Room ID if found, None otherwise
"""
if not chat_id.startswith("user:"):
return None
target_username = chat_id.split(":", 1)[1].lower()
# Try to find any DM room involving this user
for room_id, room_info in self._room_info.items():
if room_info.get("type") == "d":
# Try to get room details with members
try:
room_detail = self.rest._request("GET", f"/api/v1/rooms.info?roomId={room_id}", headers={
"X-Auth-Token": self.rest.auth_token,
"X-User-Id": self.rest.user_id,
})
if room_detail and room_detail.get("success"):
room_data = room_detail.get("room", {})
usernames = room_data.get("usernames", [])
if target_username in [u.lower() for u in usernames]:
return room_id
except Exception as e:
logger.debug("[rocketchat] Could not get room info for %s: %s", room_id, e)
# Last resort: return first available room (better than nothing)
if self._subscribed_rooms:
first_room = next(iter(self._subscribed_rooms))
logger.warning("[rocketchat] Using first available room %s as ultimate fallback for %s",
first_room, chat_id)
return first_room
return None
async def send_clarify(
self,
chat_id: str,
question: str,
choices: Optional[list],
clarify_id: str,
session_key: str,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Render a clarify prompt with Rocket.Chat action buttons.
Multi-choice mode (``choices`` non-empty): renders one button per
option plus a final "✏️ Other (type answer)" button. Picking the
"Other" button flips the entry into text-capture mode so the next
message becomes the response.
Open-ended mode (``choices`` empty): renders the question as plain
text — no buttons. The next message in the session is captured by
the gateway's text-intercept and resolves the clarify.
"""
# Fallback to text-based clarify if choices are empty
if not choices:
return await super().send_clarify(
chat_id=chat_id,
question=question,
choices=choices,
clarify_id=clarify_id,
session_key=session_key,
metadata=metadata,
)
if not self.rest.auth_token:
return SendResult(success=False, error="Not authenticated")
# ── Virtual → Real Room Translation ─────────────────────────
# chat_id from Hermes session is virtual (e.g. "user:alice").
# We must resolve it to a real Rocket.Chat room_id for REST API.
real_room_id = chat_id
if chat_id.startswith("user:"):
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
thematic_target = _THEMATIC_TARGET_ROOM.get()
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
else:
# Priority 1: ContextVar from the message that triggered this turn
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
else:
# Priority 2: proactive message — use most recent room for this user
rooms = self._user_rooms.get(chat_id, [])
if rooms:
real_room_id = rooms[-1] # last room user was active in
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
else:
# Fallback: try to find any room with recent activity involving this user
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
fallback_room = self._find_fallback_room_for_user(chat_id)
if fallback_room:
real_room_id = fallback_room
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
else:
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
# Render full option text in the message body so users
# can read long choices that would be truncated in buttons.
# Buttons keep short numeric labels (1, 2, …, Other).
text = f"❓ {question}"
option_lines = "\n".join(
f"{i + 1}. {choice}"
for i, choice in enumerate(choices)
)
text += f"\n\n{option_lines}"
# Build buttons with short labels to avoid truncation
from . import _build_custom_buttons
button_labels = [str(i + 1) for i in range(len(choices))]
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
# Add "Other" button with special handling
buttons.append({
"type": "button",
"text": "✏️ Other",
"msg": f"CLARIFY:{clarify_id}:other",
"msg_in_chat_window": True,
"style": "default",
})
# Create attachment with buttons
attachments = [{
"color": "#1d74f5",
"title": "Please choose an option:",
"actions": buttons,
}]
# Send message with buttons
success = self.rest.post_message(real_room_id, text, attachments=attachments)
if success:
# Store clarify state for gateway identification
self._clarify_state = getattr(self, '_clarify_state', {})
self._clarify_state[clarify_id] = session_key
# For "Other" button, we need to enable text capture mode
# This is done by calling mark_awaiting_text when the user clicks "Other"
# The actual implementation will be in the message handling logic
# Mark room for button response handling (no Archivar routing)
self._rooms_with_pending_questions.add(real_room_id)
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
else:
# Fallback to text-based clarify if REST call fails
logger.warning("[rocketchat] Failed to send clarify with buttons, falling back to text")
return await super().send_clarify(
chat_id=chat_id,
question=question,
choices=choices,
clarify_id=clarify_id,
session_key=session_key,
metadata=metadata,
)
async def send_typing(self, chat_id: str, metadata=None) -> None:
pass
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
info = self._room_info.get(chat_id, {})
return {"name": info.get("name", chat_id), "type": "group" if info.get("type") in ("c", "p") else "dm"}
async def _listen_loop(self):
loop = asyncio.get_running_loop()
health_check_counter = 0
while self._running and not self._shutdown_event.is_set():
try:
msg_obj = await loop.run_in_executor(None, self._ddp_queue_get, 1.0)
if msg_obj is None:
health_check_counter += 1
# Every 60 seconds (60 x 1.0s timeouts): check for silent death
if health_check_counter >= 60:
health_check_counter = 0
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 self._auth_token and self.ddp.reconnect_and_restore(self._auth_token):
logger.info("[rocketchat] Recovered from silent death")
else:
logger.error("[rocketchat] Silent death recovery failed")
await asyncio.sleep(10)
continue
if self.ddp and not self.ddp.connected:
logger.warning("[rocketchat] DDP disconnected, reconnecting...")
if self._auth_token and self.ddp.reconnect_and_restore(self._auth_token):
logger.info("[rocketchat] Reconnected")
else:
await asyncio.sleep(5)
continue
health_check_counter = 0 # Reset on any message
await self._process_incoming(msg_obj)
except asyncio.CancelledError:
break
except Exception as e:
logger.error("[rocketchat] Listener error: %s", e)
await asyncio.sleep(1)
def _ddp_queue_get(self, timeout: float):
if not self.ddp:
return None
try:
return self.ddp._msg_queue.get(timeout=timeout)
except queue.Empty:
return None