eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! The `cronjob_manage` tool: the agent scheduling work for later.
//!
//! The tool manages the same `cron/jobs.toml` the CLI writes, through the same
//! [`crate::cron`] functions, so a job the agent creates is a job you can read, edit and delete
//! by hand — and one you did not want is one line to remove.
//!
//! It deliberately cannot *run* a job. Running one starts another agent, inside this one, on a
//! timer's authority instead of yours; that belongs to the tick the systemd timer invokes, where
//! there is a lock and a log file. `run_now` here means "when the next tick comes", and says so.

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};

/// How much of a job's prompt the approval prompt shows: long enough to read what it does, short
/// enough to sit on the same line as the schedule, the directory and the delivery path.
const PROMPT_CLIP: usize = 160;

pub struct CronTool {
    root: PathBuf,
    /// Where the job itself will be allowed to work. A job the agent creates runs later, alone,
    /// with every `ask` tool auto-approved and its tools rooted at a directory the model chose —
    /// so that directory is confined here, the one moment a person is in the loop.
    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
    }
}

/// A field sent with the wrong type is an error, not a default: `as_str` used to turn a `route`
/// of `7` into "no route" and a `deliver` of `true` into "no file", silently.
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)
        ))),
    }
}

/// Confine a path the timer will expand later. `~` is refused rather than resolved: the tick
/// expands it against its own home, so a check here would approve one directory while the job ran
/// in another.
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" => {
                // Everything the job will do, because the approval is the only human gate in
                // this flow: after it, a recurring unattended agent runs where it was told to,
                // with every `ask` tool auto-approved and its answer written where it chose.
                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() {
                        // `{:?}` keeps a multi-line prompt on this one line and marks the cut.
                        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")?;
                // A field sent with the wrong type is refused rather than dropped. A job whose
                // `deliver` was silently ignored writes nowhere, and the person who approved it
                // was told that it would.
                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)?;
                    }
                }
                // Built through the same `Draft` the CLI's form fills in, so this tool gets the
                // checks a person's `cron add` gets — the schedule parses, the workdir is a
                // directory, the name is usable. It used to build a `Job` by hand and skip every
                // one of them.
                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)?;
                // Read it back before claiming it: a file this tool wrote is a file `list` must
                // be able to read.
                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();
                // Rewrite the one block, rather than the whole file: a rewrite would drop the
                // comments a person wrote next to their other jobs.
                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) {
        // The counter, not just pid and millisecond: these tests run in parallel threads of one
        // process, and two of them sharing a root delete each other's files.
        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();
        // The job's own workspace is a subdirectory, which is what a real profile does: the
        // directory a job may work in is inside the one the run is confined to.
        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"]
        }));
        // The approval is the only human gate in this flow, so every field that decides what
        // runs later has to be in the sentence the gate shows.
        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}");
        // A long prompt is cut, and the cut is marked rather than silent.
        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}");
        // `~` is expanded by the timer with the tick's own home, so it cannot be checked here and
        // is refused rather than approved as if it were the path named.
        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}");
        // Nothing was written by either refusal.
        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);
    }
}