Compare commits

...
6 Commits
Author SHA1 Message Date
duffyduckandClaude Opus 4.8 45167b7bb5 refactor: ai-box/ (bootstrap + README) nach xtts/ verschieben
Das Host-Bootstrap bereitet genau den xtts-Stack vor (legt xtts/.env an, startet
xtts-Compose) und gilt fuer alle Dienste (f5tts/whisper/voxtral/llm). Nach dem
Klonen sucht man das in xtts/ — dort war bisher kein README.

- git mv ai-box/bootstrap.sh xtts/bootstrap.sh; ai-box/README.md → xtts/README.md
- interne Verweise cd ARIA-AGENT/ai-box → cd ARIA-AGENT/xtts (Pfad-Logik
  SCRIPT_DIR/../xtts funktioniert unveraendert, da xtts jetzt das Script-Dir ist)
- README neu betitelt: "xtts — AI-Box (Compute-Node) Setup & Bootstrap" +
  Kontext (Profile/GPU im Haupt-README)
- leeres ai-box/ entfernt

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-19 03:33:15 +02:00
duffyduckandClaude Opus 4.8 66781d8d90 feat(fleet): Auslastungs-Monitor pro Box — live nvidia-smi + Graphen (Stage E)
Pro Box ein "Auslastung"-Button in der Compute-Flotte → Modal mit live
nvidia-smi (1s), Graphen (GPU-Auslastung + Tokens/Intervall) und Besen-Reset.
Historie liegt auf der Box, Diagnostic holt sie via RVS.

- node_stats.py (identisch in allen 4 Worker-Build-Contexts): Sampler alle 15s
  (nvidia-smi + Token-Delta → Ringpuffer ~500 Punkte, persistent als JSON auf
  der Box), Live-Stream (node_stats, 1s, Auto-Stop 300s), History-Request,
  Reset. nvidia-smi via async subprocess, fail-safe ohne GPU.
- Worker-Wiring (f5tts/whisper/voxtral/llm-adapter): Import, Sampler-Task,
  _stats.handle() nach dem targetInstance-Filter. llm-adapter zaehlt Tokens
  (usage.total_tokens) → Token-Graph nur bei LLM-Boxen. Dockerfiles kopieren
  node_stats.py.
- compose: llm-adapter bekommt runtime:nvidia + NVIDIA_VISIBLE_DEVICES=all +
  DRIVER_CAPABILITIES=utility (nur nvidia-smi, KEIN VRAM/Compute).
- diagnostic/server.js: relay node_stats_* (Browser→Box) + forward (Box→Browser).
- diagnostic/index.html: Auslastung-Button pro Node (Ziel bevorzugt llm-Instanz),
  Modal mit live nvidia-smi + Inline-SVG-Sparklines, Besen-Reset.

Reporter-Wahl bevorzugt die llm-Instanz (sieht alle GPUs + Tokens); GPU-Worker
sehen ihre gepinnte Karte. Gitignored Historie stoert git-Baum der Box nicht.
Deploy: diagnostic + GPU-Boxen neu bauen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-19 03:26:17 +02:00
duffyduckandClaude Opus 4.8 5c25d6abeb feat(llm): Modell-Download + HuggingFace-Katalog (Stage D)
Neue lokale GGUF-Modelle per Knopf auf eine Box laden — ohne Image-Rebuild.

- llm-adapter besitzt jetzt llama-swaps Config: generiert
  /models/llama-swap.config.yaml aus Basis-Template (xtts/llama-swap/config.yaml)
  + persistenter Registry /models/aria_models.json. Neue RVS-Handler
  llm_provision_model / llm_remove_model (targetInstance-gefiltert): Registry+
  Config schreiben, llama-swap-Reload anstossen, neu announcen, Warmup (zieht das
  GGUF via -hf, Fortschritt via service_status loading→ready). pyyaml ergaenzt.
- compose: llama-swap liest --config /models/llama-swap.config.yaml; llm-adapter
  mountet ./models (rw) + ./llama-swap (ro Template).
- diagnostic/server.js: /shared/config/llm_catalog.json (kuratierte GGUF-Liste)
  + GET /api/llm-catalog + POST /api/llm-catalog/refresh (HuggingFace-API-Merge);
  Actions llm_provision_model / llm_remove_model / llm_test; llm_provision_result
  an Browser durchgereicht.
- diagnostic/index.html: "Modell-Katalog"-Card (HF-Refresh, Ziel-Box waehlen,
  Laden, Verfuegbarkeit) + Test-Chat-Zeile ans lokale LLM (Antwort + Latenz).

Download nutzt llama-swaps vorhandenen -hf-Pfad (kein neuer Download-Code).
Reload ist der einzige Deploy-Verify-Punkt (llama-swap-Image); Fallback Box-up.
Deploy: diagnostic neu bauen (VM) + llm-Boxen neu bauen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-19 03:12:31 +02:00
duffyduckandClaude Opus 4.8 05c6c7687a feat(llm): Flotten-Katalog + modell-bewusstes LLM-Routing (Stage C)
ARIA nutzt lokale LLMs auf mehreren ai-boxen; jede Box (llama-swap) kann
mehrere Modelle fahren. Auswahl nach MODELL, Box wird automatisch gewaehlt.

- xtts/llm-adapter/adapter.py: fragt beim Connect llama-swap GET /v1/models ab
  und meldet die Modell-Liste in worker_hello (models:[...]), Fallback [LLM_MODEL].
- bridge/aria_bridge.py: Worker-Registry speichert models[]; _pick_worker(service,
  model=) beruecksichtigt nur Boxen, die das Modell fahren koennen (nachsichtig:
  keine → None → Broadcast/Claude-Fallback); Round-Robin je service+model
  verteilt mehrere Projekte auf mehrere Boxen; _local_llm reicht das Modell durch;
  _worker_list traegt models[].
- diagnostic/server.js: workers-Map + workerList um models[] erweitert.
- diagnostic/index.html: Compute-Flotte zeigt bei llm die Modell-Liste; das
  "Lokales Modell"-Dropdown wird LIVE aus den angemeldeten Boxen gebaut
  (Vereinigung + kuratierte Namen aus local_models.json, "· N Box(en)"/"offline"),
  darunter eine kompakte LLM-Box-Liste (Node→Modelle→Health). Speisung aus dem
  vorhandenen worker_update-Broadcast.

Kein Brain-/App-Eingriff. Routing greift nur bei aktivem Lokal-Schalter.
Deploy: diagnostic + bridge + llm-Boxen neu bauen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-19 02:49:30 +02:00
duffyduckandClaude Opus 4.8 0f122a1ad7 feat(voice): zentraler Stimmen-Store + Auto-Provisioning der f5tts-Flotte
Stimmen lagen bisher nur pro Box (xtts/voices/). Jetzt haelt der Diagnostic-
Server sie zentral als /shared/voices/{name}.tar.gz und versorgt jede f5tts-Box
automatisch.

- diagnostic/server.js (Bibliothekar):
  * zentraler Store + Helfer (list/read/write/delete tar.gz)
  * reconcileVoices() beim worker_hello einer f5tts-Box: push fehlende zentrale
    Stimmen (xtts_import_voice, targetInstance) + pull box-eigene, zentral
    fehlende (xtts_export_voice) → seedet den Store aus der ersten Box
  * autonome RVS-Listener: xtts_voice_saved → zentraler Ingest (auch App-Uploads);
    xtts_voice_exported (nur eigene requestId) → in Store schreiben;
    xtts_delete_voice → zentrale Kopie mitloeschen
  * Delete-Action loescht zentrale Kopie direkt mit
- xtts/f5tts/bridge.py: worker_hello traegt jetzt voices:[names] (ohne
  default_ref) fuer den Abgleich; handle_export_voice echot requestId zurueck
  (Korrelation zentral vs. browser-initiiert)

Wiederverwendet den vorhandenen export/import-tar.gz-Transport + Stage-3-
targetInstance-Filter. Playback (preview_voice) und Lastrouting (freieste Box)
existierten bereits. Keine App-/aria-bridge-Aenderung.

