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:
@@ -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]
|
||||
|
||||
@@ -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(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user