fix(adapter): remove last 2 relative imports — use top-level sys.modules access
This commit is contained in:
+100
-127
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import contextvars
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -22,8 +23,16 @@ import time
|
||||
import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from .archivar.adapter_integration import ArchivarMessageHandler
|
||||
from .archivar.router import RoutingDecision
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
|
||||
# ── 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.setLevel(logging.INFO)
|
||||
@@ -36,13 +45,18 @@ if not logger.handlers:
|
||||
logger.propagate = False # Don't double-log to root
|
||||
|
||||
# ── Virtual Room Translation ──────────────────────────────────────────
|
||||
# Global dict keyed by virtual chat_id (e.g. "user:alice") that tracks
|
||||
# the real Rocket.Chat room_id for the current agent turn.
|
||||
# ContextVars were asyncio-task-local and invisible to the agent task,
|
||||
# causing send() to fall back to the home channel → error-not-allowed.
|
||||
# This dict is shared across all asyncio tasks in the same process.
|
||||
_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {origin_room, thematic_target}
|
||||
_room_context_lock = threading.Lock()
|
||||
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
|
||||
# agent turn, so send() can route the response back to the correct room even
|
||||
# though the Hermes session uses a synthetic user-based chat_id.
|
||||
# This is the mechanism that makes "one agent for all rooms" work
|
||||
# without touching Hermes Core.
|
||||
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||
"_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
|
||||
import threading
|
||||
@@ -646,10 +660,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ──
|
||||
# Verhindert dass der Zielraum der VORHERIGEN Nachricht an der
|
||||
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
|
||||
virtual_chat_id = f"user:{username}"
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.setdefault(virtual_chat_id, {})
|
||||
ctx["thematic_target"] = ""
|
||||
_THEMATIC_TARGET_ROOM.set("")
|
||||
|
||||
# ── CLARIFY Response Handling ───────────────────────────────────
|
||||
# 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']}"
|
||||
if move_req.get("username"):
|
||||
self.rest.post_message(move_req["target_room"], target_txt)
|
||||
virtual_chat_id = f"user:{move_req['username']}"
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.setdefault(virtual_chat_id, {})
|
||||
ctx["origin_room"] = move_req["target_room"]
|
||||
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
|
||||
forwarded = True
|
||||
feedback_type = "confirm"
|
||||
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
|
||||
@@ -787,8 +795,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self.archivar.handle_feedback_response(
|
||||
message_id=move_req["message_id"],
|
||||
user_id=user_id,
|
||||
feedback_type=feedback_type,
|
||||
username=username
|
||||
feedback_type=feedback_type
|
||||
)
|
||||
return # Move-Request verarbeitet — keine weitere Verarbeitung
|
||||
|
||||
@@ -812,67 +819,38 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
elif room_type == "d" and is_auftrag:
|
||||
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,
|
||||
)
|
||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||
if decision and decision.category:
|
||||
category = decision.category
|
||||
# [WIDERSPRUCH]-Präfix setzen — Nachricht NICHT schlucken
|
||||
text = f"[WIDERSPRUCH] {text}"
|
||||
# Kein Routing, keine Move-Requests — direkt zum Agenten
|
||||
else:
|
||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||
if decision and decision.category:
|
||||
category = decision.category
|
||||
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
||||
if hasattr(decision, 'target_room') and decision.target_room:
|
||||
virtual_chat_id = f"user:{username}"
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.setdefault(virtual_chat_id, {})
|
||||
ctx["thematic_target"] = decision.target_room
|
||||
global _question_counter
|
||||
with _question_counter_lock:
|
||||
_question_counter += 1
|
||||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||||
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
||||
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
|
||||
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
|
||||
if (getattr(decision, 'move_request_sent', False)
|
||||
and hasattr(decision, 'target_room')
|
||||
and decision.target_room):
|
||||
self._pending_move_requests[room_id] = {
|
||||
'text': text,
|
||||
'origin_room': room_id,
|
||||
'target_room': decision.target_room,
|
||||
'target_name': getattr(
|
||||
decision, 'move_request_target_name', 'Zielraum'),
|
||||
'username': username,
|
||||
'message_id': msg_id,
|
||||
}
|
||||
# Lernsystem: Keywords für Feedback-Loop speichern
|
||||
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
|
||||
self.archivar._routed_messages[msg_id] = {
|
||||
"keywords": decision.matched_keywords,
|
||||
"target_room": decision.target_room,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
# ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ──────
|
||||
if hasattr(decision, 'target_room') and decision.target_room:
|
||||
_THEMATIC_TARGET_ROOM.set(decision.target_room)
|
||||
global _question_counter
|
||||
with _question_counter_lock:
|
||||
_question_counter += 1
|
||||
# ── Ende Kontext-Weitergabe ──────────────────────────────
|
||||
# Archivar v4 Move-Request: _pending_move_requests befüllen, damit
|
||||
# der Button-Response-Handler (lines 717-764) die Antwort korrekt
|
||||
# verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann.
|
||||
if (getattr(decision, 'move_request_sent', False)
|
||||
and hasattr(decision, 'target_room')
|
||||
and decision.target_room):
|
||||
self._pending_move_requests[room_id] = {
|
||||
'text': text,
|
||||
'origin_room': room_id,
|
||||
'target_room': decision.target_room,
|
||||
'target_name': getattr(
|
||||
decision, 'move_request_target_name', 'Zielraum'),
|
||||
'username': username,
|
||||
'message_id': msg_id,
|
||||
}
|
||||
# Lernsystem: Keywords für Feedback-Loop speichern
|
||||
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
|
||||
self.archivar._routed_messages[msg_id] = {
|
||||
"keywords": decision.matched_keywords,
|
||||
"target_room": decision.target_room,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning("[rocketchat] Archivar classify_and_route() timed out")
|
||||
with _question_counter_lock:
|
||||
@@ -908,7 +886,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if is_auftrag:
|
||||
# Typ 2: Native Action-Buttons (Button-Garantie)
|
||||
try:
|
||||
from . import _build_custom_buttons
|
||||
move_prefix = f"MOVE_REQ:{room_id}"
|
||||
buttons = _build_custom_buttons(
|
||||
["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."
|
||||
self.rest.post_message(room_id, note)
|
||||
# Agent soll im Zielraum antworten, nicht im Ursprungsraum
|
||||
virtual_chat_id = f"user:{username}"
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.setdefault(virtual_chat_id, {})
|
||||
ctx["origin_room"] = decision.target_room
|
||||
_CURRENT_ORIGIN_ROOM.set(decision.target_room)
|
||||
forwarded = True
|
||||
|
||||
# Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy
|
||||
|
||||
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
|
||||
if not forwarded:
|
||||
virtual_chat_id = f"user:{username}"
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.setdefault(virtual_chat_id, {})
|
||||
ctx["origin_room"] = room_id
|
||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||
|
||||
# ── Virtual Room Translation ─────────────────────────────────
|
||||
# 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
|
||||
# ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ──
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.get(virtual_chat_id, {})
|
||||
target_room_id = ctx.get("thematic_target", "")
|
||||
target_room_id = _THEMATIC_TARGET_ROOM.get()
|
||||
if target_room_id:
|
||||
target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…")
|
||||
with _question_counter_lock:
|
||||
@@ -1089,7 +1058,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if not self.rest.auth_token:
|
||||
return False
|
||||
|
||||
from . import _build_custom_buttons
|
||||
# _build_custom_buttons available via top-level sys.modules access
|
||||
|
||||
actions = payload.get("actions", [])
|
||||
if not actions:
|
||||
@@ -1180,7 +1149,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar._stats["onboarding_active"] = True
|
||||
|
||||
# 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_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
|
||||
@@ -1410,8 +1379,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
|
||||
# Speichern + reload
|
||||
from .archivar.room_map import RoomMap
|
||||
from .archivar.config import ROOM_MAP_PATH
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.config import ROOM_MAP_PATH
|
||||
from pathlib import Path
|
||||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||||
self.archivar._room_map.reload()
|
||||
@@ -1489,7 +1458,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
remaining.append(missing[i])
|
||||
|
||||
if remaining:
|
||||
from . import _build_custom_buttons
|
||||
lines = [f"📋 Noch {len(remaining)} Raum/Räume übrig:",
|
||||
""]
|
||||
for i, room in enumerate(remaining, 1):
|
||||
@@ -1591,12 +1559,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
def _set_catch_all(self, room_id: str) -> None:
|
||||
"""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
|
||||
for rid, entry in self.archivar._room_map.rooms.items():
|
||||
entry.catch_all = (rid == room_id)
|
||||
# Persistieren
|
||||
from .archivar.room_map import RoomMap
|
||||
from archivar.room_map import RoomMap
|
||||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||||
self.archivar._room_map.reload()
|
||||
|
||||
@@ -1659,32 +1627,32 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if chat_id.startswith("user:"):
|
||||
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
||||
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.get(chat_id, {})
|
||||
thematic_target = ctx.get("thematic_target", "")
|
||||
origin = ctx.get("origin_room", "")
|
||||
if thematic_target and thematic_target != origin:
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
elif origin:
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# Priority 1: ContextVar from the message that triggered this turn
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
|
||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||
# This allows the agent to request buttons by embedding markup in its
|
||||
@@ -1721,7 +1689,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Handle interaction templates via metadata
|
||||
attachments = None
|
||||
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")
|
||||
question_id = metadata.get("question_id", "")
|
||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||
@@ -1866,14 +1840,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if chat_id.startswith("user:"):
|
||||
# Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen
|
||||
# Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie).
|
||||
with _room_context_lock:
|
||||
ctx = _room_context.get(chat_id, {})
|
||||
thematic_target = ctx.get("thematic_target", "")
|
||||
origin = ctx.get("origin_room", "")
|
||||
if thematic_target and thematic_target != origin:
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get():
|
||||
real_room_id = thematic_target
|
||||
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
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
@@ -1904,7 +1878,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
text += f"\n\n{option_lines}"
|
||||
|
||||
# Build buttons with short labels to avoid truncation
|
||||
from . import _build_custom_buttons
|
||||
button_labels = [str(i + 1) for i in range(len(choices))]
|
||||
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user