vtcode_computer_use/browser/
container.rs1use std::{ffi::OsString, path::Path, time::Duration};
10
11use anyhow::{Context, Result, bail, ensure};
12use tokio::process::{Child, ChildStdin, ChildStdout, Command};
13
14const DOCKER_TIMEOUT: Duration = Duration::from_secs(30);
15const AVAILABILITY_TIMEOUT: Duration = Duration::from_secs(10);
16const IDENTIFY_TIMEOUT: Duration = Duration::from_secs(15);
17const IDENTIFY_INTERVAL: Duration = Duration::from_millis(200);
18const CONTAINER_NAME_PREFIX: &str = "vtcode-cua-";
19const CONTAINER_ID_LEN: usize = 64;
20const DIAGNOSTIC_MAX_BYTES: usize = 512;
21
22pub struct ContainerSpec {
24 image: String,
25 build_dir: String,
26}
27
28impl ContainerSpec {
29 pub async fn approved(image: &str, build_dir: &Path) -> Result<Self> {
40 ensure!(!image.is_empty() && image.len() <= 512, "invalid browser container image");
41 ensure!(image.chars().all(|c| !c.is_control() && !c.is_whitespace()), "invalid browser container image");
42 ensure!(has_image_pin(image) && !image.ends_with(":latest"), "browser container image must be pinned");
43 let canonical = vtcode_commons::fs::canonicalize_with_context_async(build_dir, "browser build").await?;
44 ensure!(canonical.is_dir(), "browser build is not a directory");
45 let Some(dir) = canonical.to_str() else {
46 bail!("browser build path is not representable");
47 };
48 ensure!(mount_spec_safe(dir), "browser build path cannot appear in a mount spec");
49 Ok(Self { image: image.to_owned(), build_dir: dir.to_owned() })
50 }
51}
52
53pub struct ContainerHandle {
57 name: String,
58 id: String,
59 #[allow(dead_code, reason = "Owned for its kill-on-drop backstop; never read directly.")]
60 child: Child,
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum TerminateOutcome {
66 Removed,
68 AlreadyGone,
70}
71
72impl ContainerHandle {
73 pub async fn launch(spec: &ContainerSpec) -> Result<(Self, ChildStdout, ChildStdin)> {
83 let name = format!("{CONTAINER_NAME_PREFIX}{}", uuid::Uuid::new_v4().as_simple());
84 let mut child = Command::new("docker")
85 .args(docker_run_argv(spec, &name))
86 .stdin(std::process::Stdio::piped())
87 .stdout(std::process::Stdio::piped())
88 .stderr(std::process::Stdio::piped())
89 .kill_on_drop(true)
90 .spawn()
91 .context("could not start the approved browser container")?;
92 let replies = child.stdout.take().context("browser container did not pipe its replies")?;
93 let commands = child.stdin.take().context("browser container did not pipe its commands")?;
94 let id = inspect_container_id(&name, &mut child).await?;
95 Ok((Self { name, id, child }, replies, commands))
96 }
97
98 #[must_use]
100 pub fn name(&self) -> &str {
101 &self.name
102 }
103
104 #[must_use]
106 pub fn id(&self) -> &str {
107 &self.id
108 }
109
110 pub async fn terminate(&self) -> Result<TerminateOutcome> {
123 if matches!(self.present().await, Ok(Presence::Missing)) {
129 return Ok(TerminateOutcome::AlreadyGone);
130 }
131 let output = run_docker(&[
132 OsString::from("rm"),
133 OsString::from("--force"),
134 OsString::from(&self.id),
135 ])
136 .await?;
137 if !output.status.success() {
138 let diagnostic = diagnostic_text(&output.stderr);
139 if is_missing_message(&diagnostic) {
140 return Ok(TerminateOutcome::AlreadyGone);
141 }
142 bail!("could not remove browser container {}: {diagnostic}", self.id);
143 }
144 for _ in 0..3 {
147 match self.present().await? {
148 Presence::Missing => return Ok(TerminateOutcome::Removed),
149 Presence::Exists => {
150 bail!("browser container {} is still present", self.id);
151 }
152 Presence::Unknown => tokio::time::sleep(IDENTIFY_INTERVAL).await,
153 }
154 }
155 bail!("could not verify removal of browser container {}", self.id);
156 }
157
158 async fn present(&self) -> Result<Presence> {
161 let output = run_docker(&[OsString::from("inspect"), OsString::from(&self.id)]).await?;
162 if output.status.success() {
163 return Ok(Presence::Exists);
164 }
165 if is_missing_message(&diagnostic_text(&output.stderr)) {
166 return Ok(Presence::Missing);
167 }
168 Ok(Presence::Unknown)
169 }
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173enum Presence {
174 Exists,
175 Missing,
176 Unknown,
177}
178
179fn has_image_pin(image: &str) -> bool {
184 if image.contains('@') {
185 return true;
186 }
187 match image.rsplit_once('/') {
188 Some((_, last)) => last.contains(':'),
189 None => image.contains(':'),
190 }
191}
192
193fn is_missing_message(diagnostic: &str) -> bool {
196 let lower = diagnostic.to_ascii_lowercase();
197 lower.contains("no such container") || lower.contains("no such object")
198}
199
200pub async fn docker_available() -> bool {
203 let Ok(mut child) = Command::new("docker")
204 .arg("info")
205 .stdin(std::process::Stdio::null())
206 .stdout(std::process::Stdio::null())
207 .stderr(std::process::Stdio::null())
208 .kill_on_drop(true)
209 .spawn()
210 else {
211 return false;
212 };
213 tokio::time::timeout(AVAILABILITY_TIMEOUT, child.wait())
214 .await
215 .is_ok_and(|status| status.is_ok_and(|status| status.success()))
216}
217
218fn mount_spec_safe(dir: &str) -> bool {
221 !dir.is_empty() && !dir.chars().any(|c| c.is_control() || matches!(c, ',' | '"' | '\\'))
222}
223
224fn docker_run_argv(spec: &ContainerSpec, name: &str) -> Vec<OsString> {
225 [
226 "run",
227 "--rm",
228 "--interactive",
229 "--init",
230 "--pull=never",
231 "--network=none",
232 "--read-only",
233 "--cap-drop=ALL",
234 "--user=65534",
235 "--security-opt=no-new-privileges",
236 "--pids-limit=256",
237 "--memory=1g",
238 "--tmpfs=/tmp:rw,nosuid,nodev,noexec,size=512m",
239 "--env=HOME=/tmp",
240 ]
241 .into_iter()
242 .map(OsString::from)
243 .chain([
244 OsString::from(format!("--name={name}")),
245 OsString::from(format!("--mount=type=bind,src={},dst=/build,readonly", spec.build_dir)),
246 OsString::from(&spec.image),
247 ])
248 .collect()
249}
250
251async fn inspect_container_id(name: &str, child: &mut Child) -> Result<String> {
252 let start = tokio::time::Instant::now();
253 loop {
254 if let Some(status) = child.try_wait().context("could not poll the browser container")? {
255 bail!(
256 "browser container exited before its identity could be established: {status}: {}",
257 drain_stderr(child).await
258 );
259 }
260 let output = run_docker(&[
261 OsString::from("inspect"),
262 OsString::from("--format={{.Id}}"),
263 OsString::from(name),
264 ])
265 .await?;
266 if output.status.success() {
267 if let Ok(id) = parse_container_id(&String::from_utf8_lossy(&output.stdout)) {
268 return Ok(id);
269 }
270 }
271 ensure!(start.elapsed() < IDENTIFY_TIMEOUT, "could not identify the browser container");
272 tokio::time::sleep(IDENTIFY_INTERVAL).await;
273 }
274}
275
276async fn drain_stderr(child: &mut Child) -> String {
277 use tokio::io::AsyncReadExt;
278 let mut stderr = String::new();
279 if let Some(mut pipe) = child.stderr.take() {
280 let _drained = tokio::time::timeout(Duration::from_secs(2), pipe.read_to_string(&mut stderr)).await;
282 }
283 diagnostic_text(stderr.as_bytes())
284}
285
286fn parse_container_id(raw: &str) -> Result<String> {
287 let id = raw.trim().to_owned();
288 ensure!(
289 id.len() == CONTAINER_ID_LEN && id.chars().all(|c| c.is_ascii_hexdigit()),
290 "could not identify the browser container"
291 );
292 Ok(id)
293}
294
295async fn run_docker(args: &[OsString]) -> Result<std::process::Output> {
296 let child = Command::new("docker")
297 .args(args)
298 .stdin(std::process::Stdio::null())
299 .stdout(std::process::Stdio::piped())
300 .stderr(std::process::Stdio::piped())
301 .kill_on_drop(true)
302 .spawn()
303 .context("could not run docker")?;
304 match tokio::time::timeout(DOCKER_TIMEOUT, child.wait_with_output()).await {
307 Ok(output) => output.context("could not read docker output"),
308 Err(_) => bail!("docker command timed out"),
309 }
310}
311
312fn diagnostic_text(output: &[u8]) -> String {
313 let text = String::from_utf8_lossy(output);
314 let end = text.floor_char_boundary(DIAGNOSTIC_MAX_BYTES.min(text.len()));
315 text.get(..end).unwrap_or_default().to_owned()
316}
317
318#[cfg(test)]
319mod tests;