Implement cron job management tools and types

- Added `JobType`, `SessionTarget`, `Schedule`, `DeliveryConfig`, `CronJob`, `CronRun`, and `CronJobPatch` types in `src/cron/types.rs` for cron job configuration and management.
- Introduced `CronAddTool`, `CronListTool`, `CronRemoveTool`, `CronRunTool`, `CronRunsTool`, and `CronUpdateTool` in `src/tools` for adding, listing, removing, running, and updating cron jobs.
- Updated the `run` function in `src/daemon/mod.rs` to conditionally start the scheduler based on the cron configuration.
- Modified command-line argument parsing in `src/lib.rs` and `src/main.rs` to support new cron job commands.
- Enhanced the onboarding wizard in `src/onboard/wizard.rs` to include cron configuration.
- Added tests for cron job tools to ensure functionality and error handling.
This commit is contained in:
mai1015 2026-02-16 20:35:20 -05:00 committed by Chummy
parent 0ec46ac3d1
commit fb2d1cea0b
24 changed files with 2682 additions and 638 deletions

326
src/tools/cron_add.rs Normal file
View file

@ -0,0 +1,326 @@
use super::traits::{Tool, ToolResult};
use crate::config::Config;
use crate::cron::{self, DeliveryConfig, JobType, Schedule, SessionTarget};
use crate::security::SecurityPolicy;
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
pub struct CronAddTool {
config: Arc<Config>,
security: Arc<SecurityPolicy>,
}
impl CronAddTool {
pub fn new(config: Arc<Config>, security: Arc<SecurityPolicy>) -> Self {
Self { config, security }
}
}
#[async_trait]
impl Tool for CronAddTool {
fn name(&self) -> &str {
"cron_add"
}
fn description(&self) -> &str {
"Create a scheduled cron job (shell or agent) with cron/at/every schedules"
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"name": { "type": "string" },
"schedule": {
"type": "object",
"description": "Schedule object: {kind:'cron',expr,tz?} | {kind:'at',at} | {kind:'every',every_ms}"
},
"job_type": { "type": "string", "enum": ["shell", "agent"] },
"command": { "type": "string" },
"prompt": { "type": "string" },
"session_target": { "type": "string", "enum": ["isolated", "main"] },
"model": { "type": "string" },
"delivery": { "type": "object" },
"delete_after_run": { "type": "boolean" }
},
"required": ["schedule"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
if !self.config.cron.enabled {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("cron is disabled by config (cron.enabled=false)".to_string()),
});
}
let schedule = match args.get("schedule") {
Some(v) => match serde_json::from_value::<Schedule>(v.clone()) {
Ok(schedule) => schedule,
Err(e) => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Invalid schedule: {e}")),
});
}
},
None => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'schedule' parameter".to_string()),
});
}
};
let name = args
.get("name")
.and_then(serde_json::Value::as_str)
.map(str::to_string);
let job_type = match args.get("job_type").and_then(serde_json::Value::as_str) {
Some("agent") => JobType::Agent,
Some("shell") => JobType::Shell,
Some(other) => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Invalid job_type: {other}")),
});
}
None => {
if args.get("prompt").is_some() {
JobType::Agent
} else {
JobType::Shell
}
}
};
let default_delete_after_run = matches!(schedule, Schedule::At { .. });
let delete_after_run = args
.get("delete_after_run")
.and_then(serde_json::Value::as_bool)
.unwrap_or(default_delete_after_run);
let result = match job_type {
JobType::Shell => {
let command = match args.get("command").and_then(serde_json::Value::as_str) {
Some(command) if !command.trim().is_empty() => command,
_ => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'command' for shell job".to_string()),
});
}
};
if !self.security.is_command_allowed(command) {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Command blocked by security policy: {command}")),
});
}
cron::add_shell_job(&self.config, name, schedule, command)
}
JobType::Agent => {
let prompt = match args.get("prompt").and_then(serde_json::Value::as_str) {
Some(prompt) if !prompt.trim().is_empty() => prompt,
_ => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'prompt' for agent job".to_string()),
});
}
};
let session_target = match args.get("session_target") {
Some(v) => match serde_json::from_value::<SessionTarget>(v.clone()) {
Ok(target) => target,
Err(e) => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Invalid session_target: {e}")),
});
}
},
None => SessionTarget::Isolated,
};
let model = args
.get("model")
.and_then(serde_json::Value::as_str)
.map(str::to_string);
let delivery = match args.get("delivery") {
Some(v) => match serde_json::from_value::<DeliveryConfig>(v.clone()) {
Ok(cfg) => Some(cfg),
Err(e) => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Invalid delivery config: {e}")),
});
}
},
None => None,
};
cron::add_agent_job(
&self.config,
name,
schedule,
prompt,
session_target,
model,
delivery,
delete_after_run,
)
}
};
match result {
Ok(job) => Ok(ToolResult {
success: true,
output: serde_json::to_string_pretty(&json!({
"id": job.id,
"name": job.name,
"job_type": job.job_type,
"schedule": job.schedule,
"next_run": job.next_run,
"enabled": job.enabled
}))?,
error: None,
}),
Err(e) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e.to_string()),
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use crate::security::AutonomyLevel;
use tempfile::TempDir;
fn test_config(tmp: &TempDir) -> Arc<Config> {
let config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
Arc::new(config)
}
fn test_security(cfg: &Config) -> Arc<SecurityPolicy> {
Arc::new(SecurityPolicy::from_config(
&cfg.autonomy,
&cfg.workspace_dir,
))
}
#[tokio::test]
async fn adds_shell_job() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
let result = tool
.execute(json!({
"schedule": { "kind": "cron", "expr": "*/5 * * * *" },
"job_type": "shell",
"command": "echo ok"
}))
.await
.unwrap();
assert!(result.success, "{:?}", result.error);
assert!(result.output.contains("next_run"));
}
#[tokio::test]
async fn blocks_disallowed_shell_command() {
let tmp = TempDir::new().unwrap();
let mut config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
config.autonomy.allowed_commands = vec!["echo".into()];
config.autonomy.level = AutonomyLevel::Supervised;
std::fs::create_dir_all(&config.workspace_dir).unwrap();
let cfg = Arc::new(config);
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
let result = tool
.execute(json!({
"schedule": { "kind": "cron", "expr": "*/5 * * * *" },
"job_type": "shell",
"command": "curl https://example.com"
}))
.await
.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("blocked by security policy"));
}
#[tokio::test]
async fn rejects_invalid_schedule() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
let result = tool
.execute(json!({
"schedule": { "kind": "every", "every_ms": 0 },
"job_type": "shell",
"command": "echo nope"
}))
.await
.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("every_ms must be > 0"));
}
#[tokio::test]
async fn agent_job_requires_prompt() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
let result = tool
.execute(json!({
"schedule": { "kind": "cron", "expr": "*/5 * * * *" },
"job_type": "agent"
}))
.await
.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("Missing 'prompt'"));
}
}

