use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use futures::future::BoxFuture;
pub trait SubagentSpaces: Send + Sync + 'static {
type Error: std::error::Error + Send + Sync + 'static;
fn prepare(
&self,
run: RunSpace<'_>,
) -> impl Future<Output = Result<PreparedSpace, Self::Error>> + Send;
}
#[derive(Debug, Clone, Copy)]
pub struct RunSpace<'a> {
pub space: &'a Path,
pub launcher: &'a Path,
pub caller: &'a Path,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PreparedSpace {
working_copies: Vec<PathBuf>,
}
impl PreparedSpace {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_working_copy(mut self, path: impl Into<PathBuf>) -> Self {
self.working_copies.push(path.into());
self
}
#[must_use]
pub fn working_copies(&self) -> &[PathBuf] {
&self.working_copies
}
pub(crate) async fn confine(self, space: &Path) -> Result<Self, super::SubagentGrantError> {
let mut working_copies = Vec::with_capacity(self.working_copies.len());
for path in self.working_copies {
let canonical = super::canonical(&path).await?;
if !canonical.starts_with(space) {
return Err(super::SubagentGrantError::PreparedOutsideSpace {
path: canonical,
space: space.to_path_buf(),
});
}
working_copies.push(canonical);
}
Ok(Self { working_copies })
}
}
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct SpacePreparationError(Box<dyn std::error::Error + Send + Sync>);
impl SpacePreparationError {
#[must_use]
pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
self.0.downcast_ref()
}
}
trait SubagentSpacesImpl: Send + Sync {
fn prepare<'a>(
&'a self,
run: RunSpace<'a>,
) -> BoxFuture<'a, Result<PreparedSpace, SpacePreparationError>>;
}
impl<T: SubagentSpaces> SubagentSpacesImpl for T {
fn prepare<'a>(
&'a self,
run: RunSpace<'a>,
) -> BoxFuture<'a, Result<PreparedSpace, SpacePreparationError>> {
Box::pin(async move {
SubagentSpaces::prepare(self, run)
.await
.map_err(|error| SpacePreparationError(Box::new(error)))
})
}
}
#[derive(Clone)]
pub struct AnySubagentSpaces(Arc<dyn SubagentSpacesImpl>);
impl AnySubagentSpaces {
#[must_use]
pub fn new(spaces: impl SubagentSpaces) -> Self {
Self(Arc::new(spaces))
}
pub(crate) async fn prepare(
&self,
run: RunSpace<'_>,
) -> Result<PreparedSpace, SpacePreparationError> {
self.0.prepare(run).await
}
}
impl std::fmt::Debug for AnySubagentSpaces {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnySubagentSpaces").finish_non_exhaustive()
}
}