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

View File

@@ -21,7 +21,13 @@ def main() -> int:
ap.add_argument("--melo-device", default="cuda")
ap.add_argument("--melo-speed", type=float, default=1.5)
ap.add_argument("--melo-language", default="KR")
ap.add_argument("--history", default=None, help="conversation history SQLite file; no history without it")
ap.add_argument("--brain", action="store_true",
help="answer reply requests with the jarvis reply engine (needs --history)")
args = ap.parse_args()
if args.brain and not args.history:
print("--brain needs --history", file=sys.stderr)
return 2
token = os.environ.get("JARVIS_VOICE_TOKEN", "")
if not token:
@@ -44,10 +50,19 @@ def main() -> int:
from .tts_melo import MeloEngine
tts = MeloEngine(args.melo_python, args.melo_device, args.melo_speed, args.melo_language)
history = brain = None
if args.history:
from jarvis.memory.history import HistoryStore
history = HistoryStore(args.history)
if args.brain:
from .brain import JarvisBrain
brain = JarvisBrain()
async def run() -> None:
worker = VoiceWorker(token, transcriber, vad.stream, tts)
worker = VoiceWorker(token, transcriber, vad.stream, tts, history=history, brain=brain)
server = await worker.serve(args.host, args.port)
debug_log(f"voice worker listening on {args.host}:{args.port} tts={'on' if tts else 'off'}",
debug_log(f"voice worker listening on {args.host}:{args.port} tts={'on' if tts else 'off'} "
f"history={'on' if history else 'off'} brain={'on' if brain else 'off'}",
"voice_worker")
print(f"READY {args.host}:{args.port}", flush=True)
await server.serve_forever()
@@ -59,6 +74,8 @@ def main() -> int:
finally:
if tts:
tts.close()
if history:
history.close()
return 0

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

View File

@@ -10,3 +10,5 @@ numpy
python-dotenv==1.0.1
# MeloTTS runs in its own Python 3.11 venv (see the "melo" entry in scripts/m0/m0lib/envs.py) and is
# reached through melo_child.py; pass that venv's python with --melo-python.
# --history needs nothing more. --brain runs the jarvis reply engine and needs its dependencies too
# (the brain part of the repository's requirements.txt: requests, mcp, beautifulsoup4, ...).

View File

@@ -16,6 +16,7 @@ import numpy as np
from jarvis.debug import debug_log
from .audio import InputConverter, loudness_equalise
from .brain import Brain, MemorySettings
from .protocol import KIND_AUDIO, ProtocolError, decode_audio_frame, encode_tts_frame
from .scheduler import DecodeOptions, SttResult, SttScheduler, Transcriber
from .segmenter import SR, Final, Partial, Segmenter, SpeechStart, VadStream
@@ -38,7 +39,8 @@ def is_loopback(host: str) -> bool:
class VoiceWorker:
def __init__(self, token: str, transcriber: Transcriber | None, vad_factory: Callable[[], VadStream],
tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05):
tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05,
history=None, brain: Brain | None = None):
if not token:
raise ValueError("a connection token is required")
self.token = token
@@ -47,6 +49,9 @@ class VoiceWorker:
self.tts_engine = tts_engine
self.hello_timeout_s = hello_timeout_s
self.tick_s = tick_s
self.history = history # jarvis.memory.history.HistoryStore or None
self.brain = brain
self.brain_lock = asyncio.Lock() # one reply at a time
self.scheduler: SttScheduler | None = None
self.tts: TtsService | None = None
self._ids = itertools.count(1)
@@ -129,6 +134,14 @@ class Session:
if not isinstance(stt, dict):
raise ValueError("stt must be an object")
self.settings.update(stt)
self.memory = MemorySettings()
memory = hello.get("memory")
if memory is not None:
if not isinstance(memory, dict):
raise ValueError("memory must be an object")
self.memory.update(memory)
self.voice_channel: str | None = None
self.names: dict[str, str] = {}
self.speakers: dict[str, _Speaker] = {}
self.tts_requests: dict[str, TtsRequest] = {}
self.out: asyncio.Queue = asyncio.Queue()
@@ -164,6 +177,7 @@ class Session:
debug_log(f"session {self.sid} receive ended: {type(e).__name__}", "voice_worker")
finally:
self.closed = True
self._leave_voice()
ticker.cancel()
writer.cancel()
if w.scheduler:
@@ -231,6 +245,9 @@ class Session:
return cb
def _send_final(self, speaker: str, ev: Final, res: SttResult) -> None:
store = self.worker.history
if store is not None and self.voice_channel and res.text.strip():
store.add_voice(self.voice_channel, speaker, self.names.get(speaker, speaker), res.text, time.time())
self.send({"type": "final", "speaker": speaker, "utt": ev.utt, "text": res.text,
"end_reason": ev.reason, "audio_ms": len(ev.audio) * 1000 // SR,
"wait_ms": int((time.monotonic() - ev.decided_at) * 1000), "stt_ms": res.stt_ms})
@@ -247,7 +264,12 @@ class Session:
return
kind = msg.get("type")
handler = {"speaking_end": self._on_speaking_end, "speaker_leave": self._on_speaker_leave,
"config": self._on_config, "tts": self._on_tts, "tts_cancel": self._on_tts_cancel}.get(kind)
"config": self._on_config, "tts": self._on_tts, "tts_cancel": self._on_tts_cancel,
"voice_join": self._on_voice_join, "voice_leave": lambda m: self._leave_voice(),
"member_join": self._on_member_join, "member_leave": self._on_member_leave,
"chat_message": self._on_chat_message, "chat_edit": self._on_chat_edit,
"chat_delete": self._on_chat_delete, "reply": self._on_reply,
"memory_config": self._on_memory_config}.get(kind)
if handler is None:
self.error("bad_message", f"unknown type: {kind!r}")
return
@@ -304,6 +326,125 @@ class Session:
if req is not None and self.worker.tts:
self.worker.tts.cancel(req)
# --- history and brain ----------------------------------------------------------------------
def _strings(self, msg: dict, *keys: str) -> tuple | None:
values = tuple(msg.get(k) for k in keys)
if not all(isinstance(v, str) and v for v in values):
self.error("bad_message", f"{msg.get('type')} needs non-empty strings: {', '.join(keys)}",
**({"id": msg["id"]} if isinstance(msg.get("id"), str) else {}))
return None
return values
def _leave_voice(self) -> None:
if self.voice_channel and self.worker.history is not None:
self.worker.history.presence_close_channel(self.voice_channel, time.time())
if self.voice_channel:
debug_log(f"session {self.sid} left voice channel {self.voice_channel}", "voice_worker")
self.voice_channel = None
def _on_voice_join(self, msg: dict) -> None:
got = self._strings(msg, "channel")
if got is None:
return
self._leave_voice()
self.voice_channel = got[0]
debug_log(f"session {self.sid} in voice channel {self.voice_channel}", "voice_worker")
def _on_member_join(self, msg: dict) -> None:
got = self._strings(msg, "user", "name")
if got is None:
return
user, name = got
self.names[user] = name
if self.voice_channel and self.worker.history is not None:
self.worker.history.presence_join(user, self.voice_channel, time.time())
def _on_member_leave(self, msg: dict) -> None:
got = self._strings(msg, "user")
if got is not None and self.voice_channel and self.worker.history is not None:
self.worker.history.presence_leave(got[0], self.voice_channel, time.time())
def _on_chat_message(self, msg: dict) -> None:
got = self._strings(msg, "channel", "message_id", "author", "name")
ts, to, text = msg.get("ts"), msg.get("to"), msg.get("text")
if got is None:
return
if not isinstance(text, str) or isinstance(ts, bool) or not isinstance(ts, (int, float)) \
or (to is not None and not isinstance(to, str)):
self.error("bad_message", "chat_message needs text, a numeric ts and an optional string to")
return
if self.worker.history is not None:
channel, message_id, author, name = got
self.worker.history.add_chat(channel, message_id, author, name, text, float(ts), to_id=to)
def _on_chat_edit(self, msg: dict) -> None:
got = self._strings(msg, "channel", "message_id")
if got is None:
return
if not isinstance(msg.get("text"), str):
self.error("bad_message", "chat_edit needs text")
return
if self.worker.history is not None:
self.worker.history.edit_chat(got[0], got[1], msg["text"])
def _on_chat_delete(self, msg: dict) -> None:
got = self._strings(msg, "channel", "message_id")
if got is not None and self.worker.history is not None:
self.worker.history.delete_chat(*got)
def _on_memory_config(self, msg: dict) -> None:
changes = {k: v for k, v in msg.items() if k != "type"}
try:
self.memory.update(changes)
except ValueError as e:
self.error("bad_message", str(e))
return
debug_log(f"session {self.sid} memory settings changed: {sorted(changes)}", "voice_worker")
def _on_reply(self, msg: dict) -> None:
got = self._strings(msg, "id", "user", "text")
if got is None:
return
rid, user, text = got
via, speak = msg.get("via"), msg.get("speak", False)
if via not in ("voice", "chat") or not isinstance(speak, bool) or len(rid.encode()) > 255:
self.error("bad_message", "reply needs via voice|chat, a boolean speak and an id under 256 bytes",
id=rid)
return
if self.worker.brain is None:
self.error("brain_unavailable", "the worker was started without --brain", id=rid)
return
asyncio.get_running_loop().create_task(self._reply(rid, user, text, via, speak))
async def _reply(self, rid: str, user: str, text: str, via: str, speak: bool) -> None:
w = self.worker
channel = self.voice_channel
async with w.brain_lock:
if self.closed:
return
now = time.time()
if w.history is not None:
m = self.memory
history = await asyncio.to_thread(
w.history.context, user, text, now, m.scope(now), minutes=m.recent_minutes,
max_records=m.recent_records, limit=m.matches, budget_tokens=m.budget_tokens)
else:
from jarvis.memory.history import HistoryContext
history = HistoryContext()
try:
answer = await asyncio.to_thread(w.brain.reply, user, text, history)
except Exception as e: # the brain must never take the session down
debug_log(f"brain reply {rid} failed: {type(e).__name__}", "voice_worker")
answer = None
answer = (answer or "").strip()
self.send({"type": "reply_text", "id": rid, "text": answer, "failed": not answer})
if not answer:
return
if via == "voice" and channel and w.history is not None:
w.history.add_reply(channel, user, answer, time.time())
if speak:
self._on_tts({"type": "tts", "id": rid, "text": answer, "more": False})
def _tts_chunk_cb(self, rid: str):
def cb(seq: int, pcm: np.ndarray) -> None:
pcm = np.asarray(pcm, dtype="<i2")

