feat: Archivar-Universalisierung A–E — env-vars, SKILL.md, Pipeline-Integration, file-download
A: config.py auf Env-Vars umgestellt (ARCHIVAR_FAKT_ROOM, _FRAGE_ROOM, _ALARM_ROOM, _CATCHALL_ROOM, _PROJECT_ROOMS)
B: adapter.py-Kommentare von BAT-Terminologie auf generisch umgeschrieben
C: archivar/SKILL.md — Hermes-Skill-Schema mit Triggern, Architektur, Konfiguration, Pitfalls
D: classify_and_route() + send_callback in _process_incoming() integriert, chat_name mit [KATEGORIE] angereichert
E: RocketChatREST.download_file() — authentifizierter Datei-Download via X-Auth-Token, kein Security-Scanner-Trigger mehr
_download_and_inline_files() inlined [FILE]-Inhalte direkt in den Prompt
This commit is contained in:
+72
-12
@@ -35,11 +35,11 @@ if not logger.handlers:
|
||||
logger.addHandler(_handler)
|
||||
logger.propagate = False # Don't double-log to root
|
||||
|
||||
# ── Option C: Virtual Room Translation ─────────────────────────────────────
|
||||
# ── 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
|
||||
# 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=""
|
||||
@@ -133,6 +133,30 @@ class RocketChatREST:
|
||||
}, data=payload)
|
||||
return bool(r and r.get("success"))
|
||||
|
||||
def download_file(self, file_id: str, filename: str) -> Optional[str]:
|
||||
"""Download a file from Rocket.Chat using the authenticated REST client.
|
||||
|
||||
Returns the file content as a string (text files) or None on failure.
|
||||
Uses the existing authToken — no security scanner triggers.
|
||||
"""
|
||||
if not self.auth_token:
|
||||
return None
|
||||
url = f"{self.base_url}/file-upload/{file_id}/{filename}"
|
||||
req = urllib.request.Request(url, headers={
|
||||
"X-Auth-Token": self.auth_token,
|
||||
"X-User-Id": self.user_id,
|
||||
})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
content = resp.read()
|
||||
try:
|
||||
return content.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return content.decode("latin-1")
|
||||
except Exception as e:
|
||||
logger.debug("File download failed: %s", e)
|
||||
return None
|
||||
|
||||
|
||||
class DDPClient:
|
||||
PING_INTERVAL = 8.0
|
||||
@@ -379,7 +403,7 @@ 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.
|
||||
# User-based room mapping for virtual chat_id translation.
|
||||
# Key: "user:<username>", Value: list of real room_ids for that user.
|
||||
# Built during connect() from REST get_rooms.
|
||||
self._user_rooms: Dict[str, List[str]] = {}
|
||||
@@ -389,7 +413,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._last_ddp_ping_ok = False
|
||||
self._running = False
|
||||
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||||
self.archivar = ArchivarMessageHandler()
|
||||
self.archivar = ArchivarMessageHandler(send_callback=self._send_via_archivar)
|
||||
|
||||
async def connect(self) -> bool:
|
||||
if not self.base_url or not self.user or not self.password:
|
||||
@@ -417,7 +441,7 @@ 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.
|
||||
# Build user→rooms map for virtual chat_id translation.
|
||||
# Each Rocket.Chat user gets a synthetic "user:<username>" chat_id that
|
||||
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
||||
# session per user across all rooms, enabling shared context.
|
||||
@@ -542,12 +566,22 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
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 ─────────────────────────
|
||||
# ── Archivar-Klassifikation ──────────────────────────────────
|
||||
# Klassifiziere die Nachricht und reichere den Context an
|
||||
category = ""
|
||||
try:
|
||||
decision = await self.archivar.classify_and_route(text)
|
||||
if decision and decision.category:
|
||||
category = decision.category
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||
|
||||
# ── 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
|
||||
# DM with alice: room_id=ABC123 → chat_id="user:alice"
|
||||
# #Project-Chat: room_id=XYZ789 → chat_id="user:alice"
|
||||
# Both get the same session key.
|
||||
virtual_chat_id = f"user:{username}"
|
||||
# Track the REAL room for send() to route the response back
|
||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||
@@ -566,7 +600,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
source = SessionSource(
|
||||
platform=Platform("rocketchat"),
|
||||
chat_id=virtual_chat_id, # ← user-based instead of room-based
|
||||
chat_name=f"{room_name} (via @{username})", # real origin visible in system prompt
|
||||
chat_name=f"{room_name} (via @{username})" + (f" [{category}]" if category else ""),
|
||||
user_id=username,
|
||||
user_name=username,
|
||||
chat_type="dm", # ← force DM to bypass group isolation in Core
|
||||
@@ -583,6 +617,32 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
except Exception as e:
|
||||
logger.error("[rocketchat] handle_message error: %s", e)
|
||||
|
||||
async def _send_via_archivar(self, room_id: str, text: str) -> bool:
|
||||
"""Callback for Archivar forwarding — sends a message copy to a target room."""
|
||||
if not self.rest.auth_token:
|
||||
return False
|
||||
return self.rest.post_message(room_id, text)
|
||||
|
||||
async def _download_and_inline_files(self, text: str) -> str:
|
||||
"""Download files referenced as [FILE] markers and inline their content."""
|
||||
import re
|
||||
_file_re = re.compile(
|
||||
r'\[FILE\]\s+(?P<name>[^\n]+?)\s+\((?P<type>[^)]+)\)\n'
|
||||
r'Download:\s+\S+/file-upload/(?P<fid>[^/]+)/(?P<fname>\S+)'
|
||||
)
|
||||
matches = list(_file_re.finditer(text))
|
||||
if not matches:
|
||||
return text
|
||||
for m in matches:
|
||||
fid = m.group("fid")
|
||||
fname = m.group("fname")
|
||||
content = self.rest.download_file(fid, fname)
|
||||
if content:
|
||||
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
||||
text += block
|
||||
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
||||
return text
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
self._mark_disconnected()
|
||||
self._shutdown_event.set()
|
||||
@@ -604,8 +664,8 @@ 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").
|
||||
# ── 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.
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
|
||||
Reference in New Issue
Block a user