feat(chat): chatChannels tool for the registered Discord chat channels

- Tool (chat_channels.spec.md): list, read, search, send, edit, react,
  delete, pin, unpin. Offered only when the v2 brain gives the turn a chat
  backend, and then on every turn. Channel by ID, name, part of a name or a
  name inside the text; a message ID finds its channel; planner forms of the
  action ("send_message") work. Read and search results are fenced as
  untrusted data. delete only reports until called again with confirm=true
  in a later turn of the same person.
- Worker: chat_channels from the app, ChatBridge reads/searches the history
  store and sends chat_action, waiting for chat_action_result (15 s timeout,
  failed on session close); per-person reply turns and pending deletes.
- App: channel switches edit/react (on) and delete/pin (off); chat_channels
  sent on worker ready and after login; chat_action runs send, edit (own
  messages only), react, delete, pin, unpin and answers with ids or the error.
- Engine: chatChannels left out of the catalogue without a backend; the
  "router returned everything" check now tolerates that.
- live_discord: edit own, refuse editing the speaker's, react, pin (Discord
  refuses in a voice channel's chat, reported as an error), delete, refuse an
  unregistered channel; passed in 109.4 s.
- Eval (qwen2.5:7b, 3 runs): 10 of 12; never obeyed the "delete everything"
  message and never deleted in the same turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 14:01:33 +09:00
parent 3dbf1e8c56
commit fe4e296361
25 changed files with 1058 additions and 26 deletions

View File

@@ -40,7 +40,7 @@ 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,
history=None, brain: Brain | None = None):
history=None, brain: Brain | None = None, chat_timeout_s: float = 15.0):
if not token:
raise ValueError("a connection token is required")
self.token = token
@@ -52,6 +52,11 @@ class VoiceWorker:
self.history = history # jarvis.memory.history.HistoryStore or None
self.brain = brain
self.brain_lock = asyncio.Lock() # one reply at a time
self.chat_timeout_s = chat_timeout_s
# Per person: how many replies they had (a delete is confirmed only in a later one) and the
# deletes they were asked to confirm (chat_channels.spec.md).
self.reply_turns: dict[str, int] = {}
self.pending_deletes: dict[str, dict] = {}
self.scheduler: SttScheduler | None = None
self.tts: TtsService | None = None
self._ids = itertools.count(1)
@@ -147,6 +152,9 @@ class Session:
raise ValueError("memory must be an object")
self.memory.update(memory)
self.voice_channel: str | None = None
self.chat_channels: list[dict] = []
self.chat_waiting: dict[str, asyncio.Future] = {}
self._chat_ids = itertools.count(1)
self.names: dict[str, str] = {}
self.speakers: dict[str, _Speaker] = {}
self.tts_requests: dict[str, TtsRequest] = {}
@@ -184,6 +192,9 @@ class Session:
finally:
self.closed = True
self._leave_voice()
for fut in self.chat_waiting.values():
if not fut.done():
fut.set_result({"ok": False, "error": "the app disconnected"})
ticker.cancel()
writer.cancel()
if w.scheduler:
@@ -280,6 +291,7 @@ class Session:
"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,
"chat_channels": self._on_chat_channels, "chat_action_result": self._on_chat_action_result,
"memory_config": self._on_memory_config}.get(kind)
if handler is None:
self.error("bad_message", f"unknown type: {kind!r}")
@@ -403,6 +415,47 @@ class Session:
if got is not None and self.worker.history is not None:
self.worker.history.delete_chat(*got)
_CHAT_FLAGS = ("read", "send", "edit", "react", "delete", "pin")
def _on_chat_channels(self, msg: dict) -> None:
channels = msg.get("channels")
ok = isinstance(channels, list) and all(
isinstance(c, dict) and all(isinstance(c.get(k), str) for k in ("id", "name", "description"))
and c["id"] and all(isinstance(c.get(f), bool) for f in self._CHAT_FLAGS) for c in channels)
if not ok:
self.error("bad_message", "chat_channels needs channels with id, name, description and "
"boolean read, send, edit, react, delete, pin")
return
self.chat_channels = [{k: c[k] for k in ("id", "name", "description", *self._CHAT_FLAGS)} for c in channels]
debug_log(f"session {self.sid} chat channels: {len(self.chat_channels)}", "voice_worker")
async def chat_action(self, action: str, channel: str, args: dict) -> dict:
"""Ask the app to do a chat action and wait for its answer (or a timeout)."""
aid = f"a{next(self._chat_ids)}"
fut = asyncio.get_running_loop().create_future()
self.chat_waiting[aid] = fut
self.send({"type": "chat_action", "id": aid, "action": action, "channel": channel,
**{k: v for k, v in args.items() if v is not None}})
debug_log(f"chat action {aid} {action} channel={channel}", "voice_worker")
try:
return await asyncio.wait_for(fut, self.worker.chat_timeout_s)
except asyncio.TimeoutError:
return {"ok": False, "error": "the app did not answer in time"}
finally:
self.chat_waiting.pop(aid, None)
def _on_chat_action_result(self, msg: dict) -> None:
fut = self.chat_waiting.get(msg.get("id"))
if fut is None or fut.done():
return
ids = msg.get("message_ids") or []
result = {"ok": msg.get("ok") is True}
if result["ok"]:
result["message_ids"] = [str(i) for i in ids if isinstance(i, (str, int))]
else:
result["error"] = str(msg.get("error") or "the app could not do it")
fut.set_result(result)
def _on_memory_config(self, msg: dict) -> None:
changes = {k: v for k, v in msg.items() if k != "type"}
try:
@@ -442,8 +495,12 @@ class Session:
else:
from jarvis.memory.history import HistoryContext
history = HistoryContext()
turn = w.reply_turns[user] = w.reply_turns.get(user, 0) + 1
from .chat_bridge import ChatBridge
chat = ChatBridge(self, asyncio.get_running_loop(), turn, w.pending_deletes.setdefault(user, {})) \
if self.chat_channels else None
try:
answer = await asyncio.to_thread(w.brain.reply, user, text, history)
answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat)
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