101
src/tools/cron_list.rs Normal file
View file

@ -0,0 +1,101 @@
use super::traits::{Tool, ToolResult};
use crate::config::Config;
use crate::cron;
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
pub struct CronListTool {
config: Arc<Config>,
}
impl CronListTool {
pub fn new(config: Arc<Config>) -> Self {
Self { config }
}
}
#[async_trait]
impl Tool for CronListTool {
fn name(&self) -> &str {
"cron_list"
}
fn description(&self) -> &str {
"List all scheduled cron jobs"
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {},
"additionalProperties": false
})
}
async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
if !self.config.cron.enabled {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("cron is disabled by config (cron.enabled=false)".to_string()),
});
}
match cron::list_jobs(&self.config) {
Ok(jobs) => Ok(ToolResult {
success: true,
output: serde_json::to_string_pretty(&jobs)?,
error: None,
}),
Err(e) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e.to_string()),
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use tempfile::TempDir;
fn test_config(tmp: &TempDir) -> Arc<Config> {
let config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
Arc::new(config)
}
#[tokio::test]
async fn returns_empty_list_when_no_jobs() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronListTool::new(cfg);
let result = tool.execute(json!({})).await.unwrap();
assert!(result.success);
assert_eq!(result.output.trim(), "[]");
}
#[tokio::test]
async fn errors_when_cron_disabled() {
let tmp = TempDir::new().unwrap();
let mut cfg = (*test_config(&tmp)).clone();
cfg.cron.enabled = false;
let tool = CronListTool::new(Arc::new(cfg));
let result = tool.execute(json!({})).await.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("cron is disabled"));
}
}

114
src/tools/cron_remove.rs Normal file
View file

