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
//! Cron job management tool handlers and file-based job storage helpers.
//!
//! Split from `tools_misc.rs` for maintainability. All methods live in
//! `impl AgentRuntime` via the split-impl pattern (same struct, different file).
use std::time::Duration;
use anyhow::{Result, anyhow};
use chrono::Utc;
use serde_json::{Value, json};
use tracing::debug;
use uuid::Uuid;
impl super::runtime::AgentRuntime {
pub(crate) async fn tool_cron(&self, args: Value, ctx: &super::runtime::RunContext) -> Result<Value> {
let action = args["action"]
.as_str()
.ok_or_else(|| anyhow!("cron: `action` required"))?;
let cron_dir = crate::config::loader::base_dir();
let cron_path = cron_dir.join("cron.json5");
match action {
"list" => {
let jobs = read_cron_jobs(&cron_path).await;
// Add 1-based index to each job for easier reference by LLMs
let jobs_with_index: Vec<Value> = jobs
.iter()
.enumerate()
.map(|(i, j)| {
let mut indexed = j.clone();
indexed["_index"] = json!(i + 1);
indexed
})
.collect();
Ok(
json!({"jobs": jobs_with_index, "hint": "Use index number (#1, #2, etc.) for removal to avoid ID truncation issues"}),
)
}
"add" => {
let message = args["message"]
.as_str()
.ok_or_else(|| anyhow!("cron add: `message` required"))?;
let name = args["name"].as_str();
let tz = args["tz"].as_str();
let agent_id = args["agent_id"].as_str().or(args["agentId"].as_str());
let mut jobs = read_cron_jobs(&cron_path).await;
let now_ms = Utc::now().timestamp_millis() as u64;
let id = Uuid::new_v4().to_string();
let mut job = json!({
"id": id,
"agentId": agent_id.unwrap_or("main"),
"enabled": true,
"createdAtMs": now_ms,
"updatedAtMs": now_ms,
});
// Schedule: support cron expr, delay (once), or interval.
let delay_ms = args["delay_ms"].as_u64().or(args["delayMs"].as_u64());
let schedule = args["schedule"].as_str();
if let Some(delay) = delay_ms {
// Short delays (<=30min): use in-memory timer, skip cron.json5.
// Longer delays: persist to cron.json5 (survives restart).
let short_threshold_ms = 30 * 60 * 1000; // 30 minutes
if delay <= short_threshold_ms {
let msg_text = message.to_owned();
let event_bus = self.event_bus.clone();
let session_key = ctx.session_key.clone();
let delay_dur = Duration::from_millis(delay);
let timer_name = name.unwrap_or("reminder").to_owned();
debug!(delay_ms = delay, name = %timer_name, "cron: using in-memory timer (short delay)");
tokio::spawn(async move {
tokio::time::sleep(delay_dur).await;
// Emit via event_bus so WS auto-relay delivers to connected UI.
if let Some(bus) = event_bus {
// Send text delta with reminder content
let _ = bus.send(crate::events::AgentEvent {
session_id: session_key.clone(),
agent_id: "cron".to_owned(),
delta: msg_text,
done: false,
files: vec![],
images: vec![],
tool_log: vec![],
});
// Send done signal
let _ = bus.send(crate::events::AgentEvent {
session_id: session_key,
agent_id: "cron".to_owned(),
delta: String::new(),
done: true,
files: vec![],
images: vec![],
tool_log: vec![],
});
}
});
return Ok(json!({"added": id, "type": "in-memory timer", "delay_ms": delay, "message": message}));
}
// Long delay: persist to cron.json5
let at_ms = now_ms + delay;
job["schedule"] = json!({"kind": "once", "atMs": at_ms});
} else if let Some(sched) = schedule {
// Standard cron expression or interval.
// Always include timezone. Use LLM-provided, config, or auto-detected.
let tz_val = tz
.map(String::from)
.or_else(|| self.config.agents.defaults.timezone.clone())
.unwrap_or_else(|| {
// Auto-detect from system offset
let offset = chrono::Local::now().offset().local_minus_utc();
match offset {
25200 => "Asia/Bangkok",
28800 => "Asia/Shanghai",
32400 => "Asia/Tokyo",
-18000 => "US/Eastern",
-28800 => "US/Pacific",
_ => "UTC",
}.to_owned()
});
job["schedule"] = json!({"kind": "cron", "expr": sched, "tz": tz_val});
} else {
return Err(anyhow!("cron add: `schedule` or `delay_ms` required"));
}
// Payload in OpenClaw format.
job["payload"] = json!({"kind": "systemEvent", "text": message});
if let Some(n) = name {
job["name"] = json!(n);
}
// Auto-set delivery to the originating channel+peer when not explicitly specified.
let channel = &ctx.channel;
let peer_id = &ctx.peer_id;
if !channel.is_empty() && channel != "system" && channel != "cron" && !peer_id.is_empty() {
job["delivery"] = json!({
"channel": channel,
"to": peer_id,
"mode": "always"
});
debug!(channel, peer_id, "cron add: auto-set delivery to originating channel");
}
jobs.push(job);
write_cron_jobs(&cron_path, &jobs).await?;
// Notify gateway to reload cron jobs
let port = self.config.gateway.port;
let client = reqwest::Client::new();
if let Err(e) = client
.post(format!("http://127.0.0.1:{port}/api/v1/cron/reload"))
.timeout(Duration::from_secs(3))
.send()
.await
{
debug!(err = %e, "cron add: failed to notify gateway reload");
}
Ok(json!({"added": id, "schedule": schedule, "message": message}))
}
"remove" => {
let mut jobs = read_cron_jobs(&cron_path).await;
// Support both `id` and `index` parameters (prefer index for reliability)
let removed_job = if let Some(index) = args["index"].as_u64() {
// 1-based index
let idx = index as usize;
if idx == 0 || idx > jobs.len() {
return Err(anyhow!(
"cron remove: invalid index {} (valid: 1-{})",
index,
jobs.len()
));
}
let job = jobs.remove(idx - 1);
write_cron_jobs(&cron_path, &jobs).await?;
job
} else if let Some(id) = args["id"].as_str() {
let before = jobs.len();
jobs.retain(|j| j["id"].as_str() != Some(id));
let removed = before - jobs.len();
if removed == 0 {
return Err(anyhow!("cron remove: job not found with id={}", id));
}
write_cron_jobs(&cron_path, &jobs).await?;
json!({"id": id, "count": removed})
} else {
return Err(anyhow!(
"cron remove: `index` or `id` required (index is preferred)"
));
};
// Notify gateway to reload cron jobs
let port = self.config.gateway.port;
let client = reqwest::Client::new();
if let Err(e) = client
.post(format!("http://127.0.0.1:{port}/api/v1/cron/reload"))
.timeout(Duration::from_secs(3))
.send()
.await
{
debug!(err = %e, "cron remove: failed to notify gateway reload");
}
Ok(json!({"removed": removed_job}))
}
"enable" | "disable" => {
let enabled = action == "enable";
let mut jobs = read_cron_jobs(&cron_path).await;
let idx = if let Some(index) = args["index"].as_u64() {
let idx = index as usize;
if idx == 0 || idx > jobs.len() {
return Err(anyhow!(
"cron {}: invalid index {} (valid: 1-{})",
action, index, jobs.len()
));
}
idx - 1
} else if let Some(id) = args["id"].as_str() {
match jobs.iter().position(|j| j["id"].as_str() == Some(id)) {
Some(pos) => pos,
None => return Err(anyhow!("cron {}: job not found with id={}", action, id)),
}
} else {
return Err(anyhow!(
"cron {}: `index` or `id` required (index is preferred)",
action
));
};
let id = jobs[idx]["id"].as_str().unwrap_or("?").to_string();
jobs[idx]["enabled"] = json!(enabled);
jobs[idx]["updatedAtMs"] = json!(Utc::now().timestamp_millis() as u64);
write_cron_jobs(&cron_path, &jobs).await?;
// Notify gateway to reload cron jobs
let port = self.config.gateway.port;
let client = reqwest::Client::new();
if let Err(e) = client
.post(format!("http://127.0.0.1:{port}/api/v1/cron/reload"))
.timeout(Duration::from_secs(3))
.send()
.await
{
debug!(err = %e, "cron {}: failed to notify gateway reload", action);
}
Ok(json!({action: id}))
}
"edit" => {
let mut jobs = read_cron_jobs(&cron_path).await;
let idx = if let Some(index) = args["index"].as_u64() {
let idx = index as usize;
if idx == 0 || idx > jobs.len() {
return Err(anyhow!(
"cron edit: invalid index {} (valid: 1-{})",
index, jobs.len()
));
}
idx - 1
} else if let Some(id) = args["id"].as_str() {
match jobs.iter().position(|j| j["id"].as_str() == Some(id)) {
Some(pos) => pos,
None => return Err(anyhow!("cron edit: job not found with id={}", id)),
}
} else {
return Err(anyhow!(
"cron edit: `index` or `id` required (index is preferred)"
));
};
let id = jobs[idx]["id"].as_str().unwrap_or("?").to_string();
if let Some(schedule) = args["schedule"].as_str() {
let tz = args["tz"].as_str();
if let Some(tz_val) = tz {
jobs[idx]["schedule"] = json!({"kind": "cron", "expr": schedule, "tz": tz_val});
} else {
jobs[idx]["schedule"] = json!({"kind": "cron", "expr": schedule});
}
}
if let Some(message) = args["message"].as_str() {
jobs[idx]["payload"] = json!({"kind": "systemEvent", "text": message});
}
if let Some(name) = args["name"].as_str() {
jobs[idx]["name"] = json!(name);
}
if let Some(agent_id) = args["agentId"].as_str().or(args["agent_id"].as_str()) {
jobs[idx]["agentId"] = json!(agent_id);
}
jobs[idx]["updatedAtMs"] = json!(Utc::now().timestamp_millis() as u64);
write_cron_jobs(&cron_path, &jobs).await?;
// Notify gateway to reload cron jobs
let port = self.config.gateway.port;
let client = reqwest::Client::new();
if let Err(e) = client
.post(format!("http://127.0.0.1:{port}/api/v1/cron/reload"))
.timeout(Duration::from_secs(3))
.send()
.await
{
debug!(err = %e, "cron edit: failed to notify gateway reload");
}
Ok(json!({"edited": id}))
}
other => Err(anyhow!(
"cron: unsupported action `{other}` (list, add, edit, remove, enable, disable)"
)),
}
}
}
// ---------------------------------------------------------------------------
// Cron helpers (file-based job storage)
// ---------------------------------------------------------------------------
/// Read cron jobs from cron.json5.
/// Handles both bare array `[...]` and wrapped `{"version":1,"jobs":[...]}` formats.
/// Parses with json5 for comment support.
pub(crate) async fn read_cron_jobs(path: &std::path::Path) -> Vec<Value> {
let data = tokio::fs::read_to_string(path)
.await
.unwrap_or_else(|_| "[]".to_owned());
// Parse with json5 (falls back to serde_json).
let wrapper: Value = json5::from_str(&data)
.or_else(|_| serde_json::from_str(&data))
.unwrap_or(Value::Array(vec![]));
if let Some(jobs) = wrapper.get("jobs").and_then(|v| v.as_array()) {
return jobs.clone();
}
if let Some(arr) = wrapper.as_array() {
return arr.clone();
}
Vec::new()
}
/// Write cron jobs as JSON (readable by json5 parser).
pub(crate) async fn write_cron_jobs(path: &std::path::Path, jobs: &[Value]) -> Result<()> {
let wrapper = json!({"version": 1, "jobs": jobs});
tokio::fs::write(path, serde_json::to_string_pretty(&wrapper)?)
.await
.map_err(|e| anyhow!("cron: failed to write jobs: {e}"))?;
Ok(())
}