moadim 0.17.0

Loop engine for AI agents — cron jobs and routines over REST, MCP, and a built-in web UI
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Data-plane CLI subcommands.
//!
//! These mirror the daemon's `/api/v1` REST routes (and the MCP tools) so every action is reachable
//! from the command line too. Each subcommand is a thin client: it serializes its flags into the
//! same JSON the REST API expects, sends it to the running server over the loopback HTTP client in
//! [`crate::cli`], and prints the server's response. The daemon must already be running
//! (`moadim` / `moadim -i`); when it is not, these commands report that and exit
//! [`crate::cli::EXIT_NOT_RUNNING`].

use clap::{Parser, Subcommand};
use serde_json::{Map, Value};

/// Top-level parser for the data-plane subcommands, parsed from argv with the leading `moadim`
/// binary name already stripped (`no_binary_name`), so the first token is the subcommand keyword.
#[derive(Parser)]
#[command(
    name = "moadim",
    version,
    no_binary_name = true,
    about = "moadim data commands"
)]
struct DataCli {
    /// The selected data subcommand.
    #[command(subcommand)]
    command: DataCommand,
}

/// The data subcommand groups: cron jobs, routines, agents, and echo.
#[derive(Subcommand)]
enum DataCommand {
    /// Manage cron jobs (create/list/get/update/replace/delete/trigger/logs).
    #[command(subcommand, visible_alias = "cron")]
    CronJobs(CronCmd),
    /// Manage routines (create/list/get/update/replace/delete/trigger/logs/ical).
    #[command(subcommand, visible_alias = "routine")]
    Routines(RoutineCmd),
    /// Trigger a routine on its schedule by ID (invoked by the generated crontab line).
    #[command(subcommand, visible_alias = "sched")]
    Schedule(ScheduleCmd),
    /// List the available agent registry keys.
    Agents,
    /// Echo a message back via the server, with a server timestamp.
    Echo {
        /// The message to echo.
        message: String,
    },
}

/// Cron-job operations, each mapping to a `/api/v1/cron-jobs` REST route.
#[derive(Subcommand)]
enum CronCmd {
    /// Create a new cron job.
    Create {
        /// Cron expression (host local timezone, not UTC).
        #[arg(long)]
        schedule: String,
        /// Handler identifier to invoke when the schedule fires.
        #[arg(long)]
        handler: String,
        /// Optional metadata as a JSON value (object/array/scalar).
        #[arg(long)]
        metadata: Option<String>,
        /// Machines to run this job on, as a JSON array (e.g. `["work","server"]`). Empty/omitted
        /// means the job runs on no machine until assigned.
        #[arg(long)]
        machines: Option<String>,
        /// Create the job disabled instead of enabled (the default).
        #[arg(long)]
        disabled: bool,
    },
    /// List all cron jobs.
    List,
    /// Get a single cron job by ID.
    Get {
        /// UUID of the cron job.
        id: String,
    },
    /// Update fields of an existing cron job (only the flags you pass change).
    Update {
        /// UUID of the cron job to update.
        id: String,
        /// New cron expression (host local timezone, not UTC).
        #[arg(long)]
        schedule: Option<String>,
        /// New handler identifier.
        #[arg(long)]
        handler: Option<String>,
        /// New metadata as a JSON value.
        #[arg(long)]
        metadata: Option<String>,
        /// New machines targeting list as a JSON array (e.g. `["work","server"]`).
        #[arg(long)]
        machines: Option<String>,
        /// New enabled state (`true`/`false`).
        #[arg(long)]
        enabled: Option<bool>,
    },
    /// Replace a cron job wholesale (all fields, like create but for an existing ID).
    Replace {
        /// UUID of the cron job to replace.
        id: String,
        /// Cron expression (host local timezone, not UTC).
        #[arg(long)]
        schedule: String,
        /// Handler identifier to invoke when the schedule fires.
        #[arg(long)]
        handler: String,
        /// Optional metadata as a JSON value.
        #[arg(long)]
        metadata: Option<String>,
        /// Machines to run this job on, as a JSON array (e.g. `["work","server"]`).
        #[arg(long)]
        machines: Option<String>,
        /// Replace into a disabled state instead of enabled (the default).
        #[arg(long)]
        disabled: bool,
    },
    /// Delete a cron job by ID.
    Delete {
        /// UUID of the cron job to delete.
        id: String,
    },
    /// Manually trigger a cron job outside its schedule.
    Trigger {
        /// UUID of the cron job to trigger.
        id: String,
    },
    /// Print a cron job's log file.
    Logs {
        /// UUID of the cron job whose logs to print.
        id: String,
    },
}

