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

@@ -68,6 +68,26 @@ impl ChatChannels {
Some(_) => Ok(()),
}
}
/// The switch a chat action needs (`send`, `edit`, `react`, `delete`, `pin`, `unpin`).
pub fn check_action(&self, id: u64, action: &str) -> Result<(), ChatAccessError> {
let Some(c) = self.by_id.get(&id) else {
return Err(ChatAccessError(format!("channel {id} is not a registered chat channel")));
};
let on = match action {
"send" => c.send,
"edit" => c.edit,
"react" => c.react,
"delete" => c.delete,
"pin" | "unpin" => c.pin,
_ => return Err(ChatAccessError(format!("unknown chat action {action}"))),
};
if on { Ok(()) } else { Err(ChatAccessError(format!("{action} is turned off for channel {id}"))) }
}
pub fn all(&self) -> impl Iterator<Item = &ChatChannelSettings> {
self.by_id.values()
}
}
/// Split text into messages of at most `limit` UTF-16 units, breaking at the last newline, else the
@@ -157,7 +177,23 @@ mod tests {
}
fn ch(id: u64, read: bool, send: bool) -> ChatChannelSettings {
ChatChannelSettings { id, name: String::new(), description: String::new(), read, send }
ChatChannelSettings { id, name: String::new(), description: String::new(), read, send, edit: true,
react: true, delete: false, pin: false }
}
#[test]
fn each_action_needs_its_own_switch() {
let mut open = ch(1, true, true);
open.delete = true;
let c = ChatChannels::new(&[open, ch(2, true, false)]);
for a in ["send", "edit", "react", "delete"] {
assert!(c.check_action(1, a).is_ok(), "{a}");
}
assert!(c.check_action(1, "pin").is_err() && c.check_action(1, "unpin").is_err());
assert!(c.check_action(2, "send").is_err() && c.check_action(2, "delete").is_err());
assert!(c.check_action(2, "react").is_ok());
assert!(c.check_action(3, "send").unwrap_err().0.contains("not a registered"));
assert!(c.check_action(1, "explode").is_err());
}
#[test]

View File