@ -0,0 +1,114 @@
use super::traits::{Tool, ToolResult};
use crate::config::Config;
use crate::cron;
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
pub struct CronRemoveTool {
config: Arc<Config>,
}
impl CronRemoveTool {
pub fn new(config: Arc<Config>) -> Self {
Self { config }
}
}
#[async_trait]
impl Tool for CronRemoveTool {
fn name(&self) -> &str {
"cron_remove"
}
fn description(&self) -> &str {
"Remove a cron job by id"
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"job_id": { "type": "string" }
},
"required": ["job_id"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
if !self.config.cron.enabled {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("cron is disabled by config (cron.enabled=false)".to_string()),
});
}
let job_id = match args.get("job_id").and_then(serde_json::Value::as_str) {
Some(v) if !v.trim().is_empty() => v,
_ => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'job_id' parameter".to_string()),
});
}
};
match cron::remove_job(&self.config, job_id) {
Ok(()) => Ok(ToolResult {
success: true,
output: format!("Removed cron job {job_id}"),
error: None,
}),
Err(e) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e.to_string()),
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use tempfile::TempDir;
fn test_config(tmp: &TempDir) -> Arc<Config> {
let config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
Arc::new(config)
}
#[tokio::test]
async fn removes_existing_job() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let job = cron::add_job(&cfg, "*/5 * * * *", "echo ok").unwrap();
let tool = CronRemoveTool::new(cfg.clone());
let result = tool.execute(json!({"job_id": job.id})).await.unwrap();
assert!(result.success);
assert!(cron::list_jobs(&cfg).unwrap().is_empty());
}
#[tokio::test]
async fn errors_when_job_id_missing() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronRemoveTool::new(cfg);
let result = tool.execute(json!({})).await.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("Missing 'job_id'"));
}
}

147
src/tools/cron_run.rs Normal file
View file

@ -0,0 +1,147 @@
use super::traits::{Tool, ToolResult};
use crate::config::Config;
use crate::cron;
use async_trait::async_trait;
use chrono::Utc;
use serde_json::json;
use std::sync::Arc;
pub struct CronRunTool {
config: Arc<Config>,
}
impl CronRunTool {
pub fn new(config: Arc<Config>) -> Self {
Self { config }
}
}
#[async_trait]
impl Tool for CronRunTool {
fn name(&self) -> &str {
"cron_run"
}
fn description(&self) -> &str {
"Force-run a cron job immediately and record run history"
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"job_id": { "type": "string" }
},
"required": ["job_id"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
if !self.config.cron.enabled {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("cron is disabled by config (cron.enabled=false)".to_string()),
});
}
let job_id = match args.get("job_id").and_then(serde_json::Value::as_str) {
Some(v) if !v.trim().is_empty() => v,
_ => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'job_id' parameter".to_string()),
});
}
};
let job = match cron::get_job(&self.config, job_id) {
Ok(job) => job,
Err(e) => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e.to_string()),
});
}
};
let started_at = Utc::now();
let (success, output) = cron::scheduler::execute_job_now(&self.config, &job).await;
let finished_at = Utc::now();
let duration_ms = (finished_at - started_at).num_milliseconds();
let status = if success { "ok" } else { "error" };
let _ = cron::record_run(
&self.config,
&job.id,
started_at,
finished_at,
status,
Some(&output),
duration_ms,
);
let _ = cron::record_last_run(&self.config, &job.id, finished_at, success, &output);
Ok(ToolResult {
success,
output: serde_json::to_string_pretty(&json!({
"job_id": job.id,
"status": status,
"duration_ms": duration_ms,
"output": output
}))?,
error: if success {
None
} else {
Some("cron job execution failed".to_string())
},
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use tempfile::TempDir;
fn test_config(tmp: &TempDir) -> Arc<Config> {
let config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
Arc::new(config)
}
#[tokio::test]
async fn force_runs_job_and_records_history() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let job = cron::add_job(&cfg, "*/5 * * * *", "echo run-now").unwrap();
let tool = CronRunTool::new(cfg.clone());
let result = tool.execute(json!({ "job_id": job.id })).await.unwrap();
assert!(result.success, "{:?}", result.error);
let runs = cron::list_runs(&cfg, &job.id, 10).unwrap();
assert_eq!(runs.len(), 1);
}
#[tokio::test]
async fn errors_for_missing_job() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronRunTool::new(cfg);
let result = tool
.execute(json!({ "job_id": "missing-job-id" }))
.await
.unwrap();
assert!(!result.success);
assert!(result.error.unwrap_or_default().contains("not found"));
}
}

175
src/tools/cron_runs.rs Normal file
View file

