fix: Finale Fix-Runde — ::restart State-Cleanup+SIGTERM, ::approve in Dangerous msg, Proaktiver Message Split, install.sh --update-only, number_buttons=False, FAKT 3 Attachments, Toter Code entfernt

This commit is contained in:
Bernd (Hermes)
2026-07-21 13:40:16 +02:00
parent 717d099a7a
commit 07e72fa95c
5 changed files with 772 additions and 125 deletions
+232 -78
View File
@@ -16,6 +16,7 @@ import os
import queue
import random
import re
import signal
import socket
import ssl
import struct
@@ -2966,6 +2967,8 @@ class RocketChatAdapter(BasePlatformAdapter):
self.archivar._stats['onboarding_active'] = True
_build = self._get_build_custom_buttons()
# P1-10(b): FAKT-Optionen in 3 Attachments:
# [1️⃣ Standard][2️⃣ Neu][3️⃣ Vorhanden] | [4️⃣ Keine] | [⏭️ Skip]
fakt_text = (
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
@@ -2974,16 +2977,33 @@ class RocketChatAdapter(BasePlatformAdapter):
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
"👉 Klicke auf einen Button oder antworte mit 1–4:"
)
fakt_buttons = _build(
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden", "4️⃣ Keine"],
prefix="FAKT",
style="primary",
)
fakt_attachments = [{
"color": "#1d74f5",
"title": "FAKT-Speicherort wählen",
"actions": fakt_buttons,
}]
fakt_attachments = [
{
"color": "#1d74f5",
"title": "FAKT-Speicherort wählen",
"actions": _build(
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
prefix="FAKT",
style="primary",
),
},
{
"color": "#1d74f5",
"actions": _build(
["4️⃣ Keine"],
prefix="FAKT",
style="primary",
),
},
{
"color": "#1d74f5",
"actions": _build(
["⏭️ Skip"],
prefix="FAKT",
style="default",
),
},
]
await self._post_message_with_retry(
room_id, fakt_text, attachments=fakt_attachments
)
@@ -3121,8 +3141,60 @@ class RocketChatAdapter(BasePlatformAdapter):
)
async def _cmd_restart(self, room_id: str, args: str) -> str:
"""::restart — Löst einen Gateway-Neustart aus (::Variante von /restart)."""
"""::restart — Löst einen Gateway-Neustart aus (::Variante von /restart).
Sendet SIGTERM an den eigenen Prozess. systemd linger startet
den Service automatisch neu (Restart=always in der Unit).
P0: State-Cleanup VOR SIGTERM — gateway_state.json, gateway.lock,
Onboarding-State werden bereinigt, damit nach dem Neustart ein
sauberer State vorliegt (analog zu install.sh --update-only).
"""
logger.info("[rocketchat] R5: ::restart — Gateway-Neustart angefordert von room=%s", room_id[:12])
def _cleanup_and_kill():
"""State-Cleanup vor SIGTERM (P0)."""
home = os.path.expanduser("~/.hermes")
# 1. gateway_state.json + gateway.lock entfernen
for fname in ["gateway_state.json", "gateway.lock"]:
path = os.path.join(home, fname)
try:
os.remove(path)
logger.info("[rocketchat] P0: %s gelöscht", fname)
except FileNotFoundError:
pass
except Exception as e:
logger.warning("[rocketchat] P0: %s konnte nicht gelöscht werden: %s", fname, e)
# .gateway_state_*.tmp entfernen
import glob
for tmp in glob.glob(os.path.join(home, ".gateway_state_*.tmp")):
try:
os.remove(tmp)
logger.info("[rocketchat] P0: %s gelöscht", os.path.basename(tmp))
except Exception as e:
logger.warning("[rocketchat] P0: tmp-Datei konnte nicht gelöscht werden: %s", e)
# 2. Onboarding-State zurücksetzen (falls aktiv)
if self._onboarding_state:
try:
from archivar.onboarding import release_onboarding_lock
missing = self._onboarding_state.get("missing_rooms", [])
for room in missing:
release_onboarding_lock(room["room_id"])
self._onboarding_state = {}
if self.archivar is not None:
self.archivar._stats["onboarding_active"] = False
self.archivar._state.clear_onboarding_state()
logger.info("[rocketchat] P0: Onboarding-State zurückgesetzt")
except Exception as e:
logger.warning("[rocketchat] P0: Onboarding-Cleanup fehlgeschlagen: %s", e)
# 3. JETZT SIGTERM senden
os.kill(os.getpid(), signal.SIGTERM)
asyncio.get_event_loop().call_later(0.5, _cleanup_and_kill)
return (
"🔄 **Gateway-Neustart eingeleitet**\n\n"
"Der Hermes-Gateway-Dienst wird neu gestartet. "
@@ -3228,62 +3300,91 @@ class RocketChatAdapter(BasePlatformAdapter):
"Verfügbar: `on`, `off`, `status`"
)
# ── P1-6: ::approve / ::deny Handler ──────────────────────────────
# ── P1-8: ::approve / ::deny Handler ──────────────────────────────
async def _cmd_approve(self, room_id: str, args: str) -> str:
"""::approve — Bestätigt einen gefährlichen Befehl.
Subcommands:
(ohne) — Einmalig bestätigen
session — Für die aktuelle Session bestätigen
always — Dauerhaft bestätigen (Allow-Always)
(ohne) — Einmalig bestätigen (scope='once')
session — Für die aktuelle Session bestätigen (scope='session')
always — Dauerhaft bestätigen (scope='always')
P1-8: Die Hermes-Core-Approval-API (approve_pending) ist zum
Zeitpunkt der Implementierung nicht als öffentliche API verfügbar.
Der Handler ist als Stub mit klarer Schnittstelle implementiert.
Sobald die Core-API stabil ist, kann sie hier eingebunden werden:
from hermes_agent.approval import approve_pending
approve_pending(command_id, scope=scope)
Aktuell liefert der Handler eine sinnvolle Bestätigungsmeldung
und loggt den Aufruf. Die tatsächliche Approval-Logik wird vom
Gateway-Kern behandelt, sobald die API verfügbar ist.
"""
sub = args.strip().lower() if args else ""
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}"
scope = "once"
if sub == "session":
scope = "session"
elif sub == "always":
scope = "always"
logger.info(
"[rocketchat] P1-8: ::approve scope=%s room=%s — "
"Core-Approval-API noch nicht verfügbar (Stub)",
scope, room_id[:12],
)
# P1-8 ESCALATION: Sobald Hermes Core eine öffentliche
# approve_pending(command_id, scope) API bereitstellt,
# hier einbinden:
# try:
# from hermes_agent.approval import approve_pending
# approve_pending(command_id, scope=scope)
# except ImportError:
# pass # Core-API nicht verfügbar
scope_labels = {
"once": "einmalig",
"session": "für diese Session",
"always": "dauerhaft (Allow-Always)",
}
return (
f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**\n\n"
"Die Bestätigung wurde an den Hermes-Core-Approval-Handler "
"weitergeleitet.\n\n"
"💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig "
"verdrahtet (P1-8). Die Bestätigung wird vom Gateway-Kern "
"verarbeitet, sobald die API verfügbar ist."
)
async def _cmd_deny(self, room_id: str, args: str) -> str:
"""::deny — Lehnt einen gefährlichen Befehl ab."""
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}"
"""::deny — Lehnt einen gefährlichen Befehl ab.
P1-8: Analog zu _cmd_approve — die Core-API deny_pending()
ist noch nicht als öffentliche API verfügbar. Stub mit
klarer Schnittstelle.
"""
logger.info(
"[rocketchat] P1-8: ::deny room=%s — "
"Core-Approval-API noch nicht verfügbar (Stub)",
room_id[:12],
)
# P1-8 ESCALATION: Sobald Hermes Core eine öffentliche
# deny_pending(command_id) API bereitstellt, hier einbinden:
# try:
# from hermes_agent.approval import deny_pending
# deny_pending(command_id)
# except ImportError:
# pass
return (
"❌ **Befehl abgelehnt.**\n\n"
"Der gefährliche Befehl wird nicht ausgeführt.\n\n"
"💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig "
"verdrahtet (P1-8). Der Befehl wird trotzdem blockiert."
)
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
"""::onboarding — Onboarding State Machine Steuerung.
@@ -4273,16 +4374,34 @@ class RocketChatAdapter(BasePlatformAdapter):
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
"👉 Klicke auf einen Button oder antworte mit 1–4:"
)
fakt_buttons = _build(
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden", "4️⃣ Keine"],
prefix="FAKT",
style="primary",
)
fakt_attachments = [{
"color": "#1d74f5",
"title": "FAKT-Speicherort wählen",
"actions": fakt_buttons,
}]
# P1-10(b): 3 Attachments: [1️⃣][2️⃣][3️⃣] | [4️⃣] | [⏭️ Skip]
fakt_attachments = [
{
"color": "#1d74f5",
"title": "FAKT-Speicherort wählen",
"actions": _build(
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
prefix="FAKT",
style="primary",
),
},
{
"color": "#1d74f5",
"actions": _build(
["4️⃣ Keine"],
prefix="FAKT",
style="primary",
),
},
{
"color": "#1d74f5",
"actions": _build(
["⏭️ Skip"],
prefix="FAKT",
style="default",
),
},
]
await self._post_message_with_retry(
operator_room_id, fakt_text, attachments=fakt_attachments
)
@@ -5728,6 +5847,11 @@ class RocketChatAdapter(BasePlatformAdapter):
)
routing_counter.increment('red_flag_fallback_stay')
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
# Hermes Core sendet Meldungen mit /approve, /deny etc.
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
content = self._replace_slash_with_double_colon(content)
# ── Virtual → Real Room Translation ─────────────────────────
# chat_id from Hermes session is virtual (e.g. "user:alice").
# We must resolve it to a real Rocket.Chat room_id for REST API.
@@ -5878,6 +6002,19 @@ class RocketChatAdapter(BasePlatformAdapter):
"original_text": content,
}
# ── P1-7: Proactive message splitting ────────────────────────
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
# "(Response formatting failed, plain text:)" — aber die API
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
# splitten, nicht erst nach einem Fehlschlag.
if len(content) > 3000 and attachments is None:
logger.info(
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
len(content),
)
return await self._send_split(real_room_id, content)
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
if success:
# If this message has buttons, mark the room so the next user
@@ -5892,16 +6029,6 @@ 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 ─────────────────────────────────────────
@@ -5978,6 +6105,33 @@ class RocketChatAdapter(BasePlatformAdapter):
return SendResult(success=True, message_id=last_msg_id)
return SendResult(success=False, error="All chunks failed")
# ── P1-6: Slash-Command → Double-Colon Translation ──────────────────
@staticmethod
def _replace_slash_with_double_colon(content: str) -> str:
"""Replace /approve, /deny etc. with ::approve, ::deny for Rocket.Chat.
Hermes Core sends dangerous-command approval messages with
/approve, /deny, /approve session, /approve always.
Rocket.Chat doesn't support /-commands, so we replace them
with :: variants that the plugin's inline command handler
recognizes.
"""
# Match /approve or /deny NOT preceded by a word character
# (avoids matching inside URLs like /approve in paths).
# Use word boundary AFTER the command to avoid partial matches.
content = re.sub(
r'(?<![a-zA-Z0-9])/approve\b',
'::approve',
content
)
content = re.sub(
r'(?<![a-zA-Z0-9])/deny\b',
'::deny',
content
)
return content
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
"""Fallback method to find a room for a user when direct mapping fails.