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:"):
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
name: archivar
|
||||
description: >
|
||||
Archivar — Embedding-basierte Nachrichten-Klassifikation und Routing im Rocket.Chat-Plugin.
|
||||
Klassifiziert eingehende Nachrichten in FAKT, FRAGE, ALARM und leitet sie in konfigurierte
|
||||
Zielräume weiter. Nutzt nomic-embed-text via Ollama (localhost:11434) mit Keyword-Fallback.
|
||||
trigger: >
|
||||
archivar, klassifikation, routing, nachrichten routing, klassifizierung,
|
||||
fakt frage alarm, embedding, nomic-embed-text, kategorie, weiterleitung,
|
||||
in welchen raum, wohin ging, zielraum, verteiler, konfidenz, fallback,
|
||||
archiv, archivar stats, archivar statistik, catch-all, catch all
|
||||
version: 1.0.0
|
||||
date: 2026-06-03
|
||||
---
|
||||
|
||||
# Archivar — Nachrichten-Klassifikation & Routing
|
||||
|
||||
## Übersicht
|
||||
|
||||
Der Archivar ist ein Submodul des Rocket.Chat-Plugins, das eingehende Nachrichten
|
||||
automatisch klassifiziert und optional in konfigurierte Zielräume weiterleitet.
|
||||
|
||||
**Kernfunktion:**
|
||||
- **Embedding-basierte Klassifikation** via nomic-embed-text (Ollama, localhost:11434)
|
||||
- **3 Kategorien:** FAKT (Wissen, Doku), FRAGE (Hilfe, Probleme), ALARM (Dringend, Ausfälle)
|
||||
- **Konfidenz-Schwellenwert:** 0.6 — darunter geht die Nachricht in den Catch-All-Raum
|
||||
- **Keyword-Fallback:** Wenn Ollama ausfällt, greift eine Heuristik mit deutschen + englischen Keywords
|
||||
- **Meta-Erkennung:** Fragen über den Archivar selbst werden nicht weitergeleitet
|
||||
|
||||
## Architektur
|
||||
|
||||
```
|
||||
Adapter._process_incoming()
|
||||
└─ MessageClassifier.classify()
|
||||
└─ OllamaEmbeddingClient.get_embedding()
|
||||
└─ nomic-embed-text (localhost:11434, 5s Timeout, 768-dim Vektoren)
|
||||
└─ MessageRouter.route()
|
||||
├─ FAKT → Zielraum (konfigurierbar via Env)
|
||||
├─ FRAGE → Default-Zielraum oder projektspezifischer Raum
|
||||
│ (Keyword-Matching: "plugin", "docs", "lan")
|
||||
├─ ALARM → Direktnachricht an Admin
|
||||
└─ < 0.6 → Catch-All-Raum
|
||||
```
|
||||
|
||||
## Konfiguration (Umgebungsvariablen)
|
||||
|
||||
Alle Raum-IDs werden über Umgebungsvariablen gesteuert — keine hartcodierten Werte:
|
||||
|
||||
| Variable | Zweck |
|
||||
|---|---|
|
||||
| `ARCHIVAR_FAKT_ROOM` | Zielraum für FAKT-Kategorie (z.B. Dokumentations-Wiki) |
|
||||
| `ARCHIVAR_FRAGE_ROOM` | Default-Zielraum für FRAGE-Kategorie |
|
||||
| `ARCHIVAR_ALARM_ROOM` | Zielraum für ALARM-Kategorie (Direktnachricht an Admin) |
|
||||
| `ARCHIVAR_CATCHALL_ROOM` | Fallback für unklassifizierte Nachrichten |
|
||||
| `ARCHIVAR_PROJECT_ROOMS` | JSON-Map für projektspezifisches FRAGE-Routing (z.B. `{"plugin":"ROOM_ID","docs":"ROOM_ID"}`) |
|
||||
|
||||
## Statistik
|
||||
|
||||
Der Archivar trackt laufend:
|
||||
- `total` — Gesamtzahl verarbeiteter Nachrichten
|
||||
- `classified` — erfolgreich klassifiziert
|
||||
- `catch_all` — unter Konfidenz-Schwellenwert
|
||||
- `fallback` — via Keyword-Heuristik (Ollama down)
|
||||
- `meta` — Meta-Fragen (nicht weitergeleitet)
|
||||
- `errors` — Fehler
|
||||
- `total_latency_ms` — kumulierte Latenz
|
||||
|
||||
**Abfrage:** Statistiken sind über `archivar.stats` als dict verfügbar.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **Meta-Fragen-Schutz:** Fragen wie "Wohin ging meine Nachricht?" oder "Wie arbeitet der Archivar?" werden erkannt und nicht weitergeleitet — sonst landen sie im Zielraum.
|
||||
- **Ollama-Timeout:** 5 Sekunden. Bei Überschreitung → Fallback. Erhöhen via `OLLAMA_TIMEOUT` wenn Embedding-Modell auf schwacher Hardware.
|
||||
- **Raum-IDs müssen existieren:** Wenn eine Env-Variable nicht gesetzt ist, wird die entsprechende Kategorie nicht geroutet (nur klassifiziert, kein Forward).
|
||||
- **Konfidenz 0.6:** Zu niedrig → zu viele False Positives. Zu hoch → zu viel landet im Catch-All.
|
||||
- **Embedding-Dimension:** nomic-embed-text produziert 768-dimensionale Vektoren. Anderes Modell → Dimension anpassen (`embedding_dim` in config.py).
|
||||
|
||||
## Fallback-Keywords
|
||||
|
||||
Bei Ollama-Ausfall greift diese Heuristik:
|
||||
|
||||
| Kategorie | Deutsche Keywords | Englische Keywords |
|
||||
|---|---|---|
|
||||
| FRAGE | frage, wie, was ist, warum, hilfe, problem, funktioniert nicht, kaputt, erklären | question, how, why, help, problem, explain |
|
||||
| ALARM | alarm, hilfe, dringend, sofort, notfall, ausfall, absturz, kritisch | alarm, emergency, urgent, critical, crash, sos |
|
||||
+45
-22
@@ -1,18 +1,20 @@
|
||||
"""
|
||||
Archivar-Konfiguration: Raum-Mapping, Kategorie-Texte und Ollama-Einstellungen.
|
||||
|
||||
Alle Raum-IDs stammen direkt aus der Architektur-Skizze
|
||||
(/home/bernd/Archivar_Architecture.md) und werden als kanonisch betrachtet.
|
||||
Alle Raum-IDs werden über Umgebungsvariablen gesteuert — keine hartcodierten Werte.
|
||||
OLLAMA_CONFIG bleibt auf localhost:11434 (generischer Default).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Dict
|
||||
|
||||
# ── Ollama-Konfiguration ────────────────────────────────────────────────────
|
||||
|
||||
OLLAMA_CONFIG: dict = {
|
||||
"base_url": "http://localhost:11434",
|
||||
"base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"),
|
||||
"model": "nomic-embed-text",
|
||||
"timeout": 5.0, # Sekunden — bei Überschreitung → Fallback
|
||||
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
||||
@@ -46,29 +48,50 @@ CONFIDENCE_THRESHOLD: float = 0.6
|
||||
"""Nachrichten mit confidence >= 0.6 werden klassifiziert, alles darunter
|
||||
geht an den CATCH_ALL_ROOM."""
|
||||
|
||||
# ── Raum-Mapping ────────────────────────────────────────────────────────────
|
||||
# ECHTE IDs aus der Architektur-Skizze — NICHT ERFUNDEN!
|
||||
# FRAGE ist nested: FRAGE["default"] = string, FRAGE["project_specific"] = dict
|
||||
# ── Raum-Mapping (via Env-Vars) ─────────────────────────────────────────────
|
||||
# Alle Raum-IDs werden aus Umgebungsvariablen gelesen.
|
||||
# Falls nicht gesetzt → None (Router sendet dann nur Klassifikation, kein Routing).
|
||||
#
|
||||
# ARCHIVAR_FAKT_ROOM — Zielraum für FAKT-Kategorie (z.B. Dokumentation/Wiki)
|
||||
# ARCHIVAR_FRAGE_ROOM — Default-Zielraum für FRAGE-Kategorie
|
||||
# ARCHIVAR_ALARM_ROOM — Zielraum für ALARM-Kategorie (DM mit Admin)
|
||||
# ARCHIVAR_CATCHALL_ROOM — Fallback für unklassifizierte Nachrichten
|
||||
# ARCHIVAR_PROJECT_ROOMS — JSON-Map für projektspezifisches FRAGE-Routing
|
||||
# Beispiel: {"plugin":"ROOM_ID","docs":"ROOM_ID"}
|
||||
|
||||
ROOM_MAPPING: dict = {
|
||||
# Protonbridge-Plugin: Catch-All / Wissensdatenbank
|
||||
"FAKT": "69f8beaef06dba03be82f9fc",
|
||||
def _resolve_room_mapping() -> dict:
|
||||
"""Baut ROOM_MAPPING aus Umgebungsvariablen zusammen."""
|
||||
mapping: dict = {}
|
||||
|
||||
# Fragen-Routing — default: BAT-Team, projektspezifisch weiterleitbar
|
||||
"FRAGE": {
|
||||
"default": "6a049d493a62ef8f1ead2320", # #BAT-Team
|
||||
"project_specific": {
|
||||
"plugin": "6a19b0ff02aeecd36b1aa16c", # #Rocketchat-Plugin
|
||||
"lan": "6a1c56d4b73efec2bebec2db", # #LAN-Dokumentation
|
||||
},
|
||||
},
|
||||
fakt = os.getenv("ARCHIVAR_FAKT_ROOM", "").strip()
|
||||
if fakt:
|
||||
mapping["FAKT"] = fakt
|
||||
|
||||
# DM mit Andreas — direkter Alarm-Kanal
|
||||
"ALARM": "69f4e777f06dba03be82dce7",
|
||||
}
|
||||
frage_default = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
|
||||
frage_entry: dict = {}
|
||||
if frage_default:
|
||||
frage_entry["default"] = frage_default
|
||||
|
||||
# Catch-All-Raum: wohin unklassifizierbare Nachrichten gehen
|
||||
CATCH_ALL_ROOM: str = "69f8beaef06dba03be82f9fc" # Protonbridge-Plugin
|
||||
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
|
||||
if project_json:
|
||||
try:
|
||||
frage_entry["project_specific"] = json.loads(project_json)
|
||||
except json.JSONDecodeError:
|
||||
pass # ignorieren, kein projektspezifisches Routing
|
||||
|
||||
if frage_entry:
|
||||
mapping["FRAGE"] = frage_entry
|
||||
|
||||
alarm = os.getenv("ARCHIVAR_ALARM_ROOM", "").strip()
|
||||
if alarm:
|
||||
mapping["ALARM"] = alarm
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
ROOM_MAPPING: dict = _resolve_room_mapping()
|
||||
|
||||
CATCH_ALL_ROOM: str = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip() or None
|
||||
|
||||
# ── Fallback-Keyword-Heuristik ──────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in New Issue
Block a user