@ -0,0 +1,175 @@
use super::traits::{Tool, ToolResult};
use crate::config::Config;
use crate::cron;
use async_trait::async_trait;
use serde::Serialize;
use serde_json::json;
use std::sync::Arc;
const MAX_RUN_OUTPUT_CHARS: usize = 500;
pub struct CronRunsTool {
config: Arc<Config>,
}
impl CronRunsTool {
pub fn new(config: Arc<Config>) -> Self {
Self { config }
}
}
#[derive(Serialize)]
struct RunView {
id: i64,
job_id: String,
started_at: chrono::DateTime<chrono::Utc>,
finished_at: chrono::DateTime<chrono::Utc>,
status: String,
output: Option<String>,
duration_ms: Option<i64>,
}
#[async_trait]
impl Tool for CronRunsTool {
fn name(&self) -> &str {
"cron_runs"
}
fn description(&self) -> &str {
"List recent run history for a cron job"
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"job_id": { "type": "string" },
"limit": { "type": "integer" }
},
"required": ["job_id"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
if !self.config.cron.enabled {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("cron is disabled by config (cron.enabled=false)".to_string()),
});
}
let job_id = match args.get("job_id").and_then(serde_json::Value::as_str) {
Some(v) if !v.trim().is_empty() => v,
_ => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'job_id' parameter".to_string()),
});
}
};
let limit = args
.get("limit")
.and_then(serde_json::Value::as_u64)
.map_or(10, |v| usize::try_from(v).unwrap_or(10));
match cron::list_runs(&self.config, job_id, limit) {
Ok(runs) => {
let runs: Vec<RunView> = runs
.into_iter()
.map(|run| RunView {
id: run.id,
job_id: run.job_id,
started_at: run.started_at,
finished_at: run.finished_at,
status: run.status,
output: run.output.map(|out| truncate(&out, MAX_RUN_OUTPUT_CHARS)),
duration_ms: run.duration_ms,
})
.collect();
Ok(ToolResult {
success: true,
output: serde_json::to_string_pretty(&runs)?,
error: None,
})
}
Err(e) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e.to_string()),
}),
}
}
}
fn truncate(input: &str, max_chars: usize) -> String {
if input.chars().count() <= max_chars {
return input.to_string();
}
let mut out: String = input.chars().take(max_chars).collect();
out.push_str("...");
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use chrono::{Duration as ChronoDuration, Utc};
use tempfile::TempDir;
fn test_config(tmp: &TempDir) -> Arc<Config> {
let config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
Arc::new(config)
}
#[tokio::test]
async fn lists_runs_with_truncation() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let job = cron::add_job(&cfg, "*/5 * * * *", "echo ok").unwrap();
let long_output = "x".repeat(1000);
let now = Utc::now();
cron::record_run(
&cfg,
&job.id,
now,
now + ChronoDuration::milliseconds(1),
"ok",
Some(&long_output),
1,
)
.unwrap();
let tool = CronRunsTool::new(cfg.clone());
let result = tool
.execute(json!({ "job_id": job.id, "limit": 5 }))
.await
.unwrap();
assert!(result.success);
assert!(result.output.contains("..."));
}
#[tokio::test]
async fn errors_when_job_id_missing() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let tool = CronRunsTool::new(cfg);
let result = tool.execute(json!({})).await.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("Missing 'job_id'"));
}
}

177
src/tools/cron_update.rs Normal file
View file

