Skip to main content

vtcode_core/scheduler/
daemon.rs

1use anyhow::{Context, Result};
2use chrono::{DateTime, Utc};
3use std::path::PathBuf;
4use std::process::Stdio;
5use std::time::Duration;
6use tokio::process::Command;
7
8use super::advance_record_runtime;
9use super::session::resolve_scheduled_workspace_path;
10use super::spec::{ScheduledTaskAction, ScheduledTaskDefinition, ScheduledTaskRecord, TaskRunStatus};
11use super::store::{DurableTaskStore, release_claim_async, try_acquire_claim_async};
12use crate::notifications::{NotificationEvent, send_global_notification};
13use vtcode_commons::VtCodePaths;
14
15#[derive(Debug, Clone)]
16pub struct SchedulerDaemon {
17    store: DurableTaskStore,
18    executable_path: PathBuf,
19}
20
21impl SchedulerDaemon {
22    #[must_use]
23    pub fn new(store: DurableTaskStore, executable_path: PathBuf) -> Self {
24        Self { store, executable_path }
25    }
26
27    pub async fn serve_forever(&self) -> Result<()> {
28        loop {
29            // A failing sweep (transient I/O, store hiccup) must never stop
30            // the daemon: log it and keep the 1s cadence so healthy tasks
31            // keep firing.
32            if let Err(error) = self.run_due_tasks_once().await {
33                tracing::warn!(error = %error, "Scheduled task sweep failed; continuing");
34            }
35            tokio::time::sleep(Duration::from_secs(1)).await;
36        }
37    }
38
39    pub async fn run_due_tasks_once(&self) -> Result<usize> {
40        let now = Utc::now();
41        let mut records = self.store.load_records_async().await?;
42        let mut executed = 0usize;
43
44        records.sort_by_key(|record| record.runtime.next_run_at);
45        for mut record in records {
46            let Some(next_run_at) = record.runtime.next_run_at else {
47                continue;
48            };
49            if now < next_run_at {
50                continue;
51            }
52            if !try_acquire_claim_async(self.store.paths().clone(), record.definition.id.clone()).await? {
53                continue;
54            }
55
56            let result = self.execute_record(&record, now).await;
57            let release_result = release_claim_async(self.store.paths().clone(), record.definition.id.clone()).await;
58            let run_outcome = result?;
59            release_result?;
60
61            apply_run_outcome(&mut record, run_outcome)?;
62            self.store.update_runtime_async(record).await?;
63            executed = executed.saturating_add(1);
64        }
65
66        Ok(executed)
67    }
68
69    async fn execute_record(&self, record: &ScheduledTaskRecord, run_at: DateTime<Utc>) -> Result<RunOutcome> {
70        match &record.definition.action {
71            ScheduledTaskAction::Reminder { message } => {
72                let notification = send_global_notification(NotificationEvent::IdlePrompt {
73                    title: format!("Scheduled reminder: {}", record.definition.name),
74                    message: message.clone(),
75                })
76                .await;
77                let status = match notification {
78                    Ok(()) => TaskRunStatus::ReminderSent,
79                    Err(error) => TaskRunStatus::Failed {
80                        message: format!("failed to send reminder notification: {error:#}"),
81                    },
82                };
83                Ok(RunOutcome {
84                    ran_at: run_at,
85                    status,
86                    artifact_dir: None,
87                    events_file: None,
88                    last_message_file: None,
89                })
90            }
91            ScheduledTaskAction::Prompt { prompt } => {
92                let artifact_dir = self.store.paths().artifact_dir(&record.definition.id, run_at);
93                let events_file = artifact_dir.join("events.jsonl");
94                let last_message_file = artifact_dir.join("last-message.txt");
95                let workspace_label = scheduled_workspace_label(&record.definition);
96                let workspace = resolve_scheduled_task_workspace(&record.definition);
97                let execution = async {
98                    VtCodePaths::ensure_user_dir(&artifact_dir)
99                        .with_context(|| format!("Failed to create run artifact dir {}", artifact_dir.display()))?;
100
101                    let mut command = Command::new(&self.executable_path);
102                    command
103                        .arg("exec")
104                        .arg("--events")
105                        .arg(&events_file)
106                        .arg("--last-message-file")
107                        .arg(&last_message_file)
108                        .arg(prompt)
109                        .stdin(Stdio::null())
110                        .stdout(Stdio::null())
111                        .stderr(Stdio::null());
112
113                    if let Some(workspace) = workspace? {
114                        command.current_dir(&workspace);
115                    }
116
117                    command.status().await.with_context(|| {
118                        format!(
119                            "Failed to spawn scheduled VT Code exec for task {} using {} in {}",
120                            record.definition.id,
121                            self.executable_path.display(),
122                            workspace_label
123                        )
124                    })
125                }
126                .await;
127                let run_status = match execution {
128                    Ok(status) if status.success() => TaskRunStatus::Success,
129                    Ok(status) => TaskRunStatus::Failed {
130                        message: format!("vtcode exec exited with {status}"),
131                    },
132                    Err(error) => TaskRunStatus::Failed { message: format!("{error:#}") },
133                };
134                Ok(RunOutcome {
135                    ran_at: run_at,
136                    status: run_status,
137                    artifact_dir: artifact_dir.is_dir().then_some(artifact_dir),
138                    events_file: events_file.is_file().then_some(events_file),
139                    last_message_file: last_message_file.is_file().then_some(last_message_file),
140                })
141            }
142        }
143    }
144}
145
146fn apply_run_outcome(record: &mut ScheduledTaskRecord, outcome: RunOutcome) -> Result<()> {
147    let RunOutcome {
148        ran_at,
149        status,
150        artifact_dir,
151        events_file,
152        last_message_file,
153    } = outcome;
154
155    record.runtime.last_artifact_dir = artifact_dir;
156    record.runtime.last_events_file = events_file;
157    record.runtime.last_message_file = last_message_file;
158
159    advance_record_runtime(record, ran_at, status)?;
160
161    Ok(())
162}
163
164#[derive(Debug, Clone)]
165struct RunOutcome {
166    ran_at: DateTime<Utc>,
167    status: TaskRunStatus,
168    artifact_dir: Option<PathBuf>,
169    events_file: Option<PathBuf>,
170    last_message_file: Option<PathBuf>,
171}
172
173fn scheduled_workspace_label(definition: &ScheduledTaskDefinition) -> String {
174    definition
175        .workspace
176        .as_ref()
177        .map(|path| path.display().to_string())
178        .unwrap_or_else(|| "<none>".to_string())
179}
180
181fn resolve_scheduled_task_workspace(definition: &ScheduledTaskDefinition) -> Result<Option<PathBuf>> {
182    definition
183        .workspace
184        .as_deref()
185        .map(resolve_scheduled_workspace_path)
186        .transpose()
187        .with_context(|| {
188            format!(
189                "Failed to resolve scheduled task workspace {} for task {}",
190                scheduled_workspace_label(definition),
191                definition.id
192            )
193        })
194}