@@ -14,8 +14,8 @@ use serenity::all::{
Cache, ChannelId, ChannelType, Client, CommandDataOptionValue, CommandInteraction, CommandOptionType, Context,
CreateAllowedMentions, CreateCommand, CreateCommandOption, CreateInteractionResponse,
CreateInteractionResponseMessage, CreateMessage, EditInteractionResponse, EventHandler, GatewayIntents, GetMessages,
GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, MessageId, MessageUpdateEvent, Ready,
ShardManager, UserId, VoiceState,
EditMessage, GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, MessageId,
MessageUpdateEvent, ReactionType, Ready, ShardManager, UserId, VoiceState,
};
use songbird::driver::DecodeMode;
use songbird::input::Input;
@@ -28,7 +28,7 @@ use crate::playback::{ClipSink, Playback, PlaybackEnd, PlaybackEvent};
use crate::receive::{opus_payload, OpusFrames, SpeakerStream};
use crate::settings::Settings;
use crate::speakers::SpeakerGate;
use crate::worker_client::{Final, WorkerClient, WorkerEvent};
use crate::worker_client::{ChatAction, Final, WorkerClient, WorkerEvent};
use crate::{debug_log, error_log};
/// No packet for this long and a speaker counts as stopped (Discord.js uses the same 100 ms).
@@ -265,6 +265,7 @@ impl DiscordCore {
e = fail_rx.recv() => return Err(CoreError(format!("could not log in: {}", e.unwrap_or_default()))),
};
let _ = inner.bot_id.set(ready.user.id.get());
report_chat_channels(inner);
debug_log!("discord", "logged in as {} chatContent={content}", ready.user.id);
let _ = inner.events.send(CoreEvent::Ready { user_id: ready.user.id.get(), tag: ready.user.tag() });
if let Err(e) = self.register_command(app.id.get()).await {
@@ -438,6 +439,48 @@ impl DiscordCore {
Ok(ids)
}
/// Do what the brain's chat channel tool asked (chat_channels.spec.md). The message ids made or
/// touched. Every action needs its channel switch; edits only the bot's own messages.
pub async fn chat_action(&self, a: &ChatAction) -> Result<Vec<u64>, CoreError> {
let channel: u64 = a.channel.parse().map_err(|_| CoreError(format!("bad channel id {}", a.channel)))?;
self.inner.chat.check_action(channel, &a.action)?;
if a.action == "send" {
return self.send_chat(channel, a.text.as_deref().unwrap_or("")).await;
}
let id = a.message_id.as_deref().and_then(|m| m.parse::<u64>().ok()).filter(|m| *m != 0)
.map(MessageId::new).ok_or_else(|| CoreError(format!("{} needs a message id", a.action)))?;
let http = self.http()?;
let ch = ChannelId::new(channel);
match a.action.as_str() {
"edit" => {
let text = a.text.as_deref().unwrap_or("").trim();
if text.is_empty() {
return Err(CoreError("nothing to write".into()));
}
if text.encode_utf16().count() > MESSAGE_LIMIT {
return Err(CoreError(format!("an edit must fit one message ({MESSAGE_LIMIT} characters)")));
}
let mut m = ch.message(http.as_ref(), id).await.map_err(cerr("could not fetch the message"))?;
if Some(m.author.id.get()) != self.bot_id() {
return Err(CoreError("Discord lets the bot edit only its own messages".into()));
}
m.edit(http.as_ref(), EditMessage::new().content(text).allowed_mentions(CreateAllowedMentions::new()))
.await.map_err(cerr("could not edit"))?;
}
"react" => {
let emoji = a.emoji.as_deref().unwrap_or("").trim();
let reaction = ReactionType::try_from(emoji).map_err(|_| CoreError(format!("not an emoji: {emoji}")))?;
ch.create_reaction(http.as_ref(), id, reaction).await.map_err(cerr("could not react"))?;
}
"delete" => ch.delete_message(http.as_ref(), id).await.map_err(cerr("could not delete"))?,
"pin" => ch.pin(http.as_ref(), id).await.map_err(cerr("could not pin"))?,
"unpin" => ch.unpin(http.as_ref(), id).await.map_err(cerr("could not unpin"))?,
other => return Err(CoreError(format!("unknown chat action {other}"))),
}
debug_log!("chat", "chat {} done in {channel} message={id}", a.action);
Ok(vec![id.get()])
}
pub async fn close(&self) {
self.leave("shutdown").await;
if let Some(s) = self.inner.shards.get() {
@@ -507,6 +550,11 @@ fn report_voice_state(inner: &Inner) {
debug_log!("voice", "reported voice {channel} with {n} members to the worker");
}
/// The registered chat channels and their switches, for the brain's chat tool.
fn report_chat_channels(inner: &Inner) {
inner.worker.chat_channels(inner.bot_id.get().copied(), &inner.settings.chat_channels);
}
fn should_hear(inner: &Inner, user: u64) -> bool {
if Some(user) == inner.bot_id.get().copied() {
return false;
@@ -574,7 +622,20 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
WorkerEvent::Final(m) => on_final(&inner, m),
WorkerEvent::TtsAudio { id, seq, pcm } => with_playback(&inner, |p| p.audio(&id, seq, pcm)),
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
WorkerEvent::Ready(_) => report_voice_state(&inner),
WorkerEvent::Ready(_) => {
report_chat_channels(&inner);
report_voice_state(&inner);
}
WorkerEvent::ChatAction(a) => {
let core = DiscordCore { inner: inner.clone() };
tokio::spawn(async move {
let result = core.chat_action(&a).await.map_err(|e| e.to_string());
if let Err(e) = &result {
debug_log!("chat", "chat {} {} failed: {e}", a.action, a.id);
}
core.inner.worker.chat_action_result(&a.id, result);
});
}
WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
}
}

View File

@@ -67,7 +67,7 @@ strings (numbers would lose precision).
| `voice.joinNotice` | "자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다." | Posted in the voice channel's chat on every join. Must not be empty. |
| `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`. |
| `voice.stt` | `{}` | Other worker STT settings (`partials`, `end_silence_ms`, `final_beam`, `language`, ...); the worker validates them. |
| `chatChannels` | `[]` | `{id, name, description, read (true), send (true)}` per channel. |
| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false)}` per channel. |
| `voiceWorker.python` | `python3` (`python.exe` on Windows) | Python of the worker venv. |
| `voiceWorker.cwd` | the repo's `src/` (development builds) | Folder holding the `voice_worker` package. |
| `voiceWorker.args` | `[]` | Extra worker arguments, e.g. `["--melo-python", "<MeloTTS venv python>"]`. |
@@ -177,6 +177,13 @@ registered until it is removed (M5 setup).
Discord's 2,000-character limit at the last newline or space (never inside a character), and returns
the message ids.
- A channel that is not registered, or has the needed switch off, is refused with an access error.
- **Chat tool actions** (M3, `chat_channels.spec.md`): when the worker link is ready and after login,
the core sends `chat_channels` (every registered channel with its switches, and the bot's user ID).
A `chat_action` from the worker runs `chat_action()` and answers `chat_action_result` with the
message ids or the error text: `send` (as Send above), `edit` (only the bot's own messages, one
message long, pings nobody), `react` (a Unicode or custom emoji), `delete`, `pin`, `unpin`. Each
needs its channel switch. Discord's own refusals come back as errors, for example a voice channel's
chat cannot pin.
## Tests
@@ -196,7 +203,10 @@ registered until it is removed (M5 setup).
leaving and coming back three times (each a DAVE group change), and leaving. The worker runs with
`--history`; at the end the store must hold the speaker's finals under its display name and channel,
its chat message with the edit and without the deleted one, Jarvis's own messages, a presence
interval per join, and no presence left open. It needs a second voice
interval per join, and no presence left open. The chat tool's actions run on the channel too:
editing its own message, refusing to edit the speaker's, a reaction, pin (Discord refuses it in a
voice channel's chat, which must come back as an error), delete, and refusing an unregistered
channel. It needs a second voice
channel of the server (`JARVIS_LIVE_VOICE_CHANNEL_2`) and refuses if a person is in either.
Measured on this server's RTX 5050 (2026-11-11): five sentences all heard (character error rate 0%
for three, 5% and 12.5% for two), 0.71-0.90 s from the end of speech to the final, Jarvis's speech

View File

@@ -17,6 +17,14 @@ pub struct ChatChannelSettings {
pub read: bool,
/// The assistant may send messages to this channel.
pub send: bool,
/// The assistant may edit the messages it wrote here (Discord allows only those).
pub edit: bool,
/// The assistant may add reactions here.
pub react: bool,
/// The assistant may delete messages here (needs Manage Messages for other people's). Off by default.
pub delete: bool,
/// The assistant may pin and unpin messages here. Off by default.
pub pin: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -225,6 +233,10 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
description: get_str(Some(m), "description", &path, "")?,
read: get_bool(Some(m), "read", &path, true)?,
send: get_bool(Some(m), "send", &path, true)?,
edit: get_bool(Some(m), "edit", &path, true)?,
react: get_bool(Some(m), "react", &path, true)?,
delete: get_bool(Some(m), "delete", &path, false)?,
pin: get_bool(Some(m), "pin", &path, false)?,
});
}
@@ -307,7 +319,8 @@ mod tests {
assert_eq!(s.voice.wake_words, vec!["자비스", "javis"]);
assert_eq!(s.voice.stt.get("end_silence_ms"), Some(&json!(250)));
assert_eq!(s.chat_channels, vec![ChatChannelSettings { id: IDN, name: "일정".into(),
description: "일정 올리는 곳".into(), read: true, send: false }]);
description: "일정 올리는 곳".into(), read: true, send: false, edit: true, react: true, delete: false,
pin: false }]);
assert_eq!(s.voice_worker.args, vec!["--melo-python", "/m/python"]);
assert_eq!(s.voice_worker.cwd, PathBuf::from("/repo/src"));
}

View File

@@ -104,6 +104,21 @@ pub struct WorkerError {
pub id: Option<String>,
}
/// The brain's chat channel tool asks the app to act (voice_worker.spec.md, chat_channels.spec.md).
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct ChatAction {
pub id: String,
/// `send`, `edit`, `react`, `delete`, `pin` or `unpin`.
pub action: String,
pub channel: String,
#[serde(default)]
pub message_id: Option<String>,
#[serde(default)]
pub text: Option<String>,
#[serde(default)]
pub emoji: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum WorkerEvent {
Ready(HelloOk),
@@ -113,6 +128,7 @@ pub enum WorkerEvent {
Final(Final),
TtsAudio { id: String, seq: u32, pcm: Vec<u8> },
TtsDone(TtsDone),
ChatAction(ChatAction),
Error(WorkerError),
}
@@ -258,6 +274,28 @@ impl WorkerClient {
"text": text}));
}
/// The registered chat channels, their switches and the bot's own user ID, for the chat tool.
pub fn chat_channels(&self, bot: Option<u64>, channels: &[crate::settings::ChatChannelSettings]) {
let list: Vec<Value> = channels.iter().map(|c| json!({"id": c.id.to_string(), "name": c.name,
"description": c.description, "read": c.read, "send": c.send, "edit": c.edit, "react": c.react,
"delete": c.delete, "pin": c.pin})).collect();
let mut v = json!({"type": "chat_channels", "channels": list});
if let Some(b) = bot {
v["bot"] = Value::String(b.to_string());
}
self.send_json(v);
}
/// The outcome of a `chat_action`: the message ids it made or touched, or why it failed.
pub fn chat_action_result(&self, id: &str, result: Result<Vec<u64>, String>) {
let v = match result {
Ok(ids) => json!({"type": "chat_action_result", "id": id, "ok": true,
"message_ids": ids.iter().map(|i| i.to_string()).collect::<Vec<_>>()}),
Err(e) => json!({"type": "chat_action_result", "id": id, "ok": false, "error": e}),
};
self.send_json(v);
}
pub fn chat_delete(&self, channel: u64, message: u64) {
self.send_json(json!({"type": "chat_delete", "channel": channel.to_string(),
"message_id": message.to_string()}));
@@ -419,6 +457,7 @@ fn on_text(inner: &Inner, t: &str) {
"speech_start" => serde_json::from_value(v).ok().map(WorkerEvent::SpeechStart),
"partial" => serde_json::from_value(v).ok().map(WorkerEvent::Partial),
"final" => serde_json::from_value(v).ok().map(WorkerEvent::Final),
"chat_action" => serde_json::from_value(v).ok().map(WorkerEvent::ChatAction),
"tts_done" => serde_json::from_value::<TtsDone>(v).ok().and_then(|d| {
inner.state.lock().unwrap().open_tts.remove(&d.id).then_some(WorkerEvent::TtsDone(d))
}),

View File

@@ -187,7 +187,8 @@ async fn discord_voice_core_on_real_discord() {
// The "person" here is a bot, so bots must be heard.
"voice": {"listenToBots": true},
// The voice channel's own chat stands in for a registered chat channel.
"chatChannels": [{"id": voice.to_string(), "name": "테스트", "description": "라이브 테스트"}],
"chatChannels": [{"id": voice.to_string(), "name": "테스트", "description": "라이브 테스트",
"delete": true, "pin": true}],
})).unwrap();
let (core, mut core_rx) = DiscordCore::new(settings, bot_token.clone(), worker.clone(), worker_events);
let events: Arc<Mutex<Vec<CoreEvent>>> = Arc::default();
@@ -344,6 +345,44 @@ async fn discord_voice_core_on_real_discord() {
tokio::time::sleep(Duration::from_millis(500)).await;
assert!(!events.lock().unwrap().iter().any(|e| matches!(e, CoreEvent::Chat(c) if c.content == reply)));
// 5b. The chat tool's actions, as the worker asks for them: edit (own messages only), react, pin,
// unpin, delete; a switch that is off is refused.
let act = |action: &str, id: u64, text: Option<&str>, emoji: Option<&str>| jarvis_app::worker_client::ChatAction {
id: "live".into(), action: action.into(), channel: voice.to_string(), message_id: Some(id.to_string()),
text: text.map(Into::into), emoji: emoji.map(Into::into) };
let tool_msg = format!("자비스 도구 시험 {}", stop_at.elapsed().as_nanos());
let tid = core.send_chat(voice, &tool_msg).await.unwrap()[0];
let edited_tool = format!("{tool_msg} 수정");
core.chat_action(&act("edit", tid, Some(&edited_tool), None)).await.expect("edit own message");
let err = core.chat_action(&act("edit", marker_msg.id.get(), Some("남의 글"), None)).await.unwrap_err();
assert!(err.0.contains("own"), "{err}");
core.chat_action(&act("react", marker_msg.id.get(), None, Some("👍"))).await.expect("react");
// A voice channel's chat cannot pin (Discord answers "cannot be pinned in this channel"); the
// refusal must come back as an error the assistant can say, not a crash.
let pinned = core.chat_action(&act("pin", tid, None, None)).await;
let pin_report = match &pinned {
Ok(_) => "pinned".to_string(),
Err(e) => {
assert!(e.0.contains("pinned"), "unexpected pin error: {e}");
format!("refused by Discord: {}", e.0)
}
};
let fetched = ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(tid)).await.unwrap();
assert_eq!(fetched.content, edited_tool, "edit");
assert_eq!(fetched.pinned, pinned.is_ok(), "pin state");
let marked = ChannelId::new(voice).message(&s_http, marker_msg.id).await.unwrap();
assert!(marked.reactions.iter().any(|r| r.count >= 1), "no reaction");
if pinned.is_ok() {
core.chat_action(&act("unpin", tid, None, None)).await.expect("unpin");
}
core.chat_action(&act("delete", tid, None, None)).await.expect("delete");
tokio::time::sleep(Duration::from_millis(800)).await;
assert!(ChannelId::new(voice).message(&s_http, serenity::all::MessageId::new(tid)).await.is_err(), "not deleted");
let off = jarvis_app::worker_client::ChatAction { channel: voice2.to_string(), ..act("send", tid, Some("x"), None) };
assert!(core.chat_action(&off).await.unwrap_err().0.contains("not a registered"));
report.insert("chat_tool".into(), json!({"edit": true, "edit_others_refused": true, "react": true,
"pin": pin_report, "delete": true, "unregistered_refused": true}));
// 6. Moving to another channel and back: the old connection's shutdown must not end the new one.
for (to, what) in [(voice2, "the second channel"), (voice, "the first channel")] {
core.join(to).await.expect("move");
@@ -425,11 +464,12 @@ print(json.dumps({"voice": [[r.author_name, r.channel_id, r.text] for r in own i
assert!(voice_recs.iter().all(|r| r[0].as_str() != Some(&speaker_id.to_string()) && !r[2].as_str().unwrap().is_empty()),
"a final without the speaker's name: {h}");
assert!(voice_recs.iter().any(|r| r[0].as_str() == Some(speaker_name.as_str())), "{speaker_name} not in {h}");
assert!(voice_recs.iter().any(|r| r[1] == voice.to_string()), "{h}");
assert!(voice_recs.iter().any(|r| r[1].as_str() == Some(voice.to_string().as_str())), "{h}");
let chat: Vec<&str> = h["chat"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
assert_eq!(chat, [edited.as_str()], "speaker chat in the history");
let jarvis_chat: Vec<&str> = h["jarvis_chat"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect();
assert!(jarvis_chat.contains(&reply.as_str()) && jarvis_chat.iter().any(|t| t.contains("받아 적습니다")), "{h}");
assert!(!jarvis_chat.iter().any(|t| t.contains(&tool_msg)), "the deleted tool message is still stored: {h}");
assert!(h["presence"].as_u64().unwrap() >= 4, "joins and rejoins open presence: {h}");
assert_eq!(h["open"], 0, "presence left open after Jarvis left: {h}");

View File

@@ -6,7 +6,8 @@ use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use jarvis_app::frames::{encode_audio_frame, KIND_TTS};
use jarvis_app::playback::TtsBackend;
use jarvis_app::worker_client::{TtsDone, WorkerClient, WorkerClientOptions, WorkerEvent};
use jarvis_app::settings::ChatChannelSettings;
use jarvis_app::worker_client::{ChatAction, TtsDone, WorkerClient, WorkerClientOptions, WorkerEvent};
use serde_json::{json, Value};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
@@ -259,3 +260,29 @@ async fn history_messages_follow_the_worker_protocol() {
]);
c.close();
}
#[tokio::test]
async fn chat_channels_go_out_and_chat_actions_come_back_with_their_results() {
let w = FakeWorker::start(0).await;
let (c, mut rx) = client(&w.url(), json!({}));
c.start();
c.wait_ready(Duration::from_secs(2)).await.expect("ready");
c.chat_channels(Some(900), &[ChatChannelSettings { id: 5, name: "일정".into(), description: "약속".into(),
read: true, send: true, edit: true, react: true, delete: false, pin: false }]);
w.send(Message::text(json!({"type": "chat_action", "id": "a1", "action": "react", "channel": "5",
"message_id": "77", "emoji": "👍"}).to_string()));
let ev = next_matching(&mut rx, |e| matches!(e, WorkerEvent::ChatAction(_))).await;
assert_eq!(ev, WorkerEvent::ChatAction(ChatAction { id: "a1".into(), action: "react".into(), channel: "5".into(),
message_id: Some("77".into()), text: None, emoji: Some("👍".into()) }));
c.chat_action_result("a1", Ok(vec![77]));
c.chat_action_result("a2", Err("send is turned off".into()));
until(|| w.got().len() >= 4).await;
let got: Vec<Value> = w.got()[1..].iter().map(|g| match g { Got::Json(v) => v.clone(), Got::Bin(_) => json!(null) }).collect();
assert_eq!(got, vec![
json!({"type": "chat_channels", "bot": "900", "channels": [{"id": "5", "name": "일정", "description": "약속",
"read": true, "send": true, "edit": true, "react": true, "delete": false, "pin": false}]}),
json!({"type": "chat_action_result", "id": "a1", "ok": true, "message_ids": ["77"]}),
json!({"type": "chat_action_result", "id": "a2", "ok": false, "error": "send is turned off"}),
]);
c.close();
}