/// Schedule operations driven by the OS crontab, keyed only by ID.
#[derive(Subcommand)]
enum ScheduleCmd {
    /// Run a routine on its schedule by ID.
    ///
    /// This is what the generated crontab line invokes at each fire time. It records a *scheduled*
    /// trigger (not a manual one), so it maps to the routine's `scheduled-trigger` route rather than
    /// the manual `trigger` route.
    Trigger {
        /// UUID of the routine to trigger.
        id: String,
    },
}

/// Routine operations, each mapping to a `/api/v1/routines` REST route.
#[derive(Subcommand)]
enum RoutineCmd {
    /// Create a new routine.
    Create {
        /// Cron expression (host local timezone, not UTC).
        #[arg(long)]
        schedule: String,
        /// Human-readable title.
        #[arg(long)]
        title: String,
        /// Agent registry key to launch.
        #[arg(long)]
        agent: String,
        /// Task prompt.
        #[arg(long)]
        prompt: String,
        /// Repositories as a JSON array (e.g. `[{"repository":"url","branch":"main"}]`).
        #[arg(long)]
        repositories: Option<String>,
        /// Machines to run this routine on, as a JSON array (e.g. `["work","server"]`). Empty/omitted
        /// means the routine runs on no machine until assigned.
        #[arg(long)]
        machines: Option<String>,
        /// Workbench TTL in seconds for finished runs.
        #[arg(long)]
        ttl_secs: Option<u64>,
        /// Max runtime in seconds before the watchdog kills a run.
        #[arg(long)]
        max_runtime_secs: Option<u64>,
        /// Create the routine disabled instead of enabled (the default).
        #[arg(long)]
        disabled: bool,
    },
    /// List all routines.
    List,
    /// Get a single routine by ID.
    Get {
        /// UUID of the routine.
        id: String,
    },
    /// Update fields of an existing routine (only the flags you pass change).
    Update {
        /// UUID of the routine to update.
        id: String,
        /// New cron expression (host local timezone, not UTC).
        #[arg(long)]
        schedule: Option<String>,
        /// New title.
        #[arg(long)]
        title: Option<String>,
        /// New agent registry key.
        #[arg(long)]
        agent: Option<String>,
        /// New prompt.
        #[arg(long)]
        prompt: Option<String>,
        /// New repositories as a JSON array.
        #[arg(long)]
        repositories: Option<String>,
        /// New machines targeting list as a JSON array (e.g. `["work","server"]`).
        #[arg(long)]
        machines: Option<String>,
        /// New enabled state (`true`/`false`).
        #[arg(long)]
        enabled: Option<bool>,
        /// New workbench TTL in seconds.
        #[arg(long)]
        ttl_secs: Option<u64>,
        /// New max runtime in seconds.
        #[arg(long)]
        max_runtime_secs: Option<u64>,
    },
    /// Replace a routine wholesale (all fields, like create but for an existing ID).
    Replace {
        /// UUID of the routine to replace.
        id: String,
        /// Cron expression (host local timezone, not UTC).
        #[arg(long)]
        schedule: String,
        /// Human-readable title.
        #[arg(long)]
        title: String,
        /// Agent registry key to launch.
        #[arg(long)]
        agent: String,
        /// Task prompt.
        #[arg(long)]
        prompt: String,
        /// Repositories as a JSON array.
        #[arg(long)]
        repositories: Option<String>,
        /// Machines to run this routine on, as a JSON array (e.g. `["work","server"]`).
        #[arg(long)]
        machines: Option<String>,
        /// Workbench TTL in seconds for finished runs.
        #[arg(long)]
        ttl_secs: Option<u64>,
        /// Max runtime in seconds before the watchdog kills a run.
        #[arg(long)]
        max_runtime_secs: Option<u64>,
        /// Replace into a disabled state instead of enabled (the default).
        #[arg(long)]
        disabled: bool,
    },
    /// Delete a routine by ID.
    Delete {
        /// UUID of the routine to delete.
        id: String,
    },
    /// Manually trigger a routine outside its schedule.
    Trigger {
        /// UUID of the routine to trigger.
        id: String,
    },
    /// Print a routine's newest run log.
    Logs {
        /// UUID of the routine whose logs to print.
        id: String,
    },
    /// Print the iCalendar feed of upcoming routine fire times.
    Ical,
}

