feat(voice_worker): record history from the app and answer reply requests with the brain

Worker (voice_worker.spec.md "History and brain"):
- --history <file> keeps the conversation history store; --brain hosts the
  jarvis reply engine (JarvisBrain, settings point ollama_base_url at /v1).
- voice_join / voice_leave / member_join / member_leave keep presence; the
  session end closes it. Non-empty finals are stored under the speaker's name
  in the current voice channel.
- chat_message / chat_edit / chat_delete keep registered chat channels.
- reply builds the asker's scoped history context, runs the brain on a thread
  (one at a time), answers reply_text, stores a voice answer, and with
  speak=true says it under the same id. memory settings in hello and
  memory_config. brain_unavailable without --brain.

App (discord_core.spec.md "History reporting"):
- WorkerClient sends the new messages; the core reports the voice channel
  and its heard members after a join, a move and every worker reconnect,
  member joins and leaves, voice_leave when a session ends, and every message
  of a readable registered channel (its own too, with `to` on replies), edits
  and deletes.
- live_discord runs the worker with --history and checks the store at the
  end: 8 finals under the speaker's name, the edited chat message only,
  Jarvis's own messages, 5 presence intervals, none left open (passed, 107.8 s).

Eval: history recall gains a chat-record case and fails a reply that reads a
record stamp out (field run with qwen2.5:7b did once in four).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 13:16:24 +09:00
parent 7a288129de
commit 864b2e7fdb
13 changed files with 775 additions and 18 deletions

99
src/voice_worker/brain.py Normal file
View File

@@ -0,0 +1,99 @@
"""The brain the voice worker hosts: memory settings and the jarvis reply engine behind a small
interface, so the worker logic is tested with a fake (voice_worker.spec.md, "History and brain")."""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass
from typing import Optional, Protocol
from jarvis.debug import debug_log
from jarvis.memory.history import HistoryContext, Scope
class Brain(Protocol):
def reply(self, user: str, text: str, history: HistoryContext) -> Optional[str]:
"""Blocking; called on a worker thread, one call at a time."""
@dataclass
class MemorySettings:
chat: bool = True
others: bool = True
off: bool = False
since_days: Optional[float] = None
recent_minutes: float = 30
recent_records: int = 20
matches: int = 5
budget_tokens: float = 4000
_BOOLS = ("chat", "others", "off")
_NUMBERS = {"recent_minutes": (0, 24 * 60), "recent_records": (0, 200), "matches": (0, 20),
"budget_tokens": (0, 100_000)}
def update(self, changes: dict) -> None:
"""Apply ``changes`` atomically; raises ValueError naming the first bad field."""
new = dict(self.__dict__)
for key, value in changes.items():
if key in self._BOOLS:
if not isinstance(value, bool):
raise ValueError(f"{key} must be true or false")
elif key == "since_days":
if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float))
or value <= 0):
raise ValueError("since_days must be a positive number or null")
elif key in self._NUMBERS:
lo, hi = self._NUMBERS[key]
if isinstance(value, bool) or not isinstance(value, (int, float)) or not lo <= value <= hi:
raise ValueError(f"{key} must be a number from {lo} to {hi}")
if key in ("recent_records", "matches"):
value = int(value)
else:
raise ValueError(f"unknown memory setting: {key}")
new[key] = value
self.__dict__.update(new)
def scope(self, now: float) -> Scope:
since = now - self.since_days * 86400 if self.since_days else None
return Scope(chat=self.chat, others=self.others, since=since, off=self.off)
class JarvisBrain:
"""The existing jarvis reply engine with the user's history context.
Uses the jarvis settings (``ollama_base_url`` is Strata's ``/v1`` in v2) and its database for
the long-term memory it already keeps. Each user has their own short-term dialogue memory so
tool carry-over follows the person who asked.
"""
def __init__(self, language: Optional[str] = None):
from jarvis.config import load_settings
from jarvis.memory.db import Database
self.cfg = load_settings()
self.db = Database(self.cfg.db_path, self.cfg.sqlite_vss_path)
self.language = language
self._memories: dict = {}
self._lock = threading.Lock()
debug_log(f"brain ready: llm={self.cfg.ollama_base_url} model={self.cfg.ollama_chat_model}", "voice_worker")
def _memory(self, user: str):
from jarvis.memory.conversation import DialogueMemory
with self._lock:
mem = self._memories.get(user)
if mem is None:
mem = DialogueMemory(inactivity_timeout=self.cfg.dialogue_memory_timeout, max_interactions=20)
self._memories[user] = mem
return mem
def reply(self, user: str, text: str, history: HistoryContext) -> Optional[str]:
from jarvis.reply.engine import run_reply_engine
t0 = time.perf_counter()
answer = run_reply_engine(self.db, self.cfg, None, text, self._memory(user),
language=self.language, history=history)
debug_log(f"brain reply user={user} ok={bool(answer)} ms={(time.perf_counter() - t0) * 1000:.0f}",
"voice_worker")
return answer