Skip to main content

eclipse_core/
tools_cron.rs

1//! The `cronjob_manage` tool: the agent scheduling work for later.
2//!
3//! The tool manages the same `cron/jobs.toml` the CLI writes, through the same
4//! [`crate::cron`] functions, so a job the agent creates is a job you can read, edit and delete
5//! by hand — and one you did not want is one line to remove.
6//!
7//! It deliberately cannot *run* a job. Running one starts another agent, inside this one, on a
8//! timer's authority instead of yours; that belongs to the tick the systemd timer invokes, where
9//! there is a lock and a log file. `run_now` here means "when the next tick comes", and says so.
10
11use crate::cron::{self, Job, State};
12use crate::tools::{str_arg, Tool, ToolError};
13use async_trait::async_trait;
14use serde_json::{json, Value};
15use std::path::{Path, PathBuf};
16
17/// How much of a job's prompt the approval prompt shows: long enough to read what it does, short
18/// enough to sit on the same line as the schedule, the directory and the delivery path.
19const PROMPT_CLIP: usize = 160;
20
21pub struct CronTool {
22    root: PathBuf,
23    /// Where the job itself will be allowed to work. A job the agent creates runs later, alone,
24    /// with every `ask` tool auto-approved and its tools rooted at a directory the model chose —
25    /// so that directory is confined here, the one moment a person is in the loop.
26    workspace: PathBuf,
27}
28
29impl CronTool {
30    pub fn new(root: PathBuf, workspace: PathBuf) -> Self {
31        Self { root, workspace }
32    }
33
34    fn describe_job(job: &Job, state: &State, now: i64) -> String {
35        let s = state.get(&job.name);
36        let mut line = format!("{} ({})", job.name, job.schedule.describe());
37        if !job.enabled {
38            line.push_str(" [disabled]");
39        }
40        match cron::next_due_for(job, state, now) {
41            None => line.push_str(" — never"),
42            Some(ms) => {
43                let (y, mo, d, h, mi) = cron::local_parts(ms);
44                line.push_str(&format!(" — next {y:04}-{mo:02}-{d:02} {h:02}:{mi:02}"));
45            }
46        }
47        match (&s.last_outcome, s.last_started_ms) {
48            (Some(outcome), Some(_)) => {
49                line.push_str(&format!(", last {} ({} runs)", outcome, s.runs))
50            }
51            (None, _) => line.push_str(", never run"),
52            (Some(outcome), None) => line.push_str(&format!(", last {outcome}")),
53        }
54        if let Some(deliver) = &job.deliver {
55            line.push_str(&format!(", writes {deliver}"));
56        }
57        line
58    }
59}
60
61/// A field sent with the wrong type is an error, not a default: `as_str` used to turn a `route`
62/// of `7` into "no route" and a `deliver` of `true` into "no file", silently.
63fn kind(v: &Value) -> &'static str {
64    match v {
65        Value::Null => "null",
66        Value::Bool(_) => "a boolean",
67        Value::Number(_) => "a number",
68        Value::String(_) => "a string",
69        Value::Array(_) => "a list",
70        Value::Object(_) => "an object",
71    }
72}
73
74fn opt_string(args: &Value, key: &str) -> Result<Option<String>, ToolError> {
75    match args.get(key) {
76        None | Some(Value::Null) => Ok(None),
77        Some(Value::String(s)) => Ok(Some(s.clone())),
78        Some(other) => Err(ToolError::InvalidArgs(format!(
79            "`{key}` must be a string, but it is {}",
80            kind(other)
81        ))),
82    }
83}
84
85fn skills_arg(args: &Value) -> Result<Vec<String>, ToolError> {
86    match args.get("skills") {
87        None | Some(Value::Null) => Ok(Vec::new()),
88        Some(Value::Array(items)) => items
89            .iter()
90            .map(|v| match v {
91                Value::String(s) => Ok(s.clone()),
92                other => Err(ToolError::InvalidArgs(format!(
93                    "`skills` must be a list of names, but it holds {}",
94                    kind(other)
95                ))),
96            })
97            .collect(),
98        Some(other) => Err(ToolError::InvalidArgs(format!(
99            "`skills` must be a list of names, but it is {}",
100            kind(other)
101        ))),
102    }
103}
104
105/// Confine a path the timer will expand later. `~` is refused rather than resolved: the tick
106/// expands it against its own home, so a check here would approve one directory while the job ran
107/// in another.
108fn in_workspace(workspace: &Path, key: &str, requested: &str) -> Result<(), ToolError> {
109    if requested.trim().starts_with('~') {
110        return Err(ToolError::InvalidArgs(format!(
111            "`{key}` is expanded by the timer, so `{requested}` cannot be checked here; give a path \
112             inside the workspace ({})",
113            workspace.display()
114        )));
115    }
116    crate::tools::confine(workspace, requested)
117        .map(|_| ())
118        .map_err(|e| match e {
119            ToolError::Failed(why) => ToolError::InvalidArgs(format!("`{key}` {why}")),
120            other => other,
121        })
122}
123
124fn clip(text: &str, cap: usize) -> String {
125    if text.chars().count() <= cap {
126        return text.to_string();
127    }
128    let mut cut: String = text.chars().take(cap).collect();
129    cut.push('…');
130    cut
131}
132
133#[async_trait]
134impl Tool for CronTool {
135    fn name(&self) -> &str {
136        "cronjob_manage"
137    }
138
139    fn description(&self) -> &str {
140        "Schedule prompts to run later, on a timer: list what is scheduled, add a job, remove \
141one, or pause one. Jobs live in cron/jobs.toml and run when the systemd timer ticks — this \
142does not execute a job now, it decides what will run. Schedules are local time: `every 30m`, \
143`hourly`, `daily 07:30`, `weekly mon 09:00`. Use it for recurring work the user asked to have \
144happen without them (a morning summary, a nightly check); not for a one-off task, which is \
145just this conversation."
146    }
147
148    fn parameters(&self) -> Value {
149        json!({
150            "type": "object",
151            "properties": {
152                "action": {
153                    "type": "string",
154                    "enum": ["list", "add", "remove", "pause", "resume"],
155                    "description": "list what is scheduled; add a job; remove one; pause or resume one"
156                },
157                "name": {
158                    "type": "string",
159                    "description": "The job's name: letters, digits, `-` and `_`. Required for everything but list."
160                },
161                "schedule": {
162                    "type": "string",
163                    "description": "For add: `every 30m`, `hourly`, `daily 07:30` or `weekly mon 09:00`, in local time."
164                },
165                "prompt": {
166                    "type": "string",
167                    "description": "For add: the instructions the job runs. It starts a fresh conversation each time, so it must stand alone — say where any context comes from."
168                },
169                "deliver": {
170                    "type": "string",
171                    "description": "For add: also write the reply to this file, inside the workspace, e.g. `reports/brief.md`. Without it the reply goes only to the run log. No `~`, because the timer expands it and the path could not be checked."
172                },
173                "route": {
174                    "type": "string",
175                    "description": "For add: pin the job to one route instead of following the config's fallback chain."
176                },
177                "workdir": {
178                    "type": "string",
179                    "description": "For add: the directory the job starts in, when it needs to touch files. It must exist and be inside the workspace: the job runs there, alone, with every ask auto-approved."
180                },
181                "skills": {
182                    "type": "array",
183                    "items": { "type": "string" },
184                    "description": "For add: skills the job loads before it starts."
185                },
186                "schema": {
187                    "type": "object",
188                    "description": "For add: a JSON schema the reply must be shaped like. It goes into the request as `response_format`, and a reply that is not a JSON document fails the job — useful when something downstream parses the log."
189                }
190            },
191            "required": ["action"]
192        })
193    }
194
195    fn describe_call(&self, args: &Value) -> String {
196        let action = args["action"].as_str().unwrap_or("?");
197        let name = args["name"].as_str().unwrap_or("");
198        match action {
199            "add" => {
200                // Everything the job will do, because the approval is the only human gate in
201                // this flow: after it, a recurring unattended agent runs where it was told to,
202                // with every `ask` tool auto-approved and its answer written where it chose.
203                let mut line = format!(
204                    "cronjob_manage add {name} ({}) — permanent: every run is unattended and \
205                     every ask is auto-approved",
206                    args["schedule"].as_str().unwrap_or("?")
207                );
208                if let Some(prompt) = args["prompt"].as_str() {
209                    if !prompt.trim().is_empty() {
210                        // `{:?}` keeps a multi-line prompt on this one line and marks the cut.
211                        line.push_str(&format!("; prompt {:?}", clip(prompt, PROMPT_CLIP)));
212                    }
213                }
214                for key in ["workdir", "deliver", "route"] {
215                    if let Some(v) = args[key].as_str() {
216                        if !v.is_empty() {
217                            line.push_str(&format!("; {key} {v}"));
218                        }
219                    }
220                }
221                match args["skills"].as_array() {
222                    Some(skills) if !skills.is_empty() => {
223                        line.push_str(&format!("; {} skill(s)", skills.len()))
224                    }
225                    _ => {}
226                }
227                if args["schema"].is_object() {
228                    line.push_str("; reply shaped by a schema");
229                }
230                line
231            }
232            _ => format!("cronjob_manage {action} {name}")
233                .trim_end()
234                .to_string(),
235        }
236    }
237
238    async fn call(&self, args: Value) -> Result<String, ToolError> {
239        let action = str_arg(&args, "action")?;
240        let fail = |e: crate::Error| ToolError::Failed(e.to_string());
241        let now = crate::session::now_ms() as i64;
242        match action {
243            "list" => {
244                let jobs = cron::load(&self.root).map_err(fail)?;
245                let state = cron::load_state(&self.root).map_err(fail)?;
246                if jobs.is_empty() {
247                    return Ok(format!(
248                        "no jobs are scheduled ({} does not exist yet)",
249                        cron::jobs_path(&self.root).display()
250                    ));
251                }
252                let mut out = format!(
253                    "{} jobs in {}:\n",
254                    jobs.len(),
255                    cron::jobs_path(&self.root).display()
256                );
257                for job in &jobs {
258                    out.push_str(&format!("- {}\n", Self::describe_job(job, &state, now)));
259                }
260                Ok(out)
261            }
262            "add" => {
263                let name = str_arg(&args, "name")?;
264                let schedule = str_arg(&args, "schedule")?;
265                let prompt = str_arg(&args, "prompt")?;
266                // A field sent with the wrong type is refused rather than dropped. A job whose
267                // `deliver` was silently ignored writes nowhere, and the person who approved it
268                // was told that it would.
269                let route = opt_string(&args, "route")?;
270                let workdir = opt_string(&args, "workdir")?;
271                let deliver = opt_string(&args, "deliver")?;
272                let skills = skills_arg(&args)?;
273                let schema = match args.get("schema") {
274                    None | Some(Value::Null) => None,
275                    Some(v) if v.is_object() => Some(v.to_string()),
276                    Some(other) => {
277                        return Err(ToolError::InvalidArgs(format!(
278                            "`schema` must be an object, but it is {}",
279                            kind(other)
280                        )))
281                    }
282                };
283                for (key, value) in [("workdir", &workdir), ("deliver", &deliver)] {
284                    if let Some(v) = value {
285                        in_workspace(&self.workspace, key, v)?;
286                    }
287                }
288                // Built through the same `Draft` the CLI's form fills in, so this tool gets the
289                // checks a person's `cron add` gets — the schedule parses, the workdir is a
290                // directory, the name is usable. It used to build a `Job` by hand and skip every
291                // one of them.
292                let job = cron::Draft {
293                    name: name.to_string(),
294                    schedule: schedule.to_string(),
295                    prompt: prompt.to_string(),
296                    enabled: true,
297                    route,
298                    workdir,
299                    skills,
300                    deliver,
301                    schema,
302                }
303                .to_job()
304                .map_err(fail)?;
305                cron::append_job(&self.root, &job).map_err(fail)?;
306                // Read it back before claiming it: a file this tool wrote is a file `list` must
307                // be able to read.
308                let jobs = cron::load(&self.root).map_err(fail)?;
309                let state = cron::load_state(&self.root).map_err(fail)?;
310                let stored = jobs.iter().find(|j| j.name == job.name).ok_or_else(|| {
311                    ToolError::Failed("the job did not survive being written".into())
312                })?;
313                Ok(format!(
314                    "added {}\nIt is permanent and unattended: when it fires it starts a fresh \
315                     conversation where every `ask` tool is auto-approved. `eclipse cron run {}` \
316                     runs it now, by hand; `eclipse cron remove {}` stops it for good.",
317                    Self::describe_job(stored, &state, now),
318                    job.name,
319                    job.name
320                ))
321            }
322            "remove" => {
323                let name = str_arg(&args, "name")?;
324                if cron::remove_job(&self.root, name).map_err(fail)? {
325                    Ok(format!(
326                        "removed {name}. Its run logs are still in {}",
327                        cron::runs_dir(&self.root, name).display()
328                    ))
329                } else {
330                    Err(ToolError::Failed(format!("no job named `{name}`")))
331                }
332            }
333            "pause" | "resume" => {
334                let name = str_arg(&args, "name")?;
335                let mut jobs = cron::load(&self.root).map_err(fail)?;
336                let job = jobs
337                    .iter_mut()
338                    .find(|j| j.name == name)
339                    .ok_or_else(|| ToolError::Failed(format!("no job named `{name}`")))?;
340                let want = action == "resume";
341                if job.enabled == want {
342                    return Ok(format!(
343                        "{name} is already {}",
344                        if want { "running" } else { "paused" }
345                    ));
346                }
347                job.enabled = want;
348                let job = job.clone();
349                // Rewrite the one block, rather than the whole file: a rewrite would drop the
350                // comments a person wrote next to their other jobs.
351                cron::replace_job(&self.root, &job).map_err(fail)?;
352                Ok(format!(
353                    "{name} is now {}. {}",
354                    if want { "enabled" } else { "paused" },
355                    if want {
356                        "The next tick will pick it up."
357                    } else {
358                        "Its history and logs stay."
359                    }
360                ))
361            }
362            other => Err(ToolError::InvalidArgs(format!(
363                "unknown action {other:?}: use list, add, remove, pause or resume"
364            ))),
365        }
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372    use crate::tools::Tool;
373
374    fn tool() -> (CronTool, PathBuf) {
375        // The counter, not just pid and millisecond: these tests run in parallel threads of one
376        // process, and two of them sharing a root delete each other's files.
377        static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
378        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
379        let root = std::env::temp_dir().join(format!(
380            "eclipse-cron-tool-{}-{}-{n}",
381            std::process::id(),
382            crate::session::now_ms()
383        ));
384        std::fs::create_dir_all(&root).unwrap();
385        // The job's own workspace is a subdirectory, which is what a real profile does: the
386        // directory a job may work in is inside the one the run is confined to.
387        let workspace = root.join("work");
388        std::fs::create_dir_all(&workspace).unwrap();
389        (CronTool::new(root.clone(), workspace), root)
390    }
391
392    #[tokio::test]
393    async fn adding_a_job_writes_it_and_listing_shows_it() {
394        let (t, root) = tool();
395        let out = t
396            .call(json!({
397                "action": "add",
398                "name": "brief",
399                "schedule": "daily 07:30",
400                "prompt": "Summarise the overnight changes",
401                "deliver": "work/brief.md"
402            }))
403            .await
404            .unwrap();
405        assert!(out.contains("added brief (daily 07:30)"), "{out}");
406        assert!(out.contains("permanent and unattended"), "{out}");
407        let listed = t.call(json!({"action": "list"})).await.unwrap();
408        assert!(listed.contains("brief (daily 07:30)"), "{listed}");
409        assert!(listed.contains("never run"), "{listed}");
410        let _ = std::fs::remove_dir_all(&root);
411    }
412
413    #[test]
414    fn pausing_rewrites_one_block_and_leaves_the_others_alone() {
415        let (t, root) = tool();
416        let rt = tokio::runtime::Builder::new_current_thread()
417            .build()
418            .unwrap();
419        rt.block_on(async {
420            for name in ["one", "two"] {
421                t.call(json!({
422                    "action": "add", "name": name, "schedule": "every 30m", "prompt": "p"
423                }))
424                .await
425                .unwrap();
426            }
427        });
428        std::fs::write(
429            cron::jobs_path(&root),
430            format!(
431                "{}\n# a comment a person wrote\n",
432                std::fs::read_to_string(cron::jobs_path(&root)).unwrap()
433            ),
434        )
435        .unwrap();
436        rt.block_on(async {
437            let out = t
438                .call(json!({"action": "pause", "name": "one"}))
439                .await
440                .unwrap();
441            assert!(out.contains("paused"), "{out}");
442        });
443        let text = std::fs::read_to_string(cron::jobs_path(&root)).unwrap();
444        assert!(
445            text.contains("# a comment a person wrote"),
446            "comments survive"
447        );
448        let jobs = cron::load(&root).unwrap();
449        assert!(!jobs[0].enabled, "one is paused");
450        assert!(jobs[1].enabled, "two is untouched");
451        let _ = std::fs::remove_dir_all(&root);
452    }
453
454    #[tokio::test]
455    async fn a_bad_schedule_says_what_schedules_exist() {
456        let (t, root) = tool();
457        let err = t
458            .call(json!({"action": "add", "name": "x", "schedule": "every tuesday", "prompt": "p"}))
459            .await
460            .unwrap_err()
461            .to_string();
462        assert!(err.contains("unrecognised schedule"), "{err}");
463        let _ = std::fs::remove_dir_all(&root);
464    }
465
466    #[tokio::test]
467    async fn removing_something_that_is_not_there_says_so() {
468        let (t, root) = tool();
469        let err = t
470            .call(json!({"action": "remove", "name": "ghost"}))
471            .await
472            .unwrap_err()
473            .to_string();
474        assert!(err.contains("no job named `ghost`"), "{err}");
475        let _ = std::fs::remove_dir_all(&root);
476    }
477
478    #[tokio::test]
479    async fn the_approval_prompt_names_what_the_job_will_actually_do() {
480        let (t, _root) = tool();
481        let line = t.describe_call(&json!({
482            "action": "add",
483            "name": "backup",
484            "schedule": "daily 03:00",
485            "prompt": "Back up /mnt/media to the NAS, then prune anything older than 30 days",
486            "workdir": "work",
487            "deliver": "work/backup.md",
488            "route": "mmnuc/inkling-2-mini",
489            "skills": ["ops"]
490        }));
491        // The approval is the only human gate in this flow, so every field that decides what
492        // runs later has to be in the sentence the gate shows.
493        assert!(line.contains("permanent"), "{line}");
494        assert!(line.contains("auto-approved"), "{line}");
495        assert!(line.contains("Back up /mnt/media"), "{line}");
496        assert!(line.contains("workdir work"), "{line}");
497        assert!(line.contains("deliver work/backup.md"), "{line}");
498        assert!(line.contains("route mmnuc/inkling-2-mini"), "{line}");
499        assert!(line.contains("1 skill(s)"), "{line}");
500        assert!(!line.contains('\n'), "the gate shows one line: {line}");
501        // A long prompt is cut, and the cut is marked rather than silent.
502        let long = t.describe_call(&json!({
503            "action": "add", "name": "x", "schedule": "hourly", "prompt": "a".repeat(400)
504        }));
505        assert!(long.contains('…'), "{long}");
506        assert!(long.chars().count() < 400, "{long}");
507    }
508
509    #[tokio::test]
510    async fn a_job_cannot_be_pointed_outside_the_workspace_it_was_approved_for() {
511        let (t, root) = tool();
512        let err = t
513            .call(json!({
514                "action": "add", "name": "escape", "schedule": "hourly", "prompt": "p",
515                "workdir": "/"
516            }))
517            .await
518            .unwrap_err()
519            .to_string();
520        assert!(err.contains("outside the workspace"), "{err}");
521        // `~` is expanded by the timer with the tick's own home, so it cannot be checked here and
522        // is refused rather than approved as if it were the path named.
523        let err = t
524            .call(json!({
525                "action": "add", "name": "tilde", "schedule": "hourly", "prompt": "p",
526                "deliver": "~/notes/brief.md"
527            }))
528            .await
529            .unwrap_err()
530            .to_string();
531        assert!(err.contains("expanded by the timer"), "{err}");
532        let _ = std::fs::remove_dir_all(&root);
533    }
534
535    #[tokio::test]
536    async fn a_field_of_the_wrong_type_is_refused_not_ignored() {
537        let (t, root) = tool();
538        let err = t
539            .call(json!({
540                "action": "add", "name": "typed", "schedule": "hourly", "prompt": "p",
541                "deliver": true
542            }))
543            .await
544            .unwrap_err()
545            .to_string();
546        assert!(err.contains("`deliver` must be a string"), "{err}");
547        let err = t
548            .call(json!({
549                "action": "add", "name": "typed", "schedule": "hourly", "prompt": "p",
550                "skills": "ops"
551            }))
552            .await
553            .unwrap_err()
554            .to_string();
555        assert!(err.contains("`skills` must be a list"), "{err}");
556        // Nothing was written by either refusal.
557        assert!(cron::load(&root).unwrap().is_empty());
558        let _ = std::fs::remove_dir_all(&root);
559    }
560
561    #[tokio::test]
562    async fn a_workspace_that_is_not_a_directory_is_refused_before_the_job_exists() {
563        let (t, root) = tool();
564        let err = t
565            .call(json!({
566                "action": "add", "name": "typo", "schedule": "hourly", "prompt": "p",
567                "workdir": "work/not-there"
568            }))
569            .await
570            .unwrap_err()
571            .to_string();
572        assert!(err.contains("not a directory"), "{err}");
573        assert!(cron::load(&root).unwrap().is_empty());
574        let _ = std::fs::remove_dir_all(&root);
575    }
576}