Deploy: diagnostic + f5tts-Boxen neu bauen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-19 01:32:06 +02:00
duffyduckandClaude Opus 4.8 a773832bca refactor: "Gamebox" ueberall durch "AI-Box(en)" ersetzen
Rein terminologisch: die feste "Gamebox" ist konzeptuell zu beliebig vielen
AI-Boxen geworden (Multi-Node-Compute-Fleet). Wort-Sweep ueber Code-Kommentare,
Strings, README, docs, .env.example, CHANGELOG — keine Identifier/Keys betroffen
(Gamebox kam nirgends in Variablennamen vor). Casing erhalten: Gamebox→AI-Box,
gamebox→ai-box. NODE_NAME-Default gamebox→ai-box, Instanz-IDs f5tts@ai-box.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-19 00:34:21 +02:00
31 changed files with 1538 additions and 133 deletions
+1 -1
View File
@@ -235,7 +235,7 @@ Nur **App neu bauen** (kein Backend). APK 0.2.2.0.
## [0.2.0.4 – 0.2.0.5] — 2026-07-11 — Plan B: Lokales LLM („Gemini-Feeling")
Ein kleines, schnelles Modell (**Qwen3 8B** via llama.cpp/llama-swap auf der Gamebox-GPU) übernimmt einfache Turns in **<1 s**; alles Schwere/Technische/Werkzeug-artige reicht ein Router automatisch an **Claude** weiter. Ziel: schnelle Antworten ohne die Claude-Max-Subscription aufzugeben.
Ein kleines, schnelles Modell (**Qwen3 8B** via llama.cpp/llama-swap auf der AI-Box-GPU) übernimmt einfache Turns in **<1 s**; alles Schwere/Technische/Werkzeug-artige reicht ein Router automatisch an **Claude** weiter. Ziel: schnelle Antworten ohne die Claude-Max-Subscription aufzugeben.
### Hinzugefügt
+4 -4
View File
@@ -805,7 +805,7 @@ cp ARIA-v0.0.3.0.apk ~/ARIA-AGENT/rvs/updates/
Die GPU-Dienste laufen auf einem oder mehreren separaten Rechnern mit NVIDIA GPU.
Jeder **Compute-Node** verbindet sich ueber RVS mit der ARIA-Infrastruktur — kein
VPN noetig, funktioniert ueber verschiedene Netze hinweg. Frueher war das *eine*
feste „Gamebox"; jetzt sind es beliebig viele Nodes, jeder per `.env` konfiguriert.
feste „AI-Box"; jetzt sind es beliebig viele Nodes, jeder per `.env` konfiguriert.
### Dienste & Profile
@@ -828,7 +828,7 @@ LLM-Box COMPOSE_PROFILES=llm LLM_GPU=0
-- kleine Karte: Whisper (klein) statt Voxtral, neben F5-TTS --
Klein-Box COMPOSE_PROFILES=whisper,f5tts WHISPER_GPU=0 F5TTS_GPU=0
── oder All-in-One ──
Gamebox COMPOSE_PROFILES=voxtral,f5tts,llm VOXTRAL_GPU=1 F5TTS_GPU=0 LLM_GPU=0
AI-Box COMPOSE_PROFILES=voxtral,f5tts,llm VOXTRAL_GPU=1 F5TTS_GPU=0 LLM_GPU=0
↕ RVS (Rechenzentrum, WebSocket Relay)
@@ -1052,7 +1052,7 @@ docker exec aria-brain curl localhost:8080/memory/stats
- [x] Pre-Roll-Buffer einstellbar in App-Settings
- [x] Decimal-zu-Worte fuer TTS + generisches Acronym-Buchstabieren
- [x] voice_preload/voice_ready: visueller Status-Indikator beim Stimmen-Wechsel
- [x] Whisper STT auf die Gamebox ausgelagert (CUDA float16, fast Echtzeit)
- [x] Whisper STT auf die AI-Box ausgelagert (CUDA float16, fast Echtzeit)
- [x] **F5-TTS ersetzt XTTS** — bessere Voice-Cloning-Qualitaet, Whisper-auto-transkribierter Referenz-Text
- [x] Audio-Pause statt Ducking (TRANSIENT statt MAY_DUCK) + release-Timing fix
- [x] VAD-Stille-Toleranz einstellbar (1-8s) + adaptive Mikro-Baseline + Max-Aufnahme einstellbar (1-30 min)
@@ -1107,7 +1107,7 @@ docker exec aria-brain curl localhost:8080/memory/stats
- [x] App: Chat-Suche mit Next/Prev Navigation statt Filter
- [x] Token/Call-Metrics + Subscription-Quota-Tracking (Pro / Max 5x / Max 20x / Custom)
- [x] Datei-Manager Multi-Select: Bulk-Download als ZIP + Bulk-Delete (Diagnostic + App)
- [x] **FLUX.1 Bildgenerierung**: eigener `flux-bridge`-Container auf der Gamebox (analog xtts/whisper) mit Hot-Swap zwischen FLUX.1-dev (Quali) und FLUX.1-schnell (Tempo). Default-Modell + Raw-/Switch-Keywords + HuggingFace-Token in Diagnostic-UI verwaltet, automatischer Pipeline-Reload bei Modell-Wechsel. ARIA bekommt `flux_generate`-Tool, Output landet als `/shared/uploads/aria_generated_<ts>.png` und wird via `[FILE: ...]`-Marker als Anhang-Bubble in App + Diagnostic gerendert. Download-Status (mehrere GB) sichtbar als 🎉-Toast wenn fertig
- [x] **FLUX.1 Bildgenerierung**: eigener `flux-bridge`-Container auf der AI-Box (analog xtts/whisper) mit Hot-Swap zwischen FLUX.1-dev (Quali) und FLUX.1-schnell (Tempo). Default-Modell + Raw-/Switch-Keywords + HuggingFace-Token in Diagnostic-UI verwaltet, automatischer Pipeline-Reload bei Modell-Wechsel. ARIA bekommt `flux_generate`-Tool, Output landet als `/shared/uploads/aria_generated_<ts>.png` und wird via `[FILE: ...]`-Marker als Anhang-Bubble in App + Diagnostic gerendert. Download-Status (mehrere GB) sichtbar als 🎉-Toast wenn fertig
- [x] **ARIA Live (Diagnostic) + Not-Aus**: read-only Mirror der Claude-Code-Session ersetzt den SSH-Tab. Tool-Calls + Inputs + Outputs (truncated 4 KB) live, farbcodiert. Roter ⛔ Not-Aus-Button schickt `cancel_request` mit `hard:true` → Bridge ruft den proxy-internen `/cancel-all` Side-Channel (Port 3457) → alle Claude-Subprocesses sofort tot. Plus: Idle-Watchdog im Proxy (20 min Inaktivitaet → Subprocess-Kill) + httpx-Timeout-Split im Brain (connect 10s / read 24h) damit lange Pentests durchlaufen
- [x] **OAuth2-Pipeline ueber RVS-Callback**: Caddy mit Let's Encrypt vor dem RVS, HTTP-Route `/oauth/callback/{service}` broadcastet als `oauth_callback`-WS-Message, aria-bridge forwarded an Brain, Token landet in `/shared/config/oauth_tokens.json` (mode 0600). ARIAs `oauth_register_provider`-Tool legt neue Provider on-demand an (URLs/scopes, nicht Credentials). Diagnostic + App haben beide Provider-Verwaltung inklusive Custom-Provider-Anlage
- [x] **Skill-Mgmt-Tools fuer ARIA**: `skill_update` (Code/README/pip_packages mit venv-Rebuild) + `skill_delete` — verhindert Skill-Friedhof mit `-v2`/`-fixed`-Suffixen. Plus App-seitiger SkillBrowser (Run + Live-Output + Logs der letzten 20 Runs) in Settings → 🛠️ Skills
+4 -4
View File
@@ -357,7 +357,7 @@ const ChatScreen: React.FC = () => {
// folgende identische Events (z.B. zwei 'thinking' hintereinander) den
// Stream zumuellen. Eigentlich seltener Fall, aber billig zu pruefen.
const lastThoughtKeyRef = useRef<string>('');
// Service-Status (Gamebox: F5-TTS / Whisper Lade-Status) + Banner-Sichtbarkeit
// Service-Status (AI-Box: F5-TTS / Whisper Lade-Status) + Banner-Sichtbarkeit
const [serviceStatus, setServiceStatus] = useState<Record<string, {state: string, model?: string, loadSeconds?: number, error?: string, downloading?: boolean, freshlyDownloaded?: boolean}>>({});
const [serviceBannerDismissed, setServiceBannerDismissed] = useState(false);
// Gerätelokale TTS-Config: globaler Toggle (aus Settings) + temporäres Muten (Mund-Button)
@@ -1591,7 +1591,7 @@ const ChatScreen: React.FC = () => {
}
}
// Gamebox-Bridges (f5tts/whisper/flux) melden Lade-Status — Banner oben.
// AI-Box-Bridges (f5tts/whisper/flux) melden Lade-Status — Banner oben.
// Toast bei Download-Ende: erstmaliger HF-Download (mehrere GB) → User
// soll wissen dass er Bilder/Stimmen jetzt nutzen kann ohne in den
// Banner gucken zu muessen.
@@ -2289,7 +2289,7 @@ const ChatScreen: React.FC = () => {
// Aufraeumen von "verarbeitet"-Placeholder die nie ein STT-Result bekommen
// haben (leere Aufnahme, Wake-Word-Echo, STT-Fehler etc). Timeout skaliert
// mit der Aufnahmedauer — Whisper braucht auf der Gamebox grob real-time/5,
// mit der Aufnahmedauer — Whisper braucht auf der AI-Box grob real-time/5,
// plus Bridge-Roundtrip + Network. Formel: 60s Buffer + 1x Aufnahmedauer.
// Bei 5min Aufnahme = 6 min Wait, bei 5s Aufnahme = 65s. Sicher genug damit
// langsame STTs nicht versehentlich aufgeraeumt werden.
@@ -3060,7 +3060,7 @@ const ChatScreen: React.FC = () => {
</TouchableOpacity>
</View>
{/* Service-Status Banner (Gamebox: F5-TTS / Whisper Lade-Status) */}
{/* Service-Status Banner (AI-Box: F5-TTS / Whisper Lade-Status) */}
{(() => {
const entries = Object.entries(serviceStatus);
if (entries.length === 0 || serviceBannerDismissed) return null;
+1 -1
View File
@@ -859,7 +859,7 @@ META_TOOLS = [
"function": {
"name": "flux_generate",
"description": (
"Generiere ein Bild aus einem Text-Prompt via FLUX auf der Gamebox-GPU. "
"Generiere ein Bild aus einem Text-Prompt via FLUX auf der AI-Box-GPU. "
"Brauchbar fuer 'mal mir ein X', 'wie sieht ein Y aus?', Mockups, "
"Konzept-Skizzen, Memes. Render dauert 20-90s — kuendige es Stefan "
"kurz an, dann ist er nicht ueberrascht.\n\n"
+1 -1
View File
@@ -1,7 +1,7 @@
"""
Local-LLM-Client (Plan B) — Brain-Seite.
Ruft das schnelle lokale LLM (Qwen3 auf der Gamebox) ueber die Bridge:
Ruft das schnelle lokale LLM (Qwen3 auf der AI-Box) ueber die Bridge:
Brain → HTTP /internal/local-llm → Bridge → RVS → llm-adapter → llama.cpp
Analog zum Claude-`proxy_client`, nur ueber die Bridge (die ist der RVS-Client;
+48 -32
View File
@@ -2,7 +2,7 @@
ARIA Voice Bridge — Hauptmodul.
Verbindet die Android App (via RVS) mit ARIA-Core. Spracheingabe laeuft
ueber die whisper-bridge (Gamebox, faster-whisper auf CUDA), Sprachausgabe
ueber die whisper-bridge (AI-Box, faster-whisper auf CUDA), Sprachausgabe
ueber die f5tts-bridge (Voice Cloning, satzweises PCM-Streaming).
Nachrichtenfluss:
@@ -479,7 +479,7 @@ class STTEngine:
Erkannter Text oder leerer String.
"""
if self.model is None:
# Lazy-Load: normalerweise laeuft STT remote auf der Gamebox.
# Lazy-Load: normalerweise laeuft STT remote auf der AI-Box.
# Erst wenn das Fallback hier zuschlaegt, laden wir lokal.
logger.info("Lokales Whisper-Fallback — Modell wird nachgeladen...")
try:
@@ -654,7 +654,7 @@ class ARIABridge:
self._seen_client_msg_ids: "OrderedDict[str, float]" = OrderedDict()
self._SEEN_CLIENT_MSG_LIMIT = 200
# Komponenten (TTS: F5-TTS remote auf der Gamebox, lokales TTS wurde entfernt)
# Komponenten (TTS: F5-TTS remote auf der AI-Box, lokales TTS wurde entfernt)
self.tts_enabled = True
self.xtts_voice = ""
self._f5tts_config: dict = {}
@@ -686,7 +686,7 @@ class ARIABridge:
except (TypeError, ValueError):
self._persistent_xtts_speed = None
# F5-TTS-Felder aufsammeln (werden spaeter via RVS rebroadcastet,
# damit die f5tts-bridge auf der Gamebox die Settings auch nach
# damit die f5tts-bridge auf der AI-Box die Settings auch nach
# Restart wiederbekommt — sonst stuende sie auf Hard-Defaults)
for k in ("f5ttsModel", "f5ttsCkptFile", "f5ttsVocabFile",
"f5ttsCfgStrength", "f5ttsNfeStep"):
@@ -746,7 +746,7 @@ class ARIABridge:
# Gleiche Logik fuer die Wiedergabegeschwindigkeit (F5-TTS speed-Param,
# App-Setting aria_tts_speed, 1.0 = normal).
self._next_speed_override: Optional[float] = None
# STT-Requests die aktuell auf Antwort von der whisper-bridge (Gamebox) warten.
# STT-Requests die aktuell auf Antwort von der whisper-bridge (AI-Box) warten.
# requestId → Future mit dem Text (oder None bei Fehler).
self._pending_stt: dict[str, asyncio.Future] = {}
# whisper-bridge service_status: True wenn ready, False/None wenn loading/unbekannt.
@@ -771,7 +771,7 @@ class ARIABridge:
# {service, node, gpus, model, busy, last_seen}. Genutzt fuer die
# Diagnostic-Flotten-Anzeige und (Stage 3) targetInstance-Routing.
self._workers: dict[str, dict] = {}
# FLUX-Render-Requests die aktuell auf Antwort der flux-bridge (Gamebox) warten.
# FLUX-Render-Requests die aktuell auf Antwort der flux-bridge (AI-Box) warten.
# requestId → Future mit dem flux_response-Payload (oder None bei Fehler).
self._pending_flux: dict[str, asyncio.Future] = {}
# flux-bridge service_status: True wenn ready. Render-Timeouts werden
@@ -779,7 +779,7 @@ class ARIABridge:
self._remote_flux_ready: bool = False
# Lokales LLM (Plan B): requestId → Future mit dem llm_response-Payload.
# Analog zu _pending_flux — Brain ruft /internal/local-llm, wir relayen
# llm_request via RVS an den llm-adapter (Gamebox) und warten auf
# llm_request via RVS an den llm-adapter (AI-Box) und warten auf
# llm_response.
self._pending_llm: dict[str, asyncio.Future] = {}
# User-Message-Counter fuer Auto-Compact. Bei zu langer Konversation
@@ -815,7 +815,7 @@ class ARIABridge:
logger.info("ARIA Voice Bridge startet...")
logger.info("=" * 50)
# STT wird standardmaessig von der whisper-bridge (Gamebox) erledigt.
# STT wird standardmaessig von der whisper-bridge (AI-Box) erledigt.
# Lokales Whisper ist nur Fallback und wird lazy geladen wenn remote nicht
# antwortet. Das spart RAM auf der VM und Startup-Zeit.
@@ -1759,7 +1759,7 @@ class ARIABridge:
"""Broadcastet die aktuelle voice_config.json einmalig nach RVS-Connect.
Damit bekommen frisch verbundene Bridges (insbesondere die f5tts-bridge
auf der Gamebox nach Container-Restart) die zuletzt in Diagnostic
auf der AI-Box nach Container-Restart) die zuletzt in Diagnostic
gewaehlten Settings — ohne dass der User in Diagnostic was klicken muss.
"""
try:
@@ -2202,7 +2202,7 @@ class ARIABridge:
await self._broadcast_current_mode()
# Persistierte Voice-Config broadcasten — die f5tts-bridge auf
# der Gamebox bekommt damit nach Restart die zuletzt in
# der AI-Box bekommt damit nach Restart die zuletzt in
# Diagnostic gewaehlten Settings wieder (sonst stuende sie auf
# ihren Hard-Defaults).
asyncio.create_task(self._broadcast_persisted_config())
@@ -2563,7 +2563,7 @@ class ARIABridge:
elif msg_type == "config":
# Konfiguration von App/Diagnostic empfangen + persistent speichern.
# Felder die nicht direkt zur aria-bridge gehoeren (f5tts*) werden
# nur persistiert; die f5tts-bridge auf der Gamebox empfaengt den
# nur persistiert; die f5tts-bridge auf der AI-Box empfaengt den
# gleichen RVS-Broadcast und reagiert selber.
changed = False
if "ttsEnabled" in payload:
@@ -2587,7 +2587,7 @@ class ARIABridge:
new_model = payload["whisperModel"]
allowed = {"tiny", "base", "small", "medium", "large-v3"}
if new_model in allowed and new_model != self.stt_engine.model_size:
logger.info("[rvs] Whisper-Modell → %s (nur Config; Modell laedt Gamebox)",
logger.info("[rvs] Whisper-Modell → %s (nur Config; Modell laedt AI-Box)",
new_model)
self.stt_engine.model_size = new_model
self.stt_engine.model = None
@@ -3448,7 +3448,7 @@ class ARIABridge:
return
elif msg_type == "llm_response":
# Antwort des llm-adapter (Gamebox) auf unseren llm_request.
# Antwort des llm-adapter (AI-Box) auf unseren llm_request.
request_id = payload.get("requestId", "")
future = self._pending_llm.get(request_id)
if future is None or future.done():
@@ -3457,7 +3457,7 @@ class ARIABridge:
return
elif msg_type == "service_status":
# Gamebox-Bridges (whisper / f5tts / flux) melden ihren Lade-Status.
# AI-Box-Bridges (whisper / f5tts / flux) melden ihren Lade-Status.
# Wir nutzen das fuer den dynamischen STT-Timeout: solange whisper
# im 'loading' steckt, geben wir der Bridge mehr Zeit (Modell-Download
# kann 1-2 Min dauern), statt nach 45s lokal zu fallbacken.
@@ -3544,12 +3544,17 @@ class ARIABridge:
iid = (payload.get("instanceId") or "").strip()
if iid:
prev = self._workers.get(iid, {})
_models = payload.get("models")
self._workers[iid] = {
"instanceId": iid,
"service": payload.get("service") or "",
"node": payload.get("node") or "",
"gpus": payload.get("gpus") or "",
"model": payload.get("model") or "",
# models: welche Modelle die Box fahren kann (llm/llama-swap).
# Fallback auf [model] fuer alte Adapter ohne models-Feld.
"models": [m for m in _models if m] if isinstance(_models, list)
else ([payload.get("model")] if payload.get("model") else []),
"busy": bool(prev.get("busy", False)),
"last_seen": time.time(),
}
@@ -3616,11 +3621,11 @@ class ARIABridge:
else:
logger.debug("[rvs] Unbekannter Typ: %s", msg_type)
# STT-Orchestrierung: zuerst Remote (Gamebox), Fallback lokal.
# STT-Orchestrierung: zuerst Remote (AI-Box), Fallback lokal.
# Zwei Timeouts:
# ready=True → 45s reicht selbst fuer lange Audios
# ready=False → 300s, weil das Modell evtl. noch heruntergeladen wird
# (large-v3 ~3GB, kann auf der Gamebox 1-2 Min dauern).
# (large-v3 ~3GB, kann auf der AI-Box 1-2 Min dauern).
_STT_REMOTE_TIMEOUT_READY_S = 45.0
_STT_REMOTE_TIMEOUT_LOADING_S = 300.0
@@ -3973,15 +3978,15 @@ class ARIABridge:
_FLUX_TIMEOUT_LOADING_S = 900.0 # 15 min beim allerersten Mal (Modell-Download)
# ── Local-LLM-Roundtrip: Brain → Bridge → RVS → llm-adapter → zurueck ──
# Qwen3 auf der Gamebox antwortet auf kurze Turns in <1 s. Grosszuegiger
# Timeout deckt Kaltstart / laengere Antworten / Netz-Jitter (Gamebox@home)
# Qwen3 auf der AI-Box antwortet auf kurze Turns in <1 s. Grosszuegiger
# Timeout deckt Kaltstart / laengere Antworten / Netz-Jitter (AI-Box@home)
# ab. Bei Timeout faellt der Router im Brain per Escalation auf Claude.
_LLM_TIMEOUT_S = 30.0
async def _local_llm(self, messages: list, max_tokens: int = 512,
temperature: float = 0.7, stop=None, tools=None,
model=None) -> dict:
"""Schickt einen llm_request an den llm-adapter (Gamebox), wartet auf
"""Schickt einen llm_request an den llm-adapter (AI-Box), wartet auf
llm_response. tools (B1b) werden durchgereicht; tool_calls kommen zurueck.
Rueckgabe: {ok, content, tool_calls, model, elapsedMs} oder {ok:False, error}."""
if self.ws_rvs is None:
@@ -4006,9 +4011,10 @@ class ARIABridge:
req_payload["tools"] = tools
if model:
req_payload["model"] = model
# Redundanz/Multitasking: freie llm-Instanz gezielt adressieren; None
# → Broadcast wie bisher. Mehrere Instanzen → parallele Turns.
llm_target = self._pick_worker("llm")
# Redundanz/Multitasking: freie llm-Instanz gezielt adressieren, die
# das gewaehlte Modell fahren kann; None → Broadcast wie bisher.
# Mehrere Boxen mit demselben Modell → Round-Robin (pro Projekt verteilt).
llm_target = self._pick_worker("llm", model=model or None)
if llm_target:
req_payload["targetInstance"] = llm_target
logger.info("[rvs] llm_request → llm-adapter (id=%s, msgs=%d, max_tokens=%d, tools=%d, model=%s, target=%s)",
@@ -4024,7 +4030,7 @@ class ARIABridge:
try:
result = await asyncio.wait_for(future, timeout=self._LLM_TIMEOUT_S)
except asyncio.TimeoutError:
return {"ok": False, "error": f"Timeout ({self._LLM_TIMEOUT_S:.0f}s) — Gamebox nicht erreichbar?"}
return {"ok": False, "error": f"Timeout ({self._LLM_TIMEOUT_S:.0f}s) — AI-Box nicht erreichbar?"}
if not isinstance(result, dict) or not result.get("ok"):
err = (result or {}).get("error") if isinstance(result, dict) else "leeres Resultat"
return {"ok": False, "error": err or "llm-adapter Fehler"}
@@ -4527,7 +4533,7 @@ class ARIABridge:
await _send_response(writer, 200, result)
elif method == "POST" and path == "/internal/flux-generate":
# Vom Brain (flux_generate-Tool) gefeuert. Wir routen den
# Render-Request via RVS an die flux-bridge (Gamebox),
# Render-Request via RVS an die flux-bridge (AI-Box),
# warten synchron auf die PNG-Antwort, speichern sie nach
# /shared/uploads/ und melden Pfad + Render-Stats zurueck.
# Brain referenziert das Bild dann mit [FILE:]-Marker in
@@ -4564,7 +4570,7 @@ class ARIABridge:
await _send_response(writer, status, result)
elif method == "POST" and path == "/internal/local-llm":
# Vom Brain (Router / Testchat) gefeuert. Wir relayen den
# Chat-Request via RVS an den llm-adapter (Gamebox Qwen3),
# Chat-Request via RVS an den llm-adapter (AI-Box Qwen3),
# warten synchron auf llm_response und geben content zurueck.
try:
data = json.loads(body.decode("utf-8", "ignore"))
@@ -4767,29 +4773,39 @@ class ARIABridge:
out.append({
"instanceId": w["instanceId"], "service": w.get("service") or "",
"node": w.get("node") or "", "gpus": w.get("gpus") or "",
"model": w.get("model") or "", "busy": bool(w.get("busy")),
"model": w.get("model") or "", "models": w.get("models") or [],
"busy": bool(w.get("busy")),
"online": (now - w.get("last_seen", 0)) < self.WORKER_OFFLINE_S,
})
return out
def _pick_worker(self, service: str) -> Optional[str]:
def _pick_worker(self, service: str, model: Optional[str] = None) -> Optional[str]:
"""Waehlt eine online, moeglichst freie Instanz des Diensts (Round-Robin
ueber die freien). Gibt die instanceId oder None (keine online). Fuer
Stage-3-Routing (targetInstance)."""
ueber die freien). Gibt die instanceId oder None. Fuer Stage-3-Routing
(targetInstance).
model: wenn gesetzt (nur llm sinnvoll), kommen nur Boxen in Frage, die das
Modell fahren koennen (models-Liste oder legacy model-Feld). Meldet KEINE
Box das Modell → None (nachsichtig: Aufrufer faellt auf Broadcast zurueck)."""
now = time.time()
online = [w for w in self._workers.values()
if w.get("service") == service
and (now - w.get("last_seen", 0)) < self.WORKER_OFFLINE_S]
if model:
online = [w for w in online
if model in (w.get("models") or [])
or w.get("model") == model]
if not online:
return None
free = [w for w in online if not w.get("busy")]
pool = free or online # alle busy → trotzdem eine nehmen (least-bad)
# Round-Robin: rotierender Zeiger pro Dienst.
# Round-Robin: rotierender Zeiger pro Dienst(+Modell).
rr_key = f"{service}:{model}" if model else service
rr = getattr(self, "_worker_rr", None)
if rr is None:
rr = self._worker_rr = {}
idx = rr.get(service, 0) % len(pool)
rr[service] = idx + 1
idx = rr.get(rr_key, 0) % len(pool)
rr[rr_key] = idx + 1
chosen = pool[idx]
chosen["busy"] = True # optimistisch, bis der naechste Ping korrigiert
return chosen["instanceId"]
+299 -24
View File
@@ -162,7 +162,7 @@
</style>
</head>
<body>
<!-- Service-Status Banner unten rechts (Gamebox: F5-TTS / Whisper Lade-Status) -->
<!-- Service-Status Banner unten rechts (AI-Box: F5-TTS / Whisper Lade-Status) -->
<div id="service-status-banner" style="display:none;position:fixed;bottom:16px;right:16px;z-index:999;background:#1E1E2E;border:1px solid #2A2A3E;border-radius:8px;padding:10px 14px;font-size:12px;color:#fff;min-width:240px;max-width:360px;box-shadow:0 4px 14px rgba(0,0,0,0.5);">
<div style="display:flex;align-items:flex-start;gap:8px;">
<span id="service-status-icon" style="font-size:18px;line-height:1;">&#x23F3;</span>
@@ -171,6 +171,31 @@
</div>
</div>
<!-- Auslastungs-Monitor Modal (Stage E) -->
<div id="node-stats-modal" style="display:none;position:fixed;inset:0;z-index:1001;background:rgba(0,0,0,0.8);align-items:center;justify-content:center;">
<div style="background:#0D0D1A;border:1px solid #2A2A3E;border-radius:10px;padding:16px;max-width:900px;width:94%;max-height:92vh;overflow:auto;display:flex;flex-direction:column;gap:10px;">
<div style="display:flex;align-items:center;justify-content:space-between;">
<h3 style="margin:0;color:#fff;">Auslastung: <span id="node-stats-node">—</span></h3>
<div style="display:flex;gap:10px;align-items:center;">
<button onclick="resetNodeStats()" title="Historie zuruecksetzen" style="background:none;border:none;color:#FFD60A;font-size:18px;cursor:pointer;">🧹</button>
<button onclick="closeNodeStats()" style="background:none;border:none;color:#8888AA;font-size:22px;cursor:pointer;">&times;</button>
</div>
</div>
<div style="display:flex;gap:14px;flex-wrap:wrap;">
<div style="flex:1;min-width:280px;">
<div style="font-size:11px;color:#8888AA;margin-bottom:2px;">GPU-Auslastung (%)</div>
<div id="node-stats-graph-gpu"></div>
</div>
<div id="node-stats-tokens-wrap" style="flex:1;min-width:280px;">
<div style="font-size:11px;color:#8888AA;margin-bottom:2px;">Tokens / Intervall</div>
<div id="node-stats-graph-tokens"></div>
</div>
</div>
<div style="font-size:11px;color:#8888AA;margin-top:4px;">live <code>nvidia-smi</code>:</div>
<pre id="node-stats-smi" style="background:#000;border:1px solid #1E1E2E;border-radius:6px;padding:8px;color:#3FFF9F;font-size:11px;line-height:1.25;overflow:auto;max-height:340px;margin:0;">(warte auf Box…)</pre>
</div>
</div>
<!-- Voice-Preview Modal -->
<div id="voice-preview-modal" style="display:none;position:fixed;inset:0;z-index:1000;background:rgba(0,0,0,0.7);align-items:center;justify-content:center;">
<div style="background:#1A1A2E;border:1px solid #2A2A3E;border-radius:10px;padding:20px;max-width:560px;width:90%;display:flex;flex-direction:column;gap:12px;">
@@ -548,7 +573,7 @@
<h2>Lokales LLM (schnelle Antworten) <button class="info-btn" onclick="showInfo('local-llm')" title="Wie funktioniert das?">ℹ</button></h2>
<div class="card" style="max-width:540px;">
<div style="font-size:11px;color:#8888AA;margin-bottom:12px;line-height:1.55;">
Ein schnelles lokales Modell (<strong>Qwen3</strong> auf der Gamebox) beantwortet
Ein schnelles lokales Modell (<strong>Qwen3</strong> auf der AI-Box) beantwortet
<strong>leichte Fragen in unter 1&nbsp;Sekunde</strong>. Was schwerer wird, gibt es
automatisch an <strong>Claude</strong> ab. Aenderungen greifen sofort
(kein Neustart) — geschrieben nach <code>/shared/config/local_llm.json</code>.
@@ -600,14 +625,46 @@
</div>
<div id="local-llm-model-desc" style="font-size:10px;color:#8888AA;margin:0 0 2px 0;line-height:1.5;"></div>
<div style="font-size:10px;color:#FFD60A;margin:0 0 4px 0;line-height:1.5;">
Beim ersten Wechsel zu einem Modell lädt die Gamebox das GGUF (mehrere GB) —
Beim ersten Wechsel zu einem Modell lädt die AI-Box das GGUF (mehrere GB) —
die <strong>erste Antwort dauert dann länger</strong>, danach ist es gecacht.
Liste kommt aus <code>/shared/config/local_models.json</code> (Keys = xtts/llama-swap/config.yaml).
Verfügbare Modelle kommen <strong>live</strong> von den angemeldeten LLM-Boxen;
Namen aus <code>/shared/config/local_models.json</code>.
</div>
<!-- LLM-Flotte: welche Box faehrt welche Modelle (live via RVS) -->
<div id="local-llm-fleet" style="font-size:11px;color:#8888AA;margin:6px 0 0 0;"></div>
<!-- Test-Chat: kurze Nachricht direkt ans lokale LLM -->
<div style="margin:12px 0 0 0;padding-top:10px;border-top:1px solid #2a2a3a;">
<div style="font-size:12px;color:#E0E0F0;margin-bottom:4px;"><strong>Test-Chat</strong> (aktuelles Modell, direkt ans lokale LLM):</div>
<div style="display:flex;gap:6px;">
<input id="llm-test-input" type="text" placeholder="z. B. Sag kurz Hallo." style="flex:1;background:#1E1E2E;border:1px solid #333;border-radius:4px;padding:6px 8px;color:#E0E0F0;font-family:inherit;font-size:12px;" onkeydown="if(event.key==='Enter')runLlmTest();">
<button class="btn secondary" onclick="runLlmTest()" style="padding:4px 12px;font-size:11px;">Senden</button>
</div>
<div id="llm-test-result" style="font-size:11px;color:#8888AA;margin-top:6px;white-space:pre-wrap;"></div>
</div>
<div id="local-llm-status" style="font-size:11px;color:#6a6a88;margin-top:8px;padding-top:8px;border-top:1px solid #2a2a3a;min-height:14px;"></div>
</div>
</div>
<!-- Modell-Katalog: GGUF-Modelle herunterladen/aktivieren (Stage D) -->
<div class="settings-section">
<div style="display:flex;justify-content:space-between;align-items:center;">
<h2 style="margin:0;">Modell-Katalog</h2>
<button class="btn secondary" onclick="refreshLlmCatalog()" style="padding:4px 10px;font-size:11px;">Von HuggingFace aktualisieren</button>
</div>
<div class="card" style="max-width:720px;">
<p style="color:#8888AA;font-size:12px;margin:0 0 8px;">
Gaengige lokale GGUF-Modelle. „Laden" schickt das Modell an die gewaehlte
LLM-Box — llama-swap zieht das GGUF beim ersten Mal (mehrere GB) und meldet
den Fortschritt. Danach ist es im Modell-Dropdown oben waehlbar.
<span style="color:#FFD60A;">Achte auf den VRAM der Box (Groesse je Modell).</span>
</p>
<div id="llm-catalog-list" style="font-size:12px;color:#8888AA;">(lade Katalog…)</div>
<div id="llm-catalog-status" style="font-size:11px;color:#6a6a88;margin-top:6px;min-height:14px;"></div>
</div>
</div>
<!-- Externe KI-Anbieter (Platzhalter) -->
<div class="settings-section">
<h2>Externe Anbieter (OpenRouter &amp; Co)</h2>
@@ -647,7 +704,7 @@
<summary style="color:#8888AA;font-size:12px;cursor:pointer;">F5-TTS Modell-Tuning (advanced)</summary>
<div style="margin-top:10px;display:flex;flex-direction:column;gap:8px;">
<div style="color:#8888AA;font-size:11px;">
Werden via RVS an die f5tts-bridge auf der Gamebox geschickt.
Werden via RVS an die f5tts-bridge auf der AI-Box geschickt.
Modell-/Checkpoint-Wechsel triggert einen Reload (~30s).
Hardcoded Defaults: F5TTS_v1_Base, cfg_strength=2.5, nfe_step=32.
</div>
@@ -838,7 +895,7 @@
<div class="settings-section">
<h2>FLUX Bildgenerierung</h2>
<div style="font-size:11px;color:#8888AA;margin-bottom:8px;">
Steuerung der Image-Generation (flux-bridge auf der Gamebox).
Steuerung der Image-Generation (flux-bridge auf der AI-Box).
Default-Modell wird via RVS gepusht — Wechsel triggert Pipeline-Reload (15-30s
aus HF-Cache, mehrere Minuten beim Erst-Download). Keywords nutzt ARIAs Brain
im System-Prompt.
@@ -2006,7 +2063,48 @@
}
if (msg.type === 'sat_update') { satellites = msg.satellites || []; renderSatellites(); return; }
if (msg.type === 'worker_update') { workers = msg.workers || []; renderWorkers(); return; }
if (msg.type === 'worker_update') { workers = msg.workers || []; renderWorkers(); if (typeof refreshLocalLlmModelChoices === 'function') refreshLocalLlmModelChoices(); if (typeof renderLlmCatalog === 'function') renderLlmCatalog(); return; }
if (msg.type === 'llm_response') {
const p = msg.payload || {};
const out = document.getElementById('llm-test-result');
if (out) {
const ms = window._llmTestStart ? (Date.now() - window._llmTestStart) : (p.elapsedMs || 0);
if (p.ok) { out.textContent = (p.content || '(leer)') + '\n— ' + (p.model || '') + ' · ' + ms + ' ms'; out.style.color = '#E0E0F0'; }
else { out.textContent = '✗ ' + (p.error || 'Fehler'); out.style.color = '#FF6B6B'; }
}
return;
}
if (msg.type === 'llm_provision_result') {
const p = msg.payload || {};
const st = document.getElementById('llm-catalog-status');
if (st) {
if (p.removed) { st.textContent = `✓ '${p.key}' entfernt`; st.style.color = '#8888AA'; }
else if (p.ok) { st.textContent = `✓ '${p.key}' geladen/aktiv auf ${p.instanceId || '?'}`; st.style.color = '#3FFF3F'; }
else { st.textContent = `✗ '${p.key}': ${p.error || 'Fehler'}`; st.style.color = '#FF6B6B'; }
}
return;
}
if (msg.type === 'node_stats') {
const p = msg.payload || {};
if (_nodeStatsTarget && p.instanceId === _nodeStatsTarget) {
const el = document.getElementById('node-stats-smi');
if (el) el.textContent = p.nvidiaSmi || '(leer)';
}
return;
}
if (msg.type === 'node_stats_history') {
const p = msg.payload || {};
if (_nodeStatsTarget && p.instanceId === _nodeStatsTarget) renderNodeStatsHistory(p);
return;
}
if (msg.type === 'node_stats_reset_done') {
const p = msg.payload || {};
if (_nodeStatsTarget && p.instanceId === _nodeStatsTarget) {
renderNodeStatsHistory({ samples: [], tokenCapable: false });
send({ action: 'node_stats_history_request', targetInstance: _nodeStatsTarget });
}
return;
}
if (msg.type === 'sat_devices') {
if (msg.satellite) { satDevices[msg.satellite] = { devices: msg.devices || [], location: msg.location, ts: Date.now() }; }
satScanning = null;
@@ -2022,6 +2120,7 @@
alert('Es war kein Fingerprint vorhanden.');
}
refreshVoiceIdStatus();
loadLlmCatalog();
switchSettingsTab(localStorage.getItem('diag_settings_subtab') || 'models');
return;
}
@@ -2939,7 +3038,7 @@
'Glob': '\uD83D\uDCC1 Dateien suchen',
'Agent': '\uD83E\uDD16 Sub-Agent',
};
// ── Service-Status Banner (Gamebox: F5-TTS / Whisper Lade-Status) ──
// ── Service-Status Banner (AI-Box: F5-TTS / Whisper Lade-Status) ──
// Aggregiert die Status-Infos der Bridges. Wenn irgendwas am Laden
// ist, zeigt das Banner unten rechts. Sobald alles auf 'ready' ist,
// bleibt's einen Moment und wird dann vom User weggeklickt (oder
@@ -4265,20 +4364,82 @@
const meta = WORKER_SVC_META[w.service] || { icon: '⚙️', label: w.service };
const dot = !w.online ? '#666' : (w.busy ? '#FFB020' : '#3FFF3F');
const stat = !w.online ? 'offline' : (w.busy ? 'beschaeftigt' : 'frei');
// llm-Boxen koennen mehrere Modelle fahren (llama-swap) → Liste zeigen.
const modelText = (w.service === 'llm' && Array.isArray(w.models) && w.models.length)
? w.models.join(', ') : (w.model || '');
return '<div style="display:flex;align-items:center;gap:8px;padding:4px 0;">' +
'<span style="width:8px;height:8px;border-radius:50%;background:' + dot + ';display:inline-block;"></span>' +
'<span>' + meta.icon + ' <b>' + escapeHtml(meta.label) + '</b></span>' +
'<span style="color:#8888AA;">' + escapeHtml(w.model || '') + '</span>' +
'<span style="color:#8888AA;">' + escapeHtml(modelText) + '</span>' +
(w.gpus ? '<span style="color:#8888AA;">GPU ' + escapeHtml(w.gpus) + '</span>' : '') +
'<span style="margin-left:auto;color:' + dot + ';">' + stat + '</span>' +
'</div>';
}).join('');
// Auslastungs-Button pro Node — Ziel bevorzugt die llm-Instanz (sieht alle
// GPUs + Tokens), sonst irgendein online Worker des Node.
const group = byNode[node];
const rep = group.find(w => w.service === 'llm' && w.online) || group.find(w => w.online) || group[0];
const btn = rep ? '<button class="btn secondary" onclick="openNodeStats(\'' + escapeHtml(rep.instanceId) + '\',\'' + escapeHtml(node) + '\')" style="padding:2px 8px;font-size:10px;margin-left:8px;">Auslastung</button>' : '';
return '<div style="margin-bottom:10px;">' +
'<div style="font-weight:600;color:#AAB;margin-bottom:2px;">🖥️ ' + escapeHtml(node) + '</div>' +
'<div style="font-weight:600;color:#AAB;margin-bottom:2px;">🖥️ ' + escapeHtml(node) + btn + '</div>' +
rows + '</div>';
}).join('');
}
// ── Auslastungs-Monitor (Stage E) ───────────────────────
let _nodeStatsTarget = '';
function openNodeStats(instanceId, node) {
_nodeStatsTarget = instanceId;
document.getElementById('node-stats-node').textContent = node + ' (' + instanceId + ')';
document.getElementById('node-stats-smi').textContent = '(warte auf Box…)';
document.getElementById('node-stats-graph-gpu').innerHTML = '';
document.getElementById('node-stats-graph-tokens').innerHTML = '';
document.getElementById('node-stats-modal').style.display = 'flex';
send({ action: 'node_stats_history_request', targetInstance: instanceId });
send({ action: 'node_stats_stream_start', targetInstance: instanceId });
}
function closeNodeStats() {
if (_nodeStatsTarget) send({ action: 'node_stats_stream_stop', targetInstance: _nodeStatsTarget });
_nodeStatsTarget = '';
document.getElementById('node-stats-modal').style.display = 'none';
}
function resetNodeStats() {
if (!_nodeStatsTarget) return;
send({ action: 'node_stats_reset', targetInstance: _nodeStatsTarget });
}
// Simple Inline-SVG-Sparkline (kein Fremd-Lib, CSP-sicher).
function sparkline(values, opts) {
opts = opts || {};
const w = 320, h = 90, pad = 4, color = opts.color || '#0096FF';
if (!values.length) return '<div style="color:#555;font-size:11px;">(keine Daten)</div>';
const max = Math.max(opts.max || 0, ...values, 1);
const n = values.length;
const pts = values.map((v, i) => {
const x = pad + (n === 1 ? 0 : (i / (n - 1)) * (w - 2 * pad));
const y = h - pad - (Math.max(0, v) / max) * (h - 2 * pad);
return x.toFixed(1) + ',' + y.toFixed(1);
}).join(' ');
return '<svg viewBox="0 0 ' + w + ' ' + h + '" style="width:100%;height:90px;background:#0A0A16;border:1px solid #1E1E2E;border-radius:6px;">' +
'<polyline points="' + pts + '" fill="none" stroke="' + color + '" stroke-width="1.5"/>' +
'<text x="' + (w - pad) + '" y="12" text-anchor="end" fill="#888" font-size="10">max ' + (opts.fmt ? opts.fmt(max) : Math.round(max)) + '</text>' +
'</svg>';
}
function renderNodeStatsHistory(p) {
const samples = p.samples || [];
const gpu = samples.map(s => Number(s.gpu) || 0);
document.getElementById('node-stats-graph-gpu').innerHTML =
sparkline(gpu, { color: '#3FFF9F', max: 100, fmt: v => Math.round(v) + '%' });
const wrap = document.getElementById('node-stats-tokens-wrap');
if (p.tokenCapable) {
wrap.style.display = '';
const tok = samples.map(s => Number(s.tokens) || 0);
document.getElementById('node-stats-graph-tokens').innerHTML =
sparkline(tok, { color: '#FFD60A' });
} else {
wrap.style.display = 'none';
}
}
// ── Satelliten-Ansicht ─────────────────────────────────
let satellites = []; // [{id, location, caps, control, online}]
let satDevices = {}; // id → {devices, location, ts}
@@ -6475,17 +6636,17 @@
html: `
<p>Jeder Turn, den das <strong>lokale LLM</strong> oder ein <strong>Fast-Path</strong> (reiner Skill, ganz ohne LLM) beantwortet, ist ein Claude-Call, der <strong>nicht</strong> gegen dein Subscription-Quota laeuft.</p>
<p><strong>„Claude-Calls gespart"</strong> = Anzahl der local- + fast-path-Antworten im Zeitfenster. Konservativ gezaehlt: 1 Antwort = mindestens 1 gesparter Claude-Call (bei Tool-Use waeren es real oft mehr).</p>
<p><strong>„lokale Tokens"</strong> = Prompt+Antwort-Tokens, die auf deiner eigenen Gamebox-GPU verarbeitet wurden (echte <code>usage</code>-Zahlen vom Modell, sonst chars/4-Schaetzung). Die kosten dich nichts ausser Strom.</p>
<p><strong>„lokale Tokens"</strong> = Prompt+Antwort-Tokens, die auf deiner eigenen AI-Box-GPU verarbeitet wurden (echte <code>usage</code>-Zahlen vom Modell, sonst chars/4-Schaetzung). Die kosten dich nichts ausser Strom.</p>
<p>Fast-Path-Antworten (z.B. „nächstes Lied") haben ~0 Tokens — reiner Skill-Aufruf, kein Modell.</p>
`,
},
'local-llm': {
title: 'Lokales LLM — schnelle Antworten',
html: `
<p>Ein kleines, schnelles Modell (<strong>Qwen3 8B</strong>) laeuft auf deiner Gamebox-GPU und beantwortet <strong>einfache Plauder-Turns in &lt;1&nbsp;s</strong>. Alles Schwere, Technische oder Werkzeug-artige (Wetter, Timer, Musik, Bilder, Gedaechtnis, Code) reicht ein Router automatisch an <strong>Claude</strong> weiter.</p>
<p>Ein kleines, schnelles Modell (<strong>Qwen3 8B</strong>) laeuft auf deiner AI-Box-GPU und beantwortet <strong>einfache Plauder-Turns in &lt;1&nbsp;s</strong>. Alles Schwere, Technische oder Werkzeug-artige (Wetter, Timer, Musik, Bilder, Gedaechtnis, Code) reicht ein Router automatisch an <strong>Claude</strong> weiter.</p>
<p><strong>Lokales LLM nutzen</strong> — Master-Schalter. Aus = alle Anfragen laufen wie bisher ueber Claude.</p>
<p><strong>Nur lokales LLM</strong> — erzwingt lokal, KEIN Claude-Fallback. Zum Ausprobieren, wie stark das lokale Modell allein ist. Achtung: Werkzeug-Turns (Wetter/Timer/…) funktionieren dann nicht — das lokale Tier hat keine Tools.</p>
<p>Die Antwortzeit haengt an deinem Heim-Internet (Gamebox @home, ARIA @RZ). Ist die Gamebox aus/nicht erreichbar, faellt ARIA automatisch auf Claude zurueck.</p>
<p>Die Antwortzeit haengt an deinem Heim-Internet (AI-Box @home, ARIA @RZ). Ist die AI-Box aus/nicht erreichbar, faellt ARIA automatisch auf Claude zurueck.</p>
`,
},
'local-llm-tools': {
@@ -6825,18 +6986,66 @@
el.textContent = m && m.description ? m.description : '';
}
async function loadLocalModelList() {
// Kuratierte Namen/Beschreibungen laden; die tatsaechliche Verfuegbarkeit
// kommt live aus der Flotte (refreshLocalLlmModelChoices).
try {
const r = await fetch('/api/local-models-list');
const j = await r.json();
_localModelsCache = (j && j.models) || [];
} catch (e) { _localModelsCache = []; }
const sel = document.getElementById('local-llm-model');
if (sel) {
sel.innerHTML = _localModelsCache.map(m =>
`<option value="${m.id}">${m.display_name || m.id}</option>`).join('') || '<option value="">(keine)</option>';
if (_localModelsCache.some(m => m.id === _currentLocalModel)) sel.value = _currentLocalModel;
updateLocalModelDesc();
refreshLocalLlmModelChoices();
}
// Zaehlt pro Modell die online LLM-Boxen, die es fahren koennen.
function fleetLlmModelCounts() {
const counts = {};
for (const w of workers) {
if (w.service !== 'llm' || !w.online) continue;
const list = (Array.isArray(w.models) && w.models.length) ? w.models : (w.model ? [w.model] : []);
for (const id of list) counts[id] = (counts[id] || 0) + 1;
}
return counts;
}
// Baut das Modell-Dropdown aus der Vereinigung von live-Flotte + kuratierter
// Liste; zeigt pro Modell "· N Box(en)" bzw. "· offline". Auswahl bleibt
// erhalten (auch wenn das gewaehlte Modell gerade keine online Box hat).
function refreshLocalLlmModelChoices() {
const sel = document.getElementById('local-llm-model');
if (!sel) return;
const counts = fleetLlmModelCounts();
const nameOf = id => { const m = _localModelsCache.find(x => x.id === id); return (m && m.display_name) || id; };
const ids = new Set();
Object.keys(counts).forEach(id => ids.add(id));
_localModelsCache.forEach(m => ids.add(m.id));
if (_currentLocalModel) ids.add(_currentLocalModel);
const order = Array.from(ids).sort();
sel.innerHTML = order.map(id => {
const n = counts[id] || 0;
const avail = n > 0 ? ` · ${n} Box${n > 1 ? 'en' : ''}` : ' · offline';
return `<option value="${id}">${escapeHtml(nameOf(id))}${avail}</option>`;
}).join('') || '<option value="">(keine)</option>';
if (order.includes(_currentLocalModel)) sel.value = _currentLocalModel;
updateLocalModelDesc();
renderLocalLlmFleet();
}
// Kompakte Box-Liste unter dem Dropdown: Node → Modelle → Health.
function renderLocalLlmFleet() {
const box = document.getElementById('local-llm-fleet');
if (!box) return;
const llm = workers.filter(w => w.service === 'llm');
if (!llm.length) { box.innerHTML = '<span style="color:#6a6a88;">Keine LLM-Box angemeldet. Starte eine Box mit <code>COMPOSE_PROFILES=llm</code>.</span>'; return; }
const byNode = {};
for (const w of llm) { (byNode[w.node || '?'] = byNode[w.node || '?'] || []).push(w); }
box.innerHTML = '<div style="color:#AAB;margin-bottom:2px;">LLM-Boxen:</div>' + Object.keys(byNode).sort().map(node => {
return byNode[node].map(w => {
const dot = !w.online ? '#666' : (w.busy ? '#FFB020' : '#3FFF3F');
const models = (Array.isArray(w.models) && w.models.length) ? w.models.join(', ') : (w.model || '—');
return '<div style="display:flex;align-items:center;gap:6px;padding:2px 0;">' +
'<span style="width:7px;height:7px;border-radius:50%;background:' + dot + ';display:inline-block;"></span>' +
'<span>🖥️ ' + escapeHtml(node) + '</span>' +
'<span style="color:#8888AA;">' + escapeHtml(models) + '</span>' +
'</div>';
}).join('');
}).join('');
}
async function loadLocalLlmConfig() {
try {
@@ -6849,11 +7058,8 @@
if (ol) ol.checked = !!c.localOnly;
if (tv) tv.value = (c.toolVariant === 'full') ? 'full' : 'slim';
_currentLocalModel = c.localLlmModel || 'qwen3-8b';
const sel = document.getElementById('local-llm-model');
if (sel && _localModelsCache.some(m => m.id === _currentLocalModel)) {
sel.value = _currentLocalModel;
updateLocalModelDesc();
}
// Dropdown neu aufbauen (Flotte+kuratiert) und die gespeicherte Auswahl setzen.
refreshLocalLlmModelChoices();
setLocalLlmStatus(c);
} catch (e) { /* still */ }
}
@@ -6876,6 +7082,75 @@
} catch (e) { /* still */ }
}
// ── Modell-Katalog (Stage D) ────────────────────────────
let _llmCatalog = [];
async function loadLlmCatalog() {
try {
const r = await fetch('/api/llm-catalog');
const j = await r.json();
_llmCatalog = (j && j.models) || [];
} catch (e) { _llmCatalog = []; }
renderLlmCatalog();
}
async function refreshLlmCatalog() {
const st = document.getElementById('llm-catalog-status');
if (st) { st.textContent = 'Aktualisiere von HuggingFace…'; st.style.color = '#8888AA'; }
try {
const r = await fetch('/api/llm-catalog/refresh', { method: 'POST' });
const j = await r.json();
_llmCatalog = (j && j.models) || _llmCatalog;
renderLlmCatalog();
if (st) { st.textContent = j.ok ? `✓ ${j.added || 0} neue Modelle von HuggingFace` : `✗ ${j.error || 'Fehler'}`; st.style.color = j.ok ? '#3FFF3F' : '#FF6B6B'; }
} catch (e) { if (st) { st.textContent = '✗ ' + e.message; st.style.color = '#FF6B6B'; } }
}
// online LLM-Boxen (fuer die Ziel-Auswahl + Verfuegbarkeit)
function onlineLlmBoxes() { return workers.filter(w => w.service === 'llm' && w.online); }
function boxesServing(id) { return onlineLlmBoxes().filter(w => (w.models || []).includes(id) || w.model === id); }
function renderLlmCatalog() {
const box = document.getElementById('llm-catalog-list');
if (!box) return;
if (!_llmCatalog.length) { box.innerHTML = '<span style="color:#6a6a88;">Katalog leer.</span>'; return; }
const boxes = onlineLlmBoxes();
box.innerHTML = _llmCatalog.map((m, i) => {
const have = boxesServing(m.id);
const haveTxt = have.length ? `<span style="color:#3FFF3F;">✓ auf ${have.map(b => escapeHtml(b.node)).join(', ')}</span>` : '<span style="color:#6a6a88;">nicht geladen</span>';
const sizeTxt = m.sizeGB ? ` · ~${m.sizeGB} GB` : '';
const opts = boxes.length
? boxes.map(b => `<option value="${escapeHtml(b.instanceId)}">${escapeHtml(b.node)}</option>`).join('')
: '<option value="">(keine Box online)</option>';
return '<div style="display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid #1E1E2E;flex-wrap:wrap;">' +
'<span style="min-width:150px;"><b>' + escapeHtml(m.id) + '</b>' + sizeTxt + '</span>' +
'<span style="color:#8888AA;flex:1;min-width:160px;">' + escapeHtml(m.description || m.hfRepo || '') + '</span>' +
haveTxt +
'<select id="llm-cat-box-' + i + '" style="background:#1E1E2E;border:1px solid #333;border-radius:4px;padding:3px 6px;color:#E0E0F0;font-size:11px;">' + opts + '</select>' +
'<button class="btn secondary" ' + (boxes.length ? '' : 'disabled') + ' onclick="provisionModel(' + i + ')" style="padding:3px 10px;font-size:11px;">Laden</button>' +
'</div>';
}).join('');
}
function provisionModel(i) {
const m = _llmCatalog[i];
if (!m) return;
const sel = document.getElementById('llm-cat-box-' + i);
const target = sel && sel.value;
if (!target) return;
const st = document.getElementById('llm-catalog-status');
if (st) { st.textContent = `Lade '${m.id}' auf ${target}… (GGUF-Download kann dauern)`; st.style.color = '#FFD60A'; }
send({ action: 'llm_provision_model', targetInstance: target, key: m.id, hfRepo: m.hfRepo, quant: m.quant, ctx: m.ctx });
}
function runLlmTest() {
const inp = document.getElementById('llm-test-input');
const out = document.getElementById('llm-test-result');
const text = (inp && inp.value || '').trim();
if (!text) return;
const sel = document.getElementById('local-llm-model');
const model = (sel && sel.value) || _currentLocalModel || '';
const serving = boxesServing(model);
const target = serving.length ? serving[0].instanceId : '';
if (out) { out.textContent = '… sende an ' + (target || '(Broadcast)') + ' (' + model + ')'; out.style.color = '#8888AA'; }
window._llmTestStart = Date.now();
send({ action: 'llm_test', text, model, targetInstance: target });
}
// ── Einstellungen: OpenClaw Config ──────────────────────
// loadOpenClawConfig entfernt — aria-core ist raus.
+197 -5
View File
@@ -349,6 +349,66 @@ function loadLocalModels() {
return DEFAULT_LOCAL_MODELS;
}
// ── LLM-Modell-Katalog (Stage D): herunterladbare GGUF-Modelle ───────
// /shared/config/llm_catalog.json — kuratierte Liste guter GGUF-Modelle plus
// per HuggingFace-Refresh nachgeladene. Der llm-adapter zieht ein Modell via
// -hf beim ersten Load. { id(key), hfRepo, quant, sizeGB, description, source }.
const LLM_CATALOG_FILE = "/shared/config/llm_catalog.json";
const DEFAULT_LLM_CATALOG = [
{ id: "qwen3-8b", hfRepo: "Qwen/Qwen3-8B-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 6, description: "Bestes Tool-Calling, passt auf 12 GB.", source: "curated" },
{ id: "qwen3-4b", hfRepo: "Qwen/Qwen3-4B-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 3, description: "Kleiner + flotter, etwas schwaecher.", source: "curated" },
{ id: "qwen3-14b", hfRepo: "Qwen/Qwen3-14B-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 10, description: "Staerker, braucht mehr VRAM (~16 GB).", source: "curated" },
{ id: "llama-3.1-8b", hfRepo: "bartowski/Meta-Llama-3.1-8B-Instruct-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 5, description: "Llama 3.1 8B Instruct.", source: "curated" },
{ id: "mistral-small-3", hfRepo: "bartowski/Mistral-Small-24B-Instruct-2501-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 14, description: "Mistral Small 24B — stark, viel VRAM.", source: "curated" },
{ id: "gemma-2-9b", hfRepo: "bartowski/gemma-2-9b-it-GGUF", quant: "Q4_K_M", ctx: 8192, sizeGB: 6, description: "Google Gemma 2 9B Instruct.", source: "curated" },
];
function loadLlmCatalog() {
try {
const arr = JSON.parse(fs.readFileSync(LLM_CATALOG_FILE, "utf-8"));
if (Array.isArray(arr) && arr.length && arr.every(m => m && typeof m.id === "string")) return arr;
} catch {}
try {
fs.mkdirSync("/shared/config", { recursive: true });
fs.writeFileSync(LLM_CATALOG_FILE, JSON.stringify(DEFAULT_LLM_CATALOG, null, 2));
} catch {}
return DEFAULT_LLM_CATALOG;
}
function saveLlmCatalog(arr) {
try {
fs.mkdirSync("/shared/config", { recursive: true });
const tmp = LLM_CATALOG_FILE + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(arr, null, 2));
fs.renameSync(tmp, LLM_CATALOG_FILE);
return true;
} catch (e) { log("warn", "llm", `Katalog speichern fehlgeschlagen: ${e.message}`); return false; }
}
function slugModelId(repo) {
return String(repo).toLowerCase().replace(/^.*\//, "").replace(/-gguf$/,"").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "model";
}
// Holt populaere GGUF-Modelle von der HuggingFace-API und merged sie in den
// Katalog (kuratierte Eintraege + Beschreibungen bleiben erhalten).
async function refreshLlmCatalogFromHF() {
const url = "https://huggingface.co/api/models?search=GGUF&sort=downloads&direction=-1&limit=40";
const r = await fetch(url, { headers: { "User-Agent": "aria-diagnostic" } });
if (!r.ok) throw new Error(`HF API ${r.status}`);
const list = await r.json();
const existing = loadLlmCatalog();
const byId = new Map(existing.map(m => [m.id, m]));
let added = 0;
for (const m of (Array.isArray(list) ? list : [])) {
const repo = m.id || m.modelId;
if (!repo || !/gguf/i.test(repo)) continue;
const id = slugModelId(repo);
if (byId.has(id)) continue; // kuratierte/vorhandene nicht ueberschreiben
const entry = { id, hfRepo: repo, quant: "Q4_K_M", ctx: 8192, sizeGB: 0,
description: `HuggingFace · ${(m.downloads || 0).toLocaleString("de")} Downloads`, source: "hf" };
byId.set(id, entry); added++;
}
const merged = Array.from(byId.values());
saveLlmCatalog(merged);
return { models: merged, added };
}
// ── File-Project-Manifest ───────────────────────────────────────────
// Jeder Eintrag map[absoluter_pfad] = project_id (leer = Hauptchat).
// Wird vom files-list-Endpoint + files-set-project gepflegt.
@@ -499,7 +559,7 @@ function workerList() {
const now = Date.now();
return Array.from(workers.values()).map(w => ({
instanceId: w.instanceId, service: w.service, node: w.node,
gpus: w.gpus, model: w.model, busy: !!w.busy,
gpus: w.gpus, model: w.model, models: w.models || [], busy: !!w.busy,
online: (now - (w.last_seen || 0)) < WORKER_OFFLINE_MS,
}));
}
@@ -508,6 +568,64 @@ function broadcastWorkers() {
broadcast({ type: "worker_update", workers: workerList() });
}
// ── Voice-Flotte: zentraler Stimmen-Store + Auto-Provisioning ──────
// Der Diagnostic-Server ist der "Stimmen-Bibliothekar": Stimmen liegen
// zentral als /shared/voices/{name}.tar.gz (das f5tts-Export-Artefakt =
// wav+txt). Meldet sich eine f5tts-Box (worker_hello), gleichen wir ab und
// schieben ihr fehlende Stimmen (xtts_import_voice, targetInstance) bzw. ziehen
// bei ihr vorhandene, zentral fehlende Stimmen (xtts_export_voice) in den Store.
const CENTRAL_VOICES_DIR = "/shared/voices";
const centralExportPending = new Map(); // requestId -> name (unsere eigenen Export-Anfragen)
function ensureCentralVoicesDir() {
try { fs.mkdirSync(CENTRAL_VOICES_DIR, { recursive: true }); } catch (_) {}
}
function centralVoiceNames() {
ensureCentralVoicesDir();
try {
return fs.readdirSync(CENTRAL_VOICES_DIR)
.filter(f => f.endsWith(".tar.gz"))
.map(f => f.slice(0, -7));
} catch (_) { return []; }
}
function readCentralVoiceB64(name) {
try { return fs.readFileSync(`${CENTRAL_VOICES_DIR}/${name}.tar.gz`).toString("base64"); }
catch (_) { return null; }
}
function writeCentralVoice(name, dataB64) {
ensureCentralVoicesDir();
try { fs.writeFileSync(`${CENTRAL_VOICES_DIR}/${name}.tar.gz`, Buffer.from(dataB64, "base64")); return true; }
catch (e) { log("warn", "voice", `zentral schreiben ${name} fehlgeschlagen: ${e.message}`); return false; }
}
function deleteCentralVoice(name) {
try { fs.unlinkSync(`${CENTRAL_VOICES_DIR}/${name}.tar.gz`); log("info", "voice", `zentral geloescht: ${name}`); }
catch (_) {}
}
function requestCentralExport(name) {
// Broadcast-Export-Anfrage; die Box, die die Stimme hat, antwortet. Wir
// korrelieren die Antwort ueber requestId (nur unsere eigenen verarbeiten).
const requestId = "central_" + Date.now() + "_" + Math.random().toString(36).slice(2, 8);
centralExportPending.set(requestId, name);
setTimeout(() => centralExportPending.delete(requestId), 30000);
sendToRVS_raw({ type: "xtts_export_voice", payload: { name, requestId }, timestamp: Date.now() });
}
function provisionVoiceToInstance(name, instanceId) {
const data = readCentralVoiceB64(name);
if (!data) return;
sendToRVS_raw({ type: "xtts_import_voice",
payload: { name, data, targetInstance: instanceId }, timestamp: Date.now() });
log("info", "voice", `provisioniere '${name}' → ${instanceId}`);
}
// Abgleich beim worker_hello einer f5tts-Box: push (zentral→Box) + pull (Box→zentral, seed).
function reconcileVoices(instanceId, boxVoices) {
const central = centralVoiceNames();
const boxSet = new Set(Array.isArray(boxVoices) ? boxVoices : []);
const centralSet = new Set(central);
for (const name of central) if (!boxSet.has(name)) provisionVoiceToInstance(name, instanceId);
for (const name of boxSet) if (!centralSet.has(name)) requestCentralExport(name);
log("info", "voice", `reconcile ${instanceId}: box=${boxSet.size} central=${central.length}`);
}
// ── OpenClaw Gateway Verbindung ─────────────────────────
async function connectGateway() {
@@ -961,9 +1079,12 @@ function connectRVS(forcePlain) {
workers.set(p.instanceId, {
instanceId: p.instanceId, service: p.service || "",
node: p.node || "", gpus: p.gpus || "", model: p.model || "",
models: Array.isArray(p.models) ? p.models : (p.model ? [p.model] : []),
busy: !!prev.busy, last_seen: Date.now(),
});
broadcastWorkers();
// Voice-Flotte: f5tts-Box gerade online → Stimmen abgleichen/provisionieren.
if ((p.service || "") === "f5tts") reconcileVoices(p.instanceId, p.voices);
}
} else if (msg.type === "worker_ping") {
// Heartbeat eines Workers (traegt busy-Status).
@@ -972,13 +1093,37 @@ function connectRVS(forcePlain) {
let w = workers.get(p.instanceId);
if (!w) {
const svc = String(p.instanceId).split("@")[0];
w = { instanceId: p.instanceId, service: svc, node: "", gpus: "", model: "", busy: false, last_seen: 0 };
w = { instanceId: p.instanceId, service: svc, node: "", gpus: "", model: "", models: [], busy: false, last_seen: 0 };
workers.set(p.instanceId, w);
}
w.busy = !!p.busy;
w.last_seen = Date.now();
broadcastWorkers();
}
} else if (msg.type === "xtts_voice_saved") {
// Neue Stimme (App- ODER Diagnostic-Upload, via RVS-Broadcast) → zentral
// sichern. Online-Boxen haben sie durch den voice_upload-Broadcast schon;
// der zentrale Store macht sie persistent + fuer spaeter joinende Boxen
// verfuegbar (die holt dann reconcileVoices ab).
const p = msg.payload || {};
if (p.name && !p.error) {
log("info", "voice", `Stimme '${p.name}' gespeichert → zentraler Ingest`);
requestCentralExport(p.name);
}
} else if (msg.type === "xtts_voice_exported") {
// Antwort auf eine UNSERER zentralen Export-Anfragen (requestId-Match) →
// in den zentralen Store schreiben. Browser-initiierte Exports tragen
// keinen centralExportPending-requestId und werden hier ignoriert.
const p = msg.payload || {};
const rid = p.requestId || "";
if (rid && centralExportPending.has(rid)) {
centralExportPending.delete(rid);
if (p.ok && p.name && p.data) writeCentralVoice(p.name, p.data);
}
} else if (msg.type === "xtts_delete_voice") {
// App-initiierter Delete (Broadcast) → zentrale Kopie mitloeschen.
const p = msg.payload || {};
if (p.name) deleteCentralVoice(p.name);
} else if (msg.type === "agent_activity") {
// Bridge meldet "ARIA denkt/schreibt/tool" oder "idle" — an Browser
// weiterreichen, damit der Thinking-Indikator im Chat erscheint.
@@ -1025,7 +1170,7 @@ function connectRVS(forcePlain) {
}
broadcast({ type: "voice_ready", payload: msg.payload });
} else if (msg.type === "service_status") {
// Gamebox-Bridges (f5tts/whisper) melden ihren Lade-Status —
// AI-Box-Bridges (f5tts/whisper) melden ihren Lade-Status —
// an Browser durchreichen fuer das Banner unten rechts
const svc = msg.payload?.service || "?";
const state = msg.payload?.state || "?";
@@ -1040,6 +1185,12 @@ function connectRVS(forcePlain) {
log("info", "rvs", `service_status ${svc} ${state}${model ? ` (${model})` : ""}`);
}
broadcast({ type: "service_status", payload: msg.payload });
} else if (msg.type === "llm_provision_result") {
// Ergebnis eines Modell-Downloads/Aktivierens → an Browser (Katalog-Status).
broadcast({ type: "llm_provision_result", payload: msg.payload || {} });
} else if (msg.type === "node_stats" || msg.type === "node_stats_history" || msg.type === "node_stats_reset_done") {
// Auslastungs-Monitor (Stage E): Box-Antworten an die Browser durchreichen.
broadcast({ type: msg.type, payload: msg.payload || {} });
} else if (msg.type === "audio_pcm" && msg.payload && _previewPending.size > 0) {
// PCM-Chunks einer laufenden Voice-Preview — sammeln + WAV bauen
_handlePreviewChunk(msg.payload);
@@ -1782,6 +1933,20 @@ const server = http.createServer((req, res) => {
} else if (req.url === "/api/local-models-list" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, models: loadLocalModels() }));
} else if (req.url === "/api/llm-catalog" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, models: loadLlmCatalog() }));
} else if (req.url === "/api/llm-catalog/refresh" && req.method === "POST") {
refreshLlmCatalogFromHF()
.then(r => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, models: r.models, added: r.added }));
log("info", "llm", `LLM-Katalog von HuggingFace aktualisiert: +${r.added} Modelle`);
})
.catch(err => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: err.message, models: loadLlmCatalog() }));
});
} else if (req.url === "/api/local-llm-config" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(readLocalLlmConfig()));
@@ -2660,9 +2825,11 @@ wss.on("connection", (ws) => {
// tar.gz (base64) an XTTS-Bridge schicken — die packt aus
sendToRVS_withResponse("xtts_import_voice", { name: msg.name, data: msg.data }, "xtts_voice_imported", ws);
} else if (msg.action === "xtts_delete_voice") {
// Weiterleiten an XTTS-Bridge, die antwortet mit neuer Liste
// Weiterleiten an alle f5tts-Boxen (Broadcast) + zentrale Kopie loeschen.
// (Der eigene Broadcast kommt nicht zu uns zurueck, daher hier direkt.)
sendToRVS_raw({ type: "xtts_delete_voice", payload: { name: msg.name }, timestamp: Date.now() });
log("info", "server", `Voice-Delete '${msg.name}' an XTTS-Bridge gesendet`);
if (msg.name) deleteCentralVoice(msg.name);
log("info", "server", `Voice-Delete '${msg.name}' an f5tts-Boxen + zentral geloescht`);
} else if (msg.action === "delete_chat_message") {
// Bubble loeschen — Bridge raeumt chat_backup.jsonl + Brain-conversation
// + broadcastet chat_message_deleted via RVS.
@@ -2751,6 +2918,31 @@ wss.on("connection", (ws) => {
// Sessions- und Brain-File-Viewer entfernt — Sessions sind raus, Memory
// laeuft jetzt komplett ueber die Vector-DB im aria-brain (siehe Gehirn-Tab).
// restart_session kommt weiter rein, weil der Watchdog ihn manchmal triggert.
} else if (msg.action === "llm_provision_model") {
// Modell auf eine bestimmte LLM-Box laden/aktivieren (Stage D).
sendToRVS_raw({ type: "llm_provision_model", payload: {
targetInstance: msg.targetInstance || "",
key: msg.key, hfRepo: msg.hfRepo, quant: msg.quant, ctx: msg.ctx, ngl: msg.ngl,
}, timestamp: Date.now() });
log("info", "llm", `provision '${msg.key}' (${msg.hfRepo}) → ${msg.targetInstance || "?"}`);
} else if (msg.action === "llm_remove_model") {
sendToRVS_raw({ type: "llm_remove_model", payload: {
targetInstance: msg.targetInstance || "", key: msg.key }, timestamp: Date.now() });
log("info", "llm", `remove '${msg.key}' → ${msg.targetInstance || "?"}`);
} else if (msg.action === "llm_test") {
// Test-Chat: kurze Nachricht direkt ans lokale LLM (llm_request/llm_response).
const reqId = "diagtest_" + Date.now();
sendToRVS_withResponse("llm_request", {
requestId: reqId,
messages: [{ role: "user", content: String(msg.text || "Sag kurz Hallo.") }],
max_tokens: 256, temperature: 0.5,
model: msg.model || "", targetInstance: msg.targetInstance || "",
}, "llm_response", ws);
log("info", "llm", `Test-Chat → ${msg.model || "?"} @ ${msg.targetInstance || "(broadcast)"}`);
} else if (msg.action === "node_stats_stream_start" || msg.action === "node_stats_stream_stop"
|| msg.action === "node_stats_history_request" || msg.action === "node_stats_reset") {
// Auslastungs-Monitor (Stage E): an die Box (targetInstance) durchreichen.
sendToRVS_raw({ type: msg.action, payload: { targetInstance: msg.targetInstance || "" }, timestamp: Date.now() });
} else if (msg.action === "restart_session") {
handleRestartSession(ws);
// ── Einstellungen ──
+2 -2
View File
@@ -1,7 +1,7 @@
# FLUX.1-dev Bildgenerierung — Architektur & Stand
Ergaenzung des ARIA-Agent-Stacks um native Text-to-Image-Generierung via
FLUX.1-dev auf der Gamebox. Folgt dem **gleichen Pattern wie f5tts / whisper**:
FLUX.1-dev auf der AI-Box. Folgt dem **gleichen Pattern wie f5tts / whisper**:
ein eigener Container auf dem Gaming-PC, der sich selbst per WebSocket zum
RVS verbindet und auf seinen Request-Typ lauscht.
@@ -23,7 +23,7 @@ aria-bridge ── send_to_core ──▶ aria-brain
RVS
│ fanout
▼
flux-bridge (Gamebox)
flux-bridge (AI-Box)
│ FluxPipeline.from_pretrained(...)
│ pipeline(prompt, width, height, steps, guidance).images[0]
│ PIL → PNG → base64
+9 -9
View File
@@ -1,4 +1,4 @@
# Plan B — Lokaler LLM-Router (Gamebox) neben Claude
# Plan B — Lokaler LLM-Router (AI-Box) neben Claude
**Ziel:** „Gemini-Feeling" für den Alltag, ohne die Claude-Max-Subscription
aufzugeben. Ein schnelles lokales LLM beantwortet die einfachen ~80 % der Turns
@@ -11,7 +11,7 @@ Gemessen (10.07.2026): CLI-Round-trip über den Claude-Max-Proxy hat einen
**harten Boden von ~3,5 s** (Subprozess-Start pro Turn). Streaming-API würde das
brechen, kostet aber API-Geld → verliert die Max-Subscription. Ein lokales
LLM für die einfachen Turns umgeht den 3,5-s-Boden komplett und ist **gratis**
(läuft auf vorhandener Gamebox-GPU). Echtes Speech-to-Speech-Duplex (Gemini
(läuft auf vorhandener AI-Box-GPU). Echtes Speech-to-Speech-Duplex (Gemini
Live nativ) ist mit einem Text-Modell als Hirn prinzipiell nicht drin.
## Modell & Serving (entschieden)
@@ -19,17 +19,17 @@ Live nativ) ist mit einem Text-Modell als Hirn prinzipiell nicht drin.
- **Modell:** Qwen3 8B, GGUF **Q4_K_M** (~6 GB). Bestes Tool-Calling der 7/8B-
Klasse, solides Deutsch, Apache-2.0. Alt.: Mistral Small 3 7B (schneller,
weniger Tool-Calling).
- **Serving:** **llama.cpp `llama-server`** im Docker-Container auf der Gamebox
- **Serving:** **llama.cpp `llama-server`** im Docker-Container auf der AI-Box
(kein Ollama nötig — nativer OpenAI-kompatibler `/v1/chat/completions`).
- **VRAM-Budget:** 12-GB-Karte, Whisper-small (~1–2 GB) + F5-TTS (~1–2 GB) →
~8–9 GB frei → passt. (FLUX ist auf 12 GB eh raus.)
## Anbindung: über den RVS, wie TTS/STT (kein IP-Pflegen)
Die Gamebox ist ein anderer Host als das Brain. Statt direktem HTTP (IP/Port/
Die AI-Box ist ein anderer Host als das Brain. Statt direktem HTTP (IP/Port/
Firewall) läuft das LLM **über den RVS-Token-Room**, exakt wie Whisper/F5-TTS:
- llama.cpp hört nur auf localhost der Gamebox.
- llama.cpp hört nur auf localhost der AI-Box.
- Ein **dünner RVS-Adapter** daneben (Vorbild: whisper-/xtts-Bridge) verbindet
sich mit dem RVS-Token, lauscht auf `llm_request`, ruft lokal llama-server,
schickt `llm_response` (korreliert per requestId) zurück.
@@ -115,7 +115,7 @@ mit Ziel lokal.
## Phasen
- **B0 — Infra:** llama.cpp-Container + RVS-Adapter auf der Gamebox,
- **B0 — Infra:** llama.cpp-Container + RVS-Adapter auf der AI-Box,
`ALLOWED_TYPES`, `local_llm_chat()` im Brain. Isoliert testen („sag hallo").
- **B1 — Router + lokale Tools:** Heuristik Tier-1/2 + Escalation, schlanke
Persona lokal, **kuratierte Tool-Auswahl lokal** (Adapter/Bridge/Brain-Tool-
@@ -207,8 +207,8 @@ Zerfaellt in zwei Teile:
(Docker-Socket) + Controller mit Placement-Policy + Reconciliation +
Broadcast-Kollisions-Vermeidung (nicht 2× dieselbe Faehigkeit). = Mini-Nomad.
**Empfehlung:** Fuer 2 Gameboxen NICHT bauen — statische Platzierung reicht
(Gamebox1=LLM, Gamebox2=Voice). Dynamisches Laden/Entladen zum VRAM-Freimachen
**Empfehlung:** Fuer 2 AI-Boxen NICHT bauen — statische Platzierung reicht
(AI-Box1=LLM, AI-Box2=Voice). Dynamisches Laden/Entladen zum VRAM-Freimachen
deckt `llama-swap` innerhalb eines Hosts (B0.5). Waechst die Flotte: erst den
billigen Heartbeat-Teil; fuer echte Orchestrierung Docker Swarm / Nomad nehmen
statt selbst einen Scheduler zu bauen.
@@ -227,7 +227,7 @@ lohnt nicht):
einen Heartbeat via RVS (Host, GPU-Util, VRAM frei/belegt, laufende
GPU-Container). Diagnostic zeigt pro Host VRAM-Balken + Dienste + „Host X hat
N GB frei". Kein Start/Stop, nur Sicht + Hinweis wohin verschiebbar.
- **Zukunft (Gamebox3, 4×3060 = 48 GB):** neuer Host, eigenes Profil, `up` →
- **Zukunft (AI-Box3, 4×3060 = 48 GB):** neuer Host, eigenes Profil, `up` →
erscheint im Dashboard; grosses lokales LLM oder FLUX-Vollausbau dorthin.
Ohne Orchestrator.
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
ARIA FLUX-Bridge — laeuft auf der Gamebox (RTX 3060).
ARIA FLUX-Bridge — laeuft auf der AI-Box (RTX 3060).
Empfaengt flux_request via RVS → FLUX.1-dev/-schnell auf GPU → sendet
flux_response mit base64-PNG zurueck an die aria-bridge. Diese speichert
+5 -5
View File
@@ -183,9 +183,9 @@ Wichtige Mechanismen:
- [x] Decimal-zu-Worte fuer TTS (0.1 → null komma eins, mit IP-Schutz-Lookahead)
- [x] Generic Acronym-Buchstabieren (XTTS → X T T S, USB → U S B, ueber expliziter Liste)
- [x] voice_preload/voice_ready: Stille Mini-Render bei Voice-Wechsel + Toast/Status "bereit"
- [x] Whisper STT auf die Gamebox ausgelagert (faster-whisper CUDA, float16) — neuer aria-whisper-bridge Container
- [x] aria-bridge: STT primaer remote (Gamebox), Fallback lokal nach 45s Timeout
- [x] Whisper-Modell hot-swap auf Gamebox via config-Broadcast aus Diagnostic
- [x] Whisper STT auf die AI-Box ausgelagert (faster-whisper CUDA, float16) — neuer aria-whisper-bridge Container
- [x] aria-bridge: STT primaer remote (AI-Box), Fallback lokal nach 45s Timeout
- [x] Whisper-Modell hot-swap auf AI-Box via config-Broadcast aus Diagnostic
- [x] **F5-TTS ersetzt XTTS komplett** — neuer aria-f5tts-bridge Container, Voice Cloning, satzweises Streaming
- [x] Voice-Upload mit Whisper-Auto-Transkription — User muss keinen Referenz-Text eintippen
- [x] Audio-Pause statt Ducking: Spotify/YouTube pausieren komplett waehrend TTS (TRANSIENT statt MAY_DUCK)
@@ -334,7 +334,7 @@ Skills mit Tool-Use.
- [x] Datei-Manager (Diagnostic + App-Modal): /shared/uploads/ verwalten, Multi-Select + Select-All + Bulk-Download als ZIP + Bulk-Delete
- [x] Wipe-All-Button (Memory + Stimmen + Settings)
- [x] Voice Export/Import pro Stimme (Diagnostic + XTTS-Bridge auf Gamebox)
- [x] Voice Export/Import pro Stimme (Diagnostic + XTTS-Bridge auf AI-Box)
- [x] F5/Whisper-Settings als JSON-Bundle Export/Import
- [x] App Chat-Suche umgebaut: Highlight + Next/Prev statt Filter
- [x] App Pinch-Zoom in Bildern rewriten (Multi-Touch-Race-Bugs)
@@ -399,7 +399,7 @@ Skills mit Tool-Use.
### Architektur
- [ ] Diagnostic: System-Info Tab (Container-Status, Disk, RAM, CPU)
- [ ] RVS Zombie-Connections endgueltig loesen
- [ ] Gamebox: kleine Web-Oberflaeche fuer Credentials/Server-Config oder zentral aus Diagnostic per RVS push
- [ ] AI-Box: kleine Web-Oberflaeche fuer Credentials/Server-Config oder zentral aus Diagnostic per RVS push
- [ ] Erste Skills bauen lassen (yt-dlp, pdf-extract, image-resize, etc.) — durch normale Anfragen, ARIA legt sie selbst an
- [ ] Heartbeat (periodische Selbst-Checks)
- [ ] Lokales LLM als Waechter (Triage vor Claude-Call)
+1 -1
View File
@@ -63,7 +63,7 @@ const ALLOWED_TYPES = new Set([
"agent_stream",
"oauth_callback",
// Lokales LLM (Plan B) — Router im Brain schickt einfache Turns an das
// Qwen3 auf der Gamebox (via Bridge → RVS → llm-adapter → llama.cpp).
// Qwen3 auf der AI-Box (via Bridge → RVS → llm-adapter → llama.cpp).
// llm_partial ist fuer B2 (Token-Streaming) reserviert, noch ungenutzt.
"llm_request", "llm_response", "llm_partial",
// Workspace-Desktop (Code-Projekte): Live-Code-Editor (CodeMirror in der App)
+2 -2
View File
@@ -20,8 +20,8 @@ COMPOSE_PROFILES=whisper,f5tts
# ─── Node-Name ────────────────────────────────────
# Freier Name dieses Rechners. Erscheint in Diagnostic (Flotten-Anzeige) und
# in den Logs, und bildet die Instanz-ID der Dienste (z.B. f5tts@gamebox).
NODE_NAME=gamebox
# in den Logs, und bildet die Instanz-ID der Dienste (z.B. f5tts@ai-box).
NODE_NAME=ai-box
# ─── GPU-Zuordnung pro Dienst ─────────────────────
# Setzt NVIDIA_VISIBLE_DEVICES fuer den jeweiligen Container.
+10 -5
View File
@@ -1,7 +1,12 @@
# ai-box — KI-Box (gpubox) Bootstrap
# xtts — AI-Box (Compute-Node) Setup & Bootstrap
Macht aus einem frisch installierten **Debian Trixie** (headless, nur SSH) einen
startklaren GPU-Satelliten-Host für den `xtts`-Stack (STT/TTS/LLM).
Der `xtts`-Stack sind ARIAs GPU-Dienste (STT: Voxtral/Whisper · TTS: F5-TTS ·
lokales LLM). Er läuft auf einer oder mehreren **AI-Boxen** — jede per `.env`
konfiguriert (`COMPOSE_PROFILES`, GPU-Zuordnung). Details zu Profilen/GPU-Wahl
stehen im Haupt-README (Abschnitt „Compute-Nodes").
`bootstrap.sh` macht aus einem frisch installierten **Debian Trixie** (headless,
nur SSH) einen startklaren GPU-Host für diesen Stack.
## Was das Script tut
@@ -20,13 +25,13 @@ Alles **idempotent** — mehrfach ausführbar.
```bash
git clone <repo> ARIA-AGENT
cd ARIA-AGENT/ai-box
cd ARIA-AGENT/xtts
sudo ./bootstrap.sh
# → Wenn der Treiber frisch installiert wurde: einmal neu starten, dann nochmal:
sudo reboot
# … nach dem Boot:
cd ARIA-AGENT/ai-box
cd ARIA-AGENT/xtts
sudo ./bootstrap.sh --up --token <DEIN_RVS_TOKEN>
```
+2 -2
View File
@@ -4,7 +4,7 @@
# GPU-Satelliten-Host fuer den xtts-Stack (Voxtral/Whisper STT, F5-TTS, lokales LLM).
#
# Ablauf nach `git clone`:
# cd ARIA-AGENT/ai-box
# cd ARIA-AGENT/xtts
# sudo ./bootstrap.sh # richtet Treiber + Docker + NVIDIA-Toolkit ein
# # (falls Treiber frisch installiert: einmal `sudo reboot`, dann Script erneut)
# sudo ./bootstrap.sh --up # dazu: xtts-Stack (Whisper+F5+LLM) hochziehen
@@ -122,7 +122,7 @@ EOF
ok "nvidia-driver aus backports installiert: ${NEWV}"
echo
echo -e "${c_y}==> REBOOT noetig, damit der neue Treiber laedt:${c_0}"
echo -e "${c_y} sudo reboot && danach: cd ai-box && sudo ./bootstrap.sh --up --token <TOKEN>${c_0}"
echo -e "${c_y} sudo reboot && danach: cd xtts && sudo ./bootstrap.sh --up --token <TOKEN>${c_0}"
echo -e "${c_y} (nvidia-smi zeigt dann die neue Version + CUDA-Level)${c_0}"
exit 0
else
+19 -7
View File
@@ -1,7 +1,7 @@
# ════════════════════════════════════════════════
# ARIA Compute-Node — GPU-Dienste (STT / TTS / LLM)
#
# KEINE feste "Gamebox" mehr: dieser Stack laeuft auf beliebig vielen
# KEINE feste "AI-Box" mehr: dieser Stack laeuft auf beliebig vielen
# Worker-Nodes. Jeder Node startet ueber COMPOSE_PROFILES nur die Dienste,
# die er anbieten soll, und pinnt sie per *_GPU auf bestimmte Grafikkarten.
# Alles verbindet sich ueber RVS mit der ARIA-Infrastruktur — kein VPN.
@@ -10,7 +10,7 @@
# STT-Box → COMPOSE_PROFILES=voxtral
# TTS-Box → COMPOSE_PROFILES=f5tts
# LLM-Box → COMPOSE_PROFILES=llm
# All-in-One → COMPOSE_PROFILES=voxtral,f5tts,llm (die alte Gamebox)
# All-in-One → COMPOSE_PROFILES=voxtral,f5tts,llm (die alte AI-Box)
#
# FLUX-Bildgenerierung liegt im /flux Verzeichnis — eigener Stack.
# ════════════════════════════════════════════════
@@ -123,32 +123,41 @@ services:
# bestimmt das `model`-Feld im Request (Brain schickt es aus local_llm.json).
# Erster Load zieht das GGUF via -hf von HF (Cache unter /models, persistent).
# OpenAI-kompatibel auf :8080, nur im Compose-Netz; die Bruecke macht der
# llm-adapter. Modell-Liste: ./llama-swap/config.yaml.
# llm-adapter. Die Modell-Liste erzeugt der llm-adapter dynamisch aus
# ./llama-swap/config.yaml (Basis) + Registry → /models/llama-swap.config.yaml.
llama-swap:
image: ghcr.io/mostlygeek/llama-swap:unified-cuda
container_name: aria-llama-swap
profiles: ["llm"] # startet nur mit COMPOSE_PROFILES=…llm…
runtime: nvidia
volumes:
- ./models:/models # HF-Download-Cache (persistent)
- ./llama-swap/config.yaml:/app/config.yaml:ro # Modell-Liste
- ./models:/models # HF-Cache + generierte Config
environment:
- NVIDIA_VISIBLE_DEVICES=${LLM_GPU:-0}
- NVIDIA_DRIVER_CAPABILITIES=compute,utility
- LLAMA_CACHE=/models # llama-server legt -hf-Downloads hier ab
command: ["--config", "/app/config.yaml", "--listen", "0.0.0.0:8080"]
# Liest die vom llm-adapter generierte Config. Beim allerersten Boot faengt
# restart: unless-stopped die Reihenfolge ab, bis der Adapter sie geschrieben hat.
command: ["--config", "/models/llama-swap.config.yaml", "--listen", "0.0.0.0:8080"]
restart: unless-stopped
# ─── Local-LLM-Adapter — RVS <-> llama.cpp ────
# Verbindet sich per Token an den RVS (wie f5tts/whisper), nimmt llm_request
# entgegen, ruft llama.cpp lokal, antwortet llm_response.
# entgegen, ruft llama.cpp lokal, antwortet llm_response. Verwaltet ausserdem
# llama-swaps Config (Modelle hinzufuegen/entfernen via llm_provision_model).
llm-adapter:
build: ./llm-adapter
container_name: aria-llm-adapter
profiles: ["llm"]
runtime: nvidia # nur fuer nvidia-smi (Auslastungs-Monitor) — kein Compute
depends_on:
- llama-swap
volumes:
- ./models:/models # generierte Config + Registry + Cache
- ./llama-swap:/llamaswap:ro # Basis-Template (config.yaml)
environment:
- NVIDIA_VISIBLE_DEVICES=all # alle Karten sichtbar (nur nvidia-smi)
- NVIDIA_DRIVER_CAPABILITIES=utility # utility = nvidia-smi, KEIN VRAM/Compute
- NODE_NAME=${NODE_NAME:-node}
- RVS_HOST=${RVS_HOST}
- RVS_PORT=${RVS_PORT:-443}
@@ -157,6 +166,9 @@ services:
- RVS_TOKEN=${RVS_TOKEN}
- LLAMA_URL=http://llama-swap:8080
- LLM_MODEL=${LLM_MODEL:-qwen3-8b}
- LLAMA_BASE_CONFIG=/llamaswap/config.yaml
- LLAMA_GEN_CONFIG=/models/llama-swap.config.yaml
- LLM_REGISTRY=/models/aria_models.json
# Erster Load eines Modells kann ein GGUF ziehen (mehrere GB) — grosszuegig.
- LLM_TIMEOUT_SEC=${LLM_TIMEOUT_SEC:-600}
restart: unless-stopped
+1
View File
@@ -20,6 +20,7 @@ COPY requirements.txt .
RUN printf 'torch==2.6.0\ntorchaudio==2.6.0\n' > /tmp/torch-constraint.txt && \
pip3 install --no-cache-dir -c /tmp/torch-constraint.txt -r requirements.txt
COPY node_stats.py .
COPY bridge.py .
CMD ["python3", "bridge.py"]
+31 -6
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
ARIA F5-TTS Bridge — laeuft auf der Gamebox (RTX 3060).
ARIA F5-TTS Bridge — laeuft auf der AI-Box (RTX 3060).
Empfaengt xtts_request via RVS → F5-TTS Voice Cloning auf GPU → streamt
16-bit PCM Chunks als audio_pcm Nachrichten zurueck an die App.
@@ -69,6 +69,11 @@ INSTANCE_ID = f"{WORKER_SERVICE}@{NODE_NAME}"
WORKER_PING_INTERVAL_S = int(os.getenv("WORKER_PING_INTERVAL_S", "10"))
_tts_busy = False # True waehrend eine Synthese laeuft (busy-Report im ping)
# ── Auslastungs-Monitor (Stage E) ──────────────────────────
import node_stats
STATS_PATH = os.getenv("STATS_PATH", f"/root/.cache/huggingface/aria_stats_{WORKER_SERVICE}.json")
_stats = node_stats.NodeStats(INSTANCE_ID, NODE_NAME, STATS_PATH, logger=logger)
DEFAULT_F5TTS_MODEL = "F5TTS_v1_Base"
DEFAULT_F5TTS_CKPT_FILE = "" # leer = Default-Checkpoint von HF
DEFAULT_F5TTS_VOCAB_FILE = "" # leer = Default-Vocab vom Modell
@@ -387,7 +392,7 @@ async def _send(ws, mtype: str, payload: dict) -> None:
# ──────────────────────────────────────────────────────────────
# DEBUG-LOG ueber RVS → /shared/logs/app.log
#
# Gleiches Pattern wie in whisper-bridge: Stefan's Gamebox ist
# Gleiches Pattern wie in whisper-bridge: Stefan's AI-Box ist
# Windows (kein SSH), in Zukunft koennten whisper + f5tts auf
# unterschiedlichen Hosts laufen. Logs ueber RVS heisst: ein Pfad.
#
@@ -675,6 +680,18 @@ async def handle_voice_upload(ws, payload: dict) -> None:
await _send(ws, "xtts_voice_saved", {"name": name, "error": str(e)[:200]})
def _local_voice_names() -> list:
"""Namen der lokal vorhandenen Nutzer-Stimmen (ohne den Box-lokalen
default_ref-Fallback) — fuer die Provisioning-Reconciliation im worker_hello."""
names = []
if VOICES_DIR.exists():
for wav in sorted(VOICES_DIR.glob("*.wav")):
if wav.stem == "default_ref":
continue
names.append(wav.stem)
return names
async def handle_list_voices(ws) -> None:
try:
voices = []
@@ -711,13 +728,16 @@ async def handle_delete_voice(ws, payload: dict) -> None:
async def handle_export_voice(ws, payload: dict) -> None:
"""Packt eine Stimme (.wav + .txt) als tar.gz und sendet sie base64 zurueck."""
name = (payload.get("name") or "").strip()
# requestId aus dem Request zuruueckspiegeln — der Diagnostic-Bibliothekar
# korreliert damit zentrale Exports gegen browser-initiierte.
req_id = payload.get("requestId", "") or ""
if not name:
await _send(ws, "xtts_voice_exported", {"ok": False, "error": "name fehlt"})
await _send(ws, "xtts_voice_exported", {"ok": False, "requestId": req_id, "error": "name fehlt"})
return
try:
wav, txt = voice_paths(name)
if not wav.exists():
await _send(ws, "xtts_voice_exported", {"ok": False, "name": name, "error": "Stimme nicht gefunden"})
await _send(ws, "xtts_voice_exported", {"ok": False, "requestId": req_id, "name": name, "error": "Stimme nicht gefunden"})
return
import io, tarfile
buf = io.BytesIO()
@@ -727,10 +747,10 @@ async def handle_export_voice(ws, payload: dict) -> None:
tar.add(txt, arcname=txt.name)
data = base64.b64encode(buf.getvalue()).decode("ascii")
logger.info("Voice exportiert: %s (%d KB tar.gz)", name, len(buf.getvalue()) // 1024)
await _send(ws, "xtts_voice_exported", {"ok": True, "name": name, "data": data})
await _send(ws, "xtts_voice_exported", {"ok": True, "requestId": req_id, "name": name, "data": data})
except Exception as e:
logger.exception("handle_export_voice Fehler")
await _send(ws, "xtts_voice_exported", {"ok": False, "name": name, "error": str(e)[:200]})
await _send(ws, "xtts_voice_exported", {"ok": False, "requestId": req_id, "name": name, "error": str(e)[:200]})
async def handle_import_voice(ws, payload: dict) -> None:
@@ -827,6 +847,7 @@ async def _worker_register(ws, *, model: str = "", busy_fn=None) -> None:
await _send(ws, "worker_hello", {
"instanceId": INSTANCE_ID, "service": WORKER_SERVICE,
"node": NODE_NAME, "gpus": GPU_IDS, "model": model,
"voices": _local_voice_names(), # fuer Voice-Provisioning-Reconciliation
})
while True:
await asyncio.sleep(WORKER_PING_INTERVAL_S)
@@ -902,6 +923,9 @@ async def run_loop(runner: F5Runner) -> None:
tgt = payload.get("targetInstance")
if tgt and tgt != INSTANCE_ID:
continue
# Auslastungs-Monitor (node_stats_*) abfangen.
if await _stats.handle(ws, mtype, payload, _send):
continue
if mtype == "xtts_request":
try:
@@ -1024,6 +1048,7 @@ async def main() -> None:
sys.exit(1)
VOICES_DIR.mkdir(parents=True, exist_ok=True)
runner = F5Runner()
asyncio.create_task(_stats.run_sampler()) # Auslastungs-Sampler (Stage E)
await run_loop(runner)
+167
View File
@@ -0,0 +1,167 @@
"""
ARIA Node-Stats — Auslastungs-Monitor pro Box (GPU + optional Tokens).
Identische Kopie in jedem Worker-Build-Context (f5tts/whisper/voxtral/llm-adapter),
weil jeder Worker ein eigener Docker-Build-Context ist.
Aufgaben:
- Sampler-Loop (alle SAMPLE_SEC): nvidia-smi-Auslastung + Token-Delta → Ringpuffer
(persistent als JSON auf der Box). Laeuft unabhaengig vom Modal.
- Live-Stream: bei node_stats_stream_start jede Sekunde rohes nvidia-smi + Werte
senden (bis stop / Auto-Timeout).
- History-Request + Reset (Besen).
Reicht `handle(ws, mtype, payload)` in die Worker-Message-Loop ein; gibt True
zurueck, wenn die Nachricht eine node_stats_*-Nachricht war.
"""
import asyncio
import json
import os
import time
SAMPLE_SEC = int(os.getenv("STATS_SAMPLE_SEC", "15"))
HISTORY_CAP = int(os.getenv("STATS_HISTORY_CAP", "500")) # ~2h bei 15s
STREAM_MAX_SEC = int(os.getenv("STATS_STREAM_MAX_SEC", "300"))
async def _run_cmd(*args, timeout=8) -> str:
"""Fuehrt ein Kommando aus, gibt stdout (str) zurueck; '' bei Fehler."""
try:
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
return (out or b"").decode("utf-8", "replace")
except Exception:
return ""
class NodeStats:
def __init__(self, instance_id: str, node_name: str, history_path: str,
token_getter=None, logger=None):
self.instance_id = instance_id
self.node_name = node_name
self.history_path = history_path
self.token_getter = token_getter # callable -> kumulative Token-Zahl (oder None)
self.log = logger
self.samples = self._load()
self._last_tokens = self._tokens_now()
self._stream_task = None
# ── Persistenz ──────────────────────────────────────────
def _load(self) -> list:
try:
with open(self.history_path) as f:
data = json.load(f)
return data if isinstance(data, list) else []
except Exception:
return []
def _persist(self) -> None:
try:
os.makedirs(os.path.dirname(self.history_path) or ".", exist_ok=True)
tmp = self.history_path + ".tmp"
with open(tmp, "w") as f:
json.dump(self.samples[-HISTORY_CAP:], f)
os.replace(tmp, self.history_path)
except Exception:
pass
def _tokens_now(self) -> int:
try:
return int(self.token_getter()) if self.token_getter else 0
except Exception:
return 0
# ── nvidia-smi ──────────────────────────────────────────
async def _query_gpu(self) -> dict:
"""Aggregierte GPU-Werte ueber alle sichtbaren Karten."""
out = await _run_cmd(
"nvidia-smi",
"--query-gpu=utilization.gpu,memory.used,memory.total",
"--format=csv,noheader,nounits")
utils, used, total = [], 0, 0
for line in out.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 3:
continue
try:
utils.append(float(parts[0]))
used += float(parts[1])
total += float(parts[2])
except ValueError:
continue
gpu = round(sum(utils) / len(utils), 1) if utils else 0.0
return {"gpu": gpu, "memUsed": int(used), "memTotal": int(total)}
async def _nvidia_smi_text(self) -> str:
txt = await _run_cmd("nvidia-smi")
return txt or "nvidia-smi nicht verfuegbar"
# ── Sampler (Verlauf) ───────────────────────────────────
async def run_sampler(self) -> None:
while True:
try:
g = await self._query_gpu()
now_tok = self._tokens_now()
dtok = max(0, now_tok - self._last_tokens)
self._last_tokens = now_tok
self.samples.append({
"ts": int(time.time()),
"gpu": g["gpu"], "memUsed": g["memUsed"],
"memTotal": g["memTotal"], "tokens": dtok,
})
if len(self.samples) > HISTORY_CAP:
self.samples = self.samples[-HISTORY_CAP:]
self._persist()
except Exception as e:
if self.log:
self.log.debug("node_stats sample fehlgeschlagen: %s", e)
await asyncio.sleep(SAMPLE_SEC)
# ── Live-Stream ─────────────────────────────────────────
async def _stream(self, ws, send) -> None:
t0 = time.time()
try:
while time.time() - t0 < STREAM_MAX_SEC:
g = await self._query_gpu()
smi = await self._nvidia_smi_text()
await send(ws, "node_stats", {
"instanceId": self.instance_id, "node": self.node_name,
"nvidiaSmi": smi, **g,
})
await asyncio.sleep(1)
except asyncio.CancelledError:
raise
except Exception:
return
# ── Dispatch ────────────────────────────────────────────
async def handle(self, ws, mtype: str, payload: dict, send) -> bool:
if mtype == "node_stats_stream_start":
if self._stream_task and not self._stream_task.done():
self._stream_task.cancel()
self._stream_task = asyncio.create_task(self._stream(ws, send))
return True
if mtype == "node_stats_stream_stop":
if self._stream_task:
self._stream_task.cancel()
self._stream_task = None
return True
if mtype == "node_stats_history_request":
await send(ws, "node_stats_history", {
"instanceId": self.instance_id, "node": self.node_name,
"samples": self.samples[-HISTORY_CAP:],
"tokenCapable": self.token_getter is not None,
"sampleSec": SAMPLE_SEC,
})
return True
if mtype == "node_stats_reset":
self.samples = []
self._persist()
await send(ws, "node_stats_reset_done",
{"instanceId": self.instance_id, "node": self.node_name})
return True
return False
+1
View File
@@ -3,6 +3,7 @@ FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY node_stats.py .
COPY adapter.py .
CMD ["python", "-u", "adapter.py"]
+4 -4
View File
@@ -1,6 +1,6 @@
# Local-LLM-Adapter (Gamebox) — Plan B, Phase B0
# Local-LLM-Adapter (AI-Box) — Plan B, Phase B0
Bringt ein lokales, schnelles LLM (Qwen3 8B) auf die Gamebox und haengt es
Bringt ein lokales, schnelles LLM (Qwen3 8B) auf die AI-Box und haengt es
per RVS an ARIA — fuer die einfachen ~80 % der Turns (<1 s), waehrend Claude
das Tiefen-Hirn bleibt. Siehe `docs/plan-local-llm-router.md` im Repo-Root.
@@ -17,7 +17,7 @@ das Tiefen-Hirn bleibt. Siehe `docs/plan-local-llm-router.md` im Repo-Root.
cached es unter `xtts/models/` (Bind-Mount → kein Re-Download bei Restart).
Default: **Qwen3 8B, Q4_K_M** aus dem offiziellen Repo `Qwen/Qwen3-8B-GGUF`.
Modell/Quant wechseln = in der `.env` der Gamebox setzen (kein Code):
Modell/Quant wechseln = in der `.env` der AI-Box setzen (kein Code):
```
LLM_HF_REPO=Qwen/Qwen3-8B-GGUF # HF-Repo
@@ -35,7 +35,7 @@ umstellen + Container neu — Ein-Zeilen-Wechsel, kein Code.
Modelle) ist ein geplanter Folge-Baustein via `llama-swap` — siehe
`docs/plan-local-llm-router.md`.
## Start (auf der Gamebox)
## Start (auf der AI-Box)
```bash
cd xtts
+203 -12
View File
@@ -1,5 +1,5 @@
"""
ARIA Local-LLM-Adapter (Gamebox) — Plan B, Phase B0.
ARIA Local-LLM-Adapter (AI-Box) — Plan B, Phase B0.
Bruecke zwischen RVS und dem lokalen llama.cpp-Server. Spiegelt das Muster der
whisper-bridge: verbindet sich per WebSocket mit dem RVS (Token-Room, TLS mit
@@ -7,7 +7,7 @@ ws-Fallback, Reconnect-Backoff), lauscht auf `llm_request` und ruft den lokalen
llama.cpp-`/v1/chat/completions`-Endpoint (OpenAI-kompatibel), antwortet mit
`llm_response` (korreliert per requestId).
Topologie: Gamebox steht zuhause, ARIA im RZ — die Kommunikation laeuft ueber
Topologie: AI-Box steht zuhause, ARIA im RZ — die Kommunikation laeuft ueber
den RVS (wie TTS/STT), keine IPs zu pflegen. Nur URL + Token.
Env:
@@ -65,6 +65,94 @@ _inflight = 0 # laufende llm_requests (busy-Report im ping)
# empfindlich reagiert: LLM_DISABLE_THINKING=false setzen.
LLM_DISABLE_THINKING = os.getenv("LLM_DISABLE_THINKING", "true").lower() == "true"
# ── Modell-Verwaltung (Stage D): Adapter besitzt llama-swaps Config ──
# llama-swap liest die GENERIERTE Config (beschreibbar, im /models-Bind). Wir
# erzeugen sie aus dem Basis-Template (kuratierte Defaults) + der persistenten
# Box-Registry (per Diagnostic hinzugefuegte Modelle). So werden neue Modelle
# ohne Image-Rebuild waehlbar.
import yaml # pyyaml
BASE_CONFIG_PATH = os.getenv("LLAMA_BASE_CONFIG", "/llamaswap/config.yaml")
GEN_CONFIG_PATH = os.getenv("LLAMA_GEN_CONFIG", "/models/llama-swap.config.yaml")
REGISTRY_PATH = os.getenv("LLM_REGISTRY", "/models/aria_models.json")
# ── Auslastungs-Monitor (Stage E) ──────────────────────────
import node_stats
STATS_PATH = os.getenv("STATS_PATH", "/models/aria_stats.json")
_total_tokens = 0 # kumulativ, fuer den Token-Graph
_stats = node_stats.NodeStats(INSTANCE_ID, NODE_NAME, STATS_PATH,
token_getter=lambda: _total_tokens, logger=logger)
def _load_registry() -> list:
try:
with open(REGISTRY_PATH) as f:
data = json.load(f)
return data if isinstance(data, list) else []
except Exception:
return []
def _save_registry(reg: list) -> None:
try:
tmp = REGISTRY_PATH + ".tmp"
with open(tmp, "w") as f:
json.dump(reg, f, indent=2)
os.replace(tmp, REGISTRY_PATH)
except Exception as e:
logger.warning("Registry speichern fehlgeschlagen: %s", e)
def _generate_config() -> int:
"""Schreibt die llama-swap-Config aus Basis-Template + Registry. Gibt die
Anzahl Modelle zurueck. Idempotent, bei jeder Aenderung + beim Start."""
base = {}
try:
with open(BASE_CONFIG_PATH) as f:
base = yaml.safe_load(f) or {}
except Exception as e:
logger.warning("Basis-Template %s nicht lesbar (%s)", BASE_CONFIG_PATH, e)
models = dict(base.get("models") or {})
for e in _load_registry():
key = (e.get("key") or "").strip()
repo = (e.get("hfRepo") or "").strip()
if not key or not repo:
continue
quant = (e.get("quant") or "Q4_K_M").strip()
ctx = int(e.get("ctx") or 8192)
ngl = int(e.get("ngl") or 99)
models[key] = {
"cmd": (f"llama-server --port ${{PORT}} --host 127.0.0.1\n"
f"-hf {repo}:{quant}\n-ngl {ngl} -c {ctx} --jinja"),
"ttl": 3600,
}
out = dict(base)
out["models"] = models
try:
os.makedirs(os.path.dirname(GEN_CONFIG_PATH), exist_ok=True)
tmp = GEN_CONFIG_PATH + ".tmp"
with open(tmp, "w") as f:
yaml.safe_dump(out, f, sort_keys=False, default_flow_style=False)
os.replace(tmp, GEN_CONFIG_PATH)
logger.info("llama-swap-Config generiert: %d Modelle → %s", len(models), GEN_CONFIG_PATH)
except Exception as e:
logger.error("Config schreiben fehlgeschlagen: %s", e)
return len(models)
async def _reload_llama() -> None:
"""Stoesst llama-swap-Reload an. Viele Builds watchen die Config-Datei ohnehin;
zusaetzlich versuchen wir bekannte Reload-Endpunkte (Fehler ignoriert)."""
for path in ("/api/config/reload", "/reload"):
try:
async with httpx.AsyncClient(timeout=10) as c:
r = await c.post(f"{LLAMA_URL}{path}")
if r.status_code < 400:
logger.info("llama-swap reload via %s", path)
return
except Exception:
pass
logger.info("llama-swap reload: kein Endpoint — verlasse mich auf File-Watch")
async def _send(ws, mtype: str, payload: dict) -> None:
try:
@@ -108,11 +196,17 @@ async def _call_llama(messages: list, *, max_tokens: int, temperature: float,
r.raise_for_status()
data = r.json()
msg = (data.get("choices") or [{}])[0].get("message", {}) or {}
usage = data.get("usage") or {}
try:
global _total_tokens
_total_tokens += int(usage.get("total_tokens") or 0)
except Exception:
pass
return {
"ok": True,
"content": msg.get("content") or "",
"tool_calls": msg.get("tool_calls") or None,
"usage": data.get("usage"),
"usage": usage,
}
except Exception as e:
logger.warning("llama.cpp-Call fehlgeschlagen: %s", e)
@@ -133,14 +227,39 @@ async def _emit_llm_status(ws, state: str, model: str, **extra) -> None:
{"service": "llm", "state": state, "model": model, **extra})
async def _fetch_available_models() -> list:
"""Fragt llama-swap ab, welche Modelle diese Box fahren kann (GET /v1/models,
OpenAI-kompatibel → {data:[{id},...]}). Das sind die config.yaml-Keys.
Defensiv: bei Fehler Fallback auf [LLM_MODEL]."""
try:
async with httpx.AsyncClient(timeout=10) as client:
r = await client.get(f"{LLAMA_URL}/v1/models")
r.raise_for_status()
data = r.json()
ids = [m.get("id") for m in (data.get("data") or []) if m.get("id")]
return ids or [LLM_MODEL]
except Exception as e:
logger.warning("llama-swap /v1/models nicht abfragbar (%s) — Fallback [%s]", e, LLM_MODEL)
return [LLM_MODEL]
async def _announce(ws) -> None:
"""Sendet ein frisches worker_hello mit der aktuellen Modell-Liste (nach
Provision/Remove aufrufen, damit Bridge+Diagnostic das neue Modell lernen)."""
models = await _fetch_available_models()
await _send(ws, "worker_hello", {
"instanceId": INSTANCE_ID, "service": WORKER_SERVICE,
"node": NODE_NAME, "gpus": GPU_IDS, "model": LLM_MODEL,
"models": models, # welche Modelle diese Box fahren kann (llama-swap-Keys)
})
logger.info("worker_hello: models=%s", models)
async def _worker_register(ws) -> None:
"""Meldet diesen Worker bei der aria-bridge an (worker_hello) und haelt die
Flotten-Registry per periodischem worker_ping (mit busy-Status) frisch."""
try:
await _send(ws, "worker_hello", {
"instanceId": INSTANCE_ID, "service": WORKER_SERVICE,
"node": NODE_NAME, "gpus": GPU_IDS, "model": LLM_MODEL,
})
await _announce(ws)
while True:
await asyncio.sleep(WORKER_PING_INTERVAL_S)
await _send(ws, "worker_ping",
@@ -213,6 +332,61 @@ async def _do_llm_request(ws, payload: dict) -> None:
})
async def _handle_provision(ws, payload: dict) -> None:
"""Fuegt ein Modell hinzu: Registry+Config schreiben, reload, dann Warmup
(zieht das GGUF via -hf beim ersten Load). Meldet die neue Modell-Liste."""
key = (payload.get("key") or "").strip()
repo = (payload.get("hfRepo") or "").strip()
if not key or not repo:
await _send(ws, "llm_provision_result",
{"instanceId": INSTANCE_ID, "key": key, "ok": False, "error": "key/hfRepo fehlt"})
return
entry = {
"key": key, "hfRepo": repo,
"quant": (payload.get("quant") or "Q4_K_M").strip(),
"ctx": int(payload.get("ctx") or 8192),
"ngl": int(payload.get("ngl") or 99),
}
reg = [e for e in _load_registry() if e.get("key") != key]
reg.append(entry)
_save_registry(reg)
_generate_config()
await _reload_llama()
await _announce(ws) # Bridge/Diagnostic lernen das neue Modell
# Warmup: Mini-Request → llama-swap laedt/zieht das Modell (Fortschritt via
# service_status loading→ready, freshlyDownloaded).
await _emit_llm_status(ws, "loading", key)
t0 = time.time()
res = await _call_llama([{"role": "user", "content": "hi"}],
max_tokens=1, temperature=0.0, stop=None, model=key)
dt = time.time() - t0
if res.get("ok"):
_ready_models.add(key)
await _emit_llm_status(ws, "ready", key, loadSeconds=round(dt, 1),
freshlyDownloaded=dt > 25)
else:
await _emit_llm_status(ws, "error", key, error=(res.get("error") or "")[:160])
await _send(ws, "llm_provision_result",
{"instanceId": INSTANCE_ID, "key": key, "ok": res.get("ok", False),
"error": res.get("error"), "elapsedMs": int(dt * 1000)})
logger.info("provision %s (%s) → ok=%s %.1fs", key, repo, res.get("ok"), dt)
async def _handle_remove(ws, payload: dict) -> None:
"""Entfernt ein Modell aus Registry+Config (GGUF bleibt im Cache)."""
key = (payload.get("key") or "").strip()
if not key:
return
reg = [e for e in _load_registry() if e.get("key") != key]
_save_registry(reg)
_generate_config()
await _reload_llama()
await _announce(ws)
await _send(ws, "llm_provision_result",
{"instanceId": INSTANCE_ID, "key": key, "ok": True, "removed": True})
logger.info("removed model %s", key)
async def _run() -> None:
if not RVS_HOST:
logger.error("RVS_HOST nicht gesetzt — Abbruch")
@@ -221,6 +395,14 @@ async def _run() -> None:
logger.error("RVS_TOKEN nicht gesetzt — Abbruch")
return
# llama-swap-Config aus Basis-Template + Registry erzeugen, BEVOR llama-swap
# sie braucht (llama-swap restart: unless-stopped faengt die Erst-Boot-
# Reihenfolge ab, falls es kurz vor uns startet).
_generate_config()
# Auslastungs-Sampler (GPU + Tokens) laeuft unabhaengig vom RVS.
asyncio.create_task(_stats.run_sampler())
use_tls = RVS_TLS
retry_s = 2
tls_fallback_tried = False
@@ -243,17 +425,26 @@ async def _run() -> None:
msg = json.loads(raw)
except Exception:
continue
if msg.get("type") != "llm_request":
continue
mtype = msg.get("type")
payload = msg.get("payload", {}) or {}
# Redundanz-Routing: gezielt an eine andere Instanz adressiert
# → ignorieren. Ohne targetInstance → wie bisher (jeder nimmt).
tgt = payload.get("targetInstance")
if tgt and tgt != INSTANCE_ID:
continue
# Jede Anfrage nebenlaeufig — llama.cpp serialisiert intern,
# aber wir blockieren so nicht den Empfang weiterer Messages.
asyncio.create_task(_handle_llm_request(ws, payload))
# Auslastungs-Monitor (node_stats_*) abfangen.
if await _stats.handle(ws, mtype, payload, _send):
continue
if mtype not in ("llm_request", "llm_provision_model", "llm_remove_model"):
continue
if mtype == "llm_provision_model":
asyncio.create_task(_handle_provision(ws, payload))
elif mtype == "llm_remove_model":
asyncio.create_task(_handle_remove(ws, payload))
else:
# Jede Anfrage nebenlaeufig — llama.cpp serialisiert intern,
# aber wir blockieren so nicht den Empfang weiterer Messages.
asyncio.create_task(_handle_llm_request(ws, payload))
except Exception as e:
logger.warning("RVS-Verbindung verloren/fehlgeschlagen: %s", e)
try:
+167
View File
@@ -0,0 +1,167 @@
"""
ARIA Node-Stats — Auslastungs-Monitor pro Box (GPU + optional Tokens).
Identische Kopie in jedem Worker-Build-Context (f5tts/whisper/voxtral/llm-adapter),
weil jeder Worker ein eigener Docker-Build-Context ist.
Aufgaben:
- Sampler-Loop (alle SAMPLE_SEC): nvidia-smi-Auslastung + Token-Delta → Ringpuffer
(persistent als JSON auf der Box). Laeuft unabhaengig vom Modal.
- Live-Stream: bei node_stats_stream_start jede Sekunde rohes nvidia-smi + Werte
senden (bis stop / Auto-Timeout).
- History-Request + Reset (Besen).
Reicht `handle(ws, mtype, payload)` in die Worker-Message-Loop ein; gibt True
zurueck, wenn die Nachricht eine node_stats_*-Nachricht war.
"""
import asyncio
import json
import os
import time
SAMPLE_SEC = int(os.getenv("STATS_SAMPLE_SEC", "15"))
HISTORY_CAP = int(os.getenv("STATS_HISTORY_CAP", "500")) # ~2h bei 15s
STREAM_MAX_SEC = int(os.getenv("STATS_STREAM_MAX_SEC", "300"))
async def _run_cmd(*args, timeout=8) -> str:
"""Fuehrt ein Kommando aus, gibt stdout (str) zurueck; '' bei Fehler."""
try:
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
return (out or b"").decode("utf-8", "replace")
except Exception:
return ""
class NodeStats:
def __init__(self, instance_id: str, node_name: str, history_path: str,
token_getter=None, logger=None):
self.instance_id = instance_id
self.node_name = node_name
self.history_path = history_path
self.token_getter = token_getter # callable -> kumulative Token-Zahl (oder None)
self.log = logger
self.samples = self._load()
self._last_tokens = self._tokens_now()
self._stream_task = None
# ── Persistenz ──────────────────────────────────────────
def _load(self) -> list:
try:
with open(self.history_path) as f:
data = json.load(f)
return data if isinstance(data, list) else []
except Exception:
return []
def _persist(self) -> None:
try:
os.makedirs(os.path.dirname(self.history_path) or ".", exist_ok=True)
tmp = self.history_path + ".tmp"
with open(tmp, "w") as f:
json.dump(self.samples[-HISTORY_CAP:], f)
os.replace(tmp, self.history_path)
except Exception:
pass
def _tokens_now(self) -> int:
try:
return int(self.token_getter()) if self.token_getter else 0
except Exception:
return 0
# ── nvidia-smi ──────────────────────────────────────────
async def _query_gpu(self) -> dict:
"""Aggregierte GPU-Werte ueber alle sichtbaren Karten."""
out = await _run_cmd(
"nvidia-smi",
"--query-gpu=utilization.gpu,memory.used,memory.total",
"--format=csv,noheader,nounits")
utils, used, total = [], 0, 0
for line in out.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 3:
continue
try:
utils.append(float(parts[0]))
used += float(parts[1])
total += float(parts[2])
except ValueError:
continue
gpu = round(sum(utils) / len(utils), 1) if utils else 0.0
return {"gpu": gpu, "memUsed": int(used), "memTotal": int(total)}
async def _nvidia_smi_text(self) -> str:
txt = await _run_cmd("nvidia-smi")
return txt or "nvidia-smi nicht verfuegbar"
# ── Sampler (Verlauf) ───────────────────────────────────
async def run_sampler(self) -> None:
while True:
try:
g = await self._query_gpu()
now_tok = self._tokens_now()
dtok = max(0, now_tok - self._last_tokens)
self._last_tokens = now_tok
self.samples.append({
"ts": int(time.time()),
"gpu": g["gpu"], "memUsed": g["memUsed"],
"memTotal": g["memTotal"], "tokens": dtok,
})
if len(self.samples) > HISTORY_CAP:
self.samples = self.samples[-HISTORY_CAP:]
self._persist()
except Exception as e:
if self.log:
self.log.debug("node_stats sample fehlgeschlagen: %s", e)
await asyncio.sleep(SAMPLE_SEC)
# ── Live-Stream ─────────────────────────────────────────
async def _stream(self, ws, send) -> None:
t0 = time.time()
try:
while time.time() - t0 < STREAM_MAX_SEC:
g = await self._query_gpu()
smi = await self._nvidia_smi_text()
await send(ws, "node_stats", {
"instanceId": self.instance_id, "node": self.node_name,
"nvidiaSmi": smi, **g,
})
await asyncio.sleep(1)
except asyncio.CancelledError:
raise
except Exception:
return
# ── Dispatch ────────────────────────────────────────────
async def handle(self, ws, mtype: str, payload: dict, send) -> bool:
if mtype == "node_stats_stream_start":
if self._stream_task and not self._stream_task.done():
self._stream_task.cancel()
self._stream_task = asyncio.create_task(self._stream(ws, send))
return True
if mtype == "node_stats_stream_stop":
if self._stream_task:
self._stream_task.cancel()
self._stream_task = None
return True
if mtype == "node_stats_history_request":
await send(ws, "node_stats_history", {
"instanceId": self.instance_id, "node": self.node_name,
"samples": self.samples[-HISTORY_CAP:],
"tokenCapable": self.token_getter is not None,
"sampleSec": SAMPLE_SEC,
})
return True
if mtype == "node_stats_reset":
self.samples = []
self._persist()
await send(ws, "node_stats_reset_done",
{"instanceId": self.instance_id, "node": self.node_name})
return True
return False
+1
View File
@@ -1,2 +1,3 @@
websockets>=12.0
httpx>=0.27.0
pyyaml>=6.0
+1 -1
View File
@@ -21,6 +21,6 @@ COPY requirements.txt .
RUN printf 'torch==2.6.0\ntorchaudio==2.6.0\n' > /tmp/torch-constraint.txt && \
pip3 install --no-cache-dir -c /tmp/torch-constraint.txt -r requirements.txt
COPY bridge.py speaker_id.py ./
COPY bridge.py speaker_id.py node_stats.py ./
CMD ["python3", "bridge.py"]
+9
View File
@@ -68,6 +68,11 @@ WORKER_SERVICE = "voxtral"
INSTANCE_ID = f"{WORKER_SERVICE}@{NODE_NAME}"
WORKER_PING_INTERVAL_S = int(os.getenv("WORKER_PING_INTERVAL_S", "10"))
# ── Auslastungs-Monitor (Stage E) ──────────────────────────
import node_stats
STATS_PATH = os.getenv("STATS_PATH", f"/root/.cache/huggingface/aria_stats_{WORKER_SERVICE}.json")
_stats = node_stats.NodeStats(INSTANCE_ID, NODE_NAME, STATS_PATH, logger=logger)
STREAM_TRANSCRIBE_INTERVAL_MS = int(os.getenv("STREAM_TRANSCRIBE_INTERVAL_MS", "1000"))
STREAM_DEFAULT_ENDPOINT_MS = 2400
STREAM_DEFAULT_HARD_CAP_MS = 300000
@@ -757,6 +762,9 @@ async def run_loop(sessions: SessionManager) -> None:
tgt = payload.get("targetInstance")
if tgt and tgt != INSTANCE_ID:
continue
# Auslastungs-Monitor (node_stats_*) abfangen.
if await _stats.handle(ws, mtype, payload, _send):
continue
if mtype == "stt_stream_start":
sessions.start_session(payload)
elif mtype == "stt_audio_chunk":
@@ -856,6 +864,7 @@ async def main() -> None:
await loop.run_in_executor(None, runner.load) # Modell laden (blockierend)
sessions = SessionManager(runner)
logger.info("Voxtral-Bridge startet — Modell=%s", VOXTRAL_MODEL)
asyncio.create_task(_stats.run_sampler()) # Auslastungs-Sampler (Stage E)
await asyncio.gather(run_loop(sessions), sessions.run_endpointer())
+167
View File
@@ -0,0 +1,167 @@
"""
ARIA Node-Stats — Auslastungs-Monitor pro Box (GPU + optional Tokens).
Identische Kopie in jedem Worker-Build-Context (f5tts/whisper/voxtral/llm-adapter),
weil jeder Worker ein eigener Docker-Build-Context ist.
Aufgaben:
- Sampler-Loop (alle SAMPLE_SEC): nvidia-smi-Auslastung + Token-Delta → Ringpuffer
(persistent als JSON auf der Box). Laeuft unabhaengig vom Modal.
- Live-Stream: bei node_stats_stream_start jede Sekunde rohes nvidia-smi + Werte
senden (bis stop / Auto-Timeout).
- History-Request + Reset (Besen).
Reicht `handle(ws, mtype, payload)` in die Worker-Message-Loop ein; gibt True
zurueck, wenn die Nachricht eine node_stats_*-Nachricht war.
"""
import asyncio
import json
import os
import time
SAMPLE_SEC = int(os.getenv("STATS_SAMPLE_SEC", "15"))
HISTORY_CAP = int(os.getenv("STATS_HISTORY_CAP", "500")) # ~2h bei 15s
STREAM_MAX_SEC = int(os.getenv("STATS_STREAM_MAX_SEC", "300"))
async def _run_cmd(*args, timeout=8) -> str:
"""Fuehrt ein Kommando aus, gibt stdout (str) zurueck; '' bei Fehler."""
try:
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
return (out or b"").decode("utf-8", "replace")
except Exception:
return ""
class NodeStats:
def __init__(self, instance_id: str, node_name: str, history_path: str,
token_getter=None, logger=None):
self.instance_id = instance_id
self.node_name = node_name
self.history_path = history_path
self.token_getter = token_getter # callable -> kumulative Token-Zahl (oder None)
self.log = logger
self.samples = self._load()
self._last_tokens = self._tokens_now()
self._stream_task = None
# ── Persistenz ──────────────────────────────────────────
def _load(self) -> list:
try:
with open(self.history_path) as f:
data = json.load(f)
return data if isinstance(data, list) else []
except Exception:
return []
def _persist(self) -> None:
try:
os.makedirs(os.path.dirname(self.history_path) or ".", exist_ok=True)
tmp = self.history_path + ".tmp"
with open(tmp, "w") as f:
json.dump(self.samples[-HISTORY_CAP:], f)
os.replace(tmp, self.history_path)
except Exception:
pass
def _tokens_now(self) -> int:
try:
return int(self.token_getter()) if self.token_getter else 0
except Exception:
return 0
# ── nvidia-smi ──────────────────────────────────────────
async def _query_gpu(self) -> dict:
"""Aggregierte GPU-Werte ueber alle sichtbaren Karten."""
out = await _run_cmd(
"nvidia-smi",
"--query-gpu=utilization.gpu,memory.used,memory.total",
"--format=csv,noheader,nounits")
utils, used, total = [], 0, 0
for line in out.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 3:
continue
try:
utils.append(float(parts[0]))
used += float(parts[1])
total += float(parts[2])
except ValueError:
continue
gpu = round(sum(utils) / len(utils), 1) if utils else 0.0
return {"gpu": gpu, "memUsed": int(used), "memTotal": int(total)}
async def _nvidia_smi_text(self) -> str:
txt = await _run_cmd("nvidia-smi")
return txt or "nvidia-smi nicht verfuegbar"
# ── Sampler (Verlauf) ───────────────────────────────────
async def run_sampler(self) -> None:
while True:
try:
g = await self._query_gpu()
now_tok = self._tokens_now()
dtok = max(0, now_tok - self._last_tokens)
self._last_tokens = now_tok
self.samples.append({
"ts": int(time.time()),
"gpu": g["gpu"], "memUsed": g["memUsed"],
"memTotal": g["memTotal"], "tokens": dtok,
})
if len(self.samples) > HISTORY_CAP:
self.samples = self.samples[-HISTORY_CAP:]
self._persist()
except Exception as e:
if self.log:
self.log.debug("node_stats sample fehlgeschlagen: %s", e)
await asyncio.sleep(SAMPLE_SEC)
# ── Live-Stream ─────────────────────────────────────────
async def _stream(self, ws, send) -> None:
t0 = time.time()
try:
while time.time() - t0 < STREAM_MAX_SEC:
g = await self._query_gpu()
smi = await self._nvidia_smi_text()
await send(ws, "node_stats", {
"instanceId": self.instance_id, "node": self.node_name,
"nvidiaSmi": smi, **g,
})
await asyncio.sleep(1)
except asyncio.CancelledError:
raise
except Exception:
return
# ── Dispatch ────────────────────────────────────────────
async def handle(self, ws, mtype: str, payload: dict, send) -> bool:
if mtype == "node_stats_stream_start":
if self._stream_task and not self._stream_task.done():
self._stream_task.cancel()
self._stream_task = asyncio.create_task(self._stream(ws, send))
return True
if mtype == "node_stats_stream_stop":
if self._stream_task:
self._stream_task.cancel()
self._stream_task = None
return True
if mtype == "node_stats_history_request":
await send(ws, "node_stats_history", {
"instanceId": self.instance_id, "node": self.node_name,
"samples": self.samples[-HISTORY_CAP:],
"tokenCapable": self.token_getter is not None,
"sampleSec": SAMPLE_SEC,
})
return True
if mtype == "node_stats_reset":
self.samples = []
self._persist()
await send(ws, "node_stats_reset_done",
{"instanceId": self.instance_id, "node": self.node_name})
return True
return False
+1 -1
View File
@@ -17,6 +17,6 @@ RUN pip3 install --no-cache-dir torch==2.3.1 torchaudio==2.3.1 \
COPY requirements.txt .
RUN pip3 install --no-cache-dir -r requirements.txt
COPY bridge.py speaker_id.py ./
COPY bridge.py speaker_id.py node_stats.py ./
CMD ["python3", "bridge.py"]
+12 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""
ARIA Whisper Bridge — laeuft auf der Gamebox (RTX 3060).
ARIA Whisper Bridge — laeuft auf der AI-Box (RTX 3060).
Zwei Modi:
@@ -67,6 +67,11 @@ WORKER_SERVICE = "whisper"
INSTANCE_ID = f"{WORKER_SERVICE}@{NODE_NAME}"
WORKER_PING_INTERVAL_S = int(os.getenv("WORKER_PING_INTERVAL_S", "10"))
# ── Auslastungs-Monitor (Stage E) ──────────────────────────
import node_stats
STATS_PATH = os.getenv("STATS_PATH", f"/root/.cache/huggingface/aria_stats_{WORKER_SERVICE}.json")
_stats = node_stats.NodeStats(INSTANCE_ID, NODE_NAME, STATS_PATH, logger=logger)
ALLOWED_MODELS = {"tiny", "base", "small", "medium", "large-v3"}
# Streaming-Parameter (Defaults — koennen pro Session vom App-Payload ueberschrieben werden)
@@ -292,7 +297,7 @@ async def _send(ws, mtype: str, payload: dict) -> None:
# ──────────────────────────────────────────────────────────────
# DEBUG-LOG ueber RVS → /shared/logs/app.log
#
# Stefan's Gamebox ist Windows, kein SSH → wir brauchen Whisper-Bridge-
# Stefan's AI-Box ist Windows, kein SSH → wir brauchen Whisper-Bridge-
# Logs ueber den gleichen Pfad wie die App: app_log-Messages via RVS,
# aria-bridge schreibt sie in /shared/logs/app.log. Diagnostic / App-
# Logs-Tab zeigen sie dann mit platform="whisper".
@@ -881,7 +886,7 @@ async def run_loop(runner: WhisperRunner, sessions: SessionManager) -> None:
logger.info("Initial: sende config_request an aria-bridge")
await _send(ws, "config_request", {"service": "whisper"})
# Startup-Marker — App-Logs zeigen damit ob Streaming-Code
# ueberhaupt aktiv ist (Stefan baut auf Gamebox via PS,
# ueberhaupt aktiv ist (Stefan baut auf AI-Box via PS,
# Build/Restart kann unbeabsichtigt alte Version weiterfahren).
await _debug_log(ws, "boot",
"whisper-bridge online — streaming-mode ENABLED, debug-log ON")
@@ -904,6 +909,9 @@ async def run_loop(runner: WhisperRunner, sessions: SessionManager) -> None:
tgt = payload.get("targetInstance")
if tgt and tgt != INSTANCE_ID:
continue
# Auslastungs-Monitor (node_stats_*) abfangen.
if await _stats.handle(ws, mtype, payload, _send):
continue
if mtype == "stt_request":
req_id = payload.get("requestId", "?")
@@ -1096,6 +1104,7 @@ async def main() -> None:
# Endpointer-Loop nebenbei laufen lassen — er pruefst _ws is None und
# schlaeft solange das nicht gesetzt ist.
asyncio.create_task(sessions.run_endpointer())
asyncio.create_task(_stats.run_sampler()) # Auslastungs-Sampler (Stage E)
await run_loop(runner, sessions)
+167
View File
@@ -0,0 +1,167 @@
"""
ARIA Node-Stats — Auslastungs-Monitor pro Box (GPU + optional Tokens).
Identische Kopie in jedem Worker-Build-Context (f5tts/whisper/voxtral/llm-adapter),
weil jeder Worker ein eigener Docker-Build-Context ist.
Aufgaben:
- Sampler-Loop (alle SAMPLE_SEC): nvidia-smi-Auslastung + Token-Delta → Ringpuffer
(persistent als JSON auf der Box). Laeuft unabhaengig vom Modal.
- Live-Stream: bei node_stats_stream_start jede Sekunde rohes nvidia-smi + Werte
senden (bis stop / Auto-Timeout).
- History-Request + Reset (Besen).
Reicht `handle(ws, mtype, payload)` in die Worker-Message-Loop ein; gibt True
zurueck, wenn die Nachricht eine node_stats_*-Nachricht war.
"""
import asyncio
import json
import os
import time
SAMPLE_SEC = int(os.getenv("STATS_SAMPLE_SEC", "15"))
HISTORY_CAP = int(os.getenv("STATS_HISTORY_CAP", "500")) # ~2h bei 15s
STREAM_MAX_SEC = int(os.getenv("STATS_STREAM_MAX_SEC", "300"))
async def _run_cmd(*args, timeout=8) -> str:
"""Fuehrt ein Kommando aus, gibt stdout (str) zurueck; '' bei Fehler."""
try:
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
return (out or b"").decode("utf-8", "replace")
except Exception:
return ""
class NodeStats:
def __init__(self, instance_id: str, node_name: str, history_path: str,
token_getter=None, logger=None):
self.instance_id = instance_id
self.node_name = node_name
self.history_path = history_path
self.token_getter = token_getter # callable -> kumulative Token-Zahl (oder None)
self.log = logger
self.samples = self._load()
self._last_tokens = self._tokens_now()
self._stream_task = None
# ── Persistenz ──────────────────────────────────────────
def _load(self) -> list:
try:
with open(self.history_path) as f:
data = json.load(f)
return data if isinstance(data, list) else []
except Exception:
return []
def _persist(self) -> None:
try:
os.makedirs(os.path.dirname(self.history_path) or ".", exist_ok=True)
tmp = self.history_path + ".tmp"
with open(tmp, "w") as f:
json.dump(self.samples[-HISTORY_CAP:], f)
os.replace(tmp, self.history_path)
except Exception:
pass
def _tokens_now(self) -> int:
try:
return int(self.token_getter()) if self.token_getter else 0
except Exception:
return 0
# ── nvidia-smi ──────────────────────────────────────────
async def _query_gpu(self) -> dict:
"""Aggregierte GPU-Werte ueber alle sichtbaren Karten."""
out = await _run_cmd(
"nvidia-smi",
"--query-gpu=utilization.gpu,memory.used,memory.total",
"--format=csv,noheader,nounits")
utils, used, total = [], 0, 0
for line in out.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 3:
continue
try:
utils.append(float(parts[0]))
used += float(parts[1])
total += float(parts[2])
except ValueError:
continue
gpu = round(sum(utils) / len(utils), 1) if utils else 0.0
return {"gpu": gpu, "memUsed": int(used), "memTotal": int(total)}
async def _nvidia_smi_text(self) -> str:
txt = await _run_cmd("nvidia-smi")
return txt or "nvidia-smi nicht verfuegbar"
# ── Sampler (Verlauf) ───────────────────────────────────
async def run_sampler(self) -> None:
while True:
try:
g = await self._query_gpu()
now_tok = self._tokens_now()
dtok = max(0, now_tok - self._last_tokens)
self._last_tokens = now_tok
self.samples.append({
"ts": int(time.time()),
"gpu": g["gpu"], "memUsed": g["memUsed"],
"memTotal": g["memTotal"], "tokens": dtok,
})
if len(self.samples) > HISTORY_CAP:
self.samples = self.samples[-HISTORY_CAP:]
self._persist()
except Exception as e:
if self.log:
self.log.debug("node_stats sample fehlgeschlagen: %s", e)
await asyncio.sleep(SAMPLE_SEC)
# ── Live-Stream ─────────────────────────────────────────
async def _stream(self, ws, send) -> None:
t0 = time.time()
try:
while time.time() - t0 < STREAM_MAX_SEC:
g = await self._query_gpu()
smi = await self._nvidia_smi_text()
await send(ws, "node_stats", {
"instanceId": self.instance_id, "node": self.node_name,
"nvidiaSmi": smi, **g,
})
await asyncio.sleep(1)
except asyncio.CancelledError:
raise
except Exception:
return
# ── Dispatch ────────────────────────────────────────────
async def handle(self, ws, mtype: str, payload: dict, send) -> bool:
if mtype == "node_stats_stream_start":
if self._stream_task and not self._stream_task.done():
self._stream_task.cancel()
self._stream_task = asyncio.create_task(self._stream(ws, send))
return True
if mtype == "node_stats_stream_stop":
if self._stream_task:
self._stream_task.cancel()
self._stream_task = None
return True
if mtype == "node_stats_history_request":
await send(ws, "node_stats_history", {
"instanceId": self.instance_id, "node": self.node_name,
"samples": self.samples[-HISTORY_CAP:],
"tokenCapable": self.token_getter is not None,
"sampleSec": SAMPLE_SEC,
})
return True
if mtype == "node_stats_reset":
self.samples = []
self._persist()
await send(ws, "node_stats_reset_done",
{"instanceId": self.instance_id, "node": self.node_name})
return True
return False