Skip to main content

aither_sandbox/
tool_environment.rs

1use std::path::{Path, PathBuf};
2
3use futures::{StreamExt, TryStreamExt, stream};
4
5use crate::ContainerPath;
6use crate::shell_session::{
7    ShellBackend, ShellSessionRegistry, SshRuntimeProfile, SshServer, SshSessionAuthorizer,
8    bootstrap_ssh_runtime,
9};
10use crate::tool_distribution::ToolDistribution;
11use crate::tool_runtime::{
12    PreparedEnvironment, PreparedTools, ToolCatalog, ToolRuntimeError, ToolTarget,
13};
14use crate::tool_transport::{ContainerToolTransport, SshToolTransport, probe_tool_environment};
15
16/// The home backend's tools, typed by where that backend sees them.
17#[derive(Debug, Clone)]
18enum PreparedHome {
19    Local(PreparedTools<PathBuf>),
20    Container {
21        container_id: String,
22        tools: PreparedTools<ContainerPath>,
23    },
24}
25
26impl PreparedHome {
27    const fn backend(&self) -> ShellBackend {
28        match self {
29            Self::Local(_) => ShellBackend::Local,
30            Self::Container { .. } => ShellBackend::Container,
31        }
32    }
33
34    const fn catalog(&self) -> &ToolCatalog {
35        match self {
36            Self::Local(tools) => tools.catalog(),
37            Self::Container { tools, .. } => tools.catalog(),
38        }
39    }
40}
41
42#[derive(Debug, Clone)]
43struct PreparedSsh {
44    server: SshServer,
45    runtime: SshRuntimeProfile,
46    tools: PreparedTools<PathBuf>,
47}
48
49#[derive(Debug, Clone)]
50pub struct PreparedToolEnvironments {
51    home: Option<PreparedHome>,
52    ssh: Vec<PreparedSsh>,
53    catalog: ToolCatalog,
54}
55
56impl ShellSessionRegistry {
57    /// Prepares every configured environment before an agent can use this registry.
58    ///
59    /// # Errors
60    /// Fails on unsupported platforms, missing artifacts, denied SSH provisioning,
61    /// integrity failures or inconsistent command versions across environments.
62    pub async fn initialize_tools(
63        mut self,
64        distribution: &ToolDistribution,
65        cache_root: &Path,
66    ) -> Result<Self, ToolRuntimeError> {
67        let availability = self.availability();
68        let home = async {
69            if availability.container {
70                let runtime = self
71                    .container_runtime()
72                    .cloned()
73                    .ok_or(ToolRuntimeError::MissingContainerRuntime)?;
74                let transport = ContainerToolTransport::new(runtime.clone());
75                let info = probe_tool_environment(&transport).await?;
76                let bundle = distribution
77                    .load(&info.target, &cache_root.join("artifacts"))
78                    .await?;
79                let tools = bundle.verify_container_mount(&transport).await?;
80                Ok::<_, ToolRuntimeError>(Some(PreparedHome::Container {
81                    container_id: runtime.container_id().into(),
82                    tools,
83                }))
84            } else if availability.local {
85                let bundle = distribution
86                    .load(&ToolTarget::native()?, &cache_root.join("artifacts"))
87                    .await?;
88                let tools = bundle.prepare_local(&cache_root.join("runtimes")).await?;
89                Ok(Some(PreparedHome::Local(tools)))
90            } else {
91                Ok(None)
92            }
93        };
94        let remote = async {
95            if !availability.ssh {
96                return Ok::<_, ToolRuntimeError>(Vec::new());
97            }
98            let authorizer = self.ssh_authorizer();
99            stream::iter(self.list_ssh_servers())
100                .map(|server| {
101                    let authorizer = authorizer.clone();
102                    async move {
103                        let runtime = bootstrap_ssh_runtime(&server.target, &authorizer).await.map_err(|error| ToolRuntimeError::SshBootstrap(error.to_string()))?;
104                        let transport = SshToolTransport::new(server.clone());
105                        let info = probe_tool_environment(&transport).await?;
106                        let bundle = distribution.load(&info.target, &cache_root.join("artifacts")).await?;
107                        let tools = bundle.prepare_remote(&transport, &info.cache_root, || async {
108                            let authorizer = authorizer.as_ref().ok_or_else(|| ToolRuntimeError::InstallDenied(server.target.clone()))?;
109                            let approved = authorizer.authorize_runtime_install(&server.target, "Prepare verified apply_patch, rg, ast-grep and jq in the managed tools directory.").await.map_err(ToolRuntimeError::Authorization)?;
110                            if !approved { return Err(ToolRuntimeError::InstallDenied(server.target.clone())); }
111                            Ok(())
112                        }).await?;
113                        Ok(PreparedSsh { server, runtime, tools })
114                    }
115                })
116                .buffer_unordered(4)
117                .try_collect::<Vec<_>>()
118                .await
119        };
120        let (home, mut ssh) = futures::try_join!(home, remote)?;
121        ssh.sort_by(|left, right| left.server.id().cmp(right.server.id()));
122        let catalog = home
123            .as_ref()
124            .map(PreparedHome::catalog)
125            .or_else(|| ssh.first().map(|ssh| ssh.tools.catalog()))
126            .ok_or_else(|| {
127                ToolRuntimeError::NotInitialized("no configured execution environment".into())
128            })?
129            .clone();
130        if ssh.iter().any(|ssh| ssh.tools.catalog() != &catalog) {
131            return Err(ToolRuntimeError::CatalogMismatch);
132        }
133        self.prepared_tools = Some(PreparedToolEnvironments { home, ssh, catalog });
134        Ok(self)
135    }
136
137    /// Prepared environments, provided they are exactly the configured backends.
138    ///
139    /// Preparation is bound to the home backend, the container it mounted
140    /// into and the SSH server set; a registry whose configuration changed
141    /// after preparation describes environments nobody prepared.
142    fn prepared_environments(&self) -> Result<&PreparedToolEnvironments, ToolRuntimeError> {
143        let prepared = self
144            .prepared_tools
145            .as_ref()
146            .ok_or_else(|| ToolRuntimeError::NotInitialized("execution environments".into()))?;
147        if prepared.home.as_ref().map(PreparedHome::backend) != self.resolve_local_backend().ok() {
148            return Err(ToolRuntimeError::EnvironmentChanged(
149                PreparedEnvironment::HomeBackend,
150            ));
151        }
152        if let Some(PreparedHome::Container { container_id, .. }) = prepared.home.as_ref()
153            && self
154                .container_runtime()
155                .map(crate::ContainerShellRuntime::container_id)
156                != Some(container_id.as_str())
157        {
158            return Err(ToolRuntimeError::EnvironmentChanged(
159                PreparedEnvironment::Container,
160            ));
161        }
162        let mut configured = if self.availability().ssh {
163            self.ssh_servers().iter().collect::<Vec<_>>()
164        } else {
165            Vec::new()
166        };
167        configured.sort_by(|left, right| left.id().cmp(right.id()));
168        if !prepared
169            .ssh
170            .iter()
171            .map(|ready| &ready.server)
172            .eq(configured)
173        {
174            return Err(ToolRuntimeError::EnvironmentChanged(
175                PreparedEnvironment::SshServers,
176            ));
177        }
178        Ok(prepared)
179    }
180
181    pub(crate) fn local_tools(&self) -> Result<&PreparedTools<PathBuf>, ToolRuntimeError> {
182        match &self.prepared_environments()?.home {
183            Some(PreparedHome::Local(tools)) => Ok(tools),
184            _ => Err(ToolRuntimeError::NotInitialized("local environment".into())),
185        }
186    }
187
188    pub(crate) fn container_tools(
189        &self,
190    ) -> Result<&PreparedTools<ContainerPath>, ToolRuntimeError> {
191        match &self.prepared_environments()?.home {
192            Some(PreparedHome::Container { tools, .. }) => Ok(tools),
193            _ => Err(ToolRuntimeError::NotInitialized(
194                "container environment".into(),
195            )),
196        }
197    }
198
199    pub(crate) fn ssh_tools(
200        &self,
201        server: &SshServer,
202    ) -> Result<(&SshRuntimeProfile, &PreparedTools<PathBuf>), ToolRuntimeError> {
203        self.prepared_environments()?
204            .ssh
205            .iter()
206            .find(|ready| &ready.server == server)
207            .map(|ready| (&ready.runtime, &ready.tools))
208            .ok_or_else(|| ToolRuntimeError::NotInitialized(server.id().into()))
209    }
210
211    /// Catalog derived only from environments that completed initialization.
212    ///
213    /// # Errors
214    /// Rejects an uninitialized registry, or one whose home backend, container
215    /// or SSH server set changed after preparation.
216    pub fn prepared_catalog(&self) -> Result<&ToolCatalog, ToolRuntimeError> {
217        self.prepared_environments()
218            .map(|prepared| &prepared.catalog)
219    }
220
221    #[cfg(test)]
222    pub(crate) fn with_test_tools(self, tools: PreparedTools<PathBuf>) -> Self {
223        self.with_test_home(PreparedHome::Local(tools))
224    }
225
226    #[cfg(test)]
227    pub(crate) fn with_test_container_tools(
228        self,
229        tools: PreparedTools<ContainerPath>,
230        container_id: String,
231    ) -> Self {
232        self.with_test_home(PreparedHome::Container {
233            container_id,
234            tools,
235        })
236    }
237
238    #[cfg(test)]
239    fn with_test_home(mut self, home: PreparedHome) -> Self {
240        let catalog = home.catalog().clone();
241        self.prepared_tools = Some(PreparedToolEnvironments {
242            home: Some(home),
243            ssh: Vec::new(),
244            catalog,
245        });
246        self
247    }
248
249    /// Records `server` as prepared with `tools`, as SSH bootstrap would.
250    #[cfg(test)]
251    pub(crate) fn with_test_ssh(
252        mut self,
253        server: SshServer,
254        tools: PreparedTools<PathBuf>,
255    ) -> Self {
256        let prepared = self
257            .prepared_tools
258            .as_mut()
259            .expect("prepare the home environment before an SSH server");
260        prepared.ssh.push(PreparedSsh {
261            server,
262            runtime: SshRuntimeProfile::Heel {
263                binary: "/usr/local/bin/heel".into(),
264            },
265            tools,
266        });
267        prepared
268            .ssh
269            .sort_by(|left, right| left.server.id().cmp(right.server.id()));
270        self
271    }
272}