380 lines
18 KiB
Python
380 lines
18 KiB
Python
# @implements: [F-064, F-556] — P-064 Hook-Registrierung; F-556 Multi-Profil-Adapter-Reduktion (ROCKETCHAT_SKIP_ADAPTER)
|
|
"""
|
|
Rocket.Chat Platform Plugin for Hermes Agent.
|
|
|
|
Registers a gateway platform adapter that connects to a self-hosted
|
|
Rocket.Chat server via DDP/WebSocket (real-time incoming messages + presence)
|
|
and REST API (outgoing replies).
|
|
"""
|
|
|
|
import logging
|
|
import os
|
|
import sys
|
|
|
|
# P3 Fix: Ensure archivar submodule is importable as top-level module.
|
|
# Without this, absolute imports like 'from archivar.config import ...'
|
|
# fail when the plugin is loaded from site-packages/plugins/rocketchat/.
|
|
sys.path.insert(0, os.path.dirname(__file__))
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ── V9: Modul-Level-Adapter-Referenz für Hook-Callbacks ──────────────────
|
|
# F1.1: Statt privater ctx._adapter/ctx._platforms nutzen die Hook-Callbacks
|
|
# diese offizielle Modul-Referenz. Sie wird in RocketChatAdapter.connect()
|
|
# gesetzt und in disconnect() auf None zurückgesetzt.
|
|
_active_adapter = None # RocketChatAdapter instance, set in connect()
|
|
|
|
# ── V9: Hook-Registrierungs-Flag (Idempotenz) ────────────────────────────
|
|
_hooks_registered = False
|
|
|
|
# ── V9: PluginContext-Referenz (für deferred Hook-Registrierung) ─────────
|
|
_plugin_ctx = None # PluginContext, set in register()
|
|
|
|
# ── Interaction Templates (source of truth — zero yaml dependency) ──
|
|
_TEMPLATE_MAP = {
|
|
"yes_no": {
|
|
"label": "Ja/Nein",
|
|
"description": "Binary confirmation",
|
|
"attachment": {"color": "#1d74f5", "title": "Bitte bestätigen:"},
|
|
"buttons": [
|
|
{"text": "✅ Ja", "msg": "ja", "style": "primary"},
|
|
{"text": "❌ Nein", "msg": "nein", "style": "danger"},
|
|
],
|
|
},
|
|
"confirm_cancel": {
|
|
"label": "Bestätigen/Abbrechen",
|
|
"description": "Safe action with abort",
|
|
"attachment": {"color": "#1d74f5", "title": "Aktion bestätigen:"},
|
|
"buttons": [
|
|
{"text": "✅ Bestätigen", "msg": "bestätigen", "style": "primary"},
|
|
{"text": "🚫 Abbrechen", "msg": "abbrechen", "style": "danger"},
|
|
],
|
|
},
|
|
"ok": {
|
|
"label": "OK",
|
|
"description": "Single acknowledgement",
|
|
"attachment": {"color": "#1d74f5", "title": "Hinweis:"},
|
|
"buttons": [
|
|
{"text": "👍 OK", "msg": "ok", "style": "primary"},
|
|
],
|
|
},
|
|
"multi_choice_3": {
|
|
"label": "3 Optionen",
|
|
"description": "Three-option selection",
|
|
"attachment": {"color": "#1d74f5", "title": "Wähle eine Option:"},
|
|
"buttons": [
|
|
{"text": "1._Links", "msg": "links", "style": "default"},
|
|
{"text": "2._Rechts", "msg": "rechts", "style": "default"},
|
|
{"text": "3._Zwei_Runden", "msg": "zwei_runden", "style": "default"},
|
|
],
|
|
},
|
|
}
|
|
|
|
|
|
def _build_custom_buttons(labels: list, prefix: str = "", style: str = "default") -> list:
|
|
"""Build Rocket.Chat action buttons from plain label strings.
|
|
|
|
Rocket.Chat UI truncates button text after ~11-12 chars.
|
|
Use short labels (emoji+text without spaces, or numbered refs).
|
|
|
|
Args:
|
|
labels: Button display texts (keep short — emoji preferred)
|
|
prefix: Payload prefix for correlation (e.g. "ONBOARD:<rid>")
|
|
style: Rocket.Chat button style — "default" (grey) or "primary" (blue)
|
|
"""
|
|
import hashlib
|
|
buttons = []
|
|
for idx, label in enumerate(labels):
|
|
# Sanitize label for button text (keep short)
|
|
display = label.strip()
|
|
# Payload may carry question_id prefix for correlation
|
|
msg_payload = display
|
|
if prefix:
|
|
msg_payload = f"{prefix}::{msg_payload}"
|
|
# P-051: action_id zwingend für RC 6.x (sonst actions-Array ignoriert)
|
|
action_id = hashlib.sha1(f"{msg_payload}:{idx}".encode()).hexdigest()[:12]
|
|
buttons.append({
|
|
"type": "button",
|
|
"text": display,
|
|
"msg": msg_payload,
|
|
"msg_in_chat_window": True,
|
|
"style": style,
|
|
"action_id": action_id,
|
|
})
|
|
return buttons
|
|
|
|
|
|
def check_requirements():
|
|
"""Rocket.Chat adapter uses only stdlib (urllib, socket, ssl, threading)."""
|
|
return True
|
|
|
|
|
|
def _truthy(value) -> bool:
|
|
"""Truthy-Check für Env/Config-Flags (true/1/yes/on — case-insensitive)."""
|
|
return str(value or "").strip().lower() in ("true", "1", "yes", "on")
|
|
|
|
|
|
def _skip_adapter_flag(config) -> bool:
|
|
"""Ist ROCKETCHAT_SKIP_ADAPTER gesetzt? (Variante C — Multi-Profil-Adapter-Reduktion, F-556)
|
|
|
|
Unter Hermes-Multiplex wird ein Satelliten-Profil (don/finn/miguel/rainer/viola)
|
|
innerhalb von ``_profile_runtime_scope()`` gestartet. Dessen eigenes ``.env`` ist
|
|
NUR über die scoped-secret-Lesung lesbar — ein pauschales ``os.getenv()`` fällt
|
|
auf das geerbte Prozess-Env des Default-Profils zurück und sähe das Satelliten-Flag
|
|
NICHT (genau der Grund, warum Variante A/B scheiterten).
|
|
|
|
Kanonische Lesung: ``gateway.platforms._shared.get_scoped_secret`` — die EINE
|
|
scoped-secret-Implementierung des Core (gateway/AGENTS.md § Profile scope). Sie
|
|
liefert unter einem Satelliten-Scope den eigenen ``.env``-Wert, beim Default-Profil
|
|
(unscoped) dessen ``os.environ``-Wert, und single-profile liest ``os.environ``.
|
|
Die Adapter-eigene Nachbau-Form (``try get_secret / except: os.getenv``) ist laut
|
|
Core explizit verboten (Fallback-after-miss-Leak) — deshalb hier NICHT verwendet.
|
|
|
|
``validate_config()`` liefert bei gesetztem Flag False → ``create_adapter()``
|
|
liefert None → der Adapter wird NICHT instanziiert. Der CLI-Pfad (hermes chat
|
|
--profile) startet keinen Gateway-Adapter und ist damit unberührt.
|
|
"""
|
|
# 1) Kanonische scoped-secret-Lesung (Satelliten-.env bzw. Default-Env).
|
|
try:
|
|
from gateway.platforms._shared import get_scoped_secret
|
|
val = get_scoped_secret("ROCKETCHAT_SKIP_ADAPTER", None)
|
|
except Exception:
|
|
# Core nicht importierbar (z.B. Unit-Test-Kontext ohne gateway-Package) →
|
|
# Fallback auf os.environ (single-profile-Pfad).
|
|
val = os.getenv("ROCKETCHAT_SKIP_ADAPTER")
|
|
if val is not None and str(val).strip():
|
|
return _truthy(val)
|
|
# 2) config.yaml extra (opt-in Steuerung, z.B. platforms.rocketchat.extra.skip_adapter).
|
|
extra = getattr(config, "extra", {}) or {}
|
|
extra_val = extra.get("skip_adapter")
|
|
if extra_val is not None and str(extra_val).strip():
|
|
return _truthy(extra_val)
|
|
return False
|
|
|
|
|
|
def validate_config(config) -> bool:
|
|
"""Check whether the platform is properly configured.
|
|
|
|
F-556: Liefert False, wenn ``ROCKETCHAT_SKIP_ADAPTER`` im Profil gesetzt ist —
|
|
dann wird der Adapter vom Gateway nicht instanziiert (Variante C, Multi-Profil).
|
|
"""
|
|
if _skip_adapter_flag(config):
|
|
logger.info(
|
|
"[F-556] ROCKETCHAT_SKIP_ADAPTER gesetzt — Rocket.Chat-Adapter für dieses "
|
|
"Profil übersprungen (Multi-Profil-Adapter-Reduktion)."
|
|
)
|
|
return False
|
|
extra = getattr(config, "extra", {}) or {}
|
|
base_url = os.getenv("ROCKETCHAT_BASE_URL") or extra.get("base_url", "")
|
|
user = os.getenv("ROCKETCHAT_USER") or extra.get("user", "")
|
|
password = os.getenv("ROCKETCHAT_PASSWORD") or extra.get("password", "")
|
|
return bool(base_url and user and password)
|
|
|
|
|
|
def is_connected(config) -> bool:
|
|
"""Check whether Rocket.Chat is configured (env or config.yaml)."""
|
|
return validate_config(config)
|
|
|
|
|
|
def register(ctx):
|
|
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
|
global _plugin_ctx
|
|
_plugin_ctx = ctx # F1.2: Store for deferred hook registration in connect()
|
|
|
|
_MULTIROOM = os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
|
|
|
|
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
|
from .rc_tools import register_tools
|
|
|
|
ctx.register_platform(
|
|
name="rocketchat",
|
|
label="Rocket.Chat",
|
|
adapter_factory=lambda cfg: RocketChatAdapter(cfg),
|
|
check_fn=check_requirements,
|
|
validate_config=validate_config,
|
|
is_connected=is_connected,
|
|
required_env=["ROCKETCHAT_BASE_URL", "ROCKETCHAT_USER", "ROCKETCHAT_PASSWORD"],
|
|
install_hint="No extra packages needed (stdlib only)",
|
|
allowed_users_env="ROCKETCHAT_ALLOWED_USERS",
|
|
allow_all_env="ROCKETCHAT_ALLOW_ALL_USERS",
|
|
max_message_length=4000,
|
|
emoji="🚀",
|
|
pii_safe=False,
|
|
allow_update_command=True,
|
|
platform_hint=(
|
|
"You are chatting via Rocket.Chat. You support markdown formatting: "
|
|
"**bold**, *italic*, `inline code`, ```code blocks```, and [links](url). "
|
|
"Messages can be up to ~4000 characters. You have a green online dot "
|
|
"via DDP presence. Use professional but friendly tone."
|
|
),
|
|
)
|
|
|
|
register_tools(ctx)
|
|
|
|
# ── V9: PresenceEngine — Hook-Registrierung (deferred) ────────────────
|
|
# Die 8 Hooks (6 Core + 2 Tool-Filter) werden NICHT hier in register()
|
|
# registriert, sondern erst in RocketChatAdapter.connect().
|
|
#
|
|
# Grund (F1.2 — Lifecycle): In register() existiert der Adapter noch
|
|
# nicht — register_platform() erzeugt nur eine Factory. Die Hooks
|
|
# brauchen aber Zugriff auf den instanziierten Adapter (via
|
|
# _presence_engine). connect() ist die korrekte Lifecycle-Phase:
|
|
# Der Adapter ist vollständig initialisiert, REST-Login erfolgt,
|
|
# PresenceEngine ist gebunden, und der asyncio-Loop läuft.
|
|
#
|
|
# Hook-Mapping (V10.0.2 — P-032 Fix, siehe docs/architecture/2026-08-03-presence-engine-schachuhr.md):
|
|
# pre_gateway_dispatch → main_agent += 1 (ROT Start)
|
|
# post_llm_call → main_agent -= 1 (ROT Ende, Clamp bei 0)
|
|
# subagent_start → delegate_subagent += 1 (GELB Start)
|
|
# subagent_stop → delegate_subagent -= 1 (GELB Ende)
|
|
# on_session_start → chat_profile += 1 (GELB Start, echter Session-Start)
|
|
# on_session_end → NO-OP (feuert PRO TURN, nicht pro Session)
|
|
# on_session_finalize → chat_profile -= 1 (GELB Ende, echtes Session-Ende)
|
|
# on_session_reset → alle Counter auf 0 (/reset)
|
|
# pre_tool_call → background_term += 1 (wenn terminal bg=true)
|
|
# post_tool_call → NO-OP (P-043: kein Dekrement im selben Turn)
|
|
# background_process_stop → background_term -= 1 (P-043: echtes Prozess-Ende)
|
|
#
|
|
# Die Callbacks nutzen adapter._active_adapter (Modul-Level-Referenz,
|
|
# gesetzt in connect()) statt privater ctx-Attribute (F1.1 — offizielle API).
|
|
#
|
|
# _register_presence_hooks() wird von RocketChatAdapter.connect()
|
|
# aufgerufen. Idempotent: doppelte Aufrufe (z.B. Reconnect) sind No-Ops.
|
|
|
|
|
|
def _register_presence_hooks() -> None:
|
|
"""Registriere 13 Presence-Hooks via ctx.register_hook().
|
|
|
|
Wird von RocketChatAdapter.connect() aufgerufen, sobald der Adapter
|
|
vollständig initialisiert ist (REST-Login, PresenceEngine, asyncio-Loop).
|
|
|
|
Idempotent: doppelte Aufrufe (z.B. Reconnect) sind No-Ops.
|
|
"""
|
|
global _hooks_registered
|
|
if _hooks_registered:
|
|
return
|
|
|
|
ctx = _plugin_ctx
|
|
if ctx is None:
|
|
logger.warning("[presence-v9] Kein PluginContext — Hook-Registrierung übersprungen")
|
|
return
|
|
|
|
try:
|
|
# ── Wrapper: Holt die PresenceEngine via _active_adapter ──────────
|
|
# V9.0.1: SYNCHRON — invoke_hook() im Core ruft Callbacks via
|
|
# ret = cb(**kwargs) auf. Async-Callbacks würden als Coroutine-Objekt
|
|
# zurückgegeben aber nie awaited → Hook-Code wird NIE ausgeführt.
|
|
def _get_engine_and_call(method_name: str, **kwargs):
|
|
"""Hole PresenceEngine aus dem aktiven Adapter und rufe Methode auf.
|
|
|
|
Nutzt die Modul-Level-Referenz _active_adapter (F1.1: offizielle
|
|
API statt privater ctx._adapter/ctx._platforms).
|
|
|
|
V9.0.1: Synchron — invoke_hook() erwartet sync-Callbacks.
|
|
"""
|
|
try:
|
|
adapter = _active_adapter
|
|
if adapter is None:
|
|
logger.debug("[HOOK-DEBUG] hook=%s, engine_found=False (adapter None), callback_called=False, counters=N/A", method_name)
|
|
return
|
|
engine = getattr(adapter, '_presence_engine', None)
|
|
if engine is None or not engine.is_enabled():
|
|
logger.debug("[HOOK-DEBUG] hook=%s, engine_found=%s, callback_called=False, counters=N/A", method_name, engine is not None)
|
|
return
|
|
method = getattr(engine, method_name, None)
|
|
if method is not None:
|
|
method(**kwargs)
|
|
logger.debug(
|
|
"[HOOK-DEBUG] hook=%s, engine_found=True, callback_called=True, counters=%s",
|
|
method_name, engine.get_counters(),
|
|
)
|
|
else:
|
|
logger.debug("[HOOK-DEBUG] hook=%s, engine_found=True, callback_called=False (no method), counters=%s", method_name, engine.get_counters())
|
|
except Exception as e:
|
|
logger.debug("[presence-v9] Hook %s fehlgeschlagen: %s", method_name, e)
|
|
|
|
# ── 6 Core-Hooks (V9.0.1: synchron) ──────────────────────────────
|
|
def _on_pre_gateway_dispatch(**kwargs):
|
|
_get_engine_and_call("on_pre_gateway_dispatch", **kwargs)
|
|
|
|
def _on_post_llm_call(**kwargs):
|
|
_get_engine_and_call("on_post_llm_call", **kwargs)
|
|
|
|
def _on_subagent_start(**kwargs):
|
|
_get_engine_and_call("on_subagent_start", **kwargs)
|
|
|
|
def _on_subagent_stop(**kwargs):
|
|
_get_engine_and_call("on_subagent_stop", **kwargs)
|
|
|
|
def _on_session_start(**kwargs):
|
|
_get_engine_and_call("on_session_start", **kwargs)
|
|
|
|
def _on_session_end(**kwargs):
|
|
# P-032: on_session_end feuert PRO TURN — No-Op in der Engine.
|
|
# chat_profile-Dekrement erfolgt via on_session_finalize/on_session_reset.
|
|
_get_engine_and_call("on_session_end", **kwargs)
|
|
|
|
def _on_session_finalize(**kwargs):
|
|
_get_engine_and_call("on_session_finalize", **kwargs)
|
|
|
|
def _on_session_reset(**kwargs):
|
|
_get_engine_and_call("on_session_reset", **kwargs)
|
|
|
|
# ── 2 Tool-Filter-Hooks (O-1: Background-Terminal-Workaround) ─────
|
|
def _on_pre_tool_call(**kwargs):
|
|
_get_engine_and_call("on_pre_tool_call", **kwargs)
|
|
|
|
def _on_post_tool_call(**kwargs):
|
|
_get_engine_and_call("on_post_tool_call", **kwargs)
|
|
|
|
# ── P-043: background_process_stop Hook ──────────────────────────
|
|
# F97: ENTFERNT — toter Hook. 'background_process_stop' existiert
|
|
# NICHT in Core-VALID_HOOKS (0 Treffer in hermes_cli/plugins.py).
|
|
# Die Registrierung schlug still fehl (P-064-Klasse). Der
|
|
# background_term-Dekrement-Pfad läuft real nur via GC (P-148,
|
|
# separat dokumentiert — NICHT Teil von F97).
|
|
def _on_background_process_stop(**kwargs):
|
|
_get_engine_and_call("on_background_process_stop", **kwargs)
|
|
|
|
# ── F97: Kanban-Worker-Hooks (additiv, S-Subklasse) ──────────────
|
|
def _on_kanban_worker_spawned(**kwargs):
|
|
_get_engine_and_call("on_kanban_worker_spawned", **kwargs)
|
|
|
|
def _on_kanban_worker_exited(**kwargs):
|
|
_get_engine_and_call("on_kanban_worker_exited", **kwargs)
|
|
|
|
def _on_kanban_worker_stale_claim(**kwargs):
|
|
_get_engine_and_call("on_kanban_worker_stale_claim", **kwargs)
|
|
|
|
# ── Registrierung via offizielle API ──────────────────────────────
|
|
ctx.register_hook("pre_gateway_dispatch", _on_pre_gateway_dispatch)
|
|
ctx.register_hook("post_llm_call", _on_post_llm_call)
|
|
ctx.register_hook("subagent_start", _on_subagent_start)
|
|
ctx.register_hook("subagent_stop", _on_subagent_stop)
|
|
ctx.register_hook("on_session_start", _on_session_start)
|
|
ctx.register_hook("on_session_end", _on_session_end)
|
|
ctx.register_hook("on_session_finalize", _on_session_finalize)
|
|
ctx.register_hook("on_session_reset", _on_session_reset)
|
|
ctx.register_hook("pre_tool_call", _on_pre_tool_call)
|
|
ctx.register_hook("post_tool_call", _on_post_tool_call)
|
|
# F97: background_process_stop-Registrierung ENTFERNT (toter Hook).
|
|
# F97: 3 Kanban-Worker-Hooks additiv registriert.
|
|
ctx.register_hook("on_kanban_worker_spawned", _on_kanban_worker_spawned)
|
|
ctx.register_hook("on_kanban_worker_exited", _on_kanban_worker_exited)
|
|
ctx.register_hook("on_kanban_worker_stale_claim", _on_kanban_worker_stale_claim)
|
|
|
|
_hooks_registered = True
|
|
logger.info(
|
|
"[presence-v10] 13 Hooks registriert: "
|
|
"pre_gateway_dispatch, post_llm_call, subagent_start, subagent_stop, "
|
|
"on_session_start, on_session_end, on_session_finalize, on_session_reset, "
|
|
"pre_tool_call, post_tool_call, "
|
|
"on_kanban_worker_spawned, on_kanban_worker_exited, on_kanban_worker_stale_claim "
|
|
"(background_process_stop entfernt — toter Hook)"
|
|
)
|
|
except Exception as e:
|
|
logger.warning(
|
|
"[presence-v9] Hook-Registrierung fehlgeschlagen: %s — "
|
|
"PresenceEngine läuft ohne Hooks (graceful degradation)", e
|
|
)
|