1use std::sync::Arc;
6
7use adk_kernel::drivers::EffectClass;
8use adk_kernel::{AgendaItem, AgendaState};
9use async_trait::async_trait;
10use chrono::{DateTime, Duration, FixedOffset, Utc};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13use serde_json::{Value, json};
14
15use super::registry::{Entry, single_time};
16use super::{Callers, ObjectKind, VerbDone, VerbError, VerbHandler, VerbScope, VerbSpec, words};
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
34#[serde(rename_all = "camelCase")]
35pub struct ComingUpItem {
36 pub id: String,
38 pub title: String,
40 pub area: String,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub at: Option<DateTime<Utc>>,
45 pub at_text: String,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub ends: Option<DateTime<Utc>>,
50 pub choices: Vec<SnoozeChoice>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub why_not: Option<String>,
55}
56
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
71#[serde(rename_all = "camelCase")]
72pub struct SnoozeChoice {
73 pub to: DateTime<FixedOffset>,
75 pub label: String,
77 pub at_text: String,
79 pub tomorrow: bool,
81}
82
83pub(crate) fn catalogue() -> Vec<Entry> {
85 let coming_up = VerbSpec::new(
86 "coming_up",
87 "Coming up",
88 "List what is coming up for the person: each item's id, title, when it wakes, and the \
89 two times it may be snoozed to. Reading it never asks the person.",
90 EffectClass::Read,
91 )
92 .with_objects([ObjectKind::ComingUp])
93 .with_callers(Callers::PersonAndAgents);
94 let snooze = VerbSpec::new(
95 "snooze",
96 words::SNOOZE,
97 words::SNOOZE_SOMETHING,
98 EffectClass::WriteLocal,
99 )
100 .with_objects([ObjectKind::ComingUp])
101 .with_args(json!({
102 "type": "object",
103 "properties": {
104 "item": {
105 "type": "string",
106 "description": "The id of the item, as coming_up lists it"
107 },
108 "to": {
109 "type": "string",
110 "format": "date-time",
111 "description": "When it should wake instead: exactly one of the two times coming_up lists for the item"
112 }
113 },
114 "required": ["item", "to"],
115 "additionalProperties": false
116 }))
117 .with_callers(Callers::PersonAndAgents)
118 .only_delays()
119 .reversible()
120 .with_voice_phrase("snooze");
121 vec![
122 Entry { spec: coming_up, handler: Arc::new(ComingUp) },
123 Entry { spec: snooze, handler: Arc::new(Snooze) },
124 ]
125}
126
127impl VerbScope {
128 pub async fn coming_up(&self) -> Result<Vec<ComingUpItem>, VerbError> {
135 let mut out = Vec::new();
136 for item in self.items().await? {
137 out.push(self.coming_up_item(&item).await?);
138 }
139 out.sort_by(|a, b| match (a.at, b.at) {
140 (Some(a), Some(b)) => a.cmp(&b),
141 (Some(_), None) => std::cmp::Ordering::Less,
142 (None, Some(_)) => std::cmp::Ordering::Greater,
143 (None, None) => std::cmp::Ordering::Equal,
144 });
145 Ok(out)
146 }
147
148 async fn coming_up_item(&self, item: &AgendaItem) -> Result<ComingUpItem, VerbError> {
149 let at = match &item.state {
150 AgendaState::Scheduled { wake } => single_time(wake),
151 _ => None,
152 };
153 let why_not = match &item.state {
154 AgendaState::Running { .. } => Some(words::ALREADY_STARTED),
155 AgendaState::Scheduled { .. } if at.is_none() => Some(words::NOT_ONE_TIME),
156 AgendaState::Scheduled { .. } if self.started(item).await? => {
157 Some(words::ALREADY_STARTED)
158 }
159 AgendaState::Scheduled { .. } => None,
160 _ => Some(words::NOT_SCHEDULED),
161 };
162 let choices = match (at, why_not) {
163 (Some(at), None) => self.choices(at, item.expires_at),
164 _ => Vec::new(),
165 };
166 let why_not = why_not.map(str::to_string).or_else(|| match (at, item.expires_at) {
167 (Some(_), Some(ends)) if choices.is_empty() => {
168 Some(words::ends_at(&self.time_text(ends)))
169 }
170 _ => None,
171 });
172 Ok(ComingUpItem {
173 id: item.id.clone(),
174 title: item.title.clone(),
175 area: item.partition.to_string(),
176 at,
177 at_text: at.map(|at| self.time_text(at)).unwrap_or_default(),
178 ends: item.expires_at,
179 choices,
180 why_not,
181 })
182 }
183
184 fn choices(&self, at: DateTime<Utc>, ends: Option<DateTime<Utc>>) -> Vec<SnoozeChoice> {
186 [
187 (Duration::hours(1), words::ONE_HOUR_LATER, false),
188 (Duration::days(1), words::TOMORROW_SAME_TIME, true),
189 ]
190 .into_iter()
191 .map(|(by, label, tomorrow)| (at + by, label, tomorrow))
192 .filter(|(to, _, _)| ends.is_none_or(|ends| *to <= ends))
193 .map(|(to, label, tomorrow)| SnoozeChoice {
194 to: to.with_timezone(&self.offset()),
195 label: label.to_string(),
196 at_text: self.time_text(to),
197 tomorrow,
198 })
199 .collect()
200 }
201
202 async fn snoozable(
205 &self,
206 id: &str,
207 to: DateTime<Utc>,
208 ) -> Result<(AgendaItem, DateTime<Utc>), VerbError> {
209 let item = self.item(id).await?;
210 let wake = match &item.state {
211 AgendaState::Scheduled { wake } => wake,
212 AgendaState::Running { .. } => return Err(VerbError::refused(words::ALREADY_STARTED)),
213 AgendaState::Proposed | AgendaState::Approved => {
214 return Err(VerbError::refused(words::NOT_SCHEDULED));
215 }
216 _ => return Err(VerbError::refused(words::ENDED)),
217 };
218 let Some(at) = single_time(wake) else {
219 return Err(VerbError::refused(words::NOT_ONE_TIME));
220 };
221 if to != at + Duration::hours(1) && to != at + Duration::days(1) {
222 if to <= at {
225 return Err(VerbError::refused(words::IT_MOVED));
226 }
227 let times: Vec<String> = self
228 .choices(at, item.expires_at)
229 .into_iter()
230 .map(|choice| choice.at_text)
231 .collect();
232 return Err(VerbError::refused(match (times.is_empty(), item.expires_at) {
233 (true, Some(ends)) => words::ends_at(&self.time_text(ends)),
234 _ => words::only_moves_to(×),
235 }));
236 }
237 if let Some(ends) = item.expires_at.filter(|ends| to > *ends) {
238 return Err(VerbError::refused(words::ends_at(&self.time_text(ends))));
239 }
240 if self.started(&item).await? {
241 return Err(VerbError::refused(words::ALREADY_STARTED));
242 }
243 Ok((item, at))
244 }
245}
246
247pub fn find_by_title<'a>(
270 items: &'a [ComingUpItem],
271 title: &str,
272) -> Result<&'a ComingUpItem, VerbError> {
273 let wanted = normalize(title);
274 let exact: Vec<&ComingUpItem> =
275 items.iter().filter(|item| normalize(&item.title) == wanted).collect();
276 match exact.as_slice() {
277 [only] => return Ok(only),
278 [] => {}
279 several => {
280 return Err(VerbError::Ambiguous {
281 said: title.to_string(),
282 matches: several.iter().map(|item| item.title.clone()).collect(),
283 });
284 }
285 }
286 let partial: Vec<&ComingUpItem> = items
287 .iter()
288 .filter(|item| !wanted.is_empty() && normalize(&item.title).contains(&wanted))
289 .collect();
290 if partial.len() > 1 {
291 return Err(VerbError::Ambiguous {
292 said: title.to_string(),
293 matches: partial.iter().map(|item| item.title.clone()).collect(),
294 });
295 }
296 Err(VerbError::not_found(format!("“{title}”")))
297}
298
299pub(crate) fn normalize(text: &str) -> String {
301 text.split(|c: char| !c.is_alphanumeric() && c != '\'')
302 .filter(|word| !word.is_empty())
303 .map(str::to_lowercase)
304 .collect::<Vec<_>>()
305 .join(" ")
306}
307
308fn snooze_args(args: &Value) -> Result<(String, DateTime<Utc>), VerbError> {
310 let item = args.get("item").and_then(Value::as_str).filter(|item| !item.is_empty());
311 let to = args.get("to").and_then(Value::as_str);
312 let (Some(item), Some(to)) = (item, to) else {
313 return Err(VerbError::invalid(
314 "snooze takes `item`, the id coming_up lists, and `to`, one of its two times",
315 ));
316 };
317 let to = DateTime::parse_from_rfc3339(to)
318 .map_err(|_| VerbError::invalid(format!("`to` is not a time with its offset: {to}")))?
319 .with_timezone(&Utc);
320 Ok((item.to_string(), to))
321}
322
323struct ComingUp;
325
326#[async_trait]
327impl VerbHandler for ComingUp {
328 async fn describe(&self, _scope: &VerbScope, _args: &Value) -> Result<String, VerbError> {
329 Ok("List what is coming up".to_string())
330 }
331
332 async fn run(&self, scope: &VerbScope, _args: &Value) -> Result<VerbDone, VerbError> {
333 let items = scope.coming_up().await?;
334 let text = match items.len() {
335 0 => "Nothing is coming up".to_string(),
336 1 => "1 thing is coming up".to_string(),
337 count => format!("{count} things are coming up"),
338 };
339 let result = serde_json::to_value(&items).unwrap_or(Value::Null);
340 Ok(VerbDone::new("coming_up", text).with_result(json!({ "items": result })))
341 }
342}
343
344struct Snooze;
346
347#[async_trait]
348impl VerbHandler for Snooze {
349 async fn describe(&self, scope: &VerbScope, args: &Value) -> Result<String, VerbError> {
350 let (id, to) = snooze_args(args)?;
351 let (item, _) = scope.snoozable(&id, to).await?;
352 Ok(words::move_to(&item.title, &scope.time_text(to)))
353 }
354
355 async fn run(&self, scope: &VerbScope, args: &Value) -> Result<VerbDone, VerbError> {
356 let (id, to) = snooze_args(args)?;
357 let (item, from) = scope.snoozable(&id, to).await?;
358 scope.move_wake(&id, from, to).await?;
359 let at_text = scope.time_text(to);
360 Ok(VerbDone::new("snooze", words::moved_to(&item.title, &at_text))
361 .with_target(format!("agenda:{id}"), item.title.clone())
362 .with_result(json!({
363 "item": id,
364 "title": item.title,
365 "from": from,
366 "to": to.with_timezone(&scope.offset()),
367 "atText": at_text,
368 })))
369 }
370}