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:
@@ -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, Ready, ShardManager, UserId,
|
||||
VoiceState,
|
||||
GuildId, Http, InstallationContext, Interaction, InteractionContext, Message, MessageId, MessageUpdateEvent, Ready,
|
||||
ShardManager, UserId, VoiceState,
|
||||
};
|
||||
use songbird::driver::DecodeMode;
|
||||
use songbird::input::Input;
|
||||
@@ -359,6 +359,7 @@ impl DiscordCore {
|
||||
tokio::spawn(speaking_end_timer(Arc::downgrade(&self.inner), rx.clone(), alive.clone()));
|
||||
*self.inner.session.lock().unwrap() = Some(Session { guild_id: gc.guild_id.get(), channel_id, rx, alive });
|
||||
let _ = self.inner.player.send(PlayerCmd::SetCall(Some(call)));
|
||||
report_voice_state(&self.inner);
|
||||
debug_log!("voice", "joined voice {channel_id}");
|
||||
let _ = self.inner.events.send(CoreEvent::Joined { guild_id: gc.guild_id.get(), channel_id });
|
||||
let notice = CreateMessage::new().content(&self.inner.settings.voice.join_notice)
|
||||
@@ -477,6 +478,7 @@ async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str, disconnect: b
|
||||
inner.worker.speaker_leave(&user.to_string());
|
||||
}
|
||||
inner.gate.lock().unwrap().clear();
|
||||
inner.worker.voice_leave();
|
||||
if disconnect {
|
||||
let _ = inner.songbird.remove(GuildId::new(s.guild_id)).await;
|
||||
}
|
||||
@@ -484,6 +486,27 @@ async fn end_session(inner: &Arc<Inner>, s: Session, reason: &str, disconnect: b
|
||||
let _ = inner.events.send(CoreEvent::Left { guild_id: s.guild_id, channel_id: s.channel_id, reason: reason.into() });
|
||||
}
|
||||
|
||||
/// Tell the worker which voice channel Jarvis is in and who is there, so the history store knows
|
||||
/// who heard what. After a join, a move, and every (re)connection of the worker.
|
||||
fn report_voice_state(inner: &Inner) {
|
||||
let Some((guild, channel)) = inner.session.lock().unwrap().as_ref().map(|s| (s.guild_id, s.channel_id)) else {
|
||||
return;
|
||||
};
|
||||
inner.worker.voice_join(channel);
|
||||
let users: Vec<u64> = inner.cache.get()
|
||||
.and_then(|c| c.guild(GuildId::new(guild)).map(|g| g.voice_states.values()
|
||||
.filter(|v| v.channel_id.map(|c| c.get()) == Some(channel))
|
||||
.map(|v| v.user_id.get())
|
||||
.collect()))
|
||||
.unwrap_or_default();
|
||||
let mut n = 0;
|
||||
for user in users.into_iter().filter(|u| should_hear(inner, *u)) {
|
||||
inner.worker.member_join(user, &name_of(inner, user));
|
||||
n += 1;
|
||||
}
|
||||
debug_log!("voice", "reported voice {channel} with {n} members to the worker");
|
||||
}
|
||||
|
||||
fn should_hear(inner: &Inner, user: u64) -> bool {
|
||||
if Some(user) == inner.bot_id.get().copied() {
|
||||
return false;
|
||||
@@ -551,7 +574,8 @@ 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(_) | WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
|
||||
WorkerEvent::Ready(_) => report_voice_state(&inner),
|
||||
WorkerEvent::Disconnected | WorkerEvent::Error(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -756,23 +780,65 @@ impl EventHandler for Handler {
|
||||
if let Some(s) = inner.session.lock().unwrap().as_mut() {
|
||||
s.channel_id = c;
|
||||
}
|
||||
report_voice_state(inner);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let was_here = old.and_then(|o| o.channel_id).map(|c| c.get()) == Some(session_channel);
|
||||
if was_here && new_channel != Some(session_channel) {
|
||||
let is_here = new_channel == Some(session_channel);
|
||||
if was_here && !is_here {
|
||||
Receiver { core: Arc::downgrade(inner), rx }.left(inner, user);
|
||||
inner.worker.member_leave(user);
|
||||
} else if is_here && !was_here && should_hear(inner, user) {
|
||||
// Also fires for a mute or deafen when the old state was not cached; the worker keeps
|
||||
// one open presence per person, so that is harmless.
|
||||
inner.worker.member_join(user, &name_of(inner, user));
|
||||
}
|
||||
}
|
||||
|
||||
async fn message(&self, _: Context, m: Message) {
|
||||
let inner = &self.core.inner;
|
||||
let ch = m.channel_id.get();
|
||||
if !self.core.chat_content() || !inner.chat.can_read(ch) || Some(m.author.id.get()) == self.core.bot_id() {
|
||||
if !self.core.chat_content() || !inner.chat.can_read(ch) {
|
||||
return;
|
||||
}
|
||||
let c = to_chat(inner, &m);
|
||||
// The history keeps Jarvis's own messages too; a reply to someone's message is an answer to them.
|
||||
let to = c.from_self.then(|| m.referenced_message.as_ref().map(|r| r.author.id.get())).flatten();
|
||||
inner.worker.chat_message(c.channel_id, c.message_id, c.author_id, &c.author_name, &c.content,
|
||||
m.timestamp.unix_timestamp() as f64, to);
|
||||
if c.from_self {
|
||||
return;
|
||||
}
|
||||
debug_log!("chat", "chat message in {ch} from {} chars={}", m.author.id, m.content.chars().count());
|
||||
let _ = inner.events.send(CoreEvent::Chat(to_chat(inner, &m)));
|
||||
let _ = inner.events.send(CoreEvent::Chat(c));
|
||||
}
|
||||
|
||||
async fn message_update(&self, _: Context, _: Option<Message>, _: Option<Message>, e: MessageUpdateEvent) {
|
||||
let ch = e.channel_id.get();
|
||||
if !self.core.chat_content() || !self.core.inner.chat.can_read(ch) {
|
||||
return;
|
||||
}
|
||||
if let Some(text) = &e.content {
|
||||
debug_log!("chat", "chat message {} edited in {ch}", e.id);
|
||||
self.core.inner.worker.chat_edit(ch, e.id.get(), text);
|
||||
}
|
||||
}
|
||||
|
||||
async fn message_delete(&self, _: Context, channel: ChannelId, id: MessageId, _: Option<GuildId>) {
|
||||
if self.core.inner.chat.can_read(channel.get()) {
|
||||
debug_log!("chat", "chat message {id} deleted in {channel}");
|
||||
self.core.inner.worker.chat_delete(channel.get(), id.get());
|
||||
}
|
||||
}
|
||||
|
||||
async fn message_delete_bulk(&self, _: Context, channel: ChannelId, ids: Vec<MessageId>, _: Option<GuildId>) {
|
||||
if self.core.inner.chat.can_read(channel.get()) {
|
||||
debug_log!("chat", "{} chat messages deleted in {channel}", ids.len());
|
||||
for id in ids {
|
||||
self.core.inner.worker.chat_delete(channel.get(), id.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn interaction_create(&self, _: Context, interaction: Interaction) {
|
||||
|
||||
Reference in New Issue
Block a user