View File

@@ -24,6 +24,7 @@ WebSocket. Design background lives in `docs/v2/voice-and-llm.md` and `docs/v2/ar
JARVIS_VOICE_TOKEN=<secret> python -m voice_worker --host 127.0.0.1 --port 8771 \
[--stt-model large-v3-turbo] [--stt-device cuda] [--stt-compute int8_float16] \
[--melo-python <path to the MeloTTS venv python>] [--melo-device cuda] [--melo-speed 1.5]
[--history <history.sqlite>] [--brain]
```
Run from `src/` (or with `src/` on `PYTHONPATH`) in a venv built from `voice_worker/requirements.txt`. MeloTTS needs its own Python 3.11 venv
@@ -176,10 +177,57 @@ is ready. Requests are served first come, first served by one TTS engine. `tts_c
request's unsent sentences, and `tts_done` follows with `cancelled: true`. A sentence that fails to
synthesise is reported with `error` (`code: "tts_failed"`) and the request ends with `failed: true`.
### History and brain (M3)
The worker also hosts the brain (the existing `jarvis` reply engine) and the conversation history
store (`src/jarvis/memory/history.spec.md`). Start it with `--history <file>` to keep history and
`--brain` to answer (`--brain` needs `--history`; it loads the jarvis settings, whose
`ollama_base_url` points at Strata's `/v1`). Without them the messages below are accepted and
ignored, except `reply`, which answers `error` `brain_unavailable`.
The app tells the worker where Jarvis is and who is there. Speaker IDs are Discord user IDs, the
same strings as in audio frames. Times are taken by the worker on arrival, except chat messages,
which carry Discord's own time.
```
-> {"type": "voice_join", "channel": "<voice channel id>"} // Jarvis joined (or moved to) this channel
-> {"type": "voice_leave"} // Jarvis left the voice channel
-> {"type": "member_join", "user": "<id>", "name": "<display name>"} // also for everyone already there
-> {"type": "member_leave", "user": "<id>"}
-> {"type": "chat_message", "channel": "...", "message_id": "...", "author": "<id>", "name": "...",
"text": "...", "ts": 1762830000.5, "to": "<id>"} // to: only on Jarvis's own answer to someone
-> {"type": "chat_edit", "channel": "...", "message_id": "...", "text": "..."}
-> {"type": "chat_delete", "channel": "...", "message_id": "..."}
-> {"type": "reply", "id": "r1", "user": "<id>", "text": "...", "via": "voice", "speak": true}
<- {"type": "reply_text", "id": "r1", "text": "...", "failed": false}
```
- `voice_join` closes the presence of everyone in the previous channel and starts a new one;
`voice_leave` and the end of the session close it, because nothing said after that is heard.
`member_join` opens the user's presence in the current channel and remembers their name;
`member_leave` closes it. Members outside a voice channel are ignored.
- Every non-empty `final` is stored as a `voice` record of the current channel under the speaker's
name (the user ID until `member_join` names them). A final outside a voice channel is not stored.
- Chat messages are stored only as given; the app sends only registered channels.
- `reply` asks the brain to answer `user`'s `text`. The worker builds the history context for that
user (their scope only) and runs the reply engine on a worker thread, one reply at a time.
`reply_text` carries the answer (`failed: true` with empty text when the brain gave none). A voice
answer (`via: "voice"`) is stored as a `reply` record to the user in the current channel; a chat
answer is stored when the app reports the sent message as `chat_message` with `to`. With
`speak: true` the answer is also spoken through the TTS path under the same id (audio frames and
`tts_done`), and `tts_cancel` with that id stops it. Each user keeps their own short-term dialogue
memory (tool carry-over) across replies.
- Memory settings, optional in `hello` as `"memory": {...}` and changeable with
`{"type": "memory_config", ...}`: `chat` (true), `others` (true), `off` (false), `since_days`
(null: whole history), `recent_minutes` (30), `recent_records` (20), `matches` (5),
`budget_tokens` (4000).
- Logs carry IDs, counts and timings only, never record, question or answer text.
### Errors
`{"type": "error", "code": "...", "message": "...", "id": "..."}`. Codes: `bad_message` (unknown type,
bad JSON, bad field), `bad_frame` (malformed binary frame), `tts_unavailable`, `tts_failed`. Errors
bad JSON, bad field), `bad_frame` (malformed binary frame), `tts_unavailable`, `tts_failed`,
`brain_unavailable`. Errors
never close the connection after the handshake.
## Debug logging