Skip to main content

agentmux_srv/drone/executor/blocks/
run.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Run block: runs a fixed command line in a container
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md §3.6).
6//!
7//! Block config (`node.data`):
8//!   * `command`  required, a list of strings: the program and its arguments. It is an argv, run
9//!                directly, never through a shell: no pipes, no expansion.
10//!   * `env`      optional, an object of environment variables.
11//!   * `cwd`      optional, a directory inside the container.
12//!   * `image`    optional, the container image; this AgentMux's base image when absent.
13//!   * `where`    `"container"` (the default). `"host"` is refused: it needs a named allowance that
14//!                this build has no way to give.
15//!   * `ok_exit_codes`  optional, the exit codes that are not a failure (`[0]` when absent).
16//!   * `timeout_seconds`  how long it may run: 5 minutes when absent, at most 60 minutes.
17//!
18//! **The command line is never built from outside text.** Every `{{reference}}` in `command`, `env`
19//! and `cwd` must read a clean value (written in the graph, or a number or id made of it); one that
20//! reads text from outside the drone (an event, a web response, an agent's answer, or a number
21//! worked out from one) is refused when the block runs.
22//!
23//! The container has no network, no mounts, a read-only root, no capabilities and limits on
24//! memory, processes and CPU (`backend::container::oneshot`). Mounts, network hosts and secrets are
25//! not supported yet: a block that asks for them is refused, so none is given by mistake.
26//!
27//! Output: `{ "exit_code", "stdout", "stderr", "duration_ms", "truncated" }`, with stdout and
28//! stderr cut at 64 KB. All of it is outside text (the block's output is tainted). An exit code
29//! that is not in `ok_exit_codes` fails the block.
30
31use serde_json::{json, Value};
32
33use crate::backend::container::image::{resolve_container_image, DEFAULT_AGENT_IMAGE};
34use crate::backend::container::oneshot::{OneShot, OneShotOutcome};
35use crate::drone::data_flow::ExecutionScope;
36use crate::drone::types::FlowNode;
37
38/// The longest a Run block may be given, in seconds.
39pub const MAX_TIMEOUT_SECONDS: u64 = 3_600;
40/// How much of stderr is put in the error of a block that failed.
41const ERROR_TAIL_CHARS: usize = 300;
42/// What a block asking for these gets, until they are supported.
43const NOT_YET: [&str; 6] = ["mounts", "hosts", "network", "vault", "secrets", "stdin"];
44
45/// A command, with its references still to fill in.
46#[derive(Debug, PartialEq)]
47pub(crate) struct RunSpec {
48    pub image: Option<String>,
49    pub command: Vec<String>,
50    pub env: Vec<(String, String)>,
51    pub cwd: Option<String>,
52    pub ok_exit_codes: Vec<i64>,
53}
54
55/// The block's settings, as written. Pure: nothing is filled in or run.
56pub(crate) fn parse(node: &FlowNode) -> Result<RunSpec, String> {
57    let data = &node.data;
58    for key in NOT_YET {
59        if data.get(key).is_some_and(|v| !v.is_null()) {
60            return Err(format!("run block: `{key}` is not supported yet: the command runs with no network, no mounts and no secrets"));
61        }
62    }
63    match data.get("where").and_then(Value::as_str).map(str::trim) {
64        None | Some("") | Some("container") => {}
65        Some("host") => return Err("run block: `where: host` needs a named allowance that this build can't give yet; use `where: container`".to_string()),
66        Some(other) => return Err(format!("run block: `where` is `container` or `host`, not `{other}`")),
67    }
68    let command: Vec<String> = data
69        .get("command")
70        .and_then(Value::as_array)
71        .ok_or("run block: `command` must be a list, the program and then its arguments")?
72        .iter()
73        .map(|a| a.as_str().map(str::to_string).ok_or("run block: every item of `command` must be text"))
74        .collect::<Result<_, _>>()?;
75    if command.first().map_or(true, |program| program.trim().is_empty()) {
76        return Err("run block: `command` needs a program as its first item".to_string());
77    }
78    let env = match data.get("env") {
79        None | Some(Value::Null) => Vec::new(),
80        Some(Value::Object(map)) => map
81            .iter()
82            .map(|(k, v)| {
83                let valid = !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !k.starts_with(|c: char| c.is_ascii_digit());
84                match (valid, v.as_str()) {
85                    (true, Some(text)) => Ok((k.clone(), text.to_string())),
86                    (false, _) => Err(format!("run block: `{k}` is not a name an environment variable can have")),
87                    (_, None) => Err(format!("run block: `env.{k}` must be text")),
88                }
89            })
90            .collect::<Result<_, _>>()?,
91        Some(_) => return Err("run block: `env` must be an object of names and text".to_string()),
92    };
93    let cwd = match data.get("cwd") {
94        None | Some(Value::Null) => None,
95        Some(Value::String(s)) if s.trim().is_empty() => None,
96        Some(Value::String(s)) => Some(s.trim().to_string()),
97        Some(_) => return Err("run block: `cwd` must be text".to_string()),
98    };
99    let image = match data.get("image") {
100        None | Some(Value::Null) => None,
101        Some(Value::String(s)) if s.trim().is_empty() => None,
102        Some(Value::String(s)) if s.contains("{{") => return Err("run block: `image` must be written in the graph, not a {{reference}}".to_string()),
103        Some(Value::String(s)) => Some(s.trim().to_string()),
104        Some(_) => return Err("run block: `image` must be text".to_string()),
105    };
106    let ok_exit_codes = match data.get("ok_exit_codes") {
107        None | Some(Value::Null) => vec![0],
108        Some(Value::Array(items)) if !items.is_empty() => {
109            items.iter().map(|c| c.as_i64().ok_or("run block: `ok_exit_codes` must be a list of whole numbers")).collect::<Result<_, _>>()?
110        }
111        Some(_) => return Err("run block: `ok_exit_codes` must be a list of whole numbers".to_string()),
112    };
113    if let Some(secs) = data.get("timeout_seconds").and_then(Value::as_u64) {
114        if secs > MAX_TIMEOUT_SECONDS {
115            return Err(format!("run block: `timeout_seconds` is at most {MAX_TIMEOUT_SECONDS} (60 minutes)"));
116        }
117    }
118    Ok(RunSpec { image, command, env, cwd, ok_exit_codes })
119}
120
121/// The block is set rightly. Called when a graph is checked.
122pub fn check(node: &FlowNode) -> Result<(), String> {
123    parse(node).map(|_| ())
124}
125
126/// What to run, with every reference filled in; refused when one reads outside text.
127pub(crate) fn compose(node: &FlowNode, scope: &ExecutionScope) -> Result<(OneShot, Vec<i64>), String> {
128    let spec = parse(node)?;
129    let clean = |what: String, template: &str| -> Result<String, String> {
130        let (tainted, derived) = scope.bits_of(template);
131        if tainted || derived {
132            let why = if tainted { "text from outside the drone" } else { "a value worked out from text from outside the drone" };
133            return Err(format!("run block: {what} reads {why}; a command line is never built from outside text"));
134        }
135        Ok(scope.resolve(template))
136    };
137    let mut argv = Vec::with_capacity(spec.command.len());
138    for (i, arg) in spec.command.iter().enumerate() {
139        argv.push(clean(format!("`command[{i}]`"), arg)?);
140    }
141    if argv[0].trim().is_empty() {
142        return Err("run block: the program is empty once its references are filled in".to_string());
143    }
144    let mut env = Vec::with_capacity(spec.env.len());
145    for (name, value) in &spec.env {
146        env.push((name.clone(), clean(format!("`env.{name}`"), value)?));
147    }
148    let cwd = spec.cwd.as_deref().map(|c| clean("`cwd`".to_string(), c)).transpose()?;
149    let image = spec.image.unwrap_or_else(|| resolve_container_image(DEFAULT_AGENT_IMAGE));
150    Ok((OneShot { image, argv, env, cwd }, spec.ok_exit_codes))
151}
152
153pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
154    let (one, ok_codes) = compose(node, scope)?;
155    let state = crate::drone::host::state()?;
156    let manager = state.container_manager.get_or_explain().await.map_err(|e| format!("run block: {e}"))?;
157    let outcome = manager.run_oneshot(&one).await.map_err(|e| format!("run block: {e}"))?;
158    outcome_of(&outcome, &ok_codes)
159}
160
161/// What the command came to, as the block's output; a code that is not an ok one fails the block.
162pub(crate) fn outcome_of(done: &OneShotOutcome, ok_codes: &[i64]) -> Result<Value, String> {
163    if !ok_codes.contains(&done.exit_code) {
164        let tail = tail_line(&done.stderr);
165        return Err(if tail.is_empty() { format!("run block: the command exited with code {}", done.exit_code) } else { format!("run block: the command exited with code {}: {tail}", done.exit_code) });
166    }
167    Ok(json!({
168        "exit_code": done.exit_code,
169        "stdout": done.stdout,
170        "stderr": done.stderr,
171        "duration_ms": done.duration_ms,
172        "truncated": done.truncated,
173    }))
174}
175
176/// The end of `text` on one line.
177fn tail_line(text: &str) -> String {
178    let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
179    let count = flat.chars().count();
180    if count <= ERROR_TAIL_CHARS {
181        return flat;
182    }
183    let tail: String = flat.chars().skip(count - ERROR_TAIL_CHARS).collect();
184    format!("…{tail}")
185}
186
187#[cfg(test)]
188#[path = "run_tests.rs"]
189mod tests;