Skip to main content

vtcode_core/scheduler/
session.rs

1use anyhow::{Context, Result, anyhow, bail};
2use chrono::{DateTime, Duration as ChronoDuration, Local, LocalResult, NaiveDateTime, NaiveTime, TimeZone, Utc};
3use humantime::parse_duration as parse_human_duration;
4use regex::Regex;
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7use std::sync::LazyLock;
8
9use super::spec::{
10    DueSessionPrompt, ScheduleSpec, ScheduledTaskAction, ScheduledTaskDefinition, ScheduledTaskRecord,
11    ScheduledTaskSummary, TaskRunStatus,
12};
13use super::{
14    MAX_SCHEDULED_TASKS, SESSION_TASK_EXPIRY_HOURS, advance_record_runtime, due_session_prompt,
15    initialize_runtime_state,
16};
17use crate::utils::path::normalize_path;
18
19static REMIND_AT_RE: LazyLock<Regex> = LazyLock::new(|| {
20    Regex::new(r"(?ix)^\s*remind\s+me\s+at\s+(?P<when>.+?)\s+to\s+(?P<prompt>.+)\s*$").expect("remind-at regex")
21});
22
23static REMIND_IN_RE: LazyLock<Regex> = LazyLock::new(|| {
24    Regex::new(
25        r"(?ix)
26        ^\s*in\s+
27        (?P<count>\d+)
28        \s*
29        (?P<unit>minutes|minute|hours|hour|days|day)
30        \s*,?\s*
31        (?P<prompt>.+)
32        \s*$
33    ",
34    )
35    .expect("remind-in regex")
36});
37
38static TIME_ONLY_RE: LazyLock<Regex> = LazyLock::new(|| {
39    Regex::new(r"(?ix)^\s*(?P<hour>\d{1,2})(?::(?P<minute>\d{2}))?\s*(?P<ampm>am|pm)?\s*$").expect("time-only regex")
40});
41
42#[derive(Debug, Default, Clone)]
43pub struct SessionScheduler {
44    pub(crate) tasks: BTreeMap<String, ScheduledTaskRecord>,
45}
46
47impl SessionScheduler {
48    #[must_use]
49    pub fn new() -> Self {
50        Self { tasks: BTreeMap::new() }
51    }
52
53    #[must_use]
54    pub fn len(&self) -> usize {
55        self.tasks.len()
56    }
57
58    #[must_use]
59    pub fn is_empty(&self) -> bool {
60        self.tasks.is_empty()
61    }
62
63    pub fn create_prompt_task(
64        &mut self,
65        name: Option<String>,
66        prompt: String,
67        schedule: ScheduleSpec,
68        created_at: DateTime<Utc>,
69    ) -> Result<ScheduledTaskSummary> {
70        self.ensure_capacity()?;
71        let expires_at = schedule
72            .is_recurring()
73            .then(|| created_at + ChronoDuration::hours(SESSION_TASK_EXPIRY_HOURS));
74        let definition = ScheduledTaskDefinition::new(
75            name,
76            schedule,
77            ScheduledTaskAction::Prompt { prompt },
78            None,
79            created_at,
80            expires_at,
81        )?;
82        let runtime = initialize_runtime_state(&definition)?;
83        let record = ScheduledTaskRecord { definition: definition.clone(), runtime };
84        let summary = record.summary();
85        self.tasks.insert(definition.id.clone(), record);
86        Ok(summary)
87    }
88
89    pub fn list(&self) -> Vec<ScheduledTaskSummary> {
90        self.tasks.values().map(ScheduledTaskRecord::summary).collect()
91    }
92
93    pub fn delete(&mut self, query: &str) -> Option<ScheduledTaskSummary> {
94        let query = query.trim();
95        if query.is_empty() {
96            return None;
97        }
98        if let Some(record) = self.tasks.remove(query) {
99            return Some(record.summary());
100        }
101        // Names are not unique: only delete when exactly one task matches, so
102        // an ambiguous name can never remove the wrong task.
103        let mut matches = self
104            .tasks
105            .iter()
106            .filter(|(_, record)| record.definition.name.eq_ignore_ascii_case(query))
107            .map(|(id, _)| id.clone());
108        let (Some(key), None) = (matches.next(), matches.next()) else {
109            return None;
110        };
111        self.tasks.remove(&key).map(|record| record.summary())
112    }
113
114    pub fn collect_due_prompts(&mut self, now: DateTime<Utc>) -> Result<Vec<DueSessionPrompt>> {
115        let mut due = Vec::new();
116        let mut completed = Vec::new();
117        for record in self.tasks.values_mut() {
118            let Some(next_run_at) = record.runtime.next_run_at else {
119                continue;
120            };
121            if now < next_run_at {
122                continue;
123            }
124
125            if let Some(prompt) = due_session_prompt(record) {
126                due.push(prompt);
127            }
128
129            if advance_record_runtime(record, now, TaskRunStatus::Triggered)? {
130                completed.push(record.definition.id.clone());
131            }
132        }
133
134        for id in completed {
135            self.tasks.remove(&id);
136        }
137
138        Ok(due)
139    }
140
141    fn ensure_capacity(&self) -> Result<()> {
142        if self.tasks.len() >= MAX_SCHEDULED_TASKS {
143            bail!("A session can hold at most {MAX_SCHEDULED_TASKS} scheduled tasks");
144        }
145        Ok(())
146    }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum SessionLanguageCommand {
151    CreateOneShotPrompt { prompt: String, run_at: DateTime<Utc> },
152    ListTasks,
153    CancelTask { query: String },
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct ScheduleCreateInput {
158    pub name: Option<String>,
159    pub prompt: Option<String>,
160    pub reminder: Option<String>,
161    pub every: Option<String>,
162    pub cron: Option<String>,
163    pub at: Option<String>,
164    pub workspace: Option<PathBuf>,
165}
166
167impl ScheduleCreateInput {
168    pub fn build_definition(
169        self,
170        now: DateTime<Local>,
171        default_workspace: Option<PathBuf>,
172    ) -> Result<ScheduledTaskDefinition> {
173        // Blank action text counts as absent so `--prompt ""` fails with the
174        // same "one of" error instead of creating an empty task.
175        let prompt = self
176            .prompt
177            .map(|value| value.trim().to_string())
178            .filter(|value| !value.is_empty());
179        let reminder = self
180            .reminder
181            .map(|value| value.trim().to_string())
182            .filter(|value| !value.is_empty());
183        let action = match (prompt, reminder) {
184            (Some(prompt), None) => ScheduledTaskAction::Prompt { prompt },
185            (None, Some(reminder)) => ScheduledTaskAction::Reminder { message: reminder },
186            (Some(_), Some(_)) => bail!("Choose either --prompt or --reminder"),
187            (None, None) => bail!("One of --prompt or --reminder is required"),
188        };
189
190        let schedule = match (self.every, self.cron, self.at) {
191            (Some(raw), None, None) => {
192                let duration = parse_human_duration(raw.trim())
193                    .with_context(|| format!("Invalid --every duration: {}", raw.trim()))?;
194                ScheduleSpec::fixed_interval(duration)?
195            }
196            (None, Some(expression), None) => ScheduleSpec::cron5(expression)?,
197            (None, None, Some(raw)) => ScheduleSpec::one_shot(parse_local_datetime(raw.trim(), now)?),
198            _ => bail!("Choose exactly one of --every, --cron, or --at"),
199        };
200
201        let workspace = match (&action, self.workspace.or(default_workspace)) {
202            (ScheduledTaskAction::Prompt { .. }, Some(path)) => Some(path),
203            (ScheduledTaskAction::Prompt { .. }, None) => {
204                bail!("Prompt tasks require a workspace (pass --workspace or create from chat)")
205            }
206            (ScheduledTaskAction::Reminder { .. }, path) => path,
207        }
208        .map(|path| resolve_scheduled_workspace_path(&path))
209        .transpose()?;
210
211        if matches!(action, ScheduledTaskAction::Prompt { .. }) && workspace.as_ref().is_some_and(|path| !path.is_dir())
212        {
213            let workspace = workspace.as_ref().context("prompt workspace should exist")?;
214            bail!("Prompt task workspace does not exist or is not a directory: {}", workspace.display());
215        }
216
217        ScheduledTaskDefinition::new(self.name, schedule, action, workspace, now.with_timezone(&Utc), None)
218    }
219}
220
221pub(crate) fn resolve_scheduled_workspace_path(path: &Path) -> Result<PathBuf> {
222    resolve_scheduled_workspace_path_with_home(path, dirs::home_dir().as_deref())
223}
224
225pub(crate) fn resolve_scheduled_workspace_path_with_home(path: &Path, home_dir: Option<&Path>) -> Result<PathBuf> {
226    let expanded = expand_scheduled_workspace_home(path, home_dir);
227    let absolute = if expanded.is_absolute() {
228        expanded
229    } else {
230        std::env::current_dir()
231            .context("Failed to resolve current directory for scheduled task workspace")?
232            .join(expanded)
233    };
234    Ok(normalize_path(&absolute))
235}
236
237fn expand_scheduled_workspace_home(path: &Path, home_dir: Option<&Path>) -> PathBuf {
238    let Some(raw) = path.to_str() else {
239        return path.to_path_buf();
240    };
241
242    if raw == "~" {
243        return home_dir.map(Path::to_path_buf).unwrap_or_else(|| path.to_path_buf());
244    }
245
246    if let Some(rest) = raw.strip_prefix("~/")
247        && let Some(home_dir) = home_dir
248    {
249        return home_dir.join(rest);
250    }
251
252    path.to_path_buf()
253}
254
255pub fn parse_session_language_command(input: &str, now: DateTime<Local>) -> Option<Result<SessionLanguageCommand>> {
256    let trimmed = input.trim();
257    if trimmed.is_empty() {
258        return None;
259    }
260
261    let normalized = trimmed.trim_end_matches(['?', '.', '!']).to_ascii_lowercase();
262    if normalized == "what scheduled tasks do i have" {
263        return Some(Ok(SessionLanguageCommand::ListTasks));
264    }
265
266    if let Some(captures) = REMIND_AT_RE.captures(trimmed) {
267        let when = captures.name("when").map(|value| value.as_str()).unwrap_or_default();
268        let prompt = captures
269            .name("prompt")
270            .map(|value| value.as_str().trim().to_string())
271            .unwrap_or_default();
272        return Some(
273            parse_local_datetime(when, now)
274                .map(|run_at| SessionLanguageCommand::CreateOneShotPrompt { prompt, run_at }),
275        );
276    }
277
278    if let Some(captures) = REMIND_IN_RE.captures(trimmed) {
279        let too_far = || anyhow!("Reminder is too far in the future");
280        let Ok(count) = captures["count"].parse::<i64>() else {
281            return Some(Err(too_far()));
282        };
283        let prompt = captures["prompt"].trim().to_string();
284        // Checked constructors: `TimeDelta::{minutes,hours,days}` and `+`
285        // panic on overflow, and the count comes straight from user input.
286        let delta = match captures["unit"].to_ascii_lowercase().as_str() {
287            "minute" | "minutes" => ChronoDuration::try_minutes(count),
288            "hour" | "hours" => ChronoDuration::try_hours(count),
289            "day" | "days" => ChronoDuration::try_days(count),
290            _ => return None,
291        };
292        let Some(delta) = delta else {
293            return Some(Err(too_far()));
294        };
295        let Some(run_at) = now.checked_add_signed(delta) else {
296            return Some(Err(too_far()));
297        };
298        return Some(Ok(SessionLanguageCommand::CreateOneShotPrompt { prompt, run_at: run_at.with_timezone(&Utc) }));
299    }
300
301    if let Some(query) = strip_cancel_prefix(trimmed) {
302        return Some(Ok(SessionLanguageCommand::CancelTask { query: query.trim().to_string() }));
303    }
304
305    None
306}
307
308fn strip_cancel_prefix(trimmed: &str) -> Option<&str> {
309    const PREFIX_LEN: usize = "cancel ".len();
310    if trimmed.len() >= PREFIX_LEN && trimmed[..PREFIX_LEN].eq_ignore_ascii_case("cancel ") {
311        Some(&trimmed[PREFIX_LEN..])
312    } else {
313        None
314    }
315}
316
317pub fn parse_schedule_create_args(args: &str) -> Result<ScheduleCreateInput> {
318    let tokens = shell_words::split(args).with_context(|| format!("Failed to parse arguments: {args}"))?;
319    parse_schedule_create_tokens(&tokens)
320}
321
322pub fn parse_schedule_create_tokens(tokens: &[String]) -> Result<ScheduleCreateInput> {
323    let mut name = None;
324    let mut prompt = None;
325    let mut reminder = None;
326    let mut every = None;
327    let mut cron = None;
328    let mut at = None;
329    let mut workspace = None;
330    let mut index = 0usize;
331
332    while index < tokens.len() {
333        let token = &tokens[index];
334        let (flag, inline_value) = if let Some((left, right)) = token.split_once('=') {
335            (left, Some(right.to_string()))
336        } else {
337            (token.as_str(), None)
338        };
339
340        let take_value = |idx: &mut usize| -> Result<String> {
341            if let Some(value) = inline_value.clone() {
342                return Ok(value);
343            }
344            let Some(value) = tokens.get(*idx + 1) else {
345                bail!("Missing value for {flag}");
346            };
347            *idx += 1;
348            Ok(value.clone())
349        };
350
351        match flag {
352            "--name" => name = Some(take_value(&mut index)?),
353            "--prompt" => prompt = Some(take_value(&mut index)?),
354            "--reminder" => reminder = Some(take_value(&mut index)?),
355            "--every" => every = Some(take_value(&mut index)?),
356            "--cron" => cron = Some(take_value(&mut index)?),
357            "--at" => at = Some(take_value(&mut index)?),
358            "--workspace" => workspace = Some(PathBuf::from(take_value(&mut index)?)),
359            "--help" | "help" => {
360                bail!(
361                    "Usage: /schedule create --prompt <text>|--reminder <text> --every <dur>|--cron <expr>|--at <time> [--name <label>] [--workspace <path>]"
362                );
363            }
364            _ => bail!("Unknown option: {token}"),
365        }
366        index += 1;
367    }
368
369    Ok(ScheduleCreateInput { name, prompt, reminder, every, cron, at, workspace })
370}
371
372pub fn parse_local_datetime(raw: &str, now: DateTime<Local>) -> Result<DateTime<Utc>> {
373    let trimmed = raw.trim();
374    if trimmed.is_empty() {
375        bail!("Time value cannot be empty");
376    }
377
378    if let Ok(parsed) = DateTime::parse_from_rfc3339(trimmed) {
379        return Ok(parsed.with_timezone(&Utc));
380    }
381
382    for format in ["%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M:%S"] {
383        if let Ok(naive) = NaiveDateTime::parse_from_str(trimmed, format) {
384            return localize_naive_datetime(naive).map(|value| value.with_timezone(&Utc));
385        }
386    }
387
388    if let Some(captures) = TIME_ONLY_RE.captures(trimmed) {
389        let mut hour = captures["hour"].parse::<u32>()?;
390        let minute = captures
391            .name("minute")
392            .map(|value| value.as_str().parse::<u32>())
393            .transpose()?
394            .unwrap_or(0);
395        if minute >= 60 {
396            bail!("Invalid minute in time value");
397        }
398        if let Some(ampm) = captures.name("ampm").map(|value| value.as_str().to_ascii_lowercase()) {
399            if hour == 0 || hour > 12 {
400                bail!("Invalid 12-hour clock value");
401            }
402            if ampm == "pm" && hour != 12 {
403                hour += 12;
404            }
405            if ampm == "am" && hour == 12 {
406                hour = 0;
407            }
408        } else if hour >= 24 {
409            bail!("Invalid 24-hour clock value");
410        }
411
412        let time = NaiveTime::from_hms_opt(hour, minute, 0).ok_or_else(|| anyhow!("Invalid time value"))?;
413        let today = now.date_naive();
414        let naive = today.and_time(time);
415        let mut localized = localize_naive_datetime(naive)?;
416        if localized <= now {
417            localized = localize_naive_datetime((today + ChronoDuration::days(1)).and_time(time))?;
418        }
419        return Ok(localized.with_timezone(&Utc));
420    }
421
422    bail!("Unsupported time format. Use RFC3339, YYYY-MM-DD HH:MM, or a local time like 3pm")
423}
424
425fn localize_naive_datetime(naive: NaiveDateTime) -> Result<DateTime<Local>> {
426    match Local.from_local_datetime(&naive) {
427        LocalResult::Single(value) => Ok(value),
428        LocalResult::Ambiguous(first, _) => Ok(first),
429        LocalResult::None => bail!("Local time does not exist due to timezone transition"),
430    }
431}