use crate::cron::{self, Job, State};
use crate::tools::{str_arg, Tool, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
const PROMPT_CLIP: usize = 160;
pub struct CronTool {
root: PathBuf,
workspace: PathBuf,
}
impl CronTool {
pub fn new(root: PathBuf, workspace: PathBuf) -> Self {
Self { root, workspace }
}
fn describe_job(job: &Job, state: &State, now: i64) -> String {
let s = state.get(&job.name);
let mut line = format!("{} ({})", job.name, job.schedule.describe());
if !job.enabled {
line.push_str(" [disabled]");
}
match cron::next_due_for(job, state, now) {
None => line.push_str(" — never"),
Some(ms) => {
let (y, mo, d, h, mi) = cron::local_parts(ms);
line.push_str(&format!(" — next {y:04}-{mo:02}-{d:02} {h:02}:{mi:02}"));
}
}
match (&s.last_outcome, s.last_started_ms) {
(Some(outcome), Some(_)) => {
line.push_str(&format!(", last {} ({} runs)", outcome, s.runs))
}
(None, _) => line.push_str(", never run"),
(Some(outcome), None) => line.push_str(&format!(", last {outcome}")),
}
if let Some(deliver) = &job.deliver {
line.push_str(&format!(", writes {deliver}"));
}
line
}
}
fn kind(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "a boolean",
Value::Number(_) => "a number",
Value::String(_) => "a string",
Value::Array(_) => "a list",
Value::Object(_) => "an object",
}
}
fn opt_string(args: &Value, key: &str) -> Result<Option<String>, ToolError> {
match args.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(other) => Err(ToolError::InvalidArgs(format!(
"`{key}` must be a string, but it is {}",
kind(other)
))),
}
}
fn skills_arg(args: &Value) -> Result<Vec<String>, ToolError> {
match args.get("skills") {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::Array(items)) => items
.iter()
.map(|v| match v {
Value::String(s) => Ok(s.clone()),
other => Err(ToolError::InvalidArgs(format!(
"`skills` must be a list of names, but it holds {}",
kind(other)
))),
})
.collect(),
Some(other) => Err(ToolError::InvalidArgs(format!(
"`skills` must be a list of names, but it is {}",
kind(other)
))),
}
}
fn in_workspace(workspace: &Path, key: &str, requested: &str) -> Result<(), ToolError> {
if requested.trim().starts_with('~') {
return Err(ToolError::InvalidArgs(format!(
"`{key}` is expanded by the timer, so `{requested}` cannot be checked here; give a path \
inside the workspace ({})",
workspace.display()
)));
}
crate::tools::confine(workspace, requested)
.map(|_| ())
.map_err(|e| match e {
ToolError::Failed(why) => ToolError::InvalidArgs(format!("`{key}` {why}")),
other => other,
})
}
fn clip(text: &str, cap: usize) -> String {
if text.chars().count() <= cap {
return text.to_string();
}
let mut cut: String = text.chars().take(cap).collect();
cut.push('…');
cut
}
#[async_trait]
impl Tool for CronTool {
fn name(&self) -> &str {
"cronjob_manage"
}
fn description(&self) -> &str {
"Schedule prompts to run later, on a timer: list what is scheduled, add a job, remove \
one, or pause one. Jobs live in cron/jobs.toml and run when the systemd timer ticks — this \
does not execute a job now, it decides what will run. Schedules are local time: `every 30m`, \
`hourly`, `daily 07:30`, `weekly mon 09:00`. Use it for recurring work the user asked to have \
happen without them (a morning summary, a nightly check); not for a one-off task, which is \
just this conversation."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["list", "add", "remove", "pause", "resume"],
"description": "list what is scheduled; add a job; remove one; pause or resume one"
},
"name": {
"type": "string",
"description": "The job's name: letters, digits, `-` and `_`. Required for everything but list."
},
"schedule": {
"type": "string",
"description": "For add: `every 30m`, `hourly`, `daily 07:30` or `weekly mon 09:00`, in local time."
},
"prompt": {
"type": "string",
"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."
},
"deliver": {
"type": "string",
"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."
},
"route": {
"type": "string",
"description": "For add: pin the job to one route instead of following the config's fallback chain."
},
"workdir": {
"type": "string",
"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."
},
"skills": {
"type": "array",
"items": { "type": "string" },
"description": "For add: skills the job loads before it starts."
},
"schema": {
"type": "object",
"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."
}
},
"required": ["action"]
})
}
fn describe_call(&self, args: &Value) -> String {
let action = args["action"].as_str().unwrap_or("?");
let name = args["name"].as_str().unwrap_or("");
match action {
"add" => {
let mut line = format!(
"cronjob_manage add {name} ({}) — permanent: every run is unattended and \
every ask is auto-approved",
args["schedule"].as_str().unwrap_or("?")
);
if let Some(prompt) = args["prompt"].as_str() {
if !prompt.trim().is_empty() {
line.push_str(&format!("; prompt {:?}", clip(prompt, PROMPT_CLIP)));
}
}
for key in ["workdir", "deliver", "route"] {
if let Some(v) = args[key].as_str() {
if !v.is_empty() {
line.push_str(&format!("; {key} {v}"));
}
}
}
match args["skills"].as_array() {
Some(skills) if !skills.is_empty() => {
line.push_str(&format!("; {} skill(s)", skills.len()))
}
_ => {}
}
if args["schema"].is_object() {
line.push_str("; reply shaped by a schema");
}
line
}
_ => format!("cronjob_manage {action} {name}")
.trim_end()
.to_string(),
}
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let action = str_arg(&args, "action")?;
let fail = |e: crate::Error| ToolError::Failed(e.to_string());
let now = crate::session::now_ms() as i64;
match action {
"list" => {
let jobs = cron::load(&self.root).map_err(fail)?;
let state = cron::load_state(&self.root).map_err(fail)?;
if jobs.is_empty() {
return Ok(format!(
"no jobs are scheduled ({} does not exist yet)",
cron::jobs_path(&self.root).display()
));
}
let mut out = format!(
"{} jobs in {}:\n",
jobs.len(),
cron::jobs_path(&self.root).display()
);
for job in &jobs {
out.push_str(&format!("- {}\n", Self::describe_job(job, &state, now)));
}
Ok(out)
}
"add" => {
let name = str_arg(&args, "name")?;
let schedule = str_arg(&args, "schedule")?;
let prompt = str_arg(&args, "prompt")?;
let route = opt_string(&args, "route")?;
let workdir = opt_string(&args, "workdir")?;
let deliver = opt_string(&args, "deliver")?;
let skills = skills_arg(&args)?;
let schema = match args.get("schema") {
None | Some(Value::Null) => None,
Some(v) if v.is_object() => Some(v.to_string()),
Some(other) => {
return Err(ToolError::InvalidArgs(format!(
"`schema` must be an object, but it is {}",
kind(other)
)))
}
};
for (key, value) in [("workdir", &workdir), ("deliver", &deliver)] {
if let Some(v) = value {
in_workspace(&self.workspace, key, v)?;
}
}
let job = cron::Draft {
name: name.to_string(),
schedule: schedule.to_string(),
prompt: prompt.to_string(),
enabled: true,
route,
workdir,
skills,
deliver,
schema,
}
.to_job()
.map_err(fail)?;
cron::append_job(&self.root, &job).map_err(fail)?;
let jobs = cron::load(&self.root).map_err(fail)?;
let state = cron::load_state(&self.root).map_err(fail)?;
let stored = jobs.iter().find(|j| j.name == job.name).ok_or_else(|| {
ToolError::Failed("the job did not survive being written".into())
})?;
Ok(format!(
"added {}\nIt is permanent and unattended: when it fires it starts a fresh \
conversation where every `ask` tool is auto-approved. `eclipse cron run {}` \
runs it now, by hand; `eclipse cron remove {}` stops it for good.",
Self::describe_job(stored, &state, now),
job.name,
job.name
))
}
"remove" => {
let name = str_arg(&args, "name")?;
if cron::remove_job(&self.root, name).map_err(fail)? {
Ok(format!(
"removed {name}. Its run logs are still in {}",
cron::runs_dir(&self.root, name).display()
))
} else {
Err(ToolError::Failed(format!("no job named `{name}`")))
}
}
"pause" | "resume" => {
let name = str_arg(&args, "name")?;
let mut jobs = cron::load(&self.root).map_err(fail)?;
let job = jobs
.iter_mut()
.find(|j| j.name == name)
.ok_or_else(|| ToolError::Failed(format!("no job named `{name}`")))?;
let want = action == "resume";
if job.enabled == want {
return Ok(format!(
"{name} is already {}",
if want { "running" } else { "paused" }
));
}
job.enabled = want;
let job = job.clone();
cron::replace_job(&self.root, &job).map_err(fail)?;
Ok(format!(
"{name} is now {}. {}",
if want { "enabled" } else { "paused" },
if want {
"The next tick will pick it up."
} else {
"Its history and logs stay."
}
))
}
other => Err(ToolError::InvalidArgs(format!(
"unknown action {other:?}: use list, add, remove, pause or resume"
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tools::Tool;
fn tool() -> (CronTool, PathBuf) {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let root = std::env::temp_dir().join(format!(
"eclipse-cron-tool-{}-{}-{n}",
std::process::id(),
crate::session::now_ms()
));
std::fs::create_dir_all(&root).unwrap();
let workspace = root.join("work");
std::fs::create_dir_all(&workspace).unwrap();
(CronTool::new(root.clone(), workspace), root)
}
#[tokio::test]
async fn adding_a_job_writes_it_and_listing_shows_it() {
let (t, root) = tool();
let out = t
.call(json!({
"action": "add",
"name": "brief",
"schedule": "daily 07:30",
"prompt": "Summarise the overnight changes",
"deliver": "work/brief.md"
}))
.await
.unwrap();
assert!(out.contains("added brief (daily 07:30)"), "{out}");
assert!(out.contains("permanent and unattended"), "{out}");
let listed = t.call(json!({"action": "list"})).await.unwrap();
assert!(listed.contains("brief (daily 07:30)"), "{listed}");
assert!(listed.contains("never run"), "{listed}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn pausing_rewrites_one_block_and_leaves_the_others_alone() {
let (t, root) = tool();
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
rt.block_on(async {
for name in ["one", "two"] {
t.call(json!({
"action": "add", "name": name, "schedule": "every 30m", "prompt": "p"
}))
.await
.unwrap();
}
});
std::fs::write(
cron::jobs_path(&root),
format!(
"{}\n# a comment a person wrote\n",
std::fs::read_to_string(cron::jobs_path(&root)).unwrap()
),
)
.unwrap();
rt.block_on(async {
let out = t
.call(json!({"action": "pause", "name": "one"}))
.await
.unwrap();
assert!(out.contains("paused"), "{out}");
});
let text = std::fs::read_to_string(cron::jobs_path(&root)).unwrap();
assert!(
text.contains("# a comment a person wrote"),
"comments survive"
);
let jobs = cron::load(&root).unwrap();
assert!(!jobs[0].enabled, "one is paused");
assert!(jobs[1].enabled, "two is untouched");
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn a_bad_schedule_says_what_schedules_exist() {
let (t, root) = tool();
let err = t
.call(json!({"action": "add", "name": "x", "schedule": "every tuesday", "prompt": "p"}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("unrecognised schedule"), "{err}");
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn removing_something_that_is_not_there_says_so() {
let (t, root) = tool();
let err = t
.call(json!({"action": "remove", "name": "ghost"}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("no job named `ghost`"), "{err}");
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn the_approval_prompt_names_what_the_job_will_actually_do() {
let (t, _root) = tool();
let line = t.describe_call(&json!({
"action": "add",
"name": "backup",
"schedule": "daily 03:00",
"prompt": "Back up /mnt/media to the NAS, then prune anything older than 30 days",
"workdir": "work",
"deliver": "work/backup.md",
"route": "mmnuc/inkling-2-mini",
"skills": ["ops"]
}));
assert!(line.contains("permanent"), "{line}");
assert!(line.contains("auto-approved"), "{line}");
assert!(line.contains("Back up /mnt/media"), "{line}");
assert!(line.contains("workdir work"), "{line}");
assert!(line.contains("deliver work/backup.md"), "{line}");
assert!(line.contains("route mmnuc/inkling-2-mini"), "{line}");
assert!(line.contains("1 skill(s)"), "{line}");
assert!(!line.contains('\n'), "the gate shows one line: {line}");
let long = t.describe_call(&json!({
"action": "add", "name": "x", "schedule": "hourly", "prompt": "a".repeat(400)
}));
assert!(long.contains('…'), "{long}");
assert!(long.chars().count() < 400, "{long}");
}
#[tokio::test]
async fn a_job_cannot_be_pointed_outside_the_workspace_it_was_approved_for() {
let (t, root) = tool();
let err = t
.call(json!({
"action": "add", "name": "escape", "schedule": "hourly", "prompt": "p",
"workdir": "/"
}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("outside the workspace"), "{err}");
let err = t
.call(json!({
"action": "add", "name": "tilde", "schedule": "hourly", "prompt": "p",
"deliver": "~/notes/brief.md"
}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("expanded by the timer"), "{err}");
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn a_field_of_the_wrong_type_is_refused_not_ignored() {
let (t, root) = tool();
let err = t
.call(json!({
"action": "add", "name": "typed", "schedule": "hourly", "prompt": "p",
"deliver": true
}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("`deliver` must be a string"), "{err}");
let err = t
.call(json!({
"action": "add", "name": "typed", "schedule": "hourly", "prompt": "p",
"skills": "ops"
}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("`skills` must be a list"), "{err}");
assert!(cron::load(&root).unwrap().is_empty());
let _ = std::fs::remove_dir_all(&root);
}
#[tokio::test]
async fn a_workspace_that_is_not_a_directory_is_refused_before_the_job_exists() {
let (t, root) = tool();
let err = t
.call(json!({
"action": "add", "name": "typo", "schedule": "hourly", "prompt": "p",
"workdir": "work/not-there"
}))
.await
.unwrap_err()
.to_string();
assert!(err.contains("not a directory"), "{err}");
assert!(cron::load(&root).unwrap().is_empty());
let _ = std::fs::remove_dir_all(&root);
}
}