@ -0,0 +1,177 @@
use super::traits::{Tool, ToolResult};
use crate::config::Config;
use crate::cron::{self, CronJobPatch};
use crate::security::SecurityPolicy;
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
pub struct CronUpdateTool {
config: Arc<Config>,
security: Arc<SecurityPolicy>,
}
impl CronUpdateTool {
pub fn new(config: Arc<Config>, security: Arc<SecurityPolicy>) -> Self {
Self { config, security }
}
}
#[async_trait]
impl Tool for CronUpdateTool {
fn name(&self) -> &str {
"cron_update"
}
fn description(&self) -> &str {
"Patch an existing cron job (schedule, command, prompt, enabled, delivery, model, etc.)"
}
fn parameters_schema(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"job_id": { "type": "string" },
"patch": { "type": "object" }
},
"required": ["job_id", "patch"]
})
}
async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
if !self.config.cron.enabled {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("cron is disabled by config (cron.enabled=false)".to_string()),
});
}
let job_id = match args.get("job_id").and_then(serde_json::Value::as_str) {
Some(v) if !v.trim().is_empty() => v,
_ => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'job_id' parameter".to_string()),
});
}
};
let patch_val = match args.get("patch") {
Some(v) => v.clone(),
None => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some("Missing 'patch' parameter".to_string()),
});
}
};
let patch = match serde_json::from_value::<CronJobPatch>(patch_val) {
Ok(patch) => patch,
Err(e) => {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Invalid patch payload: {e}")),
});
}
};
if let Some(command) = &patch.command {
if !self.security.is_command_allowed(command) {
return Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Command blocked by security policy: {command}")),
});
}
}
match cron::update_job(&self.config, job_id, patch) {
Ok(job) => Ok(ToolResult {
success: true,
output: serde_json::to_string_pretty(&job)?,
error: None,
}),
Err(e) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(e.to_string()),
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use tempfile::TempDir;
fn test_config(tmp: &TempDir) -> Arc<Config> {
let config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
std::fs::create_dir_all(&config.workspace_dir).unwrap();
Arc::new(config)
}
fn test_security(cfg: &Config) -> Arc<SecurityPolicy> {
Arc::new(SecurityPolicy::from_config(
&cfg.autonomy,
&cfg.workspace_dir,
))
}
#[tokio::test]
async fn updates_enabled_flag() {
let tmp = TempDir::new().unwrap();
let cfg = test_config(&tmp);
let job = cron::add_job(&cfg, "*/5 * * * *", "echo ok").unwrap();
let tool = CronUpdateTool::new(cfg.clone(), test_security(&cfg));
let result = tool
.execute(json!({
"job_id": job.id,
"patch": { "enabled": false }
}))
.await
.unwrap();
assert!(result.success, "{:?}", result.error);
assert!(result.output.contains("\"enabled\": false"));
}
#[tokio::test]
async fn blocks_disallowed_command_updates() {
let tmp = TempDir::new().unwrap();
let mut config = Config {
workspace_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
};
config.autonomy.allowed_commands = vec!["echo".into()];
std::fs::create_dir_all(&config.workspace_dir).unwrap();
let cfg = Arc::new(config);
let job = cron::add_job(&cfg, "*/5 * * * *", "echo ok").unwrap();
let tool = CronUpdateTool::new(cfg.clone(), test_security(&cfg));
let result = tool
.execute(json!({
"job_id": job.id,
"patch": { "command": "curl https://example.com" }
}))
.await
.unwrap();
assert!(!result.success);
assert!(result
.error
.unwrap_or_default()
.contains("blocked by security policy"));
}
}

View file