/// Parse `args` (argv with the binary name stripped) and run the selected data subcommand against
/// the running server, returning the process exit code to surface.
///
/// On a clap parse error (bad flags, `--help`, `--version`) the formatted message is printed and the
/// matching code returned (`0` for help/version, `2` for a usage error), mirroring clap conventions
/// without aborting the process so the path stays unit-testable.
pub fn run(args: Vec<String>) -> i32 {
    match DataCli::try_parse_from(args) {
        Ok(cli) => dispatch(cli.command),
        Err(err) => {
            let _ = err.print();
            match err.kind() {
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => 0,
                _ => 2,
            }
        }
    }
}

/// Route a parsed [`DataCommand`] to the matching REST call.
fn dispatch(command: DataCommand) -> i32 {
    match command {
        DataCommand::CronJobs(cmd) => dispatch_cron(cmd),
        DataCommand::Routines(cmd) => dispatch_routine(cmd),
        DataCommand::Schedule(ScheduleCmd::Trigger { id }) => request(
            "POST",
            &format!("{}/scheduled-trigger", routine_path(&id)),
            None,
        ),
        DataCommand::Agents => request("GET", "/api/v1/agents", None),
        DataCommand::Echo { message } => {
            let body = object([("message", Value::String(message))]);
            request("POST", "/api/v1/echo", Some(&body))
        }
    }
}

/// Route a parsed [`CronCmd`] to the matching `/cron-jobs` REST call.
fn dispatch_cron(cmd: CronCmd) -> i32 {
    match cmd {
        CronCmd::Create {
            schedule,
            handler,
            metadata,
            machines,
            disabled,
        } => match cron_body(schedule, handler, metadata, machines, disabled) {
            Ok(body) => request("POST", "/api/v1/cron-jobs", Some(&body)),
            Err(code) => code,
        },
        CronCmd::List => request("GET", "/api/v1/cron-jobs", None),
        CronCmd::Get { id } => request("GET", &cron_path(&id), None),
        CronCmd::Update {
            id,
            schedule,
            handler,
            metadata,
            machines,
            enabled,
        } => {
            let mut map = Map::new();
            insert_opt(&mut map, "schedule", schedule.map(Value::String));
            insert_opt(&mut map, "handler", handler.map(Value::String));
            match insert_json_opt(&mut map, "metadata", metadata) {
                Ok(()) => {}
                Err(code) => return code,
            }
            match insert_json_opt(&mut map, "machines", machines) {
                Ok(()) => {}
                Err(code) => return code,
            }
            insert_opt(&mut map, "enabled", enabled.map(Value::Bool));
            request("PATCH", &cron_path(&id), Some(&to_body(map)))
        }
        CronCmd::Replace {
            id,
            schedule,
            handler,
            metadata,
            machines,
            disabled,
        } => match cron_body(schedule, handler, metadata, machines, disabled) {
            Ok(body) => request("PUT", &cron_path(&id), Some(&body)),
            Err(code) => code,
        },
        CronCmd::Delete { id } => request("DELETE", &cron_path(&id), None),
        CronCmd::Trigger { id } => request("POST", &format!("{}/trigger", cron_path(&id)), None),
        CronCmd::Logs { id } => request("GET", &format!("{}/logs", cron_path(&id)), None),
    }
}

