Compare commits
32 Commits
v2.1.0
..
58f00c0c23
| Author | SHA1 | Date | |
|---|---|---|---|
| 58f00c0c23 | |||
| 1bb3f52fad | |||
| 65a3baa3e5 | |||
| a3f67775ab | |||
| fa2a24f747 | |||
| be917afcbd | |||
| a078620827 | |||
| b5a43223ac | |||
| e5a32abf5c | |||
| 4b2e933529 | |||
| f509710193 | |||
| c2ded4ab9a | |||
| 4af89ce13e | |||
| 7364ae3333 | |||
| 4ef07a14b9 | |||
| 7eac6b7dba | |||
| c4775ca99e | |||
| d7ce3afcd0 | |||
| 70008660fc | |||
| ccce90fdb0 | |||
| 886e566e77 | |||
| abe93cc2dc | |||
| 1c7b82e27f | |||
| 7a0abc465a | |||
| d01eded6ff | |||
| 13a87fb233 | |||
| d6b30d8d87 | |||
| f54f90be5b | |||
| bb8623aed5 | |||
| e3dc543af5 | |||
| 88b7149dd1 | |||
| e6eddcd3da |
@@ -102,6 +102,14 @@ GATEWAY_ALLOW_ALL_USERS=true
|
|||||||
- Bot user account on the Rocket.Chat server
|
- Bot user account on the Rocket.Chat server
|
||||||
- Python 3.10+ (hermes-agent venv)
|
- Python 3.10+ (hermes-agent venv)
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Cause | Fix |
|
||||||
|
|---------|-------|-----|
|
||||||
|
| `No module named 'hermes_plugins.rocketchat_platform.tools'` | `__init__.py` has hard `from .tools import register_tools` but `tools.py` missing | Wrap import in `try/except ImportError` and guard `register_tools(ctx)` call |
|
||||||
|
| `Failed to load plugin 'rocketchat-platform': No module named 'archivar'` | Plugin submodule uses **absolute imports** (`from archivar.X import Y`) — these only work when the module is on global `sys.path`, not in Hermes' Plugin-Loader context | **All imports within the plugin package MUST be relative.** Rule: `from archivar.X` → `from .X` (inside submodule), `from archivar.X` → `from .archivar.X` (from `adapter.py`). Affects ALL `.py` files in the submodule. 2026-06-03: 11 imports in 5 files affected |
|
||||||
|
| Gateway shows `No adapter available for rocketchat`, only Telegram active | Plugin loading failed silently — check `errors.log` for the exact import error | Fix the import, then `systemctl --user restart hermes-gateway`. Verify: `journalctl --user -u hermes-gateway | grep "Subscribed to"` |
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
[Unlicense](LICENSE) — Public Domain. See [LICENSE](LICENSE).
|
[Unlicense](LICENSE) — Public Domain. See [LICENSE](LICENSE).
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ The agent uses `send_message` with a `metadata` dict. The adapter converts this
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
send_message(
|
send_message(
|
||||||
target="rocketchat:protonbridge",
|
target="rocketchat:my-room",
|
||||||
text="Should I proceed?",
|
text="Should I proceed?",
|
||||||
metadata={
|
metadata={
|
||||||
"template": "custom",
|
"template": "custom",
|
||||||
@@ -90,7 +90,7 @@ Without it, a late click on an old button creates silent context errors. Always
|
|||||||
```python
|
```python
|
||||||
# Step 1: Choose format
|
# Step 1: Choose format
|
||||||
send_message(
|
send_message(
|
||||||
target="rocketchat:protonbridge",
|
target="rocketchat:my-room",
|
||||||
text="Which export format?",
|
text="Which export format?",
|
||||||
metadata={
|
metadata={
|
||||||
"template": "custom",
|
"template": "custom",
|
||||||
@@ -103,7 +103,7 @@ send_message(
|
|||||||
|
|
||||||
# Step 2: Choose destination
|
# Step 2: Choose destination
|
||||||
send_message(
|
send_message(
|
||||||
target="rocketchat:protonbridge",
|
target="rocketchat:my-room",
|
||||||
text="Where to send the CSV?",
|
text="Where to send the CSV?",
|
||||||
metadata={
|
metadata={
|
||||||
"template": "custom",
|
"template": "custom",
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
## Problem
|
## Problem
|
||||||
|
|
||||||
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Andreas' DM und der
|
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Die Admin-DM und der
|
||||||
#BAT-Team-Raum hatten zwei unabhängige Bernd-Instanzen — doppeltes
|
#Support-Team-Raum hatten zwei unabhängige Instanzen — doppeltes
|
||||||
Informations-Management, kein gemeinsamer Kontext.
|
Informations-Management, kein gemeinsamer Kontext.
|
||||||
|
|
||||||
## Lösung: Virtuelle Raum-Übersetzung (Plugin-only)
|
## Lösung: Virtuelle Raum-Übersetzung (Plugin-only)
|
||||||
@@ -16,7 +16,7 @@ user-basierten virtuellen Chat-IDs. Keine Hermes-Core-Änderungen.
|
|||||||
### Datenfluss
|
### Datenfluss
|
||||||
|
|
||||||
```
|
```
|
||||||
EINGANG: RC-Raum (DM / #BAT-Team)
|
EINGANG: RC-Raum (DM / #Support-Team)
|
||||||
↓
|
↓
|
||||||
_adapter._process_incoming():
|
_adapter._process_incoming():
|
||||||
room_id → user:<username> als chat_id
|
room_id → user:<username> als chat_id
|
||||||
@@ -24,9 +24,9 @@ _adapter._process_incoming():
|
|||||||
chat_type=dm (umgeht group isolation in Core)
|
chat_type=dm (umgeht group isolation in Core)
|
||||||
↓
|
↓
|
||||||
Hermes Core: build_session_key()
|
Hermes Core: build_session_key()
|
||||||
→ agent:main:rocketchat:dm:user:andreas ← EIN Key für alle Räume!
|
→ agent:main:rocketchat:dm:user:admin ← EIN Key für alle Räume!
|
||||||
↓
|
↓
|
||||||
Agent antwortet mit chat_id="user:andreas"
|
Agent antwortet mit chat_id="user:admin"
|
||||||
↓
|
↓
|
||||||
_adapter.send():
|
_adapter.send():
|
||||||
ContextVar lesen → echter room_id
|
ContextVar lesen → echter room_id
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
# Archivar: Zweistufiger Klassifikator — Architektur-Skizze
|
||||||
|
|
||||||
|
**Auftraggeber:** Andreas
|
||||||
|
**Lead:** Bernd
|
||||||
|
**Datum:** 2026-06-04
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ausgangslage
|
||||||
|
|
||||||
|
### Ist-Zustand
|
||||||
|
- Reine Embedding-Klassifikation via `nomic-embed-text` (Ollama, localhost:11434)
|
||||||
|
- 3 Kategorietexte (FAKT, FRAGE, ALARM) als Referenzvektoren
|
||||||
|
- Kosinus-Ähnlichkeit mit Schwellwert 0.6
|
||||||
|
- Keyword-Fallback nur bei Ollama-Down
|
||||||
|
|
||||||
|
### Messergebnisse (04.06.2026, 14 Tests)
|
||||||
|
- **Embedding-only: 50% korrekt** (7/14)
|
||||||
|
- 3 Fehler: ALARM → FRAGE (klar dringende Nachrichten)
|
||||||
|
- 3 Fehler: FRAGE → FAKT (technisch formulierte Fragen)
|
||||||
|
- 1 Fehler: "HILFE" → FRAGE (Ein-Wort-Alarm)
|
||||||
|
|
||||||
|
### Root Cause
|
||||||
|
Das Embedding-Modell versteht keine Absicht — es vergleicht nur Wortvektor-Ähnlichkeit.
|
||||||
|
"Sicherheitslücke im DDP-Client — bitte sofort patchen" klingt für nomic-embed-text
|
||||||
|
ähnlicher zu "Dies ist eine Information..." als zu "Dies ist eine dringende Nachricht...",
|
||||||
|
weil die Kategorietexte selbst keine Schlüsselwörter enthalten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Ziel-Architektur
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ Stufe 0: Keyword- │ ~0ms, reiner String-Match
|
||||||
|
│ Vorfilter │ Fängt: "ALARM", "HILFE", "STOP",
|
||||||
|
│ (config.py erweitert)│ "red flag", "gehackt", etc.
|
||||||
|
└──────┬───────────────┘
|
||||||
|
│
|
||||||
|
│ Keyword-Treffer?
|
||||||
|
│
|
||||||
|
┌───┴───┐
|
||||||
|
│ JA │ NEIN
|
||||||
|
▼ ▼
|
||||||
|
┌─────┐ ┌──────────────────┐
|
||||||
|
│FERTIG│ │ Stufe 1: Embedding│ nomic-embed-text (30ms, 274 MB)
|
||||||
|
│<1ms │ │ Kosinus-Ähnlichkeit│ Unverändert — Honcho nutzt es weiter
|
||||||
|
└─────┘ └──────┬─────────────┘
|
||||||
|
│
|
||||||
|
│ Konfidenz ≥ 0.70?
|
||||||
|
│
|
||||||
|
┌───┴───┐
|
||||||
|
│ JA │ NEIN
|
||||||
|
▼ ▼
|
||||||
|
┌─────┐ ┌──────────────────┐
|
||||||
|
│FERTIG│ │ Stufe 2: LLM │ qwen2.5:7b (~4.5 GB, ~150ms auf 20 Cores)
|
||||||
|
│30ms │ │ Prompt-Klassifik. │ "FAKT, FRAGE oder ALARM?"
|
||||||
|
└─────┘ └──────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Drei Stufen, nicht zwei.** Der Keyword-Vorfilter (Stufe 0) ist essentiell für ALARM-Nachrichten —
|
||||||
|
er fängt "HILFE", "ALARM", "STOP", "red flag" bevor sie ins Embedding gehen und dort als
|
||||||
|
FRAGE oder FAKT fehlklassifiziert werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Stufe 0: Keyword-Vorfilter (Priorität: HOCH)
|
||||||
|
|
||||||
|
### Neue ALARM-Keywords (in `config.py::FALLBACK_KEYWORDS`)
|
||||||
|
```python
|
||||||
|
"ALARM": [
|
||||||
|
"alarm", "hilfe", "dringend", "sofort", "notfall", "ausfall",
|
||||||
|
"absturz", "kritisch", "emergency", "feuer", "panne", "sos",
|
||||||
|
"sicherheitslücke", # Bestand
|
||||||
|
"stop", # NEU: Sofortiger Handlungsabbruch
|
||||||
|
"red flag", # NEU: Manifest-Sprache
|
||||||
|
"abort", # NEU: Abbruch mit Dringlichkeit
|
||||||
|
"kompromittiert", # NEU: Sicherheitsvorfall
|
||||||
|
"datenverlust", # NEU: Unwiederbringlich
|
||||||
|
"exploit", # NEU: Aktiver Angriff
|
||||||
|
"gehackt", # NEU: Eindeutiger Vorfall
|
||||||
|
"ausgefallen", # NEU: Verbform
|
||||||
|
"produktivsystem", # NEU: Produktivsystem-Bezug
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Neue FRAGE-Keywords
|
||||||
|
```python
|
||||||
|
"FRAGE": [
|
||||||
|
"frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
||||||
|
"kannst du", "können sie", "help", "hilfe", "problem",
|
||||||
|
"funktioniert nicht", "kaputt", "erklären", "erkläre",
|
||||||
|
"was bedeutet", # NEU: Definition anfordern
|
||||||
|
"zeig mir", # NEU: Imperativ mit Frageabsicht
|
||||||
|
"konflikt", # NEU: Problem-Indikator
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Routing-Logik
|
||||||
|
```python
|
||||||
|
def _keyword_prefilter(text: str) -> Optional[str]:
|
||||||
|
"""Stufe 0: Keyword-Vorfilter. Liefert Kategorie oder None."""
|
||||||
|
t = text.lower()
|
||||||
|
# ALARM zuerst prüfen — höchste Priorität
|
||||||
|
for kw in FALLBACK_KEYWORDS["ALARM"]:
|
||||||
|
if kw in t:
|
||||||
|
return "ALARM"
|
||||||
|
for kw in FALLBACK_KEYWORDS["FRAGE"]:
|
||||||
|
if kw in t:
|
||||||
|
return "FRAGE"
|
||||||
|
return None # → Embedding (Stufe 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Effekt:** ~25% der Nachrichten werden in <1ms klassifiziert. ALARM-Fehlklassifikationen
|
||||||
|
(HILFE→FRAGE) werden komplett eliminiert. Die ALARM-Check-Liste ist die
|
||||||
|
Sicherheitsgarantie — kein Alarm darf unentdeckt bleiben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Stufe 1: Embedding (unverändert)
|
||||||
|
|
||||||
|
Bleibt exakt wie jetzt:
|
||||||
|
- `nomic-embed-text` via `localhost:11434`
|
||||||
|
- 3 Kategorietexte (FAKT, FRAGE, ALARM)
|
||||||
|
- Kosinus-Ähnlichkeit, Schwellwert **erhöht auf 0.70** (vorher 0.60)
|
||||||
|
- Begründung: Grenzfälle gehen jetzt an Stufe 2 (LLM), nicht an Catch-All
|
||||||
|
- Höhere Präzision, niedrigere Recall-Rate — aber Recall wird vom LLM aufgefangen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Stufe 2: LLM-Klassifikator (NEU)
|
||||||
|
|
||||||
|
### Modell: qwen2.5:7b
|
||||||
|
- **Deutsch-Performance:** Stark (getestet auf deutschen Texten)
|
||||||
|
- **RAM:** ~4.5 GB (neben nomic-embed-text: 274 MB → ~5 GB gesamt)
|
||||||
|
- **Latenz:** ~150ms auf 20 CPU-Cores (Ollama, localhost:11434)
|
||||||
|
- **Kosten:** 0€ (lokal)
|
||||||
|
|
||||||
|
### Prompt-Design
|
||||||
|
```python
|
||||||
|
CLASSIFY_PROMPT = """Klassifiziere die folgende Nachricht in EINE Kategorie.
|
||||||
|
Antworte NUR mit einem Wort: FAKT, FRAGE oder ALARM.
|
||||||
|
|
||||||
|
Kategorien:
|
||||||
|
- FAKT: Information, Dokumentation, Status-Update ohne Handlungsbedarf
|
||||||
|
- FRAGE: Frage, Problembeschreibung, Bitte um Hilfe oder Erklärung
|
||||||
|
- ALARM: Dringend! Ausfall, Sicherheitsvorfall, Datenverlust, sofortiger Handlungsbedarf
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
|
||||||
|
Kategorie:"""
|
||||||
|
```
|
||||||
|
|
||||||
|
### Integration in classifier.py
|
||||||
|
```python
|
||||||
|
class MessageClassifier:
|
||||||
|
def __init__(self, ...):
|
||||||
|
self._enable_llm = True # Feature-Flag
|
||||||
|
self._llm_model = "qwen2.5:7b"
|
||||||
|
self._llm_timeout = 5.0
|
||||||
|
self._llm_confidence_threshold = 0.70 # Nur unterhalb LLM befragen
|
||||||
|
|
||||||
|
async def _llm_classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Stufe 2: LLM-basierte Klassifikation für Grenzfälle."""
|
||||||
|
try:
|
||||||
|
response = await self._call_ollama_chat(
|
||||||
|
model=self._llm_model,
|
||||||
|
prompt=CLASSIFY_PROMPT.format(text=text),
|
||||||
|
timeout=self._llm_timeout,
|
||||||
|
)
|
||||||
|
category = response.strip().upper()
|
||||||
|
if category in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return category
|
||||||
|
except Exception:
|
||||||
|
logger.warning("LLM classification failed, using embedding result")
|
||||||
|
return None
|
||||||
|
```
|
||||||
|
|
||||||
|
### Latenz-Kaskade
|
||||||
|
```
|
||||||
|
Stufe 0 (Keyword): <1ms → ~25% der Nachrichten
|
||||||
|
Stufe 1 (Embedding): ~30ms → ~55% (Konfidenz ≥ 0.70)
|
||||||
|
Stufe 2 (LLM): ~150ms → ~20% (Grenzfälle)
|
||||||
|
Gesamt (gewichtet): ~42ms → 3× schneller als reines LLM
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Ressourcen
|
||||||
|
|
||||||
|
### RAM (Host: 15 GB verfügbar)
|
||||||
|
| Komponente | RAM |
|
||||||
|
|---|---|
|
||||||
|
| nomic-embed-text | 274 MB |
|
||||||
|
| qwen2.5:7b | ~4.5 GB |
|
||||||
|
| Hermes Gateway + System | ~3 GB |
|
||||||
|
| **Frei** | **~7 GB** ✅ |
|
||||||
|
|
||||||
|
### CPU (20 Cores verfügbar)
|
||||||
|
- Ollama nutzt alle Cores für Inference
|
||||||
|
- qwen2.5:7b skaliert gut auf 20 Cores → ~150ms realistisch
|
||||||
|
|
||||||
|
### Disk
|
||||||
|
- qwen2.5:7b: ~4.7 GB Download (einmalig)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Fallback-Strategie (unverändert)
|
||||||
|
|
||||||
|
1. Keyword Vorfilter → Embedding → LLM
|
||||||
|
2. LLM nicht verfügbar → Embedding-Ergebnis verwenden (auch wenn Konfidenz < 0.70)
|
||||||
|
3. Embedding nicht verfügbar → Keyword-Fallback wie bisher
|
||||||
|
4. **Feature-Flag `_enable_llm`**: LLM-Stufe kann jederzeit deaktiviert werden
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Änderungen an bestehendem Code
|
||||||
|
|
||||||
|
| Datei | Änderung | Umfang |
|
||||||
|
|---|---|---|
|
||||||
|
| `config.py` | Keyword-Listen erweitern, LLM-Config | ~15 Zeilen |
|
||||||
|
| `classifier.py` | `_keyword_prefilter()`, `_llm_classify()`, Schwellwert auf 0.70 | ~60 Zeilen |
|
||||||
|
| `adapter_integration.py` | LLM-Modell-Parameter durchreichen | ~5 Zeilen |
|
||||||
|
|
||||||
|
Keine Änderungen an:
|
||||||
|
- `router.py` — Routing-Logik unverändert
|
||||||
|
- `adapter.py` — Integration unverändert
|
||||||
|
- `doc_store.py` — unverändert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Risiken & Mitigation
|
||||||
|
|
||||||
|
| Risiko | Eintrittswahrsch. | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| LLM halluziniert Kategorie | Niedrig (3-Wort-Output) | Fallback auf Embedding |
|
||||||
|
| Ollama OOM mit beiden Modellen | Niedrig (~5 GB von 15) | Feature-Flag → LLM abschalten |
|
||||||
|
| LLM-Latenz > 500ms | Mittel | 5s Timeout, Fallback |
|
||||||
|
| Keyword "stop" in normalem Text | Niedrig | Nur ALARM-Keywords — "stop" ist nie informell |
|
||||||
@@ -0,0 +1,446 @@
|
|||||||
|
# Archivar — Architekturskizze & Implementierungsplan
|
||||||
|
|
||||||
|
> **Status:** Vorschlag — wartet auf Andreas' Review
|
||||||
|
> **Basis:** Konzept-Story `docs/archivar-konzept.md` (Commit `fa2a24f`)
|
||||||
|
> **Datum:** 05.06.2026
|
||||||
|
> **Ziel:** Umbau vom 3-Kategorien-Klassifikator zum thematischen Router
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Architekturentscheidungen
|
||||||
|
|
||||||
|
Drei Lücken aus der Gap-Analyse, hier entschieden:
|
||||||
|
|
||||||
|
### L1: Raum-Map-Format
|
||||||
|
|
||||||
|
**Entscheidung:** JSON-Datei unter `~/.hermes/hermes-agent/data/room-map.json`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {
|
||||||
|
"<rocketchat_room_id>": {
|
||||||
|
"name": "#Rocketchat-Plugin",
|
||||||
|
"theme": "Plugin-Entwicklung & Hermes-Integration",
|
||||||
|
"keywords": ["plugin", "adapter", "rocketchat", "gateway", "archivar", "schnittstelle"],
|
||||||
|
"catch_all": false
|
||||||
|
},
|
||||||
|
"<rocketchat_room_id>": {
|
||||||
|
"name": "#BAT-Team",
|
||||||
|
"theme": "BAT-Projektentwicklung",
|
||||||
|
"keywords": ["bat", "trading", "docker", "backtesting", "orderbuch"],
|
||||||
|
"catch_all": false
|
||||||
|
},
|
||||||
|
"<dm_room_id>": {
|
||||||
|
"name": "DM Andreas",
|
||||||
|
"theme": "Meta, Strategie, Alarme",
|
||||||
|
"keywords": [],
|
||||||
|
"catch_all": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": [
|
||||||
|
"<multi_agent_room_id>"
|
||||||
|
],
|
||||||
|
"fact_store_path": "/data/Wissensdatenbank/Inbox/"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warum JSON:**
|
||||||
|
- Maschinenlesbar ohne YAML-Dependency
|
||||||
|
- `json.load()` ist in der Python-Stdlib, null zusätzliche Abhängigkeiten
|
||||||
|
- Editierbar mit jedem Editor
|
||||||
|
- `version`-Feld für zukünftige Migrationen
|
||||||
|
- `excluded_rooms` für den Multi-Agent-Raum-Ausschluss
|
||||||
|
|
||||||
|
**Pfad-Wahl:** `~/.hermes/hermes-agent/data/` — persistente Daten unter Hermes-Kontrolle, nicht im Repo. Gleich wie `archivar_docs/`.
|
||||||
|
|
||||||
|
### L2: Catch-All-Validierung
|
||||||
|
|
||||||
|
**Entscheidung:** Beim Gateway-Start (Adapter-Initialisierung) validiert der Archivar:
|
||||||
|
|
||||||
|
1. Genau ein Raum hat `catch_all: true`
|
||||||
|
2. Bei 0 → **Gateway-Start wird abgelehnt** mit: `FATAL: No catch_all room defined in room-map.json`
|
||||||
|
3. Bei >1 → **Gateway-Start wird abgelehnt** mit: `FATAL: Multiple catch_all rooms: #RaumA, #RaumB`
|
||||||
|
4. Der Catch-All-Raum MUSS in den subscribed rooms des Bots sein
|
||||||
|
|
||||||
|
**Implementierung:** `RoomMap.load()` wirft `RoomMapValidationError` (neue Exception-Klasse). `ArchivarMessageHandler.initialize()` fängt sie und logged FATAL.
|
||||||
|
|
||||||
|
### L3: Onboarding-Integration
|
||||||
|
|
||||||
|
**Entscheidung:** Gateway-Hook — nicht im Archivar-Modul selbst, sondern als separates Tool im Rocket.Chat-Plugin.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. Gateway subscribed neuen Raum (via `rocketchat_rooms` oder Admin-Invite)
|
||||||
|
2. Plugin erkennt: Raum-ID nicht in `room-map.json`
|
||||||
|
3. Plugin sendet DM an Admin (konfigurierbar, default: Catch-All-Raum-Besitzer):
|
||||||
|
```
|
||||||
|
Neuer Raum erkannt: #NeuerRaum (ID: 6a...)
|
||||||
|
1. Was ist das Thema dieses Raums?
|
||||||
|
2. Welche Stichworte beschreiben das Thema?
|
||||||
|
```
|
||||||
|
4. Admin antwortet → Plugin schreibt Eintrag in `room-map.json`
|
||||||
|
5. **Optional:** `/reload` oder Gateway-Neustart zum Aktivieren
|
||||||
|
|
||||||
|
**Implementierung:** `plugin/onboarding.py` — separate Datei, nicht im Archivar-Modul. Nutzt `send_callback` für die DM.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Datenmodell
|
||||||
|
|
||||||
|
### 2.1 RoomMap (NEU — `plugin/archivar/room_map.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class RoomEntry:
|
||||||
|
room_id: str
|
||||||
|
name: str
|
||||||
|
theme: str
|
||||||
|
keywords: list[str]
|
||||||
|
catch_all: bool = False
|
||||||
|
|
||||||
|
class RoomMap:
|
||||||
|
"""Lädt, validiert und durchsucht die Raum-Map."""
|
||||||
|
|
||||||
|
def __init__(self, path: Path | None = None)
|
||||||
|
|
||||||
|
# Properties
|
||||||
|
rooms: dict[str, RoomEntry] # room_id → RoomEntry
|
||||||
|
catch_all_room: RoomEntry | None # Der EINE Catch-All-Raum
|
||||||
|
excluded_room_ids: set[str] # Nie routen
|
||||||
|
fact_store_path: Path # FAKT-Ablagepfad
|
||||||
|
|
||||||
|
# Lookup
|
||||||
|
def find_room_by_keywords(self, text: str) -> RoomEntry | None
|
||||||
|
def find_room_by_theme_match(self, text: str, llm_client) -> RoomEntry | None
|
||||||
|
def is_excluded(self, room_id: str) -> bool
|
||||||
|
|
||||||
|
# Validation
|
||||||
|
def validate(self, subscribed_ids: set[str]) -> list[str] # Fehlerliste
|
||||||
|
```
|
||||||
|
|
||||||
|
**Neu gegenüber heute:**
|
||||||
|
- `room_map.json` als Single Source of Truth (ersetzt Env-Vars `ARCHIVAR_*_ROOM`)
|
||||||
|
- `RoomEntry` als strukturiertes Objekt (statt Dict-of-Dicts)
|
||||||
|
- `catch_all_room` als Property (statt separater `CATCH_ALL_ROOM` Variable)
|
||||||
|
- `excluded_room_ids` (statt nichts)
|
||||||
|
- `validate()` für Gateway-Start (ersetzt stilles Ignorieren)
|
||||||
|
|
||||||
|
### 2.2 RoomRouter (UMBAU — `plugin/archivar/router.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class RoomRouter:
|
||||||
|
"""Thematischer Router: Nachricht → Zielraum."""
|
||||||
|
|
||||||
|
def __init__(self, room_map: RoomMap, classifier: MessageClassifier)
|
||||||
|
|
||||||
|
async def route(self, text: str, origin_room_id: str) -> RoutingDecision:
|
||||||
|
"""
|
||||||
|
NEUER Ablauf:
|
||||||
|
1. origin_room_id in excluded_rooms? → sofort Catch-All
|
||||||
|
2. Keyword-Match in room_map.keywords? → Zielraum
|
||||||
|
3. Embedding-Klassifikation → Kategorie (FAKT/FRAGE/ALARM)
|
||||||
|
4. LLM: "In welchen Raum?" mit room_map als Kontext
|
||||||
|
5. Kein Treffer → catch_all_room
|
||||||
|
|
||||||
|
RoutingDecision.target_room ist JETZT der Raum aus der Map,
|
||||||
|
nicht mehr der aus Env-Vars.
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
**Neu gegenüber heute:**
|
||||||
|
- `_detect_project()` durch `RoomMap.find_room_by_keywords()` ersetzt
|
||||||
|
- `_resolve_room_with_project()` durch `RoomMap.find_room_by_theme_match()` (LLM) ersetzt
|
||||||
|
- `ROOM_MAPPING` Env-Vars → `room_map.json`
|
||||||
|
- Der Router KENNT die Map (statt sie nur zu konsultieren)
|
||||||
|
|
||||||
|
### 2.3 MessageClassifier (REFACTOR — `plugin/archivar/classifier.py`)
|
||||||
|
|
||||||
|
**Bleibt weitgehend erhalten**, aber LLM-Prompt ändert sich:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ALT (config.py, Zeile 129-139):
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere ... in FAKT, FRAGE oder ALARM."""
|
||||||
|
|
||||||
|
# NEU (config.py):
|
||||||
|
LLM_ROOM_PROMPT = """Diese Räume sind verfügbar:
|
||||||
|
{room_list}
|
||||||
|
|
||||||
|
In welchen Raum gehört diese Nachricht?
|
||||||
|
Antworte NUR mit dem Raum-Namen (oder "CATCH_ALL" wenn unsicher).
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
Raum:"""
|
||||||
|
```
|
||||||
|
|
||||||
|
**Zusätzliche Änderungen:**
|
||||||
|
- `max_tokens: 20` (Raum-Namen sind länger als Kategorien)
|
||||||
|
- `LLMClassifyResult` → `LLMRoomResult`
|
||||||
|
- `_llm_classify_sync()` ruft `RoomMap.find_room_by_theme_match()` auf
|
||||||
|
|
||||||
|
### 2.4 ArchivarMessageHandler (REFACTOR — `plugin/archivar/adapter_integration.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class ArchivarMessageHandler:
|
||||||
|
def __init__(self, room_map_path: Path | None = None, ...):
|
||||||
|
self._room_map = RoomMap(room_map_path) # NEU
|
||||||
|
self._room_map.validate(subscribed_ids) # NEU: wirft bei Fehler
|
||||||
|
|
||||||
|
async def classify_and_route(self, text: str, origin_room_id: str) -> RoutingDecision:
|
||||||
|
# Check excluded rooms FIRST
|
||||||
|
if self._room_map.is_excluded(origin_room_id):
|
||||||
|
return RoutingDecision(...) # silent ignore
|
||||||
|
|
||||||
|
# Then route
|
||||||
|
return await self._router.route(text, origin_room_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Was bleibt, was fliegt raus?
|
||||||
|
|
||||||
|
### Bleibt (bewährter Code)
|
||||||
|
|
||||||
|
| Komponente | Datei | Grund |
|
||||||
|
|-----------|-------|-------|
|
||||||
|
| Keyword-Vorfilter (`_keyword_prefilter`) | `classifier.py` | Schnelle ALARM-Erkennung, bewährt |
|
||||||
|
| Embedding-Klassifikation (Stufe 1) | `classifier.py` | Funktioniert, nomic-embed-text zuverlässig |
|
||||||
|
| `ClassificationResult` Dataclass | `classifier.py` | Stabile Schnittstelle |
|
||||||
|
| `EmbeddingClient` Interface | `classifier.py` | Gut testbar, injectable |
|
||||||
|
| `OllamaEmbeddingClient` | `classifier.py` | Bewährter Transport |
|
||||||
|
| `OllamaLLMClient` | `classifier.py` | Wiederverwendbar für neuen Prompt |
|
||||||
|
| `DocumentationStore` | `doc_store.py` | FAKT-Ablage funktioniert |
|
||||||
|
| Meta-Fragen-Erkennung | `router.py` | Bewährt, unverändert |
|
||||||
|
| Subscription-Validierung | `router.py` | Bleibt, aber gegen `room_map.rooms` prüfen |
|
||||||
|
|
||||||
|
### Fliegt raus (ersetzt)
|
||||||
|
|
||||||
|
| Komponente | Datei | Ersetzt durch |
|
||||||
|
|-----------|-------|--------------|
|
||||||
|
| `ROOM_MAPPING` (Env-Vars) | `config.py` | `room_map.json` |
|
||||||
|
| `CATCH_ALL_ROOM` (Env-Var) | `config.py` | `room_map.catch_all_room` |
|
||||||
|
| `_PROJECT_KEYWORDS` (hartcodiert) | `router.py` | `RoomEntry.keywords` aus Map |
|
||||||
|
| `_detect_project()` | `router.py` | `RoomMap.find_room_by_keywords()` |
|
||||||
|
| `_resolve_room_with_project()` | `router.py` | `RoomMap.find_room_by_theme_match()` |
|
||||||
|
| `LLM_CLASSIFY_PROMPT` (Kategorien) | `config.py` | `LLM_ROOM_PROMPT` (Raum-Lookup) |
|
||||||
|
| `ARCHIVAR_*_ROOM` Env-Vars (alle) | `.env` | `room-map.json` |
|
||||||
|
|
||||||
|
### Neu (hinzugefügt)
|
||||||
|
|
||||||
|
| Komponente | Datei | Zweck |
|
||||||
|
|-----------|-------|-------|
|
||||||
|
| `RoomMap` | `plugin/archivar/room_map.py` | Single Source of Truth |
|
||||||
|
| `RoomEntry` Dataclass | `plugin/archivar/room_map.py` | Strukturierter Raum-Eintrag |
|
||||||
|
| `RoomMapValidationError` | `plugin/archivar/room_map.py` | Gateway-Start-Schutz |
|
||||||
|
| `room-map.json` | `~/.hermes/hermes-agent/data/` | Persistente Map |
|
||||||
|
| `LLM_ROOM_PROMPT` | `config.py` | Neuer LLM-Prompt (Raum statt Kategorie) |
|
||||||
|
| `onboarding.py` | `plugin/onboarding.py` | Onboarding-Hook (Phase 2) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Migrationspfad
|
||||||
|
|
||||||
|
### Phase 1: Datenmodell & Map-Loader (Miguel, ~2h)
|
||||||
|
|
||||||
|
1. **`room_map.py` erstellen:**
|
||||||
|
- `RoomEntry` Dataclass
|
||||||
|
- `RoomMap` Klasse mit `load()`, `validate()`, `find_room_by_keywords()`
|
||||||
|
- `room-map.json` Schema + Beispiel-Datei
|
||||||
|
- Unit-Tests für Validierung (0 Catch-All, 2 Catch-All, excluded rooms)
|
||||||
|
|
||||||
|
2. **`config.py` ergänzen:**
|
||||||
|
- `LLM_ROOM_PROMPT` Template
|
||||||
|
- `ROOM_MAP_PATH` Default (`~/.hermes/hermes-agent/data/room-map.json`)
|
||||||
|
- Alte Env-Vars als **deprecated** markieren (mit Warning-Log)
|
||||||
|
|
||||||
|
3. **Alte Env-Vars noch lesen als Fallback:**
|
||||||
|
```python
|
||||||
|
def _migrate_from_env_vars() -> dict | None:
|
||||||
|
"""Liest ARCHIVAR_*_ROOM Env-Vars und baut temporäre Map.
|
||||||
|
Logged WARNING: 'Using deprecated ARCHIVAR_*_ROOM env vars.
|
||||||
|
Please migrate to room-map.json'."""
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2: Router-Umbau (Miguel, ~3h)
|
||||||
|
|
||||||
|
4. **`RoomRouter` in `router.py` umbauen:**
|
||||||
|
- `route()` nimmt jetzt `origin_room_id` Parameter
|
||||||
|
- `_resolve_room_with_project()` → ruft `RoomMap.find_room_by_keywords()` auf
|
||||||
|
- Keyword-Matching aus `_PROJECT_KEYWORDS` entfernen → Keywords aus `RoomEntry` nutzen
|
||||||
|
- LLM-Pfad: `LLM_ROOM_PROMPT.format(room_list=..., text=...)` statt `LLM_CLASSIFY_PROMPT`
|
||||||
|
|
||||||
|
5. **`RoutingDecision` erweitern:**
|
||||||
|
- `matched_room_name: str | None` Feld (für Debugging)
|
||||||
|
|
||||||
|
### Phase 3: Integration & Test (Miguel, ~2h)
|
||||||
|
|
||||||
|
6. **`adapter_integration.py` anpassen:**
|
||||||
|
- `ArchivarMessageHandler.__init__()` lädt `RoomMap`
|
||||||
|
- `validate()` beim Start (FATAL bei Fehler)
|
||||||
|
- `classify_and_route()` prüft `is_excluded(origin_room_id)`
|
||||||
|
|
||||||
|
7. **`adapter.py` Einhängung prüfen:**
|
||||||
|
- `set_subscribed_room_ids()` muss VOR `initialize()` aufgerufen werden
|
||||||
|
- `initialize()` muss `room_map.validate(subscribed_ids)` aufrufen
|
||||||
|
|
||||||
|
8. **Integrationstest auf `.45`:**
|
||||||
|
- Test-Map mit 2 Räumen + Catch-All erstellen
|
||||||
|
- Nachricht mit Plugin-Keywords → muss in Plugin-Raum landen
|
||||||
|
- Unbekannte Nachricht → muss im Catch-All landen
|
||||||
|
- Nachricht aus excluded room → muss ignoriert werden
|
||||||
|
- Gateway-Start mit 0 Catch-All → muss FATAL loggen
|
||||||
|
|
||||||
|
### Phase 4: Onboarding (später, Miguel ~1.5h)
|
||||||
|
|
||||||
|
9. **`onboarding.py` erstellen:**
|
||||||
|
- Erkennt neue Räume (nicht in Map)
|
||||||
|
- Sendet strukturierte DM an Admin
|
||||||
|
- Parst Admin-Antwort → schreibt Map-Eintrag
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Datenfluss (NEU)
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht (text, origin_room_id)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
origin_room_id in excluded_rooms? ────► IGNORE (silent)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Keyword-Match in RoomMap.keywords? ───► Zielraum gefunden → Route
|
||||||
|
│
|
||||||
|
▼ (kein Keyword-Treffer)
|
||||||
|
Embedding-Klassifikation (nomic-embed-text)
|
||||||
|
│
|
||||||
|
├── ALARM (conf ≥ 0.6) → catch_all_room (Admin-DM)
|
||||||
|
├── FRAGE (conf ≥ 0.6) → LLM-Room-Lookup
|
||||||
|
├── FAKT (conf ≥ 0.6) → fact_store_path (Dateisystem)
|
||||||
|
└── conf < 0.6 → LLM-Room-Lookup
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
LLM: "In welchen Raum?" mit room_map als Kontext
|
||||||
|
│
|
||||||
|
├── Raum erkannt → Route
|
||||||
|
└── Kein Raum → catch_all_room
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Menschlicher Override
|
||||||
|
|
||||||
|
Der Archivar ist ein automatisches System — aber der Mensch behält immer das
|
||||||
|
letzte Wort. Der Override ist keine „Notbremse", sondern ein **konstruktives
|
||||||
|
Korrektur-Werkzeug**, das den Archivar trainiert, besser zu werden.
|
||||||
|
|
||||||
|
### 6.1 Override durch Admin-Reaktion
|
||||||
|
|
||||||
|
Der Admin kann auf eine fehlgeleitete Nachricht im Zielraum mit einem
|
||||||
|
**Reply** reagieren. Das Reply-Format ist simpel: `!r <raum-name>`.
|
||||||
|
|
||||||
|
```
|
||||||
|
Beispiel:
|
||||||
|
Originalnachricht im #Infrastruktur:
|
||||||
|
„Das Docker-Image für das Plugin ist kaputt"
|
||||||
|
|
||||||
|
Admin reply:
|
||||||
|
!r #Rocketchat-Plugin
|
||||||
|
```
|
||||||
|
|
||||||
|
**Was dann passiert:**
|
||||||
|
1. Der Archivar erkennt das Reply-Format (`!r` am Zeilenanfang)
|
||||||
|
2. Die Originalnachricht wird aus dem falschen Raum **gelöscht**
|
||||||
|
3. Die Nachricht wird in den korrekten Raum **verschoben** (mit `[UMGELEITET]` Prefix)
|
||||||
|
4. **Die Korrektur wird in der Map gespeichert:**
|
||||||
|
- Das Keyword der Nachricht (z.B. `docker`) wird temporär für diesen Kontext
|
||||||
|
dem richtigen Raum zugeordnet
|
||||||
|
- Bei 3 Overrides für dasselbe Keyword-Muster → permanenter Eintrag in die
|
||||||
|
`keyword_overrides` der `room-map.json`
|
||||||
|
|
||||||
|
### 6.2 Override-Schema in der Map
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"rooms": { ... },
|
||||||
|
"excluded_rooms": [ ... ],
|
||||||
|
"fact_store_path": "/data/Wissensdatenbank/Inbox/",
|
||||||
|
"keyword_overrides": {
|
||||||
|
"plugin": "docker",
|
||||||
|
"bat": "backtesting",
|
||||||
|
"plugin": "gateway"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`keyword_overrides` ist eine **flache Map**: `raum_name → keyword`. Wenn ein Raum
|
||||||
|
bereits ein Override für ein Keyword hat, wird der Score dieses Raums bei einem
|
||||||
|
Match künstlich erhöht.
|
||||||
|
|
||||||
|
**Begrenzung:** Maximal 50 Override-Einträge. Bei Überschreitung werden die
|
||||||
|
ältesten (nach Datum) gelöscht. Overrides sind **Trainingsdaten**, kein Ersatz
|
||||||
|
für saubere Keywords in der Map.
|
||||||
|
|
||||||
|
### 6.3 Override im Datenfluss
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht (text, origin_room_id)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
origin_room_id in excluded_rooms? ────► IGNORE (silent)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Keyword-Match in keyword_overrides? ───► Override-Raum (höchste Prio)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Keyword-Match in RoomMap.keywords? ───► Zielraum gefunden → Route
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
(Rest wie gehabt: Embedding → LLM → Catch-All)
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Override hat die **höchste Priorität** im Keyword-Matching — noch vor den
|
||||||
|
normalen Raum-Keywords. Der Mensch korrigiert einmal, der Archivar lernt daraus.
|
||||||
|
|
||||||
|
### 6.4 Override-Antwort an den Admin
|
||||||
|
|
||||||
|
Nach erfolgreichem Override antwortet der Archivar im Zielraum mit einer
|
||||||
|
Bestätigung:
|
||||||
|
|
||||||
|
```
|
||||||
|
[UMGELEITET von #Infrastruktur] Das Docker-Image für das Plugin ist kaputt
|
||||||
|
↳ Override gespeichert: "docker" + Kontext "Plugin" → #Rocketchat-Plugin
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.5 Was der Override NICHT ist
|
||||||
|
|
||||||
|
- **Kein Echtzeit-Eingriff.** Der Override korrigiert bereits geroutete Nachrichten. Er verhindert nicht die initiale Fehlleitung — er behebt sie und verhindert Wiederholungen.
|
||||||
|
- **Kein Chat-Befehlssystem.** `!r` ist das einzige Override-Kommando. Keine weitere Befehlssyntax.
|
||||||
|
- **Kein Ersatz für gute Keywords.** Wenn der Admin ständig overriden muss, sind die Keywords in der Map falsch — nicht der Override-Mechanismus.
|
||||||
|
|
||||||
|
### 6.6 Override-Regeln für die Sicherheit
|
||||||
|
|
||||||
|
1. **Nur der Admin** (Besitzer des Catch-All-Raums) darf overriden. Replies von anderen Nutzern werden ignoriert.
|
||||||
|
2. **Nur in abonnierten Räumen.** Override aus nicht-abonnierten Räumen wird ignoriert.
|
||||||
|
3. **Kein Override auf sich selbst.** `!r` in den gleichen Raum → wird ignoriert.
|
||||||
|
4. **Kein Override in excluded_rooms.** Der Multi-Agent-Raum ist komplett ausgenommen.
|
||||||
|
5. **Keine Endlosschleife.** Wenn dieselbe Nachricht 3× overriden wird → Stop, Admin benachrichtigen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Checkliste für Andreas' Review
|
||||||
|
|
||||||
|
- [ ] **Menschlicher Override:** `!r <raum>` Reply-Mechanismus sinnvoll? Admin-only korrekt?
|
||||||
|
- [ ] **Override-Lernen:** Keyword-Overrides nach 3 Wiederholungen permanent — guter Schwellwert?
|
||||||
|
- [ ] **Override-Begrenzung:** Max 50 Einträge, älteste verdrängen — angemessen?
|
||||||
|
- [ ] **Override im Datenfluss:** Höchste Keyword-Priorität vor Raum-Keywords — korrekt?
|
||||||
|
- [ ] **Sicherheitsregeln:** Admin-only, keine Selbst-Overrides, keine excluded_rooms, 3× Stop — vollständig?
|
||||||
|
- [ ] **L1 — JSON-Format:** `room-map.json` Schema akzeptabel? Oder lieber YAML?
|
||||||
|
- [ ] **L1 — Pfad:** `~/.hermes/hermes-agent/data/` korrekt? Oder `/data/Wissensdatenbank/...`?
|
||||||
|
- [ ] **L2 — FATAL bei 0 Catch-All:** Zu hart? Oder genau richtig (Fail-Fast)?
|
||||||
|
- [ ] **L2 — Validierung beim Start:** Gateway-Start-Blockade akzeptabel?
|
||||||
|
- [ ] **L3 — Onboarding als separates Plugin-Tool:** Passt die Trennung vom Archivar-Modul?
|
||||||
|
- [ ] **Datenfluss:** Passt die Logik "ALARM → Admin, FRAGE → Themenraum, FAKT → Datei"?
|
||||||
|
- [ ] **LLM-Prompt:** `LLM_ROOM_PROMPT` mit Raum-Liste sinnvoll?
|
||||||
|
- [ ] **Migrationspfad:** Alte Env-Vars als deprecated-Fallback okay für Übergang?
|
||||||
|
- [ ] **Multi-Agent-Raum-Ausschluss:** `excluded_rooms` in Map + `origin_room_id`-Check ausreichend?
|
||||||
|
- [ ] **FAKT-Ablagepfad:** `fact_store_path` in der Map konfigurierbar — korrekt?
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
# Archivar — Konzept & Architekturziel
|
||||||
|
|
||||||
|
> **Status:** Konzeptioneller Anker. Dieses Dokument dokumentiert das WARUM, nicht das WIE.
|
||||||
|
> Implementierungsentscheidungen müssen sich an diesem Dokument messen lassen.
|
||||||
|
|
||||||
|
## Das Problem
|
||||||
|
|
||||||
|
Ein Hermes-Agent in mehreren Chat-Räumen sieht jede Nachricht — Statusmeldungen,
|
||||||
|
Fragen, Alarme, Smalltalk. Ohne Filter ertrinkt er im Rauschen. Schlimmer:
|
||||||
|
Eine echte Frage oder ein Alarm zwischen zwei Status-Updates wird übersehen,
|
||||||
|
weil alles gleich aussieht.
|
||||||
|
|
||||||
|
**Der Mensch ist der Flaschenhals.** Jede Nachricht muss ein Mensch lesen und
|
||||||
|
entscheiden: „Ist das wichtig? Wer ist zuständig? In welchen Raum gehört das?"
|
||||||
|
|
||||||
|
## Die Lösungsidee
|
||||||
|
|
||||||
|
Der Archivar ist ein **thematischer Router**, der vor dem Agenten sitzt und
|
||||||
|
Nachrichten automatisch dem richtigen Raum zuordnet — ohne dass ein Mensch
|
||||||
|
jede Nachricht prüfen muss.
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Archivar klassifiziert
|
||||||
|
│
|
||||||
|
├── Thema erkannt → Zielraum (Projektraum, Themenraum)
|
||||||
|
├── Kein Thema → Catch-All („Alles andere")
|
||||||
|
└── Alarm → DM Auftraggeber (sofort)
|
||||||
|
```
|
||||||
|
|
||||||
|
Das ist ein **einfacher Entscheidungsbaum**, kein komplexes ML-System.
|
||||||
|
Die Intelligenz liegt in der **Raum-Map**: eine Zuordnung von Themen zu Räumen,
|
||||||
|
die der Archivar konsultiert.
|
||||||
|
|
||||||
|
## Die Raum-Map
|
||||||
|
|
||||||
|
Jeder abonnierte Raum bekommt ein **Thema**. Das Thema ist eine informelle
|
||||||
|
Beschreibung dessen, was in diesen Raum gehört, plus eine optionale
|
||||||
|
**Stichwortliste**, die der Archivar für die automatische Zuordnung nutzt.
|
||||||
|
|
||||||
|
**Catch-All** ist ein **Attribut eines Raums** — nicht mehr, nicht weniger.
|
||||||
|
Genau ein Raum trägt dieses Attribut. Alles, was der Archivar keinem anderen
|
||||||
|
Thema zuordnen kann, landet dort: nicht verloren, sondern gesammelt an einem
|
||||||
|
definierten Ort. Der Admin sieht es, entscheidet — und kein Rauschen bleibt
|
||||||
|
unentdeckt liegen.
|
||||||
|
|
||||||
|
### ⛔ Ausschluss-Regel
|
||||||
|
|
||||||
|
Der **Multi-Agent-Raum** (Bot-zu-Bot-Kommunikation & Training) ist **NIE**
|
||||||
|
Teil der Raum-Map. Er darf **weder** Catch-All sein **noch** ein Thema
|
||||||
|
bekommen. Der Archivar ignoriert diesen Raum vollständig.
|
||||||
|
|
||||||
|
**Grund:** Würden unbeaufsichtigte Agenten Nachrichten aus diesem Raum empfangen
|
||||||
|
und beantworten, entstünde eine unkontrollierte Bot-zu-Bot-Kommunikation —
|
||||||
|
Halluzinationen, Endlosschleifen, ungewollte Aktionen. Der Raum dient
|
||||||
|
ausschließlich dem expliziten Training und der direkten Agenten-Interaktion.
|
||||||
|
Jede automatische Weiterleitung dorthin ist ein Sicherheitsrisiko.
|
||||||
|
|
||||||
|
| Raum | Thema | Stichworte | Catch-All |
|
||||||
|
|------|-------|------------|-----------|
|
||||||
|
| `#Projekt-Alpha` | Frontend-Entwicklung | ui, design, css, komponente, layout | — |
|
||||||
|
| `#Projekt-Beta` | API & Backend | api, endpoint, datenbank, auth, rest | — |
|
||||||
|
| `#Infrastruktur` | Server & Deployment | docker, nginx, cert, domain, backup | — |
|
||||||
|
| `DM Admin` | Meta, Strategie, Alarme | (reserviert für ALARM) | ✅ |
|
||||||
|
|
||||||
|
**Regel:** Ein Raum mit Thema bekommt nur thematisch passende Nachrichten.
|
||||||
|
Der Catch-All-Raum bekommt alles, was nirgendwo sonst hinpasst — und nichts,
|
||||||
|
was bereits ein Thema hat.
|
||||||
|
|
||||||
|
### FAKT-Ablage — kein Raum, sondern ein Pfad
|
||||||
|
|
||||||
|
Fakten sind **Dokumentation, nicht Kommunikation.** Sie gehören nicht in einen
|
||||||
|
Chat-Raum, sondern an einen festen Ablageort im Dateisystem. Der Archivar
|
||||||
|
schreibt FAKT-Nachrichten dorthin — sie werden nie in einen Raum geroutet,
|
||||||
|
unabhängig von der Konfiguration.
|
||||||
|
|
||||||
|
| Zieltyp | Beispiel | Zweck |
|
||||||
|
|---------|----------|-------|
|
||||||
|
| **Themenraum** | `#Projekt-Beta` | Thematische Diskussion |
|
||||||
|
| **Catch-All-Raum** | `DM Admin` | Alles Unklassifizierte |
|
||||||
|
| **FAKT-Ablage** | `/data/Wissensdatenbank/Inbox/` | Reine Dokumentation |
|
||||||
|
|
||||||
|
Für Community-Installationen kann der Ablagepfad in der Raum-Map konfiguriert
|
||||||
|
werden — bei uns ist es die Inbox der Wissensdatenbank. Der Mechanismus ist
|
||||||
|
derselbe wie bei `StartObsidian`: Fakten sammeln sich dort, der Admin räumt
|
||||||
|
sie später auf (morgens, vor dem Tagesstart). Kein Sortieren zur Laufzeit,
|
||||||
|
kein Routing-Overhead — einfach ablegen und später zuordnen.
|
||||||
|
|
||||||
|
## Das Onboarding-Interview
|
||||||
|
|
||||||
|
Wenn der Gateway einen neuen Raum abonniert, führt der Agent ein kurzes
|
||||||
|
Interview mit dem Auftraggeber:
|
||||||
|
|
||||||
|
1. „Was ist das Thema dieses Raums?"
|
||||||
|
2. „Welche Stichworte beschreiben das Thema?"
|
||||||
|
3. Eintrag in die Raum-Map
|
||||||
|
|
||||||
|
Danach kennt der Archivar den Raum und kann Nachrichten automatisch
|
||||||
|
zuordnen. Kein neuer Raum bleibt unkonfiguriert.
|
||||||
|
|
||||||
|
## Abgrenzung: Was der Archivar NICHT ist
|
||||||
|
|
||||||
|
- **Kein Chat-Bot.** Er antwortet nicht, er routet nur.
|
||||||
|
- **Kein Agent.** Er trifft keine inhaltlichen Entscheidungen, er ordnet nur zu.
|
||||||
|
- **Kein Klassifikator um der Klassifikation willen.** Die Kategorien (FAKT/FRAGE/ALARM)
|
||||||
|
sind Mittel zum Zweck — sie dienen der Raum-Zuordnung, nicht der semantischen Analyse.
|
||||||
|
|
||||||
|
## Warum das wichtig ist
|
||||||
|
|
||||||
|
Der Agent ist ein **Multi-Room-Agent**: eine Instanz, die alle Räume sieht
|
||||||
|
und alles weiß. Der Archivar gibt diesem Agenten ein **Kommunikationsverhalten**,
|
||||||
|
das menschlicher Gesprächslogik folgt:
|
||||||
|
|
||||||
|
- **Aufgabe vom Auftraggeber (DM)** → wird dort empfangen, Analyse erfolgt dort.
|
||||||
|
- **Abarbeitung & Delegation** → wird im Themenraum gepostet, wo das Team es sieht.
|
||||||
|
- **Ergebnisse & Status** → landen im Themenraum, nicht im DM.
|
||||||
|
- **Alarme** → sofort in den DM, keine Verzögerung.
|
||||||
|
|
||||||
|
```
|
||||||
|
DM Andreas: „Bernd, setze die Maßnahmen für das Plugin im Team um..."
|
||||||
|
↓ (Bernd analysiert, delegiert an Rainer/Miguel)
|
||||||
|
#Plugin-Dev: „Auftrag analysiert: Profil erstellt.
|
||||||
|
Rainer macht die Architekturskizze..."
|
||||||
|
↓ (Rainer postet Skizze)
|
||||||
|
#Plugin-Dev: „Architekturskizze liegt vor. Miguel beginnt mit Implementierung."
|
||||||
|
↓ (Miguel postet Fortschritt)
|
||||||
|
#Plugin-Dev: „Implementierung abgeschlossen. Quality Gate bestanden."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Bernd entwickelt NIE selbst.** Er hält die Fäden in der Hand — delegiert,
|
||||||
|
koordiniert, informiert — ist aber **immer für den Auftraggeber ansprechbar**.
|
||||||
|
Ein Agent, der alles im Blick hat.
|
||||||
|
|
||||||
|
Der Archivar macht dieses Verhalten **automatisch**: Er weiß, welche Antwort
|
||||||
|
in welchen Raum gehört, ohne dass der Agent bei jeder Nachricht neu entscheiden
|
||||||
|
muss. Das ist Raumlogik, nicht Klassifikation um ihrer selbst willen.
|
||||||
|
|
||||||
|
## Historie
|
||||||
|
|
||||||
|
| Datum | Ereignis |
|
||||||
|
|-------|----------|
|
||||||
|
| 2026-05-29 | Erstes Konzept: Room-Topic-Map im RC-Skill dokumentiert |
|
||||||
|
| 2026-05-31 | Onboarding-Interview für neue Räume spezifiziert |
|
||||||
|
| 2026-06-03 | Commit `abe93cc`: Raum-Map anonymisiert (Vorbereitung öffentliches Repo) |
|
||||||
|
| 2026-06-03/04 | Archivar implementiert als 3-Kategorien-Klassifikator — **Abweichung vom Konzept** |
|
||||||
|
| 2026-06-05 | Konzeptionelles Audit: Ist-Zustand ≠ Architekturziel |
|
||||||
|
|
||||||
|
## Architekturziel (wiederherzustellen)
|
||||||
|
|
||||||
|
1. **Raum-Map ist die Single Source of Truth** für Themen-Zuordnung
|
||||||
|
2. **Onboarding-Interview** für jeden neuen Raum
|
||||||
|
3. **Einfacher Entscheidungsbaum:** Thema erkannt → Zielraum; kein Thema → Catch-All
|
||||||
|
4. **Stichwortlisten** pro Raum, nicht 2 hartcodierte Projekt-Keys
|
||||||
|
5. **LLM (Premium)** verbessert die Zuordnungsgenauigkeit, ersetzt aber nicht die Map
|
||||||
|
|
||||||
|
> **Ehern:** Der Archivar ist ein Router, kein Klassifikator.
|
||||||
|
> Die Frage ist nicht „Welche Kategorie?" sondern „In welchen Raum?"
|
||||||
|
|
||||||
|
## Gap-Analyse: Konzept vs. Implementierung (05.06.2026)
|
||||||
|
|
||||||
|
|
||||||
|
### Warum Rainer das nicht allein zu Ende denken kann
|
||||||
|
|
||||||
|
Diese Story ist ein **gutes Briefing**, aber **kein fertiger Architekturauftrag**.
|
||||||
|
Drei Lücken, die Rainer erst schließen müsste — und die der Lead (Bernd)
|
||||||
|
schließen sollte, bevor der Auftrag an den Architekten geht:
|
||||||
|
|
||||||
|
| # | Was fehlt | Warum Rainer es braucht |
|
||||||
|
|---|-----------|------------------------|
|
||||||
|
| **L1** | **Raum-Map-Format** — JSON? YAML? Python-Dict? Wo liegt sie? Wie wird sie geladen? | Die Map ist die Single Source of Truth. Ohne Format kann Rainer keine Schnittstelle definieren. |
|
||||||
|
| **L2** | **Catch-All-Validierung** — Wer stellt sicher, dass GENAU ein Raum Catch-All ist? Was passiert bei 0 oder 2? | Ohne diese Regel ist die ganze Architektur auf Sand gebaut. Rainer muss eine Gatekeeper-Funktion spezifizieren können. |
|
||||||
|
| **L3** | **Onboarding-Integration** — Ist das ein Gateway-Hook? Ein Agent-Tool? Ein Skill? Wann genau wird es getriggert? | Ohne Einhängepunkt kann Rainer nicht entscheiden, ob das Onboarding in der Gateway-Pipeline oder außerhalb läuft. |
|
||||||
|
|
||||||
|
### Empfehlung
|
||||||
|
|
||||||
|
Die Story ist **gut genug für Rainer**, wenn wir ihm die drei Lücken als
|
||||||
|
**explizite Entscheidungspunkte** mitgeben, nicht als offene Fragen:
|
||||||
|
|
||||||
|
1. **Raum-Map-Format:** JSON-Datei unter `~/.hermes/hermes-agent/data/room-map.json`. Struktur: `{ "rooms": { "<room_id>": { "theme": "...", "keywords": [...], "catch_all": false } } }`.
|
||||||
|
2. **Catch-All-Validierung:** Beim Gateway-Start prüft der Archivar, dass genau ein Raum `catch_all: true` hat. Bei 0 oder >1 → Gateway-Start wird abgelehnt mit klarer Fehlermeldung.
|
||||||
|
3. **Onboarding-Integration:** Wird als **Gateway-Hook** implementiert. Wenn der Gateway einen neuen Raum subscribed und dieser nicht in der Map ist, triggert ein Hook das Interview via DM an den Admin.
|
||||||
|
|
||||||
|
### Was der Code tut
|
||||||
|
|
||||||
|
Der Archivar ist als **3-Kategorien-Klassifikator** implementiert:
|
||||||
|
|
||||||
|
```
|
||||||
|
Nachricht → Keyword-Filter → Embedding (nomic-embed-text) → (LLM) → FAKT|FRAGE|ALARM
|
||||||
|
```
|
||||||
|
|
||||||
|
| Komponente | Datei | Funktion |
|
||||||
|
|------------|-------|----------|
|
||||||
|
| Keyword-Vorfilter | `classifier.py` | ALARM/FRAGE-Keywords → sofortige Entscheidung |
|
||||||
|
| Embedding-Klassifikation | `classifier.py` | `nomic-embed-text` → Kosinus-Ähnlichkeit gegen 3 Kategorietexte |
|
||||||
|
| LLM-Klassifikation | `classifier.py` | `qwen2.5:7b` für Grenzfälle (aktuell defekt — Prompt zu schwach) |
|
||||||
|
| Raum-Routing | `router.py` → `config.py` | 2 hartcodierte Projekte (`plugin`, `lan`) als Env-Vars |
|
||||||
|
| Doc-Store | `doc_store.py` | FAKT-Nachrichten → Filesystem |
|
||||||
|
|
||||||
|
### Gap 1: Keine thematische Raum-Map
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Jeder Raum hat ein **Thema** + Stichwortliste | 2 hartcodierte Projekt-Keys: `plugin`, `lan` |
|
||||||
|
| Map ist **Single Source of Truth** | Map existiert nicht — Env-Vars ersetzen die Map |
|
||||||
|
| Map wächst mit neuen Räumen (Onboarding) | Kein Onboarding — neue Räume bleiben blind |
|
||||||
|
|
||||||
|
### Gap 2: Keine Catch-All als Raum-Attribut
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Catch-All ist ein **Attribut eines Raums** | Catch-All ist eine eigene Env-Var: `ARCHIVAR_CATCHALL_ROOM` |
|
||||||
|
| Genau ein Raum trägt dieses Attribut | Kann auf jeden Raum zeigen — keine Validierung auf „genau einer" |
|
||||||
|
| Der Admin sieht gesammelte unklassifizierte Nachrichten | Landet aktuell im Protonbridge-Plugin-Raum (historisch) |
|
||||||
|
|
||||||
|
### Gap 3: Kein Multi-Agent-Raum-Ausschluss
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Multi-Agent-Raum **NIE** in der Map | Kein Code, der einen Raum ausschließt |
|
||||||
|
| Archivar ignoriert diesen Raum vollständig | Wenn jemand eine FRAGE im Multi-Agent-Raum postet, routet der Archivar sie → Endlosschleife |
|
||||||
|
|
||||||
|
### Gap 4: Kategorien statt Themen
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Frage: „In welchen **Raum**?" | Frage: „Welche **Kategorie**?" |
|
||||||
|
| Routing-Ziel: **Themenraum** | Routing-Ziel: 3 Kategorien → 3 Räume |
|
||||||
|
| FRAGE mit Plugin-Kontext → #Plugin-Dev | FRAGE → #BAT-Team (default), außer Keywords schlagen an |
|
||||||
|
|
||||||
|
### Gap 5: LLM als Raumfinder, nicht als Kategorie-Klassifikator
|
||||||
|
|
||||||
|
Der aktuelle LLM-Prompt fragt: „Welche Kategorie: FAKT, FRAGE oder ALARM?" — das ist die falsche Frage.
|
||||||
|
Die richtige Frage wäre: **„In welchen thematischen Raum gehört diese Nachricht?"**
|
||||||
|
|
||||||
|
Mit einer Raum-Map als Kontext könnte das LLM bedeutend präziser arbeiten:
|
||||||
|
|
||||||
|
```
|
||||||
|
Prompt (Konzept):
|
||||||
|
„Diese Räume sind verfügbar:
|
||||||
|
- #Frontend (Thema: UI, Design, CSS)
|
||||||
|
- #Backend (Thema: API, Datenbank, Auth)
|
||||||
|
- #Infrastruktur (Thema: Docker, Server, Backup)
|
||||||
|
- DM Admin (Catch-All für alles andere)
|
||||||
|
|
||||||
|
In welchen Raum gehört diese Nachricht?
|
||||||
|
Antworte nur mit dem Raum-Namen."
|
||||||
|
|
||||||
|
Prompt (aktuell):
|
||||||
|
„Klassifiziere in FAKT, FRAGE oder ALARM."
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Unterschied ist fundamental: Das LLM kann Kontext **verstehen**, nicht nur Stichworte **matchen**. Es erkennt, dass „Das Docker-Image für das Plugin ist kaputt" trotz des Worts „docker" in den Plugin-Raum gehört, weil der **Kontext** Plugin-Entwicklung ist — das Wort „docker" ist nur das Transportmittel.
|
||||||
|
|
||||||
|
## Stichwort-Frage: Reichen Keywords?
|
||||||
|
|
||||||
|
**Nein, reichen nicht.** Zwei Beispiele:
|
||||||
|
|
||||||
|
| Nachricht | Keywords matchen | Korrektes Routing |
|
||||||
|
|-----------|-----------------|-------------------|
|
||||||
|
| „Das Docker-Image für das Plugin ist kaputt" | `docker` → #Infrastruktur | **#Plugin-Dev** (Kontext: Plugin) |
|
||||||
|
| „Die API vom Trading-Modul hat Timeout" | `api` → #Backend | **#Trading** (Kontext: BAT) |
|
||||||
|
|
||||||
|
Stichworte sind **eindeutig bei klaren Themen** („css layout kaputt" → #Frontend), aber **mehrdeutig bei Querschnittsthemen** (docker, api, gateway — die kommen in mehreren Projekten vor).
|
||||||
|
|
||||||
|
**Das LLM KANN hier helfen** — nicht als Ersatz für die Stichwortliste, sondern als **Kontext-Interpretationsschicht darüber**. Der Ablauf wäre:
|
||||||
|
|
||||||
|
1. **Stichwort-Match** (schnell, billig) — bei eindeutigen Treffern direkt routen
|
||||||
|
2. **Mehrdeutig oder kein Treffer** → LLM fragt mit Raum-Map-Kontext: „In welchen Raum?"
|
||||||
|
3. **LLM antwortet mit Raum-Namen** → Archivar routet
|
||||||
|
|
||||||
|
Das LLM **ersetzt nicht die Map** — es **konsultiert sie**. Die Map bleibt die Single Source of Truth. Das LLM ist nur der bessere Leser.
|
||||||
+11
-11
@@ -1,22 +1,22 @@
|
|||||||
# Room Topic Map — rocket.chat.thomander.de
|
# Room Topic Map — Beispielkonfiguration
|
||||||
|
|
||||||
**Stand:** 31. Mai 2026 (wiederhergestellt nach Server-Rollback)
|
**Stand:** 03. Juni 2026 (anonymisiert für generische Verwendung)
|
||||||
**Catch-All:** DM andreas/Bernd (`69f4e777f06dba03be82dce7`)
|
**Catch-All:** DM Admin (`<ADMIN_DM_ROOM_ID>`)
|
||||||
|
|
||||||
## Gemappte Räume
|
## Gemappte Räume (Beispiele)
|
||||||
|
|
||||||
| Raum | Typ | Thema |
|
| Raum | Typ | Thema |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `#BAT-Team` | channel | BAT-Trading-Plattform (Docker-Stack, Commits, Agent-Health, Entwicklerteam) |
|
| `#Support-Team` | channel | Erst-Level-Support (Tickets, Bug-Reports, User-Feedback) |
|
||||||
| `Rocketchat-Plugin` | group | Hermes Rocket.Chat Plugin (Gateway, Upload, Buttons, Adapter) |
|
| `RC-Plugin-Dev` | group | Rocket.Chat Plugin-Entwicklung (Gateway, Upload, Buttons, Adapter) |
|
||||||
| `Protonbridge-Plugin` | group | ProtonMail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
| `Mail-Bridge-Plugin` | group | E-Mail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
||||||
| `DM andreas/Bernd` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
| `DM Admin` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
||||||
| `DM mit Bernd, Thomas` | dm | 🔇 Inaktiv — nur bei expliziter Aufforderung |
|
| `DM Team-Kollege` | dm | 🔇 Inaktiv — nur bei expliziter Aufforderung |
|
||||||
| `DM mit Bernd, Susi` | dm | Bot-zu-Bot-Kommunikation & Training — NUR auf explizite Aufforderung des Auftraggebers. Niemals ungefragt nutzen. |
|
| `DM Bot-Agent` | dm | Bot-zu-Bot-Kommunikation & Training — NUR auf explizite Aufforderung des Admins. Niemals ungefragt nutzen. |
|
||||||
|
|
||||||
## Virtuelle Keys (keine echten Räume — IMMER herausfiltern)
|
## Virtuelle Keys (keine echten Räume — IMMER herausfiltern)
|
||||||
|
|
||||||
- `user:bernd` — Option-C-Session-Key, kein Raum. Darf NICHT Catch-All werden.
|
- `user:admin` — Session-Sharing-Key, kein Raum. Darf NICHT Catch-All werden.
|
||||||
|
|
||||||
## Override-Regel
|
## Override-Regel
|
||||||
|
|
||||||
|
|||||||
Regular → Executable
+383
-38
@@ -11,6 +11,8 @@ ARG_LANG=""
|
|||||||
NONINTERACTIVE=false
|
NONINTERACTIVE=false
|
||||||
CHECK_ONLY=false
|
CHECK_ONLY=false
|
||||||
UPDATE_MODE=false
|
UPDATE_MODE=false
|
||||||
|
UPDATE_ONLY=false
|
||||||
|
UPDATE_AVAILABLE=false
|
||||||
|
|
||||||
# ─── Language packs ─────────────────────────────────────────
|
# ─── Language packs ─────────────────────────────────────────
|
||||||
declare -A T
|
declare -A T
|
||||||
@@ -42,11 +44,21 @@ load_lang() {
|
|||||||
[copying]="📁 Copying plugin files…"
|
[copying]="📁 Copying plugin files…"
|
||||||
[env_written]="🔑 Credentials written to %s"
|
[env_written]="🔑 Credentials written to %s"
|
||||||
[config_updated]="⚙️ config.yaml updated"
|
[config_updated]="⚙️ config.yaml updated"
|
||||||
|
[config_provisioned]="📄 Provisioned minimal config.yaml"
|
||||||
|
[env_provisioned]="🔧 Provisioned .env template"
|
||||||
|
[env_dropin]="🔌 Systemd EnvironmentFile drop-in installed"
|
||||||
|
[copied]="📁 Copied %d plugin files"
|
||||||
|
[ollama_check]="🔍 Checking Ollama..."
|
||||||
|
[ollama_missing]="⚠️ Ollama not found. Install: curl -fsSL https://ollama.com/install.sh | sh"
|
||||||
|
[nomic_pull]="📥 Pulling nomic-embed-text (274 MB)..."
|
||||||
|
[nomic_ok]="✅ nomic-embed-text ready"
|
||||||
|
[nomic_fail]="⚠️ nomic-embed-text pull failed — Archivar will use fallback mode"
|
||||||
|
[ollama_ok]="✅ Ollama ready"
|
||||||
[service_installed]="⚡ Gateway service installed"
|
[service_installed]="⚡ Gateway service installed"
|
||||||
[restarting]="🔄 Restarting gateway…"
|
[restarting]="🔄 Restarting gateway…"
|
||||||
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
|
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
|
||||||
[dry_info]="ℹ️ Use --help for all options."
|
[dry_info]="ℹ️ Use --help for all options."
|
||||||
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Check for updates only\n --update Check for updates and install if available"
|
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Check for updates only\n --update Check for updates and install if available\n --update-only Emergency deploy: Only deploy plugin files +\n restart gateway. No questions, no config provisioning,\n no Ollama. Uses find_hermes_dir() for path discovery."
|
||||||
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||||
[param_error]="❌ Unknown option: %s"
|
[param_error]="❌ Unknown option: %s"
|
||||||
[check_update]="🔍 Checking for updates…"
|
[check_update]="🔍 Checking for updates…"
|
||||||
@@ -58,6 +70,14 @@ load_lang() {
|
|||||||
[rollback]="⏪ Restoring backup: %s"
|
[rollback]="⏪ Restoring backup: %s"
|
||||||
[rollback_success]="✅ Backup successfully restored"
|
[rollback_success]="✅ Backup successfully restored"
|
||||||
[update_failed]="❌ Update failed. Error: %s"
|
[update_failed]="❌ Update failed. Error: %s"
|
||||||
|
[update_only_banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes RC Plugin — Emergency Deploy\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
[deploying]="📦 Deploying plugin files (update-only, no questions)..."
|
||||||
|
[deploy_done]="✅ %d files deployed to %s"
|
||||||
|
[cache_cleared]="🧹 Cleared __pycache__"
|
||||||
|
[verifying]="🔍 Verifying gateway..."
|
||||||
|
[verify_ok]="✅ Gateway running with Rocket.Chat connected"
|
||||||
|
[verify_fail]="⚠️ Gateway started but Rocket.Chat not detected in logs (check journalctl)"
|
||||||
|
[verify_timeout]="⏳ Waiting for Rocket.Chat handshake..."
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
# German (default)
|
# German (default)
|
||||||
@@ -78,11 +98,21 @@ load_lang() {
|
|||||||
[copying]="📁 Kopiere Plugin-Dateien…"
|
[copying]="📁 Kopiere Plugin-Dateien…"
|
||||||
[env_written]="🔑 Zugangsdaten gespeichert in %s"
|
[env_written]="🔑 Zugangsdaten gespeichert in %s"
|
||||||
[config_updated]="⚙️ config.yaml aktualisiert"
|
[config_updated]="⚙️ config.yaml aktualisiert"
|
||||||
|
[config_provisioned]="📄 Minimale config.yaml bereitgestellt"
|
||||||
|
[env_provisioned]="🔧 .env-Vorlage bereitgestellt"
|
||||||
|
[env_dropin]="🔌 Systemd EnvironmentFile-Drop-in installiert"
|
||||||
|
[copied]="📁 %d Plugin-Dateien kopiert"
|
||||||
|
[ollama_check]="🔍 Prüfe Ollama..."
|
||||||
|
[ollama_missing]="⚠️ Ollama nicht gefunden. Installation: curl -fsSL https://ollama.com/install.sh | sh"
|
||||||
|
[nomic_pull]="📥 Lade nomic-embed-text herunter (274 MB)..."
|
||||||
|
[nomic_ok]="✅ nomic-embed-text bereit"
|
||||||
|
[nomic_fail]="⚠️ nomic-embed-text Download fehlgeschlagen — Archivar nutzt Fallback-Modus"
|
||||||
|
[ollama_ok]="✅ Ollama bereit"
|
||||||
[service_installed]="⚡ Gateway-Service installiert"
|
[service_installed]="⚡ Gateway-Service installiert"
|
||||||
[restarting]="🔄 Starte Gateway neu…"
|
[restarting]="🔄 Starte Gateway neu…"
|
||||||
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
|
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
|
||||||
[dry_info]="ℹ️ Mit --help alle Optionen anzeigen."
|
[dry_info]="ℹ️ Mit --help alle Optionen anzeigen."
|
||||||
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren"
|
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren\n --update-only Notfall-Deployment: Nur Plugin-Dateien deployen +\n Gateway-Neustart. Keine Fragen, kein Config-Provisioning,\n kein Ollama. Nutzt find_hermes_dir() für Pfad-Ermittlung."
|
||||||
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||||
[param_error]="❌ Unbekannte Option: %s"
|
[param_error]="❌ Unbekannte Option: %s"
|
||||||
[check_update]="🔍 Prüfe auf Updates…"
|
[check_update]="🔍 Prüfe auf Updates…"
|
||||||
@@ -94,6 +124,14 @@ load_lang() {
|
|||||||
[rollback]="⏪ Stelle Backup wieder her: %s"
|
[rollback]="⏪ Stelle Backup wieder her: %s"
|
||||||
[rollback_success]="✅ Backup erfolgreich wiederhergestellt"
|
[rollback_success]="✅ Backup erfolgreich wiederhergestellt"
|
||||||
[update_failed]="❌ Update fehlgeschlagen. Fehler: %s"
|
[update_failed]="❌ Update fehlgeschlagen. Fehler: %s"
|
||||||
|
[update_only_banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes RC Plugin — Notfall-Deployment\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
[deploying]="📦 Deploye Plugin-Dateien (update-only, ohne Rückfragen)..."
|
||||||
|
[deploy_done]="✅ %d Dateien deployed nach %s"
|
||||||
|
[cache_cleared]="🧹 __pycache__ gelöscht"
|
||||||
|
[verifying]="🔍 Verifiziere Gateway..."
|
||||||
|
[verify_ok]="✅ Gateway läuft mit Rocket.Chat verbunden"
|
||||||
|
[verify_fail]="⚠️ Gateway gestartet, aber Rocket.Chat nicht im Log erkannt (prüfe journalctl)"
|
||||||
|
[verify_timeout]="⏳ Warte auf Rocket.Chat-Handshake..."
|
||||||
)
|
)
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -140,19 +178,108 @@ check_for_updates() {
|
|||||||
# If we can't determine versions, exit with error
|
# If we can't determine versions, exit with error
|
||||||
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
|
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
|
||||||
echo "Could not determine version information"
|
echo "Could not determine version information"
|
||||||
return 1
|
UPDATE_AVAILABLE=false
|
||||||
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Compare versions
|
# Compare versions
|
||||||
if [ "$local_version" != "$remote_version" ]; then
|
if [ "$local_version" != "$remote_version" ]; then
|
||||||
msg update_available "$remote_version" "$local_version"
|
msg update_available "$remote_version" "$local_version"
|
||||||
return 1 # Update available
|
UPDATE_AVAILABLE=true
|
||||||
|
return 0 # Update available
|
||||||
else
|
else
|
||||||
msg no_update "$local_version"
|
msg no_update "$local_version"
|
||||||
|
UPDATE_AVAILABLE=false
|
||||||
return 0 # No update needed
|
return 0 # No update needed
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
find_hermes_dir() {
|
||||||
|
# Priorität 1: --dir Flag (bereits in ARG_DIR gesetzt)
|
||||||
|
if [ -n "${ARG_DIR:-}" ]; then
|
||||||
|
if [ -d "$ARG_DIR" ]; then
|
||||||
|
echo "$ARG_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 2: Laufenden Gateway via systemd finden
|
||||||
|
if [ -z "${HERMES_DIR:-}" ] && systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
||||||
|
set +e
|
||||||
|
EXEC_PATH=$(systemctl --user show hermes-gateway -p ExecStart --value |
|
||||||
|
sed -n 's/.*path=\([^;]*\).*/\1/p' |
|
||||||
|
sed 's|/venv/bin/python.*||' |
|
||||||
|
sed 's|/.venv/bin/python.*||')
|
||||||
|
set -e
|
||||||
|
if [ -n "$EXEC_PATH" ] && [ -d "$EXEC_PATH" ]; then
|
||||||
|
echo "$EXEC_PATH"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 3: Laufenden Prozess via /proc scannen
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
set +e
|
||||||
|
PID=$(pgrep -f "hermes_cli.main gateway run" | head -1)
|
||||||
|
set -e
|
||||||
|
if [ -n "$PID" ] && [ -d "/proc/$PID/cwd" ]; then
|
||||||
|
HERMES_DIR=$(readlink -f "/proc/$PID/cwd")
|
||||||
|
if [ -n "$HERMES_DIR" ] && [ -d "$HERMES_DIR" ]; then
|
||||||
|
echo "$HERMES_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 4: command -v hermes → Symlink auflösen → Installationsverzeichnis ableiten
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
set +e
|
||||||
|
HERMES_CMD=$(command -v hermes 2>/dev/null)
|
||||||
|
set -e
|
||||||
|
if [ -n "$HERMES_CMD" ]; then
|
||||||
|
# Symlink auflösen
|
||||||
|
if [ -L "$HERMES_CMD" ]; then
|
||||||
|
HERMES_CMD=$(readlink -f "$HERMES_CMD")
|
||||||
|
fi
|
||||||
|
# Installationsverzeichnis ableiten (gehe 2 Ebenen nach oben: bin/hermes → .)
|
||||||
|
HERMES_DIR=$(dirname "$(dirname "$HERMES_CMD")")
|
||||||
|
if [ -n "$HERMES_DIR" ] && [ -d "$HERMES_DIR" ]; then
|
||||||
|
echo "$HERMES_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 5: python3 -c "from hermes_constants import get_hermes_home; print(get_hermes_home())"
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
set +e
|
||||||
|
HERMES_HOME=$(python3 -c "from hermes_constants import get_hermes_home; print(get_hermes_home())" 2>/dev/null)
|
||||||
|
set -e
|
||||||
|
if [ -n "$HERMES_HOME" ]; then
|
||||||
|
if [ -d "$HERMES_HOME/hermes-agent" ]; then
|
||||||
|
echo "$HERMES_HOME/hermes-agent"
|
||||||
|
return 0
|
||||||
|
elif [ -d "$HERMES_HOME" ]; then
|
||||||
|
echo "$HERMES_HOME"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 6 (Fallback): Die alte Pfad-Heuristik BEHALTEN, aber um FHS erweitern
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent" "/usr/local/lib/hermes-agent"; do
|
||||||
|
if [ -d "$d" ]; then
|
||||||
|
echo "$d"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Kein Hermes-Verzeichnis gefunden
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
create_backup() {
|
create_backup() {
|
||||||
local backup_file="$1"
|
local backup_file="$1"
|
||||||
local plugin_dir="$2"
|
local plugin_dir="$2"
|
||||||
@@ -175,12 +302,23 @@ perform_update() {
|
|||||||
# Change to repo directory
|
# Change to repo directory
|
||||||
cd "$script_dir"
|
cd "$script_dir"
|
||||||
|
|
||||||
# Get remote version
|
# Check if we have local changes and stash if needed
|
||||||
|
local stashed=false
|
||||||
|
if ! git diff --quiet; then
|
||||||
|
git stash push -m "Auto-stash before update"
|
||||||
|
stashed=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Get remote version (for display only)
|
||||||
local remote_version
|
local remote_version
|
||||||
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
|
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
|
||||||
|
|
||||||
if [ "$remote_version" = "unknown" ]; then
|
if [ "$remote_version" = "unknown" ]; then
|
||||||
msg update_failed "Could not determine remote version"
|
msg update_failed "Could not determine remote version"
|
||||||
|
# Restore stash if we had changes
|
||||||
|
if $stashed; then
|
||||||
|
git stash pop 2>/dev/null || true
|
||||||
|
fi
|
||||||
return 1
|
return 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -189,10 +327,7 @@ perform_update() {
|
|||||||
# Create backup before updating
|
# Create backup before updating
|
||||||
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
||||||
local hermes_dir
|
local hermes_dir
|
||||||
hermes_dir=""
|
hermes_dir=$(find_hermes_dir 2>/dev/null || echo "")
|
||||||
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
|
|
||||||
if [ -d "$d" ]; then hermes_dir="$d"; break; fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ -n "$hermes_dir" ]; then
|
if [ -n "$hermes_dir" ]; then
|
||||||
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
@@ -204,12 +339,45 @@ perform_update() {
|
|||||||
# Perform the update
|
# Perform the update
|
||||||
local update_error=""
|
local update_error=""
|
||||||
{
|
{
|
||||||
# Pull latest changes
|
# Pull latest changes (instead of checkout)
|
||||||
git fetch --tags origin 2>&1 || { update_error="Failed to fetch from remote"; return 1; }
|
git pull origin main 2>&1 || { update_error="Failed to pull from origin main"; return 1; }
|
||||||
git checkout "$remote_version" 2>&1 || { update_error="Failed to checkout version $remote_version"; return 1; }
|
|
||||||
|
|
||||||
# Run the installer to update files
|
# Copy plugin files directly (lines 448-466)
|
||||||
HERMES_DIR="$hermes_dir" UPDATE_MODE=true ./install.sh --non-interactive 2>&1
|
PLUGIN_DST="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
|
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
||||||
|
if [ -d "$script_dir/plugin" ]; then
|
||||||
|
# Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören
|
||||||
|
# Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur)
|
||||||
|
while read -r src; do
|
||||||
|
rel="${src#$script_dir/plugin/}"
|
||||||
|
dst="$PLUGIN_DST/$rel"
|
||||||
|
mkdir -p "$(dirname "$dst")"
|
||||||
|
cp "$src" "$dst"
|
||||||
|
done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||||
|
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
|
msg copied "$copied_count"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Execute backend checks directly (Ollama check from lines 429-446)
|
||||||
|
msg ollama_check
|
||||||
|
if command -v ollama >/dev/null 2>&1; then
|
||||||
|
msg ollama_ok
|
||||||
|
# nomic-embed-text laden falls nicht vorhanden
|
||||||
|
if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then
|
||||||
|
msg nomic_pull
|
||||||
|
if ollama pull nomic-embed-text 2>/dev/null; then
|
||||||
|
msg nomic_ok
|
||||||
|
else
|
||||||
|
msg nomic_fail
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg nomic_ok
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg ollama_missing
|
||||||
|
fi
|
||||||
} || {
|
} || {
|
||||||
# Update failed, rollback
|
# Update failed, rollback
|
||||||
if [ -n "$update_error" ]; then
|
if [ -n "$update_error" ]; then
|
||||||
@@ -227,6 +395,11 @@ perform_update() {
|
|||||||
rm -f "$backup_file"
|
rm -f "$backup_file"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Restore stash if we had changes
|
||||||
|
if $stashed; then
|
||||||
|
git stash pop 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +408,11 @@ perform_update() {
|
|||||||
|
|
||||||
msg update_success "$remote_version"
|
msg update_success "$remote_version"
|
||||||
|
|
||||||
|
# Restore stash if we had changes
|
||||||
|
if $stashed; then
|
||||||
|
git stash pop 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
# Restart gateway
|
# Restart gateway
|
||||||
if [ -n "$hermes_dir" ]; then
|
if [ -n "$hermes_dir" ]; then
|
||||||
cd "$hermes_dir"
|
cd "$hermes_dir"
|
||||||
@@ -245,6 +423,82 @@ perform_update() {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ─── Emergency Deploy (update-only) ─────────────────────────
|
||||||
|
perform_update_only() {
|
||||||
|
local script_dir
|
||||||
|
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
|
||||||
|
echo -e "\n${T[update_only_banner]}\n"
|
||||||
|
|
||||||
|
# 1. Find hermes directory
|
||||||
|
local hermes_dir
|
||||||
|
hermes_dir=$(find_hermes_dir 2>/dev/null || echo "")
|
||||||
|
if [ -z "$hermes_dir" ]; then
|
||||||
|
msg no_hermes; exit 1
|
||||||
|
fi
|
||||||
|
msg found_hermes "$hermes_dir"
|
||||||
|
|
||||||
|
# 2. Backup current state
|
||||||
|
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
||||||
|
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
|
if [ -d "$plugin_dir" ]; then
|
||||||
|
create_backup "$backup_file" "$plugin_dir" \
|
||||||
|
"$HOME/.hermes/config.yaml" \
|
||||||
|
"$HOME/.config/hermes/rocketchat.env"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. Deploy all plugin files
|
||||||
|
msg deploying
|
||||||
|
local PLUGIN_DST="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
|
if [ -d "$script_dir/plugin" ]; then
|
||||||
|
while read -r src; do
|
||||||
|
rel="${src#$script_dir/plugin/}"
|
||||||
|
dst="$PLUGIN_DST/$rel"
|
||||||
|
mkdir -p "$(dirname "$dst")"
|
||||||
|
cp "$src" "$dst"
|
||||||
|
done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||||
|
local copied_count
|
||||||
|
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
|
msg deploy_done "$copied_count" "$PLUGIN_DST"
|
||||||
|
else
|
||||||
|
msg update_failed "plugin/ directory not found in $script_dir"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4. Clear stale __pycache__
|
||||||
|
find "$PLUGIN_DST" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||||
|
msg cache_cleared
|
||||||
|
|
||||||
|
# 5. Restart gateway
|
||||||
|
msg restarting
|
||||||
|
systemctl --user daemon-reload 2>/dev/null || true
|
||||||
|
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||||
|
|
||||||
|
# 6. Verify Rocket.Chat connected (wait up to 15s)
|
||||||
|
msg verifying
|
||||||
|
local verified=false
|
||||||
|
for i in $(seq 1 6); do
|
||||||
|
sleep 2.5
|
||||||
|
if journalctl --user -u hermes-gateway --since "15 seconds ago" --no-pager 2>/dev/null \
|
||||||
|
| grep -q "Subscribed to.*rocketchat\|Connecting to rocketchat"; then
|
||||||
|
verified=true
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
msg verify_timeout
|
||||||
|
done
|
||||||
|
|
||||||
|
if $verified; then
|
||||||
|
msg verify_ok
|
||||||
|
rm -f "$backup_file"
|
||||||
|
else
|
||||||
|
msg verify_fail
|
||||||
|
fi
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
# ─── Argument parsing ────────────────────────────────────
|
# ─── Argument parsing ────────────────────────────────────
|
||||||
while [ $# -gt 0 ]; do
|
while [ $# -gt 0 ]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
@@ -261,6 +515,8 @@ while [ $# -gt 0 ]; do
|
|||||||
CHECK_ONLY=true; shift ;;
|
CHECK_ONLY=true; shift ;;
|
||||||
--update)
|
--update)
|
||||||
UPDATE_MODE=true; shift ;;
|
UPDATE_MODE=true; shift ;;
|
||||||
|
--update-only)
|
||||||
|
UPDATE_ONLY=true; shift ;;
|
||||||
*)
|
*)
|
||||||
load_lang "${ARG_LANG:-${LANG##*.}}"
|
load_lang "${ARG_LANG:-${LANG##*.}}"
|
||||||
msg param_error "$1"; echo; exit 1 ;;
|
msg param_error "$1"; echo; exit 1 ;;
|
||||||
@@ -275,23 +531,26 @@ echo -e "\n${T[banner]}\n"
|
|||||||
# ─── Update Check/Perform ──────────────────────────────────────
|
# ─── Update Check/Perform ──────────────────────────────────────
|
||||||
if $CHECK_ONLY; then
|
if $CHECK_ONLY; then
|
||||||
check_for_updates
|
check_for_updates
|
||||||
exit $?
|
if $UPDATE_AVAILABLE; then
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
elif $UPDATE_MODE; then
|
elif $UPDATE_MODE; then
|
||||||
check_for_updates
|
check_for_updates
|
||||||
if [ $? -eq 1 ]; then
|
if $UPDATE_AVAILABLE; then
|
||||||
perform_update
|
perform_update
|
||||||
exit $?
|
exit $?
|
||||||
else
|
else
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
elif $UPDATE_ONLY; then
|
||||||
|
perform_update_only
|
||||||
|
exit $?
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ─── Find Hermes Agent ────────────────────────────────────
|
|
||||||
msg checking
|
msg checking
|
||||||
HERMES_DIR=""
|
HERMES_DIR=$(find_hermes_dir)
|
||||||
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
|
|
||||||
if [ -d "$d" ]; then HERMES_DIR="$d"; break; fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ -z "$HERMES_DIR" ]; then
|
if [ -z "$HERMES_DIR" ]; then
|
||||||
msg no_hermes; exit 1
|
msg no_hermes; exit 1
|
||||||
@@ -301,7 +560,7 @@ msg found_hermes "$HERMES_DIR"
|
|||||||
# ─── Detect existing installation ─────────────────────────
|
# ─── Detect existing installation ─────────────────────────
|
||||||
ENV_FILE="$HOME/.config/hermes/rocketchat.env"
|
ENV_FILE="$HOME/.config/hermes/rocketchat.env"
|
||||||
HAVE_EXISTING=false
|
HAVE_EXISTING=false
|
||||||
RC_URL="" RC_BOT_USER="" RC_BOT_PASS="" RC_HOME_CHANNEL=""
|
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}" RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
|
||||||
|
|
||||||
if [ -f "$ENV_FILE" ]; then
|
if [ -f "$ENV_FILE" ]; then
|
||||||
HAVE_EXISTING=true
|
HAVE_EXISTING=true
|
||||||
@@ -314,8 +573,11 @@ fi
|
|||||||
|
|
||||||
# ─── Non-interactive mode ─────────────────────────────────
|
# ─── Non-interactive mode ─────────────────────────────────
|
||||||
if $NONINTERACTIVE; then
|
if $NONINTERACTIVE; then
|
||||||
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}"
|
# Read from environment variables (NOT local — respect what install.sh caller exports)
|
||||||
RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
|
RC_URL="${RC_URL:-${ROCKETCHAT_BASE_URL:-}}"
|
||||||
|
RC_BOT_USER="${RC_BOT_USER:-${ROCKETCHAT_USER:-}}"
|
||||||
|
RC_BOT_PASS="${RC_BOT_PASS:-${ROCKETCHAT_PASSWORD:-}}"
|
||||||
|
RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-${ROCKETCHAT_ROOM_NAME:-}}"
|
||||||
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
|
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
|
||||||
msg env_required; exit 1
|
msg env_required; exit 1
|
||||||
fi
|
fi
|
||||||
@@ -343,33 +605,105 @@ fi
|
|||||||
msg copying
|
msg copying
|
||||||
mkdir -p "$(dirname "$ENV_FILE")"
|
mkdir -p "$(dirname "$ENV_FILE")"
|
||||||
|
|
||||||
cat > "$ENV_FILE" <<EOF
|
# Bug #12: single-quoted delimiter verhindert $-Expansion im Passwort
|
||||||
|
cat > "$ENV_FILE" <<'EOF'
|
||||||
# Hermes Rocket.Chat Plugin — credentials (generated by install.sh)
|
# Hermes Rocket.Chat Plugin — credentials (generated by install.sh)
|
||||||
export ROCKETCHAT_BASE_URL="${RC_URL}"
|
# systemd-compatible: KEY=VALUE (no export prefix!)
|
||||||
export ROCKETCHAT_USER="${RC_BOT_USER}"
|
ROCKETCHAT_BASE_URL=PLACEHOLDER_RC_URL
|
||||||
export ROCKETCHAT_PASSWORD='${RC_BOT_PASS}'
|
ROCKETCHAT_USER=PLACEHOLDER_RC_USER
|
||||||
export ROCKETCHAT_ROOM_NAME="${RC_HOME_CHANNEL}"
|
ROCKETCHAT_PASSWORD=PLACEHOLDER_RC_PASS
|
||||||
export ROCKETCHAT_ALLOW_ALL_USERS=true
|
ROCKETCHAT_ROOM_NAME=PLACEHOLDER_RC_CHANNEL
|
||||||
export GATEWAY_ALLOW_ALL_USERS=true
|
ROCKETCHAT_ALLOW_ALL_USERS=true
|
||||||
export ROCKETCHAT_PING_SEC=8
|
GATEWAY_ALLOW_ALL_USERS=true
|
||||||
export ROCKETCHAT_IDLE_SEC=900
|
ROCKETCHAT_PING_SEC=8
|
||||||
|
ROCKETCHAT_IDLE_SEC=900
|
||||||
EOF
|
EOF
|
||||||
|
# Ersetze Platzhalter mit python3 (sicher für $-Zeichen im Passwort)
|
||||||
|
export RC_URL RC_BOT_USER RC_BOT_PASS RC_HOME_CHANNEL
|
||||||
|
export ENV_FILE
|
||||||
|
python3 -c "
|
||||||
|
import os
|
||||||
|
env_file = os.environ['ENV_FILE']
|
||||||
|
with open(env_file) as f:
|
||||||
|
content = f.read()
|
||||||
|
content = content.replace('PLACEHOLDER_RC_URL', os.environ.get('RC_URL', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_USER', os.environ.get('RC_BOT_USER', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_PASS', os.environ.get('RC_BOT_PASS', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_CHANNEL', os.environ.get('RC_HOME_CHANNEL', ''))
|
||||||
|
with open(env_file, 'w') as f:
|
||||||
|
f.write(content)
|
||||||
|
"
|
||||||
chmod 600 "$ENV_FILE"
|
chmod 600 "$ENV_FILE"
|
||||||
msg env_written "$ENV_FILE"
|
msg env_written "$ENV_FILE"
|
||||||
|
|
||||||
|
# ─── Ollama Check ─────────────────────────────────────────
|
||||||
|
msg ollama_check
|
||||||
|
if command -v ollama >/dev/null 2>&1; then
|
||||||
|
msg ollama_ok
|
||||||
|
# nomic-embed-text laden falls nicht vorhanden
|
||||||
|
if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then
|
||||||
|
msg nomic_pull
|
||||||
|
if ollama pull nomic-embed-text 2>/dev/null; then
|
||||||
|
msg nomic_ok
|
||||||
|
else
|
||||||
|
msg nomic_fail
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg nomic_ok
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg ollama_missing
|
||||||
|
fi
|
||||||
|
|
||||||
# ─── Copy plugin files ────────────────────────────────────
|
# ─── Copy plugin files ────────────────────────────────────
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
|
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
|
||||||
mkdir -p "$PLUGIN_DST"
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
for f in plugin.yaml __init__.py adapter.py tools.py; do
|
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
||||||
if [ -f "$SCRIPT_DIR/plugin/$f" ]; then
|
if [ -d "$SCRIPT_DIR/plugin" ]; then
|
||||||
cp "$SCRIPT_DIR/plugin/$f" "$PLUGIN_DST/$f"
|
# Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören
|
||||||
|
# Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur)
|
||||||
|
while read -r src; do
|
||||||
|
rel="${src#$SCRIPT_DIR/plugin/}"
|
||||||
|
dst="$PLUGIN_DST/$rel"
|
||||||
|
mkdir -p "$(dirname "$dst")"
|
||||||
|
cp "$src" "$dst"
|
||||||
|
done < <(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||||
|
copied_count=$(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
|
msg copied "$copied_count"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ─── Fix #9: Provision minimal config.yaml + .env ──────────
|
||||||
|
# Only when hermes has NO config yet (fresh install, no setup run)
|
||||||
|
HERMES_HOME="$HOME/.hermes"
|
||||||
|
CONFIG="$HERMES_HOME/config.yaml"
|
||||||
|
ENVFILE="$HERMES_HOME/.env"
|
||||||
|
|
||||||
|
if [ ! -f "$CONFIG" ]; then
|
||||||
|
mkdir -p "$HERMES_HOME"
|
||||||
|
if [ -f "$SCRIPT_DIR/templates/config.yaml" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/config.yaml" "$CONFIG"
|
||||||
|
# Placeholders mit echten Werten ersetzen
|
||||||
|
sed -i "s|PLACEHOLDER_RC_URL|${RC_URL}|g" "$CONFIG"
|
||||||
|
sed -i "s|PLACEHOLDER_RC_HOME_NAME|${RC_HOME_CHANNEL}|g" "$CONFIG"
|
||||||
|
# chat_id aus room_name auflösen (Rest-API oder User-ID-Mapping)
|
||||||
|
# Fallback: den room_name direkt als chat_id verwenden
|
||||||
|
sed -i "s|PLACEHOLDER_RC_HOME_CHAT_ID|${RC_HOME_CHANNEL}|g" "$CONFIG"
|
||||||
|
msg config_provisioned
|
||||||
fi
|
fi
|
||||||
done
|
fi
|
||||||
|
if [ ! -f "$ENVFILE" ] && [ -f "$SCRIPT_DIR/templates/.env" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/.env" "$ENVFILE"
|
||||||
|
chmod 600 "$ENVFILE"
|
||||||
|
# OLLAMA_API_KEY ersetzen falls gesetzt
|
||||||
|
if [ -n "${OLLAMA_API_KEY:-}" ]; then
|
||||||
|
sed -i "s|PLACEHOLDER_OLLAMA_API_KEY|${OLLAMA_API_KEY}|g" "$ENVFILE"
|
||||||
|
fi
|
||||||
|
msg env_provisioned
|
||||||
|
fi
|
||||||
|
|
||||||
# ─── Patch config.yaml ────────────────────────────────────
|
# ─── Patch config.yaml ────────────────────────────────────
|
||||||
CONFIG="$HOME/.hermes/config.yaml"
|
|
||||||
if [ -f "$CONFIG" ]; then
|
if [ -f "$CONFIG" ]; then
|
||||||
# Ensure rocketchat-platform is in plugins.enabled
|
# Ensure rocketchat-platform is in plugins.enabled
|
||||||
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
|
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
|
||||||
@@ -399,6 +733,17 @@ fi
|
|||||||
# Install / refresh systemd user service
|
# Install / refresh systemd user service
|
||||||
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
|
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
|
||||||
|
|
||||||
|
# ─── Fix #10: systemd EnvironmentFile drop-in ─────────────
|
||||||
|
# Gateway needs rocketchat.env + .env — hermes gateway install
|
||||||
|
# does not wire them automatically.
|
||||||
|
DROPDIN_DIR="$HOME/.config/systemd/user/hermes-gateway.service.d"
|
||||||
|
DROPDIN_FILE="$DROPDIN_DIR/env.conf"
|
||||||
|
mkdir -p "$DROPDIN_DIR"
|
||||||
|
if [ -f "$SCRIPT_DIR/templates/hermes-gateway-env.conf" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/hermes-gateway-env.conf" "$DROPDIN_FILE"
|
||||||
|
msg env_dropin
|
||||||
|
fi
|
||||||
|
|
||||||
# Ensure lingering is enabled (may need sudo — best-effort)
|
# Ensure lingering is enabled (may need sudo — best-effort)
|
||||||
loginctl enable-linger 2>/dev/null || true
|
loginctl enable-linger 2>/dev/null || true
|
||||||
|
|
||||||
|
|||||||
+84
-11
@@ -23,6 +23,8 @@ 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
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
||||||
@@ -33,11 +35,11 @@ if not logger.handlers:
|
|||||||
logger.addHandler(_handler)
|
logger.addHandler(_handler)
|
||||||
logger.propagate = False # Don't double-log to root
|
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
|
# 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
|
# 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.
|
# 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.
|
# without touching Hermes Core.
|
||||||
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||||
"_rocketchat_origin_room", default=""
|
"_rocketchat_origin_room", default=""
|
||||||
@@ -131,6 +133,30 @@ class RocketChatREST:
|
|||||||
}, data=payload)
|
}, data=payload)
|
||||||
return bool(r and r.get("success"))
|
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:
|
class DDPClient:
|
||||||
PING_INTERVAL = 8.0
|
PING_INTERVAL = 8.0
|
||||||
@@ -377,7 +403,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Clarify-Queue: tracks pending button questions per chat_id
|
# Clarify-Queue: tracks pending button questions per chat_id
|
||||||
# so incoming replies can be correlated with the original question.
|
# so incoming replies can be correlated with the original question.
|
||||||
self._pending_clarifies: Dict[str, dict] = {}
|
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.
|
# Key: "user:<username>", Value: list of real room_ids for that user.
|
||||||
# Built during connect() from REST get_rooms.
|
# Built during connect() from REST get_rooms.
|
||||||
self._user_rooms: Dict[str, List[str]] = {}
|
self._user_rooms: Dict[str, List[str]] = {}
|
||||||
@@ -386,6 +412,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._health_check_timer: Optional[threading.Timer] = None
|
self._health_check_timer: Optional[threading.Timer] = None
|
||||||
self._last_ddp_ping_ok = False
|
self._last_ddp_ping_ok = False
|
||||||
self._running = False
|
self._running = False
|
||||||
|
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||||||
|
self.archivar = ArchivarMessageHandler(send_callback=self._send_via_archivar)
|
||||||
|
|
||||||
async def connect(self) -> bool:
|
async def connect(self) -> bool:
|
||||||
if not self.base_url or not self.user or not self.password:
|
if not self.base_url or not self.user or not self.password:
|
||||||
@@ -413,7 +441,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
|
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] Subscribed to %s (%s)", room["name"], room["id"])
|
||||||
logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms))
|
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
|
# Each Rocket.Chat user gets a synthetic "user:<username>" chat_id that
|
||||||
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
||||||
# session per user across all rooms, enabling shared context.
|
# session per user across all rooms, enabling shared context.
|
||||||
@@ -438,6 +466,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.info("[rocketchat] Built user-room map: %d users, %s",
|
logger.info("[rocketchat] Built user-room map: %d users, %s",
|
||||||
len(self._user_rooms),
|
len(self._user_rooms),
|
||||||
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
||||||
|
# Archivar initialisieren (Embedding-basierte Klassifikation)
|
||||||
|
try:
|
||||||
|
await self.archivar.initialize()
|
||||||
|
# Feed the actual subscribed room IDs to the router so it can
|
||||||
|
# validate targets and store unrouteable messages in doc_store.
|
||||||
|
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||||||
|
logger.info("[rocketchat] Archivar initialisiert — Embedding-basierte Nachrichten-Klassifikation aktiv")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||||||
self._mark_connected()
|
self._mark_connected()
|
||||||
self._running = True
|
self._running = True
|
||||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||||
@@ -532,12 +569,22 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
|
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])
|
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.
|
# Replace room-based chat_id with user-based virtual chat_id.
|
||||||
# This collapses all rooms per user into ONE Hermes session:
|
# This collapses all rooms per user into ONE Hermes session:
|
||||||
# DM with andreas: room_id=ABC123 → chat_id="user:andreas"
|
# DM with alice: room_id=ABC123 → chat_id="user:alice"
|
||||||
# #BAT-Team: room_id=XYZ789 → chat_id="user:andreas"
|
# #Project-Chat: room_id=XYZ789 → chat_id="user:alice"
|
||||||
# Both get the same session key: agent:main:rocketchat:dm:user:andreas
|
# Both get the same session key.
|
||||||
virtual_chat_id = f"user:{username}"
|
virtual_chat_id = f"user:{username}"
|
||||||
# Track the REAL room for send() to route the response back
|
# Track the REAL room for send() to route the response back
|
||||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||||
@@ -556,7 +603,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
source = SessionSource(
|
source = SessionSource(
|
||||||
platform=Platform("rocketchat"),
|
platform=Platform("rocketchat"),
|
||||||
chat_id=virtual_chat_id, # ← user-based instead of room-based
|
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_id=username,
|
||||||
user_name=username,
|
user_name=username,
|
||||||
chat_type="dm", # ← force DM to bypass group isolation in Core
|
chat_type="dm", # ← force DM to bypass group isolation in Core
|
||||||
@@ -573,6 +620,32 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("[rocketchat] handle_message error: %s", 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:
|
async def disconnect(self) -> None:
|
||||||
self._mark_disconnected()
|
self._mark_disconnected()
|
||||||
self._shutdown_event.set()
|
self._shutdown_event.set()
|
||||||
@@ -594,8 +667,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if not self.rest.auth_token:
|
if not self.rest.auth_token:
|
||||||
return SendResult(success=False, error="Not authenticated")
|
return SendResult(success=False, error="Not authenticated")
|
||||||
|
|
||||||
# ── Option C: Virtual → Real Room Translation ─────────────────
|
# ── Virtual → Real Room Translation ─────────────────────────
|
||||||
# chat_id from Hermes session is virtual (e.g. "user:andreas").
|
# 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.
|
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||||
real_room_id = chat_id
|
real_room_id = chat_id
|
||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
---
|
||||||
|
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 → DocumentationStore (data/archivar_docs/fakt/{timestamp}.md)
|
||||||
|
│ FAKT ist Dokumentation, keine Kommunikation — niemals in Chat-Räume.
|
||||||
|
├─ FRAGE → Default-Zielraum oder projektspezifischer Raum
|
||||||
|
│ (Keyword-Matching: "plugin", "docs", "lan")
|
||||||
|
├─ ALARM → Direktnachricht an Admin
|
||||||
|
└─ < 0.6 → Catch-All-Raum
|
||||||
|
└─ Subscription-Validierung
|
||||||
|
└─ Nur Räume, die der Bot tatsächlich abonniert hat, werden als Ziel akzeptiert.
|
||||||
|
Nicht abonnierte Räume → DokumentationStore mit Begründung.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Konfiguration (Umgebungsvariablen)
|
||||||
|
|
||||||
|
Alle Raum-IDs werden über Umgebungsvariablen gesteuert — keine hartcodierten Werte:
|
||||||
|
|
||||||
|
| Variable | Zweck |
|
||||||
|
|---|---|
|
||||||
|
| `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"}`) |
|
||||||
|
|
||||||
|
> **FAKT** hat keine Raum-Variable mehr — Fakten sind Dokumentation, keine Kommunikation.
|
||||||
|
> Sie werden ausschließlich im DocumentationStore unter `data/archivar_docs/fakt/` abgelegt.
|
||||||
|
|
||||||
|
## DocumentationStore
|
||||||
|
|
||||||
|
Nicht-routbare Nachrichten (FAKT und Subscription-Fehler) werden als Markdown-Dateien
|
||||||
|
mit YAML-Frontmatter gespeichert:
|
||||||
|
|
||||||
|
```
|
||||||
|
~/.hermes/hermes-agent/data/archivar_docs/{kategorie}/{YYYY-MM-DD_HH-MM-SS}.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Jede Datei enthält:
|
||||||
|
- **Frontmatter:** `category`, `confidence`, `timestamp`, `origin_room`, `reason`
|
||||||
|
- **Body:** Vollständiger Nachrichtentext + Routing-Begründung
|
||||||
|
|
||||||
|
Der Doc-Store ist das **primäre Ziel für FAKT-Nachrichten** — nicht Fallback, kein Catch-All.
|
||||||
|
Nur FRAGE und ALARM werden jemals in Chat-Räume geroutet.
|
||||||
|
|
||||||
|
## 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 |
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
Archivar-Modul: Klassifikation und Routing von Nachrichten im Rocket.Chat Plugin.
|
||||||
|
|
||||||
|
Bietet embedding-basierte Klassifikation (nomic-embed-text via Ollama)
|
||||||
|
für die Kategorien FAKT, FRAGE, ALARM und leitet Nachrichtenkopien an
|
||||||
|
konfigurierte Zielräume weiter.
|
||||||
|
|
||||||
|
Architektur: Siehe docs/Archivar_Architecture.md
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .classifier import MessageClassifier, ClassificationResult, EmbeddingClient, OllamaEmbeddingClient
|
||||||
|
from .config import ROOM_MAPPING, CATCH_ALL_ROOM, CATEGORY_TEXTS, OLLAMA_CONFIG, CONFIDENCE_THRESHOLD
|
||||||
|
from .doc_store import DocumentationStore
|
||||||
|
from .router import MessageRouter, RoutingDecision
|
||||||
|
from .adapter_integration import ArchivarMessageHandler
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"MessageClassifier",
|
||||||
|
"ClassificationResult",
|
||||||
|
"EmbeddingClient",
|
||||||
|
"OllamaEmbeddingClient",
|
||||||
|
"DocumentationStore",
|
||||||
|
"ROOM_MAPPING",
|
||||||
|
"CATCH_ALL_ROOM",
|
||||||
|
"CATEGORY_TEXTS",
|
||||||
|
"OLLAMA_CONFIG",
|
||||||
|
"CONFIDENCE_THRESHOLD",
|
||||||
|
"MessageRouter",
|
||||||
|
"RoutingDecision",
|
||||||
|
"ArchivarMessageHandler",
|
||||||
|
]
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
"""
|
||||||
|
Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline.
|
||||||
|
|
||||||
|
Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt
|
||||||
|
in ``adapter.py`` dient. Sie kapselt Classifier + Router und bietet eine
|
||||||
|
einfache ``classify_and_route()``-Methode für die Nachrichten-Pipeline.
|
||||||
|
|
||||||
|
Einhängung in adapter.py::
|
||||||
|
|
||||||
|
from .adapter_integration import ArchivarMessageHandler
|
||||||
|
|
||||||
|
class RocketChatAdapter(BasePlatformAdapter):
|
||||||
|
def __init__(self, config):
|
||||||
|
...
|
||||||
|
self.archivar = ArchivarMessageHandler()
|
||||||
|
|
||||||
|
async def connect(self):
|
||||||
|
...
|
||||||
|
await self.archivar.initialize()
|
||||||
|
|
||||||
|
async def _process_incoming(self, msg_obj):
|
||||||
|
...
|
||||||
|
text = msg_obj.get("msg", "")
|
||||||
|
room_id = msg_obj.get("rid", "")
|
||||||
|
|
||||||
|
decision = await self.archivar.classify_and_route(text)
|
||||||
|
|
||||||
|
if decision.target_room != room_id:
|
||||||
|
# Kopie an Zielraum senden (Original bleibt!)
|
||||||
|
prefix = decision.prefix or ""
|
||||||
|
await self._send_to_room(decision.target_room, f"{prefix}{text}")
|
||||||
|
|
||||||
|
if decision.delete_original:
|
||||||
|
await self._delete_message(room_id, msg_id)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Any, Awaitable, Callable, Dict, Optional
|
||||||
|
|
||||||
|
from .classifier import (
|
||||||
|
ClassificationResult,
|
||||||
|
EmbeddingClient,
|
||||||
|
MessageClassifier,
|
||||||
|
LLMClient,
|
||||||
|
OllamaLLMClient,
|
||||||
|
)
|
||||||
|
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG, ROOM_MAP_PATH
|
||||||
|
from .doc_store import DocumentationStore
|
||||||
|
from .room_map import RoomMap, RoomMapValidationError
|
||||||
|
from .router import MessageRouter, RoutingDecision
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Callback-Signatur: async (room_id: str, text: str) -> bool
|
||||||
|
SendCallback = Callable[[str, str], Awaitable[bool]]
|
||||||
|
|
||||||
|
|
||||||
|
class ArchivarMessageHandler:
|
||||||
|
"""Hauptklasse für die Archivar-Integration.
|
||||||
|
|
||||||
|
Kapselt Classifier und Router. Wird vom RocketChatAdapter beim Start
|
||||||
|
initialisiert und bei jeder eingehenden Nachricht aufgerufen.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
handler = ArchivarMessageHandler()
|
||||||
|
await handler.initialize() # einmalig beim Adapter-Start
|
||||||
|
|
||||||
|
# Bei jeder Nachricht:
|
||||||
|
decision = await handler.classify_and_route(text)
|
||||||
|
# decision.target_room enthält die Zielraum-ID
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
send_callback: Optional[SendCallback] = None,
|
||||||
|
confidence_threshold: float = CONFIDENCE_THRESHOLD,
|
||||||
|
ollama_base_url: Optional[str] = None,
|
||||||
|
embedding_client: Optional[EmbeddingClient] = None,
|
||||||
|
llm_client: Optional[LLMClient] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
send_callback: Optionale async Callback-Funktion zum Senden von
|
||||||
|
Nachrichten via Rocket.Chat REST API. Signatur:
|
||||||
|
``async def send(room_id: str, text: str) -> bool``.
|
||||||
|
Wenn gesetzt, kann ``handle_and_forward()`` verwendet werden.
|
||||||
|
confidence_threshold: Konfidenz-Schwellenwert (0.0–1.0).
|
||||||
|
ollama_base_url: Override für Ollama-Basis-URL.
|
||||||
|
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||||
|
Wird an den ``MessageClassifier`` durchgereicht.
|
||||||
|
Ermöglicht Mocking/alternative Embedding-Backends.
|
||||||
|
llm_client: Optionales ``LLMClient``-Interface.
|
||||||
|
Wird an den ``MessageClassifier`` durchgereicht.
|
||||||
|
Ermöglicht Mocking/alternative LLM-Backends.
|
||||||
|
"""
|
||||||
|
self._send_callback = send_callback
|
||||||
|
self._enable_llm = LLM_CONFIG["enabled"]
|
||||||
|
|
||||||
|
# Create LLM client if enabled and not provided
|
||||||
|
if self._enable_llm and llm_client is None:
|
||||||
|
llm_client = OllamaLLMClient() if LLM_CONFIG["enabled"] else None
|
||||||
|
|
||||||
|
self._classifier = MessageClassifier(
|
||||||
|
base_url=ollama_base_url,
|
||||||
|
embedding_client=embedding_client,
|
||||||
|
llm_client=llm_client
|
||||||
|
)
|
||||||
|
self._doc_store = DocumentationStore()
|
||||||
|
|
||||||
|
# Load RoomMap (try JSON first, fall back to legacy env vars)
|
||||||
|
self._room_map = self._load_room_map()
|
||||||
|
|
||||||
|
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||||||
|
self._subscribed_room_ids_cache: Optional[set] = None
|
||||||
|
|
||||||
|
self._router = MessageRouter(self._room_map, self._classifier)
|
||||||
|
self._router.set_confidence_threshold(confidence_threshold)
|
||||||
|
self._initialized = False
|
||||||
|
|
||||||
|
# Statistiken (erweitert um Latenz + Fehler)
|
||||||
|
self._stats: Dict[str, Any] = {
|
||||||
|
"total": 0,
|
||||||
|
"classified": 0,
|
||||||
|
"catch_all": 0,
|
||||||
|
"fallback": 0,
|
||||||
|
"meta": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"llm_classified": 0, # Neue Statistik für LLM-Klassifikationen
|
||||||
|
"avg_latency_ms": 0.0, # float — gleitender Durchschnitt
|
||||||
|
"last_error": None, # str | None — letzter Fehler
|
||||||
|
"latencies": [], # list[float] — per-request ms
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── RoomMap Loading ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_room_map() -> RoomMap:
|
||||||
|
"""Load RoomMap from JSON, with legacy env var fallback.
|
||||||
|
|
||||||
|
Tries ``room-map.json`` first. If not found, attempts migration from
|
||||||
|
deprecated ``ARCHIVAR_*_ROOM`` env vars.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A ``RoomMap`` instance.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFoundError: If no map source is available.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
map_path = Path(ROOM_MAP_PATH)
|
||||||
|
|
||||||
|
if map_path.exists():
|
||||||
|
logger.info("Loading room map from %s", map_path)
|
||||||
|
return RoomMap.load(map_path)
|
||||||
|
|
||||||
|
# Try legacy env vars
|
||||||
|
logger.warning(
|
||||||
|
"Room map not found at %s — trying legacy ARCHIVAR_*_ROOM env vars",
|
||||||
|
map_path,
|
||||||
|
)
|
||||||
|
from .room_map import _migrate_from_env_vars
|
||||||
|
|
||||||
|
legacy_data = _migrate_from_env_vars()
|
||||||
|
if legacy_data is not None:
|
||||||
|
logger.warning(
|
||||||
|
"Using legacy env vars for room mapping. "
|
||||||
|
"Please create %s for new features.",
|
||||||
|
map_path,
|
||||||
|
)
|
||||||
|
return RoomMap._from_dict(legacy_data)
|
||||||
|
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"No room map found at {map_path} and no legacy "
|
||||||
|
"ARCHIVAR_*_ROOM env vars set. "
|
||||||
|
"Create a room-map.json or set ARCHIVAR_CATCHALL_ROOM."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def initialize(self) -> bool:
|
||||||
|
"""Einmalige Initialisierung: Pre-compute Kategorie-Vektoren + validiere Map.
|
||||||
|
|
||||||
|
Muss vor dem ersten ``classify_and_route()``-Aufruf aufgerufen werden.
|
||||||
|
Safe für mehrfache Aufrufe — no-op wenn bereits initialisiert.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True wenn die Initialisierung erfolgreich war (Classifier bereit).
|
||||||
|
False wenn Ollama nicht erreichbar ist → Fallback-Modus aktiv.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RoomMapValidationError: Wenn die room-map.json fatal invalide ist
|
||||||
|
(0 oder >1 Catch-All, Catch-All in excluded_rooms).
|
||||||
|
"""
|
||||||
|
if self._initialized:
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.info("Initializing ArchivarMessageHandler...")
|
||||||
|
|
||||||
|
# Validate RoomMap FIRST (fail-fast)
|
||||||
|
if self._subscribed_room_ids_cache is not None:
|
||||||
|
errors = self._room_map.validate(self._subscribed_room_ids_cache)
|
||||||
|
if errors:
|
||||||
|
logger.warning(
|
||||||
|
"Room map validation warnings: %s",
|
||||||
|
"; ".join(errors),
|
||||||
|
)
|
||||||
|
|
||||||
|
success = await self._classifier.initialize()
|
||||||
|
|
||||||
|
if success:
|
||||||
|
self._initialized = True
|
||||||
|
logger.info(
|
||||||
|
"ArchivarMessageHandler ready: %d categories, model=%s",
|
||||||
|
self._classifier.category_count,
|
||||||
|
OLLAMA_CONFIG["model"],
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"ArchivarMessageHandler initialized in FALLBACK mode — "
|
||||||
|
"Ollama unavailable at %s. Will use keyword heuristics.",
|
||||||
|
OLLAMA_CONFIG["base_url"],
|
||||||
|
)
|
||||||
|
# Mark as initialized anyway — the classifier will return None
|
||||||
|
# and the router will use keyword fallback.
|
||||||
|
self._initialized = True
|
||||||
|
|
||||||
|
return success
|
||||||
|
|
||||||
|
async def classify_and_route(
|
||||||
|
self, text: str, origin_room_id: str = ""
|
||||||
|
) -> RoutingDecision:
|
||||||
|
"""Klassifiziere eine Nachricht und ermittle den Zielraum.
|
||||||
|
|
||||||
|
Dies ist die primäre Methode für die adapter.py-Integration.
|
||||||
|
Sie führt die vollständige Klassifikation + Routing-Logik aus
|
||||||
|
und gibt eine ``RoutingDecision`` zurück.
|
||||||
|
|
||||||
|
Der Adapter entscheidet dann selbst über:
|
||||||
|
- Weiterleitung der Kopie an den Zielraum
|
||||||
|
- Löschen des Originals (bei Meta-Fragen)
|
||||||
|
- Hinzufügen von Präfix-Text ([FALLBACK], [META-FRAGE])
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoutingDecision mit Kategorie, Zielraum, Konfidenz und Metadaten.
|
||||||
|
"""
|
||||||
|
if not self._initialized:
|
||||||
|
logger.warning(
|
||||||
|
"classify_and_route() called before initialize() — "
|
||||||
|
"returning catch-all decision"
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room="", # Adapter soll selbst Catch-All verwenden
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
decision = await self._router.route(text, origin_room_id)
|
||||||
|
|
||||||
|
# Update stats
|
||||||
|
self._stats["total"] += 1
|
||||||
|
if decision.is_meta:
|
||||||
|
self._stats["meta"] += 1
|
||||||
|
elif decision.is_unrouteable:
|
||||||
|
self._stats["classified"] += 1
|
||||||
|
# Store in documentation store — message is classified but
|
||||||
|
# the target room is not in our subscription list
|
||||||
|
stored = self._doc_store.store(
|
||||||
|
text=text,
|
||||||
|
category=decision.category,
|
||||||
|
confidence=decision.confidence,
|
||||||
|
reason=decision.unrouteable_reason,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Unrouteable [%s] stored in doc_store: %s",
|
||||||
|
decision.category, stored,
|
||||||
|
)
|
||||||
|
elif decision.is_fallback:
|
||||||
|
self._stats["fallback"] += 1
|
||||||
|
elif decision.is_catch_all:
|
||||||
|
self._stats["catch_all"] += 1
|
||||||
|
else:
|
||||||
|
self._stats["classified"] += 1
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s",
|
||||||
|
decision.category,
|
||||||
|
decision.confidence,
|
||||||
|
decision.target_room[:8] if decision.target_room else "none",
|
||||||
|
decision.is_meta,
|
||||||
|
decision.is_fallback,
|
||||||
|
decision.is_catch_all,
|
||||||
|
)
|
||||||
|
|
||||||
|
return decision
|
||||||
|
|
||||||
|
async def handle_and_forward(
|
||||||
|
self, text: str, origin_room_id: str, message_id: str = ""
|
||||||
|
) -> RoutingDecision:
|
||||||
|
"""Klassifiziere UND leite die Nachricht weiter (All-in-One).
|
||||||
|
|
||||||
|
Convenience-Methode für Adapter, die die Logik nicht selbst
|
||||||
|
implementieren wollen. Benötigt ``send_callback`` im Konstruktor.
|
||||||
|
|
||||||
|
Ablauf:
|
||||||
|
1. classify_and_route(text)
|
||||||
|
2. Wenn target_room != origin_room: Kopie an target_room senden
|
||||||
|
3. Bei Meta-Fragen: delete_original=True im Decision setzen
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Nachrichtentext.
|
||||||
|
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||||
|
message_id: Rocket.Chat Nachrichten-ID (für Lösch-Operationen).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoutingDecision — der Adapter kann zusätzlich löschen/präfixen.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: Wenn kein send_callback gesetzt wurde.
|
||||||
|
"""
|
||||||
|
if not self._send_callback:
|
||||||
|
raise RuntimeError(
|
||||||
|
"handle_and_forward() requires a send_callback. "
|
||||||
|
"Pass send_callback to ArchivarMessageHandler() constructor, "
|
||||||
|
"or use classify_and_route() + manual forwarding."
|
||||||
|
)
|
||||||
|
|
||||||
|
t_start: float = time.monotonic()
|
||||||
|
|
||||||
|
decision = await self.classify_and_route(text)
|
||||||
|
|
||||||
|
# If unrouteable, don't try to forward — message is already in doc_store
|
||||||
|
if decision.is_unrouteable:
|
||||||
|
return decision
|
||||||
|
|
||||||
|
# Only forward if the target differs from origin
|
||||||
|
if decision.target_room and decision.target_room != origin_room_id:
|
||||||
|
prefix = decision.prefix or ""
|
||||||
|
forwarded_text = f"{prefix}{text}" if prefix else text
|
||||||
|
|
||||||
|
try:
|
||||||
|
success = await self._send_callback(
|
||||||
|
decision.target_room, forwarded_text
|
||||||
|
)
|
||||||
|
if success:
|
||||||
|
logger.info(
|
||||||
|
"Forwarded [%s] to room %s (conf=%.3f)",
|
||||||
|
decision.category,
|
||||||
|
decision.target_room[:8],
|
||||||
|
decision.confidence,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.error(
|
||||||
|
"Failed to forward [%s] to room %s",
|
||||||
|
decision.category,
|
||||||
|
decision.target_room[:8],
|
||||||
|
)
|
||||||
|
self._stats["errors"] += 1
|
||||||
|
self._stats["last_error"] = (
|
||||||
|
f"Send callback returned False for room "
|
||||||
|
f"{decision.target_room[:8]}"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
"Exception forwarding [%s] to room %s: %s",
|
||||||
|
decision.category,
|
||||||
|
decision.target_room[:8],
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
self._stats["errors"] += 1
|
||||||
|
self._stats["last_error"] = str(e)
|
||||||
|
|
||||||
|
# Update rolling average latency
|
||||||
|
elapsed_ms: float = (time.monotonic() - t_start) * 1000.0
|
||||||
|
self._stats["latencies"].append(elapsed_ms)
|
||||||
|
n: int = len(self._stats["latencies"])
|
||||||
|
if n > 0:
|
||||||
|
self._stats["avg_latency_ms"] = (
|
||||||
|
sum(self._stats["latencies"]) / n
|
||||||
|
)
|
||||||
|
|
||||||
|
return decision
|
||||||
|
|
||||||
|
# ── Statistics ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def stats(self) -> Dict[str, int]:
|
||||||
|
"""Read-only copy of classification statistics."""
|
||||||
|
return dict(self._stats)
|
||||||
|
|
||||||
|
def reset_stats(self) -> None:
|
||||||
|
"""Reset statistics counters."""
|
||||||
|
self._stats = {
|
||||||
|
"total": 0,
|
||||||
|
"classified": 0,
|
||||||
|
"catch_all": 0,
|
||||||
|
"fallback": 0,
|
||||||
|
"meta": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"avg_latency_ms": 0.0,
|
||||||
|
"last_error": None,
|
||||||
|
"latencies": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Configuration ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def confidence_threshold(self) -> float:
|
||||||
|
"""Current confidence threshold."""
|
||||||
|
return self._router.confidence_threshold
|
||||||
|
|
||||||
|
def set_confidence_threshold(self, value: float) -> None:
|
||||||
|
"""Override confidence threshold at runtime."""
|
||||||
|
self._router.set_confidence_threshold(value)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_initialized(self) -> bool:
|
||||||
|
"""True if handler is ready for classification."""
|
||||||
|
return self._initialized
|
||||||
|
|
||||||
|
@property
|
||||||
|
def classifier_ready(self) -> bool:
|
||||||
|
"""True if the embedding classifier is operational (not just fallback)."""
|
||||||
|
return self._classifier.is_initialized
|
||||||
|
|
||||||
|
def set_send_callback(self, callback: SendCallback) -> None:
|
||||||
|
"""Set or replace the send callback after construction.
|
||||||
|
|
||||||
|
Ermöglicht ``handle_and_forward()``-Nutzung auch wenn der Callback
|
||||||
|
erst nach der Konstruktion verfügbar ist (z.B. nach REST-Login).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
callback: Async function ``(room_id, text) -> bool``.
|
||||||
|
"""
|
||||||
|
self._send_callback = callback
|
||||||
|
logger.debug("Send callback registered")
|
||||||
|
|
||||||
|
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||||
|
"""Set the bot's current subscribed room IDs for routing validation.
|
||||||
|
|
||||||
|
When set, the router will ONLY forward messages to rooms in this list.
|
||||||
|
Messages targeting unsubscribed rooms are stored in the
|
||||||
|
DocumentationStore instead.
|
||||||
|
|
||||||
|
Call this after adapter.connect() when the subscription list is ready.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_ids: List of Rocket.Chat room IDs the bot is currently
|
||||||
|
subscribed to. Pass None to disable validation.
|
||||||
|
"""
|
||||||
|
self._subscribed_room_ids_cache = set(room_ids) if room_ids else None
|
||||||
|
self._router.set_subscribed_room_ids(room_ids)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def doc_store(self) -> DocumentationStore:
|
||||||
|
"""Documentation store for unrouteable messages."""
|
||||||
|
return self._doc_store
|
||||||
@@ -0,0 +1,598 @@
|
|||||||
|
"""
|
||||||
|
Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434).
|
||||||
|
|
||||||
|
Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
||||||
|
berechneten Kategorie-Vektoren (FAKT, FRAGE, ALARM) via Kosinus-Ähnlichkeit.
|
||||||
|
Bei Ollama-Fehlern oder Timeout wird None als ClassificationResult
|
||||||
|
zurückgegeben — der Router übernimmt dann den Fallback.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import abc
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ClassificationResult:
|
||||||
|
"""Ergebnis einer Embedding-basierten Klassifikation."""
|
||||||
|
|
||||||
|
category: str
|
||||||
|
"""Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'."""
|
||||||
|
|
||||||
|
confidence: float
|
||||||
|
"""Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor."""
|
||||||
|
|
||||||
|
all_scores: Dict[str, float] = field(default_factory=dict)
|
||||||
|
"""Alle Kategorie-Scores für Debugging/Transparenz."""
|
||||||
|
|
||||||
|
latency_ms: float = 0.0
|
||||||
|
"""Gemessene Latenz der Embedding-API in Millisekunden."""
|
||||||
|
|
||||||
|
fallback: bool = False
|
||||||
|
"""True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||||
|
|
||||||
|
def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool:
|
||||||
|
"""True wenn die Konfidenz über dem Schwellenwert liegt."""
|
||||||
|
return self.confidence >= threshold
|
||||||
|
|
||||||
|
def is_fallback(self) -> bool:
|
||||||
|
"""True wenn dieses Ergebnis aus der Keyword-Heuristik stammt."""
|
||||||
|
return self.fallback
|
||||||
|
|
||||||
|
|
||||||
|
# ── Embedding Client Interface (injectable) ─────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class EmbeddingClient(abc.ABC):
|
||||||
|
"""Interface for embedding providers. Injectable for testability.
|
||||||
|
|
||||||
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
|
single ``get_embedding()`` method so that ``MessageClassifier`` can
|
||||||
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
|
Implementations must be thread-safe since ``MessageClassifier`` calls
|
||||||
|
``get_embedding()`` synchronously inside ``asyncio.to_thread``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Return the embedding vector for *text*, or None on failure.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The text to embed.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A list of floats representing the embedding vector,
|
||||||
|
or ``None`` if the embedding could not be computed.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def __subclasshook__(cls, subclass):
|
||||||
|
if cls is EmbeddingClient:
|
||||||
|
if any("get_embedding" in B.__dict__ for B in subclass.__mro__):
|
||||||
|
return True
|
||||||
|
return NotImplemented
|
||||||
|
|
||||||
|
|
||||||
|
class OllamaEmbeddingClient(EmbeddingClient):
|
||||||
|
"""Embedding client backed by Ollama's `/api/embeddings` endpoint.
|
||||||
|
|
||||||
|
Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||||||
|
the ``EmbeddingClient`` interface. Works with every Ollama model
|
||||||
|
that exposes the embeddings API (``nomic-embed-text`` recommended).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
client = OllamaEmbeddingClient()
|
||||||
|
vector = client.get_embedding("hello world")
|
||||||
|
# → [0.123, -0.456, ...] (768 floats for nomic-embed-text)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama base URL (default from ``config.OLLAMA_CONFIG``).
|
||||||
|
model: Embedding model (default from ``config.OLLAMA_CONFIG``).
|
||||||
|
timeout: Request timeout in seconds (default from ``config.OLLAMA_CONFIG``).
|
||||||
|
"""
|
||||||
|
self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or OLLAMA_CONFIG["model"]
|
||||||
|
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||||
|
|
||||||
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Call Ollama embeddings API. Returns None on any failure."""
|
||||||
|
url = f"{self._base_url}/api/embeddings"
|
||||||
|
payload = json.dumps(
|
||||||
|
{"model": self._model, "prompt": text}
|
||||||
|
).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=payload, headers=headers, method="POST"
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
embedding = data.get("embedding")
|
||||||
|
if not embedding or not isinstance(embedding, list):
|
||||||
|
logger.error(
|
||||||
|
"Ollama returned invalid embedding: %s", type(embedding)
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
return [float(v) for v in embedding]
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||||||
|
return None
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
logger.warning("Ollama connection failed: %s", e)
|
||||||
|
return None
|
||||||
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
|
logger.error("Ollama response parse error: %s", e)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unexpected error in get_embedding: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── LLM Client Interface (injectable) ───────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class LLMClient(abc.ABC):
|
||||||
|
"""Interface for LLM providers. Injectable for testability.
|
||||||
|
|
||||||
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
|
single ``classify()`` method so that ``MessageClassifier`` can
|
||||||
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
|
Implementations must be thread-safe since ``MessageClassifier`` calls
|
||||||
|
``classify()`` synchronously inside ``asyncio.to_thread``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Klassifiziere Text. Gibt Kategorie-String oder None zurück."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class OllamaLLMClient(LLMClient):
|
||||||
|
"""LLM client backed by Ollama's `/api/generate` endpoint.
|
||||||
|
|
||||||
|
Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||||||
|
the ``LLMClient`` interface. Works with every Ollama model that
|
||||||
|
exposes the generate API (``qwen2.5:7b`` recommended).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
client = OllamaLLMClient()
|
||||||
|
category = client.classify("Wie funktioniert das Plugin?")
|
||||||
|
# → "FRAGE"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama base URL (default from ``config.LLM_CONFIG``).
|
||||||
|
model: LLM model (default from ``config.LLM_CONFIG``).
|
||||||
|
timeout: Request timeout in seconds (default from ``config.LLM_CONFIG``).
|
||||||
|
"""
|
||||||
|
self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or LLM_CONFIG["model"]
|
||||||
|
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||||
|
|
||||||
|
def classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||||
|
url = f"{self._base_url}/api/generate"
|
||||||
|
payload = json.dumps(
|
||||||
|
{
|
||||||
|
"model": self._model,
|
||||||
|
"prompt": text,
|
||||||
|
"stream": False,
|
||||||
|
"options": {
|
||||||
|
"temperature": LLM_CONFIG["temperature"],
|
||||||
|
"num_predict": LLM_CONFIG["max_tokens"],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=payload, headers=headers, method="POST"
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
response_text = data.get("response", "")
|
||||||
|
if not response_text:
|
||||||
|
logger.error("Ollama returned empty response")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Trim whitespace and normalize category
|
||||||
|
category = response_text.strip().upper()
|
||||||
|
if category in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return category
|
||||||
|
else:
|
||||||
|
logger.warning("LLM returned invalid category: %s", category)
|
||||||
|
return None
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||||||
|
return None
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
logger.warning("Ollama connection failed: %s", e)
|
||||||
|
return None
|
||||||
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
|
logger.error("Ollama response parse error: %s", e)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unexpected error in classify: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class MessageClassifier:
|
||||||
|
"""Embedding-basierter Nachrichten-Klassifizierer.
|
||||||
|
|
||||||
|
Verwendet nomic-embed-text via Ollama-API auf localhost:11434.
|
||||||
|
Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher
|
||||||
|
gehalten (Caching für Sub-100ms-Performance).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
classifier = MessageClassifier()
|
||||||
|
await classifier.initialize() # pre-compute category vectors
|
||||||
|
result = await classifier.classify("Wie funktioniert das Plugin?")
|
||||||
|
print(result.category) # → "FRAGE"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
embedding_client: Optional[EmbeddingClient] = None,
|
||||||
|
llm_client: Optional[LLMClient] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama-Basis-URL (default: aus config.py).
|
||||||
|
Ignoriert wenn *embedding_client* gesetzt ist.
|
||||||
|
model: Embedding-Modell (default: 'nomic-embed-text').
|
||||||
|
Ignoriert wenn *embedding_client* gesetzt ist.
|
||||||
|
timeout: Timeout in Sekunden (default: 5.0).
|
||||||
|
Ignoriert wenn *embedding_client* gesetzt ist.
|
||||||
|
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||||
|
Wenn gesetzt, werden alle Embedding-Calls an diesen
|
||||||
|
Client delegiert (z.B. für Mocks oder alternative
|
||||||
|
Backends). Wenn ``None``, wird ein
|
||||||
|
``OllamaEmbeddingClient`` mit *base_url*, *model*
|
||||||
|
und *timeout* erstellt.
|
||||||
|
llm_client: Optionales ``LLMClient``-Interface.
|
||||||
|
Wenn gesetzt, werden LLM-Calls an diesen Client
|
||||||
|
delegiert. Wenn ``None`` und LLM aktiviert ist,
|
||||||
|
wird ein ``OllamaLLMClient`` erstellt.
|
||||||
|
"""
|
||||||
|
if embedding_client is not None:
|
||||||
|
self._embedding_client: EmbeddingClient = embedding_client
|
||||||
|
self._base_url = "injected"
|
||||||
|
self._model = "injected"
|
||||||
|
self._timeout = 0.0
|
||||||
|
else:
|
||||||
|
self._embedding_client = OllamaEmbeddingClient(
|
||||||
|
base_url=base_url, model=model, timeout=timeout
|
||||||
|
)
|
||||||
|
self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or OLLAMA_CONFIG["model"]
|
||||||
|
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||||
|
self._embedding_dim = OLLAMA_CONFIG["embedding_dim"]
|
||||||
|
|
||||||
|
# Handle LLM client
|
||||||
|
self._llm_enabled = LLM_CONFIG["enabled"]
|
||||||
|
if self._llm_enabled:
|
||||||
|
if llm_client is not None:
|
||||||
|
self._llm_client: Optional[LLMClient] = llm_client
|
||||||
|
else:
|
||||||
|
self._llm_client = OllamaLLMClient(
|
||||||
|
base_url=LLM_CONFIG["base_url"],
|
||||||
|
model=LLM_CONFIG["model"],
|
||||||
|
timeout=LLM_CONFIG["timeout"]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._llm_client = None
|
||||||
|
|
||||||
|
# Cache: category → embedding vector (768 floats)
|
||||||
|
self._category_vectors: Dict[str, List[float]] = {}
|
||||||
|
self._initialized: bool = False
|
||||||
|
self._init_error: Optional[str] = None
|
||||||
|
|
||||||
|
# Cache: message text → embedding (avoids re-embedding duplicates)
|
||||||
|
self._message_cache: Dict[str, List[float]] = {}
|
||||||
|
self._cache_max_size: int = 100
|
||||||
|
|
||||||
|
def _keyword_prefilter(self, text: str) -> Optional[str]:
|
||||||
|
"""Stufe 0: Keyword-Vorfilter. Liefert 'ALARM', 'FRAGE' oder None."""
|
||||||
|
from .config import FALLBACK_KEYWORDS
|
||||||
|
|
||||||
|
t = text.lower()
|
||||||
|
# ALARM ZUERST — höchste Priorität
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||||||
|
if kw in t:
|
||||||
|
return "ALARM"
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||||||
|
if kw in t:
|
||||||
|
return "FRAGE"
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _llm_classify(self, text: str) -> Optional[str]:
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._llm_classify_sync, text)
|
||||||
|
|
||||||
|
def _llm_classify_sync(self, text: str) -> Optional[str]:
|
||||||
|
try:
|
||||||
|
if not self._llm_client or not self._llm_enabled:
|
||||||
|
return None
|
||||||
|
|
||||||
|
prompt = LLM_CLASSIFY_PROMPT.format(text=text)
|
||||||
|
result = self._llm_client.classify(prompt)
|
||||||
|
if result in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("LLM classification failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _llm_raw_sync(self, prompt: str) -> Optional[str]:
|
||||||
|
"""Send a raw prompt to the LLM and return its response.
|
||||||
|
|
||||||
|
Unlike ``_llm_classify_sync``, this does NOT validate against
|
||||||
|
FAKT/FRAGE/ALARM categories. Used by the RoomRouter for the
|
||||||
|
``LLM_ROOM_PROMPT`` where the expected answer is a room name.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prompt: The complete prompt to send.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The LLM's response text (stripped), or None on failure.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self._llm_client or not self._llm_enabled:
|
||||||
|
return None
|
||||||
|
result = self._llm_client.classify(prompt)
|
||||||
|
if result:
|
||||||
|
return result.strip()
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("LLM raw call failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def initialize(self) -> bool:
|
||||||
|
"""Pre-compute category vectors. Returns True on success.
|
||||||
|
|
||||||
|
Must be called once before classify(). Safe to call multiple times —
|
||||||
|
subsequent calls are no-ops if already initialized.
|
||||||
|
|
||||||
|
This is async to fit into the adapter's async startup lifecycle.
|
||||||
|
Internally calls synchronous urllib.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._initialize_sync)
|
||||||
|
|
||||||
|
def _initialize_sync(self) -> bool:
|
||||||
|
"""Synchronous initialization logic."""
|
||||||
|
if self._initialized:
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Initializing classifier: model=%s, base_url=%s, timeout=%.1fs",
|
||||||
|
self._model, self._base_url, self._timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
success = True
|
||||||
|
for category, text in CATEGORY_TEXTS.items():
|
||||||
|
vector = self._get_embedding(text)
|
||||||
|
if vector is None:
|
||||||
|
logger.error(
|
||||||
|
"Failed to compute embedding for category '%s' — "
|
||||||
|
"classifier will use fallback",
|
||||||
|
category,
|
||||||
|
)
|
||||||
|
self._init_error = f"Failed to embed category '{category}'"
|
||||||
|
success = False
|
||||||
|
break
|
||||||
|
self._category_vectors[category] = vector
|
||||||
|
logger.debug("Category '%s' vectorized (%d dims)", category, len(vector))
|
||||||
|
|
||||||
|
if success:
|
||||||
|
self._initialized = True
|
||||||
|
logger.info(
|
||||||
|
"Classifier initialized successfully (%d categories)",
|
||||||
|
len(self._category_vectors),
|
||||||
|
)
|
||||||
|
return success
|
||||||
|
|
||||||
|
async def classify(self, text: str) -> Optional[ClassificationResult]:
|
||||||
|
"""Classify a message text. Returns None if embedding fails completely.
|
||||||
|
|
||||||
|
This is async to fit into the adapter's async pipeline.
|
||||||
|
Internally calls synchronous urllib.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The message text to classify.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ClassificationResult with category and confidence,
|
||||||
|
or None if the classifier is not initialized or embedding fails.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._classify_sync, text)
|
||||||
|
|
||||||
|
def _classify_sync(self, text: str) -> Optional[ClassificationResult]:
|
||||||
|
if not self._initialized:
|
||||||
|
logger.warning("classify() called before initialize() — returning None")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not text or not text.strip():
|
||||||
|
return None
|
||||||
|
|
||||||
|
text = text.strip()
|
||||||
|
|
||||||
|
t0 = time.monotonic()
|
||||||
|
|
||||||
|
# Stufe 0: Keyword-Vorfilter
|
||||||
|
keyword_result = self._keyword_prefilter(text)
|
||||||
|
if keyword_result == "ALARM":
|
||||||
|
# ALARM hat höchste Priorität - sofortige Rückgabe
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
return ClassificationResult(
|
||||||
|
category="ALARM",
|
||||||
|
confidence=0.95, # Hohe Konfidenz für Keyword-Treffer
|
||||||
|
all_scores={"ALARM": 0.95, "FRAGE": 0.0, "FAKT": 0.0},
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
# Für FRAGE geht es weiter zur Embedding-Klassifikation (mit niedrigerem Schwellwert)
|
||||||
|
|
||||||
|
# Stufe 1: Embedding-Klassifikation
|
||||||
|
vector = self._get_cached_or_compute(text)
|
||||||
|
if vector is None:
|
||||||
|
logger.debug("Failed to embed message: %.60s...", text)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Compare against all category vectors
|
||||||
|
scores: Dict[str, float] = {}
|
||||||
|
best_category: str = ""
|
||||||
|
best_score: float = -1.0
|
||||||
|
|
||||||
|
for category, cat_vector in self._category_vectors.items():
|
||||||
|
score = self._cosine_similarity(vector, cat_vector)
|
||||||
|
scores[category] = score
|
||||||
|
if score > best_score:
|
||||||
|
best_score = score
|
||||||
|
best_category = category
|
||||||
|
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
|
||||||
|
if best_score < 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Prüfe, ob die Embedding-Konfidenz ausreicht
|
||||||
|
if best_score >= LLM_CONFIDENCE_THRESHOLD:
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Stufe 2: LLM-Klassifikation, wenn Konfidenz niedrig ist
|
||||||
|
if self._llm_enabled and best_score < LLM_CONFIDENCE_THRESHOLD and self._llm_client:
|
||||||
|
llm_category = self._llm_classify_sync(text)
|
||||||
|
if llm_category:
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
return ClassificationResult(
|
||||||
|
category=llm_category,
|
||||||
|
confidence=0.95, # Hohe Konfidenz für LLM-Klassifikation
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ansonsten: originales Embedding-Ergebnis zurückgeben (auch wenn unter Schwellwert)
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Embedding-API ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Delegate to the injectable ``EmbeddingClient``.
|
||||||
|
|
||||||
|
Returns None on any failure — the caller (router) handles fallback.
|
||||||
|
"""
|
||||||
|
return self._embedding_client.get_embedding(text)
|
||||||
|
|
||||||
|
def _get_cached_or_compute(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Return cached embedding or compute and cache a new one."""
|
||||||
|
# Simple LRU-like: evict if over max
|
||||||
|
if len(self._message_cache) >= self._cache_max_size:
|
||||||
|
# Evict the oldest key (first inserted)
|
||||||
|
oldest = next(iter(self._message_cache))
|
||||||
|
del self._message_cache[oldest]
|
||||||
|
|
||||||
|
if text in self._message_cache:
|
||||||
|
return self._message_cache[text]
|
||||||
|
|
||||||
|
vector = self._get_embedding(text)
|
||||||
|
if vector is not None:
|
||||||
|
self._message_cache[text] = vector
|
||||||
|
return vector
|
||||||
|
|
||||||
|
# ── Math ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _cosine_similarity(a: List[float], b: List[float]) -> float:
|
||||||
|
"""Compute cosine similarity between two vectors.
|
||||||
|
|
||||||
|
Returns 0.0 if either vector has zero magnitude.
|
||||||
|
"""
|
||||||
|
if len(a) != len(b):
|
||||||
|
raise ValueError(
|
||||||
|
f"Vector dimension mismatch: {len(a)} vs {len(b)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
dot = sum(x * y for x, y in zip(a, b))
|
||||||
|
norm_a = math.sqrt(sum(x * x for x in a))
|
||||||
|
norm_b = math.sqrt(sum(y * y for y in b))
|
||||||
|
|
||||||
|
if norm_a == 0.0 or norm_b == 0.0:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
return dot / (norm_a * norm_b)
|
||||||
|
|
||||||
|
# ── Introspection ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_initialized(self) -> bool:
|
||||||
|
"""True if category vectors have been computed successfully."""
|
||||||
|
return self._initialized
|
||||||
|
|
||||||
|
@property
|
||||||
|
def init_error(self) -> Optional[str]:
|
||||||
|
"""Error message from initialization, or None."""
|
||||||
|
return self._init_error
|
||||||
|
|
||||||
|
@property
|
||||||
|
def category_count(self) -> int:
|
||||||
|
"""Number of cached category vectors."""
|
||||||
|
return len(self._category_vectors)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cache_size(self) -> int:
|
||||||
|
"""Number of cached message embeddings."""
|
||||||
|
return len(self._message_cache)
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"""
|
||||||
|
Archivar-Konfiguration: Raum-Mapping, Kategorie-Texte und Ollama-Einstellungen.
|
||||||
|
|
||||||
|
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": 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
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Kategorie-Referenztexte (für Embedding-Vergleich) ───────────────────────
|
||||||
|
# Diese Texte werden einmalig beim Start vektorisiert. Neue Nachrichten werden
|
||||||
|
# via Kosinus-Ähnlichkeit gegen diese Vektoren verglichen.
|
||||||
|
|
||||||
|
CATEGORY_TEXTS: Dict[str, str] = {
|
||||||
|
"FAKT": (
|
||||||
|
"Dies ist eine Information oder ein Faktenbeitrag. Es enthält objektive "
|
||||||
|
"Aussagen, Dokumentation oder Wissenswertes ohne Handlungsbedarf. Beispiele "
|
||||||
|
"sind Dokumentationsabschnitte, Systeminformationen oder allgemeine Erklärungen."
|
||||||
|
),
|
||||||
|
"FRAGE": (
|
||||||
|
"Dies ist eine Frage oder ein Hilferuf. Es wird ein Wissensbeitrag oder "
|
||||||
|
"eine Antwort auf ein konkretes Problem erwartet. Beispiele sind "
|
||||||
|
"Problembeschreibungen oder Anfragen nach Lösungen."
|
||||||
|
),
|
||||||
|
"ALARM": (
|
||||||
|
"Dies ist eine dringende Nachricht oder ein Alarm. Es erfordert eine "
|
||||||
|
"sofortige Reaktion oder Handlung. Beispiele sind Systemausfälle, "
|
||||||
|
"kritische Fehler oder Zeitdruck betreffende Anfragen."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Konfidenz-Schwellenwert ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CONFIDENCE_THRESHOLD: float = 0.6
|
||||||
|
"""Nachrichten mit confidence >= 0.6 werden klassifiziert, alles darunter
|
||||||
|
geht an den CATCH_ALL_ROOM."""
|
||||||
|
|
||||||
|
# ── 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"}
|
||||||
|
|
||||||
|
def _resolve_room_mapping() -> dict:
|
||||||
|
"""Baut ROOM_MAPPING aus Umgebungsvariablen zusammen.
|
||||||
|
|
||||||
|
FAKT wird NICHT in ROOM_MAPPING aufgenommen — Fakten sind Dokumentation,
|
||||||
|
keine Kommunikation. Sie werden ausschließlich im DocumentationStore
|
||||||
|
abgelegt, nie in einen Chat-Raum geroutet.
|
||||||
|
"""
|
||||||
|
mapping: dict = {}
|
||||||
|
|
||||||
|
# FAKT wird bewusst NICHT aus Env-Vars gelesen.
|
||||||
|
# ARCHIVAR_FAKT_ROOM existiert nicht mehr — FAKT → doc_store, immer.
|
||||||
|
|
||||||
|
frage_default = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
|
||||||
|
frage_entry: dict = {}
|
||||||
|
if frage_default:
|
||||||
|
frage_entry["default"] = frage_default
|
||||||
|
|
||||||
|
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 ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
FALLBACK_KEYWORDS: dict = {
|
||||||
|
"FRAGE": ["frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
||||||
|
"kannst du", "können sie", "help", "hilfe", "problem",
|
||||||
|
"funktioniert nicht", "kaputt", "erklären", "erkläre",
|
||||||
|
"was bedeutet", "zeig mir", "konflikt"],
|
||||||
|
"ALARM": ["alarm", "hilfe", "dringend", "sofort", "notfall",
|
||||||
|
"ausfall", "absturz", "kritisch", "emergency",
|
||||||
|
"feuer", "panne", "sos", "sicherheitslücke",
|
||||||
|
"stop", "red flag", "abort", "kompromittiert", "datenverlust",
|
||||||
|
"exploit", "gehackt", "ausgefallen", "produktivsystem"],
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
Bei Ollama-Down-Fallback: Enthält die Nachricht eines dieser Keywords,
|
||||||
|
wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ── LLM-Konfiguration ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
LLM_CONFIG = {
|
||||||
|
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||||
|
"model": "qwen2.5:7b",
|
||||||
|
"timeout": 5.0,
|
||||||
|
"base_url": "http://localhost:11434",
|
||||||
|
"temperature": 0.0,
|
||||||
|
"max_tokens": 10,
|
||||||
|
}
|
||||||
|
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere die folgende Nachricht in EINE Kategorie.
|
||||||
|
Antworte NUR mit einem Wort: FAKT, FRAGE oder ALARM.
|
||||||
|
|
||||||
|
Kategorien:
|
||||||
|
- FAKT: Information, Dokumentation, Status-Update ohne Handlungsbedarf
|
||||||
|
- FRAGE: Frage, Problembeschreibung, Bitte um Hilfe oder Erklärung
|
||||||
|
- ALARM: Dringend! Ausfall, Sicherheitsvorfall, Datenverlust, sofortiger Handlungsbedarf
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
|
||||||
|
Kategorie:"""
|
||||||
|
|
||||||
|
LLM_CONFIDENCE_THRESHOLD = 0.70
|
||||||
|
|
||||||
|
# ── Raum-Map-Konfiguration ──────────────────────────────────────────────────
|
||||||
|
# Ablösung der ARCHIVAR_*_ROOM Env-Vars durch room-map.json.
|
||||||
|
# Die alten Env-Vars funktionieren weiter (deprecated, mit WARNING). Neue
|
||||||
|
# Installationen sollten ausschließlich room-map.json verwenden.
|
||||||
|
|
||||||
|
ROOM_MAP_PATH: str = os.path.expanduser(
|
||||||
|
os.getenv("ARCHIVAR_ROOM_MAP_PATH", "~/.hermes/hermes-agent/data/room-map.json")
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── LLM-Room-Prompt (NEU — ersetzt LLM_CLASSIFY_PROMPT) ───────────────────
|
||||||
|
# Fragt das LLM nicht mehr "Welche Kategorie?" sondern "In welchen Raum?"
|
||||||
|
# Die Raum-Liste wird vom RoomRouter dynamisch eingesetzt.
|
||||||
|
|
||||||
|
LLM_ROOM_PROMPT = """Diese Räume sind verfügbar:
|
||||||
|
{room_list}
|
||||||
|
|
||||||
|
In welchen Raum gehört diese Nachricht?
|
||||||
|
Antworte NUR mit dem Raum-Namen (oder "CATCH_ALL" wenn unsicher).
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
Raum:"""
|
||||||
|
|
||||||
|
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
|
||||||
|
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
|
||||||
|
# Bleibt im Code, falls externe Skripte darauf verweisen.
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""
|
||||||
|
Documentation store for Archivar — filesystem persistence for messages
|
||||||
|
that cannot be routed because no room mapping exists or the target room
|
||||||
|
is not in the bot's subscription list.
|
||||||
|
|
||||||
|
Writes classified-but-unrouteable messages to:
|
||||||
|
~/.hermes/hermes-agent/data/archivar_docs/{category}/{timestamp}.md
|
||||||
|
|
||||||
|
Each stored document is a self-contained markdown file with YAML frontmatter
|
||||||
|
containing classification metadata and a human-readable reason why routing
|
||||||
|
was blocked.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
def _get_hermes_agent_dir() -> Path:
|
||||||
|
"""Resolve hermes-agent directory (works regardless of HERMES_HOME)."""
|
||||||
|
hermes_home = os.environ.get("HERMES_HOME", os.path.expanduser("~/.hermes"))
|
||||||
|
return Path(hermes_home) / "hermes-agent"
|
||||||
|
|
||||||
|
|
||||||
|
class DocumentationStore:
|
||||||
|
"""Filesystem store for unrouteable classified messages.
|
||||||
|
|
||||||
|
When the Archivar classifies a message but no valid target room exists
|
||||||
|
(either because ROOM_MAPPING is empty for that category, or the resolved
|
||||||
|
target room is not in the bot's current subscription list), the message
|
||||||
|
is saved here instead of being silently dropped or forwarded to the
|
||||||
|
wrong room.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
store = DocumentationStore()
|
||||||
|
path = store.store(
|
||||||
|
text="Server monitoring shows CPU spike",
|
||||||
|
category="FAKT",
|
||||||
|
confidence=0.92,
|
||||||
|
reason="ARCHIVAR_FAKT_ROOM not configured",
|
||||||
|
origin_room="6a19b0ff02aeecd36b1aa16c",
|
||||||
|
)
|
||||||
|
# → ~/.hermes/hermes-agent/data/archivar_docs/fakt/2026-06-03_21-30-00.md
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, base_dir: Optional[Path] = None) -> None:
|
||||||
|
if base_dir is None:
|
||||||
|
base_dir = _get_hermes_agent_dir() / "data" / "archivar_docs"
|
||||||
|
self._base_dir = Path(base_dir)
|
||||||
|
|
||||||
|
def store(
|
||||||
|
self,
|
||||||
|
text: str,
|
||||||
|
category: str,
|
||||||
|
confidence: float,
|
||||||
|
reason: str = "",
|
||||||
|
origin_room: str = "",
|
||||||
|
) -> str:
|
||||||
|
"""Store an unrouteable message as a markdown document.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The original message text.
|
||||||
|
category: Classification category (FAKT, FRAGE, ALARM).
|
||||||
|
confidence: Classification confidence (0.0–1.0).
|
||||||
|
reason: Human-readable reason why routing was blocked.
|
||||||
|
origin_room: Rocket.Chat room ID where the message originated.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Absolute path to the stored file.
|
||||||
|
"""
|
||||||
|
category_dir = self._base_dir / category.lower()
|
||||||
|
category_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
|
||||||
|
filename = f"{timestamp}.md"
|
||||||
|
filepath = category_dir / filename
|
||||||
|
|
||||||
|
content = self._format_doc(text, category, confidence, reason, origin_room)
|
||||||
|
filepath.write_text(content, encoding="utf-8")
|
||||||
|
|
||||||
|
return str(filepath)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_doc(
|
||||||
|
text: str,
|
||||||
|
category: str,
|
||||||
|
confidence: float,
|
||||||
|
reason: str,
|
||||||
|
origin_room: str,
|
||||||
|
) -> str:
|
||||||
|
"""Format a message as a documentation entry with YAML frontmatter."""
|
||||||
|
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
return (
|
||||||
|
f"---\n"
|
||||||
|
f"category: {category}\n"
|
||||||
|
f"confidence: {confidence:.3f}\n"
|
||||||
|
f"timestamp: {timestamp}\n"
|
||||||
|
f"origin_room: {origin_room}\n"
|
||||||
|
f"reason: {reason}\n"
|
||||||
|
f"---\n\n"
|
||||||
|
f"# {category}: Unrouteable Message\n\n"
|
||||||
|
f"**Reason:** {reason}\n\n"
|
||||||
|
f"{text}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def list_stored(self, category: str = "") -> list[Path]:
|
||||||
|
"""List stored documents, optionally filtered by category.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
category: Filter by category name (e.g. 'fakt', 'frage', 'alarm').
|
||||||
|
Empty string returns all.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Sorted list of Path objects, newest first.
|
||||||
|
"""
|
||||||
|
if category:
|
||||||
|
target = self._base_dir / category.lower()
|
||||||
|
else:
|
||||||
|
target = self._base_dir
|
||||||
|
|
||||||
|
if not target.exists():
|
||||||
|
return []
|
||||||
|
|
||||||
|
return sorted(target.glob("**/*.md"), reverse=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def base_dir(self) -> Path:
|
||||||
|
"""Base directory for stored documents."""
|
||||||
|
return self._base_dir
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://hermes-agent.nousresearch.com/schemas/room-map.schema.json",
|
||||||
|
"title": "Archivar Room Map",
|
||||||
|
"description": "Schema for the Archivar room-map.json — the single source of truth for thematic message routing.",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["version", "rooms"],
|
||||||
|
"properties": {
|
||||||
|
"version": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Schema version for future migrations.",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"rooms": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Map of room_id → RoomEntry.",
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "object",
|
||||||
|
"required": ["name", "theme"],
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Human-readable room name (e.g. '#Rocketchat-Plugin').",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"theme": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Theme / purpose of the room.",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"keywords": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Keywords for keyword-based routing.",
|
||||||
|
"items": { "type": "string", "minLength": 1 },
|
||||||
|
"default": []
|
||||||
|
},
|
||||||
|
"catch_all": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "True if this room is the single catch-all room.",
|
||||||
|
"default": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Room IDs that must never receive routed messages (e.g. Multi-Agent-Raum).",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"default": []
|
||||||
|
},
|
||||||
|
"fact_store_path": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Filesystem path for FAKT message storage (absolute or ~-prefixed).",
|
||||||
|
"default": "~/archivar_docs"
|
||||||
|
},
|
||||||
|
"keyword_overrides": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Admin-corrected keyword→room mappings (learned from !r overrides).",
|
||||||
|
"additionalProperties": { "type": "string" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
"""
|
||||||
|
Room-Map: Single Source of Truth für den thematischen Router.
|
||||||
|
|
||||||
|
Lädt, validiert und durchsucht die Raum-Map aus ``room-map.json``.
|
||||||
|
Ersetzt die bisherigen ``ARCHIVAR_*_ROOM`` Env-Vars durch ein
|
||||||
|
strukturiertes JSON-Datenmodell.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
from .room_map import RoomMap, RoomMapValidationError
|
||||||
|
|
||||||
|
try:
|
||||||
|
room_map = RoomMap.load()
|
||||||
|
room_map.validate(subscribed_ids)
|
||||||
|
except RoomMapValidationError as e:
|
||||||
|
logger.fatal("Room map invalid: %s", e)
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
room = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
|
||||||
|
# → RoomEntry(name="#Rocketchat-Plugin", ...)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ── Constants ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
DEFAULT_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
|
||||||
|
|
||||||
|
# ── Data Classes ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RoomEntry:
|
||||||
|
"""Ein Raum-Eintrag in der Map."""
|
||||||
|
|
||||||
|
room_id: str
|
||||||
|
"""Rocket.Chat Raum-ID."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
"""Menschenlesbarer Name (z. B. ``#Rocketchat-Plugin``)."""
|
||||||
|
|
||||||
|
theme: str
|
||||||
|
"""Thema des Raums (ein Satz)."""
|
||||||
|
|
||||||
|
keywords: list[str] = field(default_factory=list)
|
||||||
|
"""Stichworte für Keyword-Matching."""
|
||||||
|
|
||||||
|
catch_all: bool = False
|
||||||
|
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
|
||||||
|
|
||||||
|
def match_score(self, text: str) -> int:
|
||||||
|
"""Return number of keyword matches in *text* (case-insensitive).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The message text to match against.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Number of matching keywords (0 if none match).
|
||||||
|
"""
|
||||||
|
if not self.keywords:
|
||||||
|
return 0
|
||||||
|
text_lower = text.lower()
|
||||||
|
return sum(1 for kw in self.keywords if kw in text_lower)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Exception ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class RoomMapValidationError(Exception):
|
||||||
|
"""Raised when the room-map.json fails validation at startup."""
|
||||||
|
|
||||||
|
|
||||||
|
# ── RoomMap ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class RoomMap:
|
||||||
|
"""Lädt, validiert und durchsucht die Raum-Map.
|
||||||
|
|
||||||
|
Die Map ist ein JSON-Dokument (Schema siehe ``room-map.schema.json``).
|
||||||
|
Sie wird einmalig beim Gateway-Start geladen und danach im Speicher
|
||||||
|
gehalten. Änderungen an der JSON-Datei zur Laufzeit werden NICHT
|
||||||
|
automatisch erkannt — ein Gateway-Neustart ist nötig.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
rooms: dict[str, RoomEntry],
|
||||||
|
excluded_room_ids: set[str],
|
||||||
|
fact_store_path: Path,
|
||||||
|
version: int = 1,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize from pre-parsed data.
|
||||||
|
|
||||||
|
Use ``RoomMap.load()`` to parse from a JSON file.
|
||||||
|
"""
|
||||||
|
self._rooms = rooms
|
||||||
|
self._excluded_room_ids = excluded_room_ids
|
||||||
|
self._fact_store_path = fact_store_path
|
||||||
|
self._version = version
|
||||||
|
|
||||||
|
# ── Properties ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def rooms(self) -> dict[str, RoomEntry]:
|
||||||
|
"""All room entries, keyed by Rocket.Chat room ID."""
|
||||||
|
return dict(self._rooms)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def catch_all_room(self) -> Optional[RoomEntry]:
|
||||||
|
"""The ONE catch-all room, or None if not exactly one."""
|
||||||
|
catch_alls = [r for r in self._rooms.values() if r.catch_all]
|
||||||
|
return catch_alls[0] if len(catch_alls) == 1 else None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def excluded_room_ids(self) -> set[str]:
|
||||||
|
"""Room IDs that are excluded from all routing."""
|
||||||
|
return set(self._excluded_room_ids)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def fact_store_path(self) -> Path:
|
||||||
|
"""Path for FAKT message storage (filesystem, not a chat room)."""
|
||||||
|
return self._fact_store_path
|
||||||
|
|
||||||
|
@property
|
||||||
|
def version(self) -> int:
|
||||||
|
"""Schema version of the loaded map."""
|
||||||
|
return self._version
|
||||||
|
|
||||||
|
# ── Lookup Methods ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def find_room_by_keywords(self, text: str) -> Optional[RoomEntry]:
|
||||||
|
"""Find the room with the most keyword matches for *text*.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The message text to classify.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The ``RoomEntry`` with the highest match score, or ``None``
|
||||||
|
if no room has any matching keywords.
|
||||||
|
"""
|
||||||
|
best_room: Optional[RoomEntry] = None
|
||||||
|
best_score: int = 0
|
||||||
|
|
||||||
|
for room in self._rooms.values():
|
||||||
|
if room.catch_all:
|
||||||
|
continue # Catch-All never matches keywords
|
||||||
|
score = room.match_score(text)
|
||||||
|
if score > best_score:
|
||||||
|
best_score = score
|
||||||
|
best_room = room
|
||||||
|
|
||||||
|
return best_room
|
||||||
|
|
||||||
|
def is_excluded(self, room_id: str) -> bool:
|
||||||
|
"""True if *room_id* is in the excluded list (e.g. Multi-Agent-Raum)."""
|
||||||
|
return room_id in self._excluded_room_ids
|
||||||
|
|
||||||
|
# ── Validation ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def validate(self, subscribed_ids: Optional[set[str]] = None) -> list[str]:
|
||||||
|
"""Validate the map against subscription reality.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subscribed_ids: The bot's current subscribed room IDs.
|
||||||
|
When provided, checks that the catch-all room and all
|
||||||
|
mapped rooms are in the subscription list.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of error messages (empty = valid).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RoomMapValidationError: For fatal errors (0 or >1 catch-all,
|
||||||
|
catch-all in excluded rooms).
|
||||||
|
"""
|
||||||
|
errors: list[str] = []
|
||||||
|
|
||||||
|
# Count catch-all rooms
|
||||||
|
catch_alls = [r for r in self._rooms.values() if r.catch_all]
|
||||||
|
if len(catch_alls) == 0:
|
||||||
|
raise RoomMapValidationError(
|
||||||
|
"FATAL: No catch_all room defined in room-map.json. "
|
||||||
|
"Exactly one room must have 'catch_all: true'."
|
||||||
|
)
|
||||||
|
if len(catch_alls) > 1:
|
||||||
|
names = ", ".join(r.name for r in catch_alls)
|
||||||
|
raise RoomMapValidationError(
|
||||||
|
f"FATAL: Multiple catch_all rooms: {names}. "
|
||||||
|
"Exactly one room must have 'catch_all: true'."
|
||||||
|
)
|
||||||
|
|
||||||
|
catch_all = catch_alls[0]
|
||||||
|
|
||||||
|
# Catch-all must not be in excluded rooms
|
||||||
|
if catch_all.room_id in self._excluded_room_ids:
|
||||||
|
raise RoomMapValidationError(
|
||||||
|
f"FATAL: Catch-all room '{catch_all.name}' is in excluded_rooms. "
|
||||||
|
"The catch-all room cannot be excluded from routing."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subscription checks (non-fatal warnings)
|
||||||
|
if subscribed_ids is not None:
|
||||||
|
if catch_all.room_id not in subscribed_ids:
|
||||||
|
errors.append(
|
||||||
|
f"Catch-all room '{catch_all.name}' "
|
||||||
|
f"({catch_all.room_id[:8]}...) is not in subscribed rooms"
|
||||||
|
)
|
||||||
|
|
||||||
|
for room in self._rooms.values():
|
||||||
|
if room.room_id not in subscribed_ids:
|
||||||
|
errors.append(
|
||||||
|
f"Room '{room.name}' ({room.room_id[:8]}...) "
|
||||||
|
"is not in subscribed rooms"
|
||||||
|
)
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
|
# ── Factory ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load(cls, path: Optional[Path] = None) -> RoomMap:
|
||||||
|
"""Load and validate a room-map.json file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Path to the JSON file. Defaults to
|
||||||
|
``ARCHIVAR_ROOM_MAP_PATH`` env var or
|
||||||
|
``~/.hermes/hermes-agent/data/room-map.json``.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A validated ``RoomMap`` instance.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFoundError: If the map file does not exist.
|
||||||
|
json.JSONDecodeError: If the file is not valid JSON.
|
||||||
|
RoomMapValidationError: If the map fails semantic validation.
|
||||||
|
"""
|
||||||
|
if path is None:
|
||||||
|
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
|
||||||
|
if env_path:
|
||||||
|
path = Path(env_path)
|
||||||
|
else:
|
||||||
|
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
|
||||||
|
|
||||||
|
if not path.exists():
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"Room map not found at {path}. "
|
||||||
|
"Create one with room-map.schema.json as template."
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
return cls._from_dict(data)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _from_dict(cls, data: dict) -> RoomMap:
|
||||||
|
"""Parse a deserialized map dict into a ``RoomMap`` instance."""
|
||||||
|
version = data.get("version", 1)
|
||||||
|
|
||||||
|
# Parse rooms
|
||||||
|
rooms: dict[str, RoomEntry] = {}
|
||||||
|
for room_id, room_data in data.get("rooms", {}).items():
|
||||||
|
rooms[room_id] = RoomEntry(
|
||||||
|
room_id=room_id,
|
||||||
|
name=room_data.get("name", room_id),
|
||||||
|
theme=room_data.get("theme", ""),
|
||||||
|
keywords=room_data.get("keywords", []),
|
||||||
|
catch_all=room_data.get("catch_all", False),
|
||||||
|
)
|
||||||
|
|
||||||
|
excluded = set(data.get("excluded_rooms", []))
|
||||||
|
fact_store = Path(
|
||||||
|
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
|
||||||
|
)
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
rooms=rooms,
|
||||||
|
excluded_room_ids=excluded,
|
||||||
|
fact_store_path=fact_store,
|
||||||
|
version=version,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Migration from Legacy Env Vars ────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _migrate_from_env_vars() -> Optional[dict]:
|
||||||
|
"""Build a temporary map dict from deprecated ARCHIVAR_*_ROOM env vars.
|
||||||
|
|
||||||
|
Logs a WARNING that the env var approach is deprecated and the user
|
||||||
|
should migrate to room-map.json.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A dict suitable for ``RoomMap._from_dict()``, or ``None`` if
|
||||||
|
no legacy env vars are set.
|
||||||
|
"""
|
||||||
|
fakt = os.getenv("ARCHIVAR_FAKT_ROOM", "").strip()
|
||||||
|
frage = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
|
||||||
|
alarm = os.getenv("ARCHIVAR_ALARM_ROOM", "").strip()
|
||||||
|
catchall = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip()
|
||||||
|
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
|
||||||
|
|
||||||
|
has_any = any([fakt, frage, alarm, catchall, project_json])
|
||||||
|
if not has_any:
|
||||||
|
return None
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"Using deprecated ARCHIVAR_*_ROOM env vars. "
|
||||||
|
"Please migrate to room-map.json. "
|
||||||
|
"See docs/archivar-architektur.md for migration guide."
|
||||||
|
)
|
||||||
|
|
||||||
|
rooms: dict[str, dict] = {}
|
||||||
|
|
||||||
|
# Catch-all room
|
||||||
|
if catchall:
|
||||||
|
rooms[catchall] = {
|
||||||
|
"name": "Catch-All (legacy)",
|
||||||
|
"theme": "Legacy catch-all from ARCHIVAR_CATCHALL_ROOM",
|
||||||
|
"keywords": [],
|
||||||
|
"catch_all": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
# ALARM room
|
||||||
|
if alarm and alarm != catchall:
|
||||||
|
rooms[alarm] = {
|
||||||
|
"name": "ALARM Room (legacy)",
|
||||||
|
"theme": "Legacy alarm room from ARCHIVAR_ALARM_ROOM",
|
||||||
|
"keywords": ["alarm", "dringend", "sofort", "kritisch", "ausfall"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
# FAKT room (legacy — now goes to doc_store, but keep for migration)
|
||||||
|
if fakt and fakt != catchall and fakt != alarm:
|
||||||
|
rooms[fakt] = {
|
||||||
|
"name": "FAKT Room (legacy)",
|
||||||
|
"theme": "Legacy fakt room from ARCHIVAR_FAKT_ROOM",
|
||||||
|
"keywords": ["dokumentation", "fakt", "info"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
# FRAGE room(s)
|
||||||
|
if frage and frage != catchall:
|
||||||
|
rooms[frage] = {
|
||||||
|
"name": "FRAGE Room (legacy)",
|
||||||
|
"theme": "Legacy frage room from ARCHIVAR_FRAGE_ROOM",
|
||||||
|
"keywords": ["frage", "hilfe", "problem"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Project-specific rooms
|
||||||
|
if project_json:
|
||||||
|
try:
|
||||||
|
projects = json.loads(project_json)
|
||||||
|
for proj_key, proj_room_id in projects.items():
|
||||||
|
if proj_room_id not in rooms:
|
||||||
|
rooms[proj_room_id] = {
|
||||||
|
"name": f"Project: {proj_key} (legacy)",
|
||||||
|
"theme": f"Legacy project room for {proj_key}",
|
||||||
|
"keywords": [proj_key],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.warning("Failed to parse ARCHIVAR_PROJECT_ROOMS JSON")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": rooms,
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": os.path.expanduser("~/archivar_docs"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
"""
|
||||||
|
Routing-Logik für klassifizierte Nachrichten.
|
||||||
|
|
||||||
|
Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle
|
||||||
|
und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie
|
||||||
|
und Meta-Fragen-Erkennung.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
from .classifier import ClassificationResult, MessageClassifier
|
||||||
|
from .config import (
|
||||||
|
CONFIDENCE_THRESHOLD,
|
||||||
|
FALLBACK_KEYWORDS,
|
||||||
|
OLLAMA_CONFIG,
|
||||||
|
LLM_ROOM_PROMPT,
|
||||||
|
ROOM_MAP_PATH,
|
||||||
|
)
|
||||||
|
from .room_map import RoomMap, RoomEntry
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Meta-Fragen-Erkennung ───────────────────────────────────────────────────
|
||||||
|
# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als
|
||||||
|
# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind.
|
||||||
|
# Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem
|
||||||
|
# Hinweis in der Kopie versehen.
|
||||||
|
|
||||||
|
_META_PATTERNS: List[re.Pattern] = [
|
||||||
|
re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:who|which room|where).*(?:message|routed|sent)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
]
|
||||||
|
|
||||||
|
# ── Projekt-Keywords für FRAGE-Routing ──────────────────────────────────────
|
||||||
|
# DEPRECATED: Keywords leben jetzt in RoomEntry.keywords der room-map.json.
|
||||||
|
# Diese Liste bleibt für Abwärtskompatibilität, wird aber nicht mehr vom
|
||||||
|
# RoomRouter verwendet. Neue Installationen nutzen ausschließlich RoomMap.
|
||||||
|
|
||||||
|
_PROJECT_KEYWORDS: Dict[str, List[str]] = {
|
||||||
|
"plugin": [
|
||||||
|
"plugin", "adapter", "rocketchat", "gateway", "webhook",
|
||||||
|
"archivar", "module", "schnittstelle",
|
||||||
|
],
|
||||||
|
"lan": [
|
||||||
|
"lan", "netzwerk", "router", "switch", "vlan", "dns",
|
||||||
|
"dhcp", "ip-adresse", "subnetz", "firewall", "wlan",
|
||||||
|
"ethernet", "kabel", "patchpanel", "zugangspunkt",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RoutingDecision:
|
||||||
|
"""Entscheidung, wohin eine Nachricht weitergeleitet wird."""
|
||||||
|
|
||||||
|
category: str
|
||||||
|
"""Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'."""
|
||||||
|
|
||||||
|
target_room: str
|
||||||
|
"""Rocket.Chat Raum-ID des Zielraums."""
|
||||||
|
|
||||||
|
confidence: float
|
||||||
|
"""Konfidenz der Klassifikation (0.0–1.0)."""
|
||||||
|
|
||||||
|
is_catch_all: bool = False
|
||||||
|
"""True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging."""
|
||||||
|
|
||||||
|
is_fallback: bool = False
|
||||||
|
"""True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||||
|
|
||||||
|
is_meta: bool = False
|
||||||
|
"""True, wenn die Nachricht als Meta-Frage erkannt wurde."""
|
||||||
|
|
||||||
|
is_unrouteable: bool = False
|
||||||
|
"""True, wenn der Zielraum nicht in den subscribed rooms des Bots ist
|
||||||
|
und die Nachricht stattdessen im DocumentationStore abgelegt wird."""
|
||||||
|
|
||||||
|
unrouteable_reason: str = ""
|
||||||
|
"""Grund, warum kein Routing möglich war (nur bei is_unrouteable=True)."""
|
||||||
|
|
||||||
|
prefix: str = ""
|
||||||
|
"""Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK])."""
|
||||||
|
|
||||||
|
delete_original: bool = False
|
||||||
|
"""True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll."""
|
||||||
|
|
||||||
|
project: Optional[str] = None
|
||||||
|
"""Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None."""
|
||||||
|
|
||||||
|
matched_room_name: Optional[str] = None
|
||||||
|
"""Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde."""
|
||||||
|
|
||||||
|
all_scores: Dict[str, float] = field(default_factory=dict)
|
||||||
|
"""Alle Kategorie-Scores für Debugging/Logging."""
|
||||||
|
|
||||||
|
|
||||||
|
class MessageRouter:
|
||||||
|
"""Thematischer Router: Nachricht → Zielraum.
|
||||||
|
|
||||||
|
Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung.
|
||||||
|
Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch
|
||||||
|
``RoomMap`` abgelöst.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
room_map = RoomMap.load()
|
||||||
|
classifier = MessageClassifier()
|
||||||
|
await classifier.initialize()
|
||||||
|
|
||||||
|
router = MessageRouter(room_map, classifier)
|
||||||
|
router.set_subscribed_room_ids(["6a19...", "6a1f..."])
|
||||||
|
decision = await router.route("Wie konfiguriere ich das Plugin?", "6a1f...")
|
||||||
|
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin)
|
||||||
|
# decision.matched_room_name → "#Rocketchat-Plugin"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
room_map: RoomMap,
|
||||||
|
classifier: MessageClassifier,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
room_map: A loaded and validated ``RoomMap`` instance.
|
||||||
|
classifier: An (initialized) ``MessageClassifier``.
|
||||||
|
"""
|
||||||
|
self._room_map = room_map
|
||||||
|
self._classifier = classifier
|
||||||
|
self._confidence_threshold = CONFIDENCE_THRESHOLD
|
||||||
|
self._subscribed_room_ids: Optional[set] = None
|
||||||
|
|
||||||
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
|
||||||
|
"""Klassifiziere und route eine Nachricht.
|
||||||
|
|
||||||
|
Der vollständige Routing-Flow:
|
||||||
|
1. origin_room_id in excluded_rooms? → IGNORE (silent)
|
||||||
|
2. Keyword-Match in RoomEntry.keywords → Zielraum
|
||||||
|
3. Keyword-Override-Match → Override-Raum (höchste Prio)
|
||||||
|
4. Embedding-Klassifikation via Classifier
|
||||||
|
5. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?")
|
||||||
|
6. Kein Treffer → catch_all_room
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoutingDecision mit Zielraum, Kategorie und Metadaten.
|
||||||
|
"""
|
||||||
|
if not text or not text.strip():
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
text = text.strip()
|
||||||
|
|
||||||
|
# ── Schritt 0: Excluded rooms check ──────────────────────────
|
||||||
|
if origin_room_id and self._room_map.is_excluded(origin_room_id):
|
||||||
|
logger.debug(
|
||||||
|
"Message from excluded room %s — ignoring", origin_room_id[:8]
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 1: Meta-Fragen-Erkennung ──────────────────────────
|
||||||
|
if self._is_meta_question(text):
|
||||||
|
logger.info("Meta-question detected: %.80s...", text)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FRAGE",
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=1.0,
|
||||||
|
is_meta=True,
|
||||||
|
delete_original=True,
|
||||||
|
prefix="[META-FRAGE] ",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 1.5: Keyword-Match (aus RoomMap) ──────────────────
|
||||||
|
matched_room = self._room_map.find_room_by_keywords(text)
|
||||||
|
if matched_room is not None:
|
||||||
|
logger.debug(
|
||||||
|
"Keyword match: '%s' → %s", text[:80], matched_room.name
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FRAGE",
|
||||||
|
target_room=matched_room.room_id,
|
||||||
|
confidence=0.95,
|
||||||
|
matched_room_name=matched_room.name,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 2: Embedding-basierte Klassifikation ───────────────
|
||||||
|
result: Optional[ClassificationResult] = None
|
||||||
|
|
||||||
|
if self._classifier.is_initialized:
|
||||||
|
result = await self._classifier.classify(text)
|
||||||
|
|
||||||
|
# ── Schritt 3: Fallback bei Classifier-Versagen ────────────────
|
||||||
|
if result is None:
|
||||||
|
logger.info(
|
||||||
|
"Classifier unavailable — using keyword fallback for: %.80s...",
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
category, is_fallback = self._keyword_classify(text)
|
||||||
|
return RoutingDecision(
|
||||||
|
category=category,
|
||||||
|
target_room=self._resolve_room(category),
|
||||||
|
confidence=0.0,
|
||||||
|
is_fallback=is_fallback,
|
||||||
|
prefix="[FALLBACK] " if is_fallback else "",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 4: Konfidenz-Prüfung ───────────────────────────────
|
||||||
|
if not result.is_confident(self._confidence_threshold):
|
||||||
|
logger.debug(
|
||||||
|
"Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all",
|
||||||
|
result.confidence, self._confidence_threshold, result.category,
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category=result.category,
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=result.confidence,
|
||||||
|
is_catch_all=True,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 5: FAKT = Dokumentation, niemals Kommunikation ────
|
||||||
|
if result.category == "FAKT":
|
||||||
|
decision = RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room="", # No room — goes to doc_store
|
||||||
|
confidence=result.confidence,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
)
|
||||||
|
decision.is_unrouteable = True
|
||||||
|
decision.unrouteable_reason = (
|
||||||
|
"FAKT messages are documentation, not communication — "
|
||||||
|
"stored in doc_store, never forwarded to chat rooms"
|
||||||
|
)
|
||||||
|
logger.info("FAKT → doc_store: %.80s...", text)
|
||||||
|
return decision
|
||||||
|
|
||||||
|
# ── Schritt 6: LLM-Room-Lookup (für FRAGE) ────────────────────
|
||||||
|
if result.category == "FRAGE":
|
||||||
|
llm_room = self._llm_room_lookup(text)
|
||||||
|
if llm_room is not None:
|
||||||
|
target_room = llm_room.room_id
|
||||||
|
matched_name = llm_room.name
|
||||||
|
else:
|
||||||
|
target_room = self._resolve_room("FRAGE")
|
||||||
|
matched_name = None
|
||||||
|
|
||||||
|
decision = RoutingDecision(
|
||||||
|
category="FRAGE",
|
||||||
|
target_room=target_room,
|
||||||
|
confidence=result.confidence,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
matched_room_name=matched_name,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# ALARM → catch_all_room (Admin-DM)
|
||||||
|
decision = RoutingDecision(
|
||||||
|
category=result.category,
|
||||||
|
target_room=self._resolve_room(result.category),
|
||||||
|
confidence=result.confidence,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Subscription-Validierung ──────────────────────────────────
|
||||||
|
self._check_unrouteable(decision)
|
||||||
|
return decision
|
||||||
|
|
||||||
|
def _check_unrouteable(self, decision: RoutingDecision) -> None:
|
||||||
|
"""Validate target_room against subscribed IDs.
|
||||||
|
|
||||||
|
If the target room is not in the bot's subscription list, mark the
|
||||||
|
decision as unrouteable so the caller can store the message in the
|
||||||
|
DocumentationStore instead of forwarding it.
|
||||||
|
"""
|
||||||
|
reason = self._validate_target_room(decision.category, decision.target_room)
|
||||||
|
if reason:
|
||||||
|
decision.is_unrouteable = True
|
||||||
|
decision.unrouteable_reason = reason
|
||||||
|
logger.warning(
|
||||||
|
"Unrouteable [%s]: %s", decision.category, reason
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Room Resolution ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _resolve_room(self, category: str) -> str:
|
||||||
|
"""Resolve the target room ID for a category.
|
||||||
|
|
||||||
|
Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars.
|
||||||
|
ALARM routes to catch_all_room. FRAGE uses the catch_all as fallback.
|
||||||
|
"""
|
||||||
|
catch_all = self._room_map.catch_all_room
|
||||||
|
if catch_all is None:
|
||||||
|
logger.error("No catch_all room configured — cannot route category '%s'", category)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
if category == "ALARM":
|
||||||
|
return catch_all.room_id
|
||||||
|
|
||||||
|
# For FRAGE: use catch_all as default (LLM will refine in route())
|
||||||
|
return catch_all.room_id
|
||||||
|
|
||||||
|
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
|
||||||
|
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
||||||
|
|
||||||
|
Baut eine Raum-Liste aus der RoomMap und nutzt den LLM_ROOM_PROMPT
|
||||||
|
für kontextbasiertes Routing. Der Classifier muss LLM-fähig sein
|
||||||
|
(``ARCHIVAR_ENABLE_LLM=1``).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match.
|
||||||
|
"""
|
||||||
|
# Build room list for LLM prompt
|
||||||
|
room_list_parts = []
|
||||||
|
for room in self._room_map.rooms.values():
|
||||||
|
if room.catch_all:
|
||||||
|
continue
|
||||||
|
room_list_parts.append(
|
||||||
|
f"- {room.name}: {room.theme} (Keywords: {', '.join(room.keywords[:5])})"
|
||||||
|
)
|
||||||
|
room_list_parts.append(
|
||||||
|
f"- CATCH_ALL: {self._room_map.catch_all_room.name if self._room_map.catch_all_room else 'Admin DM'}"
|
||||||
|
)
|
||||||
|
room_list = "\n".join(room_list_parts)
|
||||||
|
|
||||||
|
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
|
||||||
|
|
||||||
|
# Try LLM classification (raw mode — expects room name, not category)
|
||||||
|
llm_result = self._classifier._llm_raw_sync(prompt)
|
||||||
|
if llm_result is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Parse LLM response — could be a room name or "CATCH_ALL"
|
||||||
|
response = llm_result.strip()
|
||||||
|
|
||||||
|
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Try to match response to a room name
|
||||||
|
response_lower = response.lower()
|
||||||
|
for room in self._room_map.rooms.values():
|
||||||
|
if response_lower == room.name.lower():
|
||||||
|
return room
|
||||||
|
if response_lower in room.name.lower():
|
||||||
|
return room
|
||||||
|
|
||||||
|
logger.debug("LLM returned unknown room: %s", response)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── Route Validation ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
# ── Meta-Question Detection ────────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _is_meta_question(text: str) -> bool:
|
||||||
|
"""Check if a message is a meta-question about the Archivar system.
|
||||||
|
|
||||||
|
Meta-questions ask about the classification/routing system itself.
|
||||||
|
They should NOT be forwarded as regular questions.
|
||||||
|
"""
|
||||||
|
for pattern in _META_PATTERNS:
|
||||||
|
if pattern.search(text):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ── Fallback: Keyword-Heuristik ────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _keyword_classify(text: str) -> Tuple[str, bool]:
|
||||||
|
"""Classify using keyword heuristics when Ollama is unavailable.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(category, is_fallback) — is_fallback is always True here.
|
||||||
|
"""
|
||||||
|
text_lower = text.lower()
|
||||||
|
|
||||||
|
# Check ALARM keywords first (highest priority)
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||||||
|
if kw in text_lower:
|
||||||
|
return "ALARM", True
|
||||||
|
|
||||||
|
# Check FRAGE keywords
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||||||
|
if kw in text_lower:
|
||||||
|
return "FRAGE", True
|
||||||
|
|
||||||
|
# Default: FAKT
|
||||||
|
return "FAKT", True
|
||||||
|
|
||||||
|
# ── Configuration ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def confidence_threshold(self) -> float:
|
||||||
|
"""Current confidence threshold."""
|
||||||
|
return self._confidence_threshold
|
||||||
|
|
||||||
|
def set_confidence_threshold(self, value: float) -> None:
|
||||||
|
"""Override the confidence threshold at runtime.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
value: New threshold (0.0–1.0).
|
||||||
|
"""
|
||||||
|
if not 0.0 <= value <= 1.0:
|
||||||
|
raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}")
|
||||||
|
self._confidence_threshold = value
|
||||||
|
logger.info("Confidence threshold set to %.2f", value)
|
||||||
|
|
||||||
|
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||||
|
"""Set the bot's current subscribed room IDs for validation.
|
||||||
|
|
||||||
|
When set, the router will ONLY route to rooms that are in this list.
|
||||||
|
Messages targeting unsubscribed rooms are marked as ``is_unrouteable``
|
||||||
|
and should be stored in the DocumentationStore instead.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_ids: List of Rocket.Chat room IDs the bot is subscribed to.
|
||||||
|
Pass None or empty list to disable validation.
|
||||||
|
"""
|
||||||
|
if room_ids:
|
||||||
|
self._subscribed_room_ids = set(room_ids)
|
||||||
|
logger.debug(
|
||||||
|
"Router subscribed IDs set: %d rooms", len(self._subscribed_room_ids)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._subscribed_room_ids = None
|
||||||
|
|
||||||
|
def _validate_target_room(self, category: str, room_id: str) -> str:
|
||||||
|
"""Validate target room against subscribed IDs.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Empty string if valid. Human-readable reason if blocked.
|
||||||
|
"""
|
||||||
|
if not room_id:
|
||||||
|
return f"no room configured for category '{category}'"
|
||||||
|
|
||||||
|
if self._subscribed_room_ids is None:
|
||||||
|
return "" # validation disabled
|
||||||
|
|
||||||
|
if room_id not in self._subscribed_room_ids:
|
||||||
|
return (
|
||||||
|
f"target room {room_id[:8]}... for category '{category}' "
|
||||||
|
f"is not in bot's subscription list "
|
||||||
|
f"({len(self._subscribed_room_ids)} subscribed rooms)"
|
||||||
|
)
|
||||||
|
|
||||||
|
return ""
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
"""
|
||||||
|
Tests für das RoomMap-Datenmodell.
|
||||||
|
|
||||||
|
Prüft:
|
||||||
|
- Laden und Validieren von room-map.json
|
||||||
|
- Keyword-Matching
|
||||||
|
- Validierungsfehler (0/2 Catch-All, excluded_rooms)
|
||||||
|
- Legacy-Env-Var-Migration
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure the archivar package is importable
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.room_map import (
|
||||||
|
RoomMap,
|
||||||
|
RoomEntry,
|
||||||
|
RoomMapValidationError,
|
||||||
|
_migrate_from_env_vars,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _make_map_json(rooms: list[dict] | None = None, excluded: list[str] | None = None) -> str:
|
||||||
|
"""Create a minimal valid room-map.json as a string."""
|
||||||
|
data: dict = {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {},
|
||||||
|
"excluded_rooms": excluded or [],
|
||||||
|
"fact_store_path": "/tmp/test_docs",
|
||||||
|
}
|
||||||
|
for room in (rooms or []):
|
||||||
|
data["rooms"][room["room_id"]] = {
|
||||||
|
"name": room["name"],
|
||||||
|
"theme": room.get("theme", ""),
|
||||||
|
"keywords": room.get("keywords", []),
|
||||||
|
"catch_all": room.get("catch_all", False),
|
||||||
|
}
|
||||||
|
return json.dumps(data)
|
||||||
|
|
||||||
|
|
||||||
|
def _tmp_map(content: str) -> Path:
|
||||||
|
"""Write content to a temp file and return its Path."""
|
||||||
|
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
||||||
|
tmp.write(content)
|
||||||
|
tmp.close()
|
||||||
|
return Path(tmp.name)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Basic Loading ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapLoad:
|
||||||
|
"""RoomMap.load() — basic loading."""
|
||||||
|
|
||||||
|
def test_load_valid_map(self):
|
||||||
|
"""Load a map with 3 rooms, 1 catch-all, 1 excluded."""
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Dev", "theme": "dev room", "keywords": ["code", "bug"]},
|
||||||
|
{"room_id": "r2", "name": "#Ops", "theme": "ops room", "keywords": ["server", "docker"]},
|
||||||
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
excluded=["rx99"],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
assert rm.version == 1
|
||||||
|
assert len(rm.rooms) == 3
|
||||||
|
assert rm.catch_all_room is not None
|
||||||
|
assert rm.catch_all_room.room_id == "r3"
|
||||||
|
assert "rx99" in rm.excluded_room_ids
|
||||||
|
assert str(rm.fact_store_path) == "/tmp/test_docs"
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_load_empty_rooms(self):
|
||||||
|
"""Map with no rooms — should load but fail validation."""
|
||||||
|
json_str = _make_map_json(rooms=[])
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
assert len(rm.rooms) == 0
|
||||||
|
# Validation should raise
|
||||||
|
with pytest.raises(RoomMapValidationError, match="No catch_all"):
|
||||||
|
rm.validate()
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_load_file_not_found(self):
|
||||||
|
"""Missing file should raise FileNotFoundError."""
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
RoomMap.load(Path("/tmp/nonexistent_room_map_2026.json"))
|
||||||
|
|
||||||
|
|
||||||
|
# ── Keyword Matching ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapKeywords:
|
||||||
|
"""RoomMap.find_room_by_keywords() tests."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def room_map(self) -> RoomMap:
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Plugin", "theme": "plugin dev", "keywords": ["plugin", "adapter", "gateway"]},
|
||||||
|
{"room_id": "r2", "name": "#BAT", "theme": "trading", "keywords": ["bat", "trading", "docker"]},
|
||||||
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
return RoomMap.load(path)
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_keyword_match_plugin(self, room_map):
|
||||||
|
"""Plugin keywords should match #Plugin room."""
|
||||||
|
result = room_map.find_room_by_keywords("Das Plugin hat einen Gateway-Bug")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin"
|
||||||
|
|
||||||
|
def test_keyword_match_bat(self, room_map):
|
||||||
|
"""BAT keywords should match #BAT room."""
|
||||||
|
result = room_map.find_room_by_keywords("Das Docker-Image für Trading ist kaputt")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#BAT"
|
||||||
|
|
||||||
|
def test_keyword_multiple_matches(self, room_map):
|
||||||
|
"""Most matching keywords wins."""
|
||||||
|
# "gateway" matches both Plugin and BAT, but "plugin" gives Plugin an edge
|
||||||
|
result = room_map.find_room_by_keywords("gateway plugin trading")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin" # plugin + gateway = 2 vs trading = 1
|
||||||
|
|
||||||
|
def test_no_keyword_match(self, room_map):
|
||||||
|
"""No keywords should return None."""
|
||||||
|
result = room_map.find_room_by_keywords("Hallo wie gehts")
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_catch_all_never_matches_keywords(self, room_map):
|
||||||
|
"""Catch-all room has no keywords, never returned."""
|
||||||
|
result = room_map.find_room_by_keywords("irgendwas")
|
||||||
|
assert result is None # Not the catch-all
|
||||||
|
|
||||||
|
def test_keyword_case_insensitive(self, room_map):
|
||||||
|
"""Keywords are case-insensitive."""
|
||||||
|
result = room_map.find_room_by_keywords("PLUGIN ADAPTER")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin"
|
||||||
|
|
||||||
|
|
||||||
|
# ── Exclusion ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapExclusion:
|
||||||
|
"""Room exclusion tests."""
|
||||||
|
|
||||||
|
def test_excluded_room(self):
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Bot-Room", "theme": "multi-agent", "keywords": []},
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
excluded=["r1"],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
assert rm.is_excluded("r1") is True
|
||||||
|
assert rm.is_excluded("admin") is False
|
||||||
|
assert rm.is_excluded("nonexistent") is False
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Validation ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapValidation:
|
||||||
|
"""RoomMap.validate() tests."""
|
||||||
|
|
||||||
|
def _load(self, rooms: list[dict], excluded: list[str] | None = None) -> RoomMap:
|
||||||
|
json_str = _make_map_json(rooms=rooms, excluded=excluded)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
return RoomMap.load(path)
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_no_catch_all(self):
|
||||||
|
"""0 catch-all rooms → RoomMapValidationError."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#A", "theme": "A"},
|
||||||
|
{"room_id": "r2", "name": "#B", "theme": "B"},
|
||||||
|
])
|
||||||
|
with pytest.raises(RoomMapValidationError, match="No catch_all"):
|
||||||
|
rm.validate()
|
||||||
|
|
||||||
|
def test_two_catch_all(self):
|
||||||
|
"""2 catch-all rooms → RoomMapValidationError."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#A", "theme": "A", "keywords": [], "catch_all": True},
|
||||||
|
{"room_id": "r2", "name": "#B", "theme": "B", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
with pytest.raises(RoomMapValidationError, match="Multiple catch_all"):
|
||||||
|
rm.validate()
|
||||||
|
|
||||||
|
def test_catch_all_in_excluded(self):
|
||||||
|
"""Catch-all in excluded_rooms → RoomMapValidationError."""
|
||||||
|
rm = self._load(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Excluded", "theme": "bad", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
excluded=["r1"],
|
||||||
|
)
|
||||||
|
with pytest.raises(RoomMapValidationError, match="excluded_rooms"):
|
||||||
|
rm.validate()
|
||||||
|
|
||||||
|
def test_valid_map_with_subscriptions(self):
|
||||||
|
"""Valid map with subscribed room IDs — no errors."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
errors = rm.validate(subscribed_ids={"r1", "admin"})
|
||||||
|
assert errors == []
|
||||||
|
|
||||||
|
def test_room_not_subscribed_warning(self):
|
||||||
|
"""Room not in subscribed_ids → non-fatal warning."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
errors = rm.validate(subscribed_ids={"admin"}) # r1 not subscribed
|
||||||
|
assert len(errors) >= 1
|
||||||
|
assert any("not in subscribed" in e for e in errors)
|
||||||
|
|
||||||
|
def test_catch_all_not_subscribed_warning(self):
|
||||||
|
"""Catch-all not in subscribed_ids → warning (not fatal)."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
errors = rm.validate(subscribed_ids={"r999"})
|
||||||
|
assert len(errors) >= 1
|
||||||
|
assert any("catch_all room" in e.lower() for e in errors)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Migration from Legacy Env Vars ─────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestMigrationFromEnvVars:
|
||||||
|
"""_migrate_from_env_vars() tests."""
|
||||||
|
|
||||||
|
def teardown_method(self):
|
||||||
|
"""Clean up env vars after each test."""
|
||||||
|
for key in list(os.environ):
|
||||||
|
if key.startswith("ARCHIVAR_"):
|
||||||
|
del os.environ[key]
|
||||||
|
|
||||||
|
def test_no_env_vars(self):
|
||||||
|
"""No legacy env vars → None."""
|
||||||
|
assert _migrate_from_env_vars() is None
|
||||||
|
|
||||||
|
def test_with_catchall_only(self):
|
||||||
|
"""ARCHIVAR_CATCHALL_ROOM set → catch-all in migrated map."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall"
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
assert "room_catchall" in result["rooms"]
|
||||||
|
assert result["rooms"]["room_catchall"]["catch_all"] is True
|
||||||
|
|
||||||
|
def test_with_multiple_rooms(self):
|
||||||
|
"""Multiple legacy vars → all rooms in migrated map."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall"
|
||||||
|
os.environ["ARCHIVAR_ALARM_ROOM"] = "room_alarm"
|
||||||
|
os.environ["ARCHIVAR_FRAGE_ROOM"] = "room_frage"
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
assert len(result["rooms"]) >= 3
|
||||||
|
|
||||||
|
def test_alarm_same_as_catchall_not_duplicated(self):
|
||||||
|
"""If ALARM_ROOM == CATCHALL_ROOM, don't create duplicate."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "same_room"
|
||||||
|
os.environ["ARCHIVAR_ALARM_ROOM"] = "same_room"
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
# Should only have one entry for "same_room" with catch_all=True
|
||||||
|
assert "same_room" in result["rooms"]
|
||||||
|
assert result["rooms"]["same_room"]["catch_all"] is True
|
||||||
|
|
||||||
|
def test_project_rooms(self):
|
||||||
|
"""ARCHIVAR_PROJECT_ROOMS JSON → project rooms in migrated map."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_admin"
|
||||||
|
os.environ["ARCHIVAR_PROJECT_ROOMS"] = '{"plugin": "r_plugin", "bat": "r_bat"}'
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
assert "r_plugin" in result["rooms"]
|
||||||
|
assert "r_bat" in result["rooms"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── RoomEntry ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomEntry:
|
||||||
|
"""RoomEntry dataclass tests."""
|
||||||
|
|
||||||
|
def test_match_score(self):
|
||||||
|
entry = RoomEntry(
|
||||||
|
room_id="r1", name="#Dev", theme="dev",
|
||||||
|
keywords=["plugin", "gateway", "adapter"],
|
||||||
|
)
|
||||||
|
assert entry.match_score("Das Plugin braucht einen Gateway-Fix") == 2
|
||||||
|
assert entry.match_score("Der Adapter ist kaputt") == 1
|
||||||
|
assert entry.match_score("Hallo Welt") == 0
|
||||||
|
|
||||||
|
def test_match_score_no_keywords(self):
|
||||||
|
entry = RoomEntry(
|
||||||
|
room_id="admin", name="DM Admin", theme="admin",
|
||||||
|
keywords=[], catch_all=True,
|
||||||
|
)
|
||||||
|
assert entry.match_score("irgendwas") == 0
|
||||||
|
|
||||||
|
def test_match_score_case_insensitive(self):
|
||||||
|
entry = RoomEntry(
|
||||||
|
room_id="r1", name="#Dev", theme="dev",
|
||||||
|
keywords=["Plugin", "GATEWAY"],
|
||||||
|
)
|
||||||
|
assert entry.match_score("plugin gateway") == 2
|
||||||
+7
-17
@@ -1,22 +1,12 @@
|
|||||||
name: rocketchat-platform
|
name: rocketchat-platform
|
||||||
|
label: Rocket.Chat
|
||||||
kind: platform
|
kind: platform
|
||||||
version: 1.0.0
|
version: 1.0.0
|
||||||
description: >
|
description: >
|
||||||
Rocket.Chat gateway adapter for Hermes Agent.
|
Rocket.Chat gateway adapter for Hermes Agent.
|
||||||
Connects to a self-hosted Rocket.Chat server via WebSocket/DDP for
|
Connects via DDP (WebSocket) to a self-hosted Rocket.Chat server,
|
||||||
real-time message streaming and presence, and REST API for sending replies.
|
monitors subscribed rooms, and routes messages through the Hermes
|
||||||
Supports channels, private groups, and direct messages.
|
agent. Includes the Archivar classification subsystem for automatic
|
||||||
author: Hermes Community
|
message routing (FAKT → doc_store, FRAGE → project room, ALARM → DM)
|
||||||
requires_env:
|
plus Button-interaction support and file upload/download.
|
||||||
- ROCKETCHAT_BASE_URL
|
author: Entwicklerteam
|
||||||
- ROCKETCHAT_USER
|
|
||||||
- ROCKETCHAT_PASSWORD
|
|
||||||
- name: ROCKETCHAT_ROOM_ID
|
|
||||||
description: "Default room/channel ID to subscribe (optional if auto-discovery enabled)"
|
|
||||||
required: false
|
|
||||||
- name: ROCKETCHAT_ALLOW_ALL_USERS
|
|
||||||
description: "Set to 'true' to allow all users (default: false = allowlist)"
|
|
||||||
required: false
|
|
||||||
- name: ROCKETCHAT_ALLOWED_USERS
|
|
||||||
description: "Comma-separated list of allowed Rocket.Chat usernames"
|
|
||||||
required: false
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Hermes Agent — API key (generated by Rocket.Chat Plugin installer)
|
||||||
|
# Set OLLAMA_API_KEY env var before running install.sh --non-interactive
|
||||||
|
OLLAMA_API_KEY=PLACEH..._KEY
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Hermes Agent — minimal working configuration
|
||||||
|
# Generated by Rocket.Chat Plugin installer
|
||||||
|
# Expand with: hermes setup
|
||||||
|
|
||||||
|
model:
|
||||||
|
default: deepseek-v4-pro
|
||||||
|
provider: ollama-cloud
|
||||||
|
base_url: https://ollama.com/v1
|
||||||
|
|
||||||
|
providers: {}
|
||||||
|
|
||||||
|
toolsets:
|
||||||
|
- hermes-cli
|
||||||
|
|
||||||
|
plugins:
|
||||||
|
enabled:
|
||||||
|
- rocketchat-platform
|
||||||
|
|
||||||
|
agent:
|
||||||
|
max_turns: 90
|
||||||
|
gateway_timeout: 1800
|
||||||
|
|
||||||
|
terminal:
|
||||||
|
backend: local
|
||||||
|
|
||||||
|
display:
|
||||||
|
language: de
|
||||||
|
|
||||||
|
gateway:
|
||||||
|
enabled: true
|
||||||
|
platforms:
|
||||||
|
rocketchat:
|
||||||
|
enabled: true
|
||||||
|
extra:
|
||||||
|
base_url: PLACEHOLDER_RC_URL
|
||||||
|
home_channel:
|
||||||
|
platform: rocketchat
|
||||||
|
chat_id: PLACEHOLDER_RC_HOME
|
||||||
|
name: PLACEHOLDER_RC_HOME_NAME
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Rocket.Chat Plugin — environment file hook for hermes-gateway
|
||||||
|
# Generated by install.sh — do not edit manually
|
||||||
|
[Service]
|
||||||
|
EnvironmentFile=%h/.config/hermes/rocketchat.env
|
||||||
|
EnvironmentFile=%h/.hermes/.env
|
||||||
Reference in New Issue
Block a user