@ -1,6 +1,12 @@
pub mod browser;
pub mod browser_open;
pub mod composio;
pub mod cron_add;
pub mod cron_list;
pub mod cron_remove;
pub mod cron_run;
pub mod cron_runs;
pub mod cron_update;
pub mod delegate;
pub mod file_read;
pub mod file_write;
@ -21,6 +27,12 @@ pub mod traits;
pub use browser::{BrowserTool, ComputerUseConfig};
pub use browser_open::BrowserOpenTool;
pub use composio::ComposioTool;
pub use cron_add::CronAddTool;
pub use cron_list::CronListTool;
pub use cron_remove::CronRemoveTool;
pub use cron_run::CronRunTool;
pub use cron_runs::CronRunsTool;
pub use cron_update::CronUpdateTool;
pub use delegate::DelegateTool;
pub use file_read::FileReadTool;
pub use file_write::FileWriteTool;
@ -40,7 +52,7 @@ pub use traits::Tool;
#[allow(unused_imports)]
pub use traits::{ToolResult, ToolSpec};
use crate::config::DelegateAgentConfig;
use crate::config::{Config, DelegateAgentConfig};
use crate::memory::Memory;
use crate::runtime::{NativeRuntime, RuntimeAdapter};
use crate::security::SecurityPolicy;
@ -67,6 +79,7 @@ pub fn default_tools_with_runtime(
/// Create full tool registry including memory tools and optional Composio
#[allow(clippy::implicit_hasher, clippy::too_many_arguments)]
pub fn all_tools(
config: Arc<Config>,
security: &Arc<SecurityPolicy>,
memory: Arc<dyn Memory>,
composio_key: Option<&str>,
@ -76,9 +89,10 @@ pub fn all_tools(
workspace_dir: &std::path::Path,
agents: &HashMap<String, DelegateAgentConfig>,
fallback_api_key: Option<&str>,
config: &crate::config::Config,
root_config: &crate::config::Config,
) -> Vec<Box<dyn Tool>> {
all_tools_with_runtime(
config,
security,
Arc::new(NativeRuntime::new()),
memory,
@ -89,13 +103,14 @@ pub fn all_tools(
workspace_dir,
agents,
fallback_api_key,
config,
root_config,
)
}
/// Create full tool registry including memory tools and optional Composio.
#[allow(clippy::implicit_hasher, clippy::too_many_arguments)]
pub fn all_tools_with_runtime(
config: Arc<Config>,
security: &Arc<SecurityPolicy>,
runtime: Arc<dyn RuntimeAdapter>,
memory: Arc<dyn Memory>,
@ -106,16 +121,22 @@ pub fn all_tools_with_runtime(
workspace_dir: &std::path::Path,
agents: &HashMap<String, DelegateAgentConfig>,
fallback_api_key: Option<&str>,
config: &crate::config::Config,
root_config: &crate::config::Config,
) -> Vec<Box<dyn Tool>> {
let mut tools: Vec<Box<dyn Tool>> = vec![
Box::new(ShellTool::new(security.clone(), runtime)),
Box::new(FileReadTool::new(security.clone())),
Box::new(FileWriteTool::new(security.clone())),
Box::new(CronAddTool::new(config.clone(), security.clone())),
Box::new(CronListTool::new(config.clone())),
Box::new(CronRemoveTool::new(config.clone())),
Box::new(CronUpdateTool::new(config.clone(), security.clone())),
Box::new(CronRunTool::new(config.clone())),
Box::new(CronRunsTool::new(config.clone())),
Box::new(MemoryStoreTool::new(memory.clone())),
Box::new(MemoryRecallTool::new(memory.clone())),
Box::new(MemoryForgetTool::new(memory)),
Box::new(ScheduleTool::new(security.clone(), config.clone())),
Box::new(ScheduleTool::new(security.clone(), root_config.clone())),
Box::new(GitOperationsTool::new(
security.clone(),
workspace_dir.to_path_buf(),
@ -225,6 +246,7 @@ mod tests {
let cfg = test_config(&tmp);
let tools = all_tools(
Arc::new(Config::default()),
&security,
mem,
None,
@ -262,6 +284,7 @@ mod tests {
let cfg = test_config(&tmp);
let tools = all_tools(
Arc::new(Config::default()),
&security,
mem,
None,
@ -400,6 +423,7 @@ mod tests {
);
let tools = all_tools(
Arc::new(Config::default()),
&security,
mem,
None,
@ -431,6 +455,7 @@ mod tests {
let cfg = test_config(&tmp);
let tools = all_tools(
Arc::new(Config::default()),
&security,
mem,
None,

View file

@ -161,9 +161,11 @@ impl ScheduleTool {
let mut lines = Vec::with_capacity(jobs.len());
for job in jobs {
let flags = match (job.paused, job.one_shot) {
(true, true) => " [paused, one-shot]",
(true, false) => " [paused]",
let paused = !job.enabled;
let one_shot = matches!(job.schedule, cron::Schedule::At { .. });
let flags = match (paused, one_shot) {
(true, true) => " [disabled, one-shot]",
(true, false) => " [disabled]",
(false, true) => " [one-shot]",
(false, false) => "",
};
@ -191,8 +193,8 @@ impl ScheduleTool {
}
fn handle_get(&self, id: &str) -> Result<ToolResult> {
match cron::get_job(&self.config, id)? {
Some(job) => {
match cron::get_job(&self.config, id) {
Ok(job) => {
let detail = json!({
"id": job.id,
"expression": job.expression,
@ -200,8 +202,8 @@ impl ScheduleTool {
"next_run": job.next_run.to_rfc3339(),
"last_run": job.last_run.map(|value| value.to_rfc3339()),
"last_status": job.last_status,
"paused": job.paused,
"one_shot": job.one_shot,
"enabled": job.enabled,
"one_shot": matches!(job.schedule, cron::Schedule::At { .. }),
});
Ok(ToolResult {
success: true,
@ -209,7 +211,7 @@ impl ScheduleTool {
error: None,
})
}
None => Ok(ToolResult {
Err(_) => Ok(ToolResult {
success: false,
output: String::new(),
error: Some(format!("Job '{id}' not found")),
@ -342,7 +344,7 @@ impl ScheduleTool {
};
match operation {
Ok(()) => ToolResult {
Ok(_) => ToolResult {
success: true,
output: if pause {
format!("Paused job {id}")