f74d206657
P1b-Fix: Der bestehende P1-Fix (room_map_summary-Kürzung) griff nur, wenn room_map_summary gesetzt war. Durch Subcommand-Ergänzungen (mode proactive, mode silent_collector, Routing-Modi-Hinweis) ist die Hilfe-Seite auch OHNE room_map_summary über das ~5000-Zeichen-Limit gewachsen → HTTP 400 Bad Request. build_help_text() baut Sektionen jetzt als separate Listen und kürzt progressiv, wenn result > 4500 Zeichen: Stufe 1: Natürliche Sprach-Befehle auf eine Zeile Stufe 2: Standard-Hermes-Befehle auf kompakte Liste (ohne Subcommands) Stufe 3: RC-Plugin-Subcommand-Details weglassen (Befehle bleiben) Core-Befehle, RC-Plugin-Befehle, Status-Farben und Plugin-Status bleiben erhalten. P1-Fix ersetzt room_map_summary jetzt direkt in status_lines, damit die Kürzung auch bei Stufe 1-3 erhalten bleibt. Test: test_build_help_text_length_with_all_commands registriert alle realen Befehle inkl. Subcommands und prüft < 4500 Zeichen (mit und ohne room_map_summary).
701 lines
26 KiB
Python
701 lines
26 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] = [
|
||
# Deutsch
|
||
"hilfe",
|
||
"ich brauche hilfe",
|
||
"hilf mir",
|
||
"was kannst du",
|
||
"was kannst du?",
|
||
"was kannst du alles",
|
||
"was kannst du alles?",
|
||
"zeig mir die befehle",
|
||
"zeige befehle",
|
||
"zeige hilfe",
|
||
"welche befehle",
|
||
"welche befehle?",
|
||
"welche befehle gibt es",
|
||
"welche befehle gibt es?",
|
||
"ich brauche hilfe zum rocketchat plugin",
|
||
"ich brauche hilfe zum rocketchat-plugin",
|
||
"rocketchat hilfe",
|
||
"plugin hilfe",
|
||
"was kann das plugin",
|
||
"was kann das plugin?",
|
||
"was geht",
|
||
"was geht?",
|
||
# Englisch
|
||
"help",
|
||
"i need help",
|
||
"help me",
|
||
"what can you do",
|
||
"what can you do?",
|
||
"show me the commands",
|
||
"rocketchat help",
|
||
"plugin help",
|
||
"commands",
|
||
]
|
||
|
||
|
||
def is_natural_help_request(text: str) -> bool:
|
||
"""Prüft ob der Text eine natürliche Hilfeseiten-Anfrage ist.
|
||
|
||
B7: Strikte Erkennung — nur exakte Matches oder sehr kurze
|
||
Sätze (≤30 Zeichen), die mit einem Trigger beginnen.
|
||
Verhindert False-Positives wie "ich brauche hilfe bei einem bug".
|
||
|
||
Args:
|
||
text: Der Nachrichtentext (wird gestripped und lowercased).
|
||
|
||
Returns:
|
||
True wenn der Text eine Hilfeseiten-Anfrage ist.
|
||
"""
|
||
stripped = text.strip().lower()
|
||
|
||
# 1. Exakter Match gegen die Trigger-Liste
|
||
if stripped in NATURAL_HELP_TRIGGERS:
|
||
return True
|
||
|
||
# 2. Kurzer Satz (≤30 Zeichen), der mit einem Trigger beginnt
|
||
# und danach nur minimale Variation hat (z.B. "hilfe bitte")
|
||
if len(stripped) <= 30:
|
||
for trigger in NATURAL_HELP_TRIGGERS:
|
||
if stripped.startswith(trigger):
|
||
remainder = stripped[len(trigger):].strip()
|
||
# Nur matchen wenn der Rest kurz ist (≤20 Zeichen)
|
||
# und keine echte Frage enthält (kein "bei", "mit", "für")
|
||
if len(remainder) <= 20:
|
||
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",
|
||
plugin_version: str = "",
|
||
) -> 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').
|
||
plugin_version: Plugin-Version (z.B. "9.2 (1d31d2c)").
|
||
|
||
Returns:
|
||
Formatierte Hilfeseite als Markdown-String.
|
||
"""
|
||
header = [
|
||
"## 🤖 Rocket.Chat Plugin — Hilfe",
|
||
"",
|
||
"👋 Ich bin Bernd, dein Hermes-Agent im Rocket.Chat. Hier sind meine Befehle:",
|
||
"",
|
||
]
|
||
|
||
# V9.2: Plugin-Version anzeigen
|
||
if plugin_version:
|
||
header.append(f"**Plugin-Version:** {plugin_version}")
|
||
header.append("")
|
||
|
||
header.append("Diese Befehle erkennst du am `::` am Satzanfang:")
|
||
header.append("")
|
||
|
||
# ── Sektion 0: Core-Befehle (Hermes Core, immer verfügbar) ────────
|
||
core_lines = [
|
||
"### ⚙️ Core-Befehle",
|
||
"",
|
||
"Diese Befehle werden direkt vom Hermes-Agenten verarbeitet "
|
||
"und sind immer verfügbar — unabhängig vom Plugin:",
|
||
"",
|
||
"- **continue** — Agent fortsetzen nach leerer Antwort / Stream-Drop. "
|
||
"Einfach `continue` in den Chat schreiben, der Agent macht weiter.",
|
||
"- **/reset** — Session zurücksetzen. "
|
||
"Löscht den gesamten Chat-Kontext und startet eine frische Session. "
|
||
"In Rocket.Chat als `::reset` nutzbar.",
|
||
"- **/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.",
|
||
"",
|
||
]
|
||
|
||
# ::-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])
|
||
|
||
standard_lines: List[str] = []
|
||
if standard_cmds:
|
||
standard_lines.append("### 🔷 Standard-Hermes-Befehle (:: als Variante)")
|
||
standard_lines.append("")
|
||
standard_lines.append("Diese Befehle sind die ::-Entsprechungen der Hermes-Slash-Commands")
|
||
standard_lines.append("(`/sethome`, `/reset`, `/busy`, …). Da Rocket.Chat kein `/` unterstützt,")
|
||
standard_lines.append("wurden sie auf `::` umgestellt:")
|
||
standard_lines.append("")
|
||
for cmd in standard_cmds:
|
||
standard_lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
||
subcmds = cmd.get('subcommands', {})
|
||
for sub_name, sub_desc in subcmds.items():
|
||
standard_lines.append(f" - `::{cmd['name']} {sub_name}` — {sub_desc}")
|
||
standard_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])
|
||
|
||
rc_lines: List[str] = []
|
||
if rc_cmds:
|
||
rc_lines.append("### 🔶 RC-Plugin-spezifische Befehle")
|
||
rc_lines.append("")
|
||
rc_lines.append("Diese Befehle steuern das Rocket.Chat-Plugin direkt:")
|
||
rc_lines.append("")
|
||
for cmd in rc_cmds:
|
||
rc_lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
||
subcmds = cmd.get('subcommands', {})
|
||
for sub_name, sub_desc in subcmds.items():
|
||
rc_lines.append(f" - `::{cmd['name']} {sub_name}` — {sub_desc}")
|
||
rc_lines.append("")
|
||
rc_lines.append(
|
||
"**Butler-Routing-Modus:** cognitive (Vorschlag+Bestätigung), "
|
||
"strict (automatisch), off (deaktiviert) — einstellbar über `::onboarding`"
|
||
)
|
||
rc_lines.append("")
|
||
|
||
# ── Sektion 3: Natürliche Sprach-Befehle ──────────────────────────
|
||
natural_lines = [
|
||
"### 🗣️ Natürliche Sprach-Befehle",
|
||
"",
|
||
"Du kannst auch in natürlicher Sprache mit mir sprechen:",
|
||
"",
|
||
"- **Raum wechseln:** 'Lass uns in #Projektraum wechseln'",
|
||
"- **Thema verschieben:** 'Das gehört in den Plugin-Raum'",
|
||
"- **Hilfe anfordern:** 'Ich brauche Hilfe zum Rocketchat Plugin'",
|
||
"- **Status abfragen:** '::status' oder 'Wie ist der Status?'",
|
||
"- **Auftrag erteilen:** 'Mach mal...', 'Teste...', 'Fix...'",
|
||
"",
|
||
]
|
||
|
||
# ── Sektion 4: Plugin-Status ──────────────────────────────────────
|
||
status_lines = [
|
||
"### 📋 Plugin-Status",
|
||
"",
|
||
]
|
||
|
||
# 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)",
|
||
}
|
||
status_lines.append("### 🚦 Status-Farben")
|
||
status_lines.append("")
|
||
status_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."
|
||
)
|
||
status_lines.append("")
|
||
for status, label in status_emoji.items():
|
||
marker = " ← aktuell" if status == current_status else ""
|
||
status_lines.append(f"- {label}{marker}")
|
||
status_lines.append("")
|
||
|
||
if room_map_summary:
|
||
status_lines.append(room_map_summary)
|
||
else:
|
||
status_lines.append("Keine Raum-Map geladen.")
|
||
|
||
footer = [
|
||
"",
|
||
"---",
|
||
"💡 **Tipp:** `::hilfe` zeigt diese Seite jederzeit an.",
|
||
"💡 Du kannst auch natürliche Sprache verwenden: 'Ich brauche Hilfe' zeigt diese Seite an.",
|
||
"",
|
||
"**Moderatorenrechte:** Im Multi-Room-Modus verschiebt der Agent "
|
||
"Nachrichten. Damit das sauber funktioniert, sollte der Bot "
|
||
"Moderatorenrechte in den Themenräumen haben.",
|
||
]
|
||
|
||
lines = header + core_lines + standard_lines + rc_lines + natural_lines + status_lines + footer
|
||
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. Die Ersetzung erfolgt
|
||
# direkt in status_lines, damit sie auch bei den P1b-Kürzungen
|
||
# (Stufe 1/2) erhalten bleibt.
|
||
MAX_HELP_LENGTH = 4000
|
||
if len(result) > MAX_HELP_LENGTH and room_map_summary:
|
||
for i, line in enumerate(status_lines):
|
||
if line == room_map_summary:
|
||
status_lines[i] = (
|
||
"Raum-Map-Übersicht aus Platzgründen weggelassen "
|
||
"(> 4000 Zeichen). `::status` für Details."
|
||
)
|
||
break
|
||
lines = header + core_lines + standard_lines + rc_lines + natural_lines + status_lines + footer
|
||
result = "\n".join(lines)
|
||
|
||
# P1b-Fix: Die Hilfe-Seite ist durch Subcommand-Ergänzungen auch OHNE
|
||
# room_map_summary über das Payload-Limit gewachsen. Der P1-Fix greift
|
||
# nur, wenn room_map_summary gesetzt ist. Zweiter Check: wenn der Text
|
||
# IMMER NOCH > 4500 Zeichen ist (nah am ~5000-Limit), kürze die
|
||
# entbehrlichsten Sektionen progressiv — zuerst die natürlichen
|
||
# Sprach-Befehle (Sektion 3), dann die Standard-Hermes-Befehle
|
||
# (Sektion 1) auf eine kompakte Liste. Core-Befehle, RC-Plugin-Befehle,
|
||
# Status-Farben und Plugin-Status bleiben erhalten.
|
||
MAX_SAFE_LENGTH = 4500
|
||
# Kompakte Varianten der entbehrlichsten Sektionen — werden nur bei
|
||
# Überschreitung des Limits verwendet.
|
||
compact_natural = [
|
||
"### 🗣️ Natürliche Sprach-Befehle",
|
||
"",
|
||
"Du kannst auch natürlich sprechen: 'Lass uns in #Raum wechseln', "
|
||
"'Das gehört in den Plugin-Raum', 'Ich brauche Hilfe', '::status'.",
|
||
"",
|
||
]
|
||
compact_standard = ["### 🔷 Standard-Hermes-Befehle (:: als Variante)", ""]
|
||
for cmd in standard_cmds:
|
||
compact_standard.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
||
compact_standard.append("")
|
||
compact_rc = ["### 🔶 RC-Plugin-spezifische Befehle", ""]
|
||
compact_rc.append("Diese Befehle steuern das Rocket.Chat-Plugin direkt:")
|
||
compact_rc.append("")
|
||
for cmd in rc_cmds:
|
||
compact_rc.append(f"- `::{cmd['name']}` — {cmd['help_text']}")
|
||
compact_rc.append("")
|
||
compact_rc.append(
|
||
"**Butler-Routing-Modus:** cognitive (Vorschlag+Bestätigung), "
|
||
"strict (automatisch), off (deaktiviert) — einstellbar über `::onboarding`"
|
||
)
|
||
compact_rc.append("")
|
||
|
||
if len(result) > MAX_SAFE_LENGTH:
|
||
# Stufe 1: Natürliche Sprach-Befehle auf eine Zeile kürzen
|
||
lines = (
|
||
header + core_lines + standard_lines + rc_lines
|
||
+ compact_natural + status_lines + footer
|
||
)
|
||
result = "\n".join(lines)
|
||
|
||
if len(result) > MAX_SAFE_LENGTH:
|
||
# Stufe 2: Standard-Hermes-Befehle auf kompakte Liste kürzen
|
||
# (nur Befehlsnamen, keine Subcommands, keine Einleitung)
|
||
lines = (
|
||
header + core_lines + compact_standard + rc_lines
|
||
+ compact_natural + status_lines + footer
|
||
)
|
||
result = "\n".join(lines)
|
||
|
||
if len(result) > MAX_SAFE_LENGTH:
|
||
# Stufe 3: RC-Plugin-Befehle behalten, aber Subcommand-Details
|
||
# weglassen (nur Befehlsname + help_text). Die Befehle selbst
|
||
# bleiben vollständig erhalten — nur die ausführlichen
|
||
# Subcommand-Aufzählungen (z.B. ::reasoning mit 9 Einträgen,
|
||
# ::onboarding mit 6) werden entfernt.
|
||
lines = (
|
||
header + core_lines + compact_standard + compact_rc
|
||
+ compact_natural + status_lines + footer
|
||
)
|
||
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,
|
||
plugin_version: str = "",
|
||
) -> 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.
|
||
plugin_version: Plugin-Version (z.B. "9.2 (1d31d2c)").
|
||
|
||
Returns:
|
||
Formatierte Status-Seite.
|
||
"""
|
||
butler_labels = {
|
||
"cognitive": "🤖 Kognitiv",
|
||
"strict": "📋 Klassisch",
|
||
"off": "🔇 Aus",
|
||
}
|
||
|
||
lines = [
|
||
"## 📊 Plugin-Status",
|
||
"",
|
||
]
|
||
|
||
# V9.2: Plugin-Version anzeigen
|
||
if plugin_version:
|
||
lines.append(f"**Plugin-Version:** {plugin_version}")
|
||
lines.append("")
|
||
|
||
lines.extend([
|
||
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")
|
||
|
||
result = "\n".join(lines)
|
||
|
||
# P2-Fix: Rocket.Chat Payload-Limit ~5000 Zeichen.
|
||
# Wenn der Status-Text > 5000 Zeichen ist, ersetze die room_map_summary
|
||
# durch eine kompakte Version (nur Raum-Name + Catch-All-Status).
|
||
MAX_STATUS_LENGTH = 5000
|
||
if len(result) > MAX_STATUS_LENGTH and room_map_summary:
|
||
# Baue kompakte Summary: nur Raum-Name + Catch-All-Marker
|
||
compact_lines = ["**Raum-Map (kompakt):**"]
|
||
for line in room_map_summary.splitlines():
|
||
stripped = line.strip()
|
||
if stripped.startswith(("Rocket.Chat", "Keywords", "Thema:")):
|
||
continue
|
||
# Zeilen wie " 1. Raumname (roomId) ★ CATCH-ALL — Thema: ..."
|
||
if stripped and stripped[0].isdigit():
|
||
# Extrahiere nur den Teil bis zum Catch-All-Marker
|
||
# Format: "1. Name (id) ★ CATCH-ALL — Thema: ..."
|
||
# oder: "1. Name (id) — Thema: ..."
|
||
if "★ CATCH-ALL" in stripped:
|
||
idx = stripped.index("★ CATCH-ALL") + len("★ CATCH-ALL")
|
||
compact_lines.append(stripped[:idx])
|
||
else:
|
||
# Nimm nur "1. Name (id)" — schneide bei " — " ab
|
||
dash_idx = stripped.find(" — ")
|
||
if dash_idx > 0:
|
||
compact_lines.append(stripped[:dash_idx])
|
||
else:
|
||
compact_lines.append(stripped)
|
||
compact_summary = "\n".join(compact_lines)
|
||
|
||
# Ersetze die room_map_summary in lines
|
||
for i, line in enumerate(lines):
|
||
if line == room_map_summary:
|
||
lines[i] = compact_summary
|
||
break
|
||
result = "\n".join(lines)
|
||
|
||
return result
|
||
|
||
|
||
# ── 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)
|
||
|
||
|
||
# ── V3 (Silent Collector): :: keywords review / status ───────────────────
|
||
|
||
|
||
def build_keywords_review_text(
|
||
pending_keywords: dict,
|
||
room_name: str = "",
|
||
) -> str:
|
||
"""V3: Baut den Review-Text für ``:: keywords review``.
|
||
|
||
Format pro Keyword: ``N. keyword (Häufigkeit) — Quelle → ✅/❌``.
|
||
Sortierung: nach Häufigkeit absteigend (bereits vom State sortiert).
|
||
|
||
Args:
|
||
pending_keywords: Dict keyword → {counter, first_seen, last_seen, source}
|
||
(bereits nach Häufigkeit sortiert).
|
||
room_name: Anzeigename des Raums (optional).
|
||
|
||
Returns:
|
||
Formatierter Review-Text.
|
||
"""
|
||
if not pending_keywords:
|
||
return "Keine Stichworte gesammelt für diesen Raum."
|
||
|
||
lines = ["🧠 **Gesammelte Stichworte**", ""]
|
||
if room_name:
|
||
lines.append(f"Raum: **{room_name}**")
|
||
lines.append("")
|
||
|
||
source_hint = {
|
||
"keywords_100": "aus deiner Nachricht erkannt",
|
||
"keywords_context": "Kontext-Begriff",
|
||
"ngram": "Begriffserkennung",
|
||
"llm_ner": "LLM-Vorschlag",
|
||
}
|
||
|
||
for i, (keyword, entry) in enumerate(pending_keywords.items(), start=1):
|
||
counter = int(entry.get("counter", 1))
|
||
source = entry.get("source", "")
|
||
source_label = source_hint.get(source, source or "unbekannt")
|
||
lines.append(
|
||
f"{i}. **{keyword}** ({counter}×) — {source_label} → ✅ / ❌"
|
||
)
|
||
|
||
lines.append("")
|
||
lines.append("Bewerte mit `:: keywords review ✅ <nr>` oder `:: keywords review ❌ <nr>`.")
|
||
lines.append("Oder `:: keywords review alle ✅` / `:: keywords review alle ❌`.")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def build_keywords_status_text(counts: dict, room_names: Optional[dict] = None) -> str:
|
||
"""V3: Baut den Status-Text für ``:: keywords status``.
|
||
|
||
Args:
|
||
counts: Dict room_id → Anzahl pending Keywords.
|
||
room_names: Optionales Dict room_id → Anzeigename.
|
||
|
||
Returns:
|
||
Formatierter Status-Text.
|
||
"""
|
||
room_names = room_names or {}
|
||
if not counts:
|
||
return "📋 Keine Stichworte gesammelt."
|
||
|
||
lines = ["📋 **Gesammelte Stichworte**", ""]
|
||
for room_id, count in sorted(counts.items(), key=lambda kv: -kv[1]):
|
||
name = room_names.get(room_id, room_id[:8])
|
||
lines.append(
|
||
f"- {count} Stichwort(e) gesammelt für **{name}**. "
|
||
f"`:: keywords review` zum Bewerten."
|
||
)
|
||
return "\n".join(lines)
|