/// Route a parsed [`RoutineCmd`] to the matching `/routines` REST call.
fn dispatch_routine(cmd: RoutineCmd) -> i32 {
    match cmd {
        RoutineCmd::Create {
            schedule,
            title,
            agent,
            prompt,
            repositories,
            machines,
            ttl_secs,
            max_runtime_secs,
            disabled,
        } => match routine_body(
            schedule,
            title,
            agent,
            prompt,
            repositories,
            machines,
            ttl_secs,
            max_runtime_secs,
            disabled,
        ) {
            Ok(body) => request("POST", "/api/v1/routines", Some(&body)),
            Err(code) => code,
        },
        RoutineCmd::List => request("GET", "/api/v1/routines", None),
        RoutineCmd::Get { id } => request("GET", &routine_path(&id), None),
        RoutineCmd::Update {
            id,
            schedule,
            title,
            agent,
            prompt,
            repositories,
            machines,
            enabled,
            ttl_secs,
            max_runtime_secs,
        } => {
            let mut map = Map::new();
            insert_opt(&mut map, "schedule", schedule.map(Value::String));
            insert_opt(&mut map, "title", title.map(Value::String));
            insert_opt(&mut map, "agent", agent.map(Value::String));
            insert_opt(&mut map, "prompt", prompt.map(Value::String));
            match insert_json_opt(&mut map, "repositories", repositories) {
                Ok(()) => {}
                Err(code) => return code,
            }
            match insert_json_opt(&mut map, "machines", machines) {
                Ok(()) => {}
                Err(code) => return code,
            }
            insert_opt(&mut map, "enabled", enabled.map(Value::Bool));
            insert_opt(&mut map, "ttl_secs", ttl_secs.map(Value::from));
            insert_opt(
                &mut map,
                "max_runtime_secs",
                max_runtime_secs.map(Value::from),
            );
            request("PATCH", &routine_path(&id), Some(&to_body(map)))
        }
        RoutineCmd::Replace {
            id,
            schedule,
            title,
            agent,
            prompt,
            repositories,
            machines,
            ttl_secs,
            max_runtime_secs,
            disabled,
        } => match routine_body(
            schedule,
            title,
            agent,
            prompt,
            repositories,
            machines,
            ttl_secs,
            max_runtime_secs,
            disabled,
        ) {
            Ok(body) => request("PUT", &routine_path(&id), Some(&body)),
            Err(code) => code,
        },
        RoutineCmd::Delete { id } => request("DELETE", &routine_path(&id), None),
        RoutineCmd::Trigger { id } => {
            request("POST", &format!("{}/trigger", routine_path(&id)), None)
        }
        RoutineCmd::Logs { id } => request("GET", &format!("{}/logs", routine_path(&id)), None),
        RoutineCmd::Ical => request("GET", "/api/v1/routines.ics", None),
    }
}

/// Build the `/api/v1/cron-jobs/{id}` path for a job ID.
fn cron_path(id: &str) -> String {
    format!("/api/v1/cron-jobs/{id}")
}

/// Build the `/api/v1/routines/{id}` path for a routine ID.
fn routine_path(id: &str) -> String {
    format!("/api/v1/routines/{id}")
}

/// Build the full create/replace JSON body for a cron job, validating optional `metadata` as JSON.
/// Returns the serialized body, or an exit code (`2`) when `metadata` is not valid JSON.
fn cron_body(
    schedule: String,
    handler: String,
    metadata: Option<String>,
    machines: Option<String>,
    disabled: bool,
) -> Result<String, i32> {
    let mut map = Map::new();
    map.insert("schedule".to_string(), Value::String(schedule));
    map.insert("handler".to_string(), Value::String(handler));
    insert_json_opt(&mut map, "metadata", metadata)?;
    insert_json_opt(&mut map, "machines", machines)?;
    map.insert("enabled".to_string(), Value::Bool(!disabled));
    Ok(to_body(map))
}

