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

@@ -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")