feat: reminders and scheduled tasks (schedule tool, app store and delivery)

The brain gets a schedule tool (add, list, delete the asker's own reminders,
timers and tasks) offered only with a schedule backend. The voice worker asks
the app through schedule_action and runs fired tasks as reply via task with
read-only tools, no MCP and a fresh short-term memory. The app keeps the
schedules in config/schedules.json, fires them every 5 s, speaks them when the
person is in Jarvis's voice channel and otherwise posts in the chat channel
they asked in (or schedule.chatChannel for voice). A feature switch and a
예약 screen list and delete everyone's schedules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 16:27:42 +09:00
parent 3d75d74f92
commit ea2d3ba958
32 changed files with 1568 additions and 59 deletions

View File

@@ -199,8 +199,16 @@ struct Inner {
/// The latest voice session's number, and the session each utterance in progress started in.
voice_session: std::sync::atomic::AtomicU64,
utt_sessions: Mutex<UttSessions>,
/// The reminders and scheduled tasks the brain's schedule tool adds to (admin.spec.md, "Schedules").
schedules: OnceLock<Arc<crate::schedule::Store>>,
/// Scheduled tasks waiting for the brain's answer, by reply id.
tasks: Mutex<HashMap<String, tokio::sync::oneshot::Sender<String>>>,
}
/// How long a scheduled task may take, waiting for an LLM switch included (the worker gives up
/// waiting for one after 180 s).
const TASK_TIMEOUT: Duration = Duration::from_secs(300);
/// The voice session each utterance in progress started in (`Heard::session`).
#[derive(Default)]
pub struct UttSessions(HashMap<(u64, u32), u64>);
@@ -260,6 +268,8 @@ impl DiscordCore {
names: Mutex::new(HashMap::new()),
voice_session: std::sync::atomic::AtomicU64::new(0),
utt_sessions: Mutex::new(UttSessions::default()),
schedules: OnceLock::new(),
tasks: Mutex::new(HashMap::new()),
});
tokio::spawn(player_task(Arc::downgrade(&inner), player_rx));
tokio::spawn(worker_task(Arc::downgrade(&inner), worker_events));
@@ -480,9 +490,28 @@ impl DiscordCore {
Some(with_playback(&self.inner, |p| p.clip(crate::earcon::pcm().to_vec())))
}
/// Have the brain answer a chat message under `id`; the text comes as `CoreEvent::ReplyText`.
pub fn chat_answer(&self, id: &str, user: u64, text: &str) -> bool {
self.inner.worker.reply(id, user, text, "chat", false)
/// Have the brain answer a chat message written in `channel` under `id`; the text comes as
/// `CoreEvent::ReplyText`.
pub fn chat_answer(&self, id: &str, user: u64, channel: u64, text: &str) -> bool {
self.inner.worker.reply_in(id, user, text, "chat", false, Some(channel))
}
/// The store the brain's schedule tool works on; without one its actions fail.
pub fn set_schedules(&self, store: Arc<crate::schedule::Store>) {
let _ = self.inner.schedules.set(store);
}
/// Run a scheduled task in the brain (read-only tools, not spoken) and wait for its answer.
pub async fn run_task(&self, id: &str, user: u64, text: &str) -> Option<String> {
let (tx, rx) = tokio::sync::oneshot::channel();
self.inner.tasks.lock().unwrap().insert(id.to_owned(), tx);
if !self.inner.worker.reply(id, user, text, "task", false) {
self.inner.tasks.lock().unwrap().remove(id);
return None;
}
let got = tokio::time::timeout(TASK_TIMEOUT, rx).await;
self.inner.tasks.lock().unwrap().remove(id);
got.ok().and_then(Result::ok).filter(|t| !t.trim().is_empty())
}
/// Tell the brain whether the chat answer `id` was posted.
@@ -633,6 +662,22 @@ impl DiscordCore {
use songbird::CoreEvent as CoreEvent_;
#[async_trait]
impl crate::schedule::Deliver for DiscordCore {
fn hears(&self, user: u64) -> bool {
self.voice_members().iter().any(|(u, _)| *u == user)
}
fn say(&self, text: &str) -> bool {
DiscordCore::say(self, text, false).is_some()
}
async fn post(&self, channel: u64, text: &str) -> Result<(), String> {
self.send_chat(channel, text).await.map(|_| ()).map_err(|e| e.to_string())
}
async fn task(&self, id: &str, user: u64, text: &str) -> Option<String> {
self.run_task(id, user, text).await
}
}
fn with_playback<T>(inner: &Inner, f: impl FnOnce(&mut Playback<WorkerClient, PlayerSink>) -> T) -> T {
let (out, events) = {
let mut p = inner.playback.lock().unwrap();
@@ -778,6 +823,10 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
WorkerEvent::ReplyText { id, text, failed } => {
debug_log!("voice", "reply {id} chars={} failed={failed}", text.chars().count());
if let Some(tx) = inner.tasks.lock().unwrap().remove(&id) {
let _ = tx.send(if failed { String::new() } else { text });
continue;
}
let _ = inner.events.send(CoreEvent::ReplyText { id, text, failed });
}
WorkerEvent::Addressed { id, addressed } => {
@@ -800,9 +849,24 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
core.inner.worker.chat_action_result(&a.id, result);
});
}
WorkerEvent::ScheduleAction(a) => {
let result = match inner.schedules.get() {
Some(store) => {
let name = a.user.parse().map(|u| name_of(&inner, u)).unwrap_or_else(|_| a.user.clone());
crate::schedule::act(store, &a, &name, chrono::Utc::now().timestamp())
}
None => Err("schedules are not available".into()),
};
if let Err(e) = &result {
debug_log!("schedule", "schedule {} {} refused: {e}", a.action, a.id);
}
inner.worker.schedule_action_result(&a.id, result);
}
WorkerEvent::Disconnected => {
// The restarted worker numbers utterances afresh: the old ones' sessions are void.
inner.utt_sessions.lock().unwrap().clear();
// Its tasks will not be answered.
inner.tasks.lock().unwrap().clear();
let _ = inner.events.send(CoreEvent::WorkerLost);
}
WorkerEvent::Error(_) => {}