1use std::sync::{Arc, OnceLock};
9use std::time::Duration;
10
11use bollard::container::LogOutput;
12use futures_util::StreamExt as _;
13
14use super::ContainerManager;
15use crate::backend::container::ContainerRuntimeHandle;
16use crate::backend::container_status::ContainerState;
17
18#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct ReadOutput {
21 pub exit: Option<i64>,
23 pub stdout: Vec<u8>,
24 pub stderr: Vec<u8>,
25}
26
27pub const TIMED_OUT_EXIT: i64 = 124;
29
30pub const NOT_RUNNING: &str = "The agent's container isn't running.";
32
33const KEEP_STDERR: usize = 16 * 1024;
35
36const GRACE: Duration = Duration::from_secs(3);
38
39const BOUNDED: &str = r#"t=$1; shift; if command -v timeout >/dev/null 2>&1; then exec timeout -k 1 "$t" "$@"; fi; exec "$@""#;
42
43fn bounded(argv: &[String], limit: Duration) -> Vec<String> {
45 let mut cmd = vec!["sh".to_string(), "-c".to_string(), BOUNDED.to_string(), "sh".to_string(), limit.as_secs().max(1).to_string()];
46 cmd.extend(argv.iter().cloned());
47 cmd
48}
49
50impl ContainerManager {
51 pub(crate) async fn exec_read(
54 &self,
55 container: &str,
56 argv: &[String],
57 env: &[(String, String)],
58 limit: Duration,
59 max_stdout: usize,
60 ) -> Result<ReadOutput, String> {
61 let session = self.exec(container, &bounded(argv, limit), None, env, false).await.map_err(|e| e.to_string())?;
62 let exec_id = session.exec_id.clone();
63 drop(session.input);
64 let mut stream = session.output;
65 let mut out = ReadOutput::default();
66 let drain = async {
67 while let Some(item) = stream.next().await {
68 match item.map_err(|e| e.to_string())? {
69 LogOutput::StdOut { message } => {
70 if out.stdout.len() + message.len() > max_stdout {
71 return Err("It printed more than can be read.".to_string());
72 }
73 out.stdout.extend_from_slice(&message);
74 }
75 LogOutput::StdErr { message } if out.stderr.len() < KEEP_STDERR => out.stderr.extend_from_slice(&message),
76 _ => {}
77 }
78 }
79 Ok(())
80 };
81 match tokio::time::timeout(limit + GRACE, drain).await {
82 Err(_) => return Err("It took too long to answer.".to_string()),
83 Ok(done) => done?,
84 }
85 for _ in 0..10 {
87 out.exit = self.inspect_exec(&exec_id).await.map_err(|e| e.to_string())?;
88 if out.exit.is_some() {
89 break;
90 }
91 tokio::time::sleep(Duration::from_millis(50)).await;
92 }
93 Ok(out)
94 }
95}
96
97static RUNTIME: OnceLock<Arc<ContainerRuntimeHandle>> = OnceLock::new();
98
99pub fn install(handle: &Arc<ContainerRuntimeHandle>) {
102 let _ = RUNTIME.set(Arc::clone(handle));
103}
104
105fn known_not_running(container: &str) -> bool {
107 crate::backend::container_status::hub()
108 .is_some_and(|hub| hub.list().containers.iter().any(|c| c.name == container && c.state != ContainerState::Running))
109}
110
111pub async fn read(
114 container: &str,
115 argv: &[String],
116 env: &[(String, String)],
117 limit: Duration,
118 max_stdout: usize,
119) -> Result<ReadOutput, String> {
120 #[cfg(test)]
121 {
122 let stand_in = stand_ins().lock().get(container).cloned();
123 if let Some(stand_in) = stand_in {
124 return stand_in(argv, env);
125 }
126 }
127 if container.is_empty() || known_not_running(container) {
128 return Err(NOT_RUNNING.to_string());
129 }
130 let manager = match RUNTIME.get() {
131 Some(handle) => handle.get().await,
132 None => None,
133 };
134 let Some(manager) = manager else {
135 return Err("No container runtime is running.".to_string());
136 };
137 manager.exec_read(container, argv, env, limit, max_stdout).await
138}
139
140#[cfg(test)]
141type StandIn = Arc<dyn Fn(&[String], &[(String, String)]) -> Result<ReadOutput, String> + Send + Sync>;
142
143#[cfg(test)]
144fn stand_ins() -> &'static parking_lot::Mutex<std::collections::HashMap<String, StandIn>> {
145 static STAND_INS: std::sync::LazyLock<parking_lot::Mutex<std::collections::HashMap<String, StandIn>>> =
146 std::sync::LazyLock::new(Default::default);
147 &STAND_INS
148}
149
150#[cfg(test)]
153pub(crate) fn stand_in_for_test(
154 container: &str,
155 answer: impl Fn(&[String], &[(String, String)]) -> Result<ReadOutput, String> + Send + Sync + 'static,
156) {
157 stand_ins().lock().insert(container.to_string(), Arc::new(answer));
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 #[test]
165 fn a_command_is_run_under_a_limit_and_never_spliced_into_the_script() {
166 let argv = vec!["git".to_string(), "-C".to_string(), "/workspace/a b; rm -rf /".to_string(), "status".to_string()];
167 let cmd = bounded(&argv, Duration::from_millis(4500));
168 assert_eq!(&cmd[..5], ["sh", "-c", BOUNDED, "sh", "4"]);
169 assert_eq!(&cmd[5..], &argv[..], "each word is one argument of the script");
170 assert_eq!(bounded(&argv, Duration::from_millis(10))[4], "1", "never a limit of none");
171 }
172
173 #[tokio::test]
174 async fn a_container_that_is_not_there_has_no_answer_and_nothing_is_started() {
175 assert_eq!(read("", &[], &[], Duration::from_secs(1), 10).await, Err(NOT_RUNNING.to_string()));
176 let other = read("agentmux-read-exec-none", &["true".to_string()], &[], Duration::from_secs(1), 10).await;
178 assert!(other.is_err(), "{other:?}");
179 }
180
181 #[tokio::test]
184 #[ignore]
185 async fn itest_exec_read_collects_output_and_exit_and_stops_a_slow_command() {
186 let cm = ContainerManager::connect().expect("connect to docker (set DOCKER_HOST)");
187 cm.check_available().await.expect("docker daemon must be reachable");
188 let name = "agentmux-itest-read-exec";
189 let image = "ghcr.io/agentmuxai/agent-base:0.59.41";
190 let clean = || async {
191 let _ = cm.remove(name, true).await;
192 for volume in ["claude", "cli"] {
193 let _ = cm.inner.docker.remove_volume(&format!("agentmux-{volume}-{name}"), None).await;
194 }
195 };
196 clean().await;
197 let spec = crate::backend::container::ContainerMountSpec::default();
198 cm.ensure_running_observed(name, image, &[], &[], &spec, &|_| {}).await.expect("ensure_running");
199
200 let words = |w: &[&str]| w.iter().map(|s| s.to_string()).collect::<Vec<_>>();
201 let pair = |k: &str, v: &str| (k.to_string(), v.to_string());
202 let limit = Duration::from_secs(4);
203 let both = cm.exec_read(name, &words(&["sh", "-c", "printf 'out\\0put|'; printf err >&2; id -u"]), &[], limit, 1024).await;
204 let env = [pair("GIT_ALLOW_PROTOCOL", ""), pair("GIT_NO_LAZY_FETCH", "1")];
205 let with_env = cm.exec_read(name, &words(&["sh", "-c", "printf %s \"${GIT_ALLOW_PROTOCOL-unset}|$GIT_NO_LAZY_FETCH\""]), &env, limit, 1024).await;
206 let failed = cm.exec_read(name, &words(&["sh", "-c", "exit 3"]), &[], limit, 1024).await;
207 let git = cm.exec_read(name, &words(&["git", "-C", "/nowhere", "rev-parse", "--show-toplevel"]), &[], limit, 1024).await;
208 let began = std::time::Instant::now();
209 let slow = cm.exec_read(name, &words(&["sleep", "31"]), &[], Duration::from_secs(1), 1024).await;
210 let took = began.elapsed();
211 tokio::time::sleep(Duration::from_secs(2)).await;
212 let left = cm.exec_read(name, &words(&["sh", "-c", "pgrep -fx 'sleep 31' | wc -l"]), &[], limit, 1024).await;
215 let kept = cm.exec_read(name, &words(&["sh", "-c", "pgrep -fx 'sleep infinity' | wc -l"]), &[], limit, 1024).await;
216 let big = cm.exec_read(name, &words(&["sh", "-c", "head -c 5000 /dev/zero"]), &[], limit, 1024).await;
217 clean().await;
218 println!("both={both:?}\nwith_env={with_env:?}\nfailed={failed:?}\ngit={git:?}\nslow={slow:?} took={took:?}\nleft={left:?}\nkept={kept:?}\nbig={big:?}");
219
220 let both = both.expect("a command that prints");
221 assert_eq!(both.exit, Some(0));
222 assert!(both.stdout.starts_with(b"out\0put|") && both.stdout.ends_with(b"\n"), "output is kept byte for byte: {both:?}");
223 assert_ne!(&both.stdout[8..], b"0\n", "it runs as the agent's user, not as root");
224 assert_eq!(both.stderr, b"err", "the error text is apart from the output");
225 assert_eq!(with_env.expect("a command with an environment").stdout, b"|1", "an empty value is set, not left out");
226 let failed = failed.expect("a command that fails");
227 assert_eq!((failed.exit, failed.stderr.is_empty()), (Some(3), true));
228 let git = git.expect("git in a folder that is not there");
229 assert!(git.exit.is_some_and(|code| code != 0) && !git.stderr.is_empty(), "{git:?}");
230 assert_eq!(slow.expect("a command that runs past its limit").exit, Some(TIMED_OUT_EXIT));
231 assert!(took < limit + GRACE, "took {took:?}");
232 assert_eq!(String::from_utf8_lossy(&left.expect("a look for what is left").stdout).trim(), "0", "the slow command was stopped inside the container");
233 assert_eq!(String::from_utf8_lossy(&kept.expect("a look for what is kept").stdout).trim(), "1", "the look counts a command that is still running");
234 assert!(big.is_err(), "more output than asked for is refused: {big:?}");
235 }
236
237 #[tokio::test]
238 async fn a_stand_in_answers_for_its_container_only() {
239 stand_in_for_test("agentmux-read-exec-a", |argv, _| Ok(ReadOutput { exit: Some(0), stdout: argv.join(" ").into_bytes(), stderr: Vec::new() }));
240 let got = read("agentmux-read-exec-a", &["echo".to_string(), "hi".to_string()], &[], Duration::from_secs(1), 10).await.unwrap();
241 assert_eq!(got.stdout, b"echo hi");
242 }
243}