fix(adapter): remove last 2 relative imports — use top-level sys.modules access

This commit is contained in:
Bernd (Hermes)
2026-06-19 17:44:04 +02:00
parent 0e13e4b30d
commit 34087299e8
+55 -82
View File
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
""" """
import asyncio import asyncio
import contextvars
import json import json
import logging import logging
import os import os
@@ -22,8 +23,16 @@ import time
import urllib.request import urllib.request
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional
from .archivar.adapter_integration import ArchivarMessageHandler from archivar.adapter_integration import ArchivarMessageHandler
from .archivar.router import RoutingDecision
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
import sys as _sys
_init_module = _sys.modules.get('rocketchat')
if _init_module is None:
_init_module = _sys.modules.get(__name__)
_TEMPLATE_MAP = getattr(_init_module, '_TEMPLATE_MAP', {})
_build_custom_buttons = getattr(_init_module, '_build_custom_buttons',
lambda labels, prefix='', style='default': [])
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
@@ -36,13 +45,18 @@ if not logger.handlers:
logger.propagate = False # Don't double-log to root logger.propagate = False # Don't double-log to root
# ── Virtual Room Translation ────────────────────────────────────────── # ── Virtual Room Translation ──────────────────────────────────────────
# Global dict keyed by virtual chat_id (e.g. "user:alice") that tracks # ContextVar tracks the real Rocket.Chat room_id that triggered the current
# the real Rocket.Chat room_id for the current agent turn. # agent turn, so send() can route the response back to the correct room even
# ContextVars were asyncio-task-local and invisible to the agent task, # though the Hermes session uses a synthetic user-based chat_id.
# causing send() to fall back to the home channel → error-not-allowed. # This is the mechanism that makes "one agent for all rooms" work
# This dict is shared across all asyncio tasks in the same process. # without touching Hermes Core.
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {origin_room, thematic_target} _CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
_room_context_lock = threading.Lock() "_rocketchat_origin_room", default=""
)
_THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
"_rocketchat_thematic_target_room", default=""
)
# Globaler Monoton-Zähler für Archivar-Fragen # Globaler Monoton-Zähler für Archivar-Fragen
import threading import threading
@@ -646,10 +660,7 @@ class RocketChatAdapter(BasePlatformAdapter):
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ── # ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der # Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum). # aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
virtual_chat_id = f"user:{username}" _THEMATIC_TARGET_ROOM.set("")
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["thematic_target"] = ""
# ── CLARIFY Response Handling ─────────────────────────────────── # ── CLARIFY Response Handling ───────────────────────────────────
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other # Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
@@ -765,10 +776,7 @@ class RocketChatAdapter(BasePlatformAdapter):
target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}" target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}"
if move_req.get("username"): if move_req.get("username"):
self.rest.post_message(move_req["target_room"], target_txt) self.rest.post_message(move_req["target_room"], target_txt)
virtual_chat_id = f"user:{move_req['username']}" _CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["origin_room"] = move_req["target_room"]
forwarded = True forwarded = True
feedback_type = "confirm" feedback_type = "confirm"
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"): elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
@@ -787,8 +795,7 @@ class RocketChatAdapter(BasePlatformAdapter):
await self.archivar.handle_feedback_response( await self.archivar.handle_feedback_response(
message_id=move_req["message_id"], message_id=move_req["message_id"],
user_id=user_id, user_id=user_id,
feedback_type=feedback_type, feedback_type=feedback_type
username=username
) )
return # Move-Request verarbeitet — keine weitere Verarbeitung return # Move-Request verarbeitet — keine weitere Verarbeitung
@@ -811,42 +818,13 @@ class RocketChatAdapter(BasePlatformAdapter):
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8]) logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
elif room_type == "d" and is_auftrag: elif room_type == "d" and is_auftrag:
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username) logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
else:
# ── RoutingWiderspruchDetector: VOR classify_and_route() ──
# NUR wenn KEIN Button-Feedback aktiv (kein pending move-request).
# Button = geregelter Standard, Text = Fall ohne Button.
contradiction = self.archivar.detect_routing_contradiction(
text, origin_room_id=room_id
)
if contradiction:
logger.info(
"[rocketchat] Routing-Widerspruch in %s: type=%s conf=%.2f — "
"stay_in_room + [WIDERSPRUCH]-Präfix",
room_id[:8],
contradiction.contradiction_type,
contradiction.confidence,
)
# Decision überschreiben: stay_in_room
decision = RoutingDecision(
category="direct_question",
target_room="",
confidence=contradiction.confidence,
stay_in_room=True,
)
category = decision.category
# [WIDERSPRUCH]-Präfix setzen — Nachricht NICHT schlucken
text = f"[WIDERSPRUCH] {text}"
# Kein Routing, keine Move-Requests — direkt zum Agenten
else: else:
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id) decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
if decision and decision.category: if decision and decision.category:
category = decision.category category = decision.category
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ────── # ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
if hasattr(decision, 'target_room') and decision.target_room: if hasattr(decision, 'target_room') and decision.target_room:
virtual_chat_id = f"user:{username}" _THEMATIC_TARGET_ROOM.set(decision.target_room)
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["thematic_target"] = decision.target_room
global _question_counter global _question_counter
with _question_counter_lock: with _question_counter_lock:
_question_counter += 1 _question_counter += 1
@@ -908,7 +886,6 @@ class RocketChatAdapter(BasePlatformAdapter):
if is_auftrag: if is_auftrag:
# Typ 2: Native Action-Buttons (Button-Garantie) # Typ 2: Native Action-Buttons (Button-Garantie)
try: try:
from . import _build_custom_buttons
move_prefix = f"MOVE_REQ:{room_id}" move_prefix = f"MOVE_REQ:{room_id}"
buttons = _build_custom_buttons( buttons = _build_custom_buttons(
["1️⃣ Rüber", "2️⃣ Hier", "3️⃣ Nein"], ["1️⃣ Rüber", "2️⃣ Hier", "3️⃣ Nein"],
@@ -961,20 +938,14 @@ class RocketChatAdapter(BasePlatformAdapter):
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert." note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
self.rest.post_message(room_id, note) self.rest.post_message(room_id, note)
# Agent soll im Zielraum antworten, nicht im Ursprungsraum # Agent soll im Zielraum antworten, nicht im Ursprungsraum
virtual_chat_id = f"user:{username}" _CURRENT_ORIGIN_ROOM.set(decision.target_room)
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["origin_room"] = decision.target_room
forwarded = True forwarded = True
# Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy # Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy
# ── _CURRENT_ORIGIN_ROOM setzen ────────────────────────────────── # ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
if not forwarded: if not forwarded:
virtual_chat_id = f"user:{username}" _CURRENT_ORIGIN_ROOM.set(room_id)
with _room_context_lock:
ctx = _room_context.setdefault(virtual_chat_id, {})
ctx["origin_room"] = room_id
# ── Virtual Room Translation ───────────────────────────────── # ── Virtual Room Translation ─────────────────────────────────
# Replace room-based chat_id with user-based virtual chat_id. # Replace room-based chat_id with user-based virtual chat_id.
@@ -997,9 +968,7 @@ class RocketChatAdapter(BasePlatformAdapter):
message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ── # ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
with _room_context_lock: target_room_id = _THEMATIC_TARGET_ROOM.get()
ctx = _room_context.get(virtual_chat_id, {})
target_room_id = ctx.get("thematic_target", "")
if target_room_id: if target_room_id:
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…") target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
with _question_counter_lock: with _question_counter_lock:
@@ -1089,7 +1058,7 @@ class RocketChatAdapter(BasePlatformAdapter):
if not self.rest.auth_token: if not self.rest.auth_token:
return False return False
from . import _build_custom_buttons # _build_custom_buttons available via top-level sys.modules access
actions = payload.get("actions", []) actions = payload.get("actions", [])
if not actions: if not actions:
@@ -1180,7 +1149,7 @@ class RocketChatAdapter(BasePlatformAdapter):
self.archivar._stats["onboarding_active"] = True self.archivar._stats["onboarding_active"] = True
# Baue Nachricht mit Emoji-Nummern-Referenzen # Baue Nachricht mit Emoji-Nummern-Referenzen
from . import _build_custom_buttons # _build_custom_buttons available via top-level sys.modules access
# Emoji-Zahlen für bis zu 10 Räume # Emoji-Zahlen für bis zu 10 Räume
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
@@ -1410,8 +1379,8 @@ class RocketChatAdapter(BasePlatformAdapter):
) )
# Speichern + reload # Speichern + reload
from .archivar.room_map import RoomMap from archivar.room_map import RoomMap
from .archivar.config import ROOM_MAP_PATH from archivar.config import ROOM_MAP_PATH
from pathlib import Path from pathlib import Path
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH)) RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
self.archivar._room_map.reload() self.archivar._room_map.reload()
@@ -1489,7 +1458,6 @@ class RocketChatAdapter(BasePlatformAdapter):
remaining.append(missing[i]) remaining.append(missing[i])
if remaining: if remaining:
from . import _build_custom_buttons
lines = [f"📋 Noch {len(remaining)} Raum/Räume übrig:", lines = [f"📋 Noch {len(remaining)} Raum/Räume übrig:",
""] ""]
for i, room in enumerate(remaining, 1): for i, room in enumerate(remaining, 1):
@@ -1591,12 +1559,12 @@ class RocketChatAdapter(BasePlatformAdapter):
def _set_catch_all(self, room_id: str) -> None: def _set_catch_all(self, room_id: str) -> None:
"""Setzt den angegebenen Raum als alleinigen Catch-All.""" """Setzt den angegebenen Raum als alleinigen Catch-All."""
from .archivar.config import ROOM_MAP_PATH from archivar.config import ROOM_MAP_PATH
from pathlib import Path from pathlib import Path
for rid, entry in self.archivar._room_map.rooms.items(): for rid, entry in self.archivar._room_map.rooms.items():
entry.catch_all = (rid == room_id) entry.catch_all = (rid == room_id)
# Persistieren # Persistieren
from .archivar.room_map import RoomMap from archivar.room_map import RoomMap
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH)) RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
self.archivar._room_map.reload() self.archivar._room_map.reload()
@@ -1659,14 +1627,14 @@ class RocketChatAdapter(BasePlatformAdapter):
if chat_id.startswith("user:"): if chat_id.startswith("user:"):
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen # Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie). # Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
with _room_context_lock: thematic_target = _THEMATIC_TARGET_ROOM.get()
ctx = _room_context.get(chat_id, {}) if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
thematic_target = ctx.get("thematic_target", "")
origin = ctx.get("origin_room", "")
if thematic_target and thematic_target != origin:
real_room_id = thematic_target real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
elif origin: else:
# Priority 1: ContextVar from the message that triggered this turn
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
real_room_id = origin real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
else: else:
@@ -1721,7 +1689,13 @@ class RocketChatAdapter(BasePlatformAdapter):
# Handle interaction templates via metadata # Handle interaction templates via metadata
attachments = None attachments = None
if metadata and metadata.get("template"): if metadata and metadata.get("template"):
from . import _TEMPLATE_MAP, _build_custom_buttons # Use sys.modules to access __init__ symbols (plugin loaded as flat module)
import sys as _sys
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
if _init is None:
_init = _sys.modules.get('rocketchat')
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
template_name = metadata.get("template") template_name = metadata.get("template")
question_id = metadata.get("question_id", "") question_id = metadata.get("question_id", "")
if template_name == "custom" and metadata.get("custom_buttons"): if template_name == "custom" and metadata.get("custom_buttons"):
@@ -1866,14 +1840,14 @@ class RocketChatAdapter(BasePlatformAdapter):
if chat_id.startswith("user:"): if chat_id.startswith("user:"):
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen # Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie). # Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
with _room_context_lock: thematic_target = _THEMATIC_TARGET_ROOM.get()
ctx = _room_context.get(chat_id, {}) if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
thematic_target = ctx.get("thematic_target", "")
origin = ctx.get("origin_room", "")
if thematic_target and thematic_target != origin:
real_room_id = thematic_target real_room_id = thematic_target
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
elif origin: else:
# Priority 1: ContextVar from the message that triggered this turn
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
real_room_id = origin real_room_id = origin
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
else: else:
@@ -1904,7 +1878,6 @@ class RocketChatAdapter(BasePlatformAdapter):
text += f"\n\n{option_lines}" text += f"\n\n{option_lines}"
# Build buttons with short labels to avoid truncation # Build buttons with short labels to avoid truncation
from . import _build_custom_buttons
button_labels = [str(i + 1) for i in range(len(choices))] button_labels = [str(i + 1) for i in range(len(choices))]
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}") buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")