Skip to main content

agent_commander/
isolation.rs

1use crate::{
2    build_docker_stop_command, build_normalized_result_metadata, build_screen_stop_command,
3    execute_detached_with_env,
4    run_deadline::{IsolationTarget, MAX_TIMER_MS},
5    start_command_with_env, Agent, AgentResult, AgentStartOptions, BuildMetadataOptions,
6};
7use std::time::Duration;
8
9pub fn validate_run_timeout(
10    timeout: Option<Duration>,
11    close_timeout: Option<Duration>,
12    detached: bool,
13) -> Result<(), String> {
14    let max = Duration::from_millis(MAX_TIMER_MS);
15    if timeout.is_some_and(|value| value < Duration::from_millis(1) || value > max) {
16        return Err(format!(
17            "timeout (--timeout-ms) must be from 1 to {MAX_TIMER_MS} milliseconds"
18        ));
19    }
20    if close_timeout.is_some_and(|value| value > max) {
21        return Err(format!(
22            "close timeout (--close-timeout-ms) must be from 0 to {MAX_TIMER_MS} milliseconds"
23        ));
24    }
25    if timeout.is_some() && detached {
26        return Err("timeout (--timeout-ms) requires an attached run".into());
27    }
28    Ok(())
29}
30
31impl Agent {
32    pub async fn isolation_target(
33        &mut self,
34        start: &AgentStartOptions,
35    ) -> Result<Option<IsolationTarget>, String> {
36        if start.dry_run || start.detached {
37            return Ok(None);
38        }
39        Ok(match self.options.isolation.as_str() {
40            "docker" => {
41                let file = self.ensure_prompt_temp_dir().await?.join("container.cid");
42                Some(IsolationTarget::Docker(file.to_string_lossy().into_owned()))
43            }
44            "screen" => self
45                .options
46                .screen_name
47                .clone()
48                .map(IsolationTarget::Screen),
49            _ => None,
50        })
51    }
52
53    pub async fn start_detached(
54        &self,
55        command: &str,
56        child_env: &[(String, String)],
57    ) -> Result<(), String> {
58        if self.options.isolation == "docker" {
59            let mut handle = start_command_with_env(command, false, false, child_env)
60                .await
61                .map_err(|error| error.to_string())?;
62            if handle
63                .wait_for_exit()
64                .await
65                .map_err(|error| error.to_string())?
66                != 0
67            {
68                let (_, stderr, _) = handle.get_output();
69                return Err(stderr.trim().to_owned());
70            }
71        } else {
72            execute_detached_with_env(command, Some(child_env))
73                .await
74                .map_err(|error| error.to_string())?;
75        }
76        println!("Agent started in detached mode");
77        match self.options.isolation.as_str() {
78            "screen" => println!(
79                "Screen session: {}",
80                self.options.screen_name.as_deref().unwrap_or_default()
81            ),
82            "docker" => println!(
83                "Container: {}",
84                self.options.container_name.as_deref().unwrap_or_default()
85            ),
86            _ => {}
87        }
88        Ok(())
89    }
90
91    pub async fn stop_isolated(&mut self, dry_run: bool) -> Result<AgentResult, String> {
92        let command = if self.options.isolation == "screen" {
93            let name = self
94                .options
95                .screen_name
96                .as_deref()
97                .ok_or("screen_name is required to stop screen session")?;
98            build_screen_stop_command(name)
99        } else {
100            let name = self
101                .options
102                .container_name
103                .as_deref()
104                .ok_or("container_name is required to stop docker container")?;
105            build_docker_stop_command(name)
106        };
107        let collected = async {
108            if dry_run {
109                println!("Dry run - command that would be executed:\n{command}");
110                return Ok((0, String::new(), None));
111            }
112            let env = self.child_environment()?;
113            let mut handle = start_command_with_env(&command, true, false, &env)
114                .await
115                .map_err(|error| error.to_string())?;
116            let exit = handle
117                .wait_for_exit()
118                .await
119                .map_err(|error| error.to_string())?;
120            Ok::<_, String>((
121                exit,
122                handle.get_output().0.to_owned(),
123                handle.signal().map(str::to_owned),
124            ))
125        }
126        .await;
127        if !dry_run {
128            self.cleanup_prompt_temp_dir().await;
129        }
130        let (exit_code, plain_output, signal) = collected?;
131        let metadata = build_normalized_result_metadata(BuildMetadataOptions {
132            tool: &self.options.tool,
133            exit_code,
134            plain_output: &plain_output,
135            signal,
136            ..Default::default()
137        });
138        Ok(AgentResult {
139            exit_code: Some(exit_code),
140            error_type: metadata.error_type.clone(),
141            plain_output,
142            metadata,
143            ..Default::default()
144        })
145    }
146}