返回 CodeWhale
automation.rs
根目录 / crates / engine / src / tools / automation.rs
1 //! Model-visible automation tools over `AutomationManager`.
2 //!
3 //! Unified surface (piagent phase B): the model sees one tool, `automation`,
4 //! with an `action` parameter routing to the per-action logic. The legacy
5 //! `automation_*` execution aliases were removed in v0.9.3.
6
7 use std::path::PathBuf;
8
9 use async_trait::async_trait;
10 use serde_json::{Value, json};
11
12 use crate::automation_manager::{
13 AUTOMATION_WATCHER_NO_REPORT_SENTINEL, AutomationDeliveryMode, AutomationRecord,
14 AutomationStatus, CreateAutomationRequest, UpdateAutomationRequest, run_now_shared,
15 };
16 use crate::tools::spec::{
17 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
18 optional_str, optional_u64, required_str,
19 };
20
21 /// Why an unbound host cannot start durable work, in the model's own terms.
22 pub const DISPATCH_OWNER_HINT: &str = "durable scheduling and runs need a host with an attached persistent execution owner (the Runtime or the interactive session). This one-shot host can inspect automations and store paused definitions only.";
23
24 /// Refuse work that would promise dispatch this host cannot deliver.
25 ///
26 /// An `AutomationManager` is bound to a task-execution scope only after
27 /// `bind_task_manager`, and the scheduler admits a record only in its own
28 /// scope (`collect_due_runs` skips every unbound and foreign one). A one-shot
29 /// host — headless `exec` — attaches the shared store for inspection but owns
30 /// no execution lease, so anything it marks Active would carry a `next_run_at`
31 /// that nothing can honor: a schedule that silently never fires.
32 ///
33 /// Paused definitions stay honest and are deliberately still allowed: they are
34 /// inert by definition, and the first resume from an owning host adopts them
35 /// into that host's scope (`update_automation_unlocked`).
36 pub fn require_dispatch_owner(
37 manager: &crate::automation_manager::AutomationManager,
38 intent: &str,
39 ) -> Result<(), ToolError> {
40 if manager.execution_scope().is_some() {
41 return Ok(());
42 }
43 Err(ToolError::not_available(format!(
44 "cannot {intent}: {DISPATCH_OWNER_HINT}"
45 )))
46 }
47
48 /// Read-only actions — these are the only ones the Plan-mode surface exposes.
49 const READ_ACTIONS: &[&str] = &["list", "read"];
50 const ALL_ACTIONS: &[&str] = &[
51 "create", "list", "read", "update", "pause", "resume", "adopt", "delete", "run",
52 ];
53
54 /// Unified automation tool.
55 ///
56 /// One struct, one input schema per surface: the canonical `automation`
57 /// tool (all actions, or the read-only subset via [`AutomationTool::read_only`]).
58 pub struct AutomationTool {
59 name: &'static str,
60 read_only: bool,
61 }
62
63 impl AutomationTool {
64 pub const fn new(name: &'static str) -> Self {
65 Self {
66 name,
67 read_only: false,
68 }
69 }
70
71 /// Plan-mode variant: only the read-only actions are advertised and routed.
72 pub const fn read_only(name: &'static str) -> Self {
73 Self {
74 name,
75 read_only: true,
76 }
77 }
78
79 fn allowed_actions(&self) -> &'static [&'static str] {
80 if self.read_only {
81 READ_ACTIONS
82 } else {
83 ALL_ACTIONS
84 }
85 }
86
87 fn resolve_action<'a>(&'a self, input: &'a Value) -> Result<&'a str, ToolError> {
88 let action = input.get("action").and_then(Value::as_str).ok_or_else(|| {
89 ToolError::invalid_input(format!(
90 "automation: missing `action` (one of: {})",
91 self.allowed_actions().join(", ")
92 ))
93 })?;
94 if self.allowed_actions().contains(&action) {
95 Ok(action)
96 } else {
97 Err(ToolError::invalid_input(format!(
98 "automation: invalid action `{action}` (one of: {})",
99 self.allowed_actions().join(", ")
100 )))
101 }
102 }
103
104 fn action_is_read(action: &str) -> bool {
105 READ_ACTIONS.contains(&action)
106 }
107 }
108
109 #[async_trait]
110 impl ToolSpec for AutomationTool {
111 fn name(&self) -> &'static str {
112 self.name
113 }
114
115 fn description(&self) -> &'static str {
116 if self.read_only {
117 "Inspect durable scheduled automations. Actions: \"list\" (status, next run, last run) and \"read\" (one automation plus recent run records)."
118 } else {
119 "Manage durable scheduled automations. Actions: \"create\" (approval; ONCE, HOURLY, WEEKLY, or 5-field CRON; watcher uses EXACT NOTHING_TO_REPORT when unchanged), \"list\", \"read\", and approval-gated \"update\", \"pause\", \"resume\", \"adopt\", \"delete\", \"run\"."
120 }
121 }
122
123 fn input_schema(&self) -> Value {
124 let actions: Vec<&str> = self.allowed_actions().to_vec();
125 let mut properties = serde_json::Map::new();
126 properties.insert(
127 "action".to_string(),
128 json!({
129 "type": "string",
130 "enum": actions,
131 "description": "Action to perform."
132 }),
133 );
134 if !self.read_only {
135 properties.insert(
136 "name".to_string(),
137 json!({ "type": "string", "description": "Automation name (action=create/update)." }),
138 );
139 properties.insert(
140 "prompt".to_string(),
141 json!({ "type": "string", "description": "Prompt for scheduled runs (action=create/update)." }),
142 );
143 properties.insert(
144 "rrule".to_string(),
145 json!({
146 "type": "string",
147 "description": "Supported: FREQ=ONCE;AT=2026-08-03T14:30 (local time or RFC3339), FREQ=HOURLY;INTERVAL=N[;BYDAY=MO,TU][;BYHOUR=9][;BYMINUTE=30], FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=30, or FREQ=CRON;EXPR=*/17 * * * *. Cron uses standard 5-field local time. For HOURLY, BYHOUR/BYMINUTE choose the initial local wall-clock anchor and INTERVAL advances from that anchor; BYHOUR is not a daily-only filter. Anchored wall times skip nonexistent clock times and use the first occurrence of ambiguous clock times. (action=create/update)"
148 }),
149 );
150 properties.insert(
151 "cwds".to_string(),
152 json!({ "type": "array", "items": { "type": "string" }, "description": "Working directories for scheduled runs (action=create/update)." }),
153 );
154 properties.insert(
155 "model_provider".to_string(),
156 json!({ "type": "string", "description": "Provider kind for the pinned model. Omit to inherit the configured provider." }),
157 );
158 properties.insert(
159 "model_provider_id".to_string(),
160 json!({ "type": "string", "description": "Exact configured provider id, including named custom routes. Keeps the model on that route." }),
161 );
162 properties.insert(
163 "model".to_string(),
164 json!({ "type": "string", "description": "Model id for scheduled runs (action=create/update)." }),
165 );
166 properties.insert(
167 "mode".to_string(),
168 json!({ "type": "string", "description": "Task mode for scheduled runs. Defaults to agent when omitted. (action=create/update)" }),
169 );
170 properties.insert(
171 "allow_shell".to_string(),
172 json!({ "type": "boolean", "default": false, "description": "(action=create/update)" }),
173 );
174 properties.insert(
175 "trust_mode".to_string(),
176 json!({ "type": "boolean", "default": false, "description": "(action=create/update)" }),
177 );
178 properties.insert(
179 "auto_approve".to_string(),
180 json!({ "type": "boolean", "default": false, "description": "(action=create/update)" }),
181 );
182 properties.insert(
183 "delivery_mode".to_string(),
184 json!({
185 "type": "string",
186 "enum": ["task", "watcher"],
187 "default": "task",
188 "description": format!("Delivery mode for scheduled checks. \"task\" creates a normal durable background run. \"watcher\" is for condition-shaped prompts; when there is no change, return EXACTLY {AUTOMATION_WATCHER_NO_REPORT_SENTINEL}. (action=create/update)")
189 }),
190 );
191 properties.insert(
192 "thread_id".to_string(),
193 json!({ "type": "string", "description": "Existing thread each run is delivered into as a new turn; \"current\" means this thread, \"\" clears it. Omit to run each occurrence in a new background task thread. (action=create/update)" }),
194 );
195 properties.insert(
196 "paused".to_string(),
197 json!({ "type": "boolean", "default": false, "description": "Create the automation paused (action=create)." }),
198 );
199 properties.insert(
200 "status".to_string(),
201 json!({ "type": "string", "enum": ["active", "paused"], "description": "(action=update)" }),
202 );
203 }
204 properties.insert(
205 "automation_id".to_string(),
206 json!({ "type": "string", "description": "Automation id (read/update/pause/resume/adopt/delete/run)." }),
207 );
208 properties.insert(
209 "limit".to_string(),
210 json!({ "type": "integer", "minimum": 1, "maximum": 100, "default": 50, "description": "(action=list)" }),
211 );
212 json!({
213 "type": "object",
214 "properties": properties,
215 "additionalProperties": false
216 })
217 }
218
219 fn capabilities(&self) -> Vec<ToolCapability> {
220 if self.read_only {
221 vec![ToolCapability::ReadOnly]
222 } else {
223 // `run` executes a stored automation now; the other mutating
224 // actions schedule one to execute later, with its own prompt, cwd,
225 // and task mode. Declaring only `RequiresApproval` described the
226 // *approval* consequence and hid the *execution* one, which left
227 // every capability-derived policy — including the child execution
228 // envelope — unable to see that this family spawns agent runs.
229 vec![
230 ToolCapability::ExecutesCode,
231 ToolCapability::RequiresApproval,
232 ]
233 }
234 }
235
236 fn approval_requirement(&self) -> ApprovalRequirement {
237 if self.read_only {
238 ApprovalRequirement::Auto
239 } else {
240 ApprovalRequirement::Required
241 }
242 }
243
244 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
245 match self.resolve_action(input) {
246 Ok(action) if Self::action_is_read(action) => ApprovalRequirement::Auto,
247 _ => ApprovalRequirement::Required,
248 }
249 }
250
251 fn is_read_only_for(&self, input: &Value) -> bool {
252 match self.resolve_action(input) {
253 Ok(action) => Self::action_is_read(action),
254 Err(_) => self.is_read_only(),
255 }
256 }
257
258 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
259 crate::tools::execution_envelope::enforce_tool_denial(
260 context,
261 self.name(),
262 &json!({"action": self.resolve_action(&input)?}),
263 )?;
264 match self.resolve_action(&input)? {
265 "create" => self.execute_create(&input, context).await,
266 "list" => self.execute_list(&input, context).await,
267 "read" => self.execute_read(&input, context).await,
268 "update" => self.execute_update(&input, context).await,
269 "pause" => self.execute_simple(context, &input, "pause").await,
270 "resume" => self.execute_simple(context, &input, "resume").await,
271 "adopt" => self.execute_simple(context, &input, "adopt").await,
272 "delete" => self.execute_simple(context, &input, "delete").await,
273 "run" => self.execute_run(&input, context).await,
274 action => Err(ToolError::invalid_input(format!(
275 "automation: invalid action `{action}`"
276 ))),
277 }
278 }
279 }
280
281 impl AutomationTool {
282 async fn execute_create(
283 &self,
284 input: &Value,
285 context: &ToolContext,
286 ) -> Result<ToolResult, ToolError> {
287 let manager = context
288 .runtime
289 .automations
290 .as_ref()
291 .ok_or_else(|| ToolError::not_available("AutomationManager is not attached"))?;
292 let manager = manager.lock().await;
293 // A scheduled run keeps no creating session to ask, so the authority
294 // it asks for is capped at what this session holds now.
295 let (allow_shell, trust_mode, auto_approve) = context.cap_delegated_authority(
296 optional_bool_value(input, "allow_shell"),
297 optional_bool_value(input, "trust_mode"),
298 optional_bool_value(input, "auto_approve"),
299 );
300 let req = CreateAutomationRequest {
301 destination_thread_id: destination_thread(input, context, None)?,
302 name: required_str(input, "name")?.to_string(),
303 prompt: required_str(input, "prompt")?.to_string(),
304 rrule: required_str(input, "rrule")?.to_string(),
305 cwds: session_reachable_cwds(context, string_array(input, "cwds")?)?,
306 model: optional_str(input, "model")?.map(ToString::to_string),
307 model_provider: optional_str(input, "model_provider")?.map(ToString::to_string),
308 model_provider_id: optional_str(input, "model_provider_id")?.map(ToString::to_string),
309 mode: optional_str(input, "mode")?.map(ToString::to_string),
310 allow_shell,
311 trust_mode,
312 auto_approve,
313 delivery_mode: optional_delivery_mode(input)?,
314 disallowed_tools: context.disallowed_tools.clone(),
315 status: Some(
316 if input
317 .get("paused")
318 .and_then(Value::as_bool)
319 .unwrap_or(false)
320 {
321 AutomationStatus::Paused
322 } else {
323 AutomationStatus::Active
324 },
325 ),
326 };
327 if req.status != Some(AutomationStatus::Paused) {
328 require_dispatch_owner(&manager, "create an active automation")?;
329 }
330 let automation = manager
331 .create_automation(req)
332 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
333 ToolResult::json(&automation).map_err(|e| ToolError::execution_failed(e.to_string()))
334 }
335
336 async fn execute_list(
337 &self,
338 input: &Value,
339 context: &ToolContext,
340 ) -> Result<ToolResult, ToolError> {
341 let manager = context
342 .runtime
343 .automations
344 .as_ref()
345 .ok_or_else(|| ToolError::not_available("AutomationManager is not attached"))?;
346 let manager = manager.lock().await;
347 let mut automations = manager
348 .list_automation_views()
349 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
350 automations.truncate(optional_u64(input, "limit", 50)?.clamp(1, 100) as usize);
351 ToolResult::json(&automations).map_err(|e| ToolError::execution_failed(e.to_string()))
352 }
353
354 async fn execute_read(
355 &self,
356 input: &Value,
357 context: &ToolContext,
358 ) -> Result<ToolResult, ToolError> {
359 let manager = context
360 .runtime
361 .automations
362 .as_ref()
363 .ok_or_else(|| ToolError::not_available("AutomationManager is not attached"))?;
364 let manager = manager.lock().await;
365 let id = required_str(input, "automation_id")?;
366 let automation = manager
367 .get_automation_view(id)
368 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
369 let runs = manager
370 .list_runs(id, Some(20))
371 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
372 ToolResult::json(&json!({ "automation": automation, "recent_runs": runs }))
373 .map_err(|e| ToolError::execution_failed(e.to_string()))
374 }
375
376 async fn execute_update(
377 &self,
378 input: &Value,
379 context: &ToolContext,
380 ) -> Result<ToolResult, ToolError> {
381 let manager = context
382 .runtime
383 .automations
384 .as_ref()
385 .ok_or_else(|| ToolError::not_available("AutomationManager is not attached"))?;
386 let manager = manager.lock().await;
387 let status = optional_str(input, "status")?
388 .map(parse_automation_status)
389 .transpose()?;
390 if status == Some(AutomationStatus::Active) {
391 require_dispatch_owner(&manager, "activate an automation")?;
392 }
393 let (allow_shell, trust_mode, auto_approve) = context.cap_delegated_authority(
394 optional_bool_value(input, "allow_shell"),
395 optional_bool_value(input, "trust_mode"),
396 optional_bool_value(input, "auto_approve"),
397 );
398 let id = required_str(input, "automation_id")?;
399 let existing = manager
400 .get_automation(id)
401 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
402 // Fields the call leaves out keep their stored values, so the record
403 // that results must also sit within this session's authority: a
404 // session cannot edit the prompt of an automation that runs with more
405 // than it holds.
406 require_within_session_authority(
407 context,
408 &AutomationRecord {
409 allow_shell: allow_shell.or(existing.allow_shell),
410 trust_mode: trust_mode.or(existing.trust_mode),
411 auto_approve: auto_approve.or(existing.auto_approve),
412 ..existing
413 },
414 "update",
415 )?;
416 let req = UpdateAutomationRequest {
417 destination_thread_id: if input.get("thread_id").is_some() {
418 Some(destination_thread(input, context, None)?.unwrap_or_default())
419 } else {
420 None
421 },
422 name: optional_str(input, "name")?.map(ToString::to_string),
423 prompt: optional_str(input, "prompt")?.map(ToString::to_string),
424 rrule: optional_str(input, "rrule")?.map(ToString::to_string),
425 cwds: if input.get("cwds").is_some() {
426 Some(session_reachable_cwds(
427 context,
428 string_array(input, "cwds")?,
429 )?)
430 } else {
431 None
432 },
433 model: optional_str(input, "model")?.map(ToString::to_string),
434 model_provider: optional_str(input, "model_provider")?.map(ToString::to_string),
435 model_provider_id: optional_str(input, "model_provider_id")?.map(ToString::to_string),
436 mode: optional_str(input, "mode")?.map(ToString::to_string),
437 allow_shell,
438 trust_mode,
439 auto_approve,
440 delivery_mode: optional_delivery_mode(input)?,
441 status,
442 expected_revision: None,
443 };
444 let automation = manager
445 .update_automation(id, req)
446 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
447 ToolResult::json(&automation).map_err(|e| ToolError::execution_failed(e.to_string()))
448 }
449
450 /// pause / resume / delete share the same shape: one id in, automation out.
451 async fn execute_simple(
452 &self,
453 context: &ToolContext,
454 input: &Value,
455 action: &str,
456 ) -> Result<ToolResult, ToolError> {
457 let manager = context
458 .runtime
459 .automations
460 .as_ref()
461 .ok_or_else(|| ToolError::not_available("AutomationManager is not attached"))?;
462 let manager = manager.lock().await;
463 if action == "resume" || action == "adopt" {
464 if let Ok(existing) = manager.get_automation(required_str(input, "automation_id")?) {
465 require_within_session_authority(context, &existing, action)?;
466 }
467 let intent = if action == "adopt" {
468 "adopt an automation"
469 } else {
470 "resume an automation"
471 };
472 require_dispatch_owner(&manager, intent)?;
473 }
474 if action == "adopt" {
475 let view = manager
476 .adopt_automation(required_str(input, "automation_id")?)
477 .map(|adopted| manager.record_view(adopted))
478 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
479 return ToolResult::json(&view).map_err(|e| ToolError::execution_failed(e.to_string()));
480 }
481 let automation = match action {
482 "pause" => manager.pause_automation(required_str(input, "automation_id")?),
483 "resume" => manager.resume_automation(required_str(input, "automation_id")?),
484 "delete" => manager.delete_automation(required_str(input, "automation_id")?),
485 _ => unreachable!("execute_simple only routes pause/resume/adopt/delete"),
486 }
487 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
488 ToolResult::json(&automation).map_err(|e| ToolError::execution_failed(e.to_string()))
489 }
490
491 async fn execute_run(
492 &self,
493 input: &Value,
494 context: &ToolContext,
495 ) -> Result<ToolResult, ToolError> {
496 let manager = context
497 .runtime
498 .automations
499 .as_ref()
500 .ok_or_else(|| ToolError::not_available("AutomationManager is not attached"))?;
501 let id = required_str(input, "automation_id")?;
502 {
503 let existing = manager
504 .lock()
505 .await
506 .get_automation(id)
507 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
508 require_within_session_authority(context, &existing, "run")?;
509 }
510 let task_manager = context.runtime.task_manager.as_ref().ok_or_else(|| {
511 ToolError::not_available(format!(
512 "TaskManager is not attached — {DISPATCH_OWNER_HINT}"
513 ))
514 })?;
515 // run_now_shared handles its own lock phases so the manager mutex is
516 // never held across the task-manager await.
517 let run = run_now_shared(manager, id, task_manager)
518 .await
519 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
520 ToolResult::json(&run).map_err(|e| ToolError::execution_failed(e.to_string()))
521 }
522 }
523
524 /// Refuse to update, resume or run an automation whose stored authority is
525 /// more than this session holds.
526 ///
527 /// A scheduled run executes the record's prompt with the record's own
528 /// `allow_shell` / `trust_mode` / `auto_approve`. A session with less than
529 /// that could otherwise rewrite or start work that runs with more, and the
530 /// approval card for the call would only show the fields the call sent.
531 /// Pausing and deleting only reduce what runs, so they are not checked.
532 fn require_within_session_authority(
533 context: &ToolContext,
534 automation: &AutomationRecord,
535 verb: &str,
536 ) -> Result<(), ToolError> {
537 if !crate::task_manager::deny_rules_cover(
538 &automation.disallowed_tools,
539 &context.disallowed_tools,
540 ) {
541 return Err(ToolError::permission_denied(format!(
542 "automation: cannot {verb} `{}`: it was created without every tool deny rule this session runs under. Ask the user to {verb} it from a session that holds that access.",
543 automation.id,
544 )));
545 }
546 let stored = [
547 ("allow_shell", automation.allow_shell),
548 ("trust_mode", automation.trust_mode),
549 ("auto_approve", automation.auto_approve),
550 ];
551 let (shell, trust, auto) = context.cap_delegated_authority(
552 automation.allow_shell,
553 automation.trust_mode,
554 automation.auto_approve,
555 );
556 let capped = [shell, trust, auto];
557 let above: Vec<&str> = stored
558 .iter()
559 .zip(capped)
560 .filter(|((_, value), capped)| *value == Some(true) && *capped != Some(true))
561 .map(|((name, _), _)| *name)
562 .collect();
563 if above.is_empty() {
564 return Ok(());
565 }
566 Err(ToolError::permission_denied(format!(
567 "automation: cannot {verb} `{}`: it runs with {} = true, which this session does not hold. Set {} to false in the same update, or ask the user to {verb} it from a session that holds that access.",
568 automation.id,
569 above.join(", "),
570 above.join(" / "),
571 )))
572 }
573
574 fn string_array(input: &Value, field: &str) -> Result<Vec<String>, ToolError> {
575 Ok(input
576 .get(field)
577 .and_then(Value::as_array)
578 .map(|items| {
579 items
580 .iter()
581 .filter_map(Value::as_str)
582 .map(ToString::to_string)
583 .collect::<Vec<_>>()
584 })
585 .unwrap_or_default())
586 }
587
588 /// Automation directories must be ones this session can already reach:
589 /// inside its workspace, or anywhere in trust mode.
590 fn session_reachable_cwds(
591 context: &ToolContext,
592 cwds: Vec<String>,
593 ) -> Result<Vec<PathBuf>, ToolError> {
594 cwds.iter().map(|raw| context.resolve_path(raw)).collect()
595 }
596
597 pub fn destination_thread(
598 input: &Value,
599 context: &ToolContext,
600 default: Option<String>,
601 ) -> Result<Option<String>, ToolError> {
602 match optional_str(input, "thread_id")?.map(str::trim) {
603 None => Ok(default),
604 Some("") => Ok(None),
605 Some(id) => match context.runtime.active_thread_id.as_deref() {
606 Some(current) if id == "current" || id == current => Ok(Some(current.to_string())),
607 Some(_) => Err(ToolError::invalid_input(
608 "thread_id can name only this thread (\"current\"); the Runtime API targets other threads",
609 )),
610 None => Err(ToolError::invalid_input(
611 "thread_id: this session is not a Runtime thread",
612 )),
613 },
614 }
615 }
616
617 fn optional_bool_value(input: &Value, field: &str) -> Option<bool> {
618 input.get(field).and_then(Value::as_bool)
619 }
620
621 /// Parse an `automation_update` status. #5123-class: unknown statuses used to
622 /// coerce to Active — the opposite of pause intent, and run-scheduling.
623 fn parse_automation_status(value: &str) -> Result<AutomationStatus, ToolError> {
624 match value {
625 "active" => Ok(AutomationStatus::Active),
626 "paused" => Ok(AutomationStatus::Paused),
627 other => Err(ToolError::invalid_input(format!(
628 "unknown automation status '{other}'; expected 'active' or 'paused'"
629 ))),
630 }
631 }
632
633 fn optional_delivery_mode(input: &Value) -> Result<Option<AutomationDeliveryMode>, ToolError> {
634 match optional_str(input, "delivery_mode")? {
635 None => Ok(None),
636 Some("task") => Ok(Some(AutomationDeliveryMode::Task)),
637 Some("watcher") => Ok(Some(AutomationDeliveryMode::Watcher)),
638 Some(other) => Err(ToolError::invalid_input(format!(
639 "automation: invalid delivery_mode `{other}` (expected task or watcher)"
640 ))),
641 }
642 }
643
644 #[cfg(test)]
645 mod tests {
646 use super::*;
647 use crate::tools::spec::ToolSpec;
648
649 #[tokio::test]
650 async fn stored_automation_carries_the_creating_session_deny_rules() {
651 let workspace = tempfile::tempdir().expect("workspace");
652 let manager = crate::automation_manager::AutomationManager::open_for_test(
653 workspace.path().join("automations"),
654 )
655 .expect("automation manager");
656 let shared = std::sync::Arc::new(tokio::sync::Mutex::new(manager));
657 let tool = AutomationTool::new("automation");
658 let mut restricted = ToolContext::new(workspace.path());
659 restricted.runtime.automations = Some(shared.clone());
660 restricted.disallowed_tools = vec!["mcp_secret_*".to_string()];
661 let mut open = ToolContext::new(workspace.path());
662 open.runtime.automations = Some(shared.clone());
663 let create = |name: &str| {
664 json!({
665 "action": "create",
666 "name": name,
667 "prompt": "summarise the day",
668 "rrule": "FREQ=HOURLY",
669 "paused": true
670 })
671 };
672
673 let created = tool
674 .execute(create("restricted"), &restricted)
675 .await
676 .expect("create accepted");
677 let record: Value = serde_json::from_str(&created.content).expect("record json");
678 assert_eq!(
679 record["disallowed_tools"],
680 json!(["mcp_secret_*"]),
681 "{record}"
682 );
683 let restricted_id = record["id"].as_str().expect("id").to_string();
684
685 let created = tool
686 .execute(create("open"), &open)
687 .await
688 .expect("create accepted");
689 let record: Value = serde_json::from_str(&created.content).expect("record json");
690 assert!(record.get("disallowed_tools").is_none(), "{record}");
691 let open_id = record["id"].as_str().expect("id").to_string();
692
693 tool.execute(
694 json!({"action": "update", "automation_id": restricted_id, "prompt": "again"}),
695 &restricted,
696 )
697 .await
698 .expect("a session may edit what runs under its own rules");
699 for action in ["update", "resume"] {
700 let refused = tool
701 .execute(
702 json!({"action": action, "automation_id": open_id, "prompt": "inject"}),
703 &restricted,
704 )
705 .await;
706 assert!(
707 refused.is_err(),
708 "{action}: an automation without the session's deny rules is out of reach"
709 );
710 }
711 }
712
713 #[tokio::test]
714 async fn create_and_update_cap_requested_authority_at_the_session() {
715 let workspace = tempfile::tempdir().expect("workspace");
716 let manager = crate::automation_manager::AutomationManager::open_for_test(
717 workspace.path().join("automations"),
718 )
719 .expect("automation manager");
720 let mut context = ToolContext::new(workspace.path());
721 context.shell_policy = codewhale_agent_contract::worker_profile::ShellPolicy::None;
722 context.runtime.automations = Some(std::sync::Arc::new(tokio::sync::Mutex::new(manager)));
723 let tool = AutomationTool::new("automation");
724
725 let created = tool
726 .execute(
727 json!({
728 "action": "create",
729 "name": "nightly",
730 "prompt": "summarise the day",
731 "rrule": "FREQ=HOURLY",
732 "paused": true,
733 "auto_approve": true,
734 "trust_mode": true,
735 "allow_shell": true
736 }),
737 &context,
738 )
739 .await
740 .expect("create accepted");
741 let record: Value = serde_json::from_str(&created.content).expect("record json");
742 assert_eq!(record["auto_approve"], json!(false), "{record}");
743 assert_eq!(record["trust_mode"], json!(false), "{record}");
744 assert_eq!(record["allow_shell"], json!(false), "{record}");
745 let id = record["id"].as_str().expect("id").to_string();
746
747 let updated = tool
748 .execute(
749 json!({"action": "update", "automation_id": id, "auto_approve": true}),
750 &context,
751 )
752 .await
753 .expect("update accepted");
754 let record: Value = serde_json::from_str(&updated.content).expect("record json");
755 assert_eq!(record["auto_approve"], json!(false), "{record}");
756
757 let outside = tool
758 .execute(
759 json!({
760 "action": "create",
761 "name": "elsewhere",
762 "prompt": "summarise",
763 "rrule": "FREQ=HOURLY",
764 "paused": true,
765 "cwds": ["/"]
766 }),
767 &context,
768 )
769 .await;
770 assert!(
771 outside.is_err(),
772 "a directory outside the workspace is refused"
773 );
774
775 // A session that holds the authority can still hand it on.
776 context.approval_mode = codewhale_execpolicy::ApprovalMode::Bypass;
777 context.trust_mode = true;
778 let granted = tool
779 .execute(
780 json!({
781 "action": "create",
782 "name": "unattended",
783 "prompt": "summarise",
784 "rrule": "FREQ=HOURLY",
785 "paused": true,
786 "auto_approve": true,
787 "trust_mode": true
788 }),
789 &context,
790 )
791 .await
792 .expect("create accepted");
793 let record: Value = serde_json::from_str(&granted.content).expect("record json");
794 assert_eq!(record["auto_approve"], json!(true), "{record}");
795 assert_eq!(record["trust_mode"], json!(true), "{record}");
796 }
797
798 #[tokio::test]
799 async fn a_session_cannot_edit_or_start_an_automation_that_holds_more_than_it() {
800 let workspace = tempfile::tempdir().expect("workspace");
801 let manager = crate::automation_manager::AutomationManager::open_for_test(
802 workspace.path().join("automations"),
803 )
804 .expect("automation manager");
805 let mut full = ToolContext::new(workspace.path());
806 full.approval_mode = codewhale_execpolicy::ApprovalMode::Bypass;
807 full.trust_mode = true;
808 full.runtime.automations = Some(std::sync::Arc::new(tokio::sync::Mutex::new(manager)));
809 let tool = AutomationTool::new("automation");
810 let created = tool
811 .execute(
812 json!({
813 "action": "create",
814 "name": "unattended",
815 "prompt": "summarise",
816 "rrule": "FREQ=HOURLY",
817 "paused": true,
818 "auto_approve": true,
819 "trust_mode": true
820 }),
821 &full,
822 )
823 .await
824 .expect("create accepted");
825 let record: Value = serde_json::from_str(&created.content).expect("record json");
826 assert_eq!(record["auto_approve"], json!(true), "{record}");
827 let id = record["id"].as_str().expect("id").to_string();
828
829 // The same store, seen from a session in the default approval mode.
830 let mut lesser = full.clone();
831 lesser.approval_mode = codewhale_execpolicy::ApprovalMode::default();
832 lesser.trust_mode = false;
833 assert_ne!(
834 lesser.approval_mode,
835 codewhale_execpolicy::ApprovalMode::Bypass
836 );
837
838 for call in [
839 json!({"action": "update", "automation_id": id, "prompt": "something else"}),
840 json!({"action": "update", "automation_id": id, "auto_approve": false, "prompt": "x"}),
841 json!({"action": "resume", "automation_id": id}),
842 json!({"action": "run", "automation_id": id}),
843 ] {
844 let err = tool
845 .execute(call.clone(), &lesser)
846 .await
847 .expect_err("refused while stored authority exceeds the session");
848 assert!(err.to_string().contains("does not hold"), "{call}: {err}");
849 }
850 let unchanged = full
851 .runtime
852 .automations
853 .as_ref()
854 .expect("store")
855 .lock()
856 .await
857 .get_automation(&id)
858 .expect("record");
859 assert_eq!(unchanged.prompt, "summarise");
860
861 // Lowering every stored field in the same update is allowed, and
862 // pausing never needs the authority.
863 let lowered = tool
864 .execute(
865 json!({
866 "action": "update",
867 "automation_id": id,
868 "prompt": "something else",
869 "auto_approve": false,
870 "trust_mode": false
871 }),
872 &lesser,
873 )
874 .await
875 .expect("lowering update accepted");
876 let record: Value = serde_json::from_str(&lowered.content).expect("record json");
877 assert_eq!(record["auto_approve"], json!(false), "{record}");
878 assert_eq!(record["trust_mode"], json!(false), "{record}");
879 assert_eq!(record["prompt"], json!("something else"), "{record}");
880 tool.execute(json!({"action": "pause", "automation_id": id}), &lesser)
881 .await
882 .expect("pause accepted");
883 }
884
885 #[test]
886 fn create_schema_exposes_rrule() {
887 let schema = AutomationTool::new("automation").input_schema();
888 assert!(schema["properties"]["rrule"].is_object());
889 }
890
891 #[test]
892 fn update_status_rejects_unknown_values_instead_of_coercing_to_active() {
893 assert!(matches!(
894 parse_automation_status("active"),
895 Ok(AutomationStatus::Active)
896 ));
897 assert!(matches!(
898 parse_automation_status("paused"),
899 Ok(AutomationStatus::Paused)
900 ));
901 for bad in ["pause", "disabled", "off", "stopped", ""] {
902 let err = parse_automation_status(bad).expect_err("must not coerce");
903 assert!(
904 err.to_string().contains("expected 'active' or 'paused'"),
905 "{err}"
906 );
907 }
908 }
909
910 #[test]
911 fn create_schema_auto_approve_defaults_to_false() {
912 let schema = AutomationTool::new("automation").input_schema();
913 let auto_approve = &schema["properties"]["auto_approve"];
914 assert_eq!(auto_approve["type"], "boolean");
915 assert_eq!(auto_approve["default"], false);
916 }
917
918 #[test]
919 fn create_schema_exposes_delivery_mode_and_new_schedule_forms() {
920 let schema = AutomationTool::new("automation").input_schema();
921 assert!(schema["properties"]["model"].is_object());
922 assert_eq!(
923 schema["properties"]["delivery_mode"]["enum"],
924 json!(["task", "watcher"])
925 );
926 let description = schema["properties"]["rrule"]["description"]
927 .as_str()
928 .expect("rrule description");
929 assert!(description.contains("FREQ=ONCE"));
930 assert!(description.contains("FREQ=CRON"));
931 }
932
933 #[test]
934 fn canonical_schema_lists_all_actions_and_union_fields() {
935 let schema = AutomationTool::new("automation").input_schema();
936 let actions = schema["properties"]["action"]["enum"]
937 .as_array()
938 .expect("action enum");
939 for action in [
940 "create", "list", "read", "update", "pause", "resume", "delete", "run",
941 ] {
942 assert!(
943 actions.iter().any(|value| value.as_str() == Some(action)),
944 "canonical schema must offer action {action}"
945 );
946 }
947 for field in [
948 "name",
949 "prompt",
950 "rrule",
951 "model",
952 "delivery_mode",
953 "automation_id",
954 "limit",
955 ] {
956 assert!(
957 schema["properties"][field].is_object(),
958 "canonical schema must carry union field {field}"
959 );
960 }
961 assert_eq!(schema["additionalProperties"], json!(false));
962 }
963
964 #[test]
965 fn read_only_variant_only_offers_read_actions() {
966 let tool = AutomationTool::read_only("automation");
967 let schema = tool.input_schema();
968 let actions = schema["properties"]["action"]["enum"]
969 .as_array()
970 .expect("action enum");
971 assert_eq!(actions, &vec![json!("list"), json!("read")]);
972 assert!(!schema["properties"]["rrule"].is_object());
973 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
974 assert!(tool.is_read_only());
975 }
976
977 #[test]
978 fn canonical_routes_approval_and_read_only_by_action() {
979 let canonical = AutomationTool::new("automation");
980 assert!(canonical.model_visible());
981 // Approval routing stays per action: read actions auto, writes required.
982 assert_eq!(
983 canonical.approval_requirement_for(&json!({"action": "list"})),
984 ApprovalRequirement::Auto
985 );
986 assert_eq!(
987 canonical.approval_requirement_for(&json!({"action": "delete"})),
988 ApprovalRequirement::Required
989 );
990 assert!(canonical.is_read_only_for(&json!({"action": "read"})));
991 assert!(!canonical.is_read_only_for(&json!({"action": "create"})));
992 }
993
994 #[test]
995 fn canonical_rejects_unknown_or_missing_action() {
996 let tool = AutomationTool::new("automation");
997 let err = tool
998 .resolve_action(&json!({}))
999 .expect_err("missing action must fail");
1000 assert!(err.to_string().contains("missing `action`"));
1001 let err = tool
1002 .resolve_action(&json!({"action": "explode"}))
1003 .expect_err("unknown action must fail");
1004 assert!(err.to_string().contains("invalid action"));
1005
1006 let read_only = AutomationTool::read_only("automation");
1007 let err = read_only
1008 .resolve_action(&json!({"action": "delete"}))
1009 .expect_err("read-only surface must reject write actions");
1010 assert!(err.to_string().contains("invalid action"));
1011 }
1012
1013 /// Exec-shaped services: the shared store is attached, but the one-shot
1014 /// host holds no task-execution lease, so its manager is unbound.
1015 fn exec_shaped_context(tmp: &tempfile::TempDir) -> ToolContext {
1016 let manager = crate::automation_manager::AutomationManager::open(tmp.path().to_path_buf())
1017 .expect("open store");
1018 assert!(
1019 manager.execution_scope().is_none(),
1020 "fixture must model the unbound one-shot host"
1021 );
1022 context_with(manager)
1023 }
1024
1025 /// A host that owns the task-execution lease, as the Runtime and the
1026 /// interactive session do.
1027 fn owning_context(tmp: &tempfile::TempDir) -> ToolContext {
1028 context_with(
1029 crate::automation_manager::AutomationManager::open_for_test(tmp.path().to_path_buf())
1030 .expect("open store"),
1031 )
1032 }
1033
1034 fn context_with(manager: crate::automation_manager::AutomationManager) -> ToolContext {
1035 ToolContext::new(".").with_runtime_services(crate::tools::spec::RuntimeToolServices {
1036 automations: Some(std::sync::Arc::new(tokio::sync::Mutex::new(manager))),
1037 ..Default::default()
1038 })
1039 }
1040
1041 fn create_input(paused: bool) -> Value {
1042 json!({
1043 "action": "create",
1044 "name": "nightly",
1045 "prompt": "Summarize what landed today.",
1046 "rrule": "FREQ=WEEKLY;BYDAY=MO;BYHOUR=9;BYMINUTE=30",
1047 "paused": paused,
1048 })
1049 }
1050
1051 /// The reproduced defect. With the store attached, inspection works —
1052 /// headless exec no longer answers "AutomationManager is not attached" for
1053 /// the read actions it advertises.
1054 #[tokio::test]
1055 async fn inspection_works_without_a_dispatch_owner() {
1056 let tmp = tempfile::TempDir::new().expect("tempdir");
1057 let ctx = exec_shaped_context(&tmp);
1058 let tool = AutomationTool::new("automation");
1059 let result = tool
1060 .execute(json!({"action": "list"}), &ctx)
1061 .await
1062 .expect("list must serve an attached store");
1063 assert_eq!(result.content.trim(), "[]");
1064 }
1065
1066 /// Attaching the store must not let a host without a dispatch owner
1067 /// promise work it cannot deliver: only the owning scope's scheduler
1068 /// admits a record, so an Active definition written here would carry a
1069 /// `next_run_at` nothing honors.
1070 #[tokio::test]
1071 async fn activating_work_requires_a_dispatch_owner() {
1072 let tmp = tempfile::TempDir::new().expect("tempdir");
1073 let ctx = exec_shaped_context(&tmp);
1074 let tool = AutomationTool::new("automation");
1075
1076 for (input, what) in [
1077 (create_input(false), "create an active automation"),
1078 (
1079 json!({"action": "update", "automation_id": "a1", "status": "active"}),
1080 "activate an automation",
1081 ),
1082 (json!({"action": "resume", "automation_id": "a1"}), "resume"),
1083 ] {
1084 let err = tool
1085 .execute(input, &ctx)
1086 .await
1087 .expect_err("must refuse without a dispatch owner");
1088 let message = err.to_string();
1089 assert!(
1090 message.contains("persistent execution owner"),
1091 "{what} must explain the missing owner: {message}"
1092 );
1093 }
1094 assert!(
1095 crate::automation_manager::AutomationManager::open(tmp.path().to_path_buf())
1096 .expect("reopen")
1097 .list_automations()
1098 .expect("list")
1099 .is_empty(),
1100 "a refused activation must not leave a record behind"
1101 );
1102 }
1103
1104 /// A paused definition is inert by construction and is adopted by the
1105 /// first owning host that resumes it, so storing intent stays honest.
1106 #[tokio::test]
1107 async fn a_paused_definition_is_still_allowed_without_an_owner() {
1108 let tmp = tempfile::TempDir::new().expect("tempdir");
1109 let ctx = exec_shaped_context(&tmp);
1110 let tool = AutomationTool::new("automation");
1111 tool.execute(create_input(true), &ctx)
1112 .await
1113 .expect("paused definitions need no dispatch owner");
1114 let stored = crate::automation_manager::AutomationManager::open(tmp.path().to_path_buf())
1115 .expect("reopen")
1116 .list_automations()
1117 .expect("list");
1118 assert_eq!(stored.len(), 1);
1119 assert_eq!(stored[0].status, AutomationStatus::Paused);
1120 assert!(
1121 stored[0].next_run_at.is_none(),
1122 "a paused definition must not advertise a next run"
1123 );
1124 }
1125
1126 /// The guard is about the *host*, not the action: a host that owns the
1127 /// lease keeps creating active automations exactly as before.
1128 #[tokio::test]
1129 async fn an_owning_host_still_creates_active_automations() {
1130 let tmp = tempfile::TempDir::new().expect("tempdir");
1131 let ctx = owning_context(&tmp);
1132 let tool = AutomationTool::new("automation");
1133 tool.execute(create_input(false), &ctx)
1134 .await
1135 .expect("an owning host may schedule");
1136 let stored = crate::automation_manager::AutomationManager::open(tmp.path().to_path_buf())
1137 .expect("reopen")
1138 .list_automations()
1139 .expect("list");
1140 assert_eq!(stored.len(), 1);
1141 assert_eq!(stored[0].status, AutomationStatus::Active);
1142 assert!(stored[0].next_run_at.is_some());
1143 }
1144 }
1145
1145 lines RUST