/// Build the full create/replace JSON body for a routine, validating optional `repositories` as a
/// JSON array. Returns the serialized body, or an exit code (`2`) when `repositories` is invalid.
#[allow(clippy::too_many_arguments)]
fn routine_body(
    schedule: String,
    title: String,
    agent: String,
    prompt: String,
    repositories: Option<String>,
    machines: Option<String>,
    ttl_secs: Option<u64>,
    max_runtime_secs: Option<u64>,
    disabled: bool,
) -> Result<String, i32> {
    let mut map = Map::new();
    map.insert("schedule".to_string(), Value::String(schedule));
    map.insert("title".to_string(), Value::String(title));
    map.insert("agent".to_string(), Value::String(agent));
    map.insert("prompt".to_string(), Value::String(prompt));
    insert_json_opt(&mut map, "repositories", repositories)?;
    insert_json_opt(&mut map, "machines", machines)?;
    insert_opt(&mut map, "ttl_secs", ttl_secs.map(Value::from));
    insert_opt(
        &mut map,
        "max_runtime_secs",
        max_runtime_secs.map(Value::from),
    );
    map.insert("enabled".to_string(), Value::Bool(!disabled));
    Ok(to_body(map))
}

/// Insert `key => value` into `map` only when `value` is `Some`, leaving the key absent otherwise so
/// PATCH bodies carry just the fields the user supplied.
fn insert_opt(map: &mut Map<String, Value>, key: &str, value: Option<Value>) {
    if let Some(value) = value {
        map.insert(key.to_string(), value);
    }
}

/// Parse an optional raw-JSON flag and insert it under `key` when present. Returns an exit code
/// (`2`) and prints a diagnostic when the supplied string is not valid JSON.
fn insert_json_opt(
    map: &mut Map<String, Value>,
    key: &str,
    raw: Option<String>,
) -> Result<(), i32> {
    let Some(raw) = raw else { return Ok(()) };
    match serde_json::from_str::<Value>(&raw) {
        Ok(value) => {
            map.insert(key.to_string(), value);
            Ok(())
        }
        Err(err) => {
            eprintln!("error: --{key} is not valid JSON: {err}");
            Err(2)
        }
    }
}

/// Build a small JSON object body from key/value pairs.
fn object<const N: usize>(pairs: [(&str, Value); N]) -> String {
    let mut map = Map::new();
    for (key, value) in pairs {
        map.insert(key.to_string(), value);
    }
    to_body(map)
}

/// Serialize a JSON object map into a compact request body string.
fn to_body(map: Map<String, Value>) -> String {
    Value::Object(map).to_string()
}

/// Send `method path` (with optional JSON `body`) to the running server, print the response, and map
/// it to a process exit code: `0` on a 2xx, `1` on any other HTTP status (the server's error body is
/// printed to stderr), and [`crate::cli::EXIT_NOT_RUNNING`] when no server is reachable.
fn request(method: &str, path: &str, body: Option<&str>) -> i32 {
    match crate::cli::http_request_json(method, path, body) {
        Ok((status, resp)) if (200..300).contains(&status) => {
            print_body(&resp);
            0
        }
        Ok((status, resp)) => {
            eprintln!("error: server returned HTTP {status}");
            if !resp.is_empty() {
                eprintln!("{resp}");
            }
            1
        }
        Err(_) => {
            eprintln!("moadim is not running");
            crate::cli::EXIT_NOT_RUNNING
        }
    }
}

/// Print a successful response body, pretty-printing it when it parses as JSON and echoing it raw
/// (e.g. plain-text logs / iCalendar feeds) otherwise.
fn print_body(body: &str) {
    if body.is_empty() {
        return;
    }
    match serde_json::from_str::<Value>(body) {
        Ok(value) => println!(
            "{}",
            serde_json::to_string_pretty(&value).unwrap_or_default()
        ),
        Err(_) => println!("{body}"),
    }
}

#[cfg(test)]
#[path = "commands_tests.rs"]
mod commands_tests;