use std::collections::BTreeMap;
use std::os::fd::OwnedFd;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use ag_contracts::TurnNotice;
use ag_harness::RunEventKind;
use ag_harness::bash::{BashConfig, BashError};
use ag_harness::event::Item;
use ag_harness::sandbox::{IfUnavailable, Sandbox, SandboxUnavailableReason, SandboxWarning};
use rustix::fs::{self, AtFlags, FileType, Mode, OFlags};
use super::config::{agentty_home, chatgpt_auth_file};
pub(crate) const SESSION_SANDBOX: Sandbox = Sandbox::Native {
if_unavailable: IfUnavailable::Unsandboxed,
};
pub(crate) const UTILITY_SANDBOX: Sandbox = Sandbox::Native {
if_unavailable: IfUnavailable::Refuse,
};
const CARGO_HOME_DIRECTORY: &str = "cargo";
const CARGO_CONFIG_FILES: [&str; 2] = ["config.toml", "config"];
const CARGO_TRUSTED_FILES: [&str; 4] = ["config.toml", "config", "credentials.toml", "credentials"];
const DISCARDED_CARGO_ENTRY: &str = ".agentty-discarded-cargo-entry";
const CACHE_ENVIRONMENT: [(&str, &str); 6] = [
("CARGO_HOME", CARGO_HOME_DIRECTORY),
("GOCACHE", "go-build"),
("GOMODCACHE", "go-mod"),
("PIP_CACHE_DIR", "pip"),
("XDG_CACHE_HOME", "cache"),
("npm_config_cache", "npm"),
];
const AGENTTY_PRIVATE_DIRECTORIES: [&str; 3] = ["auth", "db", "tmp"];
const APPLICATION: &str = "the application";
pub(crate) struct CommandSandbox {
git_branch: Option<String>,
hidden: Vec<PathBuf>,
temporary_directory: PathBuf,
}
impl CommandSandbox {
pub(crate) async fn prepare(
data_root: &Path,
temporary_directory: PathBuf,
workspace: &Path,
environment: &BTreeMap<String, String>,
) -> Result<Self, String> {
let host_config = Self::host_cargo_config(workspace, environment).await;
let directory = temporary_directory.clone();
tokio::task::spawn_blocking(move || {
Self::reset_cargo_home(&directory, host_config.as_deref())
})
.await
.map_err(std::io::Error::other)
.flatten()
.map_err(|error| format!("Failed to prepare the sandbox Cargo directory: {error}"))?;
Ok(Self::new(data_root, temporary_directory, environment))
}
pub(crate) fn new(
data_root: &Path,
temporary_directory: PathBuf,
environment: &BTreeMap<String, String>,
) -> Self {
let agentty_files = agentty_home(environment)
.into_iter()
.flat_map(|home| AGENTTY_PRIVATE_DIRECTORIES.map(|directory| home.join(directory)));
let hidden = std::iter::once(data_root.to_path_buf())
.chain(chatgpt_auth_file(environment))
.chain(agentty_files)
.filter_map(|path| std::path::absolute(path).ok())
.collect();
Self {
git_branch: None,
hidden,
temporary_directory,
}
}
pub(crate) fn with_git_branch(mut self, branch: Option<String>) -> Self {
self.git_branch = branch;
self
}
pub(crate) fn grant(&self, config: BashConfig) -> Result<BashConfig, BashError> {
let mut config = config
.with_full_disk_read()?
.with_write(PathBuf::from("."))?;
if let Some(branch) = &self.git_branch {
config = config.with_git_writes(branch.clone())?;
}
let mut config = config
.with_network()
.with_temporary_directory(self.temporary_directory.clone())?;
for path in &self.hidden {
config = config.with_hidden_path(path.clone())?;
}
for (name, directory) in CACHE_ENVIRONMENT {
let value = self.temporary_directory.join(directory);
config = config.with_environment(name.to_string(), value.display().to_string())?;
}
Ok(config)
}
fn reset_cargo_home(
temporary_directory: &Path,
host_config: Option<&Path>,
) -> std::io::Result<()> {
std::fs::create_dir_all(temporary_directory)?;
let temporary = fs::open(temporary_directory, Self::directory_flags(), Mode::empty())?;
let planted = fs::statat(&temporary, CARGO_HOME_DIRECTORY, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|stat| !FileType::from_raw_mode(stat.st_mode).is_dir());
if planted {
fs::unlinkat(&temporary, CARGO_HOME_DIRECTORY, AtFlags::empty())?;
}
let _ = fs::mkdirat(&temporary, CARGO_HOME_DIRECTORY, Mode::RWXU);
let cargo = fs::openat(
&temporary,
CARGO_HOME_DIRECTORY,
Self::directory_flags(),
Mode::empty(),
)?;
Self::clear_cargo_home(temporary_directory, &temporary, &cargo, host_config)
}
fn directory_flags() -> OFlags {
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
}
fn clear_cargo_home(
temporary_directory: &Path,
temporary: &OwnedFd,
cargo: &OwnedFd,
host_config: Option<&Path>,
) -> std::io::Result<()> {
for name in CARGO_TRUSTED_FILES {
match fs::statat(cargo, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) if FileType::from_raw_mode(stat.st_mode).is_dir() => {
let discarded = temporary_directory.join(DISCARDED_CARGO_ENTRY);
Self::remove_discarded(&discarded)?;
fs::renameat(cargo, name, temporary, DISCARDED_CARGO_ENTRY)?;
Self::remove_discarded(&discarded)?;
}
Ok(_) => fs::unlinkat(cargo, name, AtFlags::empty())?,
Err(_) => {}
}
}
if let Some(config) = host_config {
let _ = fs::symlinkat(config, cargo, CARGO_CONFIG_FILES[0]);
}
Ok(())
}
fn remove_discarded(path: &Path) -> std::io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_dir() => std::fs::remove_dir_all(path),
Ok(_) => std::fs::remove_file(path),
Err(_) => Ok(()),
}
}
async fn host_cargo_config(
workspace: &Path,
environment: &BTreeMap<String, String>,
) -> Option<PathBuf> {
let cargo_home = environment
.get("CARGO_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.or_else(|| {
environment
.get("HOME")
.map(|home| Path::new(home).join(".cargo"))
})?;
let found_from_workspace = cargo_home.file_name() == Some(".cargo".as_ref())
&& cargo_home
.parent()
.is_some_and(|parent| workspace.starts_with(parent));
if found_from_workspace {
return None;
}
for name in CARGO_CONFIG_FILES {
let config = cargo_home.join(name);
if tokio::fs::metadata(&config)
.await
.is_ok_and(|metadata| metadata.is_file())
{
return Some(config);
}
}
None
}
}
#[must_use = "a helper process must return this exit code from `main` at once"]
pub fn dispatch_sandbox_helper() -> Option<ExitCode> {
ag_harness::sandbox::dispatch()
}
pub(crate) fn notice(event: &RunEventKind) -> Option<TurnNotice> {
match event {
RunEventKind::SandboxUnavailable(warning) => Some(unavailable(warning)),
RunEventKind::ItemCompleted {
item: Item::ToolCall(call),
..
} if call.likely_sandbox_denial => Some(TurnNotice::LikelySandboxDenial),
_ => None,
}
}
fn unavailable(warning: &SandboxWarning) -> TurnNotice {
let message = match warning.reason {
SandboxUnavailableReason::UnixSocketsUnsupported => warning.message.clone(),
_ => format!("Commands run without the sandbox. {}", warning.message),
};
TurnNotice::SandboxUnavailable {
message,
remedy: warning.remedy.replace(APPLICATION, "Agentty"),
}
}
#[cfg(test)]
#[path = "sandbox_test.rs"]
mod tests;