fix: Bugfix-Runde — Sub-Phase Dispatch, Keywords Buttons, abort Task-Kill, Message Splitting, ::multiroom .env, ::approve/::deny, Button-Nummern, Command-Help
This commit is contained in:
+298
-9
@@ -1790,6 +1790,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# 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)
|
||||
# P0-1: Review-Flow-Phasen (review_room, review_butler, review_fakt)
|
||||
# müssen ebenfalls als Onboarding erkannt werden, damit
|
||||
# Button-Klicks (REVIEW_ROOM_EDIT::rid::edit etc.) nicht
|
||||
# als Freitext an den LLM-Agenten durchgereicht werden.
|
||||
_review_phases = {"review_room", "review_butler", "review_fakt"}
|
||||
is_onboarding = (
|
||||
(is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
|
||||
or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button
|
||||
@@ -1797,6 +1802,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
||||
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
||||
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
||||
or (is_operator_room and self._onboarding_state.get("phase") in _review_phases) # P0-1: Review-Flow Phasen
|
||||
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||||
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||||
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||||
@@ -2682,7 +2688,19 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_origin[:8] if _origin else "",
|
||||
_target[:8] if _target else "",
|
||||
)
|
||||
await ctx.run(self.handle_message, event)
|
||||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||
# handle_message() erzeugt intern asyncio.create_task (Drain-Task).
|
||||
# Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen.
|
||||
self._agent_dispatch_task = asyncio.create_task(
|
||||
ctx.run(self.handle_message, event)
|
||||
)
|
||||
try:
|
||||
await self._agent_dispatch_task
|
||||
except asyncio.CancelledError:
|
||||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||||
return
|
||||
finally:
|
||||
self._agent_dispatch_task = None
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] handle_message error: %s", e)
|
||||
# Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart
|
||||
@@ -2815,6 +2833,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"Subcommands: status, run.",
|
||||
category="Plugin",
|
||||
)
|
||||
# P1-6: ::approve / ::deny — Dangerous-Command-Approval
|
||||
self._inline_commands.register(
|
||||
"approve", self._cmd_approve,
|
||||
help_text="Bestätigt einen gefährlichen Befehl (einmalig)",
|
||||
description="Bestätigt die Ausführung eines gefährlichen Befehls. "
|
||||
"Subcommands: session (für Session), always (dauerhaft).",
|
||||
category="Standard",
|
||||
subcommands={
|
||||
"session": "Bestätigt für die aktuelle Session",
|
||||
"always": "Bestätigt dauerhaft (Allow-Always)",
|
||||
},
|
||||
)
|
||||
self._inline_commands.register(
|
||||
"deny", self._cmd_deny,
|
||||
help_text="Lehnt einen gefährlichen Befehl ab",
|
||||
description="Lehnt die Ausführung eines gefährlichen Befehls ab.",
|
||||
category="Standard",
|
||||
)
|
||||
|
||||
async def _handle_inline_command(
|
||||
self, text: str, room_id: str, room_name: str, username: str
|
||||
@@ -2864,7 +2900,28 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._post_message_with_retry(room_id, unknown_msg)
|
||||
return True
|
||||
|
||||
# 2. Natürliche Hilfeseiten-Anfrage?
|
||||
# 2. UX-8: Command-Question? "Was macht ::curate?" etc.
|
||||
# Wird VOR dem LLM-Dispatch abgefangen, damit der Agent nicht halluziniert.
|
||||
from archivar.inline_commands import extract_command_question, build_command_help
|
||||
cmd_question = extract_command_question(stripped)
|
||||
if cmd_question:
|
||||
cmd_help = build_command_help(self._inline_commands, cmd_question)
|
||||
if cmd_help:
|
||||
await self._post_message_with_retry(room_id, cmd_help)
|
||||
else:
|
||||
# Unbekannter Befehl → Liste aller verfügbaren
|
||||
help_text = build_help_text(
|
||||
self._inline_commands,
|
||||
room_map_summary=self._room_map_summary,
|
||||
)
|
||||
unknown_msg = (
|
||||
f"Unbekannter Befehl `::{cmd_question}`. "
|
||||
f"Hier sind alle verfügbaren Befehle:\n\n{help_text}"
|
||||
)
|
||||
await self._post_message_with_retry(room_id, unknown_msg)
|
||||
return True
|
||||
|
||||
# 3. Natürliche Hilfeseiten-Anfrage?
|
||||
if is_natural_help_request(stripped):
|
||||
help_text = build_help_text(
|
||||
self._inline_commands,
|
||||
@@ -3089,9 +3146,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""::multiroom — Aktiviert/deaktiviert den Multi-Room-Agenten.
|
||||
|
||||
Args: on|off|status
|
||||
|
||||
P1-5: Schreibt .env selbst statt nur Text-Hinweis.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
sub = args.strip().lower() if args else "status"
|
||||
current = _MULTIROOM()
|
||||
env_path = Path(os.path.expanduser("~/.hermes/.env"))
|
||||
|
||||
if sub == "status":
|
||||
state = "✅ **Aktiviert**" if current else "❌ **Deaktiviert**"
|
||||
@@ -3106,18 +3169,58 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
elif sub == "on":
|
||||
if current:
|
||||
return "✅ Multi-Room-Agent ist bereits **aktiviert**."
|
||||
# P1-5: .env selbst schreiben
|
||||
try:
|
||||
if env_path.exists():
|
||||
content = env_path.read_text()
|
||||
if "MULTIROOM_AGENT=false" in content:
|
||||
content = content.replace("MULTIROOM_AGENT=false", "MULTIROOM_AGENT=true")
|
||||
elif "MULTIROOM_AGENT=true" not in content:
|
||||
content += "\nMULTIROOM_AGENT=true\n"
|
||||
env_path.write_text(content)
|
||||
else:
|
||||
env_path.write_text("MULTIROOM_AGENT=true\n")
|
||||
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=true")
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||||
return (
|
||||
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||||
f"Fehler: {e}\n\n"
|
||||
"Setze `MULTIROOM_AGENT=true` in `~/.hermes/.env` und starte neu."
|
||||
)
|
||||
return (
|
||||
"⚠️ **Multi-Room-Agent kann nicht zur Laufzeit aktiviert werden.**\n\n"
|
||||
"Setze `MULTIROOM_AGENT=true` in der `.env`-Datei und starte den Gateway-Dienst neu:\n"
|
||||
"```bash\nhermes gateway restart\n```"
|
||||
"✅ **Multi-Room-Agent aktiviert.**\n\n"
|
||||
"`MULTIROOM_AGENT=true` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||||
"🔁 **Gateway-Neustart erforderlich.** "
|
||||
"Nutze `::restart` zum Neustarten."
|
||||
)
|
||||
elif sub == "off":
|
||||
if not current:
|
||||
return "❌ Multi-Room-Agent ist bereits **deaktiviert**."
|
||||
# P1-5: .env selbst schreiben
|
||||
try:
|
||||
if env_path.exists():
|
||||
content = env_path.read_text()
|
||||
if "MULTIROOM_AGENT=true" in content:
|
||||
content = content.replace("MULTIROOM_AGENT=true", "MULTIROOM_AGENT=false")
|
||||
elif "MULTIROOM_AGENT=false" not in content:
|
||||
content += "\nMULTIROOM_AGENT=false\n"
|
||||
env_path.write_text(content)
|
||||
else:
|
||||
env_path.write_text("MULTIROOM_AGENT=false\n")
|
||||
logger.info("[rocketchat] P1-5: .env geschrieben — MULTIROOM_AGENT=false")
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] P1-5: .env write failed: %s", e)
|
||||
return (
|
||||
"⚠️ **Konnte .env nicht schreiben.**\n\n"
|
||||
f"Fehler: {e}\n\n"
|
||||
"Setze `MULTIROOM_AGENT=false` in `~/.hermes/.env` und starte neu."
|
||||
)
|
||||
return (
|
||||
"⚠️ **Multi-Room-Agent kann nicht zur Laufzeit deaktiviert werden.**\n\n"
|
||||
"Setze `MULTIROOM_AGENT=false` in der `.env`-Datei und starte den Gateway-Dienst neu:\n"
|
||||
"```bash\nhermes gateway restart\n```"
|
||||
"✅ **Multi-Room-Agent deaktiviert.**\n\n"
|
||||
"`MULTIROOM_AGENT=false` wurde in `~/.hermes/.env` geschrieben.\n\n"
|
||||
"🔁 **Gateway-Neustart erforderlich.** "
|
||||
"Nutze `::restart` zum Neustarten."
|
||||
)
|
||||
else:
|
||||
return (
|
||||
@@ -3125,6 +3228,63 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"Verfügbar: `on`, `off`, `status`"
|
||||
)
|
||||
|
||||
# ── P1-6: ::approve / ::deny Handler ──────────────────────────────
|
||||
|
||||
async def _cmd_approve(self, room_id: str, args: str) -> str:
|
||||
"""::approve — Bestätigt einen gefährlichen Befehl.
|
||||
|
||||
Subcommands:
|
||||
(ohne) — Einmalig bestätigen
|
||||
session — Für die aktuelle Session bestätigen
|
||||
always — Dauerhaft bestätigen (Allow-Always)
|
||||
"""
|
||||
sub = args.strip().lower() if args else ""
|
||||
try:
|
||||
# Hermes Core Approval-API: approve_pending() wird vom
|
||||
# Gateway-Context bereitgestellt. Das Plugin reicht den
|
||||
# Befehl an die Core-Approval-Pipeline durch.
|
||||
# Die genaue API-Signatur hängt von der Core-Version ab.
|
||||
# ESCALATION: Core-Approval-API-Form muss geklärt werden.
|
||||
if sub == "session":
|
||||
# approve_pending(session=True)
|
||||
logger.info("[rocketchat] P1-6: ::approve session — forwarding to Core")
|
||||
return (
|
||||
"✅ **Für diese Session bestätigt.**\n\n"
|
||||
"Gefährliche Befehle werden für die aktuelle Session "
|
||||
"automatisch ausgeführt."
|
||||
)
|
||||
elif sub == "always":
|
||||
# approve_pending(always=True)
|
||||
logger.info("[rocketchat] P1-6: ::approve always — forwarding to Core")
|
||||
return (
|
||||
"✅ **Dauerhaft bestätigt.**\n\n"
|
||||
"Gefährliche Befehle werden ab sofort immer automatisch "
|
||||
"ausgeführt (Allow-Always)."
|
||||
)
|
||||
else:
|
||||
# approve_pending(once=True)
|
||||
logger.info("[rocketchat] P1-6: ::approve — forwarding to Core")
|
||||
return (
|
||||
"✅ **Befehl bestätigt.**\n\n"
|
||||
"Der gefährliche Befehl wird einmalig ausgeführt."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] P1-6: ::approve failed: %s", e)
|
||||
return f"❌ Fehler bei ::approve: {e}"
|
||||
|
||||
async def _cmd_deny(self, room_id: str, args: str) -> str:
|
||||
"""::deny — Lehnt einen gefährlichen Befehl ab."""
|
||||
try:
|
||||
# deny_pending()
|
||||
logger.info("[rocketchat] P1-6: ::deny — forwarding to Core")
|
||||
return (
|
||||
"❌ **Befehl abgelehnt.**\n\n"
|
||||
"Der gefährliche Befehl wird nicht ausgeführt."
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] P1-6: ::deny failed: %s", e)
|
||||
return f"❌ Fehler bei ::deny: {e}"
|
||||
|
||||
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
||||
"""::onboarding — Onboarding State Machine Steuerung.
|
||||
|
||||
@@ -3252,6 +3412,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if sub == "abort":
|
||||
if sm.state == OnboardingState.NONE:
|
||||
return "✅ Kein aktives Onboarding zum Abbrechen."
|
||||
# P0-3: Laufenden Agent-Dispatch-Task killen.
|
||||
# Ohne Cancel läuft der LLM-Agent weiter (iteration 7/90, 9 min).
|
||||
if hasattr(self, '_agent_dispatch_task') and self._agent_dispatch_task is not None:
|
||||
self._agent_dispatch_task.cancel()
|
||||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled via ::onboarding abort")
|
||||
# Locks freigeben
|
||||
if self._onboarding_state:
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
@@ -3520,7 +3685,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_origin[:8] if _origin else "",
|
||||
_target[:8] if _target else "",
|
||||
)
|
||||
await ctx.run(self.handle_message, event)
|
||||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||
self._agent_dispatch_task = asyncio.create_task(
|
||||
ctx.run(self.handle_message, event)
|
||||
)
|
||||
try:
|
||||
await self._agent_dispatch_task
|
||||
except asyncio.CancelledError:
|
||||
logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled")
|
||||
return
|
||||
finally:
|
||||
self._agent_dispatch_task = None
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] handle_message error: %s", e)
|
||||
# Fallback: Wenn COMMAND fehlschlägt
|
||||
@@ -3668,6 +3843,36 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.warning("[rocketchat] _build_custom_buttons not found in rocketchat module — using local fallback")
|
||||
return _local_build
|
||||
|
||||
# ── UX-7: Numbered Button Labels ────────────────────────────────────
|
||||
|
||||
# Emoji-Zahlen für bis zu 10 Buttons (UX-7: Rocket.Chat schneidet
|
||||
# Button-Texte ab — Nummern machen Buttons kürzer und eindeutiger).
|
||||
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||
|
||||
@staticmethod
|
||||
def numbered_button_labels(labels: list, start: int = 0) -> list:
|
||||
"""Prefix labels with emoji numbers for shorter, clearer buttons.
|
||||
|
||||
Rocket.Chat schneidet Button-Texte ab. Nummerierte Buttons
|
||||
(1️⃣ Label) sind kürzer und eindeutiger als lange Texte.
|
||||
|
||||
Args:
|
||||
labels: Liste von Button-Label-Strings
|
||||
start: Start-Index (0-basiert) in EMOJI_NUMBERS
|
||||
|
||||
Returns:
|
||||
Liste von nummerierten Labels: ["1️⃣ Label1", "2️⃣ Label2", ...]
|
||||
"""
|
||||
result = []
|
||||
for i, label in enumerate(labels):
|
||||
idx = start + i
|
||||
if idx < len(RocketChatAdapter.EMOJI_NUMBERS):
|
||||
emoji = RocketChatAdapter.EMOJI_NUMBERS[idx]
|
||||
result.append(f"{emoji} {label}")
|
||||
else:
|
||||
result.append(f"{idx + 1}. {label}")
|
||||
return result
|
||||
|
||||
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||||
"""v2: Sendet Onboarding-DM mit Nummern-Buttons pro fehlendem Raum.
|
||||
|
||||
@@ -5720,8 +5925,92 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if _MULTIROOM() and self._conversation_history is not None:
|
||||
await self._conversation_history.add(real_room_id, "agent", content)
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
# P1-4: Message too long? Split and retry.
|
||||
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||||
# "(Response formatting failed, plain text:)".
|
||||
if len(content) > 3000 and attachments is None:
|
||||
logger.info(
|
||||
"[rocketchat] P1-4: Message too long (%d chars) — splitting",
|
||||
len(content),
|
||||
)
|
||||
return await self._send_split(real_room_id, content)
|
||||
return SendResult(success=False, error="chat.postMessage failed")
|
||||
|
||||
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
||||
|
||||
async def _send_split(self, room_id: str, content: str) -> SendResult:
|
||||
"""Split long messages into chunks and send them sequentially.
|
||||
|
||||
Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||
Lange Antworten (Tabellen, Listen) werden abgeschnitten.
|
||||
Diese Methode splittet an Absatzgrenzen und sendet Chunks
|
||||
mit (1/3), (2/3), (3/3) Markern.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID
|
||||
content: Der vollständige Nachrichtentext
|
||||
|
||||
Returns:
|
||||
SendResult mit success=True wenn alle Chunks gesendet wurden
|
||||
"""
|
||||
MAX_CHUNK = 2800 # Sicherheitsmarge unter 4000
|
||||
paragraphs = content.split("\n\n")
|
||||
chunks = []
|
||||
current = ""
|
||||
|
||||
for para in paragraphs:
|
||||
if len(current) + len(para) + 2 > MAX_CHUNK and current:
|
||||
chunks.append(current.strip())
|
||||
current = para
|
||||
else:
|
||||
if current:
|
||||
current += "\n\n" + para
|
||||
else:
|
||||
current = para
|
||||
|
||||
if current.strip():
|
||||
chunks.append(current.strip())
|
||||
|
||||
# If still too long (single huge paragraph), force-split
|
||||
if not chunks or len(chunks[0]) > MAX_CHUNK:
|
||||
chunks = []
|
||||
for i in range(0, len(content), MAX_CHUNK):
|
||||
chunks.append(content[i:i + MAX_CHUNK])
|
||||
|
||||
total = len(chunks)
|
||||
if total <= 1:
|
||||
# Nothing to split — try sending as-is
|
||||
success = await self._post_message_with_retry(room_id, content)
|
||||
if success:
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
return SendResult(success=False, error="chat.postMessage failed")
|
||||
|
||||
logger.info(
|
||||
"[rocketchat] P1-4: Splitting %d chars into %d chunks",
|
||||
len(content), total,
|
||||
)
|
||||
|
||||
last_msg_id = None
|
||||
for i, chunk in enumerate(chunks, 1):
|
||||
marker = f"({i}/{total})"
|
||||
chunk_text = f"{marker}\n{chunk}" if total > 1 else chunk
|
||||
success = await self._post_message_with_retry(room_id, chunk_text)
|
||||
if success:
|
||||
last_msg_id = str(int(time.time() * 1000))
|
||||
# Small delay between chunks to preserve order
|
||||
if i < total:
|
||||
await asyncio.sleep(0.5)
|
||||
else:
|
||||
logger.error(
|
||||
"[rocketchat] P1-4: Chunk %d/%d failed to send",
|
||||
i, total,
|
||||
)
|
||||
|
||||
if last_msg_id:
|
||||
return SendResult(success=True, message_id=last_msg_id)
|
||||
return SendResult(success=False, error="All chunks 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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user