diff --git a/plugin/adapter.py b/plugin/adapter.py index 9606059..1b021ec 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -9,6 +9,7 @@ Zero external dependencies — stdlib only. """ import asyncio +import contextvars import json import logging import os @@ -32,6 +33,16 @@ if not logger.handlers: logger.addHandler(_handler) logger.propagate = False # Don't double-log to root +# ── Option C: Virtual Room Translation ───────────────────────────────────── +# 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 single mechanism that makes "ein Bernd für alle Räume" work +# without touching Hermes Core. +_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( + "_rocketchat_origin_room", default="" +) + try: from gateway.platforms.base import ( BasePlatformAdapter, @@ -366,6 +377,10 @@ class RocketChatAdapter(BasePlatformAdapter): # Clarify-Queue: tracks pending button questions per chat_id # so incoming replies can be correlated with the original question. self._pending_clarifies: Dict[str, dict] = {} + # Option C: user-based room mapping for virtual chat_id translation. + # Key: "user:", Value: list of real room_ids for that user. + # Built during connect() from REST get_rooms. + self._user_rooms: Dict[str, List[str]] = {} # Health-check state self._last_server_activity = 0.0 # ts of last DDP ping/pong or message self._health_check_timer: Optional[threading.Timer] = None @@ -398,6 +413,31 @@ class RocketChatAdapter(BasePlatformAdapter): self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]} logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"]) logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms)) + # Option C: Build user→rooms map for virtual chat_id translation. + # Each Rocket.Chat user gets a synthetic "user:" chat_id that + # maps to all rooms they participate in. This ensures Hermes creates ONE + # session per user across all rooms, enabling shared context. + self._user_rooms.clear() + for room in self._rooms: + rid = room["id"] + t = room["type"] + if t == "d": + usernames = [u.lower() for u in room.get("usernames", [])] + for uname in usernames: + if uname != (self.user or "").lower(): + virt = f"user:{uname}" + if virt not in self._user_rooms: + self._user_rooms[virt] = [] + if rid not in self._user_rooms[virt]: + self._user_rooms[virt].append(rid) + else: + # For groups/channels: query members via REST to build mappings. + # Fallback: use a generic group-based virtual chat_id. + # We still track the room so proaktive sends have a target. + pass # Group mapping handled on-demand in send() + logger.info("[rocketchat] Built user-room map: %d users, %s", + len(self._user_rooms), + {k: f"{len(v)} rooms" for k, v in self._user_rooms.items()}) self._mark_connected() self._running = True self._listen_task = asyncio.create_task(self._listen_loop()) @@ -448,20 +488,37 @@ class RocketChatAdapter(BasePlatformAdapter): # Update activity self._last_activity = time.time() room_name = self._room_info.get(room_id, {}).get("name", room_id) - logger.info("[rocketchat] Message from %s in %s: %s", username, room_name, text[:80]) - + room_type = self._room_info.get(room_id, {}).get("type", "unknown") + logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80]) + + # ── Option C: Virtual Room Translation ───────────────────────── + # Replace room-based chat_id with user-based virtual chat_id. + # This collapses all rooms per user into ONE Hermes session: + # DM with andreas: room_id=ABC123 → chat_id="user:andreas" + # #BAT-Team: room_id=XYZ789 → chat_id="user:andreas" + # Both get the same session key: agent:main:rocketchat:dm:user:andreas + virtual_chat_id = f"user:{username}" + # Track the REAL room for send() to route the response back + _CURRENT_ORIGIN_ROOM.set(room_id) + + # Ensure this user→room mapping is recorded for proaktive sends + if virtual_chat_id not in self._user_rooms: + self._user_rooms[virtual_chat_id] = [] + if room_id not in self._user_rooms[virtual_chat_id]: + self._user_rooms[virtual_chat_id].append(room_id) + # Dispatch to gateway handler via base-class handle_message try: from datetime import datetime - + message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT source = SessionSource( platform=Platform("rocketchat"), - chat_id=room_id, - chat_name=room_name, + chat_id=virtual_chat_id, # ← user-based instead of room-based + chat_name=f"{room_name} (via @{username})", # real origin visible in system prompt user_id=username, user_name=username, - chat_type="dm" if self._room_info.get(room_id, {}).get("type") == "d" else "group", + chat_type="dm", # ← force DM to bypass group isolation in Core ) event = MessageEvent( text=text, @@ -496,6 +553,26 @@ class RocketChatAdapter(BasePlatformAdapter): if not self.rest.auth_token: return SendResult(success=False, error="Not authenticated") + # ── Option C: Virtual → Real Room Translation ───────────────── + # chat_id from Hermes session is virtual (e.g. "user:andreas"). + # We must resolve it to a real Rocket.Chat room_id for REST API. + real_room_id = chat_id + if chat_id.startswith("user:"): + # 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: + # 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}") + # ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ── # This allows the agent to request buttons by embedding markup in its # response text, without requiring the gateway to pass metadata. @@ -573,7 +650,7 @@ class RocketChatAdapter(BasePlatformAdapter): _expected = ["ok", "okay", "verstanden", "alles klar"] elif _tmpl == "custom" and metadata.get("custom_buttons"): _expected = [b.lower() for b in metadata["custom_buttons"]] - self._pending_clarifies[chat_id] = { + self._pending_clarifies[real_room_id] = { "question_id": _qid, "template": _tmpl, "expected": _expected, @@ -581,7 +658,7 @@ class RocketChatAdapter(BasePlatformAdapter): "original_text": content, } - success = self.rest.post_message(chat_id, content, attachments=attachments) + success = self.rest.post_message(real_room_id, content, attachments=attachments) if success: return SendResult(success=True, message_id=str(int(time.time() * 1000))) return SendResult(success=False, error="chat.postMessage failed")