aither_sandbox/subagent/space.rs
1//! What the embedder puts in a subagent's space before the run starts.
2//!
3//! Every subagent works in a space of its own, a fresh directory under its
4//! launcher's working directory that it alone can write. An embedder that
5//! gives its terminal [`SubagentSpaces`] fills each new space before the
6//! subagent's terminal exists, typically with a clone of the repository the
7//! launcher works in, and names the working copies it made there and the
8//! directories its commands' environment points at. The run fails with the
9//! embedder's error when that fails.
10//!
11//! The space belongs to the launcher: it lies inside the launcher's working
12//! directory, stays when the run ends so the launcher can review and take
13//! over what the subagent did, and is removed by whoever owns that working
14//! directory. Only a space whose preparation failed, which no run ever
15//! worked in, is removed by the terminal that created it.
16
17use std::future::Future;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use futures::future::BoxFuture;
22use futures::{StreamExt as _, TryStreamExt as _};
23
24/// How many prepared paths are resolved at once. Each resolution is one
25/// filesystem call on the blocking pool, and an embedder names a handful, so
26/// the bound matches the import's ref checks rather than any measurement.
27const RESOLUTIONS_IN_FLIGHT: usize = 8;
28
29/// Prepares the space each subagent run works in.
30///
31/// Given to a terminal with
32/// [`Shell::with_subagent_spaces`](crate::Shell::with_subagent_spaces),
33/// it serves every subagent launched from that terminal and, at any depth,
34/// from theirs.
35pub trait SubagentSpaces: Send + Sync + 'static {
36 /// Why a space could not be prepared.
37 type Error: std::error::Error + Send + Sync + 'static;
38
39 /// Fills `run.space` for the run and names the working copies and
40 /// environment directories made in it. Each must lie inside the space.
41 fn prepare(
42 &self,
43 run: RunSpace<'_>,
44 ) -> impl Future<Output = Result<PreparedSpace, Self::Error>> + Send;
45}
46
47/// The space a subagent run is about to start in.
48#[derive(Debug, Clone, Copy)]
49pub struct RunSpace<'a> {
50 /// The run's space: an empty directory, by its canonical path, that only
51 /// the run, and the subagents it launches, can write, and its launcher
52 /// can read and write.
53 pub space: &'a Path,
54 /// The launching terminal's working directory, by its canonical path:
55 /// the main agent's, or a subagent's space when subagents nest.
56 pub launcher: &'a Path,
57 /// The directory the launch was asked for from, as the request named it:
58 /// where the launching command ran, else the launcher's working
59 /// directory.
60 pub caller: &'a Path,
61}
62
63/// What an embedder made in a run's space.
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct PreparedSpace {
66 working_copies: Vec<PathBuf>,
67 env_dirs: Vec<(String, PathBuf)>,
68}
69
70impl PreparedSpace {
71 /// A space the embedder left empty.
72 #[must_use]
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 /// Records `path`, inside the space, as a working copy the run works in.
78 #[must_use]
79 pub fn with_working_copy(mut self, path: impl Into<PathBuf>) -> Self {
80 self.working_copies.push(path.into());
81 self
82 }
83
84 /// Records the environment variable `name` as `path`, a directory inside
85 /// the space, for every command the run executes: the temporary, home or
86 /// cache directory a launcher's environment would otherwise point at a
87 /// directory the run cannot write. It overrides the launcher's sandbox
88 /// environment and [`EnvSource`](crate::EnvSource), never a command's own
89 /// variables, and reaches no subagent the run launches, whose space is
90 /// prepared on its own. A container sees `path` as it spells it through
91 /// the workspace mount.
92 #[must_use]
93 pub fn with_env_dir(mut self, name: impl Into<String>, path: impl Into<PathBuf>) -> Self {
94 self.env_dirs.push((name.into(), path.into()));
95 self
96 }
97
98 /// The working copies the run works in, by their canonical paths once
99 /// the terminal has accepted the space.
100 #[must_use]
101 pub fn working_copies(&self) -> &[PathBuf] {
102 &self.working_copies
103 }
104
105 /// The environment directories, by their canonical paths once the
106 /// terminal has accepted the space.
107 pub(crate) fn env_dirs(&self) -> &[(String, PathBuf)] {
108 &self.env_dirs
109 }
110
111 /// Resolves every working copy and environment directory and confirms it
112 /// lies inside `space`, which is canonical.
113 pub(crate) async fn confine(self, space: &Path) -> Result<Self, super::SubagentGrantError> {
114 let working_copies = futures::stream::iter(self.working_copies)
115 .map(|path| inside(path, space))
116 .buffered(RESOLUTIONS_IN_FLIGHT)
117 .try_collect::<Vec<_>>();
118 let env_dirs = futures::stream::iter(self.env_dirs)
119 .map(|(name, path)| async move {
120 Ok::<_, super::SubagentGrantError>((name, inside(path, space).await?))
121 })
122 .buffered(RESOLUTIONS_IN_FLIGHT)
123 .try_collect::<Vec<_>>();
124 let (working_copies, env_dirs) =
125 futures::future::try_join(working_copies, env_dirs).await?;
126 Ok(Self {
127 working_copies,
128 env_dirs,
129 })
130 }
131}
132
133/// `path` by its canonical path, refused unless it lies inside `space`.
134async fn inside(path: PathBuf, space: &Path) -> Result<PathBuf, super::SubagentGrantError> {
135 let canonical = super::canonical(&path).await?;
136 if !canonical.starts_with(space) {
137 return Err(super::SubagentGrantError::PreparedOutsideSpace {
138 path: canonical,
139 space: space.to_path_buf(),
140 });
141 }
142 Ok(canonical)
143}
144
145/// An embedder's failure to prepare a space, whatever its own error type.
146#[derive(Debug, thiserror::Error)]
147#[error(transparent)]
148pub struct SpacePreparationError(Box<dyn std::error::Error + Send + Sync>);
149
150impl SpacePreparationError {
151 /// The embedder's error, when it is an `E`.
152 #[must_use]
153 pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
154 self.0.downcast_ref()
155 }
156}
157
158/// Object-safe twin of [`SubagentSpaces`].
159trait SubagentSpacesImpl: Send + Sync {
160 fn prepare<'a>(
161 &'a self,
162 run: RunSpace<'a>,
163 ) -> BoxFuture<'a, Result<PreparedSpace, SpacePreparationError>>;
164}
165
166impl<T: SubagentSpaces> SubagentSpacesImpl for T {
167 fn prepare<'a>(
168 &'a self,
169 run: RunSpace<'a>,
170 ) -> BoxFuture<'a, Result<PreparedSpace, SpacePreparationError>> {
171 Box::pin(async move {
172 SubagentSpaces::prepare(self, run)
173 .await
174 .map_err(|error| SpacePreparationError(Box::new(error)))
175 })
176 }
177}
178
179/// A [`SubagentSpaces`] of any type, as a terminal holds it.
180#[derive(Clone)]
181pub struct AnySubagentSpaces(Arc<dyn SubagentSpacesImpl>);
182
183impl AnySubagentSpaces {
184 /// Erases `spaces`.
185 #[must_use]
186 pub fn new(spaces: impl SubagentSpaces) -> Self {
187 Self(Arc::new(spaces))
188 }
189
190 /// Prepares `run`'s space.
191 pub(crate) async fn prepare(
192 &self,
193 run: RunSpace<'_>,
194 ) -> Result<PreparedSpace, SpacePreparationError> {
195 self.0.prepare(run).await
196 }
197}
198
199impl std::fmt::Debug for AnySubagentSpaces {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 f.debug_struct("AnySubagentSpaces").finish_non_exhaustive()
202 }
203}