symbi 1.13.0

AI-native agent framework for building autonomous, policy-aware agents that can safely collaborate with humans, other agents, and large language models
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
//! CLI commands for managing cron-scheduled agent jobs.
//!
//! Provides `symbi cron list|add|remove|pause|resume|status|run|history`.

use clap::ArgMatches;

#[cfg(feature = "cron")]
use symbi_runtime::{CronJobDefinition, CronJobId, JobStore, SqliteJobStore};

/// Entry point for `symbi cron <subcommand>`.
pub async fn run(matches: &ArgMatches) {
    match matches.subcommand() {
        Some(("list", _sub)) => cmd_list().await,
        Some(("add", sub)) => cmd_add(sub).await,
        Some(("remove", sub)) => cmd_remove(sub).await,
        Some(("pause", sub)) => cmd_pause(sub).await,
        Some(("resume", sub)) => cmd_resume(sub).await,
        Some(("status", sub)) => cmd_status(sub).await,
        Some(("run", sub)) => cmd_run(sub).await,
        Some(("history", sub)) => cmd_history(sub).await,
        _ => {
            eprintln!("Unknown cron subcommand. Use --help for usage.");
            std::process::exit(1);
        }
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────

#[cfg(feature = "cron")]
fn open_store() -> Result<SqliteJobStore, String> {
    let path = SqliteJobStore::default_path();
    SqliteJobStore::open(&path).map_err(|e| format!("Failed to open job store: {}", e))
}

#[cfg(feature = "cron")]
fn parse_job_id(s: &str) -> Result<CronJobId, String> {
    s.parse::<CronJobId>()
        .map_err(|e| format!("Invalid job ID '{}': {}", s, e))
}

// ── Subcommands ──────────────────────────────────────────────────────────

async fn cmd_list() {
    #[cfg(feature = "cron")]
    {
        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        let jobs = match store.list_jobs(None).await {
            Ok(j) => j,
            Err(e) => {
                eprintln!("Failed to list jobs: {}", e);
                return;
            }
        };
        if jobs.is_empty() {
            println!("No scheduled jobs.");
            return;
        }
        println!(
            "{:<38} {:<20} {:<10} {:<20} {:<6}",
            "ID", "NAME", "STATUS", "NEXT RUN", "RUNS"
        );
        println!("{}", "-".repeat(100));
        for job in &jobs {
            let next = job
                .next_run
                .map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string())
                .unwrap_or_else(|| "".to_string());
            println!(
                "{:<38} {:<20} {:<10} {:<20} {:<6}",
                job.job_id,
                truncate(&job.name, 18),
                format!("{:?}", job.status),
                next,
                job.run_count,
            );
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_add(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let name = matches.get_one::<String>("name").expect("name required");
        let cron_expr = matches.get_one::<String>("cron").expect("cron required");
        let tz = matches
            .get_one::<String>("tz")
            .map(|s| s.as_str())
            .unwrap_or("UTC");
        let agent_name = matches.get_one::<String>("agent").expect("agent required");
        let one_shot = matches.get_flag("one-shot");

        // Build a minimal AgentConfig — the runtime will resolve the full config on execution.
        let agent_config = symbi_runtime::types::AgentConfig {
            id: symbi_runtime::types::AgentId::new(),
            name: agent_name.clone(),
            dsl_source: String::new(),
            execution_mode: symbi_runtime::types::ExecutionMode::Ephemeral,
            security_tier: symbi_runtime::types::SecurityTier::Tier1,
            resource_limits: symbi_runtime::types::ResourceLimits::default(),
            capabilities: vec![],
            policies: vec![],
            metadata: std::collections::HashMap::new(),
            priority: symbi_runtime::types::Priority::Normal,
        };

        let mut job = CronJobDefinition::new(
            name.clone(),
            cron_expr.clone(),
            tz.to_string(),
            agent_config,
        );
        job.one_shot = one_shot;

        if let Some(policy) = matches.get_one::<String>("policy") {
            job.policy_ids.push(policy.clone());
        }

        // Validate cron expression before saving.
        if let Err(e) = cron_expr.parse::<cron::Schedule>() {
            eprintln!("Invalid cron expression: {}", e);
            std::process::exit(1);
        }

        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };

        // Compute next_run.
        let tz_parsed: chrono_tz::Tz = match tz.parse() {
            Ok(t) => t,
            Err(_) => {
                eprintln!("Invalid timezone: {}", tz);
                std::process::exit(1);
            }
        };
        let now = chrono::Utc::now().with_timezone(&tz_parsed);
        if let Ok(schedule) = cron_expr.parse::<cron::Schedule>() {
            job.next_run = schedule
                .after(&now)
                .next()
                .map(|dt| dt.with_timezone(&chrono::Utc));
        }

        match store.save_job(&job).await {
            Ok(()) => {
                println!("Created job: {}", job.job_id);
                if let Some(nr) = job.next_run {
                    println!("  Next run: {}", nr.format("%Y-%m-%d %H:%M:%S UTC"));
                }
            }
            Err(e) => eprintln!("Failed to create job: {}", e),
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_remove(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let id_str = matches
            .get_one::<String>("job-id")
            .expect("job-id required");
        let job_id = match parse_job_id(id_str) {
            Ok(id) => id,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        match store.delete_job(job_id).await {
            Ok(true) => println!("Removed job {}", job_id),
            Ok(false) => eprintln!("Job {} not found", job_id),
            Err(e) => eprintln!("Failed to remove job: {}", e),
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_pause(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let id_str = matches
            .get_one::<String>("job-id")
            .expect("job-id required");
        let job_id = match parse_job_id(id_str) {
            Ok(id) => id,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        match store.get_job(job_id).await {
            Ok(Some(mut job)) => {
                job.status = symbi_runtime::CronJobStatus::Paused;
                job.enabled = false;
                job.updated_at = chrono::Utc::now();
                if let Err(e) = store.save_job(&job).await {
                    eprintln!("Failed to pause job: {}", e);
                } else {
                    println!("Paused job {}", job_id);
                }
            }
            Ok(None) => eprintln!("Job {} not found", job_id),
            Err(e) => eprintln!("Failed to get job: {}", e),
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_resume(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let id_str = matches
            .get_one::<String>("job-id")
            .expect("job-id required");
        let job_id = match parse_job_id(id_str) {
            Ok(id) => id,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        match store.get_job(job_id).await {
            Ok(Some(mut job)) => {
                job.status = symbi_runtime::CronJobStatus::Active;
                job.enabled = true;
                job.updated_at = chrono::Utc::now();
                if let Err(e) = store.save_job(&job).await {
                    eprintln!("Failed to resume job: {}", e);
                } else {
                    println!("Resumed job {}", job_id);
                }
            }
            Ok(None) => eprintln!("Job {} not found", job_id),
            Err(e) => eprintln!("Failed to get job: {}", e),
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_status(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let id_str = matches
            .get_one::<String>("job-id")
            .expect("job-id required");
        let job_id = match parse_job_id(id_str) {
            Ok(id) => id,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        match store.get_job(job_id).await {
            Ok(Some(job)) => {
                println!("Job:        {}", job.job_id);
                println!("Name:       {}", job.name);
                println!("Cron:       {}", job.cron_expression);
                println!("Timezone:   {}", job.timezone);
                println!("Status:     {:?}", job.status);
                println!("Enabled:    {}", job.enabled);
                println!("One-shot:   {}", job.one_shot);
                println!("Runs:       {}", job.run_count);
                println!("Failures:   {}", job.failure_count);
                println!(
                    "Created:    {}",
                    job.created_at.format("%Y-%m-%d %H:%M:%S UTC")
                );
                println!(
                    "Updated:    {}",
                    job.updated_at.format("%Y-%m-%d %H:%M:%S UTC")
                );
                if let Some(lr) = job.last_run {
                    println!("Last run:   {}", lr.format("%Y-%m-%d %H:%M:%S UTC"));
                }
                if let Some(nr) = job.next_run {
                    println!("Next run:   {}", nr.format("%Y-%m-%d %H:%M:%S UTC"));
                }

                // Show recent history.
                match store.get_run_history(job_id, 5).await {
                    Ok(history) if !history.is_empty() => {
                        println!("\nRecent runs:");
                        for run in &history {
                            let duration = run
                                .execution_time_ms
                                .map(|ms| format!("{}ms", ms))
                                .unwrap_or_else(|| "".to_string());
                            println!(
                                "  {} | {} | {} | {}",
                                run.started_at.format("%Y-%m-%d %H:%M:%S"),
                                run.status,
                                duration,
                                run.error.as_deref().unwrap_or(""),
                            );
                        }
                    }
                    _ => {}
                }
            }
            Ok(None) => eprintln!("Job {} not found", job_id),
            Err(e) => eprintln!("Failed to get job: {}", e),
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_run(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let id_str = matches
            .get_one::<String>("job-id")
            .expect("job-id required");
        let job_id = match parse_job_id(id_str) {
            Ok(id) => id,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        // Force-triggering requires a running CronScheduler (with an AgentScheduler).
        // For offline use, we just validate the job exists.
        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };
        match store.get_job(job_id).await {
            Ok(Some(_)) => {
                println!(
                    "Job {} exists. Force-trigger requires a running runtime (symbi up).",
                    job_id
                );
                println!(
                    "Connect to the runtime API to trigger: POST /schedules/{}/trigger",
                    job_id
                );
            }
            Ok(None) => eprintln!("Job {} not found", job_id),
            Err(e) => eprintln!("Failed to get job: {}", e),
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

async fn cmd_history(matches: &ArgMatches) {
    #[cfg(feature = "cron")]
    {
        let limit = matches
            .get_one::<String>("limit")
            .and_then(|s| s.parse::<usize>().ok())
            .unwrap_or(20);

        let store = match open_store() {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}", e);
                return;
            }
        };

        if let Some(id_str) = matches.get_one::<String>("job") {
            // History for a specific job.
            let job_id = match parse_job_id(id_str) {
                Ok(id) => id,
                Err(e) => {
                    eprintln!("{}", e);
                    return;
                }
            };
            match store.get_run_history(job_id, limit).await {
                Ok(history) => print_history(&history),
                Err(e) => eprintln!("Failed to get history: {}", e),
            }
        } else {
            // History across all jobs — list each job's recent history.
            match store.list_jobs(None).await {
                Ok(jobs) => {
                    for job in &jobs {
                        match store.get_run_history(job.job_id, limit).await {
                            Ok(history) if !history.is_empty() => {
                                println!("=== {} ({}) ===", job.name, job.job_id);
                                print_history(&history);
                                println!();
                            }
                            _ => {}
                        }
                    }
                }
                Err(e) => eprintln!("Failed to list jobs: {}", e),
            }
        }
    }
    #[cfg(not(feature = "cron"))]
    {
        let _ = matches;
        eprintln!("Cron feature is not enabled. Rebuild with --features cron");
    }
}

#[cfg(feature = "cron")]
fn print_history(history: &[symbi_runtime::JobRunRecord]) {
    if history.is_empty() {
        println!("No run history.");
        return;
    }
    println!(
        "{:<20} {:<38} {:<12} {:<10} ERROR",
        "STARTED", "RUN ID", "STATUS", "DURATION"
    );
    for run in history {
        let duration = run
            .execution_time_ms
            .map(|ms| format!("{}ms", ms))
            .unwrap_or_else(|| "".to_string());
        println!(
            "{:<20} {:<38} {:<12} {:<10} {}",
            run.started_at.format("%Y-%m-%d %H:%M:%S"),
            run.run_id,
            run.status.to_string(),
            duration,
            run.error.as_deref().unwrap_or(""),
        );
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.len() > max {
        format!("{}", &s[..max - 1])
    } else {
        s.to_string()
    }
}