1c53a9fe07
- build_help_text: Wenn Hilfe-Text > 4000 Zeichen, wird room_map_summary durch Platzhalter ersetzt. Verhindert HTTP 400 bei Rocket.Chat (Payload-Limit ~5000 Zeichen, ::hilfe mit 5 Räumen war 4571 Zeichen). - RoomMap.save: Refuse-Guard prüft vor dem Schreiben, ob die existierende Disk-Datei mehr Räume enthält als die In-Memory-Map. Verweigert das Schreiben mit Warning wenn Disk > In-Memory. Verhindert Datenverlust beim Multiroom-Toggle (false→true schrieb leere Map). - Tests: test_build_help_text_length_limit (max 4000 Zeichen), test_build_help_text_keeps_summary_when_short, TestRoomMapSaveRefuseGuard (4 Tests: refuse, allow-more, allow-equal, allow-no-disk). Closes: Rainers Review P1-Fixes 1+2+3
474 lines
17 KiB
Python
474 lines
17 KiB
Python
"""
|
|
R5: Inline-Befehlserkennung — Command-Registry und Help-Text-Generator.
|
|
|
|
Stellt die ::-Befehlssyntax für erfahrene Nutzer bereit:
|
|
::sethome — Setzt den Heimatraum (Alternative zu /sethome)
|
|
::setfakt — Ändert den FAKT-Speicherort
|
|
::hilfe — Zeigt Hilfeseite mit allen Befehlen
|
|
::status — Zeigt aktuellen Plugin-Status
|
|
::reset — Alternative zu /reset
|
|
|
|
Die Hilfeseite wird auch durch natürliche Sprache ausgelöst:
|
|
'Ich brauche Hilfe zum Rocketchat Plugin'
|
|
'Was kannst du?'
|
|
'Hilfe'
|
|
|
|
Konvention für Command-Handler:
|
|
Handler, die selbst posten (z.B. Buttons, Attachments), MÜSSEN einen
|
|
leeren String ("") zurückgeben. _handle_inline_command sendet den
|
|
Return-Wert sonst doppelt als Textnachricht.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Dict, List, Optional, Callable, Awaitable, Any
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ── Natural language help triggers ──────────────────────────────────────
|
|
# Diese Sätze lösen die Hilfeseite aus (case-insensitive, stripped).
|
|
NATURAL_HELP_TRIGGERS: List[str] = [
|
|
"hilfe",
|
|
"help",
|
|
"was kannst du",
|
|
"was kannst du?",
|
|
"ich brauche hilfe zum rocketchat plugin",
|
|
"ich brauche hilfe zum rocketchat-plugin",
|
|
"rocketchat hilfe",
|
|
"rocketchat help",
|
|
"plugin hilfe",
|
|
"plugin help",
|
|
"was kann das plugin",
|
|
"was kann das plugin?",
|
|
"welche befehle",
|
|
"welche befehle?",
|
|
"welche befehle gibt es",
|
|
"welche befehle gibt es?",
|
|
"zeige befehle",
|
|
"zeige hilfe",
|
|
"commands",
|
|
"was geht",
|
|
"was geht?",
|
|
]
|
|
|
|
|
|
def is_natural_help_request(text: str) -> bool:
|
|
"""Prüft ob der Text eine natürliche Hilfeseiten-Anfrage ist.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext (wird gestripped und lowercased).
|
|
|
|
Returns:
|
|
True wenn der Text eine Hilfeseiten-Anfrage ist.
|
|
"""
|
|
stripped = text.strip().lower()
|
|
# Exakte Matches
|
|
if stripped in NATURAL_HELP_TRIGGERS:
|
|
return True
|
|
# Enthält-Matches für längere Sätze
|
|
for trigger in NATURAL_HELP_TRIGGERS:
|
|
if len(trigger) > 10 and trigger in stripped:
|
|
return True
|
|
return False
|
|
|
|
|
|
# ── UX-8: Command Question Detection ────────────────────────────────────
|
|
|
|
# Muster für Fragen über ::-Befehle: "Was macht ::curate?", "Wie geht ::onboarding?"
|
|
# Diese werden VOR dem LLM-Dispatch abgefangen, damit der Agent nicht halluziniert.
|
|
_COMMAND_QUESTION_PATTERNS = [
|
|
"was macht ::",
|
|
"was ist ::",
|
|
"wie geht ::",
|
|
"wie funktioniert ::",
|
|
"erkläre ::",
|
|
"was bedeutet ::",
|
|
"wofür ist ::",
|
|
"was kann ::",
|
|
"hilfe zu ::",
|
|
"help ::",
|
|
"what does ::",
|
|
"how to ::",
|
|
]
|
|
|
|
|
|
def extract_command_question(text: str) -> Optional[str]:
|
|
"""Extrahiert den ::-Befehl aus einer Frage wie 'Was macht ::curate?'.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext.
|
|
|
|
Returns:
|
|
Den Befehlsnamen (ohne ::) wenn eine Command-Frage erkannt wurde,
|
|
sonst None.
|
|
"""
|
|
stripped = text.strip().lower()
|
|
for pattern in _COMMAND_QUESTION_PATTERNS:
|
|
if pattern in stripped:
|
|
# Extrahiere den Befehl nach dem Pattern
|
|
idx = stripped.find(pattern) + len(pattern)
|
|
rest = stripped[idx:].strip()
|
|
# Nimm das erste Wort (den Befehl)
|
|
cmd = rest.split()[0] if rest else ""
|
|
# Entferne Satzzeichen
|
|
cmd = cmd.rstrip("?!.,;:")
|
|
if cmd:
|
|
return cmd
|
|
return None
|
|
|
|
|
|
def build_command_help(registry: InlineCommandRegistry, name: str) -> Optional[str]:
|
|
"""Baut einen Hilfetext für einen einzelnen ::-Befehl.
|
|
|
|
Args:
|
|
registry: Die InlineCommandRegistry.
|
|
name: Der Befehlsname (ohne ::).
|
|
|
|
Returns:
|
|
Formatierter Hilfetext oder None wenn der Befehl nicht existiert.
|
|
"""
|
|
cmd = registry._commands.get(name)
|
|
if cmd is None:
|
|
return None
|
|
|
|
lines = [
|
|
f"## `::{name}`",
|
|
"",
|
|
f"**{cmd['help_text']}**",
|
|
"",
|
|
]
|
|
if cmd.get("description"):
|
|
lines.append(cmd["description"])
|
|
lines.append("")
|
|
|
|
subcmds = cmd.get("subcommands", {})
|
|
if subcmds:
|
|
lines.append("**Subcommands:**")
|
|
for sub_name, sub_desc in subcmds.items():
|
|
lines.append(f"- `::{name} {sub_name}` — {sub_desc}")
|
|
lines.append("")
|
|
|
|
lines.append(f"💡 `::hilfe` zeigt alle Befehle an.")
|
|
return "\n".join(lines)
|
|
|
|
|
|
# ── Inline-Command Registry ────────────────────────────────────────────
|
|
|
|
# Command-Handler-Signatur: async def handler(room_id: str, args: str) -> str
|
|
# Gibt den Antworttext zurück, der im Raum gepostet wird.
|
|
CommandHandler = Callable[[str, str], Awaitable[str]]
|
|
|
|
|
|
class InlineCommandRegistry:
|
|
"""Registry für ::-Befehle mit Handler und Help-Text."""
|
|
|
|
def __init__(self):
|
|
self._commands: Dict[str, Dict[str, Any]] = {}
|
|
|
|
def register(
|
|
self,
|
|
name: str,
|
|
handler: CommandHandler,
|
|
help_text: str,
|
|
description: str = "",
|
|
category: str = "Plugin",
|
|
subcommands: Optional[Dict[str, str]] = None,
|
|
) -> None:
|
|
"""Registriert einen ::-Befehl.
|
|
|
|
Args:
|
|
name: Befehlsname ohne :: (z.B. 'sethome').
|
|
handler: Async callable (room_id, args) -> Antworttext.
|
|
help_text: Kurzer Hilfetext (eine Zeile).
|
|
description: Ausführliche Beschreibung.
|
|
category: Kategorie für die Hilfeseite.
|
|
subcommands: Optionales Dict {subcmd: beschreibung} für Befehle
|
|
mit Subcommands (z.B. {'start': 'Startet...', ...}).
|
|
"""
|
|
self._commands[name] = {
|
|
"handler": handler,
|
|
"help_text": help_text,
|
|
"description": description,
|
|
"category": category,
|
|
"subcommands": subcommands or {},
|
|
}
|
|
|
|
def get_handler(self, name: str) -> Optional[CommandHandler]:
|
|
"""Gibt den Handler für einen Befehl zurück."""
|
|
cmd = self._commands.get(name)
|
|
return cmd["handler"] if cmd else None
|
|
|
|
def get_commands(self) -> Dict[str, Dict[str, Any]]:
|
|
"""Gibt alle registrierten Befehle zurück."""
|
|
return dict(self._commands)
|
|
|
|
def is_registered(self, name: str) -> bool:
|
|
"""Prüft ob ein Befehl registriert ist."""
|
|
return name in self._commands
|
|
|
|
|
|
# ── Help-Text-Generator ─────────────────────────────────────────────────
|
|
|
|
|
|
def build_help_text(
|
|
registry: InlineCommandRegistry,
|
|
room_map_summary: str = "",
|
|
presence_enabled: Optional[bool] = None,
|
|
current_status: str = "online",
|
|
) -> str:
|
|
"""Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen.
|
|
|
|
Args:
|
|
registry: Die InlineCommandRegistry mit allen registrierten Befehlen.
|
|
room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil.
|
|
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht verfügbar).
|
|
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
|
|
|
Returns:
|
|
Formatierte Hilfeseite als Markdown-String.
|
|
"""
|
|
lines = [
|
|
"## 🤖 Rocket.Chat Plugin — Hilfe",
|
|
"",
|
|
"Diese Befehle erkennst du am `::` am Satzanfang:",
|
|
"",
|
|
]
|
|
|
|
# ── Sektion 0: Core-Befehle (Hermes Core, immer verfügbar) ────────
|
|
lines.append("### ⚙️ Core-Befehle")
|
|
lines.append("")
|
|
lines.append(
|
|
"Diese Befehle werden direkt vom Hermes-Agenten verarbeitet "
|
|
"und sind immer verfügbar — unabhängig vom Plugin:"
|
|
)
|
|
lines.append("")
|
|
lines.append(
|
|
"- **continue** — Agent fortsetzen nach leerer Antwort / Stream-Drop. "
|
|
"Einfach `continue` in den Chat schreiben, der Agent macht weiter."
|
|
)
|
|
lines.append(
|
|
"- **/reset** — Session zurücksetzen. "
|
|
"Löscht den gesamten Chat-Kontext und startet eine frische Session. "
|
|
"In Rocket.Chat als `::reset` nutzbar."
|
|
)
|
|
lines.append(
|
|
"- **/compress** — Kontext manuell komprimieren. "
|
|
"Verdichtet den Chat-Verlauf, um Token zu sparen und die "
|
|
"Antwortqualität bei langen Sessions zu erhalten. "
|
|
"In Rocket.Chat als `::compress` nutzbar."
|
|
)
|
|
lines.append("")
|
|
|
|
# ::-Befehle nach Kategorie gruppieren
|
|
by_category: Dict[str, List[Dict[str, Any]]] = {}
|
|
for name, cmd in registry.get_commands().items():
|
|
cat = cmd.get("category", "Plugin")
|
|
by_category.setdefault(cat, []).append({"name": name, **cmd})
|
|
|
|
# ── Sektion 1: Standard-Hermes-Befehle (:: als Variante) ──────────
|
|
standard_categories = {"Standard", "Gateway", "Session", "Info"}
|
|
standard_cmds = []
|
|
for cat in sorted(by_category):
|
|
if cat in standard_categories:
|
|
standard_cmds.extend(by_category[cat])
|
|
|
|
if standard_cmds:
|
|
lines.append("### 🔷 Standard-Hermes-Befehle (:: als Variante)")
|
|
lines.append("")
|
|
lines.append("Diese Befehle sind die ::-Entsprechungen der Hermes-Slash-Commands")
|
|
lines.append("(`/sethome`, `/reset`, `/busy`, …). Da Rocket.Chat kein `/` unterstützt,")
|
|
lines.append("wurden sie auf `::` umgestellt:")
|
|
lines.append("")
|
|
for cmd in standard_cmds:
|
|
lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
|
subcmds = cmd.get('subcommands', {})
|
|
for sub_name, sub_desc in subcmds.items():
|
|
lines.append(f" - `::{cmd['name']} {sub_name}` — {sub_desc}")
|
|
lines.append("")
|
|
|
|
# ── Sektion 2: RC-Plugin-spezifische Befehle ──────────────────────
|
|
rc_categories = {"Raum", "Konfiguration", "Hilfe", "Plugin"}
|
|
rc_cmds = []
|
|
for cat in sorted(by_category):
|
|
if cat in rc_categories:
|
|
rc_cmds.extend(by_category[cat])
|
|
|
|
if rc_cmds:
|
|
lines.append("### 🔶 RC-Plugin-spezifische Befehle")
|
|
lines.append("")
|
|
lines.append("Diese Befehle steuern das Rocket.Chat-Plugin direkt:")
|
|
lines.append("")
|
|
for cmd in rc_cmds:
|
|
lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
|
subcmds = cmd.get('subcommands', {})
|
|
for sub_name, sub_desc in subcmds.items():
|
|
lines.append(f" - `::{cmd['name']} {sub_name}` — {sub_desc}")
|
|
lines.append("")
|
|
|
|
# ── Sektion 3: Natürliche Sprach-Befehle ──────────────────────────
|
|
lines.append("### 🗣️ Natürliche Sprach-Befehle")
|
|
lines.append("")
|
|
lines.append("Du kannst auch in natürlicher Sprache mit mir sprechen:")
|
|
lines.append("")
|
|
lines.append("- **Raum wechseln:** 'Lass uns in #Projektraum wechseln'")
|
|
lines.append("- **Thema verschieben:** 'Das gehört in den Plugin-Raum'")
|
|
lines.append("- **Hilfe anfordern:** 'Ich brauche Hilfe zum Rocketchat Plugin'")
|
|
lines.append("- **Status abfragen:** '::status' oder 'Wie ist der Status?'")
|
|
lines.append("- **Auftrag erteilen:** 'Mach mal...', 'Teste...', 'Fix...'")
|
|
lines.append("")
|
|
|
|
# ── Sektion 4: Plugin-Status ──────────────────────────────────────
|
|
lines.append("### 📋 Plugin-Status")
|
|
lines.append("")
|
|
|
|
# P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv
|
|
if presence_enabled:
|
|
status_emoji = {
|
|
"online": "🟢 online (idle, verfügbar)",
|
|
"away": "🟡 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
|
|
"busy": "🔴 busy (verarbeitet Nachricht)",
|
|
}
|
|
lines.append("### 🚦 Status-Farben")
|
|
lines.append("")
|
|
lines.append(
|
|
"Der Bot zeigt seinen Status nach dem **Flughafen-Prinzip** an: "
|
|
"wie eine Ampel signalisiert er, ob er bereit (grün), beschäftigt "
|
|
"(rot) oder im Hintergrund aktiv (gelb) ist."
|
|
)
|
|
lines.append("")
|
|
for status, label in status_emoji.items():
|
|
marker = " ← aktuell" if status == current_status else ""
|
|
lines.append(f"- {label}{marker}")
|
|
lines.append("")
|
|
|
|
if room_map_summary:
|
|
lines.append(room_map_summary)
|
|
else:
|
|
lines.append("Keine Raum-Map geladen.")
|
|
|
|
lines.append("")
|
|
lines.append("---")
|
|
lines.append("💡 **Tipp:** `::hilfe` zeigt diese Seite jederzeit an.")
|
|
lines.append("")
|
|
lines.append(
|
|
"**Moderatorenrechte:** Im Multi-Room-Modus verschiebt der Agent "
|
|
"Nachrichten. Damit das sauber funktioniert, sollte der Bot "
|
|
"Moderatorenrechte in den Themenräumen haben."
|
|
)
|
|
|
|
result = "\n".join(lines)
|
|
|
|
# P1-Fix: Rocket.Chat hat ein Payload-Limit von ~5000 Zeichen.
|
|
# Wenn der Hilfe-Text > 4000 Zeichen ist, lasse die room_map_summary
|
|
# weg und ersetze sie durch einen kurzen Hinweis.
|
|
MAX_HELP_LENGTH = 4000
|
|
if len(result) > MAX_HELP_LENGTH and room_map_summary:
|
|
# Finde den Index der room_map_summary in lines und ersetze sie
|
|
for i, line in enumerate(lines):
|
|
if line == room_map_summary:
|
|
lines[i] = (
|
|
"Raum-Map-Übersicht aus Platzgründen weggelassen "
|
|
"(> 4000 Zeichen). `::status` für Details."
|
|
)
|
|
break
|
|
result = "\n".join(lines)
|
|
|
|
return result
|
|
|
|
|
|
def build_status_text(
|
|
room_count: int = 0,
|
|
archivar_active: bool = False,
|
|
butler_mode: str = "unknown",
|
|
onboarding_active: bool = False,
|
|
room_map_summary: str = "",
|
|
presence_enabled: Optional[bool] = None,
|
|
current_status: str = "online",
|
|
pulse_active: bool = False,
|
|
) -> str:
|
|
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
|
|
|
Args:
|
|
room_count: Anzahl der Räume in der Map.
|
|
archivar_active: Ob der Archivar aktiv ist.
|
|
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
|
|
onboarding_active: Ob Onboarding gerade läuft.
|
|
room_map_summary: Raum-Map-Übersicht.
|
|
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht anzeigen).
|
|
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
|
pulse_active: Ob der PulseController gerade pulsiert.
|
|
|
|
Returns:
|
|
Formatierte Status-Seite.
|
|
"""
|
|
butler_labels = {
|
|
"cognitive": "🤖 Kognitiv",
|
|
"strict": "📋 Klassisch",
|
|
"off": "🔇 Aus",
|
|
}
|
|
|
|
lines = [
|
|
"## 📊 Plugin-Status",
|
|
"",
|
|
f"- **Räume in Map:** {room_count}",
|
|
f"- **Archivar:** {'✅ Aktiv' if archivar_active else '❌ Inaktiv'}",
|
|
f"- **Butler-Modus:** {butler_labels.get(butler_mode, butler_mode)}",
|
|
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
|
|
]
|
|
|
|
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
|
|
if presence_enabled is not None:
|
|
status_labels = {
|
|
"online": "🟢 online (idle, verfügbar)",
|
|
"away": "🟡 away (Hintergrund-Task aktiv)",
|
|
"busy": "🔴 busy (verarbeitet Nachricht)",
|
|
}
|
|
pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv"
|
|
if presence_enabled:
|
|
lines.append(f"- **PresenceEngine:** ✅ Aktiv")
|
|
lines.append(f"- **Aktueller Status:** {status_labels.get(current_status, current_status)}")
|
|
lines.append(f"- **Pulse:** {pulse_label}")
|
|
else:
|
|
lines.append(f"- **PresenceEngine:** ❌ Inaktiv")
|
|
|
|
if room_map_summary:
|
|
lines.append("")
|
|
lines.append(room_map_summary)
|
|
|
|
lines.append("")
|
|
lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
# ── Inline-Command-Parser ───────────────────────────────────────────────
|
|
|
|
|
|
def parse_inline_command(text: str) -> Optional[tuple]:
|
|
"""Parst einen ::-Befehl aus dem Nachrichtentext.
|
|
|
|
Args:
|
|
text: Der Nachrichtentext.
|
|
|
|
Returns:
|
|
(command_name, args) wenn ein ::-Befehl erkannt wurde, sonst None.
|
|
command_name ist der Befehl ohne :: (z.B. 'sethome').
|
|
args ist der Rest des Texts nach dem Befehl (kann leer sein).
|
|
"""
|
|
stripped = text.strip()
|
|
if not stripped.startswith("::"):
|
|
return None
|
|
|
|
# Extrahiere Befehl und Argumente
|
|
# Format: ::befehl [args]
|
|
rest = stripped[2:] # Entferne ::
|
|
if not rest:
|
|
return None
|
|
|
|
parts = rest.split(None, 1)
|
|
command = parts[0].lower()
|
|
args = parts[1] if len(parts) > 1 else ""
|
|
|
|
return (command, args)
|