use crate::foreground_wait::ForegroundWait;
use crate::grants::{GrantSet, TerminalGrants};
use crate::outage::Outages;
use std::{
borrow::Cow,
io::{Read, Write},
net::{SocketAddr, TcpListener as StdTcpListener, TcpStream as StdTcpStream},
path::{Path, PathBuf},
process::Stdio,
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
time::Duration,
};
use aither_core::llm::{CallIdentity, ToolContext};
use aither_core::llm::{
CommandOutcome, CommandResult, CommandStream, Interruption, IntoToolResult, StoredFile, Tool,
ToolResult,
};
use askama::Template;
use async_channel::{Receiver, Sender};
use async_io::Async;
use executor_core::{Executor, Task};
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
#[cfg(target_os = "linux")]
use heel::supervisor::{TreeControl, TreeReport};
use heel::{
Access, AllowAll, Audited, CpuPriority, DomainRequest, Grant, IoPriority, IpcRouter,
NetworkAuditLog, NetworkPolicy, ProcessPriority, ResolvedPath, Sandbox, SandboxConfig,
SecurityConfig, StdioConfig, WorkingDir,
};
#[cfg(not(target_os = "linux"))]
struct TreeReport;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use shell_words::split as split_shell_words;
use tracing::{debug, info, warn};
#[cfg(all(unix, feature = "jobserver"))]
use crate::jobserver::{JobBroker, JobPool, job_broker_channel};
use crate::{
ContainerPath, MountRoot, PreparedTools, ToolDistribution, ToolRuntimeError,
builtin::builtin_router,
command::{
AnyCommandGate, AnyCommandObserver, CommandBlocked, CommandRole, GateDecision, ToolRegistry,
},
job_registry::{JobRegistry, JobStatus, job_registry_channel},
output::{
INLINE_OUTPUT_LIMIT, MediaResolution, OutputFormat, OutputStore, save_raw_to_file,
stored_path,
},
permission::{PermissionError, PermissionHandler, PermissionRequest, Review, TerminalMode},
process_tree::{JobMarker, JobProcess, JobTree},
shell_session::{
BridgeAddress, ContainerExecOutcome, ContainerShellRuntime, ExecLifetime, ShellBackend,
ShellRuntimeAvailability, ShellSessionRegistry, SshRuntimeProfile,
},
stdin_watch::{
EpisodeDetector, FeedCounter, LocalStdinProbe, STDIN_WATCH_INTERVAL, StdinWatchSignal,
},
subagent::{
CommitLedger, CommittingWorktree, ImportBudget, ImportLimits, LaunchHistory, Launcher,
Spelling, SubagentGit, SubagentGrant, SubagentGrantError, canonical as canonical_path,
},
};
mod subagent_git;
pub fn erase_terminal_tool<T>(tool: T) -> crate::command::DynTerminalToolEntry
where
T: Tool + 'static,
{
use crate::command::{DynTerminalToolEntry, DynToolHandler};
use aither_core::llm::tool::ToolDefinition;
let definition = ToolDefinition::new(&tool);
let tool = Arc::new(tool);
let handler: DynToolHandler = Arc::new(move |args: &str, cx: ToolContext| {
let tool = tool.clone();
let args = args.to_string();
Box::pin(async move {
let parsed = match serde_json::from_str::<T::Arguments>(&args) {
Ok(parsed) => parsed,
Err(error) => return ToolResult::error(format!("Parse error: {error}")),
};
match tool.call(parsed, cx).await {
Ok(output) => output
.into_tool_result()
.unwrap_or_else(|error| ToolResult::error(format!("Error: {error}"))),
Err(error) => ToolResult::error(format!("Error: {error}")),
}
})
});
DynTerminalToolEntry {
definition,
handler,
}
}
fn random_task_id() -> String {
crate::naming::random_word_slug(4)
}
pub async fn open_network_audit_log(
dir: impl AsRef<Path>,
max_files: usize,
) -> Result<NetworkAuditLog, TerminalError> {
let dir = dir.as_ref();
async_fs::create_dir_all(dir).await?;
NetworkAuditLog::rolling_daily(dir, max_files).map_err(|error| {
TerminalError::SandboxSetup(format!("failed to open network audit log: {error}"))
})
}
#[derive(Clone)]
struct PermissionNetworkPolicy<P> {
permission_handler: Arc<P>,
}
impl<P: PermissionHandler + 'static> NetworkPolicy for PermissionNetworkPolicy<P> {
async fn check(&self, request: &DomainRequest) -> bool {
self.permission_handler
.authorize_domain(request.host(), request.port())
.await
}
}
fn parse_direct_command(script: &str) -> Result<(String, Vec<String>), TerminalError> {
let parts = split_shell_words(script)
.map_err(|error| TerminalError::Execution(format!("failed to parse command: {error}")))?;
let Some((program, args)) = parts.split_first() else {
return Err(TerminalError::Execution(
"command must not be empty".to_string(),
));
};
Ok((program.clone(), args.to_vec()))
}
enum TerminalLaunch {
Direct { program: String, args: Vec<String> },
Shell { program: String, args: Vec<String> },
}
fn script_requires_shell(script: &str) -> bool {
let mut in_single = false;
let mut in_double = false;
let mut escaped = false;
for ch in script.chars() {
if escaped {
escaped = false;
continue;
}
match ch {
'\\' if !in_single => escaped = true,
'\'' if !in_double => in_single = !in_single,
'"' if !in_single => in_double = !in_double,
'\n' | '\r' | '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '*' | '?' | '['
| ']' | '{' | '}' | '!' | '~'
if !in_single && !in_double =>
{
return true;
}
_ => {}
}
}
false
}
fn looks_like_env_assignment(token: &str) -> bool {
let Some((name, _value)) = token.split_once('=') else {
return false;
};
!name.is_empty() && name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
}
fn is_shell_builtin(program: &str) -> bool {
matches!(
program,
"alias"
| "bg"
| "break"
| "cd"
| "command"
| "continue"
| "eval"
| "exec"
| "exit"
| "export"
| "fg"
| "jobs"
| "read"
| "readonly"
| "return"
| "set"
| "shift"
| "source"
| "times"
| "trap"
| "type"
| "ulimit"
| "umask"
| "unalias"
| "unset"
)
}
fn shell_launch(managed_shell: &str, script: &str) -> (String, Vec<String>) {
#[cfg(windows)]
{
let _ = managed_shell;
let shell = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string());
return (shell, vec!["/C".to_string(), script.to_string()]);
}
#[cfg(not(windows))]
{
(
managed_shell.to_string(),
crate::tool_runtime::shell_arguments(script),
)
}
}
fn build_terminal_launch(
managed_shell: &str,
script: &str,
report: Option<&Path>,
) -> Result<TerminalLaunch, TerminalError> {
let script = script.trim();
if script.is_empty() {
return Err(TerminalError::Execution(
"command must not be empty".to_string(),
));
}
match direct_command(script)? {
Some((program, args)) => Ok(TerminalLaunch::Direct { program, args }),
None => shell_launch_reporting(managed_shell, script, report),
}
}
fn direct_command(script: &str) -> Result<Option<(String, Vec<String>)>, TerminalError> {
if script_requires_shell(script) {
return Ok(None);
}
let (program, args) = parse_direct_command(script)?;
if looks_like_env_assignment(&program)
|| is_shell_builtin(&program)
|| crate::tool_runtime::is_blocked_command(&program)
{
return Ok(None);
}
Ok(Some((program, args)))
}
fn runs_in_shell(script: &str) -> bool {
matches!(direct_command(script.trim()), Ok(None))
}
#[derive(Debug, Clone, PartialEq, Eq, Template)]
#[template(path = "command_timed_out.txt", escape = "none")]
pub struct TimeoutKill {
pub timeout: Duration,
pub started: jiff::Timestamp,
pub killed: jiff::Timestamp,
}
impl TimeoutKill {
fn started_utc(&self) -> String {
Self::utc(self.started)
}
fn killed_utc(&self) -> String {
Self::utc(self.killed)
}
fn utc(at: jiff::Timestamp) -> String {
at.strftime("%Y-%m-%d %H:%M:%S UTC").to_string()
}
#[must_use]
pub fn notice(&self) -> String {
self.render()
.expect("failed to render command_timed_out template")
}
}
#[derive(Debug)]
struct TimeoutWatch {
timeout: Duration,
started: jiff::Timestamp,
killed: std::sync::OnceLock<jiff::Timestamp>,
}
impl TimeoutWatch {
fn new(timeout: Duration) -> Self {
Self {
timeout,
started: jiff::Timestamp::now(),
killed: std::sync::OnceLock::new(),
}
}
fn kill(&self) -> Option<TimeoutKill> {
self.killed.get().map(|killed| TimeoutKill {
timeout: self.timeout,
started: self.started,
killed: *killed,
})
}
}
#[derive(Template)]
#[template(path = "carry_cwd.sh", escape = "none")]
struct CarryCwdTemplate<'a> {
escaped_report: &'a str,
escaped_script: &'a str,
}
fn shell_launch_reporting(
managed_shell: &str,
script: &str,
report: Option<&Path>,
) -> Result<TerminalLaunch, TerminalError> {
let Some(report) = report else {
let (program, args) = shell_launch(managed_shell, script);
return Ok(TerminalLaunch::Shell { program, args });
};
let script = carry_cwd_script(script, &report.to_string_lossy())?;
let (program, args) = shell_launch(managed_shell, &script);
Ok(TerminalLaunch::Shell { program, args })
}
fn carry_cwd_script(script: &str, report: &str) -> Result<String, TerminalError> {
let escaped_report = shell_escape(report);
let escaped_script = shell_escape(script);
CarryCwdTemplate {
escaped_report: &escaped_report,
escaped_script: &escaped_script,
}
.render()
.map_err(|error| {
TerminalError::Execution(format!("failed to render directory report: {error}"))
})
}
async fn ensure_mode_allowed<P: PermissionHandler>(
permission_handler: &P,
mode: TerminalMode,
script: &str,
) -> Result<(), TerminalError> {
if !mode.requires_approval() {
return Ok(());
}
let allowed = permission_handler.check(mode, script).await?;
if allowed {
Ok(())
} else {
Err(TerminalError::PermissionDenied(mode))
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TerminalArgs {
pub description: String,
pub script: String,
#[serde(default)]
pub mode: TerminalExecutionMode,
#[serde(default)]
pub ssh_server_id: Option<String>,
#[serde(default)]
pub expect: OutputFormat,
#[serde(default)]
pub resolution: MediaResolution,
#[serde(default = "default_max_lines")]
pub max_lines: u32,
#[serde(default)]
pub raw: bool,
pub timeout: u64,
#[serde(default)]
pub background: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TerminalExecutionMode {
#[default]
Default,
Sandboxed,
Unsafe,
Ssh,
}
const fn default_max_lines() -> u32 {
200
}
const MAX_LINES_CEILING: u32 = 800;
pub const DEFAULT_FOREGROUND_WAIT: Duration = Duration::from_secs(10);
pub const DEFAULT_SUBAGENT_IMPORT_LIMIT: u64 = 1024 * 1024 * 1024;
pub const DEFAULT_TIMEOUT_CAP: Duration = Duration::from_secs(120 * 60);
pub const DEFAULT_LONG_JOB_ALERT_AFTER: Duration = Duration::from_secs(40 * 60);
#[derive(Debug, Clone)]
struct TerminalLimits {
foreground_wait: ForegroundWait,
timeout_cap: Duration,
long_job_alert: Duration,
subagent_import: ImportBudget,
}
impl Default for TerminalLimits {
fn default() -> Self {
Self {
foreground_wait: ForegroundWait::new(DEFAULT_FOREGROUND_WAIT),
timeout_cap: DEFAULT_TIMEOUT_CAP,
long_job_alert: DEFAULT_LONG_JOB_ALERT_AFTER,
subagent_import: ImportBudget::new(DEFAULT_SUBAGENT_IMPORT_LIMIT),
}
}
}
#[derive(Debug, Clone)]
pub struct LongRunningJob {
pub task_id: String,
pub script: String,
pub elapsed: Duration,
}
#[derive(Debug, Clone)]
pub struct StdinBlockedJob {
pub task_id: String,
pub script: String,
}
#[derive(Debug, Clone)]
pub struct StdinProbeFailedJob {
pub task_id: String,
pub script: String,
pub error: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectoryResetReason {
Failed,
Unreported,
OutsideReadable,
OutsideWorkspace,
Removed,
}
#[derive(Debug, Clone)]
pub struct DirectoryReset {
pub dir: PathBuf,
pub reason: DirectoryResetReason,
}
const KILLED_PROCESSES_NAMED: usize = 8;
#[derive(Debug, Clone)]
pub struct DescendantsKilled {
pub processes: Vec<JobProcess>,
pub omitted: usize,
}
impl DescendantsKilled {
fn new(mut killed: Vec<JobProcess>) -> Self {
let omitted = killed.len().saturating_sub(KILLED_PROCESSES_NAMED);
killed.truncate(KILLED_PROCESSES_NAMED);
Self {
processes: killed,
omitted,
}
}
}
#[derive(Debug, Clone)]
pub enum JobAlert {
DescendantsKilled(DescendantsKilled),
DirectoryReset(DirectoryReset),
LongRunning(LongRunningJob),
StdinBlocked(StdinBlockedJob),
StdinProbeFailed(StdinProbeFailedJob),
MonitorIncrement(crate::monitor::MonitorIncrement),
MonitorStalled(crate::monitor::MonitorStalled),
MonitorEnded(crate::monitor::MonitorEnded),
}
#[derive(Debug, Clone)]
pub struct CompletedCommand {
pub stdout: CommandStream,
pub stderr: Option<CommandStream>,
pub exit_code: i32,
pub interruptions: Vec<Interruption>,
}
impl From<CompletedCommand> for CommandResult {
fn from(command: CompletedCommand) -> Self {
Self {
stdout: command.stdout,
stderr: command.stderr,
outcome: CommandOutcome::Exited {
code: command.exit_code,
},
interruptions: command.interruptions,
}
}
}
#[derive(Debug, Clone)]
pub struct StartedBackgroundTask {
pub task_id: String,
pub output_preview: String,
pub output_file: StoredFile,
}
#[derive(Clone)]
struct BackgroundStartup {
tx: async_channel::Sender<Result<(), String>>,
reported: Arc<AtomicBool>,
}
impl BackgroundStartup {
fn new(tx: async_channel::Sender<Result<(), String>>) -> Self {
Self {
tx,
reported: Arc::new(AtomicBool::new(false)),
}
}
async fn report_ready(&self) {
if self
.reported
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
let _ = self.tx.send(Ok(())).await;
}
}
async fn report_failure(&self, error: &TerminalError) {
if self
.reported
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
let _ = self.tx.send(Err(error.to_string())).await;
}
}
}
#[derive(Debug)]
pub struct CompletedTask {
pub task_id: String,
pub script: String,
pub result: Result<CompletedCommand, TerminalError>,
pub killed: bool,
pub timeout_kill: Option<TimeoutKill>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PermissionEventStage {
Waiting,
Resolved,
}
#[derive(Debug, Clone)]
pub struct PermissionEvent {
pub mode: TerminalMode,
pub script: String,
pub stage: PermissionEventStage,
}
#[derive(Clone)]
pub struct BackgroundTaskReceiver {
rx: Receiver<CompletedTask>,
alert_rx: Receiver<JobAlert>,
started_rx: Receiver<StartedBackgroundTask>,
running_tasks: Arc<AtomicUsize>,
}
#[derive(Clone, Debug)]
pub struct BackgroundTaskSender {
completed_tx: Sender<CompletedTask>,
alert_tx: Sender<JobAlert>,
started_tx: Sender<StartedBackgroundTask>,
running_tasks: Arc<AtomicUsize>,
}
impl BackgroundTaskSender {
pub fn task_started(&self) {
self.running_tasks.fetch_add(1, Ordering::AcqRel);
}
pub fn task_finished(&self) {
let previous = self.running_tasks.fetch_sub(1, Ordering::AcqRel);
assert!(
previous > 0,
"task_finished without a matching task_started"
);
}
pub async fn send_completed(&self, task: CompletedTask) {
let _ = self.completed_tx.send(task).await;
}
pub async fn send_alert(&self, alert: JobAlert) {
let _ = self.alert_tx.send(alert).await;
}
pub async fn send_started(&self, task: StartedBackgroundTask) {
let _ = self.started_tx.send(task).await;
}
}
#[must_use]
pub fn background_task_channel() -> (BackgroundTaskSender, BackgroundTaskReceiver) {
let (completed_tx, rx) = async_channel::unbounded();
let (alert_tx, alert_rx) = async_channel::unbounded();
let (started_tx, started_rx) = async_channel::unbounded();
let running_tasks = Arc::new(AtomicUsize::new(0));
(
BackgroundTaskSender {
completed_tx,
alert_tx,
started_tx,
running_tasks: running_tasks.clone(),
},
BackgroundTaskReceiver {
rx,
alert_rx,
started_rx,
running_tasks,
},
)
}
impl BackgroundTaskReceiver {
#[must_use]
pub fn take_completed(&self) -> Vec<CompletedTask> {
let mut completed = Vec::new();
while let Ok(task) = self.rx.try_recv() {
completed.push(task);
}
completed
}
#[must_use]
pub fn take_job_alerts(&self) -> Vec<JobAlert> {
let mut alerts = Vec::new();
while let Ok(alert) = self.alert_rx.try_recv() {
alerts.push(alert);
}
alerts
}
#[must_use]
pub fn take_started(&self) -> Vec<StartedBackgroundTask> {
let mut started = Vec::new();
while let Ok(task) = self.started_rx.try_recv() {
started.push(task);
}
started
}
#[must_use]
pub fn has_completed(&self) -> bool {
!self.rx.is_empty()
}
#[must_use]
pub fn has_running(&self) -> bool {
self.running_tasks.load(Ordering::Acquire) > 0
}
pub async fn recv(&self) -> Option<CompletedTask> {
self.rx.recv().await.ok()
}
pub async fn recv_timeout(&self, duration: std::time::Duration) -> Option<CompletedTask> {
futures_lite::future::or(async { self.rx.recv().await.ok() }, async {
futures_lite::future::yield_now().await;
async_io::Timer::after(duration).await;
None
})
.await
}
pub async fn recv_event(&self) -> BackgroundTaskEvent {
futures_lite::future::or(
async {
match self.rx.recv().await {
Ok(task) => BackgroundTaskEvent::Completed(Box::new(task)),
Err(_) => std::future::pending().await,
}
},
async {
match self.alert_rx.recv().await {
Ok(alert) => BackgroundTaskEvent::Alert(alert),
Err(_) => std::future::pending().await,
}
},
)
.await
}
pub async fn recv_event_timeout(
&self,
duration: std::time::Duration,
) -> Option<BackgroundTaskEvent> {
futures_lite::future::or(
async {
match self.rx.recv().await {
Ok(task) => Some(BackgroundTaskEvent::Completed(Box::new(task))),
Err(_) => std::future::pending().await,
}
},
futures_lite::future::or(
async {
match self.alert_rx.recv().await {
Ok(alert) => Some(BackgroundTaskEvent::Alert(alert)),
Err(_) => std::future::pending().await,
}
},
async {
futures_lite::future::yield_now().await;
async_io::Timer::after(duration).await;
None
},
),
)
.await
}
}
#[derive(Debug)]
pub enum BackgroundTaskEvent {
Completed(Box<CompletedTask>),
Alert(JobAlert),
}
impl std::fmt::Debug for BackgroundTaskReceiver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BackgroundTaskReceiver")
.field("pending", &self.rx.len())
.field("pending_alerts", &self.alert_rx.len())
.field("pending_started", &self.started_rx.len())
.field("running_tasks", &self.running_tasks.load(Ordering::Acquire))
.finish()
}
}
#[derive(Clone)]
pub struct PermissionEventReceiver {
rx: Receiver<PermissionEvent>,
}
impl PermissionEventReceiver {
#[must_use]
pub fn take_pending(&self) -> Vec<PermissionEvent> {
let mut events = Vec::new();
while let Ok(event) = self.rx.try_recv() {
events.push(event);
}
events
}
pub async fn recv(&self) -> Option<PermissionEvent> {
self.rx.recv().await.ok()
}
}
impl std::fmt::Debug for PermissionEventReceiver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PermissionEventReceiver")
.field("pending", &self.rx.len())
.finish()
}
}
#[derive(Clone, Debug)]
pub struct TerminalToolFactory {
tx: Sender<TerminalToolRequest>,
}
#[derive(Debug)]
struct TerminalToolRequest {
grant: SubagentGrant,
observer: Option<AnyCommandObserver>,
gate: Option<AnyCommandGate>,
reply: Sender<Result<crate::command::DynTerminalTool, SubagentGrantError>>,
}
#[derive(Debug, thiserror::Error)]
pub enum TerminalToolFactoryError {
#[error("terminal tool factory is not available")]
Unavailable,
#[error("terminal tool factory failed to return a tool")]
NoResponse,
#[error(transparent)]
Grant(#[from] SubagentGrantError),
}
impl TerminalToolFactory {
pub async fn create(
&self,
grant: SubagentGrant,
observer: Option<AnyCommandObserver>,
gate: Option<AnyCommandGate>,
) -> Result<crate::command::DynTerminalTool, TerminalToolFactoryError> {
let (reply, reply_rx) = async_channel::bounded(1);
self.tx
.send(TerminalToolRequest {
grant,
observer,
gate,
reply,
})
.await
.map_err(|_| TerminalToolFactoryError::Unavailable)?;
Ok(reply_rx
.recv()
.await
.map_err(|_| TerminalToolFactoryError::NoResponse)??)
}
}
async fn serve_launches<P, E>(
requests: Receiver<TerminalToolRequest>,
source: TerminalTool<P, E, Launching>,
) where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
let mut history = LaunchHistory::default();
while let Ok(TerminalToolRequest {
grant,
observer,
gate,
reply,
}) = requests.recv().await
{
let tool = source
.subagent(&mut history, grant, observer, gate)
.await
.map(TerminalTool::to_dyn);
if reply.send(tool).await.is_err() {
warn!("terminal tool factory response channel dropped");
}
}
}
#[derive(Clone, Debug)]
pub struct TerminalBinding {
launcher: TerminalToolFactory,
working_dir: PathBuf,
role: CommandRole,
observer: Option<AnyCommandObserver>,
}
impl TerminalBinding {
#[must_use]
pub const fn launcher(&self) -> &TerminalToolFactory {
&self.launcher
}
#[must_use]
pub fn working_dir(&self) -> &Path {
&self.working_dir
}
#[must_use]
pub const fn role(&self) -> CommandRole {
self.role
}
#[must_use]
pub const fn observer(&self) -> Option<&AnyCommandObserver> {
self.observer.as_ref()
}
}
#[derive(Clone, Debug)]
pub struct Unconfigured;
#[derive(Clone, Debug)]
pub struct Configured {
registry: Arc<ToolRegistry>,
binding: TerminalBinding,
}
#[derive(Clone, Debug)]
pub struct Launching {
registry: Arc<ToolRegistry>,
}
pub trait RegistryState: Clone + Send + Sync {
fn registry(&self) -> &Arc<ToolRegistry>;
}
impl RegistryState for Configured {
fn registry(&self) -> &Arc<ToolRegistry> {
&self.registry
}
}
impl RegistryState for Launching {
fn registry(&self) -> &Arc<ToolRegistry> {
&self.registry
}
}
#[derive(Clone, Debug)]
struct SubagentAuthority {
committing: Vec<CommittingWorktree>,
git: SubagentGit,
container: Option<ContainerConfinement>,
}
#[derive(Clone, Default)]
struct CarriedDir(Arc<Mutex<Option<PathBuf>>>);
impl CarriedDir {
fn get(&self) -> Option<PathBuf> {
self.0.lock().expect("carried directory lock").clone()
}
fn set(&self, dir: Option<PathBuf>) {
*self.0.lock().expect("carried directory lock") = dir;
}
}
#[derive(Clone)]
struct CwdCarry {
start: Option<PathBuf>,
report: PathBuf,
container: Option<ContainerCarry>,
shell: bool,
}
#[derive(Clone)]
struct ContainerCarry {
mount: MountRoot,
report: ContainerPath,
start: ContainerPath,
}
pub struct TerminalTool<P, E, State = Unconfigured> {
working_dir: PathBuf,
shell_sessions: ShellSessionRegistry,
permission_handler: Arc<P>,
executor: E,
output_store: Arc<OutputStore>,
job_registry: JobRegistry,
completed_rx: Receiver<CompletedTask>,
completed_tx: Sender<CompletedTask>,
alert_rx: Receiver<JobAlert>,
alert_tx: Sender<JobAlert>,
started_rx: Receiver<StartedBackgroundTask>,
started_tx: Sender<StartedBackgroundTask>,
limits: TerminalLimits,
running_tasks: Arc<AtomicUsize>,
permission_rx: Receiver<PermissionEvent>,
permission_tx: Sender<PermissionEvent>,
grants: TerminalGrants,
subagent: Option<SubagentAuthority>,
carried_dir: Option<CarriedDir>,
env_source: Option<Arc<dyn TerminalEnvSource>>,
network_audit: Option<NetworkAuditLog>,
priority: ProcessPriority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: Option<JobBroker>,
outages: Outages,
registry: State,
}
impl<P, E: Clone, State: Clone> Clone for TerminalTool<P, E, State> {
fn clone(&self) -> Self {
Self {
working_dir: self.working_dir.clone(),
shell_sessions: self.shell_sessions.clone(),
permission_handler: self.permission_handler.clone(),
executor: self.executor.clone(),
output_store: self.output_store.clone(),
job_registry: self.job_registry.clone(),
completed_rx: self.completed_rx.clone(),
completed_tx: self.completed_tx.clone(),
alert_rx: self.alert_rx.clone(),
alert_tx: self.alert_tx.clone(),
started_rx: self.started_rx.clone(),
started_tx: self.started_tx.clone(),
limits: self.limits.clone(),
running_tasks: self.running_tasks.clone(),
permission_rx: self.permission_rx.clone(),
permission_tx: self.permission_tx.clone(),
grants: self.grants.clone(),
subagent: self.subagent.clone(),
carried_dir: self.carried_dir.clone(),
env_source: self.env_source.clone(),
network_audit: self.network_audit.clone(),
priority: self.priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: self.jobserver.clone(),
outages: self.outages.clone(),
registry: self.registry.clone(),
}
}
}
impl<P, E: Executor + Clone + 'static> TerminalTool<P, E, Unconfigured> {
#[must_use]
pub fn with_shell_sessions(mut self, sessions: ShellSessionRegistry) -> Self {
assert!(
sessions.prepared_tools.is_none(),
"a prepared shell session registry is installed with adopt_prepared_tools"
);
self.shell_sessions = sessions;
self
}
#[must_use]
pub fn with_shell_runtime_availability(
mut self,
availability: crate::shell_session::ShellRuntimeAvailability,
) -> Self {
self.shell_sessions = self.shell_sessions.with_availability(availability);
self
}
#[must_use]
pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
self.shell_sessions = self.shell_sessions.with_container_runtime(runtime);
self
}
#[must_use]
pub fn with_network_audit_log(mut self, log: NetworkAuditLog) -> Self {
self.network_audit = Some(log);
self
}
pub async fn new_in(
parent_dir: impl AsRef<std::path::Path>,
permission_handler: P,
executor: E,
) -> Result<Self, TerminalError> {
let parent_dir = parent_dir.as_ref();
async_fs::create_dir_all(parent_dir).await?;
let working_dir = WorkingDir::random_in(parent_dir).map_err(|e| {
TerminalError::SandboxSetup(format!("failed to create working dir: {e}"))
})?;
let working_dir_path = working_dir.path().to_path_buf();
info!(working_dir = %working_dir_path.display(), "created terminal tool working directory");
let outputs_dir = working_dir_path.join("outputs");
async_fs::create_dir_all(&outputs_dir).await?;
let output_store = Arc::new(OutputStore::new(&outputs_dir).await?);
let (job_registry, job_registry_service) = job_registry_channel();
executor
.spawn(async move { job_registry_service.serve().await })
.detach();
let (completed_tx, completed_rx) = async_channel::unbounded();
let (alert_tx, alert_rx) = async_channel::unbounded();
let (started_tx, started_rx) = async_channel::unbounded();
let running_tasks = Arc::new(AtomicUsize::new(0));
let (permission_tx, permission_rx) = async_channel::unbounded();
Ok(Self {
working_dir: working_dir_path,
shell_sessions: ShellSessionRegistry::new(ShellRuntimeAvailability::default()),
permission_handler: Arc::new(permission_handler),
executor,
output_store,
job_registry,
completed_rx,
completed_tx,
alert_rx,
alert_tx,
started_rx,
started_tx,
limits: TerminalLimits::default(),
running_tasks,
permission_rx,
permission_tx,
grants: TerminalGrants::new(),
subagent: None,
carried_dir: Some(CarriedDir::default()),
env_source: None,
network_audit: None,
priority: ProcessPriority::default(),
#[cfg(all(unix, feature = "jobserver"))]
jobserver: None,
outages: Outages::none(),
registry: Unconfigured,
})
}
pub async fn new_exact(
working_dir: impl AsRef<std::path::Path>,
permission_handler: P,
executor: E,
) -> Result<Self, TerminalError> {
let working_dir_path = working_dir.as_ref().to_path_buf();
async_fs::create_dir_all(&working_dir_path).await?;
let outputs_dir = working_dir_path.join("outputs");
async_fs::create_dir_all(&outputs_dir).await?;
let output_store = Arc::new(OutputStore::new(&outputs_dir).await?);
let (job_registry, job_registry_service) = job_registry_channel();
executor
.spawn(async move { job_registry_service.serve().await })
.detach();
let (completed_tx, completed_rx) = async_channel::unbounded();
let (alert_tx, alert_rx) = async_channel::unbounded();
let (started_tx, started_rx) = async_channel::unbounded();
let running_tasks = Arc::new(AtomicUsize::new(0));
let (permission_tx, permission_rx) = async_channel::unbounded();
Ok(Self {
working_dir: working_dir_path,
shell_sessions: ShellSessionRegistry::new(ShellRuntimeAvailability::default()),
permission_handler: Arc::new(permission_handler),
executor,
output_store,
job_registry,
completed_rx,
completed_tx,
alert_rx,
alert_tx,
started_rx,
started_tx,
limits: TerminalLimits::default(),
running_tasks,
permission_rx,
permission_tx,
grants: TerminalGrants::new(),
subagent: None,
carried_dir: Some(CarriedDir::default()),
env_source: None,
network_audit: None,
priority: ProcessPriority::default(),
#[cfg(all(unix, feature = "jobserver"))]
jobserver: None,
outages: Outages::none(),
registry: Unconfigured,
})
}
}
impl<P, E, State> TerminalTool<P, E, State> {
fn map_state<Next>(self, state: impl FnOnce(State) -> Next) -> TerminalTool<P, E, Next> {
TerminalTool {
working_dir: self.working_dir,
shell_sessions: self.shell_sessions,
permission_handler: self.permission_handler,
executor: self.executor,
output_store: self.output_store,
job_registry: self.job_registry,
completed_rx: self.completed_rx,
completed_tx: self.completed_tx,
alert_rx: self.alert_rx,
alert_tx: self.alert_tx,
started_rx: self.started_rx,
started_tx: self.started_tx,
limits: self.limits,
running_tasks: self.running_tasks,
permission_rx: self.permission_rx,
permission_tx: self.permission_tx,
grants: self.grants,
subagent: self.subagent,
carried_dir: self.carried_dir,
env_source: self.env_source,
network_audit: self.network_audit,
priority: self.priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: self.jobserver,
outages: self.outages,
registry: state(self.registry),
}
}
}
impl<P, E> TerminalTool<P, E, Unconfigured>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
#[must_use]
pub fn with_registry(self, registry: Arc<ToolRegistry>) -> TerminalTool<P, E, Configured> {
let registry = Arc::new(
Arc::unwrap_or_clone(registry)
.with_terminal_controls(self.job_registry(), self.outputs_dir()),
);
self.map_state(|Unconfigured| Launching { registry })
.into_served()
}
}
#[cfg(test)]
impl<P, E> TerminalTool<P, E, Configured>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
async fn subagent_without_grant(&self) -> Result<Self, SubagentGrantError> {
self.subagent(
&mut LaunchHistory::default(),
SubagentGrant::new(),
None,
None,
)
.await
}
}
impl<P, E> TerminalTool<P, E, Launching>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
fn into_served(self) -> TerminalTool<P, E, Configured> {
let (launcher, requests) = async_channel::unbounded();
let binding = TerminalBinding {
launcher: TerminalToolFactory { tx: launcher },
working_dir: self.working_dir.clone(),
role: self.registry.registry.role(),
observer: self.registry.registry.observer().cloned(),
};
let source = self.clone();
self.executor
.spawn(async move { serve_launches(requests, source).await })
.detach();
self.map_state(|Launching { registry }| Configured {
registry: Arc::new(ToolRegistry::clone(®istry).bind(&binding)),
binding,
})
}
}
pub trait TerminalEnvSource: std::fmt::Debug + Send + Sync {
fn env(&self) -> Vec<(String, String)>;
}
impl TerminalEnvSource for Vec<(String, String)> {
fn env(&self) -> Vec<(String, String)> {
self.clone()
}
}
impl<P, E, State> TerminalTool<P, E, State>
where
E: Executor + Clone + 'static,
State: Clone,
{
#[must_use]
pub fn with_writable_paths(self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
for path in paths {
self.grants.add_writable(path.into());
}
self
}
#[must_use]
pub fn with_readable_paths(self, paths: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self {
for path in paths {
self.grants.add_readable(path.into());
}
self
}
#[must_use]
pub fn with_env_source(mut self, source: impl TerminalEnvSource + 'static) -> Self {
self.env_source = Some(Arc::new(source));
self
}
#[must_use]
pub fn with_envs(self, envs: impl IntoIterator<Item = (String, String)>) -> Self {
self.with_env_source(envs.into_iter().collect::<Vec<_>>())
}
#[must_use]
pub const fn with_process_priority(mut self, priority: ProcessPriority) -> Self {
self.priority = priority;
self
}
#[cfg(all(unix, feature = "jobserver"))]
pub fn with_jobserver_pool(
mut self,
pool: JobPool,
fifo_dir: impl AsRef<Path>,
) -> Result<Self, TerminalError> {
let (broker, service) = job_broker_channel(pool, fifo_dir)?;
self.executor
.spawn(async move { service.serve().await })
.detach();
self.jobserver = Some(broker);
Ok(self)
}
#[must_use]
pub fn with_foreground_wait(self, wait: Duration) -> Self {
self.limits.foreground_wait.set_normal(wait);
self
}
#[must_use]
pub fn foreground_wait(&self) -> ForegroundWait {
self.limits.foreground_wait.clone()
}
#[must_use]
pub const fn with_timeout_cap(mut self, cap: Duration) -> Self {
self.limits.timeout_cap = cap;
self
}
#[must_use]
pub fn with_subagent_import_limit(self, bytes: u64) -> Self {
self.limits.subagent_import.set(bytes);
self
}
#[must_use]
pub fn subagent_import_budget(&self) -> ImportBudget {
self.limits.subagent_import.clone()
}
#[must_use]
pub const fn with_long_job_alert_after(mut self, after: Duration) -> Self {
self.limits.long_job_alert = after;
self
}
#[cfg(feature = "connectivity")]
#[must_use]
pub fn with_connectivity(mut self, connectivity: &aither_connectivity::Connectivity) -> Self {
self.outages = Outages::watching(connectivity, &self.executor);
self
}
pub async fn initialize_tools(
mut self,
distribution: &ToolDistribution,
cache_root: &Path,
) -> Result<Self, ToolRuntimeError>
where
P: PermissionHandler,
State: Send,
{
self.shell_sessions = self
.shell_sessions
.initialize_tools(distribution, cache_root)
.await?;
if let Some(tools) = self.local_home_tools()? {
tools.ensure_readonly(self.writable_grants().iter()).await?;
tools.verify_local_versions(self.executor.clone()).await?;
}
Ok(self)
}
pub async fn adopt_prepared_tools(
mut self,
sessions: ShellSessionRegistry,
) -> Result<Self, ToolRuntimeError>
where
P: PermissionHandler,
State: Send,
{
sessions.prepared_catalog()?;
self.shell_sessions = sessions;
if let Some(tools) = self.local_home_tools()? {
tools.ensure_readonly(self.writable_grants().iter()).await?;
}
Ok(self)
}
fn local_home_tools(&self) -> Result<Option<&PreparedTools<PathBuf>>, ToolRuntimeError> {
match self.shell_sessions.resolve_local_backend() {
Ok(ShellBackend::Local) => self.shell_sessions.local_tools().map(Some),
_ => Ok(None),
}
}
fn writable_grants(&self) -> Vec<PathBuf> {
let grants = self.grants.snapshot();
std::iter::once(self.working_dir.clone())
.chain(grants.writable.iter().cloned())
.collect()
}
#[must_use]
pub const fn shell_sessions(&self) -> &ShellSessionRegistry {
&self.shell_sessions
}
pub fn prepared_tools_context(&self) -> Result<String, ToolRuntimeError> {
self.shell_sessions.prepared_catalog()?.render()
}
pub const fn working_dir(&self) -> &PathBuf {
&self.working_dir
}
pub fn outputs_dir(&self) -> PathBuf {
self.working_dir.join("outputs")
}
pub const fn output_store(&self) -> &Arc<OutputStore> {
&self.output_store
}
pub fn job_registry(&self) -> JobRegistry {
self.job_registry.clone()
}
pub(crate) fn job_alert_sender(&self) -> Sender<JobAlert> {
self.alert_tx.clone()
}
pub const fn executor(&self) -> &E {
&self.executor
}
pub fn grants(&self) -> TerminalGrants {
self.grants.clone()
}
pub fn background_receiver(&self) -> BackgroundTaskReceiver {
BackgroundTaskReceiver {
rx: self.completed_rx.clone(),
alert_rx: self.alert_rx.clone(),
started_rx: self.started_rx.clone(),
running_tasks: self.running_tasks.clone(),
}
}
pub fn permission_receiver(&self) -> PermissionEventReceiver {
PermissionEventReceiver {
rx: self.permission_rx.clone(),
}
}
pub fn take_completed(&self) -> Vec<CompletedTask> {
let mut completed = Vec::new();
while let Ok(task) = self.completed_rx.try_recv() {
completed.push(task);
}
completed
}
pub fn has_pending_tasks(&self) -> bool {
!self.completed_rx.is_empty() || self.running_tasks.load(Ordering::Acquire) > 0
}
}
const SUBAGENT_SPACES_DIR: &str = "subagent-spaces";
impl<P, E, State> TerminalTool<P, E, State>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
State: RegistryState,
{
#[allow(clippy::too_many_lines)]
pub(crate) async fn subagent(
&self,
history: &mut LaunchHistory,
grant: SubagentGrant,
observer: Option<AnyCommandObserver>,
gate: Option<AnyCommandGate>,
) -> Result<TerminalTool<P, E, Configured>, SubagentGrantError> {
let working_dir = canonical_path(&self.working_dir).await?;
let mut authority = vec![working_dir.clone()];
for path in &self.grants.snapshot().writable {
authority.push(canonical_path(path).await?);
}
let spaces_root = working_dir.join(SUBAGENT_SPACES_DIR);
let mount = self.container_mount().await?;
let granted = grant
.resolve(
Launcher {
writable: &authority,
committing: self
.subagent
.as_ref()
.map(|subagent| subagent.committing.as_slice()),
spaces_root: &spaces_root,
spelling: mount
.as_ref()
.map_or_else(Spelling::host, Spelling::through),
},
history,
)
.await?;
self.registry
.registry()
.record_committed(&granted.committing);
let space = spaces_root.join(crate::naming::random_word_slug(4));
let container = mount
.as_ref()
.map(|mount| container_confinement_for(mount, &space, &granted.writable))
.transpose()?;
async_fs::create_dir_all(&space)
.await
.map_err(|source| SubagentGrantError::Space {
path: space.clone(),
source,
})?;
let (completed_tx, completed_rx) = async_channel::unbounded();
let (alert_tx, alert_rx) = async_channel::unbounded();
let (started_tx, started_rx) = async_channel::unbounded();
let running_tasks = Arc::new(AtomicUsize::new(0));
let (permission_tx, permission_rx) = async_channel::unbounded();
let (job_registry, job_registry_service) = job_registry_channel();
self.executor
.spawn(async move { job_registry_service.serve().await })
.detach();
let grants = TerminalGrants::derived(&self.grants, authority, granted.writable.clone());
let readable_paths = grants.snapshot().readable.clone();
let git = match (&container, mount) {
(Some(confinement), Some(mount)) => {
SubagentGit::new(Arc::new(subagent_git::ContainerGit {
executor: self.executor.clone(),
shell_sessions: self.shell_sessions.clone(),
confinement: confinement.clone(),
mount,
priority: self.priority,
}))
}
_ => SubagentGit::new(Arc::new(subagent_git::LocalGit {
executor: self.executor.clone(),
working_dir: space.clone(),
writable: granted.writable,
readable: readable_paths,
committing: granted.committing.clone(),
priority: self.priority,
})),
};
let registry = Arc::new(
self.registry
.registry()
.for_subagent(observer, gate)
.with_terminal_controls(job_registry.clone(), self.outputs_dir()),
);
let launching = TerminalTool {
working_dir: space,
shell_sessions: self.shell_sessions.clone(),
permission_handler: self
.permission_handler
.for_subagent()
.map_or_else(|| self.permission_handler.clone(), Arc::new),
executor: self.executor.clone(),
output_store: self.output_store.clone(),
job_registry,
completed_rx,
completed_tx,
alert_rx,
alert_tx,
started_rx,
started_tx,
limits: self.limits.clone(),
running_tasks,
permission_rx,
permission_tx,
grants,
subagent: Some(SubagentAuthority {
committing: granted.committing,
git,
container,
}),
carried_dir: None,
env_source: self.env_source.clone(),
network_audit: self.network_audit.clone(),
priority: self.priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: self.jobserver.clone(),
outages: self.outages.clone(),
registry: Launching { registry },
};
Ok(launching.into_served())
}
async fn container_mount(&self) -> Result<Option<MountRoot>, SubagentGrantError> {
if self.shell_sessions.resolve_local_backend() != Ok(ShellBackend::Container) {
return Ok(None);
}
let mount = self
.shell_sessions
.container_runtime()
.and_then(ContainerShellRuntime::workspace_mount)
.ok_or(SubagentGrantError::NoContainerMount)?;
Ok(Some(MountRoot::new(
canonical_path(&mount.host_root).await?,
mount.container_root.clone(),
)))
}
}
fn container_confinement_for(
mount: &MountRoot,
space: &Path,
writable: &[PathBuf],
) -> Result<ContainerConfinement, SubagentGrantError> {
let map = |path: &Path| {
mount
.container_path(path)
.map_err(|source| SubagentGrantError::OutsideContainerMount {
path: path.to_path_buf(),
source,
})
};
Ok(ContainerConfinement {
working_dir: map(space)?,
writable: writable
.iter()
.map(|path| map(path))
.collect::<Result<_, _>>()?,
})
}
impl<P, E> TerminalTool<P, E, Configured>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
const fn registry(&self) -> &Arc<ToolRegistry> {
&self.registry.registry
}
#[must_use]
pub fn kept_receiver(&self) -> crate::command::KeptExchangeReceiver {
self.registry().kept_receiver()
}
#[must_use]
pub const fn binding(&self) -> &TerminalBinding {
&self.registry.binding
}
fn commit_ledger(&self) -> Option<CommitLedger> {
self.subagent.as_ref().and_then(|subagent| {
CommitLedger::new(
&subagent.committing,
subagent.git.clone(),
ImportLimits {
bytes: self.limits.subagent_import.clone(),
time: self.limits.foreground_wait.get(),
},
)
})
}
pub fn to_dyn(self) -> crate::command::DynTerminalTool {
use crate::command::DynTerminalTool;
let background_receiver = self.background_receiver();
let permission_receiver = self.permission_receiver();
let kept_receiver = self.kept_receiver();
let job_registry = self.job_registry();
let working_dir = self.working_dir().clone();
let command_names = self.registry().available_tool_names();
let commit_ledger = self.commit_ledger();
let role = self.registry().role();
let prepared_tools = self
.shell_sessions
.prepared_catalog()
.expect("terminal tools must be initialized before exposing child capabilities")
.clone();
let entries = vec![erase_terminal_tool(self)];
DynTerminalTool {
entries,
background_receiver,
permission_receiver,
kept_receiver,
job_registry,
working_dir,
command_names,
prepared_tools,
commit_ledger,
role,
}
}
fn resolve_execution_target(
&self,
mode: TerminalExecutionMode,
ssh_server_id: Option<&str>,
) -> Result<ExecutionTarget, TerminalError> {
match mode {
TerminalExecutionMode::Default => self.resolve_default_target(),
TerminalExecutionMode::Sandboxed => self.resolve_home_target(TerminalMode::Sandboxed),
TerminalExecutionMode::Unsafe => self.resolve_home_target(TerminalMode::Unsafe),
TerminalExecutionMode::Ssh => self.resolve_ssh_target(ssh_server_id),
}
}
fn resolve_default_target(&self) -> Result<ExecutionTarget, TerminalError> {
if self.shell_sessions.resolve_local_backend().is_ok() {
self.resolve_home_target(TerminalMode::Sandboxed)
} else {
self.resolve_ssh_target(None)
}
}
fn resolve_home_target(&self, mode: TerminalMode) -> Result<ExecutionTarget, TerminalError> {
let backend = self
.shell_sessions
.resolve_local_backend()
.map_err(TerminalError::InvalidTarget)?;
if mode == TerminalMode::Unsafe && backend != ShellBackend::Local {
return Err(TerminalError::InvalidTarget(
"unsafe mode is only available in heel local runtime".into(),
));
}
let backend = match backend {
ShellBackend::Local => {
ExecutionBackend::Local(self.shell_sessions.local_tools()?.clone())
}
ShellBackend::Container => ExecutionBackend::Container {
runtime: self
.shell_sessions
.container_runtime()
.cloned()
.ok_or(ToolRuntimeError::MissingContainerRuntime)?,
tools: self.shell_sessions.container_tools()?.clone(),
confinement: self
.subagent
.as_ref()
.and_then(|subagent| subagent.container.clone()),
},
ShellBackend::Ssh => unreachable!("the home backend is never SSH"),
};
Ok(ExecutionTarget { mode, backend })
}
fn resolve_ssh_target(
&self,
ssh_server_id: Option<&str>,
) -> Result<ExecutionTarget, TerminalError> {
self.shell_sessions
.ensure_ssh_available()
.map_err(TerminalError::InvalidTarget)?;
let server = ssh_server_id
.map_or_else(
|| self.shell_sessions.default_ssh_server(),
|id| self.shell_sessions.resolve_ssh_server(id),
)
.map_err(TerminalError::InvalidTarget)?;
let (runtime, tools) = self.shell_sessions.ssh_tools(&server)?;
Ok(ExecutionTarget {
mode: TerminalMode::Sandboxed,
backend: ExecutionBackend::Ssh {
target: server.target,
runtime: runtime.clone(),
tools: tools.clone(),
},
})
}
async fn ensure_permission_allowed(
&self,
mode: TerminalMode,
script: &str,
) -> anyhow::Result<()> {
if mode.requires_approval() {
match self
.permission_handler
.review(&PermissionRequest::Command { mode, script })
.await
{
Review::Approved => return Ok(()),
Review::Denied(reason) => {
return Err(anyhow::Error::new(TerminalError::from(
PermissionError::Denied(reason),
)));
}
Review::Passed => {}
}
}
let permission_waits = self
.permission_handler
.will_wait_for_approval(mode, script)
.await;
if permission_waits {
self.emit_permission_event(mode, script, PermissionEventStage::Waiting)
.await;
}
let permission_result =
ensure_mode_allowed(self.permission_handler.as_ref(), mode, script).await;
if permission_waits {
self.emit_permission_event(mode, script, PermissionEventStage::Resolved)
.await;
}
permission_result.map_err(anyhow::Error::new)
}
async fn emit_permission_event(
&self,
mode: TerminalMode,
script: &str,
stage: PermissionEventStage,
) {
let _ = self
.permission_tx
.send(PermissionEvent {
mode,
script: script.to_string(),
stage,
})
.await;
}
fn spawn_terminal_execution(&self, request: TerminalSpawnRequest) -> SpawnedTerminal {
let TerminalSpawnRequest {
target,
task_id,
execution_id,
script,
expect,
resolution,
max_lines,
raw,
background,
timeout,
carry,
call,
} = request;
let registry = call.map_or_else(
|| self.registry().clone(),
|call| Arc::new(self.registry().for_call(call)),
);
let ExecutionTarget { mode, backend } = target;
let (result_tx, result_rx) = async_channel::bounded(1);
let (startup_tx, startup_rx) = async_channel::bounded(1);
let stdin_alerts = Some(StdinAlerts {
tx: self.alert_tx.clone(),
task_id: task_id.clone(),
script: script.clone(),
});
let timeout_watch = self.spawn_kill_watchdog(&task_id, timeout);
self.spawn_long_job_alert(&task_id);
let lifetime = if background {
JobLifetime::Background
} else {
JobLifetime::Foreground {
alerts: self.alert_tx.clone(),
}
};
let background_startup = BackgroundStartup::new(startup_tx);
let running_tasks = self.running_tasks.clone();
let completed_tx = self.completed_tx.clone();
let outages = self.outages.clone();
outages.begin(&task_id);
running_tasks.fetch_add(1, Ordering::AcqRel);
self.executor
.spawn(execute_terminal_task(SpawnedTerminalTask {
working_dir: self.working_dir.clone(),
writable_paths: self.grants.snapshot().writable.clone(),
readable_paths: self.grants.snapshot().readable.clone(),
env_source: self.env_source.clone(),
executor: self.executor.clone(),
registry,
permission_handler: self.permission_handler.clone(),
job_registry: self.job_registry.clone(),
task_id,
execution_id,
background,
timeout_watch: timeout_watch.clone(),
carry,
carried_dir: self.carried_dir.clone(),
alert_tx: self.alert_tx.clone(),
script,
mode,
backend,
stdin_alerts,
lifetime,
background_startup,
expect,
resolution,
store_dir: self.output_store.dir().to_path_buf(),
max_lines,
raw,
result_tx,
completed_tx,
running_tasks,
network_audit: self.network_audit.clone(),
priority: self.priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: self.jobserver.clone(),
outages,
}))
.detach();
SpawnedTerminal {
result: result_rx,
startup: startup_rx,
timeout_watch,
}
}
}
impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> Tool
for TerminalTool<P, E, Configured>
{
fn name(&self) -> Cow<'static, str> {
"terminal".into()
}
type Arguments = TerminalArgs;
type Res = ToolResult;
async fn call(
&self,
arguments: Self::Arguments,
cx: ToolContext,
) -> aither_core::Result<Self::Res> {
let cap = self.limits.timeout_cap;
let timeout = Duration::from_secs(arguments.timeout);
if arguments.timeout == 0 || timeout > cap {
return Err(anyhow::anyhow!(
"terminal timeout must be between 1 and {} seconds",
cap.as_secs()
));
}
let prepared = self.prepare_execution(&arguments).await?;
let carry = if arguments.background {
None
} else {
self.cwd_carry(&prepared, &arguments.script).await
};
let spawned = self.spawn_terminal_execution(TerminalSpawnRequest {
target: prepared.target,
task_id: prepared.task_id.clone(),
execution_id: prepared.execution_id,
script: arguments.script,
expect: arguments.expect,
resolution: arguments.resolution,
max_lines: prepared.max_lines,
raw: arguments.raw,
background: arguments.background,
timeout,
carry: carry.clone(),
call: cx.identity().cloned(),
});
wait_for_background_startup(&spawned.startup).await?;
if arguments.background {
return background_terminal_result(
&self.job_registry,
&prepared.store_dir,
&prepared.task_id,
prepared.max_lines,
&self.started_tx,
)
.await;
}
let outcome =
wait_for_foreground_result(&spawned.result, self.limits.foreground_wait.get()).await;
let outcome = outcome.or_else(|| spawned.result.try_recv().ok());
match outcome {
Some(Ok(result)) => {
let killed = self
.job_registry
.get_by_task_id(&prepared.task_id)
.await
.is_some_and(|job| matches!(job.status, JobStatus::Killed));
let command = if killed {
CommandResult {
stdout: result.stdout,
stderr: result.stderr,
interruptions: result.interruptions,
outcome: CommandOutcome::Killed {
task_id: prepared.task_id.clone(),
notice: spawned.timeout_watch.kill().map_or_else(
|| "Killed before its timeout bound passed.".to_string(),
|kill| kill.notice(),
),
},
}
} else {
CommandResult::from(result)
};
command.into_tool_result()
}
Some(Err(err)) => Err(anyhow::anyhow!(err)),
None => {
background_terminal_result(
&self.job_registry,
&prepared.store_dir,
&prepared.task_id,
prepared.max_lines,
&self.started_tx,
)
.await
}
}
}
}
impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> TerminalTool<P, E, Configured> {
async fn cwd_carry(&self, prepared: &ExecutionPreparation, script: &str) -> Option<CwdCarry> {
let carried = self.carried_dir.as_ref()?;
let mount = match &prepared.target.backend {
ExecutionBackend::Local(_) if !cfg!(windows) => None,
ExecutionBackend::Container { runtime, .. } => Some(runtime.workspace_mount()?.clone()),
_ => return None,
};
let start = carried.get();
let start = match start {
Some(dir)
if async_fs::metadata(&dir)
.await
.is_ok_and(|meta| meta.is_dir()) =>
{
Some(dir)
}
Some(_) => {
carried.set(None);
let dir = if mount.is_some() {
PathBuf::from(CONTAINER_EXEC_WORKING_DIR)
} else {
self.own_dir().await
};
let _ = self
.alert_tx
.send(JobAlert::DirectoryReset(DirectoryReset {
dir,
reason: DirectoryResetReason::Removed,
}))
.await;
None
}
None => None,
};
let report = self.working_dir.join(format!(".cwd-{}", prepared.task_id));
let container = match mount {
None => None,
Some(mount) => {
let container_report = mount.container_path(&report).ok()?;
let container_start = start
.as_ref()
.and_then(|start| mount.container_path(start).ok())
.unwrap_or_else(|| {
ContainerPath::new(CONTAINER_EXEC_WORKING_DIR)
.expect("the exec directory is absolute")
});
Some(ContainerCarry {
mount,
report: container_report,
start: container_start,
})
}
};
let shell = container.is_some() || runs_in_shell(script);
Some(CwdCarry {
start,
report,
container,
shell,
})
}
#[cfg(test)]
async fn record_carried_dir(&self, carry: &CwdCarry, succeeded: bool) {
let ctx = CarryContext {
carried_dir: self.carried_dir.as_ref(),
alert_tx: &self.alert_tx,
working_dir: &self.working_dir,
grants: self.grants.snapshot(),
};
let Some(reported) = take_cwd_report(carry).await else {
if carry.shell {
alert_directory_reset(carry, DirectoryResetReason::Unreported, &ctx).await;
}
return;
};
apply_cwd_report(carry, reported, succeeded, &ctx).await;
}
async fn own_dir(&self) -> PathBuf {
canonical_path(&self.working_dir)
.await
.unwrap_or_else(|_| self.working_dir.clone())
}
}
struct CarryContext<'a> {
carried_dir: Option<&'a CarriedDir>,
alert_tx: &'a Sender<JobAlert>,
working_dir: &'a Path,
grants: std::sync::Arc<GrantSet>,
}
async fn take_cwd_report(carry: &CwdCarry) -> Option<String> {
let reported = async_fs::read_to_string(&carry.report).await;
let _ = async_fs::remove_file(&carry.report).await;
reported
.ok()
.map(|reported| reported.trim_end_matches('\n').to_owned())
.filter(|reported| !reported.is_empty())
}
async fn apply_cwd_report(
carry: &CwdCarry,
reported: String,
succeeded: bool,
ctx: &CarryContext<'_>,
) {
let Some(carried) = ctx.carried_dir else {
return;
};
if !succeeded {
if !left_in_start(carry, &reported, ctx.working_dir).await {
alert_directory_reset(carry, DirectoryResetReason::Failed, ctx).await;
}
return;
}
if let Some(container) = &carry.container {
match ContainerPath::new(reported.as_str())
.map_err(drop)
.and_then(|dir| container.mount.host_path(&dir).map_err(drop))
{
Ok(dir) => carried.set(Some(dir)),
Err(()) => {
alert_directory_reset(carry, DirectoryResetReason::OutsideWorkspace, ctx).await;
}
}
return;
}
let Ok(dir) = canonical_path(Path::new(&reported)).await else {
alert_directory_reset(carry, DirectoryResetReason::Removed, ctx).await;
return;
};
for grant in std::iter::once(ctx.working_dir)
.chain(ctx.grants.writable.iter().map(PathBuf::as_path))
.chain(ctx.grants.readable.iter().map(PathBuf::as_path))
{
if canonical_path(grant)
.await
.is_ok_and(|grant| dir.starts_with(grant))
{
carried.set(Some(dir));
return;
}
}
alert_directory_reset(carry, DirectoryResetReason::OutsideReadable, ctx).await;
}
async fn left_in_start(carry: &CwdCarry, reported: &str, working_dir: &Path) -> bool {
if let Some(container) = &carry.container {
return reported == container.start.as_str();
}
let start = carry.start.as_deref().unwrap_or(working_dir);
match (
canonical_path(Path::new(reported)).await,
canonical_path(start).await,
) {
(Ok(reported), Ok(start)) => reported == start,
_ => false,
}
}
async fn alert_directory_reset(
carry: &CwdCarry,
reason: DirectoryResetReason,
ctx: &CarryContext<'_>,
) {
let dir = match &carry.container {
Some(container) => PathBuf::from(container.start.as_str()),
None => match &carry.start {
Some(start) => start.clone(),
None => canonical_path(ctx.working_dir)
.await
.unwrap_or_else(|_| ctx.working_dir.to_path_buf()),
},
};
let _ = ctx
.alert_tx
.send(JobAlert::DirectoryReset(DirectoryReset { dir, reason }))
.await;
}
impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> TerminalTool<P, E, Configured> {
pub async fn run_background(&self, arguments: TerminalArgs) -> aither_core::Result<ToolResult> {
self.call(
TerminalArgs {
background: true,
..arguments
},
ToolContext::new(),
)
.await
}
async fn prepare_execution(
&self,
arguments: &TerminalArgs,
) -> anyhow::Result<ExecutionPreparation> {
if arguments.description.trim().is_empty() {
return Err(anyhow::anyhow!("terminal description must not be empty"));
}
crate::kill_guard::check(&arguments.script)?;
if !arguments.background && crate::poll_guard::contains_sleep(&arguments.script) {
return Err(crate::poll_guard::PollRefusal::Sleep.into());
}
let file_reads = self.fingerprint_reads(&arguments.script).await;
if !file_reads.is_empty()
&& self
.job_registry
.file_reads_unchanged(file_reads.clone())
.await
{
return Err(crate::poll_guard::PollRefusal::UnchangedFileRead {
paths: file_reads.iter().map(|(path, _)| path.clone()).collect(),
}
.into());
}
if let Some(gate) = self.registry.registry().gate()
&& let GateDecision::Block { reason } = gate.check(&arguments.script).await
{
return Err(CommandBlocked { reason }.into());
}
let target =
self.resolve_execution_target(arguments.mode, arguments.ssh_server_id.as_deref())?;
if let ExecutionBackend::Local(tools) = &target.backend {
tools
.ensure_readonly(
std::iter::once(&self.working_dir)
.chain(self.grants.snapshot().writable.iter()),
)
.await?;
}
self.ensure_permission_allowed(target.mode, &arguments.script)
.await?;
if !file_reads.is_empty() {
self.job_registry.record_file_reads(file_reads).await;
}
let task_id = random_task_id();
Ok(ExecutionPreparation {
target,
execution_id: format!("exec-{task_id}"),
task_id,
store_dir: self.output_store.dir().to_path_buf(),
max_lines: arguments.max_lines.min(MAX_LINES_CEILING) as usize,
})
}
async fn fingerprint_reads(
&self,
script: &str,
) -> Vec<(std::path::PathBuf, crate::job_registry::FileFingerprint)> {
let mut reads = Vec::new();
for target in crate::poll_guard::file_reads(script) {
let mut path = std::path::PathBuf::from(&target);
if path.is_relative() {
path = self.working_dir.join(path);
}
if let Ok(meta) = async_fs::metadata(&path).await
&& meta.is_file()
{
reads.push((path, (meta.len(), meta.modified().ok())));
}
}
reads
}
fn spawn_kill_watchdog(&self, task_id: &str, timeout: Duration) -> Arc<TimeoutWatch> {
let watch = Arc::new(TimeoutWatch::new(timeout));
let job_registry = self.job_registry.clone();
let task_id = task_id.to_string();
let recorded = watch.clone();
self.executor
.spawn(async move {
async_io::Timer::after(timeout).await;
if let Some(job) = job_registry.get_by_task_id(&task_id).await
&& matches!(job.status, JobStatus::Running)
{
let _ = recorded.killed.set(jiff::Timestamp::now());
job_registry.kill(job.pid).await;
}
})
.detach();
watch
}
fn spawn_long_job_alert(&self, task_id: &str) {
let job_registry = self.job_registry.clone();
let alert_tx = self.alert_tx.clone();
let task_id = task_id.to_string();
let alert_after = self.limits.long_job_alert;
self.executor
.spawn(async move {
async_io::Timer::after(alert_after).await;
if let Some(job) = job_registry.get_by_task_id(&task_id).await
&& matches!(job.status, JobStatus::Running)
{
let _ = alert_tx
.send(JobAlert::LongRunning(LongRunningJob {
task_id,
script: job.script,
elapsed: job.started_at.elapsed(),
}))
.await;
}
})
.detach();
}
}
struct ExecutionPreparation {
target: ExecutionTarget,
task_id: String,
execution_id: String,
store_dir: PathBuf,
max_lines: usize,
}
async fn wait_for_background_startup(
startup_rx: &Receiver<Result<(), String>>,
) -> anyhow::Result<()> {
match startup_rx.recv().await {
Ok(Ok(())) => Ok(()),
Ok(Err(err)) => Err(anyhow::anyhow!(err)),
Err(_) => Err(anyhow::anyhow!(
"background startup channel dropped before registration"
)),
}
}
async fn wait_for_foreground_result(
result_rx: &Receiver<Result<CompletedCommand, String>>,
limit: Duration,
) -> Option<Result<CompletedCommand, String>> {
futures_lite::future::or(async { result_rx.recv().await.ok() }, async {
async_io::Timer::after(limit).await;
result_rx.try_recv().ok()
})
.await
}
async fn background_terminal_result(
job_registry: &JobRegistry,
store_dir: &Path,
task_id: &str,
max_lines: usize,
started_tx: &Sender<StartedBackgroundTask>,
) -> aither_core::Result<ToolResult> {
let redirect =
start_background_output_redirect(job_registry, store_dir, task_id, max_lines).await?;
let _ = started_tx
.send(StartedBackgroundTask {
task_id: task_id.to_string(),
output_preview: redirect.preview.clone(),
output_file: redirect.file.clone(),
})
.await;
let stdout = if redirect.truncated {
CommandStream::Stored {
file: redirect.file.clone(),
preview: redirect.preview,
truncated: true,
}
} else {
CommandStream::Inline {
text: redirect.preview,
}
};
CommandResult {
stdout,
stderr: None,
interruptions: Vec::new(),
outcome: CommandOutcome::Running {
task_id: task_id.to_string(),
output: redirect.file,
},
}
.into_tool_result()
}
struct BackgroundRedirect {
file: StoredFile,
preview: String,
truncated: bool,
}
async fn start_background_output_redirect(
job_registry: &JobRegistry,
store_dir: &Path,
task_id: &str,
max_lines: usize,
) -> Result<BackgroundRedirect, anyhow::Error> {
let (url, output_path) = save_raw_to_file(store_dir, &[]).await?;
let file = StoredFile {
url,
path: output_path.display().to_string(),
};
let snapshot = job_registry
.start_output_redirect(task_id, output_path)
.await
.map_err(anyhow::Error::msg)?;
let (preview, truncated) = preview_first_lines(&snapshot, max_lines);
Ok(BackgroundRedirect {
file,
preview: background_preview(&preview),
truncated,
})
}
fn background_preview(preview: &str) -> String {
if preview.trim().is_empty() {
String::new()
} else {
preview.trim_end().to_string()
}
}
struct StandaloneExecution<P, E> {
working_dir: PathBuf,
writable_paths: Vec<PathBuf>,
readable_paths: Vec<PathBuf>,
env_source: Option<Arc<dyn TerminalEnvSource>>,
executor: E,
registry: Arc<ToolRegistry>,
permission_handler: Arc<P>,
job_registry: JobRegistry,
task_id: String,
execution_id: String,
background: bool,
carry: Option<CwdCarry>,
carried_dir: Option<CarriedDir>,
alert_tx: Sender<JobAlert>,
script: String,
mode: TerminalMode,
backend: ExecutionBackend,
stdin_alerts: Option<StdinAlerts>,
lifetime: JobLifetime,
background_startup: BackgroundStartup,
network_audit: Option<NetworkAuditLog>,
priority: ProcessPriority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: Option<JobBroker>,
expect: OutputFormat,
resolution: MediaResolution,
store_dir: PathBuf,
max_lines: usize,
raw: bool,
}
struct StandaloneStart<'a, P, E> {
working_dir: &'a Path,
writable_paths: &'a [PathBuf],
readable_paths: &'a [PathBuf],
env_source: &'a Option<Arc<dyn TerminalEnvSource>>,
executor: E,
registry: &'a Arc<ToolRegistry>,
permission_handler: Arc<P>,
job_registry: &'a JobRegistry,
task_id: &'a str,
execution_id: &'a str,
carry: Option<&'a CwdCarry>,
script: &'a str,
mode: TerminalMode,
backend: &'a ExecutionBackend,
stdin_alerts: Option<StdinAlerts>,
lifetime: JobLifetime,
background_startup: &'a BackgroundStartup,
network_audit: Option<NetworkAuditLog>,
priority: ProcessPriority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: &'a Option<JobBroker>,
}
struct LocalBackgroundExecution<'a, E> {
prepared_tools: &'a PreparedTools<PathBuf>,
working_dir: &'a Path,
writable_paths: &'a [PathBuf],
readable_paths: &'a [PathBuf],
env_source: &'a Option<Arc<dyn TerminalEnvSource>>,
executor: E,
registry: &'a Arc<ToolRegistry>,
task_id: &'a str,
execution_id: &'a str,
carry: Option<&'a CwdCarry>,
script: &'a str,
mode: TerminalMode,
job_registry: &'a JobRegistry,
stdin_alerts: Option<StdinAlerts>,
lifetime: JobLifetime,
background_startup: &'a BackgroundStartup,
priority: ProcessPriority,
#[cfg(all(unix, feature = "jobserver"))]
job_fifo: Option<crate::jobserver::CommandFifo>,
}
struct ContainerBackgroundExecution<'a, E> {
executor: E,
env_source: &'a Option<Arc<dyn TerminalEnvSource>>,
registry: &'a Arc<ToolRegistry>,
task_id: &'a str,
execution_id: &'a str,
script: &'a str,
mode: TerminalMode,
container_runtime: &'a ContainerShellRuntime,
prepared_tools: &'a PreparedTools<ContainerPath>,
confinement: Option<&'a ContainerConfinement>,
carry: Option<&'a ContainerCarry>,
ipc_commands: &'a [String],
job_registry: &'a JobRegistry,
stdin_alerts: Option<StdinAlerts>,
lifetime: JobLifetime,
background_startup: &'a BackgroundStartup,
priority: ProcessPriority,
}
struct SshBackgroundExecution<'a> {
prepared_tools: &'a PreparedTools<PathBuf>,
task_id: &'a str,
execution_id: &'a str,
script: &'a str,
mode: TerminalMode,
ssh_target: &'a str,
ssh_runtime: &'a SshRuntimeProfile,
job_registry: &'a JobRegistry,
background_startup: &'a BackgroundStartup,
}
struct CompletedProcessOutput<'a> {
job_registry: &'a JobRegistry,
pid: u32,
output: std::process::Output,
background_output: bool,
store_dir: &'a Path,
expect: OutputFormat,
resolution: MediaResolution,
max_lines: usize,
raw: bool,
}
enum ExecutionBackend {
Local(PreparedTools<PathBuf>),
Container {
runtime: ContainerShellRuntime,
tools: PreparedTools<ContainerPath>,
confinement: Option<ContainerConfinement>,
},
Ssh {
target: String,
runtime: SshRuntimeProfile,
tools: PreparedTools<PathBuf>,
},
}
struct ExecutionTarget {
mode: TerminalMode,
backend: ExecutionBackend,
}
struct TerminalSpawnRequest {
target: ExecutionTarget,
task_id: String,
execution_id: String,
script: String,
expect: OutputFormat,
resolution: MediaResolution,
max_lines: usize,
raw: bool,
background: bool,
timeout: Duration,
carry: Option<CwdCarry>,
call: Option<CallIdentity>,
}
struct SpawnedTerminal {
result: Receiver<Result<CompletedCommand, String>>,
startup: Receiver<Result<(), String>>,
timeout_watch: Arc<TimeoutWatch>,
}
struct SpawnedTerminalTask<P, E> {
working_dir: PathBuf,
writable_paths: Vec<PathBuf>,
readable_paths: Vec<PathBuf>,
executor: E,
registry: Arc<ToolRegistry>,
permission_handler: Arc<P>,
job_registry: JobRegistry,
task_id: String,
execution_id: String,
background: bool,
timeout_watch: Arc<TimeoutWatch>,
carry: Option<CwdCarry>,
carried_dir: Option<CarriedDir>,
alert_tx: Sender<JobAlert>,
script: String,
mode: TerminalMode,
backend: ExecutionBackend,
stdin_alerts: Option<StdinAlerts>,
lifetime: JobLifetime,
background_startup: BackgroundStartup,
expect: OutputFormat,
resolution: MediaResolution,
store_dir: PathBuf,
max_lines: usize,
raw: bool,
result_tx: Sender<Result<CompletedCommand, String>>,
completed_tx: Sender<CompletedTask>,
running_tasks: Arc<AtomicUsize>,
env_source: Option<Arc<dyn TerminalEnvSource>>,
network_audit: Option<NetworkAuditLog>,
priority: ProcessPriority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: Option<JobBroker>,
outages: Outages,
}
async fn execute_terminal_task<P, E>(task: SpawnedTerminalTask<P, E>)
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
let SpawnedTerminalTask {
working_dir,
writable_paths,
readable_paths,
env_source,
executor,
registry,
permission_handler,
job_registry,
task_id,
execution_id,
background,
timeout_watch,
carry,
carried_dir,
alert_tx,
script,
mode,
backend,
stdin_alerts,
lifetime,
background_startup,
expect,
resolution,
store_dir,
max_lines,
raw,
result_tx,
completed_tx,
running_tasks,
network_audit,
priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver,
outages,
} = task;
let status_registry = job_registry.clone();
let result = execute_script_standalone(StandaloneExecution {
working_dir,
writable_paths,
readable_paths,
env_source,
executor,
registry,
permission_handler,
job_registry,
task_id: task_id.clone(),
execution_id,
background,
carry,
carried_dir,
alert_tx,
script: script.clone(),
mode,
backend,
stdin_alerts,
lifetime,
background_startup,
network_audit,
priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver,
expect,
resolution,
store_dir,
max_lines,
raw,
})
.await;
let interruptions = outages.end(&task_id).await;
let result = result.map(|command| CompletedCommand {
interruptions,
..command
});
let quick_result = match &result {
Ok(ok) => Ok(ok.clone()),
Err(err) => Err(err.to_string()),
};
let _ = result_tx.send(quick_result).await;
let killed = status_registry
.get_by_task_id_settled(&task_id)
.await
.is_some_and(|job| matches!(job.status, JobStatus::Killed));
let _ = completed_tx
.send(CompletedTask {
task_id,
script,
result,
killed,
timeout_kill: timeout_watch.kill().filter(|_| killed),
})
.await;
running_tasks.fetch_sub(1, Ordering::AcqRel);
}
#[allow(clippy::too_many_lines)]
async fn execute_script_standalone<P, E>(
request: StandaloneExecution<P, E>,
) -> Result<CompletedCommand, TerminalError>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
let StandaloneExecution {
working_dir,
writable_paths,
readable_paths,
env_source,
executor,
registry,
permission_handler,
job_registry,
task_id,
execution_id,
background,
carry,
carried_dir,
alert_tx,
script,
mode,
backend,
stdin_alerts,
lifetime,
background_startup,
network_audit,
priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver,
expect,
resolution,
store_dir,
max_lines,
raw,
} = request;
info!(
script_len = script.len(),
?mode,
"executing background terminal command"
);
debug!(script = %script, "script content");
let start_result = start_standalone_execution(StandaloneStart {
working_dir: &working_dir,
writable_paths: &writable_paths,
readable_paths: &readable_paths,
env_source: &env_source,
executor,
registry: ®istry,
permission_handler,
job_registry: &job_registry,
task_id: &task_id,
execution_id: &execution_id,
carry: carry.as_ref(),
script: &script,
mode,
backend: &backend,
stdin_alerts,
lifetime,
background_startup: &background_startup,
network_audit,
priority,
#[cfg(all(unix, feature = "jobserver"))]
jobserver: &jobserver,
})
.await;
let (pid, output) = match start_result {
Ok(started) => started,
Err(error) => {
background_startup.report_failure(&error).await;
return Err(error);
}
};
let result = save_completed_process_output(CompletedProcessOutput {
job_registry: &job_registry,
pid,
output,
background_output: background,
store_dir: &store_dir,
expect,
resolution,
max_lines,
raw,
})
.await?;
let exit_code = result.exit_code;
debug!(exit_code, "background script completed");
let output_path = stored_path(&result.stdout);
job_registry.complete(pid, exit_code, output_path).await;
if let Some(carry) = &carry {
let ctx = CarryContext {
carried_dir: carried_dir.as_ref(),
alert_tx: &alert_tx,
working_dir: &working_dir,
grants: std::sync::Arc::new(GrantSet {
readable: readable_paths.clone(),
writable: writable_paths.clone(),
}),
};
if let Some(reported) = take_cwd_report(carry).await {
apply_cwd_report(carry, reported, exit_code == 0, &ctx).await;
} else if ctx.carried_dir.is_some() && carry.shell {
alert_directory_reset(carry, DirectoryResetReason::Unreported, &ctx).await;
}
}
Ok(result)
}
#[cfg(all(unix, feature = "jobserver"))]
async fn open_command_fifo(
broker: &JobBroker,
backend: &ExecutionBackend,
) -> Result<crate::jobserver::CommandFifo, TerminalError> {
match backend {
ExecutionBackend::Local(_) => Ok(broker.open_fifo().await?),
ExecutionBackend::Container { .. } | ExecutionBackend::Ssh { .. } => {
Err(TerminalError::Execution(
"jobserver token pools are supported for local executions only".into(),
))
}
}
}
#[allow(clippy::too_many_lines)]
async fn start_standalone_execution<P, E>(
request: StandaloneStart<'_, P, E>,
) -> Result<(u32, std::process::Output), TerminalError>
where
P: PermissionHandler + 'static,
E: Executor + Clone + 'static,
{
#[cfg(all(unix, feature = "jobserver"))]
let job_fifo = match request.jobserver {
Some(broker) => Some(open_command_fifo(broker, request.backend).await?),
None => None,
};
let prepared_tools = match request.backend {
ExecutionBackend::Local(tools) => tools,
ExecutionBackend::Container {
runtime,
tools,
confinement,
} => {
let ipc_commands = request.registry.registered_tool_names();
return execute_container_background(ContainerBackgroundExecution {
executor: request.executor,
env_source: request.env_source,
registry: request.registry,
task_id: request.task_id,
execution_id: request.execution_id,
script: request.script,
mode: request.mode,
container_runtime: runtime,
prepared_tools: tools,
confinement: confinement.as_ref(),
carry: request.carry.and_then(|carry| carry.container.as_ref()),
ipc_commands: &ipc_commands,
job_registry: request.job_registry,
stdin_alerts: request.stdin_alerts,
lifetime: request.lifetime,
background_startup: request.background_startup,
priority: request.priority,
})
.await;
}
ExecutionBackend::Ssh {
target,
runtime,
tools,
} => {
return execute_ssh_background(SshBackgroundExecution {
prepared_tools: tools,
task_id: request.task_id,
execution_id: request.execution_id,
script: request.script,
mode: request.mode,
ssh_target: target,
ssh_runtime: runtime,
job_registry: request.job_registry,
background_startup: request.background_startup,
})
.await;
}
};
let local = LocalBackgroundExecution {
prepared_tools,
working_dir: request.working_dir,
writable_paths: request.writable_paths,
readable_paths: request.readable_paths,
env_source: request.env_source,
executor: request.executor,
registry: request.registry,
task_id: request.task_id,
execution_id: request.execution_id,
carry: request.carry,
script: request.script,
mode: request.mode,
job_registry: request.job_registry,
stdin_alerts: request.stdin_alerts,
lifetime: request.lifetime,
background_startup: request.background_startup,
priority: request.priority,
#[cfg(all(unix, feature = "jobserver"))]
job_fifo,
};
match request.mode {
TerminalMode::Sandboxed => {
execute_audited_sandboxed_background(
local,
PermissionNetworkPolicy {
permission_handler: request.permission_handler,
},
request.network_audit,
)
.await
}
TerminalMode::Unsafe => execute_unsafe_background(local).await,
}
}
async fn execute_audited_sandboxed_background<E, N>(
local: LocalBackgroundExecution<'_, E>,
policy: N,
audit: Option<NetworkAuditLog>,
) -> Result<(u32, std::process::Output), TerminalError>
where
E: Executor + Clone + 'static,
N: NetworkPolicy + 'static,
{
match audit {
Some(log) => execute_sandboxed_background(local, Audited::new(policy, log)).await,
None => execute_sandboxed_background(local, policy).await,
}
}
async fn save_completed_process_output(
request: CompletedProcessOutput<'_>,
) -> Result<CompletedCommand, TerminalError> {
let CompletedProcessOutput {
job_registry,
pid,
output,
background_output,
store_dir,
expect,
resolution,
max_lines,
raw,
} = request;
let stdout = save_completed_stdout(
job_registry,
pid,
&output.stdout,
CompletedStdoutFormat {
background_output,
store_dir,
expect,
resolution,
max_lines,
raw,
},
)
.await?;
let stderr = save_completed_stderr(job_registry, pid, store_dir, &output.stderr).await?;
let exit_code = output.status.code().unwrap_or(-1);
Ok(CompletedCommand {
stdout,
stderr,
exit_code,
interruptions: Vec::new(),
})
}
struct CompletedStdoutFormat<'a> {
background_output: bool,
store_dir: &'a Path,
expect: OutputFormat,
resolution: MediaResolution,
max_lines: usize,
raw: bool,
}
async fn save_completed_stdout(
job_registry: &JobRegistry,
pid: u32,
stdout: &[u8],
format: CompletedStdoutFormat<'_>,
) -> Result<CommandStream, TerminalError> {
let byte_limit = Some(INLINE_OUTPUT_LIMIT);
let data_to_save = if format.background_output {
Cow::Borrowed(stdout)
} else {
compressed_stdout_data(format.store_dir, stdout, format.expect, format.raw).await?
};
match crate::output::save_text_with_line_limit(
format.store_dir,
data_to_save.as_ref(),
format.expect,
format.resolution,
format.max_lines,
byte_limit,
)
.await
{
Ok(entry) => Ok(entry),
Err(err) => {
job_registry.fail(pid, &err.to_string(), None).await;
Err(TerminalError::Io(err))
}
}
}
async fn compressed_stdout_data<'a>(
store_dir: &Path,
stdout: &'a [u8],
expect: OutputFormat,
raw: bool,
) -> Result<Cow<'a, [u8]>, TerminalError> {
let is_text = matches!(expect, OutputFormat::Text | OutputFormat::Auto);
if raw || !is_text || stdout.is_empty() {
return Ok(Cow::Borrowed(stdout));
}
let Ok(text) = std::str::from_utf8(stdout) else {
return Ok(Cow::Borrowed(stdout));
};
let cleaned = crate::output_compress::compress_text(store_dir, text)
.await
.map_err(TerminalError::Io)?;
Ok(cleaned.map_or(Cow::Borrowed(stdout), |cleaned| {
Cow::Owned(cleaned.into_bytes())
}))
}
async fn save_completed_stderr(
job_registry: &JobRegistry,
pid: u32,
store_dir: &Path,
stderr: &[u8],
) -> Result<Option<CommandStream>, TerminalError> {
if stderr.is_empty() {
return Ok(None);
}
match OutputStore::save_to_dir_with_limit(
store_dir,
stderr,
OutputFormat::Text,
MediaResolution::Auto,
Some(INLINE_OUTPUT_LIMIT),
)
.await
{
Ok(entry) => Ok(Some(entry)),
Err(err) => {
job_registry.fail(pid, &err.to_string(), None).await;
Err(TerminalError::Io(err))
}
}
}
#[cfg(unix)]
const GIT_SHIM: &str = include_str!("../templates/git_shim");
#[cfg(unix)]
async fn write_git_shim(tools: &PreparedTools<PathBuf>) -> Result<(), TerminalError> {
use std::os::unix::fs::PermissionsExt as _;
let shim = tools.bin_dir().join("git");
match async_fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&shim)
.await
{
Ok(mut file) => {
file.write_all(GIT_SHIM.as_bytes()).await.map_err(|error| {
TerminalError::Execution(format!("writing {}: {error}", shim.display()))
})?;
file.flush().await.map_err(|error| {
TerminalError::Execution(format!("writing {}: {error}", shim.display()))
})?;
async_fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755))
.await
.map_err(|error| {
TerminalError::Execution(format!("writing {}: {error}", shim.display()))
})
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
Err(error) => Err(TerminalError::Execution(format!(
"writing {}: {error}",
shim.display()
))),
}
}
#[cfg(not(unix))]
async fn write_git_shim(_tools: &PreparedTools<PathBuf>) -> Result<(), TerminalError> {
Ok(())
}
#[cfg(unix)]
fn container_git_preamble(
registry: &ToolRegistry,
mount: Option<&MountRoot>,
) -> Result<String, TerminalError> {
use std::fmt::Write as _;
let mut environment = Vec::new();
let spell = |path: &Path| -> Result<String, TerminalError> {
let mount = mount.ok_or_else(|| {
TerminalError::SandboxSetup(format!(
"a committing worktree {} has no workspace mount to map through",
path.display()
))
})?;
let host_root =
std::fs::canonicalize(&mount.host_root).unwrap_or_else(|_| mount.host_root.clone());
MountRoot::new(host_root, mount.container_root.clone())
.container_path(path)
.map(|path| path.to_string())
.map_err(|source| {
TerminalError::SandboxSetup(format!(
"{} is outside the container workspace mount: {source}",
path.display()
))
})
};
committed_git_environment(registry, &mut environment, spell)?;
if environment.is_empty() {
return Ok(String::new());
}
let mut preamble =
"aither_shim=${TMPDIR:-/tmp}/aither-shim-$$\nmkdir -p \"$aither_shim\"\n".to_string();
preamble.push_str("cat > \"$aither_shim/git\" <<'AITHER_GIT_SHIM'\n");
preamble.push_str(GIT_SHIM);
preamble.push_str(
"AITHER_GIT_SHIM\nchmod +x \"$aither_shim/git\"\nPATH=\"$aither_shim:$PATH\"\nexport PATH\n",
);
for (name, value) in &environment {
writeln!(preamble, "export {name}={}", shell_words::quote(value))
.expect("a string cannot fail a write");
}
Ok(preamble)
}
#[cfg(not(unix))]
fn container_git_preamble(
_registry: &ToolRegistry,
_mount: Option<&MountRoot>,
) -> Result<String, TerminalError> {
Ok(String::new())
}
fn committed_git_environment(
registry: &ToolRegistry,
environment: &mut Vec<(String, String)>,
spell: impl Fn(&Path) -> Result<String, TerminalError>,
) -> Result<(), TerminalError> {
if registry.role() != crate::command::CommandRole::Main {
return Ok(());
}
let committed = registry.committed_worktrees();
if committed.is_empty() {
return Ok(());
}
environment.push((
"AITHER_GIT_WORKTREES_COUNT".to_string(),
committed.len().to_string(),
));
for (index, worktree) in committed.iter().enumerate() {
environment.push((
format!("AITHER_GIT_WORKTREE_PATH_{index}"),
spell(worktree.worktree())?,
));
environment.push((
format!("AITHER_GIT_WORKTREE_GITDIR_{index}"),
spell(worktree.git_dir())?,
));
}
Ok(())
}
fn local_path_grants(
writable: &[PathBuf],
readable: &[PathBuf],
tools: &PreparedTools<PathBuf>,
job_fifo: Option<&Path>,
) -> heel::Result<Vec<Grant>> {
fn resolved(path: &Path) -> heel::Result<ResolvedPath> {
ResolvedPath::new(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()))
}
writable
.iter()
.map(|path| Ok(Grant::new(resolved(path)?, Access::WRITE | Access::EXEC)))
.chain(
readable
.iter()
.map(|path| Ok(Grant::new(resolved(path)?, Access::READ))),
)
.chain(std::iter::once(Ok(Grant::new(
resolved(tools.bin_dir())?,
Access::EXEC,
))))
.chain(
tools
.uv_dir()
.map(|path| Ok(Grant::new(resolved(path)?, Access::WRITE | Access::EXEC))),
)
.chain(
job_fifo
.iter()
.map(|path| Ok(Grant::new(resolved(path)?, Access::WRITE))),
)
.chain(toolchain_grants(resolved))
.collect()
}
fn host_toolchain_homes() -> impl Iterator<Item = (&'static str, PathBuf)> {
let home = std::env::home_dir;
[
std::env::var_os("CARGO_HOME")
.map(PathBuf::from)
.or_else(|| home().map(|home| home.join(".cargo")))
.map(|path| ("CARGO_HOME", path)),
std::env::var_os("RUSTUP_HOME")
.map(PathBuf::from)
.or_else(|| home().map(|home| home.join(".rustup")))
.map(|path| ("RUSTUP_HOME", path)),
]
.into_iter()
.flatten()
.filter(|(_, path)| path.is_dir())
}
fn toolchain_grants(
resolved: impl Fn(&Path) -> heel::Result<ResolvedPath>,
) -> impl Iterator<Item = heel::Result<Grant>> {
host_toolchain_homes()
.map(move |(_, path)| Ok(Grant::new(resolved(&path)?, Access::WRITE | Access::EXEC)))
}
#[cfg(all(unix, feature = "jobserver"))]
fn with_jobserver_environment(
mut environment: Vec<(String, String)>,
fifo: Option<&crate::jobserver::CommandFifo>,
) -> Vec<(String, String)> {
if let Some(fifo) = fifo {
environment.extend(fifo.environment());
}
environment
}
async fn execute_sandboxed_background<E, N>(
context: LocalBackgroundExecution<'_, E>,
policy: N,
) -> Result<(u32, std::process::Output), TerminalError>
where
E: Executor + Clone + 'static,
N: NetworkPolicy + 'static,
{
let mut runtime_environment = local_runtime_environment(&context).await?;
let marker = JobMarker::new();
runtime_environment.push(marker.entry());
#[cfg(all(unix, feature = "jobserver"))]
let runtime_environment =
with_jobserver_environment(runtime_environment, context.job_fifo.as_ref());
#[cfg(all(unix, feature = "jobserver"))]
let job_fifo_path = context
.job_fifo
.as_ref()
.map(crate::jobserver::CommandFifo::path);
#[cfg(not(all(unix, feature = "jobserver")))]
let job_fifo_path: Option<&Path> = None;
let grants = local_path_grants(
context.writable_paths,
context.readable_paths,
context.prepared_tools,
job_fifo_path,
)
.map_err(|error| TerminalError::SandboxSetup(error.to_string()))?;
let config_builder = SandboxConfig::builder()
.network(policy)
.working_dir(
std::fs::canonicalize(context.working_dir)
.unwrap_or_else(|_| context.working_dir.to_path_buf()),
)
.grants(grants)
.security(SecurityConfig::interactive())
.executable_working_dir(true)
.priority(context.priority);
#[cfg(target_os = "linux")]
let config_builder = config_builder.supervised_spawn(true);
let config = match create_ipc_router(context.registry) {
Some(router) => config_builder.ipc(router).build(),
None => config_builder.build(),
};
let sandbox = Sandbox::with_config_and_executor(config, context.executor.clone())
.await
.map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;
let launch = build_terminal_launch(
&context.prepared_tools.shell()?,
context.script,
context.carry.map(|carry| carry.report.as_path()),
)?;
let (program, args) = match &launch {
TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
(program, args)
}
};
let mut command = sandbox.command(program);
if let Some(start) = context.carry.and_then(|carry| carry.start.as_deref()) {
command = command.current_dir(start);
}
let (child, tree) = spawn_local_command(
command,
args,
runtime_environment,
context.stdin_alerts.as_ref(),
&context.lifetime,
context.job_registry,
&context.executor,
&marker,
)
.await?;
let pid = child.id();
context
.job_registry
.register_with_tree(
pid,
context.task_id,
context.execution_id,
context.script,
context.mode,
None,
Some(tree.clone()),
)
.await;
context.background_startup.report_ready().await;
let output = collect_local_process_output(
child,
context.executor,
context.job_registry,
pid,
LocalJob {
tree,
lifetime: context.lifetime,
stdin_alerts: context.stdin_alerts,
},
"missing stdout pipe for sandbox process",
"missing stderr pipe for sandbox process",
)
.await?;
Ok((pid, output))
}
async fn execute_unsafe_background<E: Executor + Clone + 'static>(
context: LocalBackgroundExecution<'_, E>,
) -> Result<(u32, std::process::Output), TerminalError> {
let mut runtime_environment = local_runtime_environment(&context).await?;
let marker = JobMarker::new();
runtime_environment.push(marker.entry());
#[cfg(all(unix, feature = "jobserver"))]
let runtime_environment =
with_jobserver_environment(runtime_environment, context.job_fifo.as_ref());
#[cfg(all(unix, feature = "jobserver"))]
let job_fifo_path = context
.job_fifo
.as_ref()
.map(crate::jobserver::CommandFifo::path);
#[cfg(not(all(unix, feature = "jobserver")))]
let job_fifo_path: Option<&Path> = None;
let grants = local_path_grants(
context.writable_paths,
context.readable_paths,
context.prepared_tools,
job_fifo_path,
)
.map_err(|error| TerminalError::SandboxSetup(error.to_string()))?;
let config_builder = SandboxConfig::builder()
.network(AllowAll)
.working_dir(
std::fs::canonicalize(context.working_dir)
.unwrap_or_else(|_| context.working_dir.to_path_buf()),
)
.grants(grants)
.security(SecurityConfig::permissive())
.executable_working_dir(true)
.priority(context.priority);
#[cfg(target_os = "linux")]
let config_builder = config_builder.supervised_spawn(true);
let config = match create_ipc_gateway_router(context.registry) {
Some(router) => config_builder.ipc(router).build(),
None => config_builder.build(),
};
let sandbox = Sandbox::with_config_and_executor(config, context.executor.clone())
.await
.map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;
let launch = build_terminal_launch(
&context.prepared_tools.shell()?,
context.script,
context.carry.map(|carry| carry.report.as_path()),
)?;
let (program, args) = match &launch {
TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
(program, args)
}
};
let mut command = sandbox.command(program);
if let Some(start) = context.carry.and_then(|carry| carry.start.as_deref()) {
command = command.current_dir(start);
}
let (child, tree) = spawn_local_command(
command,
args,
runtime_environment,
context.stdin_alerts.as_ref(),
&context.lifetime,
context.job_registry,
&context.executor,
&marker,
)
.await?;
let pid = child.id();
context
.job_registry
.register_with_tree(
pid,
context.task_id,
context.execution_id,
context.script,
context.mode,
None,
Some(tree.clone()),
)
.await;
context.background_startup.report_ready().await;
let output = collect_local_process_output(
child,
context.executor,
context.job_registry,
pid,
LocalJob {
tree,
lifetime: context.lifetime,
stdin_alerts: context.stdin_alerts,
},
"missing stdout pipe for unsafe process",
"missing stderr pipe for unsafe process",
)
.await?;
Ok((pid, output))
}
#[derive(Clone)]
enum JobLifetime {
Foreground { alerts: Sender<JobAlert> },
Background,
}
struct StdinAlerts {
tx: Sender<JobAlert>,
task_id: String,
script: String,
}
impl StdinAlerts {
async fn raise(&self) {
debug!(task_id = %self.task_id, "background job is blocked on stdin");
let _ = self
.tx
.send(JobAlert::StdinBlocked(StdinBlockedJob {
task_id: self.task_id.clone(),
script: self.script.clone(),
}))
.await;
}
async fn raise_failure(&self, error: String) {
warn!(task_id = %self.task_id, error = %error, "stdin watch failed");
let _ = self
.tx
.send(JobAlert::StdinProbeFailed(StdinProbeFailedJob {
task_id: self.task_id.clone(),
script: self.script.clone(),
error,
}))
.await;
}
}
const fn local_stdin_config(alerts: Option<&StdinAlerts>) -> StdioConfig {
if alerts.is_some() {
StdioConfig::Piped
} else {
StdioConfig::Null
}
}
struct LocalStdinWatch {
probe: LocalStdinProbe,
feed: FeedCounter,
detector: EpisodeDetector,
alerts: StdinAlerts,
}
impl LocalStdinWatch {
async fn run(mut self) -> std::convert::Infallible {
loop {
async_io::Timer::after(STDIN_WATCH_INTERVAL).await;
let Self {
probe,
feed,
mut detector,
alerts,
} = self;
let fed = feed.count();
let (probe, observed) = blocking::unblock(move || {
let observed = probe.probe();
(probe, observed)
})
.await;
match observed {
Ok(observed) => {
if detector.observe(fed, observed) {
alerts.raise().await;
}
}
Err(error) => {
alerts.raise_failure(error.to_string()).await;
std::future::pending::<()>().await;
}
}
self = Self {
probe,
feed,
detector,
alerts,
};
}
}
}
async fn collect_local_process_output<E: Executor + Clone + 'static>(
mut child: LocalChild,
executor: E,
job_registry: &JobRegistry,
pid: u32,
job: LocalJob,
missing_stdout_message: &'static str,
missing_stderr_message: &'static str,
) -> Result<std::process::Output, TerminalError> {
let LocalJob {
tree,
lifetime,
stdin_alerts,
} = job;
let mut stdin_watch = None;
if let Some(stdin) = child.take_stdin() {
let feed = FeedCounter::default();
if let Some(alerts) = stdin_alerts {
let probe = LocalStdinProbe::new(pid, &stdin)
.map_err(|error| TerminalError::Execution(format!("stdin probe: {error}")))?;
stdin_watch = Some(LocalStdinWatch {
probe,
feed: feed.clone(),
detector: EpisodeDetector::default(),
alerts,
});
}
let input_tx = spawn_terminal_stdin_writer(stdin, feed);
job_registry.attach_terminal_input(pid, input_tx).await;
}
let stdout = child
.take_stdout()
.ok_or_else(|| TerminalError::Execution(missing_stdout_message.into()))?;
let stderr = child
.take_stderr()
.ok_or_else(|| TerminalError::Execution(missing_stderr_message.into()))?;
let (chunk_tx, chunk_rx) = async_channel::unbounded();
spawn_terminal_reader(stdout, chunk_tx.clone(), false);
spawn_terminal_reader(stderr, chunk_tx.clone(), true);
drop(chunk_tx);
executor
.spawn(drain_terminal_chunks(job_registry.clone(), pid, chunk_rx))
.detach();
let exited = match wait_for_local_process_exit(&mut child, stdin_watch).await {
Ok(exited) => exited,
Err(error) => {
tree.finish().await;
job_registry.close_stdout(pid).await;
job_registry.close_stderr(pid).await;
return Err(error);
}
};
let descendants = end_descendants(&tree, &lifetime).await;
tree.finish().await;
let (status, report) = match exited {
Some(status) => (Ok(status), None),
None => match child.wait_reported().await {
Ok((status, report)) => (Ok(status), report),
Err(error) => (Err(TerminalError::Execution(error.to_string())), None),
},
};
let _ = &report;
#[cfg(target_os = "linux")]
if let Some(report) = report {
let killed: Vec<JobProcess> = report
.killed
.into_iter()
.map(|process| JobProcess {
pid: process.pid,
name: process.name,
})
.collect();
if !killed.is_empty() {
info!(
killed = killed.len(),
"the supervisor killed the finished command's descendants"
);
if let JobLifetime::Foreground { alerts } = &lifetime {
let _ = alerts
.send(JobAlert::DescendantsKilled(DescendantsKilled::new(killed)))
.await;
}
}
}
let status = match (descendants, status) {
(Ok(()), Ok(status)) => status,
(Err(error), _) | (Ok(()), Err(error)) => {
job_registry.close_stdout(pid).await;
job_registry.close_stderr(pid).await;
job_registry.fail(pid, &error.to_string(), None).await;
return Err(error);
}
};
wait_for_terminal_stream_close(job_registry, pid).await;
let (stdout, stderr) = job_registry.terminal_output(pid).await.ok_or_else(|| {
TerminalError::Execution(format!("missing terminal output for pid {pid}"))
})?;
let output = std::process::Output {
status,
stdout,
stderr,
};
Ok(output)
}
struct LocalJob {
tree: JobTree,
lifetime: JobLifetime,
stdin_alerts: Option<StdinAlerts>,
}
#[cfg(target_os = "linux")]
const SUPERVISED_REAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
enum LocalChild {
#[cfg_attr(target_os = "linux", allow(dead_code))]
Plain(heel::Child),
#[cfg(target_os = "linux")]
Foreground(heel::supervisor::SupervisedChild<heel::supervisor::Foreground>),
#[cfg(target_os = "linux")]
Background(heel::supervisor::SupervisedChild<heel::supervisor::Background>),
}
impl LocalChild {
fn id(&self) -> u32 {
match self {
Self::Plain(child) => child.id(),
#[cfg(target_os = "linux")]
Self::Foreground(child) => child.id(),
#[cfg(target_os = "linux")]
Self::Background(child) => child.id(),
}
}
fn take_stdin(&mut self) -> Option<std::fs::File> {
match self {
Self::Plain(child) => child.take_stdin(),
#[cfg(target_os = "linux")]
Self::Foreground(child) => child.take_stdin(),
#[cfg(target_os = "linux")]
Self::Background(child) => child.take_stdin(),
}
}
fn take_stdout(&mut self) -> Option<std::fs::File> {
match self {
Self::Plain(child) => child.take_stdout(),
#[cfg(target_os = "linux")]
Self::Foreground(child) => child.take_stdout(),
#[cfg(target_os = "linux")]
Self::Background(child) => child.take_stdout(),
}
}
fn take_stderr(&mut self) -> Option<std::fs::File> {
match self {
Self::Plain(child) => child.take_stderr(),
#[cfg(target_os = "linux")]
Self::Foreground(child) => child.take_stderr(),
#[cfg(target_os = "linux")]
Self::Background(child) => child.take_stderr(),
}
}
#[cfg(target_os = "linux")]
fn tree_control(&self) -> TreeControl {
match self {
Self::Foreground(child) => child.tree_control(),
#[cfg(target_os = "linux")]
Self::Background(child) => child.tree_control(),
Self::Plain(_) => unreachable!("a supervised spawn returns no plain child"),
}
}
async fn wait_reported(
&mut self,
) -> Result<(std::process::ExitStatus, Option<TreeReport>), heel::Error> {
match self {
Self::Plain(child) => Ok((child.wait().await?, None)),
#[cfg(target_os = "linux")]
Self::Foreground(child) => {
let exit = child.wait().await?;
Ok((exit.status, Some(exit.report)))
}
#[cfg(target_os = "linux")]
Self::Background(child) => Ok((child.wait().await?, None)),
}
}
}
#[allow(clippy::too_many_arguments)]
async fn spawn_local_command<E: Executor + Clone + 'static>(
command: heel::Command<'_>,
args: &[String],
environment: Vec<(String, String)>,
stdin_alerts: Option<&StdinAlerts>,
lifetime: &JobLifetime,
job_registry: &JobRegistry,
executor: &E,
marker: &JobMarker,
) -> Result<(LocalChild, JobTree), TerminalError> {
let command = command
.args(args)
.envs(environment)
.stdin(local_stdin_config(stdin_alerts))
.stdout(StdioConfig::Piped)
.stderr(StdioConfig::Piped);
#[cfg(target_os = "linux")]
{
let _ = (job_registry, executor, marker);
let child = match lifetime {
JobLifetime::Foreground { .. } => LocalChild::Foreground(
command
.spawn_supervised(heel::supervisor::Foreground {
reap_timeout: SUPERVISED_REAP_TIMEOUT,
})
.await
.map_err(|error| TerminalError::Execution(error.to_string()))?,
),
JobLifetime::Background => LocalChild::Background(
command
.spawn_supervised(heel::supervisor::Background {
reap_timeout: SUPERVISED_REAP_TIMEOUT,
})
.await
.map_err(|error| TerminalError::Execution(error.to_string()))?,
),
};
let tree = JobTree::supervised(child.tree_control());
Ok((child, tree))
}
#[cfg(not(target_os = "linux"))]
{
let _ = lifetime;
let child = command
.spawn()
.await
.map_err(|error| TerminalError::Execution(error.to_string()))?;
let pid = child.id();
let tree = job_registry.start_process_tree(executor, pid, marker);
Ok((LocalChild::Plain(child), tree))
}
}
async fn end_descendants(tree: &JobTree, lifetime: &JobLifetime) -> Result<(), TerminalError> {
match lifetime {
JobLifetime::Foreground { alerts } => {
let killed = tree
.kill_descendants()
.await
.map_err(|error| TerminalError::Execution(error.to_string()))?;
if !killed.is_empty() {
info!(
killed = killed.len(),
"killed descendants of a finished foreground command"
);
let _ = alerts
.send(JobAlert::DescendantsKilled(DescendantsKilled::new(killed)))
.await;
}
Ok(())
}
JobLifetime::Background => tree
.wait_descendants_exit()
.await
.map_err(|error| TerminalError::Execution(error.to_string())),
}
}
#[cfg_attr(unix, allow(clippy::needless_pass_by_ref_mut))]
async fn wait_for_local_process_exit(
child: &mut LocalChild,
stdin_watch: Option<LocalStdinWatch>,
) -> Result<Option<std::process::ExitStatus>, TerminalError> {
#[cfg(unix)]
let exit = async {
crate::process_tree::wait_for_exit(child.id())
.await
.map(|()| None)
.map_err(|error| TerminalError::Execution(error.to_string()))
};
#[cfg(not(unix))]
let exit = async {
child
.wait_reported()
.await
.map(|(status, _)| Some(status))
.map_err(|error| TerminalError::Execution(error.to_string()))
};
let Some(stdin_watch) = stdin_watch else {
return exit.await;
};
futures_lite::future::or(exit, async { match stdin_watch.run().await {} }).await
}
fn container_exec_script(
registry: &ToolRegistry,
container_runtime: &ContainerShellRuntime,
prepared_tools: &PreparedTools<ContainerPath>,
carry: Option<&ContainerCarry>,
script: &str,
) -> Result<String, TerminalError> {
let preamble = container_git_preamble(registry, container_runtime.workspace_mount())?;
let script = if preamble.is_empty() {
script.to_string()
} else {
format!("{preamble}{script}")
};
let script = prepared_tools.wrap_script(&script)?;
let script = match carry {
Some(carry) => carry_cwd_script(&script, carry.report.as_str())?,
None => script,
};
Ok(prepared_tools.shell_command(&script)?)
}
async fn execute_container_background<E: Executor + Clone + 'static>(
context: ContainerBackgroundExecution<'_, E>,
) -> Result<(u32, std::process::Output), TerminalError> {
let container_runtime = context.container_runtime;
let exec = container_runtime.exec();
let pid = u32::from_le_bytes(
uuid::Uuid::new_v4().as_u128().to_le_bytes()[..4]
.try_into()
.expect("uuid byte slice has four bytes"),
);
let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
let (input_tx, input_rx) = async_channel::unbounded::<Vec<u8>>();
context
.job_registry
.register(
pid,
context.task_id,
context.execution_id,
context.script,
context.mode,
None,
)
.await;
let script = container_exec_script(
context.registry,
context.container_runtime,
context.prepared_tools,
context.carry,
context.script,
)?;
let script = inject_env_exports(script, context.env_source.as_ref())?;
let exec_lifetime = if let JobLifetime::Foreground { .. } = context.lifetime {
drop(input_tx);
ExecLifetime::Foreground
} else {
context
.job_registry
.attach_terminal_input(pid, input_tx)
.await;
let (signal_tx, signal_rx) = async_channel::unbounded::<StdinWatchSignal>();
if let Some(alerts) = context.stdin_alerts {
context
.executor
.clone()
.spawn(async move {
while let Ok(signal) = signal_rx.recv().await {
match signal {
StdinWatchSignal::Blocked => alerts.raise().await,
StdinWatchSignal::Failed(error) => {
alerts.raise_failure(error).await;
}
}
}
})
.detach();
}
ExecLifetime::Background {
stdin_blocked: signal_tx,
}
};
context.job_registry.attach_kill_switch(pid, kill_tx).await;
context.background_startup.report_ready().await;
let ipc_bridge = if context.ipc_commands.is_empty() {
None
} else {
Some(start_container_ipc_bridge(
context.executor,
Arc::clone(context.registry),
container_runtime.workspace_mount().cloned(),
container_runtime.ipc_route().bind(),
)?)
};
let working_dir = context
.carry
.map_or(CONTAINER_EXEC_WORKING_DIR, |carry| carry.start.as_str());
let wrapped_script = wrap_container_script(
&script,
context.ipc_commands,
ipc_bridge.as_ref().map(|bridge| ContainerIpcEndpoint {
host: container_runtime.ipc_route().host(),
port: bridge.port(),
}),
context.priority,
context.prepared_tools.bin_dir(),
working_dir,
context.confinement,
)?;
let execution = exec
.exec_boxed(
container_runtime.container_id(),
&wrapped_script,
working_dir,
kill_rx,
input_rx,
exec_lifetime,
)
.await;
if let Some(bridge) = ipc_bridge {
bridge.stop().await;
}
record_container_exec_outcome(context.job_registry, pid, &context.lifetime, execution).await
}
async fn record_container_exec_outcome(
job_registry: &JobRegistry,
pid: u32,
lifetime: &JobLifetime,
execution: Result<ContainerExecOutcome, String>,
) -> Result<(u32, std::process::Output), TerminalError> {
match execution {
Ok(ContainerExecOutcome::Completed { output, killed }) => {
if let JobLifetime::Foreground { alerts } = lifetime
&& !killed.is_empty()
{
info!(
killed = killed.len(),
"killed processes of a finished foreground container command"
);
let _ = alerts
.send(JobAlert::DescendantsKilled(DescendantsKilled::new(killed)))
.await;
}
if !output.stdout.is_empty() {
job_registry.append_stdout(pid, output.stdout.clone()).await;
}
if !output.stderr.is_empty() {
job_registry.append_stderr(pid, output.stderr.clone()).await;
}
job_registry.close_stdout(pid).await;
job_registry.close_stderr(pid).await;
Ok((pid, output))
}
Ok(ContainerExecOutcome::Killed) => {
job_registry.close_stdout(pid).await;
job_registry.close_stderr(pid).await;
Err(TerminalError::Execution("container job killed".to_string()))
}
Err(err) => {
job_registry.fail(pid, &err, None).await;
job_registry.close_stdout(pid).await;
job_registry.close_stderr(pid).await;
Err(TerminalError::Execution(err))
}
}
}
#[derive(Template)]
#[template(path = "ssh_tool_execution.sh", escape = "none")]
struct SshToolExecutionTemplate<'a> {
binary: Cow<'a, str>,
tools_dir: Cow<'a, str>,
uv_grant: Option<String>,
program: Cow<'a, str>,
arguments: String,
}
async fn execute_ssh_background(
context: SshBackgroundExecution<'_>,
) -> Result<(u32, std::process::Output), TerminalError> {
let target = context.ssh_target;
let remote_cmd = match (context.ssh_runtime, context.mode) {
(SshRuntimeProfile::Heel { binary }, TerminalMode::Sandboxed) => {
let script = context.prepared_tools.wrap_script(context.script)?;
let (program, args) = shell_launch(&context.prepared_tools.shell()?, &script);
let directory = context.prepared_tools.script_bin_dir()?;
let uv_grant = context
.prepared_tools
.uv_dir()
.map(|dir| {
let dir = dir
.to_str()
.ok_or_else(|| ToolRuntimeError::InvalidCache(dir.clone()))?;
Ok::<_, ToolRuntimeError>(
shell_words::quote(&format!("{dir}=rwx")).into_owned(),
)
})
.transpose()?;
SshToolExecutionTemplate {
binary: shell_words::quote(binary),
tools_dir: shell_words::quote(directory),
uv_grant,
program: shell_words::quote(&program),
arguments: shell_words::join(&args),
}
.render()
.map_err(ToolRuntimeError::from)?
}
(SshRuntimeProfile::Heel { .. }, TerminalMode::Unsafe) => {
return Err(TerminalError::InvalidTarget(
"unsafe mode is not supported for ssh backend".into(),
));
}
};
let mut command = std::process::Command::new("ssh");
command
.arg("-o")
.arg("BatchMode=yes")
.arg("-o")
.arg("ConnectTimeout=10")
.arg(target)
.arg(remote_cmd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
let child = async_process::Command::from(command)
.spawn()
.map_err(|e| TerminalError::Execution(e.to_string()))?;
let pid = child.id();
context
.job_registry
.register(
pid,
context.task_id,
context.execution_id,
context.script,
context.mode,
None,
)
.await;
context.background_startup.report_ready().await;
match child.output().await {
Ok(output) => {
if !output.stdout.is_empty() {
context
.job_registry
.append_stdout(pid, output.stdout.clone())
.await;
}
if !output.stderr.is_empty() {
context
.job_registry
.append_stderr(pid, output.stderr.clone())
.await;
}
context.job_registry.close_stdout(pid).await;
context.job_registry.close_stderr(pid).await;
Ok((pid, output))
}
Err(err) => {
context.job_registry.fail(pid, &err.to_string(), None).await;
context.job_registry.close_stdout(pid).await;
context.job_registry.close_stderr(pid).await;
Err(TerminalError::Execution(err.to_string()))
}
}
}
fn inject_env_exports(
script: String,
env_source: Option<&Arc<dyn TerminalEnvSource>>,
) -> Result<String, TerminalError> {
let Some(source) = env_source else {
return Ok(script);
};
let mut rendered = String::new();
for (name, value) in source.env() {
if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
|| name.chars().next().is_some_and(|c| c.is_ascii_digit())
{
return Err(TerminalError::Execution(format!(
"invalid environment variable name for container exec: {name}"
)));
}
rendered.push_str("export ");
rendered.push_str(&name);
rendered.push('=');
rendered.push_str(&shell_escape(&value));
rendered.push('\n');
}
rendered.push_str(&script);
Ok(rendered)
}
fn shell_escape(value: &str) -> String {
let escaped = value.replace('\'', "'\"'\"'");
let mut output = String::with_capacity(escaped.len() + 2);
output.push('\'');
output.push_str(&escaped);
output.push('\'');
output
}
async fn local_runtime_environment<E: Executor>(
context: &LocalBackgroundExecution<'_, E>,
) -> Result<Vec<(String, String)>, TerminalError> {
write_git_shim(context.prepared_tools).await?;
let mut env =
prepare_session_runtime_environment(context.working_dir, context.prepared_tools).await?;
committed_git_environment(context.registry, &mut env, |path| {
Ok(path.display().to_string())
})?;
env.extend(context.env_source.iter().flat_map(|s| s.env()));
Ok(env)
}
async fn prepare_session_runtime_environment(
working_dir: &Path,
tools: &PreparedTools<PathBuf>,
) -> Result<Vec<(String, String)>, TerminalError> {
let session_tmp = working_dir.join("tmp");
let session_cache = working_dir.join(".cache");
let bun_cache = session_cache.join("bun");
let session_config = working_dir.join(".config");
let playwright_cache = session_cache.join("ms-playwright");
let python_path = working_dir.join("skills").join("python");
for directory in [
&session_tmp,
&session_cache,
&bun_cache,
&session_config,
&playwright_cache,
] {
async_fs::create_dir_all(directory).await?;
}
let tmp = path_environment_value("TMPDIR", &session_tmp)?;
let cache = path_environment_value("XDG_CACHE_HOME", &session_cache)?;
let bun = path_environment_value("BUN_INSTALL_CACHE_DIR", &bun_cache)?;
let config = path_environment_value("XDG_CONFIG_HOME", &session_config)?;
let playwright = path_environment_value("PLAYWRIGHT_BROWSERS_PATH", &playwright_cache)?;
let home = path_environment_value("HOME", working_dir)?;
let python = std::env::var_os("PYTHONPATH").map_or_else(
|| Ok::<_, TerminalError>(python_path.clone().into_os_string()),
|existing| {
std::env::join_paths(
std::iter::once(python_path.clone()).chain(std::env::split_paths(&existing)),
)
.map_err(|error| {
TerminalError::Execution(format!("failed to construct session PYTHONPATH: {error}"))
})
},
)?;
let python = python.into_string().map_err(|value| {
TerminalError::Execution(format!(
"session PYTHONPATH is not valid UTF-8: {}",
value.to_string_lossy()
))
})?;
let host_path = std::env::var_os("PATH")
.filter(|path| !path.is_empty())
.unwrap_or_else(|| heel::default_sandbox_path().into());
let path = tools
.prepend_path(Some(host_path.as_os_str()))?
.into_string()
.map_err(|_| ToolRuntimeError::InvalidCache(tools.bin_dir().clone()))?;
let mut env = vec![
("PATH".to_string(), path),
("TMPDIR".to_string(), tmp.clone()),
("TMP".to_string(), tmp.clone()),
("TEMP".to_string(), tmp),
("HOME".to_string(), home),
("XDG_CACHE_HOME".to_string(), cache),
("XDG_CONFIG_HOME".to_string(), config),
("BUN_INSTALL_CACHE_DIR".to_string(), bun),
("PLAYWRIGHT_BROWSERS_PATH".to_string(), playwright),
("PYTHONPATH".to_string(), python),
];
if let Some(uv) = tools.uv_environment() {
env.push((
"UV_CACHE_DIR".to_string(),
path_environment_value("UV_CACHE_DIR", &uv.cache)?,
));
env.push((
"UV_PYTHON_INSTALL_DIR".to_string(),
path_environment_value("UV_PYTHON_INSTALL_DIR", &uv.python_installs)?,
));
env.push((
"UV_PYTHON_PREFERENCE".to_string(),
crate::tool_runtime::UV_PYTHON_PREFERENCE.to_string(),
));
}
for (name, home) in host_toolchain_homes() {
env.push((name.to_string(), path_environment_value(name, &home)?));
}
Ok(env)
}
fn path_environment_value(name: &str, path: &Path) -> Result<String, TerminalError> {
path.to_str().map(str::to_string).ok_or_else(|| {
TerminalError::Execution(format!(
"session environment path for {name} is not valid UTF-8: {}",
path.display()
))
})
}
#[derive(Template)]
#[template(path = "container_ipc_wrapper.sh", escape = "none")]
struct ContainerIpcWrapperTemplate<'a> {
escaped_commands: &'a str,
ipc_host: &'a str,
ipc_port: u16,
script: &'a str,
}
#[derive(Clone, Copy)]
struct ContainerIpcEndpoint<'a> {
host: &'a str,
port: u16,
}
const CONTAINER_EXEC_WORKING_DIR: &str = "/workspace";
#[derive(Clone, Debug, PartialEq, Eq)]
struct ContainerConfinement {
working_dir: ContainerPath,
writable: Vec<ContainerPath>,
}
#[derive(Clone, Copy)]
struct ContainerRunScope<'a> {
tools_dir: &'a ContainerPath,
working_dir: &'a str,
confinement: Option<&'a ContainerConfinement>,
}
#[derive(Template)]
#[template(path = "container_heel_run.sh", escape = "none")]
struct ContainerHeelRunTemplate<'a> {
heel_bin: &'a str,
resolve_heel: bool,
escaped_working_dir: &'a str,
escaped_tools_dir: &'a str,
escaped_grants: Option<Vec<String>>,
escaped_ipc_endpoint: Option<String>,
nice: Option<u8>,
io_priority: Option<&'static str>,
escaped_script: &'a str,
}
fn heel_run_container_command(
script: &str,
priority: ProcessPriority,
heel_bin: &str,
resolve_heel: bool,
ipc_endpoint: Option<ContainerIpcEndpoint<'_>>,
scope: ContainerRunScope<'_>,
) -> Result<String, TerminalError> {
let ContainerRunScope {
tools_dir,
working_dir,
confinement,
} = scope;
let nice = match priority.cpu() {
CpuPriority::Nice(level) => Some(level.get()),
CpuPriority::Normal => None,
};
let io_priority = match priority.io() {
IoPriority::Utility => Some("utility"),
IoPriority::Background => Some("background"),
IoPriority::Normal => None,
};
let working_dir =
confinement.map_or(working_dir, |confinement| confinement.working_dir.as_str());
let escaped_grants = confinement.map(|confinement| {
confinement
.writable
.iter()
.map(|path| shell_escape(&format!("{path}=rw")))
.collect()
});
let escaped_working_dir = shell_escape(working_dir);
let escaped_tools_dir = shell_escape(tools_dir.as_str());
let escaped_ipc_endpoint = ipc_endpoint
.map(|endpoint| format!("tcp://{}:{}", endpoint.host, endpoint.port))
.map(|endpoint| shell_escape(&endpoint));
let escaped_script = shell_escape(script);
ContainerHeelRunTemplate {
heel_bin,
resolve_heel,
escaped_working_dir: &escaped_working_dir,
escaped_tools_dir: &escaped_tools_dir,
escaped_grants,
escaped_ipc_endpoint,
nice,
io_priority,
escaped_script: &escaped_script,
}
.render()
.map_err(|error| {
TerminalError::Execution(format!("failed to render container heel command: {error}"))
})
}
fn prioritized_container_script(
script: &str,
priority: ProcessPriority,
tools_dir: &ContainerPath,
working_dir: &str,
confinement: Option<&ContainerConfinement>,
) -> Result<String, TerminalError> {
if priority.is_normal() && confinement.is_none() {
return Ok(script.to_string());
}
heel_run_container_command(
script,
priority,
"\"$MAY_HEEL_BIN\"",
true,
None,
ContainerRunScope {
tools_dir,
working_dir,
confinement,
},
)
}
fn wrap_container_script(
script: &str,
ipc_commands: &[String],
ipc_endpoint: Option<ContainerIpcEndpoint<'_>>,
priority: ProcessPriority,
tools_dir: &ContainerPath,
working_dir: &str,
confinement: Option<&ContainerConfinement>,
) -> Result<String, TerminalError> {
if ipc_commands.is_empty() {
return prioritized_container_script(script, priority, tools_dir, working_dir, confinement);
}
let endpoint = ipc_endpoint.ok_or_else(|| {
TerminalError::Execution(
"missing container IPC endpoint for wrapped script execution".to_string(),
)
})?;
for name in ipc_commands {
if !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err(TerminalError::Execution(format!(
"invalid ipc command name for container wrapper: {name}"
)));
}
}
let escaped_commands = ipc_commands
.iter()
.map(|name| shell_escape(name))
.collect::<Vec<_>>()
.join(" ");
let script = if priority.is_normal() && confinement.is_none() {
script.to_string()
} else {
heel_run_container_command(
script,
priority,
"\"$MAY_IPC_BIN\"",
false,
Some(endpoint),
ContainerRunScope {
tools_dir,
working_dir,
confinement,
},
)?
};
ContainerIpcWrapperTemplate {
escaped_commands: &escaped_commands,
ipc_host: endpoint.host,
ipc_port: endpoint.port,
script: &script,
}
.render()
.map_err(|error| {
TerminalError::Execution(format!("failed to render container IPC wrapper: {error}"))
})
}
struct ContainerIpcBridge {
shutdown_tx: Sender<()>,
port: u16,
}
impl ContainerIpcBridge {
const fn port(&self) -> u16 {
self.port
}
async fn stop(self) {
tracing::debug!("stopping container IPC bridge");
let _ = self.shutdown_tx.send(()).await;
}
}
fn start_container_ipc_bridge<E: Executor + Clone + 'static>(
executor: E,
registry: Arc<ToolRegistry>,
workspace: Option<MountRoot>,
bind: BridgeAddress,
) -> Result<ContainerIpcBridge, TerminalError> {
let listener = StdTcpListener::bind(SocketAddr::new(bind.ip(), 0)).map_err(|e| {
TerminalError::Execution(format!("failed to bind container IPC tcp port: {e}"))
})?;
let local_addr = listener.local_addr().map_err(|e| {
TerminalError::Execution(format!("failed to resolve container IPC tcp endpoint: {e}"))
})?;
tracing::debug!(
bind = %local_addr,
"starting container IPC bridge"
);
listener.set_nonblocking(true).map_err(|e| {
TerminalError::Execution(format!(
"failed to set IPC tcp listener nonblocking mode: {e}"
))
})?;
let listener = Async::new(listener).map_err(|e| {
TerminalError::Execution(format!(
"failed to register IPC tcp listener with async reactor: {e}"
))
})?;
let (shutdown_tx, shutdown_rx) = async_channel::bounded::<()>(1);
let bridge_executor = executor.clone();
executor
.spawn(async move {
tracing::debug!(bind = %local_addr, "container IPC bridge listening");
if let Err(error) = run_container_ipc_bridge(
listener,
registry,
workspace,
shutdown_rx,
bridge_executor,
)
.await
{
tracing::debug!(error = %error, "container IPC bridge stopped with error");
}
tracing::debug!(bind = %local_addr, "container IPC bridge stopped");
})
.detach();
Ok(ContainerIpcBridge {
shutdown_tx,
port: local_addr.port(),
})
}
enum ContainerIpcBridgeEvent {
Accept(std::io::Result<(Async<StdTcpStream>, std::net::SocketAddr)>),
Shutdown,
}
async fn run_container_ipc_bridge<E: Executor + Clone + 'static>(
listener: Async<StdTcpListener>,
registry: Arc<ToolRegistry>,
workspace: Option<MountRoot>,
shutdown_rx: Receiver<()>,
executor: E,
) -> Result<(), String> {
loop {
let event = futures_lite::future::or(
async { ContainerIpcBridgeEvent::Accept(listener.accept().await) },
async {
let _ = shutdown_rx.recv().await;
ContainerIpcBridgeEvent::Shutdown
},
)
.await;
match event {
ContainerIpcBridgeEvent::Shutdown => break,
ContainerIpcBridgeEvent::Accept(Ok((stream, _addr))) => {
tracing::debug!("container IPC bridge accepted connection");
let registry = registry.clone();
let workspace = workspace.clone();
executor
.spawn(async move {
if let Err(error) =
handle_container_ipc_connection(stream, registry, workspace).await
{
tracing::debug!(error = %error, "container IPC connection failed");
}
})
.detach();
}
ContainerIpcBridgeEvent::Accept(Err(error))
if error.kind() == std::io::ErrorKind::Interrupted => {}
ContainerIpcBridgeEvent::Accept(Err(error)) => {
return Err(format!("container IPC accept failed: {error}"));
}
}
}
Ok(())
}
async fn handle_container_ipc_connection(
mut stream: Async<StdTcpStream>,
registry: Arc<ToolRegistry>,
workspace: Option<MountRoot>,
) -> Result<(), String> {
loop {
let mut length_bytes = [0_u8; 4];
match stream.read_exact(&mut length_bytes).await {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(()),
Err(error) => return Err(format!("failed to read IPC request length: {error}")),
}
let body_length = u32::from_be_bytes(length_bytes) as usize;
if body_length == 0 || body_length > 16 * 1024 * 1024 {
return Err(format!("invalid IPC request length: {body_length}"));
}
let mut body = vec![0_u8; body_length];
stream
.read_exact(&mut body)
.await
.map_err(|e| format!("failed to read IPC request body: {e}"))?;
let request = match heel::ipc::IpcRequest::decode(&body) {
Ok(request) if !request.method.is_empty() => request,
Ok(_) => {
write_container_ipc_error(&mut stream, "empty IPC method name").await?;
continue;
}
Err(error) => {
write_container_ipc_error(&mut stream, &error.to_string()).await?;
continue;
}
};
let cli_args = decode_container_ipc_args(&request.params)?;
let working_dir = workspace.as_ref().and_then(|workspace| {
let container_dir = ContainerPath::new(request.working_dir.to_str()?).ok()?;
workspace.host_path(&container_dir).ok()
});
let envelope = registry
.query_tool_handler_from(&request.method, &cli_args, working_dir.as_deref())
.await;
match crate::command::envelope_to_cli(envelope) {
Ok(rendered) => write_container_ipc_success(&mut stream, &rendered).await?,
Err(error) => {
write_container_ipc_error(&mut stream, &error.to_string()).await?;
}
}
}
}
fn decode_container_ipc_args(params: &[u8]) -> Result<Vec<String>, String> {
let parsed: serde_json::Value =
rmp_serde::from_slice(params).map_err(|e| format!("invalid IPC params: {e}"))?;
let args = parsed
.as_object()
.ok_or_else(|| "container IPC params must be a map".to_string())?;
let args = args
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect::<std::collections::HashMap<_, _>>();
Ok(crate::command::flatten_args_to_cli(&args))
}
async fn write_container_ipc_success(
stream: &mut Async<StdTcpStream>,
rendered: &str,
) -> Result<(), String> {
let payload = rmp_serde::to_vec_named(rendered)
.map_err(|e| format!("failed to encode IPC success payload: {e}"))?;
write_container_ipc_response(stream, true, &payload).await
}
async fn write_container_ipc_error(
stream: &mut Async<StdTcpStream>,
message: &str,
) -> Result<(), String> {
let payload = rmp_serde::to_vec_named(&message.to_string())
.map_err(|e| format!("failed to encode IPC error payload: {e}"))?;
write_container_ipc_response(stream, false, &payload).await
}
async fn write_container_ipc_response(
stream: &mut Async<StdTcpStream>,
success: bool,
payload: &[u8],
) -> Result<(), String> {
let body_length = 1usize
.checked_add(payload.len())
.ok_or_else(|| "IPC response payload length overflow".to_string())?;
let response_length = u32::try_from(body_length)
.map_err(|_| format!("IPC response body too large: {body_length} bytes"))?;
stream
.write_all(&response_length.to_be_bytes())
.await
.map_err(|e| format!("failed to write IPC response length: {e}"))?;
stream
.write_all(&[u8::from(success)])
.await
.map_err(|e| format!("failed to write IPC success flag: {e}"))?;
stream
.write_all(payload)
.await
.map_err(|e| format!("failed to write IPC payload: {e}"))?;
stream
.flush()
.await
.map_err(|e| format!("failed to flush IPC payload: {e}"))
}
fn preview_first_lines(data: &[u8], max_lines: usize) -> (String, bool) {
if data.is_empty() || max_lines == 0 {
return (String::new(), !data.is_empty() && max_lines == 0);
}
let text = String::from_utf8_lossy(data);
let mut preview = String::new();
let mut total_lines = 0usize;
for line in text.lines() {
total_lines += 1;
if total_lines <= max_lines {
if !preview.is_empty() {
preview.push('\n');
}
preview.push_str(line);
}
}
let truncated = total_lines > max_lines;
(preview, truncated)
}
enum TerminalChunk {
Stdout(Vec<u8>),
Stderr(Vec<u8>),
StdoutClosed,
StderrClosed,
}
fn spawn_terminal_reader<R>(
mut reader: R,
tx: async_channel::Sender<TerminalChunk>,
is_stderr: bool,
) where
R: Read + Send + 'static,
{
std::thread::spawn(move || {
let mut buffer = vec![0_u8; 8192];
loop {
match reader.read(&mut buffer) {
Ok(0) => {
let _ = tx.send_blocking(if is_stderr {
TerminalChunk::StderrClosed
} else {
TerminalChunk::StdoutClosed
});
break;
}
Ok(count) => {
let chunk = buffer[..count].to_vec();
let _ = tx.send_blocking(if is_stderr {
TerminalChunk::Stderr(chunk)
} else {
TerminalChunk::Stdout(chunk)
});
}
Err(error) => {
warn!(error = %error, is_stderr, "terminal reader failed");
let _ = tx.send_blocking(if is_stderr {
TerminalChunk::StderrClosed
} else {
TerminalChunk::StdoutClosed
});
break;
}
}
}
});
}
fn spawn_terminal_stdin_writer<W>(
mut writer: W,
feed: FeedCounter,
) -> async_channel::Sender<Vec<u8>>
where
W: Write + Send + 'static,
{
let (tx, rx) = async_channel::unbounded::<Vec<u8>>();
std::thread::spawn(move || {
while let Ok(bytes) = rx.recv_blocking() {
if bytes.is_empty() {
continue;
}
feed.record();
if let Err(error) = writer.write_all(&bytes) {
warn!(error = %error, "terminal stdin write failed");
break;
}
if let Err(error) = writer.flush() {
warn!(error = %error, "terminal stdin flush failed");
break;
}
}
});
tx
}
async fn drain_terminal_chunks(
job_registry: JobRegistry,
pid: u32,
rx: async_channel::Receiver<TerminalChunk>,
) {
while let Ok(chunk) = rx.recv().await {
match chunk {
TerminalChunk::Stdout(bytes) => job_registry.append_stdout(pid, bytes).await,
TerminalChunk::Stderr(bytes) => job_registry.append_stderr(pid, bytes).await,
TerminalChunk::StdoutClosed => job_registry.close_stdout(pid).await,
TerminalChunk::StderrClosed => job_registry.close_stderr(pid).await,
}
}
}
async fn wait_for_terminal_stream_close(job_registry: &JobRegistry, pid: u32) {
while !job_registry.terminal_streams_closed(pid).await {
async_io::Timer::after(Duration::from_millis(10)).await;
}
}
fn create_ipc_router(registry: &Arc<ToolRegistry>) -> Option<IpcRouter> {
let mut router = builtin_router();
let tool_names = registry.registered_tool_names();
tracing::info!(tools = ?tool_names, "Creating IPC router with registered tools");
for name in tool_names {
router = crate::register_tool_command(router, Arc::clone(registry), &name);
}
let has_methods = router.methods().next().is_some();
has_methods.then_some(router)
}
fn create_ipc_gateway_router(registry: &Arc<ToolRegistry>) -> Option<IpcRouter> {
let mut router = crate::register_ipc_gateway_command(IpcRouter::new(), Arc::clone(registry));
let blocked = ["kill", "jobs"];
let tool_names = registry.registered_tool_names();
for name in tool_names {
if blocked.contains(&name.as_str()) {
continue;
}
router = crate::register_tool_command(router, Arc::clone(registry), &name);
}
let has_methods = router.methods().next().is_some();
has_methods.then_some(router)
}
#[derive(Debug, thiserror::Error)]
pub enum TerminalError {
#[error("invalid terminal execution target: {0}")]
InvalidTarget(String),
#[error(transparent)]
Tools(#[from] ToolRuntimeError),
#[error(
"sandbox blocked {mode} execution; approval is required to escalate this terminal command",
mode = .0.description()
)]
PermissionDenied(TerminalMode),
#[error("permission error: {0}")]
Permission(#[from] PermissionError),
#[error("sandbox setup failed: {0}")]
SandboxSetup(String),
#[error("execution failed: {0}")]
Execution(String),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[cfg(all(unix, feature = "jobserver"))]
#[error(transparent)]
Jobserver(#[from] crate::jobserver::JobserverError),
}
impl<P, E, State> std::fmt::Debug for TerminalTool<P, E, State> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TerminalTool")
.field("working_dir", &self.working_dir)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use std::time::Duration;
use super::*;
use crate::ToolRegistryBuilder;
#[cfg(unix)]
use crate::builtin::{InputTerminalArgs, InputTerminalTool};
use crate::output::empty_stream;
#[cfg(unix)]
use heel::DenyAll;
use heel::NiceLevel;
#[cfg(all(unix, feature = "connectivity"))]
mod outage;
#[test]
fn toolchain_grants_cover_existing_dirs_rwx() {
let cargo = tempfile::tempdir().unwrap();
let rustup = tempfile::tempdir().unwrap();
unsafe {
std::env::set_var("CARGO_HOME", cargo.path());
std::env::set_var("RUSTUP_HOME", rustup.path().join("missing"));
}
let grants: Vec<Grant> = toolchain_grants(|path| {
ResolvedPath::new(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()))
})
.map(|grant| grant.expect("grant"))
.collect();
assert_eq!(grants.len(), 1, "only the existing dir is granted");
let access = grants[0].access();
assert!(access.can_write());
assert!(access.can_execute());
unsafe {
std::env::remove_var("CARGO_HOME");
std::env::remove_var("RUSTUP_HOME");
}
}
async fn prepared_test_registry() -> (
crate::tool_runtime::tests::UnlockingTempDir,
ShellSessionRegistry,
) {
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let tools = crate::tool_runtime::tests::bundle()
.prepare_local(cache.path())
.await
.unwrap();
let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
local: true,
container: false,
ssh: false,
})
.with_test_tools(tools);
(cache, registry)
}
#[derive(Default)]
struct CountingSshAuthorizer {
connects: AtomicUsize,
installs: AtomicUsize,
}
impl crate::SshSessionAuthorizer for CountingSshAuthorizer {
fn authorize_connect(
&self,
_target: &str,
) -> impl std::future::Future<Output = Result<bool, crate::SshAuthorizationError>> + Send
{
self.connects.fetch_add(1, AtomicOrdering::SeqCst);
std::future::ready(Ok(false))
}
fn authorize_runtime_install(
&self,
_target: &str,
_details: &str,
) -> impl std::future::Future<Output = Result<bool, crate::SshAuthorizationError>> + Send
{
self.installs.fetch_add(1, AtomicOrdering::SeqCst);
std::future::ready(Ok(false))
}
}
struct UnreachableContainerExec;
impl crate::ContainerExec for UnreachableContainerExec {
fn exec(
&self,
_container_id: &str,
_script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_lifetime: ExecLifetime,
) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
{
std::future::ready(Err("adoption never executes in the container".to_string()))
}
fn exec_streamed(
&self,
_container_id: &str,
_script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_stdout: Sender<Vec<u8>>,
) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
{
std::future::ready(Err("adoption never executes in the container".to_string()))
}
}
fn test_container_runtime(container_id: &str) -> ContainerShellRuntime {
ContainerShellRuntime::new(
container_id,
crate::ContainerIpcRoute::new(
"host.docker.internal",
crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
.expect("loopback binds the bridge"),
),
crate::AnyContainerExec::new(Arc::new(UnreachableContainerExec)),
)
}
fn build_server() -> crate::SshServer {
crate::SshServer {
name: "build".to_string(),
target: "builder@build.internal".to_string(),
}
}
fn local_and_ssh_registry(authorizer: &Arc<CountingSshAuthorizer>) -> ShellSessionRegistry {
ShellSessionRegistry::new(ShellRuntimeAvailability {
local: true,
container: false,
ssh: true,
})
.with_ssh_servers(vec![build_server()])
.expect("ssh server should configure")
.with_ssh_authorizer(Arc::clone(authorizer))
}
async fn fresh_terminal(
dir: &Path,
) -> TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> {
TerminalTool::new_exact(
dir,
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
}
#[cfg(unix)]
async fn script_distribution(directory: &Path) -> ToolDistribution {
let commands = crate::ManagedTool::ALL.map(crate::ManagedTool::command);
let script = format!(
"#!/bin/sh\n\
case \"${{0##*/}}\" in bash)\n\
case \"$1\" in --version) printf '%s\\n' 'GNU bash, version 1.0.0(1)-release (fixture)'; exit 0;; esac\n\
AITHER_FIXTURE_BASH=1.0.0; export AITHER_FIXTURE_BASH; exec /bin/bash \"$@\";; esac\n\
case \"${{0##*/}}\" in python*) printf '%s\\n' 'Python 3.13.1'; exit 0;; esac\n\
case \"${{0##*/}}\" in {}) ;; *) PATH=/usr/bin:/bin exec \"${{0##*/}}\" \"$@\";; esac\n\
case \"$1\" in --list) printf '%s\\n' {}; exit 0;; esac\n\
case \"$1\" in python) PATH=/usr/bin:/bin; for request; do :; done; \
dir=\"$UV_PYTHON_INSTALL_DIR/$request\"; mkdir -p \"$dir/bin\"; \
cp \"$0\" \"$dir/bin/python3.13\"; chmod 755 \"$dir/bin/python3.13\"; \
ln -s python3.13 \"$dir/bin/python3\"; exit 0;; esac\n\
printf '%s\\n' 'tool 1.0.0'\n",
commands.join("|"),
crate::tool_runtime::COREUTILS_ALIASES.join(" ")
)
.into_bytes();
let script = script.as_slice();
let path = directory.join("baseline-tool");
async_fs::write(&path, script).await.unwrap();
let artifacts = crate::tool_runtime::tests::native_tools()
.iter()
.map(|&tool| crate::ToolArtifact {
tool,
version: "1.0.0".into(),
target: crate::ToolTarget::native().unwrap(),
url: crate::ToolArtifactLocation::Download(
url::Url::from_file_path(&path).unwrap(),
),
sha256: hex::encode(crate::tool_runtime::digest(script)),
encoding: crate::ToolArtifactFormat::Executable,
})
.collect::<Vec<_>>();
let python = crate::tool_runtime::tests::python_pins_for(
crate::tool_runtime::digest(script),
"3.13.1",
);
ToolDistribution::from_json(
&serde_json::to_vec(&serde_json::json!({ "artifacts": artifacts, "python": python }))
.unwrap(),
)
.unwrap()
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn terminal_script_runs_in_the_managed_bash() {
let authorizer = Arc::new(CountingSshAuthorizer::default());
let tools_cache = tempfile::tempdir().unwrap();
let tools = crate::tool_runtime::tests::bundle()
.prepare_local(tools_cache.path())
.await
.unwrap();
let prepared = local_and_ssh_registry(&authorizer)
.with_test_tools(tools.clone())
.with_test_ssh(build_server(), tools);
let directory = tempfile::tempdir().unwrap();
let terminal = fresh_terminal(directory.path())
.await
.adopt_prepared_tools(prepared)
.await
.expect("a prepared registry should be adopted");
let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
let terminal = terminal.with_registry(registry);
let result = terminal
.call(
TerminalArgs {
description: "report the shell".to_string(),
script: "[[ -n $BASH_VERSION ]] && echo \"managed=$AITHER_FIXTURE_BASH bash\""
.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: true,
timeout: 30,
background: false,
},
ToolContext::new(),
)
.await
.expect("the script should run");
let stdout = render_terminal_result(&result);
assert!(!stdout.contains("Exit code:"), "{stdout}");
assert!(stdout.contains("managed=1.0.0 bash"), "{stdout}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn adopted_registry_runs_baseline_tools_without_ssh_consent_or_version_probes() {
let authorizer = Arc::new(CountingSshAuthorizer::default());
let artifacts = tempfile::tempdir().unwrap();
let distribution = script_distribution(artifacts.path()).await;
let first = tempfile::tempdir().unwrap();
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let denied = fresh_terminal(first.path())
.await
.with_shell_sessions(local_and_ssh_registry(&authorizer))
.initialize_tools(&distribution, cache.path())
.await;
assert!(
matches!(denied, Err(ToolRuntimeError::SshBootstrap(_))),
"a denied connection must fail preparation"
);
assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
let tools_cache = crate::tool_runtime::tests::unlocking_tempdir();
let tools = crate::tool_runtime::tests::bundle_pinned("2.0.0")
.prepare_local(tools_cache.path())
.await
.unwrap();
assert!(matches!(
tools
.verify_local_versions(executor_core::tokio::TokioGlobal)
.await,
Err(ToolRuntimeError::VersionMismatch(_))
));
let prepared = local_and_ssh_registry(&authorizer)
.with_test_tools(tools.clone())
.with_test_ssh(build_server(), tools);
let second = tempfile::tempdir().unwrap();
let terminal = fresh_terminal(second.path())
.await
.adopt_prepared_tools(prepared)
.await
.expect("a prepared registry should be adopted without probing or consent");
assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
assert_eq!(authorizer.installs.load(AtomicOrdering::SeqCst), 0);
let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
let terminal = terminal.with_registry(registry);
let result = terminal
.call(
TerminalArgs {
description: "run every baseline command".to_string(),
script: "apply_patch --version && rg --version && ast-grep --version && jq --version"
.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: true,
timeout: 30,
background: false,
},
ToolContext::new(),
)
.await
.expect("baseline commands should run");
let stdout = render_terminal_result(&result);
assert!(!stdout.contains("Exit code:"), "{stdout}");
for command in ["apply_patch", "rg", "ast-grep", "jq"] {
assert!(
stdout.contains(&format!("{command} 1.0.0")),
"{command} should run from the adopted tools; stdout: {stdout}"
);
}
assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
assert_eq!(authorizer.installs.load(AtomicOrdering::SeqCst), 0);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_container_home_still_gives_the_host_runnable_tools() {
let container = ShellSessionRegistry::new(ShellRuntimeAvailability {
local: false,
container: true,
ssh: false,
})
.with_container_runtime(test_container_runtime("aither-host-tools"))
.with_test_container_tools(
crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools()),
"aither-host-tools".to_string(),
);
assert!(
matches!(
container.local_tools(),
Err(ToolRuntimeError::NotInitialized(_))
),
"the container's own tools are not host-runnable"
);
let artifacts = tempfile::tempdir().unwrap();
let distribution = script_distribution(artifacts.path()).await;
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let host = container
.host_tools(&distribution, cache.path())
.await
.expect("the distribution prepares the host target");
let runtimes = std::fs::canonicalize(cache.path().join("runtimes")).unwrap();
assert!(host.bin_dir().starts_with(runtimes));
for command in ["apply_patch", "rg", "ast-grep", "jq"] {
let output = std::process::Command::new(host.bin_dir().join(command))
.output()
.expect("the host runs the prepared tool");
assert_eq!(
String::from_utf8_lossy(&output.stdout),
"tool 1.0.0\n",
"{command}"
);
}
}
#[tokio::test]
async fn adoption_rejects_a_registry_changed_after_preparation() {
let authorizer = Arc::new(CountingSshAuthorizer::default());
let tools_cache = crate::tool_runtime::tests::unlocking_tempdir();
let tools = crate::tool_runtime::tests::bundle()
.prepare_local(tools_cache.path())
.await
.unwrap();
let prepared = local_and_ssh_registry(&authorizer)
.with_test_tools(tools.clone())
.with_test_ssh(build_server(), tools.clone());
let staging = crate::SshServer {
name: "staging".to_string(),
target: "deploy@staging.internal".to_string(),
};
let retargeted = crate::SshServer {
target: "builder@build-2.internal".to_string(),
..build_server()
};
let container = ShellSessionRegistry::new(ShellRuntimeAvailability {
local: false,
container: true,
ssh: false,
})
.with_container_runtime(test_container_runtime("aither-tools-a"))
.with_test_container_tools(
crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools()),
"aither-tools-a".to_string(),
);
let dir = tempfile::tempdir().unwrap();
let adopt = |sessions: ShellSessionRegistry| {
let dir = dir.path().to_path_buf();
async move {
fresh_terminal(&dir)
.await
.adopt_prepared_tools(sessions)
.await
}
};
assert!(adopt(prepared.clone()).await.is_ok());
assert!(adopt(container.clone()).await.is_ok());
assert!(matches!(
adopt(local_and_ssh_registry(&authorizer)).await,
Err(ToolRuntimeError::NotInitialized(_))
));
for servers in [vec![build_server(), staging], Vec::new(), vec![retargeted]] {
assert!(matches!(
adopt(prepared.clone().with_ssh_servers(servers).unwrap()).await,
Err(ToolRuntimeError::EnvironmentChanged(
crate::PreparedEnvironment::SshServers
))
));
}
assert!(matches!(
adopt(container.with_container_runtime(test_container_runtime("aither-tools-b"))).await,
Err(ToolRuntimeError::EnvironmentChanged(
crate::PreparedEnvironment::Container
))
));
assert!(matches!(
adopt(prepared.with_availability(ShellRuntimeAvailability {
local: true,
container: true,
ssh: true,
}))
.await,
Err(ToolRuntimeError::EnvironmentChanged(
crate::PreparedEnvironment::HomeBackend
))
));
assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 0);
}
#[tokio::test]
async fn adoption_rechecks_this_terminals_writable_paths() {
let (cache, prepared) = prepared_test_registry().await;
let dir = tempfile::tempdir().unwrap();
let exposed = fresh_terminal(dir.path())
.await
.with_writable_paths([cache.path()])
.adopt_prepared_tools(prepared)
.await;
assert!(matches!(
exposed,
Err(ToolRuntimeError::WritableToolDirectory(_))
));
}
fn render_terminal_result(result: &ToolResult) -> String {
result.render_for_model()
}
fn started_task_id(receiver: &BackgroundTaskReceiver) -> String {
let started = receiver.take_started();
assert_eq!(started.len(), 1, "expected one started-task event");
started[0].task_id.clone()
}
#[cfg(unix)]
#[test]
fn shell_launch_runs_the_managed_bash_without_startup_files() {
let script = "printf '%s\\n' hello | cat";
let (program, args) = shell_launch("/tools/bin/bash", script);
assert_eq!(program, "/tools/bin/bash");
assert_eq!(args[..3], ["--noprofile", "--norc", "-c"]);
assert!(args[3].ends_with(script));
assert_eq!(args.len(), 4);
}
#[test]
fn blocked_commands_always_run_in_the_shell() {
for name in ["grep", "sed", "awk", "find"] {
assert_eq!(direct_command(&format!("{name} x")).unwrap(), None);
}
}
#[test]
fn inject_env_exports_prepends_valid_pairs() {
let source: Option<Arc<dyn TerminalEnvSource>> = Some(Arc::new(vec![
("MY_KEY".to_string(), "it's".to_string()),
("OTHER".to_string(), "x".to_string()),
]));
let rendered = inject_env_exports("echo hi".to_string(), source.as_ref())
.expect("valid env names should render");
assert_eq!(
rendered,
"export MY_KEY='it'\"'\"'s'\nexport OTHER='x'\necho hi"
);
}
#[test]
fn inject_env_exports_rejects_shell_syntax_names() {
let source: Option<Arc<dyn TerminalEnvSource>> =
Some(Arc::new(vec![("BAD;name".to_string(), "x".to_string())]));
assert!(inject_env_exports("echo hi".to_string(), source.as_ref()).is_err());
assert_eq!(
inject_env_exports("echo hi".to_string(), None).expect("no source passes through"),
"echo hi"
);
}
#[tokio::test]
async fn session_runtime_environment_is_prepared_without_wrapping_the_script() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let ready = crate::tool_runtime::tests::bundle()
.prepare_local(cache.path())
.await
.unwrap();
let environment = prepare_session_runtime_environment(dir.path(), &ready)
.await
.expect("session runtime environment should be prepared");
let value = |name: &str| {
environment
.iter()
.find_map(|(key, value)| (key == name).then_some(value.as_str()))
.unwrap_or_else(|| panic!("missing session environment variable {name}"))
};
assert_eq!(value("HOME"), dir.path().to_str().expect("UTF-8 temp path"));
assert_eq!(
value("TMPDIR"),
dir.path().join("tmp").to_str().expect("UTF-8 temp path")
);
assert_eq!(value("TMP"), value("TMPDIR"));
assert_eq!(value("TEMP"), value("TMPDIR"));
assert!(dir.path().join("tmp").is_dir());
assert!(dir.path().join(".cache/bun").is_dir());
assert!(dir.path().join(".cache/ms-playwright").is_dir());
assert!(dir.path().join(".config").is_dir());
if let Some(uv) = ready.uv_dir() {
assert_eq!(
value("UV_CACHE_DIR"),
uv.join("cache").to_str().expect("UTF-8 temp path")
);
assert_eq!(
value("UV_PYTHON_INSTALL_DIR"),
uv.join("python").to_str().expect("UTF-8 temp path")
);
assert_eq!(value("UV_PYTHON_PREFERENCE"), "system");
assert!(!uv.starts_with(dir.path()));
}
}
#[cfg(unix)]
#[tokio::test]
async fn the_shared_uv_directory_is_a_writable_grant_apart_from_the_tools() {
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let ready = crate::tool_runtime::tests::bundle()
.prepare_local(cache.path())
.await
.unwrap();
let uv = ready.uv_dir().expect("the test host has a managed uv");
let grants = local_path_grants(&[], &[], &ready, None).expect("grants build");
let access_of = |path: &Path| {
let path = std::fs::canonicalize(path).unwrap();
grants
.iter()
.find(|grant| grant.resolved_path().as_path() == path)
.map(heel::Grant::access)
};
assert_eq!(access_of(uv), Some(Access::WRITE | Access::EXEC));
assert_eq!(access_of(ready.bin_dir()), Some(Access::EXEC));
assert!(!ready.bin_dir().starts_with(uv) && !uv.starts_with(ready.bin_dir()));
}
#[tokio::test]
async fn session_runtime_environment_sets_toolchain_homes_and_host_path() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let cargo_home = tempfile::tempdir().unwrap();
let rustup_home = tempfile::tempdir().unwrap();
unsafe {
std::env::set_var("CARGO_HOME", cargo_home.path());
std::env::set_var("RUSTUP_HOME", rustup_home.path());
}
let ready = crate::tool_runtime::tests::bundle()
.prepare_local(cache.path())
.await
.unwrap();
let environment = prepare_session_runtime_environment(dir.path(), &ready)
.await
.expect("session runtime environment should be prepared");
unsafe {
std::env::remove_var("CARGO_HOME");
std::env::remove_var("RUSTUP_HOME");
}
let value = |name: &str| {
environment
.iter()
.find_map(|(key, value)| (key == name).then_some(value.as_str()))
.unwrap_or_else(|| panic!("missing session environment variable {name}"))
};
assert_eq!(
value("CARGO_HOME"),
cargo_home.path().to_str().expect("UTF-8 temp path")
);
assert_eq!(
value("RUSTUP_HOME"),
rustup_home.path().to_str().expect("UTF-8 temp path")
);
let host_path = std::env::var("PATH").expect("host PATH");
let path = value("PATH");
assert!(
path.starts_with(ready.bin_dir().to_str().expect("UTF-8 tools dir")),
"the managed tools dir leads PATH: {path}"
);
assert!(
path.contains(&host_path),
"the host PATH follows the tools dir: {path}"
);
}
#[tokio::test]
async fn local_path_grants_make_writable_dirs_executable() {
let workdir = tempfile::tempdir().unwrap();
let readonly = tempfile::tempdir().unwrap();
let cache = crate::tool_runtime::tests::unlocking_tempdir();
let tools = crate::tool_runtime::tests::bundle()
.prepare_local(cache.path())
.await
.unwrap();
let grants = local_path_grants(
&[workdir.path().to_path_buf()],
&[readonly.path().to_path_buf()],
&tools,
None,
)
.expect("grants build");
let canonical = |dir: &tempfile::TempDir| std::fs::canonicalize(dir.path()).unwrap();
let access_of = |dir: &tempfile::TempDir| {
grants
.iter()
.find(|grant| grant.resolved_path().as_path() == canonical(dir))
.map(heel::Grant::access)
};
let access = access_of(&workdir).expect("workdir grant");
assert!(access.can_write());
assert!(access.can_execute(), "a writable directory also executes");
let access = access_of(&readonly).expect("readonly grant");
assert!(!access.can_write());
assert!(!access.can_execute());
}
fn output_text(output: &CommandStream) -> Option<&str> {
match output {
CommandStream::Inline { text } => Some(text.as_str()),
CommandStream::Stored { preview, .. } => Some(preview.as_str()),
CommandStream::Image { .. } => None,
}
}
async fn wait_for_completed_task(
receiver: &BackgroundTaskReceiver,
task_id: &str,
) -> CompletedTask {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(task) = receiver
.take_completed()
.into_iter()
.find(|task| task.task_id == task_id)
{
return task;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.expect("background task should complete after terminal input")
}
#[derive(Default)]
struct TestPermissionHandler {
mode_checks: AtomicUsize,
domain_checks: AtomicUsize,
allow_domain: bool,
}
impl PermissionHandler for TestPermissionHandler {
fn check(
&self,
mode: TerminalMode,
_script: &str,
) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send {
self.mode_checks.fetch_add(1, AtomicOrdering::Relaxed);
std::future::ready(Ok(match mode {
TerminalMode::Sandboxed => true,
TerminalMode::Unsafe => false,
}))
}
fn check_domain(
&self,
_domain: &str,
_port: u16,
) -> impl std::future::Future<Output = bool> + Send {
self.domain_checks.fetch_add(1, AtomicOrdering::Relaxed);
std::future::ready(self.allow_domain)
}
}
#[tokio::test]
async fn test_terminal_args_defaults() {
let args: TerminalArgs = serde_json::from_str(
r#"{"description":"print a greeting","script":"echo hello","timeout":30}"#,
)
.unwrap();
assert_eq!(args.expect, OutputFormat::Text);
assert_eq!(args.resolution, MediaResolution::Auto);
assert_eq!(args.mode, TerminalExecutionMode::Default);
assert!(!args.background);
}
#[test]
fn background_preview_keeps_leading_indentation() {
assert_eq!(
background_preview(" col a col b\nrow\n\n"),
" col a col b\nrow"
);
assert_eq!(background_preview(" \n\t\n"), "");
}
fn inline(text: &str) -> CommandStream {
CommandStream::Inline {
text: text.to_string(),
}
}
fn completed(
stdout: CommandStream,
stderr: Option<CommandStream>,
exit_code: i32,
) -> CommandResult {
CompletedCommand {
stdout,
stderr,
exit_code,
interruptions: Vec::new(),
}
.into()
}
#[test]
fn completed_command_exit_zero_is_the_bare_output() {
let result = completed(inline("done"), None, 0)
.into_tool_result()
.unwrap();
assert_eq!(result.render_for_model(), "done\n");
assert_eq!(
result.command().map(|command| &command.outcome),
Some(&CommandOutcome::Exited { code: 0 })
);
}
#[test]
fn completed_command_without_any_output_says_so() {
assert_eq!(
completed(empty_stream(), None, 0).render_for_model(),
"(no output)\n"
);
}
#[test]
fn completed_command_non_zero_exit_with_stderr() {
let result = completed(inline("partial"), Some(inline("oops")), 2);
assert_eq!(
result.render_for_model(),
"partial\nstderr:\noops\nExit code: 2.\n"
);
}
#[test]
fn completed_command_stderr_only_has_no_contradicting_placeholder() {
assert_eq!(
completed(empty_stream(), Some(inline("oops")), 2).render_for_model(),
"stderr:\noops\nExit code: 2.\n"
);
}
#[tokio::test]
async fn test_terminal_args_parsing() {
let args: TerminalArgs = serde_json::from_str(
r#"{"description":"sleep in background","script":"sleep 5","timeout":30,"background":true}"#,
)
.unwrap();
assert_eq!(args.timeout, 30);
assert_eq!(args.script, "sleep 5");
assert!(args.background);
let missing_timeout = serde_json::from_str::<TerminalArgs>(
r#"{"description":"sleep in background","script":"sleep 5"}"#,
)
.unwrap_err();
assert!(missing_timeout.to_string().contains("timeout"));
let missing_description =
serde_json::from_str::<TerminalArgs>(r#"{"script":"echo hello","timeout":1}"#)
.unwrap_err();
assert!(missing_description.to_string().contains("description"));
}
#[test]
fn terminal_args_schema_lists_required_fields() {
let schema = serde_json::to_value(schemars::schema_for!(TerminalArgs)).unwrap();
let properties = schema["properties"].as_object().expect("object schema");
for field in [
"description",
"script",
"timeout",
"max_lines",
"background",
] {
assert!(
properties.contains_key(field),
"{field} missing from schema {schema}"
);
}
let required = schema["required"].as_array().expect("required list");
for field in ["description", "script", "timeout"] {
assert!(
required.iter().any(|name| name == field),
"{field} not required in {schema}"
);
}
assert!(
!required.iter().any(|name| name == "background"),
"background must not be required in {schema}"
);
}
fn container_tools_dir() -> ContainerPath {
crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools())
.bin_dir()
.clone()
}
#[test]
fn wrap_container_script_refreshes_command_hash_table() {
let wrapped = wrap_container_script(
"websearch \"gold price\"",
&[String::from("websearch")],
Some(ContainerIpcEndpoint {
host: "host.docker.internal",
port: 9000,
}),
ProcessPriority::default(),
&container_tools_dir(),
CONTAINER_EXEC_WORKING_DIR,
None,
)
.expect("wrap script");
assert!(wrapped.contains("hash -r;"));
assert!(wrapped.contains("MAY_IPC_DIR"));
assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
}
#[test]
fn wrap_container_script_preserves_user_script_semantics() {
let script = "echo '$5,040' && subagent art_direction --prompt-file tmp/prompt.md";
let wrapped = wrap_container_script(
script,
&[String::from("subagent")],
Some(ContainerIpcEndpoint {
host: "host.docker.internal",
port: 9000,
}),
ProcessPriority::default(),
&container_tools_dir(),
CONTAINER_EXEC_WORKING_DIR,
None,
)
.expect("wrap script");
assert!(wrapped.contains(script));
assert!(!wrapped.contains("set -euo pipefail"));
}
#[test]
fn wrap_container_script_rejects_invalid_ipc_command_names() {
let error = wrap_container_script(
"echo ok",
&[String::from("bad name")],
Some(ContainerIpcEndpoint {
host: "host.docker.internal",
port: 9000,
}),
ProcessPriority::default(),
&container_tools_dir(),
CONTAINER_EXEC_WORKING_DIR,
None,
)
.expect_err("invalid command name must fail");
assert!(
error
.to_string()
.contains("invalid ipc command name for container wrapper")
);
}
#[test]
fn wrap_container_script_renders_expected_endpoint() {
let wrapped = wrap_container_script(
"environment --query deployment",
&[String::from("environment"), String::from("session")],
Some(ContainerIpcEndpoint {
host: "host.containers.internal",
port: 43123,
}),
ProcessPriority::default(),
&container_tools_dir(),
CONTAINER_EXEC_WORKING_DIR,
None,
)
.expect("wrap script");
assert!(wrapped.contains("tcp://host.containers.internal:43123"));
assert!(wrapped.contains("for cmd in 'environment' 'session'; do"));
}
#[tokio::test]
async fn ensure_mode_allowed_requires_unsafe_approval() {
let handler = TestPermissionHandler {
allow_domain: true,
..Default::default()
};
let err = ensure_mode_allowed(&handler, TerminalMode::Unsafe, "rm -rf /tmp/demo")
.await
.expect_err("unsafe mode should be denied");
assert!(matches!(
err,
TerminalError::PermissionDenied(TerminalMode::Unsafe)
));
assert_eq!(handler.mode_checks.load(AtomicOrdering::Relaxed), 1);
}
#[tokio::test]
async fn permission_network_policy_delegates_domain_checks() {
let handler = Arc::new(TestPermissionHandler {
allow_domain: true,
..Default::default()
});
let policy = PermissionNetworkPolicy {
permission_handler: handler.clone(),
};
let request = DomainRequest::new("example.com", 443);
assert!(policy.check(&request).await);
assert_eq!(handler.domain_checks.load(AtomicOrdering::Relaxed), 1);
}
struct ReviewingHandler {
review: Review,
waits: AtomicUsize,
checks: AtomicUsize,
}
impl ReviewingHandler {
fn new(review: Review) -> Self {
Self {
review,
waits: AtomicUsize::new(0),
checks: AtomicUsize::new(0),
}
}
}
impl PermissionHandler for ReviewingHandler {
fn review(
&self,
_request: &PermissionRequest<'_>,
) -> impl std::future::Future<Output = Review> + Send {
std::future::ready(self.review.clone())
}
fn check(
&self,
_mode: TerminalMode,
_script: &str,
) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send {
self.checks.fetch_add(1, AtomicOrdering::Relaxed);
std::future::ready(Ok(true))
}
fn will_wait_for_approval(
&self,
_mode: TerminalMode,
_script: &str,
) -> impl std::future::Future<Output = bool> + Send {
self.waits.fetch_add(1, AtomicOrdering::Relaxed);
std::future::ready(true)
}
}
async fn permission_stages(
review: Review,
) -> (Result<(), String>, Vec<PermissionEventStage>, [usize; 2]) {
let dir = tempfile::tempdir().unwrap();
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool = TerminalTool::new_exact(
dir.path(),
ReviewingHandler::new(review),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let tool = tool.with_registry(registry);
let result = tool
.ensure_permission_allowed(TerminalMode::Unsafe, "make install")
.await
.map_err(|error| error.to_string());
let stages = tool
.permission_receiver()
.take_pending()
.into_iter()
.map(|event| event.stage)
.collect();
let handler = &tool.permission_handler;
(
result,
stages,
[
handler.waits.load(AtomicOrdering::Relaxed),
handler.checks.load(AtomicOrdering::Relaxed),
],
)
}
#[tokio::test]
async fn a_request_a_reviewer_approves_emits_no_permission_event() {
let (result, stages, [waits, checks]) = permission_stages(Review::Approved).await;
result.expect("approved");
assert_eq!(stages, Vec::<PermissionEventStage>::new());
assert_eq!([waits, checks], [0, 0], "the route is not asked");
}
#[tokio::test]
async fn a_request_a_reviewer_denies_emits_no_permission_event() {
let (result, stages, [waits, checks]) =
permission_stages(Review::Denied("not today".into())).await;
assert!(result.unwrap_err().contains("not today"));
assert_eq!(stages, Vec::<PermissionEventStage>::new());
assert_eq!([waits, checks], [0, 0], "the route is not asked");
}
#[tokio::test]
async fn a_request_every_reviewer_passes_waits_then_resolves() {
let (result, stages, [waits, checks]) = permission_stages(Review::Passed).await;
result.expect("the route allows");
assert_eq!(
stages,
[
PermissionEventStage::Waiting,
PermissionEventStage::Resolved
]
);
assert_eq!([waits, checks], [1, 1]);
}
#[tokio::test]
async fn permission_network_policy_reviews_a_domain_before_asking() {
struct Domains(Review, AtomicUsize);
impl PermissionHandler for Domains {
fn check(
&self,
_mode: TerminalMode,
_script: &str,
) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send
{
std::future::ready(Ok(true))
}
fn review(
&self,
request: &PermissionRequest<'_>,
) -> impl std::future::Future<Output = Review> + Send {
assert_eq!(
*request,
PermissionRequest::Domain {
domain: "example.com",
port: 443
}
);
std::future::ready(self.0.clone())
}
fn domain_needs_approval(
&self,
_domain: &str,
_port: u16,
) -> impl std::future::Future<Output = bool> + Send {
std::future::ready(true)
}
fn check_domain(
&self,
_domain: &str,
_port: u16,
) -> impl std::future::Future<Output = bool> + Send {
self.1.fetch_add(1, AtomicOrdering::Relaxed);
std::future::ready(true)
}
}
let request = DomainRequest::new("example.com", 443);
for (review, allowed, asked) in [
(Review::Approved, true, 0),
(Review::Denied("no".into()), false, 0),
(Review::Passed, true, 1),
] {
let handler = Arc::new(Domains(review, AtomicUsize::new(0)));
let policy = PermissionNetworkPolicy {
permission_handler: handler.clone(),
};
assert_eq!(policy.check(&request).await, allowed);
assert_eq!(handler.1.load(AtomicOrdering::Relaxed), asked);
}
}
#[test]
fn sandboxed_execution_mode_deserializes() {
let mode: TerminalExecutionMode =
serde_json::from_str("\"sandboxed\"").expect("sandboxed mode must deserialize");
assert_eq!(mode, TerminalExecutionMode::Sandboxed);
}
#[tokio::test]
async fn uninitialized_terminal_rejects_execution_and_catalog() {
let dir = tempfile::tempdir().unwrap();
let tool = TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.unwrap();
assert!(matches!(
tool.prepared_tools_context(),
Err(ToolRuntimeError::NotInitialized(_))
));
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let tool = tool.with_registry(registry);
assert!(matches!(
tool.resolve_default_target(),
Err(TerminalError::Tools(ToolRuntimeError::NotInitialized(_)))
));
}
#[tokio::test]
async fn child_terminal_exposes_controls_with_isolated_jobs() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
tool.job_registry()
.register(
424_242,
"parent-task",
"parent-execution",
"sleep 30",
TerminalMode::Sandboxed,
None,
)
.await;
let parent_registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let parent = tool.with_registry(parent_registry);
let child = parent
.subagent_without_grant()
.await
.expect("an empty grant is always given");
assert_eq!(
parent.prepared_tools_context().unwrap(),
child.prepared_tools_context().unwrap()
);
assert!(child.job_registry().list().await.is_empty());
for name in ["terminal_kill", "terminal_input", "terminal_read"] {
assert!(child.registry().is_tool_configured(name));
}
let args = vec!["--task-id".to_string(), "parent-task".to_string()];
let parent_output = serde_json::to_value(
parent
.registry()
.query_tool_handler("terminal_read", &args)
.await,
)
.unwrap();
let child_output = serde_json::to_value(
child
.registry()
.query_tool_handler("terminal_read", &args)
.await,
)
.unwrap();
assert!(parent_output.to_string().contains("running"));
assert!(!child_output.to_string().contains("running"));
let names = child
.to_dyn()
.into_entries()
.into_iter()
.map(|entry| entry.definition.name().to_string())
.collect::<Vec<_>>();
assert_eq!(names, vec!["terminal"]);
}
struct PickTool {
dir: PathBuf,
}
#[derive(serde::Deserialize, schemars::JsonSchema)]
struct PickArgs {
entry: String,
}
impl aither_core::llm::Tool for PickTool {
fn name(&self) -> std::borrow::Cow<'static, str> {
"pick".into()
}
type Arguments = PickArgs;
type Res = aither_core::llm::ToolResult;
fn call(
&self,
args: Self::Arguments,
_cx: aither_core::llm::ToolContext,
) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
std::future::ready(Ok(aither_core::llm::ToolResult::text(args.entry)))
}
}
impl crate::CommandUsage for PickTool {
async fn usage(&self) -> String {
use futures_lite::StreamExt as _;
let mut entries: Vec<String> = async_fs::read_dir(&self.dir)
.await
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.starts_with("entry-"))
.collect()
.await;
entries.sort();
format!("entries: {}", entries.join(", "))
}
}
#[tokio::test]
async fn a_main_exclusive_command_names_its_choices_and_does_not_exist_for_a_subagent() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let mut builder = ToolRegistryBuilder::new();
builder.main_exclusive(|main| {
main.configure_terminal_bound_usage_tool("pick", |binding| PickTool {
dir: binding.working_dir().to_path_buf(),
});
});
let parent = tool.with_registry(Arc::new(builder.build(dir.path().join("outputs"))));
std::fs::write(dir.path().join("entry-b"), "").unwrap();
std::fs::write(dir.path().join("entry-a"), "").unwrap();
let bare = parent.registry().query_tool_handler("pick", &[]).await;
assert!(!bare.ok);
assert_eq!(
bare.error.as_deref(),
Some(
"missing required argument: entry\n\nentries: entry-a, entry-b\n\nRun `pick --help` for usage information."
)
);
let picked = parent
.registry()
.query_tool_handler("pick", &["entry-a".to_string()])
.await;
assert_eq!(picked.payload.unwrap().render_for_cli(), "entry-a");
let child = parent
.subagent_without_grant()
.await
.expect("an empty grant is always given");
let registry = child.registry();
assert!(!registry.is_tool_configured("pick"));
assert!(!registry.registered_tool_names().contains(&"pick".into()));
assert!(registry.tool_help("pick").is_none());
let refused = registry
.query_tool_handler("pick", &["entry-a".to_string()])
.await;
assert_eq!(
refused.error.as_deref(),
Some("unknown command 'pick'. Run 'help' to see available commands.")
);
assert!(!child.to_dyn().has_command("pick"));
}
async fn query_control(
registry: &ToolRegistry,
name: &str,
args: &[&str],
) -> serde_json::Value {
let args = args.iter().map(ToString::to_string).collect::<Vec<_>>();
serde_json::to_value(registry.query_tool_handler(name, &args).await)
.expect("command envelope should serialize")
}
#[cfg(unix)]
fn background_args(description: &str, script: &str) -> TerminalArgs {
TerminalArgs {
description: description.to_string(),
script: script.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: true,
}
}
#[cfg(unix)]
async fn parent_and_child_terminals() -> (
(
tempfile::TempDir,
crate::tool_runtime::tests::UnlockingTempDir,
),
ConfiguredTestTool,
ConfiguredTestTool,
) {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_shell_runtime_availability(crate::ShellRuntimeAvailability {
local: true,
container: false,
ssh: false,
});
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let parent = tool.with_registry(registry);
let child = parent
.subagent_without_grant()
.await
.expect("an empty grant is always given");
((dir, cache), parent, child)
}
#[cfg(unix)]
#[tokio::test]
async fn configured_child_terminal_input_and_read_address_child_jobs() {
let (_dirs, _parent, child) = parent_and_child_terminals().await;
let receiver = child.background_receiver();
let result = child
.run_background(background_args(
"echo one stdin line",
"read line; printf 'got %s\\n' \"$line\"",
))
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"{rendered}"
);
let echo_id = started_task_id(&receiver);
let input = query_control(
child.registry(),
"terminal_input",
&["--task-id", &echo_id, "--input", "ping"],
)
.await;
assert_eq!(input["ok"], true, "child terminal_input failed: {input}");
wait_for_completed_task(&receiver, &echo_id).await;
let echoed =
query_control(child.registry(), "terminal_read", &["--task-id", &echo_id]).await;
assert_eq!(echoed["ok"], true, "child terminal_read failed: {echoed}");
assert!(echoed.to_string().contains("got ping"), "{echoed}");
}
#[cfg(unix)]
#[tokio::test]
async fn configured_child_terminal_kill_addresses_child_jobs() {
let (_dirs, parent, child) = parent_and_child_terminals().await;
let result = child
.run_background(background_args("sleep", "sleep 30"))
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"{rendered}"
);
let task_id = started_task_id(&child.background_receiver());
let running =
query_control(child.registry(), "terminal_read", &["--task-id", &task_id]).await;
assert_eq!(running["ok"], true, "child terminal_read failed: {running}");
assert!(running.to_string().contains("running"), "{running}");
let parent_read =
query_control(parent.registry(), "terminal_read", &["--task-id", &task_id]).await;
assert_eq!(parent_read["ok"], false, "{parent_read}");
assert!(
parent_read["error"]
.as_str()
.is_some_and(|error| error.contains("unknown task_id")),
"parent terminal_read must not see the child's task: {parent_read}"
);
let parent_kill =
query_control(parent.registry(), "terminal_kill", &["--task-id", &task_id]).await;
assert!(
parent_kill
.to_string()
.contains("No running background task"),
"parent terminal_kill must not reach the child's task: {parent_kill}"
);
let kill = query_control(child.registry(), "terminal_kill", &["--task-id", &task_id]).await;
assert!(
kill.to_string().contains("terminated"),
"child terminal_kill should stop its task: {kill}"
);
let stopped =
query_control(child.registry(), "terminal_read", &["--task-id", &task_id]).await;
assert!(
stopped.to_string().contains("was killed"),
"child task should be reported killed: {stopped}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn sandboxed_command_output_executes_pwd() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let config = SandboxConfig::builder()
.network(DenyAll)
.working_dir(
std::fs::canonicalize(dir.path()).unwrap_or_else(|_| dir.path().to_path_buf()),
)
.security(SecurityConfig::interactive())
.build();
let sandbox = Sandbox::with_config_and_executor(config, executor_core::tokio::TokioGlobal)
.await
.expect("sandbox should initialize");
let output = sandbox
.command("/bin/pwd")
.output()
.await
.expect("sandbox command output should succeed");
eprintln!("PWD OUTPUT STATUS: {:?}", output.status);
eprintln!(
"PWD OUTPUT STDOUT: {:?}",
String::from_utf8_lossy(&output.stdout)
);
assert_eq!(output.status.code(), Some(0));
}
#[cfg(unix)]
#[tokio::test]
async fn sandboxed_terminal_executes_pwd() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let job_registry = tool.job_registry();
let (startup_tx, _startup_rx) = async_channel::bounded(1);
let result = execute_script_standalone(StandaloneExecution {
working_dir: tool.working_dir().clone(),
writable_paths: Vec::new(),
readable_paths: Vec::new(),
env_source: None,
executor: executor_core::tokio::TokioGlobal,
registry,
permission_handler: Arc::new(TestPermissionHandler::default()),
job_registry,
task_id: "task-test".to_string(),
execution_id: "exec-test".to_string(),
background: false,
carry: None,
carried_dir: None,
alert_tx: async_channel::unbounded().0,
script: "/bin/pwd".to_string(),
mode: TerminalMode::Sandboxed,
backend: ExecutionBackend::Local(tool.shell_sessions.local_tools().unwrap().clone()),
stdin_alerts: None,
lifetime: JobLifetime::Foreground {
alerts: async_channel::unbounded().0,
},
background_startup: BackgroundStartup::new(startup_tx),
network_audit: None,
priority: ProcessPriority::default(),
#[cfg(all(unix, feature = "jobserver"))]
jobserver: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
store_dir: tool.outputs_dir(),
max_lines: 50,
raw: false,
})
.await;
match result {
Ok(ok) => {
eprintln!("PWD RESULT: {ok:?}");
assert_eq!(ok.exit_code, 0, "unexpected terminal result: {ok:?}");
}
Err(error) => panic!("sandboxed pwd should succeed, got error: {error}"),
}
}
#[cfg(unix)]
#[tokio::test]
async fn failed_command_reports_nonzero_exit_code() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_shell_runtime_availability(crate::ShellRuntimeAvailability {
local: true,
container: false,
ssh: false,
});
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let tool = tool.with_registry(registry);
let result = tool
.call(
TerminalArgs {
description: "exit with non-zero status".to_string(),
script: "exit 42".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: false,
},
ToolContext::new(),
)
.await
.expect("terminal call should not be promoted to transport error on non-zero exit");
assert!(
!result.is_error(),
"non-zero exit must not produce ToolResult::Error, got: {result:?}"
);
assert_eq!(
render_terminal_result(&result),
"(no output)\nExit code: 42.\n"
);
assert_eq!(
result.command().map(|command| &command.outcome),
Some(&CommandOutcome::Exited { code: 42 })
);
}
#[cfg(unix)]
#[tokio::test]
async fn background_terminal_accepts_terminal_input() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_shell_runtime_availability(crate::ShellRuntimeAvailability {
local: true,
container: false,
ssh: false,
});
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let tool = tool.with_registry(registry);
let background_receiver = tool.background_receiver();
let input_tool = InputTerminalTool::new(tool.job_registry());
let result = tool
.run_background(TerminalArgs {
description: "wait for terminal input and echo it back".to_string(),
script: "printf 'name? '; read name; printf 'hello %s\\n' \"$name\"".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: true,
})
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"{rendered}"
);
let task_id = started_task_id(&tool.background_receiver());
input_tool
.call(
InputTerminalArgs {
task_id: task_id.clone(),
input: "lexo".to_string(),
append_newline: true,
},
ToolContext::new(),
)
.await
.expect("terminal_input should succeed");
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
let terminal_result = completed
.result
.expect("background task should complete successfully after stdin input");
let stdout =
output_text(&terminal_result.stdout).expect("completed task should include stdout");
assert!(
stdout.contains("hello lexo"),
"stdin input should reach the terminal process, got: {stdout}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn killing_background_terminal_kills_descendant_processes() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_shell_runtime_availability(crate::ShellRuntimeAvailability {
local: true,
container: false,
ssh: false,
});
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
let tool = tool.with_registry(registry);
let child_pid_path = dir.path().join("child.pid");
let result = tool
.run_background(TerminalArgs {
description: "start a descendant process".to_string(),
script: "sleep 30 & echo $! > child.pid; wait".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: true,
})
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"{rendered}"
);
let mut child_pid = None;
for _ in 0..100 {
let parsed = match async_fs::read_to_string(&child_pid_path).await {
Ok(value) => value.trim().parse::<i32>().ok(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => panic!("failed to read child pid: {error}"),
};
if let Some(pid) = parsed {
child_pid = Some(pid);
break;
}
async_io::Timer::after(std::time::Duration::from_millis(20)).await;
}
let child_pid = child_pid.expect("descendant pid should be written before timeout");
assert_eq!(tool.job_registry().kill_running().await, 1);
for _ in 0..100 {
let exists = unsafe { libc::kill(child_pid, 0) } == 0;
if !exists {
return;
}
async_io::Timer::after(std::time::Duration::from_millis(20)).await;
}
panic!("descendant process {child_pid} survived terminal cancellation");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn foreground_command_blocked_on_stdin_promotes_at_the_window() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(1),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let background_receiver = tool.background_receiver();
let result = tool
.call(
terminal_args("read all of stdin", "cat"),
ToolContext::new(),
)
.await
.expect("terminal call should succeed");
let command = result.command().expect("terminal returns a command result");
let CommandOutcome::Running { task_id, .. } = &command.outcome else {
panic!(
"cat blocked on stdin must promote to a task, got {:?}",
command.outcome
);
};
assert_eq!(started_task_id(&background_receiver), *task_id);
assert!(
tool.job_registry().kill_by_task_id(task_id).await,
"the promoted task must still be running"
);
}
#[cfg(unix)]
fn terminal_args(description: &str, script: &str) -> TerminalArgs {
TerminalArgs {
description: description.to_string(),
script: script.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: false,
}
}
#[cfg(unix)]
async fn start_background_job(
tool: &TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
script: &str,
) -> String {
let result = tool
.run_background(TerminalArgs {
background: true,
..terminal_args("background job", script)
})
.await
.expect("terminal should start the job");
match result.command().map(|command| &command.outcome) {
Some(CommandOutcome::Running { task_id, .. }) => task_id.clone(),
other => panic!("background job needs a task id, got {other:?}"),
}
}
#[cfg(unix)]
async fn alerts_within(receiver: &BackgroundTaskReceiver, window: Duration) -> Vec<JobAlert> {
let deadline = std::time::Instant::now() + window;
let mut alerts = Vec::new();
while std::time::Instant::now() < deadline {
alerts.extend(receiver.take_job_alerts());
tokio::time::sleep(Duration::from_millis(50)).await;
}
alerts
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn container_foreground_command_gets_a_live_stdin_pipe() {
struct ForegroundStdinPipeExec;
impl crate::ContainerExec for ForegroundStdinPipeExec {
async fn exec(
&self,
_container_id: &str,
_script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
stdin_rx: Receiver<Vec<u8>>,
_lifetime: ExecLifetime,
) -> Result<ContainerExecOutcome, String> {
let eof = futures_lite::future::or(async { Some(stdin_rx.recv().await) }, async {
async_io::Timer::after(Duration::from_secs(5)).await;
None
})
.await
.expect("a foreground exec's stdin must be EOF at once, not left open");
assert!(eof.is_err(), "a foreground exec's stdin must carry no data");
Ok(ContainerExecOutcome::Completed {
output: std::process::Output {
status: std::os::unix::process::ExitStatusExt::from_raw(0),
stdout: Vec::new(),
stderr: Vec::new(),
},
killed: Vec::new(),
})
}
fn exec_streamed(
&self,
_container_id: &str,
_script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_stdout: Sender<Vec<u8>>,
) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
{
std::future::ready(Err("a foreground command does not stream".to_string()))
}
}
let dir = tempfile::tempdir().expect("temp dir should be created");
let registry = Arc::new(ToolRegistryBuilder::new().build(dir.path()));
let (job_registry, job_registry_service) = job_registry_channel();
tokio::spawn(async move { job_registry_service.serve().await });
let container_tools =
crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools());
let runtime = ContainerShellRuntime::new(
"aither-test-foreground-stdin",
crate::ContainerIpcRoute::new(
"host.docker.internal",
crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
.expect("loopback binds the bridge"),
),
crate::AnyContainerExec::new(Arc::new(ForegroundStdinPipeExec)),
);
let (startup_tx, _startup_rx) = async_channel::bounded(1);
let (alert_tx, _alert_rx) = async_channel::unbounded();
let (_pid, output) = execute_container_background(ContainerBackgroundExecution {
executor: executor_core::tokio::TokioGlobal,
env_source: &None,
registry: ®istry,
task_id: "task-test",
execution_id: "exec-test",
script: "cat",
mode: TerminalMode::Sandboxed,
container_runtime: &runtime,
prepared_tools: &container_tools,
ipc_commands: &[],
job_registry: &job_registry,
stdin_alerts: Some(StdinAlerts {
tx: alert_tx.clone(),
task_id: "task-test".to_string(),
script: "cat".to_string(),
}),
lifetime: JobLifetime::Foreground { alerts: alert_tx },
background_startup: &BackgroundStartup::new(startup_tx),
priority: ProcessPriority::default(),
confinement: None,
carry: None,
})
.await
.expect("a foreground container exec should complete");
assert_eq!(output.status.code(), Some(0));
}
#[cfg(unix)]
async fn stdin_reader_alerts_once_and_resumes_when_fed(reader: &str) {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(60),
Duration::from_secs(600),
)
.await;
let background_receiver = tool.background_receiver();
let task_id = start_background_job(&tool, reader).await;
let alerts = alerts_within(&background_receiver, Duration::from_secs(8)).await;
assert!(
matches!(
alerts.as_slice(),
[JobAlert::StdinBlocked(job)] if job.task_id == task_id
),
"a blocked reader must yield exactly one stdin alert: {alerts:?}"
);
InputTerminalTool::new(tool.job_registry())
.call(
InputTerminalArgs {
task_id: task_id.clone(),
input: "lexo".to_string(),
append_newline: true,
},
ToolContext::new(),
)
.await
.expect("terminal_input should succeed");
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
let terminal_result = completed.result.expect("the fed job should complete");
let stdout =
output_text(&terminal_result.stdout).expect("completed task should include stdout");
assert!(stdout.contains("hello lexo"), "got: {stdout}");
assert!(
background_receiver.take_job_alerts().is_empty(),
"a fed job that finished must not alert again"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_job_blocked_on_stdin_yields_one_alert() {
stdin_reader_alerts_once_and_resumes_when_fed("read name; printf 'hello %s\\n' \"$name\"")
.await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_grandchild_blocked_on_stdin_yields_one_alert() {
stdin_reader_alerts_once_and_resumes_when_fed(
"( ( read name; printf 'hello %s\\n' \"$name\" ); true )",
)
.await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_job_that_never_reads_stdin_yields_no_alert() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(60),
Duration::from_secs(600),
)
.await;
let background_receiver = tool.background_receiver();
let task_id = start_background_job(&tool, "sleep 3; echo finished").await;
let alerts = alerts_within(&background_receiver, Duration::from_secs(4)).await;
assert!(alerts.is_empty(), "no alert expected: {alerts:?}");
wait_for_completed_task(&background_receiver, &task_id).await;
}
#[cfg(unix)]
fn expected_lowered_nice(level: u8) -> i64 {
let current = unsafe { libc::getpriority(libc::PRIO_PROCESS as _, 0) };
i64::from(current + i32::from(level)).min(19)
}
#[cfg(unix)]
fn test_nice_priority() -> ProcessPriority {
ProcessPriority::new(
CpuPriority::Nice(NiceLevel::new(10).expect("nice level 10 is in range")),
IoPriority::Normal,
)
}
#[cfg(unix)]
async fn configured_test_terminal(
dir: &Path,
foreground_wait: Duration,
timeout_cap: Duration,
alert_after: Duration,
) -> (
crate::tool_runtime::tests::UnlockingTempDir,
TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
) {
let (cache, shell_sessions) = prepared_test_registry().await;
let tool = TerminalTool::new_exact(
dir,
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_foreground_wait(foreground_wait)
.with_timeout_cap(timeout_cap)
.with_long_job_alert_after(alert_after);
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
(cache, tool.with_registry(registry))
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn foreground_command_still_running_at_the_window_promotes_and_times_out_with_descendants()
{
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(1),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let background_receiver = tool.background_receiver();
let child_pid_path = dir.path().join("child.pid");
let result = tool
.call(
TerminalArgs {
description: "start a descendant process".to_string(),
script: "sleep 30 & echo $! > child.pid; wait".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 3,
background: false,
},
ToolContext::new(),
)
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"the still-running command must promote: {rendered}"
);
let task_id = started_task_id(&background_receiver);
let child_pid = async_fs::read_to_string(&child_pid_path)
.await
.expect("descendant pid file should exist")
.trim()
.parse::<i32>()
.expect("descendant pid should parse");
for _ in 0..500 {
if unsafe { libc::kill(child_pid, 0) } != 0 {
break;
}
async_io::Timer::after(std::time::Duration::from_millis(20)).await;
}
assert!(
unsafe { libc::kill(child_pid, 0) } != 0,
"descendant process {child_pid} survived the timeout kill"
);
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
let info = tool
.job_registry()
.get_by_task_id(&task_id)
.await
.expect("the finished job stays in the registry");
assert_eq!(
info.status,
JobStatus::Killed,
"the promoted job should be killed at its timeout: {completed:?}"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_longer_foreground_window_holds_until_restored() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(1),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let wait = tool.foreground_wait();
let run = || async {
let result = tool
.call(
TerminalArgs {
description: "outlast the normal window".to_string(),
script: "sleep 2 & wait; echo finished".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: false,
},
ToolContext::new(),
)
.await
.expect("terminal call should succeed");
render_terminal_result(&result)
};
wait.extend(Duration::from_secs(20));
let during = run().await;
assert!(
during.contains("finished") && !during.contains("Started in background"),
"the longer window keeps the command in the foreground: {during}"
);
wait.restore();
let after = run().await;
assert!(
after.contains("Started in background as task '"),
"the normal window applies again: {after}"
);
}
#[cfg(unix)]
#[derive(Clone, Copy, Debug)]
enum Descendant {
Plain,
Setsid,
}
#[cfg(unix)]
const SETSID_HELPER: &str = "setsid-helper";
#[cfg(unix)]
fn exec_dir<P, E>(tool: &TerminalTool<P, E, Configured>) -> PathBuf {
tool.shell_sessions
.local_tools()
.expect("the terminal has local tools")
.bin_dir()
.clone()
}
#[cfg(unix)]
fn build_setsid_helper(dir: &Path) -> PathBuf {
let source = dir.join("setsid_helper.rs");
std::fs::write(
&source,
"extern \"C\" { fn setsid() -> i32; }\n\
fn main() {\n\
let seconds: u64 = std::env::args().nth(1).expect(\"seconds\").parse().expect(\"seconds\");\n\
// SAFETY: `setsid` takes no arguments.\n\
if unsafe { setsid() } < 0 { std::process::exit(1); }\n\
std::thread::sleep(std::time::Duration::from_secs(seconds));\n\
}\n",
)
.expect("helper source should be written");
let binary = dir.join(SETSID_HELPER);
let status = std::process::Command::new("rustc")
.arg("--edition=2021")
.arg("-o")
.arg(&binary)
.arg(&source)
.status()
.expect("rustc should run");
assert!(status.success(), "the setsid helper should compile");
binary
}
#[cfg(unix)]
impl Descendant {
const fn process_name(self) -> &'static str {
match self {
Self::Plain => "sleep",
Self::Setsid => SETSID_HELPER,
}
}
fn script(self, exec_dir: &Path, seconds: u32) -> String {
match self {
Self::Plain => format!(
"sleep {seconds} > /dev/null 2>&1 & echo $! > child.pid; until kill -0 \"$(cat child.pid)\" 2>/dev/null; do :; done"
),
Self::Setsid => format!(
"'{}' {seconds} > /dev/null 2>&1 & echo $! > child.pid; until kill -0 \"$(cat child.pid)\" 2>/dev/null; do :; done",
build_setsid_helper(exec_dir).display()
),
}
}
}
#[cfg(unix)]
async fn recorded_child_pid(dir: &Path) -> i32 {
for _ in 0..250 {
if let Ok(text) = async_fs::read_to_string(dir.join("child.pid")).await
&& let Ok(pid) = text.trim().parse()
{
return pid;
}
async_io::Timer::after(Duration::from_millis(20)).await;
}
panic!("the descendant never recorded its pid");
}
#[cfg(unix)]
fn process_exists(pid: i32) -> bool {
unsafe { libc::kill(pid, 0) == 0 }
}
#[cfg(unix)]
async fn assert_process_gone(pid: i32, context: &str) {
for _ in 0..250 {
if !process_exists(pid) {
return;
}
async_io::Timer::after(Duration::from_millis(20)).await;
}
panic!("process {pid} survived: {context}");
}
#[cfg(unix)]
async fn foreground_command_leaving_a_descendant_kills_it_and_alerts_once(
descendant: Descendant,
) {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let receiver = tool.background_receiver();
let result = tool
.call(
terminal_args(
"leave a descendant",
&descendant.script(&exec_dir(&tool), 300),
),
ToolContext::new(),
)
.await
.expect("terminal call should succeed");
let command = result.command().expect("terminal returns a command result");
assert!(
matches!(command.outcome, CommandOutcome::Exited { code: 0 }),
"{:?}",
command.outcome
);
let child = recorded_child_pid(tool.working_dir()).await;
assert_process_gone(
child,
&format!("{descendant:?} descendant of a foreground command"),
)
.await;
let alerts = receiver.take_job_alerts();
match alerts.as_slice() {
[JobAlert::DescendantsKilled(killed)] => {
assert_eq!(killed.omitted, 0);
assert_eq!(
killed
.processes
.iter()
.map(|process| i64::from(process.pid))
.collect::<Vec<_>>(),
[i64::from(child)]
);
assert_eq!(killed.processes[0].name, descendant.process_name());
}
other => panic!("expected one descendants-killed alert, got {other:?}"),
}
assert!(
receiver.take_job_alerts().is_empty(),
"the same event must not alert twice"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn foreground_command_leaving_a_descendant_kills_it_and_alerts_once_plain() {
foreground_command_leaving_a_descendant_kills_it_and_alerts_once(Descendant::Plain).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn foreground_command_leaving_a_setsid_descendant_kills_it_and_alerts_once() {
foreground_command_leaving_a_descendant_kills_it_and_alerts_once(Descendant::Setsid).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn foreground_background_jobs_joined_by_wait_run_without_an_alert() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let receiver = tool.background_receiver();
let result = tool
.call(
terminal_args(
"run two jobs and join them",
"(sleep 1; echo one > one.txt) & (sleep 1; echo two > two.txt) & wait",
),
ToolContext::new(),
)
.await
.expect("terminal call should succeed");
let command = result.command().expect("terminal returns a command result");
assert!(
matches!(command.outcome, CommandOutcome::Exited { code: 0 }),
"{:?}",
command.outcome
);
for name in ["one.txt", "two.txt"] {
assert!(
tool.working_dir().join(name).exists(),
"{name} must be written before the command returns"
);
}
assert!(
receiver.take_job_alerts().is_empty(),
"a joined job is no survivor"
);
}
#[cfg(unix)]
async fn background_job_whose_shell_exited(
tool: &TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
script: &str,
timeout: u64,
) -> (String, i32) {
let result = tool
.run_background(TerminalArgs {
background: true,
timeout,
..terminal_args("background job", script)
})
.await
.expect("terminal should start the background job");
let task_id = match result.command().map(|command| &command.outcome) {
Some(CommandOutcome::Running { task_id, .. }) => task_id.clone(),
other => panic!("background job needs a task id, got {other:?}"),
};
let child = recorded_child_pid(tool.working_dir()).await;
tokio::time::sleep(Duration::from_millis(1200)).await;
assert!(
process_exists(child),
"the descendant must outlive the shell"
);
(task_id, child)
}
#[cfg(unix)]
async fn background_job_stays_running_until_its_descendant_exits(descendant: Descendant) {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let (task_id, child) =
background_job_whose_shell_exited(&tool, &descendant.script(&exec_dir(&tool), 3), 30)
.await;
let info = tool
.job_registry()
.get_by_task_id(&task_id)
.await
.expect("the job is registered");
assert_eq!(
info.status,
JobStatus::Running,
"the job runs while its descendant does"
);
assert!(
tool.job_registry()
.format_running_jobs()
.await
.contains(&task_id),
"the running-jobs context lists the job"
);
assert_process_gone(child, "the descendant's own exit").await;
let receiver = tool.background_receiver();
let completed = wait_for_completed_task(&receiver, &task_id).await;
assert!(completed.result.is_ok(), "{completed:?}");
let info = tool
.job_registry()
.get_by_task_id(&task_id)
.await
.expect("the finished job stays in the registry");
assert_eq!(info.status, JobStatus::Completed { exit_code: 0 });
assert!(
tool.job_registry().format_running_jobs().await.is_empty(),
"a finished job is no longer listed"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_job_stays_running_until_its_plain_descendant_exits() {
background_job_stays_running_until_its_descendant_exits(Descendant::Plain).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_job_stays_running_until_its_setsid_descendant_exits() {
background_job_stays_running_until_its_descendant_exits(Descendant::Setsid).await;
}
#[cfg(unix)]
async fn killing_a_background_job_kills_its_descendant(descendant: Descendant) {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let (task_id, child) =
background_job_whose_shell_exited(&tool, &descendant.script(&exec_dir(&tool), 300), 30)
.await;
assert!(
tool.job_registry().kill_by_task_id(&task_id).await,
"a job with a live descendant is killable"
);
assert_process_gone(
child,
&format!("terminal_kill of a job with a {descendant:?} descendant"),
)
.await;
let info = tool
.job_registry()
.get_by_task_id(&task_id)
.await
.expect("the killed job stays in the registry");
assert_eq!(info.status, JobStatus::Killed);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn killing_a_background_job_kills_its_plain_descendant() {
killing_a_background_job_kills_its_descendant(Descendant::Plain).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn killing_a_background_job_kills_its_setsid_descendant() {
killing_a_background_job_kills_its_descendant(Descendant::Setsid).await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_timeout_kills_a_descendant_that_outlived_the_shell() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let (task_id, child) = background_job_whose_shell_exited(
&tool,
&Descendant::Setsid.script(&exec_dir(&tool), 300),
2,
)
.await;
assert_process_gone(child, "the timeout of a job whose shell exited").await;
let receiver = tool.background_receiver();
wait_for_completed_task(&receiver, &task_id).await;
let info = tool
.job_registry()
.get_by_task_id(&task_id)
.await
.expect("the finished job stays in the registry");
assert_eq!(info.status, JobStatus::Killed);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagents_cleanup_kills_a_descendant_that_outlived_the_shell() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let (_task_id, child) = background_job_whose_shell_exited(
&tool,
&Descendant::Plain.script(&exec_dir(&tool), 300),
30,
)
.await;
assert_eq!(tool.job_registry().kill_running().await, 1);
assert_process_gone(child, "the cleanup of a subagent's job").await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn terminal_rejects_timeout_above_cap_and_kills_at_timeout() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(2),
Duration::from_secs(60),
)
.await;
let background_receiver = tool.background_receiver();
let args = |timeout: u64| TerminalArgs {
description: "sleep in the background".to_string(),
script: "sleep 30".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout,
background: true,
};
assert!(
tool.call(args(3), ToolContext::new()).await.is_err(),
"a timeout above the cap must be rejected"
);
let result = tool
.call(args(1), ToolContext::new())
.await
.expect("a timeout within the cap should start the job");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"{rendered}"
);
let task_id = started_task_id(&background_receiver);
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
let info = tool
.job_registry()
.get_by_task_id(&task_id)
.await
.expect("the finished job stays in the registry");
assert_eq!(
info.status,
JobStatus::Killed,
"the job should have been killed at its timeout: {completed:?}"
);
}
#[test]
fn the_timeout_notice_states_both_utc_times() {
let kill = TimeoutKill {
timeout: Duration::from_secs(90),
started: "2026-11-04T12:00:00Z".parse().expect("valid timestamp"),
killed: "2026-11-04T12:01:31Z".parse().expect("valid timestamp"),
};
assert_eq!(
kill.notice(),
"Its 90s timeout bound passed; it started at 2026-11-04 12:00:00 UTC \
and was killed at 2026-11-04 12:01:31 UTC."
);
}
#[cfg(unix)]
fn spinning_args(timeout: u64, background: bool) -> TerminalArgs {
TerminalArgs {
description: "spin past the timeout".to_string(),
script: if background {
"while :; do sleep 0.1; done"
} else {
"nice -n 19 sh -c 'while :; do :; done'"
}
.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout,
background,
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_background_job_killed_at_its_timeout_reports_its_utc_times() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let background_receiver = tool.background_receiver();
tool.call(spinning_args(1, true), ToolContext::new())
.await
.expect("the job starts");
let task_id = started_task_id(&background_receiver);
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
assert!(completed.killed);
let kill = completed
.timeout_kill
.expect("a job killed at its timeout carries the times");
assert_eq!(kill.timeout, Duration::from_secs(1));
assert!(
kill.killed.duration_since(kill.started).as_secs_f64() >= 1.0,
"{kill:?}"
);
assert!(
kill.killed.duration_since(kill.started).as_secs() < 10,
"{kill:?}"
);
assert!(
kill.notice()
.starts_with("Its 1s timeout bound passed; it started at ")
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_job_killed_by_hand_is_not_a_timeout_kill() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let background_receiver = tool.background_receiver();
tool.call(spinning_args(30, true), ToolContext::new())
.await
.expect("the job starts");
let task_id = started_task_id(&background_receiver);
assert!(tool.job_registry().kill_by_task_id(&task_id).await);
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
assert!(completed.killed);
assert_eq!(completed.timeout_kill, None);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_foreground_command_killed_at_its_timeout_reports_its_utc_times() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(20),
Duration::from_secs(60),
Duration::from_secs(60),
)
.await;
let before = jiff::Timestamp::now();
let result = tool
.call(spinning_args(1, false), ToolContext::new())
.await
.expect("a killed command still returns a result");
let rendered = render_terminal_result(&result);
let utc = |marker: &str| {
let text = rendered
.split(marker)
.nth(1)
.and_then(|rest| rest.split(" UTC").next())
.unwrap_or_else(|| panic!("{marker:?} missing: {rendered}"));
jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M:%S", text)
.expect("a UTC date and time")
.to_zoned(jiff::tz::TimeZone::UTC)
.expect("UTC has no gaps")
.timestamp()
};
assert!(
rendered.contains("Its 1s timeout bound passed; it started at "),
"{rendered}"
);
let started = utc("it started at ");
let killed = utc("was killed at ");
assert!(started.as_second() >= before.as_second(), "{rendered}");
assert!(killed.as_second() - started.as_second() >= 1, "{rendered}");
assert!(killed.as_second() - started.as_second() < 10, "{rendered}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn background_job_past_the_alert_threshold_yields_one_alert() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(60),
Duration::from_millis(300),
)
.await;
let background_receiver = tool.background_receiver();
let _result = tool
.run_background(TerminalArgs {
description: "sleep in the background".to_string(),
script: "sleep 30".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: true,
})
.await
.expect("terminal should start the job");
let task_id = started_task_id(&background_receiver);
let deadline = std::time::Instant::now() + Duration::from_secs(10);
let alerts = loop {
let alerts = background_receiver.take_job_alerts();
if !alerts.is_empty() {
break alerts;
}
assert!(
std::time::Instant::now() < deadline,
"long-running alert did not fire"
);
tokio::time::sleep(Duration::from_millis(50)).await;
};
assert_eq!(alerts.len(), 1);
assert!(
matches!(&alerts[0], JobAlert::LongRunning(job) if job.task_id == task_id),
"expected the long-running alert for the job: {alerts:?}"
);
assert!(
background_receiver.take_job_alerts().is_empty(),
"the same job must not alert twice"
);
assert!(
tool.job_registry().kill_by_task_id(&task_id).await,
"test cleanup should kill the job"
);
}
#[cfg(unix)]
async fn prioritized_terminal_tool(
dir: &Path,
priority: ProcessPriority,
) -> (
crate::tool_runtime::tests::UnlockingTempDir,
TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
) {
let (cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir,
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_process_priority(priority);
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
(cache, tool.with_registry(registry))
}
#[cfg(unix)]
fn pid_probe_args() -> TerminalArgs {
TerminalArgs {
description: "report the process pid and wait".to_string(),
script: concat!(
"printf '%s\\n' $$ > \"$PWD/pid\"; ",
"while [ ! -f \"$PWD/go\" ]; do :; done"
)
.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: false,
}
}
#[cfg(unix)]
async fn probe_pid(dir: &Path) -> u32 {
let path = dir.join("pid");
for _ in 0..150 {
if let Ok(text) = std::fs::read_to_string(&path)
&& let Ok(pid) = text.trim().parse()
{
return pid;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
panic!("the sandboxed probe did not write {}", path.display());
}
#[cfg(unix)]
fn probe_nice(pid: u32) -> i64 {
i64::from(unsafe { libc::getpriority(libc::PRIO_PROCESS as _, pid as _) })
}
#[cfg(unix)]
fn release_probe(dir: &Path) {
std::fs::File::create(dir.join("go")).expect("create the probe marker");
}
#[cfg(unix)]
#[tokio::test]
async fn foreground_command_runs_with_configured_nice() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_tools_cache, tool) =
prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
let call = tool.call(pid_probe_args(), ToolContext::new());
let probe = async {
let pid = probe_pid(dir.path()).await;
assert_eq!(
probe_nice(pid),
expected_lowered_nice(10),
"foreground command should run at the configured nice level"
);
release_probe(dir.path());
};
let (result, ()) = futures::join!(call, probe);
let rendered = render_terminal_result(&result.expect("terminal call should succeed"));
assert!(!rendered.contains("Exit code:"), "{rendered}");
}
#[cfg(unix)]
#[tokio::test]
async fn persistent_session_runs_with_configured_nice() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_tools_cache, tool) =
prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
let background_receiver = tool.background_receiver();
let input_tool = InputTerminalTool::new(tool.job_registry());
let result = tool
.run_background(TerminalArgs {
description: "start a persistent shell".to_string(),
script: "printf '%s\\n' $$ > \"$PWD/pid\"; exec sh".to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: true,
})
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
assert!(
rendered.contains("Started in background as task '"),
"{rendered}"
);
let task_id = started_task_id(&tool.background_receiver());
let pid = probe_pid(dir.path()).await;
assert_eq!(
probe_nice(pid),
expected_lowered_nice(10),
"persistent session should run at the configured nice level"
);
input_tool
.call(
InputTerminalArgs {
task_id: task_id.clone(),
input: "exit".to_string(),
append_newline: true,
},
ToolContext::new(),
)
.await
.expect("terminal_input should succeed");
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
let terminal_result = completed
.result
.expect("persistent shell should exit cleanly after input");
assert_eq!(terminal_result.exit_code, 0);
}
#[cfg(unix)]
#[tokio::test]
async fn background_job_runs_with_configured_nice() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_tools_cache, tool) =
prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
let background_receiver = tool.background_receiver();
let result = tool
.run_background(TerminalArgs {
background: true,
..pid_probe_args()
})
.await
.expect("terminal call should succeed");
let rendered = render_terminal_result(&result);
let mut started = tool.background_receiver().take_started();
assert_eq!(started.len(), 1, "expected one started-task event");
let started = started.remove(0);
let task_id = started.task_id;
assert_eq!(
rendered,
format!(
"Started in background as task '{task_id}'; output is being written to {} (absolute path: {}).\n",
started.output_file.url, started.output_file.path
)
);
assert_eq!(
result.command().map(|command| &command.outcome),
Some(&CommandOutcome::Running {
task_id: task_id.clone(),
output: started.output_file.clone(),
})
);
let pid = probe_pid(dir.path()).await;
assert_eq!(
probe_nice(pid),
expected_lowered_nice(10),
"background job should run at the configured nice level"
);
release_probe(dir.path());
let completed = wait_for_completed_task(&background_receiver, &task_id).await;
let terminal_result = completed
.result
.expect("background job should complete successfully");
assert_eq!(terminal_result.exit_code, 0);
}
#[test]
fn wrap_container_script_applies_configured_priority() {
let priority = ProcessPriority::new(
CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
IoPriority::Background,
);
let tools_dir = container_tools_dir();
let executable = format!("--executable {}", shell_escape(tools_dir.as_str()));
let wrapped = wrap_container_script(
"echo ok",
&[String::from("websearch")],
Some(ContainerIpcEndpoint {
host: "host.docker.internal",
port: 9000,
}),
priority,
&tools_dir,
"/workspace",
None,
)
.expect("wrap script");
assert!(wrapped.contains(
"\"$MAY_IPC_BIN\" run --isolation permissive --working-dir '/workspace' \
--env-passthrough PATH --env-passthrough HOME"
));
assert!(wrapped.contains(&executable));
assert!(wrapped.contains(
"--ipc-endpoint 'tcp://host.docker.internal:9000' --grant \"$MAY_IPC_DIR=rx\" \
--nice 5 --io-priority background -- sh -c 'echo ok'"
));
assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
let bare = wrap_container_script(
"echo ok",
&[],
None,
priority,
&tools_dir,
"/workspace",
None,
)
.expect("wrap script");
assert!(bare.contains("MAY_HEEL_BIN=\"$(command -v heel || true)\""));
assert!(bare.contains(
"\"$MAY_HEEL_BIN\" run --isolation permissive --working-dir '/workspace' \
--env-passthrough PATH --env-passthrough HOME"
));
assert!(bare.contains(&executable));
assert!(bare.contains("--nice 5 --io-priority background -- sh -c 'echo ok'"));
let normal = wrap_container_script(
"echo ok",
&[],
None,
ProcessPriority::default(),
&tools_dir,
"/workspace",
None,
)
.expect("wrap script");
assert_eq!(normal, "echo ok");
}
#[test]
fn wrap_container_script_prioritizes_each_half_independently() {
let io_only = wrap_container_script(
"echo ok",
&[],
None,
ProcessPriority::new(CpuPriority::Normal, IoPriority::Utility),
&container_tools_dir(),
"/workspace",
None,
)
.expect("wrap script");
assert!(io_only.contains(" --io-priority utility -- sh -c 'echo ok'"));
assert!(!io_only.contains("--nice"));
let cpu_only = wrap_container_script(
"echo ok",
&[],
None,
ProcessPriority::new(
CpuPriority::Nice(NiceLevel::new(9).expect("nice level 9 is in range")),
IoPriority::Normal,
),
&container_tools_dir(),
"/workspace",
None,
)
.expect("wrap script");
assert!(cpu_only.contains(" --nice 9 -- sh -c 'echo ok'"));
assert!(!cpu_only.contains("--io-priority"));
}
#[derive(Debug, Deserialize, JsonSchema)]
struct ProbeEchoArgs {
marker: String,
}
struct ProbeEchoTool;
impl Tool for ProbeEchoTool {
fn name(&self) -> Cow<'static, str> {
"probe_echo".into()
}
type Arguments = ProbeEchoArgs;
type Res = ToolResult;
fn call(
&self,
arguments: Self::Arguments,
_cx: ToolContext,
) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
std::future::ready(Ok(ToolResult::text(format!(
"marker: {}",
arguments.marker
))))
}
}
#[tokio::test(flavor = "multi_thread")]
async fn container_ipc_bridge_round_trips_a_command_over_tcp() {
let outputs = tempfile::tempdir().expect("outputs dir should be created");
let mut builder = ToolRegistryBuilder::new();
builder.configure_tool(ProbeEchoTool);
let registry = Arc::new(builder.build(outputs.path()));
let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
let bridge = start_container_ipc_bridge(
executor_core::tokio::TokioGlobal,
registry,
None,
BridgeAddress::try_from(loopback).expect("loopback binds the bridge"),
)
.expect("bridge should start on loopback");
let mut stream = Async::<StdTcpStream>::connect(SocketAddr::new(loopback, bridge.port()))
.await
.expect("client should connect to the bridge");
let params = rmp_serde::to_vec_named(&serde_json::json!({ "marker": "pong" }))
.expect("params should encode");
let request = heel::ipc::IpcRequest::encode("probe_echo", Path::new("/workspace"), ¶ms)
.expect("request should encode");
stream
.write_all(&request)
.await
.expect("request frame should be written");
let mut length_bytes = [0_u8; 4];
stream
.read_exact(&mut length_bytes)
.await
.expect("response length should be read");
let mut response = vec![0_u8; u32::from_be_bytes(length_bytes) as usize];
stream
.read_exact(&mut response)
.await
.expect("response body should be read");
let (success, payload) = response
.split_first()
.expect("response carries a success flag");
assert_eq!(*success, 1, "bridge should report success");
let rendered: String =
rmp_serde::from_slice(payload).expect("response should decode as msgpack");
assert_eq!(
rendered, "marker: pong",
"probe_echo should answer with the CLI-rendered payload, as `heel ipc` prints it"
);
drop(stream);
bridge.stop().await;
}
#[cfg(all(unix, aither_container_acceptance))]
struct TestDockerContainer(String);
#[cfg(all(unix, aither_container_acceptance))]
impl TestDockerContainer {
fn start(heel_bin: &Path, tools: &crate::MountSpec) -> Option<Self> {
let name = format!("aither-test-{}", uuid::Uuid::new_v4().simple());
let mount = format!("{}:/usr/local/bin/heel:ro", heel_bin.display());
let tools_mount = format!("{}:{}:ro", tools.host_path.display(), tools.container_path);
let output = std::process::Command::new("docker")
.args([
"run",
"-d",
"--name",
&name,
"--add-host=host.docker.internal:host-gateway",
"-v",
&mount,
"-v",
&tools_mount,
"ubuntu:24.04",
"tail",
"-f",
"/dev/null",
])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let prepared = std::process::Command::new("docker")
.args(["exec", &name, "mkdir", "-p", CONTAINER_EXEC_WORKING_DIR])
.output()
.is_ok_and(|output| output.status.success());
if !prepared {
let _ = std::process::Command::new("docker")
.args(["rm", "-f", &name])
.output();
return None;
}
Some(Self(name))
}
}
#[cfg(all(unix, aither_container_acceptance))]
impl Drop for TestDockerContainer {
fn drop(&mut self) {
let _ = std::process::Command::new("docker")
.args(["rm", "-f", &self.0])
.output();
}
}
#[cfg(all(unix, aither_container_acceptance))]
async fn container_bridge_address(
client: &bollard::Docker,
container_id: &str,
) -> BridgeAddress {
client
.inspect_container(
container_id,
None::<bollard::query_parameters::InspectContainerOptions>,
)
.await
.expect("container acceptance should inspect the container")
.network_settings
.and_then(|settings| settings.networks)
.and_then(|mut networks| networks.remove("bridge"))
.and_then(|endpoint| endpoint.gateway)
.expect("container acceptance requires the bridge network gateway")
.parse::<std::net::IpAddr>()
.expect("the bridge gateway should parse as an IP address")
.try_into()
.expect("the bridge gateway should be a usable bridge address")
}
#[cfg(all(unix, aither_container_acceptance))]
fn container_test_heel_binary() -> Option<PathBuf> {
std::env::var_os("HEEL_BIN")
.map(PathBuf::from)
.filter(|path| path.is_file())
.or_else(|| {
std::process::Command::new("sh")
.args(["-c", "command -v heel"])
.output()
.ok()
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|resolved| PathBuf::from(resolved.trim()))
})
.filter(|path| path.is_file())
}
#[cfg(all(unix, aither_container_acceptance))]
async fn start_acceptance_container() -> (
TestDockerContainer,
crate::tool_runtime::ImageTools,
crate::tool_runtime::tests::UnlockingTempDir,
) {
let docker_ready = std::process::Command::new("docker")
.arg("info")
.output()
.is_ok_and(|output| output.status.success());
assert!(
docker_ready,
"container acceptance requires a docker daemon"
);
let heel_bin = container_test_heel_binary()
.expect("container acceptance requires a Linux heel binary (set HEEL_BIN)");
let image = crate::tool_runtime::tests::image_tools();
let bundle = crate::tool_runtime::tests::bundle();
let tools_cache = crate::tool_runtime::tests::unlocking_tempdir();
let prepared = bundle
.prepare_local_sync(tools_cache.path(), &image.cache_key().unwrap(), None)
.expect("test bundle should stage for the image");
let staged = prepared
.bin_dir()
.parent()
.expect("prepared binaries have a parent directory")
.to_path_buf();
let tools_mount =
crate::MountSpec::read_only(&staged, image.container_directory().unwrap());
let container = TestDockerContainer::start(&heel_bin, &tools_mount)
.expect("container acceptance could not start ubuntu:24.04");
(container, image, tools_cache)
}
#[cfg(all(unix, aither_container_acceptance))]
async fn acceptance_shell_sessions(
container: &TestDockerContainer,
image: &crate::tool_runtime::ImageTools,
workspace: &Path,
) -> ShellSessionRegistry {
let client = Arc::new(
bollard::Docker::connect_with_local_defaults().expect("docker client should connect"),
);
let bind = container_bridge_address(&client, &container.0).await;
println!("ipc bridge bind: {}", bind.ip());
let exec = crate::AnyContainerExec::new(Arc::new(crate::BollardContainerExec::new(client)));
let runtime = ContainerShellRuntime::new(
container.0.clone(),
crate::ContainerIpcRoute::new("host.docker.internal", bind),
exec,
)
.with_workspace_mount(MountRoot::new(
workspace,
ContainerPath::new(CONTAINER_EXEC_WORKING_DIR).expect("the workspace is absolute"),
));
let container_tools = crate::tool_runtime::tests::container_tools(image);
ShellSessionRegistry::new(ShellRuntimeAvailability {
local: false,
container: true,
ssh: false,
})
.with_container_runtime(runtime)
.with_test_container_tools(container_tools, container.0.clone())
}
#[cfg(all(unix, aither_container_acceptance))]
#[tokio::test]
async fn container_streamed_exec_streams_stdout_reports_status_and_kills_on_drop() {
use crate::ContainerExec as _;
let (container, _bundle, _tools_cache) = start_acceptance_container().await;
let client = Arc::new(
bollard::Docker::connect_with_local_defaults().expect("docker client should connect"),
);
let exec = crate::BollardContainerExec::new(client);
let (_kill_tx, kill_rx) = async_channel::bounded::<()>(1);
let (stdin_tx, stdin_rx) = async_channel::bounded::<Vec<u8>>(1);
drop(stdin_tx);
let (out_tx, out_rx) = async_channel::bounded::<Vec<u8>>(8);
let streaming = exec.exec_streamed(
&container.0,
"head -c 300000 /dev/zero | tr '\\0' 'x'; exit 3",
"/",
kill_rx,
stdin_rx,
out_tx,
);
let collect = async {
let mut total = 0;
while let Ok(chunk) = out_rx.recv().await {
assert!(chunk.iter().all(|byte| *byte == b'x'));
total += chunk.len();
}
total
};
let (outcome, total) = futures::join!(streaming, collect);
assert_eq!(total, 300_000, "every byte arrives");
match outcome.expect("the exec runs") {
ContainerExecOutcome::Completed { output, .. } => {
assert_eq!(output.status.code(), Some(3));
}
ContainerExecOutcome::Killed => panic!("nothing killed it"),
}
let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
let (stdin_tx, stdin_rx) = async_channel::bounded::<Vec<u8>>(1);
drop(stdin_tx);
let (out_tx, out_rx) = async_channel::bounded::<Vec<u8>>(1);
drop(out_rx);
let outcome = exec
.exec_streamed(&container.0, "yes", "/", kill_rx, stdin_rx, out_tx)
.await;
drop(kill_tx);
assert!(
matches!(outcome, Ok(ContainerExecOutcome::Killed) | Err(_)),
"a gone reader stops the command: {outcome:?}"
);
}
#[cfg(all(unix, aither_container_acceptance))]
#[tokio::test]
async fn container_subagent_is_confined_while_the_main_agent_is_not() {
let (container, bundle, _tools_cache) = start_acceptance_container().await;
let dir = tempfile::tempdir().expect("temp dir should be created");
let shell_sessions = acceptance_shell_sessions(&container, &bundle, dir.path()).await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let parent = tool.with_registry(Arc::new(ToolRegistryBuilder::new().build(dir.path())));
let child = parent
.subagent_without_grant()
.await
.expect("an empty grant is always given");
let root = dunce::canonicalize(dir.path()).expect("workspace root should resolve");
let space = child
.working_dir()
.strip_prefix(&root)
.expect("the space is inside the workspace");
let container_space = format!("{CONTAINER_EXEC_WORKING_DIR}/{}", space.display());
let made = std::process::Command::new("docker")
.args(["exec", &container.0, "mkdir", "-p", &container_space])
.output()
.expect("docker exec should run");
assert!(made.status.success(), "{made:?}");
let host_workspace_write =
|name: &str| format!("touch {CONTAINER_EXEC_WORKING_DIR}/{name}");
assert_eq!(
exit_code_of(&parent, &host_workspace_write("main.txt")).await,
0,
"the main agent is unconfined in its container"
);
assert_ne!(
exit_code_of(&child, &host_workspace_write("sub.txt")).await,
0,
"a subagent cannot write the workspace root"
);
assert_eq!(
exit_code_of(&child, &format!("touch {container_space}/own.txt")).await,
0,
"a subagent writes its own space"
);
}
#[cfg(all(unix, aither_container_acceptance))]
#[tokio::test]
async fn container_command_runs_with_configured_nice_and_reaches_ipc() {
let (container, bundle, _tools_cache) = start_acceptance_container().await;
let shell_sessions = acceptance_shell_sessions(&container, &bundle, Path::new("/")).await;
let dir = tempfile::tempdir().expect("temp dir should be created");
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_process_priority(ProcessPriority::new(
CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
IoPriority::Normal,
));
let mut builder = ToolRegistryBuilder::new();
builder.configure_tool(ProbeEchoTool);
let registry = Arc::new(builder.build(tool.outputs_dir()));
let tool = tool.with_registry(registry);
let result = tool
.call(
TerminalArgs {
description: "probe container priority and IPC transport".to_string(),
script: concat!(
"printf 'nice=%s\\n' \"$(nice)\"; ",
"jq --version; ",
"probe_echo --marker pong; ",
"printf 'probe_exit=%s\\n' \"$?\""
)
.to_string(),
mode: TerminalExecutionMode::Sandboxed,
ssh_server_id: None,
expect: OutputFormat::Text,
resolution: MediaResolution::Auto,
max_lines: 50,
raw: false,
timeout: 30,
background: false,
},
ToolContext::new(),
)
.await
.expect("container terminal call should succeed");
let stdout = render_terminal_result(&result);
assert!(
!stdout.contains("Exit code:"),
"container command failed; stdout: {stdout}"
);
println!("container script output:\n{stdout}");
assert!(
stdout.contains("nice=5"),
"container command should run at the configured nice level; stdout: {stdout}"
);
assert!(
stdout.contains("jq 1.0.0"),
"a prepared command should run from the read-only tools mount; stdout: {stdout}"
);
assert!(
stdout.contains("pong"),
"probe_echo should answer from the live handler; stdout: {stdout}"
);
assert!(
stdout.contains("probe_exit=0"),
"heel ipc should exit 0 through the relayed endpoint; stdout: {stdout}"
);
}
type ConfiguredTestTool =
TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>;
#[cfg(unix)]
async fn exit_code_of(tool: &ConfiguredTestTool, script: &str) -> i32 {
let result = tool
.call(terminal_args("authority probe", script), ToolContext::new())
.await
.expect("terminal call should succeed");
match result.command().map(|command| &command.outcome) {
Some(CommandOutcome::Exited { code }) => *code,
other => panic!("the probe should run to completion, got {other:?}"),
}
}
#[cfg(unix)]
async fn authority_terminal(
dir: &Path,
) -> (
crate::tool_runtime::tests::UnlockingTempDir,
ConfiguredTestTool,
) {
configured_test_terminal(
dir,
Duration::from_secs(30),
Duration::from_secs(60),
Duration::from_secs(600),
)
.await
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_script_written_into_the_working_dir_executes() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
assert_eq!(
exit_code_of(
&tool,
"echo '#!/bin/sh\necho ok' > run.sh && chmod +x run.sh && ./run.sh",
)
.await,
0,
"a script the command writes and chmods runs"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn the_host_rust_toolchain_builds_and_tests_a_crate() {
assert!(
std::process::Command::new("cargo")
.arg("--version")
.output()
.is_ok_and(|output| output.status.success()),
"cargo must be on the host PATH for this test"
);
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
assert_eq!(
exit_code_of(&tool, "cargo --version").await,
0,
"cargo is reachable inside the sandbox"
);
let krate = dir.path().join("probe");
std::fs::create_dir_all(krate.join("src")).unwrap();
std::fs::write(
krate.join("Cargo.toml"),
"[package]\nname = \"probe\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
)
.unwrap();
std::fs::write(
krate.join("src/lib.rs"),
"#[test]\nfn it_runs() { assert_eq!(1 + 1, 2); }\n",
)
.unwrap();
let script = format!(
"cd '{}' && CARGO_TARGET_DIR='{}' cargo test",
krate.display(),
krate.join("target").display()
);
assert_eq!(
exit_code_of(&tool, &script).await,
0,
"cargo test executes the binary it built under the working dir"
);
}
#[cfg(all(unix, target_os = "macos"))]
#[tokio::test(flavor = "multi_thread")]
async fn cargo_credentials_inside_the_granted_home_stay_unreadable() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let code = exit_code_of(&tool, "cat ~/.cargo/credentials.toml").await;
assert_ne!(
code, 0,
"a credential file under ~/.cargo stays denied inside the sandbox"
);
}
async fn launch(
parent: &ConfiguredTestTool,
grant: SubagentGrant,
) -> Result<ConfiguredTestTool, SubagentGrantError> {
parent
.subagent(&mut LaunchHistory::default(), grant, None, None)
.await
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn subagent_cannot_write_the_session_root_but_writes_its_space_and_granted_worktrees() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, parent) = authority_terminal(dir.path()).await;
let granted = dir.path().join("granted");
let ungranted = dir.path().join("ungranted");
std::fs::create_dir_all(&granted).unwrap();
std::fs::create_dir_all(&ungranted).unwrap();
let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
.await
.expect("a writable directory can be granted");
let touch = |path: &Path| format!("touch '{}'", path.display());
let root_file = dir.path().join("root.txt");
assert_eq!(
exit_code_of(&parent, &touch(&root_file)).await,
0,
"the main agent writes its own space"
);
std::fs::remove_file(&root_file).unwrap();
assert_ne!(
exit_code_of(&child, &touch(&root_file)).await,
0,
"the session root is read-only to a subagent"
);
assert!(!root_file.exists());
assert_ne!(
exit_code_of(&child, &touch(&ungranted.join("x"))).await,
0,
"what the parent can write but did not grant is read-only"
);
assert_eq!(
exit_code_of(&child, &touch(&child.working_dir().join("own.txt"))).await,
0,
"a subagent writes its own space"
);
assert!(
child
.working_dir()
.starts_with(dunce::canonicalize(dir.path()).unwrap())
);
assert_ne!(child.working_dir(), parent.working_dir());
assert_eq!(
exit_code_of(&child, &touch(&granted.join("g.txt"))).await,
0,
"a subagent writes the worktrees it was granted"
);
}
#[cfg(unix)]
async fn stdout_of(tool: &ConfiguredTestTool, script: &str) -> String {
let result = tool
.call(terminal_args("carry probe", script), ToolContext::new())
.await
.expect("terminal call should succeed");
render_terminal_result(&result).trim().to_string()
}
#[cfg(unix)]
async fn pwd_of(tool: &ConfiguredTestTool) -> PathBuf {
PathBuf::from(stdout_of(tool, "pwd").await)
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_successful_cd_carries_to_the_next_foreground_command() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let root = dunce::canonicalize(dir.path()).unwrap();
assert_eq!(pwd_of(&tool).await, root);
assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
assert_eq!(pwd_of(&tool).await, root.join("sub"));
assert_eq!(exit_code_of(&tool, "mkdir -p a/b && cd a/b").await, 0);
assert_eq!(pwd_of(&tool).await, root.join("sub/a/b"));
assert_eq!(
PathBuf::from(stdout_of(&tool, "/bin/pwd").await),
root.join("sub/a/b")
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_failure_an_outside_cd_and_a_background_cd_leave_the_directory() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let root = dunce::canonicalize(dir.path()).unwrap();
stdout_of(&tool, "mkdir sub other && cd sub").await;
let sub = root.join("sub");
assert_eq!(pwd_of(&tool).await, sub);
assert_eq!(
exit_code_of(&tool, "cd ../other; exit 3").await,
3,
"the command fails"
);
assert_eq!(pwd_of(&tool).await, sub, "a failed command carries nothing");
assert_eq!(
exit_code_of(&tool, "cd /usr").await,
0,
"the cd itself succeeds"
);
assert_eq!(
pwd_of(&tool).await,
sub,
"a directory outside the readable paths carries nothing"
);
start_background_job(&tool, "cd ../other && pwd").await;
for _ in 0..500 {
if tool.running_tasks.load(Ordering::Acquire) == 0 {
break;
}
async_io::Timer::after(Duration::from_millis(20)).await;
}
assert_eq!(tool.running_tasks.load(Ordering::Acquire), 0);
assert_eq!(pwd_of(&tool).await, sub, "a background cd carries nothing");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn an_exported_variable_does_not_reach_the_next_command() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
assert_eq!(
stdout_of(
&tool,
"export CARRY_PROBE=set; mkdir sub; cd sub; echo $CARRY_PROBE"
)
.await,
"set"
);
assert_eq!(
stdout_of(&tool, "printenv CARRY_PROBE; echo rc=$?").await,
"rc=1"
);
assert_eq!(
pwd_of(&tool).await,
dunce::canonicalize(dir.path()).unwrap().join("sub")
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagents_cd_does_not_carry_over() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, parent) = authority_terminal(dir.path()).await;
let child = launch(&parent, SubagentGrant::new())
.await
.expect("a subagent without grants launches");
let space = child.working_dir().clone();
assert_eq!(exit_code_of(&child, "mkdir sub && cd sub").await, 0);
assert_eq!(
pwd_of(&child).await,
space,
"the subagent starts in its space"
);
assert_eq!(
pwd_of(&parent).await,
dunce::canonicalize(dir.path()).unwrap()
);
}
#[cfg(unix)]
#[test]
fn container_directory_report_is_written_by_the_rendered_script() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let report = dir.path().join("it's report");
let script = carry_cwd_script("mkdir sub && cd sub", &report.to_string_lossy())
.expect("the trailer should render");
let status = std::process::Command::new("sh")
.args(["-c", &script])
.current_dir(dir.path())
.status()
.expect("sh should run");
assert!(status.success());
let written = std::fs::read_to_string(&report).expect("the trailer writes the report");
assert_eq!(
PathBuf::from(written.trim_end()),
dunce::canonicalize(dir.path().join("sub")).unwrap()
);
for (script, code) in [("exit 7", 7), ("cd sub; (exit 5)", 5)] {
let status = std::process::Command::new("sh")
.args([
"-c",
&carry_cwd_script(script, &report.to_string_lossy()).unwrap(),
])
.current_dir(dir.path())
.status()
.expect("sh should run");
assert_eq!(status.code(), Some(code), "{script}");
}
std::fs::remove_file(&report).expect("the report exists");
let output = std::process::Command::new("sh")
.args([
"-c",
&carry_cwd_script("cd sub; cat <<EOF\nit's", &report.to_string_lossy()).unwrap(),
])
.current_dir(dir.path())
.output()
.expect("sh should run");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim_end(), "it's");
let written = std::fs::read_to_string(&report).expect("the trailer writes the report");
assert_eq!(
PathBuf::from(written.trim_end()),
dunce::canonicalize(dir.path().join("sub")).unwrap()
);
}
#[cfg(unix)]
fn assert_directory_reset(
receiver: &BackgroundTaskReceiver,
dir: impl AsRef<Path>,
reason: DirectoryResetReason,
) {
let alerts = receiver.take_job_alerts();
match alerts.as_slice() {
[JobAlert::DirectoryReset(reset)] => {
assert_eq!(reset.dir, dir.as_ref());
assert_eq!(reset.reason, reason);
}
other => panic!("expected one directory reset, got {other:?}"),
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_carried_directory_raises_no_alert() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let receiver = tool.background_receiver();
assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
assert_eq!(exit_code_of(&tool, "true").await, 0);
assert_eq!(exit_code_of(&tool, "pwd").await, 0);
assert_ne!(exit_code_of(&tool, "false").await, 0);
assert_ne!(exit_code_of(&tool, "ls /nonexistent-directory").await, 0);
assert!(receiver.take_job_alerts().is_empty());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_command_alerts_once_with_the_directory_commands_run_in() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let receiver = tool.background_receiver();
let root = dunce::canonicalize(dir.path()).unwrap();
assert_ne!(exit_code_of(&tool, "mkdir sub && cd sub && false").await, 0);
assert_directory_reset(&receiver, &root, DirectoryResetReason::Failed);
assert_eq!(pwd_of(&tool).await, root);
assert!(receiver.take_job_alerts().is_empty());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn exit_without_a_report_alerts_once() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let receiver = tool.background_receiver();
let root = dunce::canonicalize(dir.path()).unwrap();
assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
assert_eq!(exit_code_of(&tool, "cd ..; exit 0").await, 0);
assert_directory_reset(
&receiver,
root.join("sub"),
DirectoryResetReason::Unreported,
);
assert_eq!(pwd_of(&tool).await, root.join("sub"));
assert!(receiver.take_job_alerts().is_empty());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_directory_outside_the_readable_paths_alerts_once() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let receiver = tool.background_receiver();
let root = dunce::canonicalize(dir.path()).unwrap();
assert_eq!(exit_code_of(&tool, "cd /usr").await, 0);
assert_directory_reset(&receiver, &root, DirectoryResetReason::OutsideReadable);
assert_eq!(pwd_of(&tool).await, root);
assert!(receiver.take_job_alerts().is_empty());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_removed_carried_directory_alerts_once() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let receiver = tool.background_receiver();
let root = dunce::canonicalize(dir.path()).unwrap();
assert_eq!(exit_code_of(&tool, "mkdir gone && cd gone").await, 0);
assert!(receiver.take_job_alerts().is_empty());
std::fs::remove_dir(root.join("gone")).unwrap();
assert_eq!(pwd_of(&tool).await, root);
assert_directory_reset(&receiver, &root, DirectoryResetReason::Removed);
assert_eq!(pwd_of(&tool).await, root);
assert!(receiver.take_job_alerts().is_empty());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_container_directory_report_maps_through_the_workspace_mount() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let mount = MountRoot::new(
dir.path(),
ContainerPath::new("/workspace").expect("absolute"),
);
let report = tool.working_dir().join(".cwd-container");
let carry = CwdCarry {
start: None,
report: report.clone(),
container: Some(ContainerCarry {
mount: mount.clone(),
report: mount
.container_path(&report)
.expect("report is in the mount"),
start: ContainerPath::new("/workspace").unwrap(),
}),
shell: true,
};
let receiver = tool.background_receiver();
assert_eq!(
carry.container.as_ref().unwrap().report.as_str(),
format!(
"/workspace/{}",
report.file_name().unwrap().to_string_lossy()
)
);
let carried = tool.carried_dir.as_ref().unwrap();
std::fs::write(&report, "/workspace/sub/dir\n").unwrap();
tool.record_carried_dir(&carry, true).await;
assert_eq!(carried.get(), Some(dir.path().join("sub/dir")));
assert!(!report.exists(), "the report is consumed");
assert!(
receiver.take_job_alerts().is_empty(),
"a carried directory raises no alert"
);
std::fs::write(&report, "/etc\n").unwrap();
tool.record_carried_dir(&carry, true).await;
assert_eq!(carried.get(), Some(dir.path().join("sub/dir")));
assert_directory_reset(
&receiver,
"/workspace",
DirectoryResetReason::OutsideWorkspace,
);
std::fs::write(&report, "/workspace/other\n").unwrap();
tool.record_carried_dir(&carry, false).await;
assert_eq!(carried.get(), Some(dir.path().join("sub/dir")));
assert_directory_reset(&receiver, "/workspace", DirectoryResetReason::Failed);
tool.record_carried_dir(&carry, true).await;
assert_directory_reset(&receiver, "/workspace", DirectoryResetReason::Unreported);
std::fs::write(&report, "/workspace\n").unwrap();
tool.record_carried_dir(&carry, false).await;
assert!(receiver.take_job_alerts().is_empty());
assert_eq!(
mount
.container_path(&dir.path().join("sub/dir"))
.unwrap()
.as_str(),
"/workspace/sub/dir"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_grant_outside_the_launchers_authority_is_refused() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let outside = tempfile::tempdir().expect("temp dir should be created");
let (_cache, parent) = authority_terminal(dir.path()).await;
let error = launch(&parent, SubagentGrant::new().with_worktree(outside.path()))
.await
.expect_err("a launcher cannot hand on what it cannot write");
assert!(
matches!(error, SubagentGrantError::OutsideAuthority(_)),
"{error}"
);
}
#[cfg(unix)]
fn commit_script(worktree: &Path, subject: &str) -> String {
format!(
"git -c user.name=agent -c user.email=agent@example.com -c commit.gpgSign=false -C '{}' commit --allow-empty -m '{subject}'",
worktree.display()
)
}
#[cfg(unix)]
struct CommitSetup {
dir: tempfile::TempDir,
worktree: PathBuf,
common: PathBuf,
entry: PathBuf,
subagent: PathBuf,
parent: ConfiguredTestTool,
_cache: crate::tool_runtime::tests::UnlockingTempDir,
}
#[cfg(unix)]
impl CommitSetup {
async fn new(namespace: &str) -> Self {
let dir = tempfile::tempdir().expect("temp dir should be created");
let worktree =
crate::subagent::tests::repository_with_linked_worktree(dir.path(), namespace);
let (cache, parent) = authority_terminal(dir.path()).await;
let common = dunce::canonicalize(dir.path().join("repository/.git")).unwrap();
let entry = common.join("worktrees").join(namespace);
Self {
worktree: dunce::canonicalize(worktree).unwrap(),
subagent: entry.join("subagent"),
common,
entry,
parent,
dir,
_cache: cache,
}
}
async fn committing_child(&self, launcher: &ConfiguredTestTool) -> ConfiguredTestTool {
launch(
launcher,
SubagentGrant::new().with_committing_worktree(&self.worktree),
)
.await
.expect("the worktree can be granted with commit")
}
fn main_has(&self, id: &str) -> bool {
std::process::Command::new("git")
.args(["cat-file", "-e", id])
.current_dir(&self.common)
.output()
.unwrap()
.status
.success()
}
fn main(&self, args: &[&str]) -> String {
crate::subagent::tests::git_in(&self.common, args)
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_sandboxed_commit_lands_in_the_subagents_repository_and_the_main_one_is_read_only() {
let setup = CommitSetup::new("one").await;
let child = setup.committing_child(&setup.parent).await;
let ledger = child.commit_ledger().expect("a commit grant has a ledger");
let mark = ledger.mark().await.expect("the namespace can be read");
let before = setup.main(&["rev-parse", "refs/heads/subagent/one/work"]);
assert_eq!(
exit_code_of(&child, &commit_script(&setup.worktree, "authorized")).await,
0,
"a commit grant lets the subagent commit"
);
assert_eq!(
setup.main(&["rev-parse", "refs/heads/subagent/one/work"]),
before,
"the commit is not in the main repository yet"
);
let commits = ledger.since(&mark).await.expect("commits can be listed");
assert_eq!(commits.len(), 1, "{commits:?}");
assert_eq!(commits[0].subject, "authorized");
assert_eq!(commits[0].worktree, setup.worktree);
assert!(setup.main_has(&commits[0].commit));
assert_eq!(
setup.main(&["rev-parse", "refs/heads/subagent/one/work"]),
commits[0].commit
);
setup.main(&["fsck", "--strict", "--no-dangling"]);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn the_main_agents_git_in_a_committing_worktree_runs_nothing_the_subagent_chose() {
use std::fmt::Write as _;
use std::os::unix::fs::PermissionsExt as _;
let setup = CommitSetup::new("guarded").await;
let _child = setup.committing_child(&setup.parent).await;
let marker = setup.dir.path().join("subagent-ran");
let program = setup.dir.path().join("ran-by-git.sh");
std::fs::write(
&program,
format!("#!/bin/sh\nprintf ran >> '{}'\n", marker.display()),
)
.unwrap();
std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
let hooks = setup.dir.path().join("evil-hooks");
std::fs::create_dir(&hooks).unwrap();
let pre_commit = hooks.join("pre-commit");
std::fs::write(
&pre_commit,
format!("#!/bin/sh\nprintf hook >> '{}'\n", marker.display()),
)
.unwrap();
std::fs::set_permissions(&pre_commit, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut config = std::fs::read_to_string(setup.subagent.join("config")).unwrap();
write!(
config,
"\n[core]\n\tfsmonitor = {}\n\thooksPath = {}\n[filter \"pwn\"]\n\tclean = {}\n\trequired = true\n",
program.display(),
hooks.display(),
program.display()
)
.unwrap();
std::fs::write(setup.subagent.join("config"), config).unwrap();
std::fs::write(setup.worktree.join(".gitattributes"), "* filter=pwn\n").unwrap();
let worktree = setup.worktree.display().to_string();
for script in [
format!("git -C '{worktree}' status"),
format!("cd '{worktree}' && git status"),
format!(
"git -C '{worktree}' add -A && \
git -C '{worktree}' -c user.name=a -c user.email=a@a -c commit.gpgSign=false \
commit --allow-empty -m x"
),
] {
assert_eq!(
exit_code_of(&setup.parent, &script).await,
0,
"the ordinary git command should keep working: {script}"
);
}
assert!(
!marker.exists(),
"no program of the subagent's choosing ran through the worktree's repository"
);
std::fs::write(
setup.worktree.join(".git"),
format!("gitdir: {}\n", setup.subagent.display()),
)
.unwrap();
assert_eq!(
exit_code_of(&setup.parent, &format!("git -C '{worktree}' status")).await,
0
);
assert!(
!marker.exists(),
"a replaced .git file chose no program either"
);
let repository = dunce::canonicalize(setup.dir.path().join("repository")).unwrap();
assert_eq!(
exit_code_of(
&setup.parent,
&format!("git -C '{}' log --oneline -1", repository.display())
)
.await,
0,
"git in unrelated repositories still reaches them"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
#[allow(clippy::too_many_lines)]
async fn a_committing_subagent_can_change_nothing_the_main_repository_reads() {
let setup = CommitSetup::new("two").await;
let child = setup.committing_child(&setup.parent).await;
let absent = setup.common.join("objects/ff");
let _ = std::fs::remove_dir(&absent);
assert!(!absent.exists());
let loose_dir = std::fs::read_dir(setup.common.join("objects"))
.unwrap()
.map(|entry| entry.unwrap().path())
.find(|path| {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.len() == 2 && name != "ff")
})
.expect("the initial commit left loose objects");
let loose = std::fs::read_dir(&loose_dir)
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
let loose_name = loose.file_name().unwrap().to_str().unwrap().to_string();
let loose_dir_name = loose_dir.file_name().unwrap().to_str().unwrap().to_string();
let loose_bytes = std::fs::read(&loose).unwrap();
let own = &setup.subagent;
std::fs::create_dir_all(own.join("objects").join(&loose_dir_name)).unwrap();
std::fs::write(
own.join("objects").join(&loose_dir_name).join(&loose_name),
b"own",
)
.unwrap();
let main_objects = setup.common.join("objects");
let own_objects = own.join("objects");
let attempts: Vec<(&str, String, String)> = vec![
(
"create a fan-out directory",
format!("mkdir '{}'", main_objects.join("ff").display()),
format!("mkdir '{}'", own_objects.join("ff").display()),
),
(
"create an object in an existing fan-out directory",
format!(
"touch '{}'",
main_objects.join(&loose_dir_name).join("new").display()
),
format!(
"touch '{}'",
own_objects.join(&loose_dir_name).join("new").display()
),
),
(
"overwrite an existing loose object",
format!("echo evil > '{}'", loose.display()),
format!(
"echo evil > '{}'",
own_objects
.join(&loose_dir_name)
.join(&loose_name)
.display()
),
),
(
"replace an existing loose object by renaming over it",
format!(
"echo evil > '{}/stage' && mv -f '{}/stage' '{}'",
own_objects.display(),
own_objects.display(),
loose.display()
),
format!(
"echo evil > '{}/stage' && mv -f '{}/stage' '{}'",
own_objects.display(),
own_objects.display(),
own_objects
.join(&loose_dir_name)
.join(&loose_name)
.display()
),
),
(
"remove an existing loose object",
format!("rm -f '{}'", loose.display()),
format!(
"rm -f '{}'",
own_objects
.join(&loose_dir_name)
.join(&loose_name)
.display()
),
),
(
"create a pack",
format!(
"touch '{}'",
main_objects.join("pack/pack-x.pack").display()
),
format!("touch '{}'", own_objects.join("pack/pack-x.pack").display()),
),
(
"write an alternates file",
format!(
"echo /tmp > '{}'",
main_objects.join("info/alternates").display()
),
format!(
"echo /tmp > '{}'",
own_objects.join("info/scratch").display()
),
),
(
"move the worktree's branch",
format!(
"echo {} > '{}'",
"a".repeat(40),
setup.common.join("refs/heads/subagent/two/work").display()
),
format!(
"echo {} > '{}'",
"a".repeat(40),
own.join("refs/heads/subagent/two/scratch").display()
),
),
(
"rewrite the entry's HEAD",
format!("echo evil >> '{}'", setup.entry.join("HEAD").display()),
format!("echo evil >> '{}'", own.join("scratch-head").display()),
),
(
"rewrite the entry's index",
format!("echo evil >> '{}'", setup.entry.join("index").display()),
format!("echo evil >> '{}'", own.join("scratch-index").display()),
),
(
"rewrite the repository's configuration",
format!("echo evil >> '{}'", setup.common.join("config").display()),
format!("echo evil >> '{}'", own.join("scratch-config").display()),
),
];
for (what, denied, control) in attempts {
assert_ne!(
exit_code_of(&child, &denied).await,
0,
"must not {what} in the main repository"
);
assert_eq!(
exit_code_of(&child, &control).await,
0,
"the same command succeeds in the subagent's own repository: {what}"
);
}
assert!(!absent.exists(), "no fan-out directory appeared");
assert_eq!(
std::fs::read(&loose).unwrap(),
loose_bytes,
"the object is as it was"
);
assert!(
!std::fs::read_to_string(setup.common.join("config"))
.unwrap()
.contains("evil")
);
setup.main(&["fsck", "--strict", "--no-dangling"]);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn git_in_another_repository_works_inside_a_committing_subagents_sandbox() {
let setup = CommitSetup::new("three").await;
let other = setup.dir.path().join("other");
std::fs::create_dir_all(&other).unwrap();
crate::subagent::tests::git_in(&other, &["init", "--initial-branch=main"]);
crate::subagent::tests::git_in(&other, &["commit", "--allow-empty", "-m", "elsewhere"]);
let child = setup.committing_child(&setup.parent).await;
assert!(
stdout_of(
&child,
&format!("git -C '{}' log --oneline", other.display())
)
.await
.contains("elsewhere")
);
let clone = child.working_dir().join("clone");
assert_eq!(
exit_code_of(
&child,
&format!("git clone '{}' '{}'", other.display(), clone.display())
)
.await,
0
);
assert!(clone.join(".git").exists());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_committing_child_shares_its_parents_repository() {
let setup = CommitSetup::new("four").await;
let parent_subagent = setup.committing_child(&setup.parent).await;
let parent_ledger = parent_subagent.commit_ledger().unwrap();
let parent_mark = parent_ledger.mark().await.unwrap();
assert_eq!(
exit_code_of(
&parent_subagent,
&commit_script(&setup.worktree, "parent work")
)
.await,
0
);
let child = setup.committing_child(&parent_subagent).await;
let child_ledger = child.commit_ledger().unwrap();
let child_mark = child_ledger.mark().await.unwrap();
assert!(
stdout_of(
&child,
&format!("git -C '{}' log --oneline", setup.worktree.display())
)
.await
.contains("parent work"),
"the child sees its parent's commit"
);
assert_eq!(
exit_code_of(&child, &commit_script(&setup.worktree, "child work")).await,
0
);
let child_commits = child_ledger.since(&child_mark).await.unwrap();
assert_eq!(
child_commits
.iter()
.map(|commit| commit.subject.as_str())
.collect::<Vec<_>>(),
["child work"]
);
let parent_commits = parent_ledger.since(&parent_mark).await.unwrap();
assert_eq!(
parent_commits
.iter()
.map(|commit| commit.subject.as_str())
.collect::<Vec<_>>(),
["parent work", "child work"]
);
for commit in &parent_commits {
assert!(setup.main_has(&commit.commit));
}
setup.main(&["fsck", "--strict", "--no-dangling"]);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn objects_the_subagent_cannot_read_never_reach_the_main_repository() {
let setup = CommitSetup::new("five").await;
let child = setup.committing_child(&setup.parent).await;
let outside = tempfile::tempdir().expect("temp dir should be created");
std::fs::write(outside.path().join("secret.txt"), "secret").unwrap();
crate::subagent::tests::git_in(outside.path(), &["init", "--initial-branch=main"]);
crate::subagent::tests::git_in(outside.path(), &["add", "secret.txt"]);
crate::subagent::tests::git_in(outside.path(), &["commit", "-m", "secret commit"]);
let secret = crate::subagent::tests::git_in(outside.path(), &["rev-parse", "HEAD"]);
assert_ne!(
exit_code_of(
&child,
&format!("cat '{}'", outside.path().join("secret.txt").display())
)
.await,
0,
"the control: the sandbox cannot read the other repository"
);
let ledger = child.commit_ledger().unwrap();
let mark = ledger.mark().await.unwrap();
for entry in std::fs::read_dir(outside.path().join(".git/objects")).unwrap() {
let entry = entry.unwrap();
let name = entry.file_name();
if name.len() == 2 {
std::os::unix::fs::symlink(entry.path(), setup.subagent.join("objects").join(name))
.unwrap();
}
}
std::fs::write(
setup.subagent.join("refs/heads/subagent/five/stolen"),
format!("{secret}\n"),
)
.unwrap();
assert_eq!(
crate::subagent::tests::git_in(
&setup.subagent,
&["--git-dir", ".", "cat-file", "-t", &secret]
),
"commit",
"the control: a git that could read the other repository packs its commit"
);
let error = ledger
.since(&mark)
.await
.expect_err("the sandbox cannot read the objects it is asked to pack");
assert!(
matches!(error, crate::CommitLedgerError::Export { .. }),
"the sandboxed git is what refuses: {error}"
);
assert!(!setup.main_has(&secret), "the secret commit never arrives");
assert!(
!setup
.common
.join("refs/heads/subagent/five/stolen")
.exists(),
"and no ref names it"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn the_import_budget_is_a_setting_adjustable_while_subagents_run() {
let setup = CommitSetup::new("budget").await;
let budget = setup.parent.subagent_import_budget();
assert_eq!(budget.get(), DEFAULT_SUBAGENT_IMPORT_LIMIT);
let child = setup.committing_child(&setup.parent).await;
let ledger = child.commit_ledger().unwrap();
let mark = ledger.mark().await.unwrap();
assert_eq!(
exit_code_of(
&child,
&commit_script(&setup.worktree, "heavier than 1 byte")
)
.await,
0
);
budget.set(1);
let error = ledger
.since(&mark)
.await
.expect_err("the setting changed after the subagent launched applies to it");
assert!(
matches!(
error,
crate::CommitLedgerError::Export { .. } | crate::CommitLedgerError::Rejected { .. }
),
"{error}"
);
budget.set(0);
let listed = ledger.since(&mark).await.expect("zero bounds nothing");
assert_eq!(listed.len(), 1);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn the_run_start_refresh_shows_new_main_commits_and_keeps_unimported_work() {
let setup = CommitSetup::new("six").await;
let child = setup.committing_child(&setup.parent).await;
let ledger = child.commit_ledger().unwrap();
ledger.mark().await.unwrap();
assert_eq!(
exit_code_of(&child, &commit_script(&setup.worktree, "unimported")).await,
0
);
crate::subagent::tests::git_in(
&dunce::canonicalize(setup.dir.path().join("repository")).unwrap(),
&["commit", "--allow-empty", "-m", "main moved on"],
);
let log = |branch: &str| {
format!(
"git -C '{}' log --format=%s {branch}",
setup.worktree.display()
)
};
assert!(
!stdout_of(&child, &log("main"))
.await
.contains("main moved on"),
"the snapshot is the one from before"
);
ledger.mark().await.unwrap();
assert!(
stdout_of(&child, &log("main"))
.await
.contains("main moved on"),
"the next run starts with the main agent's new commit"
);
assert!(
stdout_of(&child, &log("subagent/six/work"))
.await
.contains("unimported"),
"the subagent's own work survives the refresh"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_container_commit_grant_refreshes_through_the_confined_streamed_exec() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let worktree = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "seven");
let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
let child = launch(
&parent,
SubagentGrant::new().with_committing_worktree(&worktree),
)
.await
.expect("a worktree inside the workspace can be granted commit");
let subagent = dunce::canonicalize(dir.path())
.unwrap()
.join("repository/.git/worktrees/seven/subagent");
let config = std::fs::read_to_string(subagent.join("config")).unwrap();
assert!(
config.contains("url = \"/workspace/repository/.git\""),
"the remote is spelled as the container sees it: {config}"
);
assert!(
config.contains("hooksPath = \"../repository/.git/hooks\""),
"{config}"
);
let _ = child.commit_ledger().unwrap().mark().await;
let scripts = scripts.lock().unwrap().clone();
let refresh = scripts
.iter()
.find(|script| script.contains("fetch"))
.expect("the refresh ran in the container");
assert!(refresh.contains("run --working-dir"), "{refresh}");
assert!(
refresh.contains("--grant '/workspace/repository/.git/worktrees/seven/subagent=rw'"),
"{refresh}"
);
assert!(
refresh.contains("git --git-dir /workspace/repository/.git/worktrees/seven/subagent"),
"{refresh}"
);
assert!(refresh.contains("main-repository"), "{refresh}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_commit_grant_needs_a_linked_worktree_whose_repository_the_launcher_can_write() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let repository = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "two")
.parent()
.unwrap()
.join("repository");
let plain = dir.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
let (_cache, parent) = authority_terminal(dir.path()).await;
let checkout = launch(
&parent,
SubagentGrant::new().with_committing_worktree(&repository),
)
.await
.expect_err("a checkout holds its git data inside the grant");
assert!(
matches!(checkout, SubagentGrantError::RepositoryCheckout(_)),
"{checkout}"
);
let not_git = launch(
&parent,
SubagentGrant::new().with_committing_worktree(&plain),
)
.await
.expect_err("a plain directory has nothing to commit in");
assert!(
matches!(not_git, SubagentGrantError::NotAWorktree(_)),
"{not_git}"
);
let elsewhere = tempfile::tempdir().expect("temp dir should be created");
let foreign =
crate::subagent::tests::repository_with_linked_worktree(elsewhere.path(), "three");
let inside = dir.path().join("three");
std::fs::rename(&foreign, &inside).unwrap();
crate::subagent::tests::git_in(
&elsewhere.path().join("repository"),
&["worktree", "repair", inside.to_str().unwrap()],
);
let outside = launch(
&parent,
SubagentGrant::new().with_committing_worktree(&inside),
)
.await
.expect_err("the launcher cannot hand on git data it cannot write");
assert!(
matches!(outside, SubagentGrantError::OutsideAuthority(_)),
"{outside}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_nested_launch_never_exceeds_its_launcher() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let worktree = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "four");
let sibling = dir.path().join("sibling");
std::fs::create_dir_all(&sibling).unwrap();
let (_cache, parent) = authority_terminal(dir.path()).await;
let writer = launch(&parent, SubagentGrant::new().with_worktree(&worktree))
.await
.unwrap();
let escalated = launch(
&writer,
SubagentGrant::new().with_committing_worktree(&worktree),
)
.await
.expect_err("a subagent without commit cannot grant it");
assert!(
matches!(escalated, SubagentGrantError::CommitOutsideAuthority(_)),
"{escalated}"
);
let sideways = launch(&writer, SubagentGrant::new().with_worktree(&sibling))
.await
.expect_err("a subagent cannot grant what it cannot write");
assert!(
matches!(sideways, SubagentGrantError::OutsideAuthority(_)),
"{sideways}"
);
let committer = launch(
&parent,
SubagentGrant::new().with_committing_worktree(&worktree),
)
.await
.unwrap();
let handed_on = launch(
&committer,
SubagentGrant::new().with_committing_worktree(&worktree),
)
.await
.expect("a subagent hands on the commit grant it holds");
assert_eq!(
handed_on.grants().snapshot().writable,
committer.grants().snapshot().writable
);
assert!(handed_on.working_dir().starts_with(committer.working_dir()));
}
#[derive(Debug, Deserialize, JsonSchema)]
struct LaunchProbeArgs {
#[serde(default)]
worktree: Option<String>,
}
struct LaunchProbe {
binding: TerminalBinding,
}
impl Tool for LaunchProbe {
fn name(&self) -> Cow<'static, str> {
"launch_probe".into()
}
type Arguments = LaunchProbeArgs;
type Res = ToolResult;
async fn call(
&self,
arguments: Self::Arguments,
_cx: ToolContext,
) -> aither_core::Result<Self::Res> {
let grant = arguments
.worktree
.into_iter()
.fold(SubagentGrant::new(), SubagentGrant::with_worktree);
let launched = self.binding.launcher().create(grant, None, None).await?;
Ok(ToolResult::Text {
text: launched.working_dir().display().to_string(),
})
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagent_running_the_launch_command_launches_with_its_own_authority() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let granted = dir.path().join("granted");
let sibling = dir.path().join("sibling");
std::fs::create_dir_all(&granted).unwrap();
std::fs::create_dir_all(&sibling).unwrap();
let tool = TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let mut builder = ToolRegistryBuilder::new();
builder.configure_terminal_bound_tool("launch_probe", |binding: &TerminalBinding| {
LaunchProbe {
binding: binding.clone(),
}
});
let parent = tool.with_registry(Arc::new(builder.build(dir.path().join("outputs"))));
let sibling_arg = sibling.to_str().unwrap();
let from_main = query_control(
parent.registry(),
"launch_probe",
&["--worktree", sibling_arg],
)
.await;
assert_eq!(from_main["ok"], true, "{from_main}");
let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
.await
.unwrap();
let refused = query_control(
child.registry(),
"launch_probe",
&["--worktree", sibling_arg],
)
.await;
assert_eq!(refused["ok"], false, "{refused}");
assert!(
refused["error"]
.as_str()
.is_some_and(|error| error.contains("is not writable by the agent launching")),
"{refused}"
);
let nested = query_control(
child.registry(),
"launch_probe",
&["--worktree", granted.to_str().unwrap()],
)
.await;
assert_eq!(nested["ok"], true, "{nested}");
let grandchild = nested["payload"].to_string();
let child_space = child.working_dir().display().to_string();
assert!(
grandchild.contains(&child_space),
"the grandchild works inside its caller's space: {grandchild} vs {child_space}"
);
}
#[tokio::test]
async fn a_subagent_of_a_subagent_gets_the_subagent_registry() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, shell_sessions) = prepared_test_registry().await;
let tool = TerminalTool::new_exact(
dir.path(),
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let mut builder = ToolRegistryBuilder::new();
builder.main_only(|reserved| reserved.configure_tool(ProbeEchoTool));
let parent = tool.with_registry(Arc::new(builder.build(dir.path().join("outputs"))));
assert_eq!(parent.registry().role(), crate::CommandRole::Main);
let child = launch(&parent, SubagentGrant::new()).await.unwrap();
let grandchild = launch(&child, SubagentGrant::new()).await.unwrap();
for terminal in [&child, &grandchild] {
assert_eq!(terminal.registry().role(), crate::CommandRole::Subagent);
let refused =
query_control(terminal.registry(), "probe_echo", &["--marker", "x"]).await;
assert_eq!(refused["ok"], false, "{refused}");
assert!(
refused["error"]
.as_str()
.is_some_and(|error| error.contains("reserved for the main agent")),
"{refused}"
);
}
assert!(grandchild.working_dir().starts_with(child.working_dir()));
let served = parent.clone().to_dyn();
assert!(served.has_command("probe_echo"));
assert_eq!(served.role(), crate::CommandRole::Main);
assert_eq!(parent.binding().role(), crate::CommandRole::Main);
assert_eq!(child.binding().role(), crate::CommandRole::Subagent);
let child = child.to_dyn();
assert!(!child.has_command("probe_echo"));
assert_eq!(child.role(), crate::CommandRole::Subagent);
}
use aither_core::llm::{AgentIdentity, SubagentIdentity, ToolCallId};
struct IdentityProbe {
entered: async_channel::Sender<CallIdentity>,
hold: Option<Receiver<()>>,
}
#[derive(Debug, Deserialize, JsonSchema)]
struct IdentityProbeArgs {}
impl Tool for IdentityProbe {
fn name(&self) -> Cow<'static, str> {
"identity_probe".into()
}
type Arguments = IdentityProbeArgs;
type Res = ToolResult;
async fn call(
&self,
_arguments: Self::Arguments,
cx: ToolContext,
) -> aither_core::Result<Self::Res> {
let identity = cx.identity().expect("a terminal call identifies itself");
self.entered.send(identity.clone()).await.unwrap();
if let Some(hold) = &self.hold {
hold.recv().await.unwrap();
}
Ok(ToolResult::text(format!("seen={}", identity.call())))
}
}
struct IdentityObserver(async_channel::Sender<(String, Option<CallIdentity>)>);
impl crate::CommandObserver for IdentityObserver {
async fn command_called(&self, call: &crate::CommandCall<'_>) {
self.0
.send((call.name.to_string(), call.call.cloned()))
.await
.unwrap();
}
}
fn call_identity(id: &str, agent: AgentIdentity) -> CallIdentity {
CallIdentity::new(ToolCallId::new(id), agent)
}
async fn within_deadline<T>(future: impl std::future::Future<Output = T>) -> T {
futures_lite::future::or(async { Some(future.await) }, async {
async_io::Timer::after(Duration::from_secs(60)).await;
None
})
.await
.expect("the probe should finish within its deadline")
}
#[cfg(unix)]
async fn identity_terminal(
dir: &Path,
probe: IdentityProbe,
observer: async_channel::Sender<(String, Option<CallIdentity>)>,
) -> (
crate::tool_runtime::tests::UnlockingTempDir,
ConfiguredTestTool,
) {
let (cache, shell_sessions) = prepared_test_registry().await;
let tool = TerminalTool::new_exact(
dir,
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let mut builder = ToolRegistryBuilder::new();
builder.configure_tool(probe);
builder.observe_commands(crate::AnyCommandObserver::new(IdentityObserver(observer)));
(
cache,
tool.with_registry(Arc::new(builder.build(dir.join("outputs")))),
)
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn an_ipc_command_receives_the_identity_of_its_terminal_call() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (entered, entered_rx) = async_channel::unbounded();
let (observed, observed_rx) = async_channel::unbounded();
let (_cache, tool) = identity_terminal(
dir.path(),
IdentityProbe {
entered,
hold: None,
},
observed,
)
.await;
let subagent = AgentIdentity::Subagent(SubagentIdentity::new(
"explore",
Some(call_identity("call_parent", AgentIdentity::Main)),
));
let identity = call_identity("call_a", subagent);
let result = within_deadline(tool.call(
terminal_args("identity probe", "identity_probe"),
ToolContext::new().with_identity(identity.clone()),
))
.await
.expect("terminal call should succeed");
assert!(
render_terminal_result(&result).contains("seen=call_a"),
"{}",
render_terminal_result(&result)
);
assert_eq!(entered_rx.recv().await.unwrap(), identity);
assert_eq!(
observed_rx.recv().await.unwrap(),
("identity_probe".to_string(), Some(identity))
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_terminal_calls_deliver_their_own_ids() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (entered, entered_rx) = async_channel::unbounded();
let (hold_tx, hold) = async_channel::unbounded();
let (observed, _observed_rx) = async_channel::unbounded();
let (_cache, tool) = identity_terminal(
dir.path(),
IdentityProbe {
entered,
hold: Some(hold),
},
observed,
)
.await;
let run = |id: &'static str| {
let tool = &tool;
async move {
let result = tool
.call(
terminal_args("identity probe", "identity_probe"),
ToolContext::new().with_identity(call_identity(id, AgentIdentity::Main)),
)
.await
.expect("terminal call should succeed");
render_terminal_result(&result)
}
};
let release = async {
let mut inside = [
entered_rx.recv().await.unwrap(),
entered_rx.recv().await.unwrap(),
];
inside.sort_by(|a, b| a.call().as_str().cmp(b.call().as_str()));
assert_eq!(
inside
.iter()
.map(|identity| identity.call().as_str())
.collect::<Vec<_>>(),
["call_a", "call_b"]
);
hold_tx.send(()).await.unwrap();
hold_tx.send(()).await.unwrap();
};
let (a, b, ()) =
within_deadline(async { futures::join!(run("call_a"), run("call_b"), release) }).await;
assert!(a.contains("seen=call_a") && !a.contains("call_b"), "{a}");
assert!(b.contains("seen=call_b") && !b.contains("call_a"), "{b}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_backgrounded_job_keeps_the_id_of_the_call_that_started_it() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (entered, entered_rx) = async_channel::unbounded();
let (observed, observed_rx) = async_channel::unbounded();
let (_cache, tool) = identity_terminal(
dir.path(),
IdentityProbe {
entered,
hold: None,
},
observed,
)
.await;
let identity = call_identity("call_bg", AgentIdentity::Main);
let mut args = terminal_args("identity probe", "identity_probe");
args.background = true;
within_deadline(tool.call(args, ToolContext::new().with_identity(identity.clone())))
.await
.expect("terminal call should succeed");
assert_eq!(within_deadline(entered_rx.recv()).await.unwrap(), identity);
assert_eq!(
within_deadline(observed_rx.recv()).await.unwrap().1,
Some(identity)
);
}
#[cfg(unix)]
struct RecordingExec {
scripts: Arc<std::sync::Mutex<Vec<String>>>,
}
#[cfg(unix)]
impl crate::ContainerExec for RecordingExec {
fn exec(
&self,
_container_id: &str,
script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_lifetime: ExecLifetime,
) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
{
self.scripts.lock().unwrap().push(script.to_string());
std::future::ready(Ok(ContainerExecOutcome::Completed {
output: std::process::Output {
status: std::os::unix::process::ExitStatusExt::from_raw(0),
stdout: Vec::new(),
stderr: Vec::new(),
},
killed: Vec::new(),
}))
}
fn exec_streamed(
&self,
_container_id: &str,
script: &str,
_working_dir: &str,
_kill_rx: Receiver<()>,
_stdin_rx: Receiver<Vec<u8>>,
_stdout: Sender<Vec<u8>>,
) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
{
self.scripts.lock().unwrap().push(script.to_string());
std::future::ready(Ok(ContainerExecOutcome::Completed {
output: std::process::Output {
status: std::os::unix::process::ExitStatusExt::from_raw(0),
stdout: Vec::new(),
stderr: Vec::new(),
},
killed: Vec::new(),
}))
}
}
#[cfg(unix)]
async fn recording_container_terminal(
dir: &Path,
workspace: Option<&Path>,
) -> (Arc<std::sync::Mutex<Vec<String>>>, ConfiguredTestTool) {
let scripts = Arc::new(std::sync::Mutex::new(Vec::new()));
let runtime = ContainerShellRuntime::new(
"aither-test-confinement",
crate::ContainerIpcRoute::new(
"host.docker.internal",
crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
.expect("loopback binds the bridge"),
),
crate::AnyContainerExec::new(Arc::new(RecordingExec {
scripts: scripts.clone(),
})),
);
let runtime = match workspace {
Some(workspace) => runtime.with_workspace_mount(MountRoot::new(
workspace,
ContainerPath::new(CONTAINER_EXEC_WORKING_DIR).expect("the workspace is absolute"),
)),
None => runtime,
};
let container_tools =
crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::image_tools());
let shell_sessions = ShellSessionRegistry::new(ShellRuntimeAvailability {
local: false,
container: true,
ssh: false,
})
.with_container_runtime(runtime)
.with_test_container_tools(container_tools, "aither-test-confinement".to_string());
let tool = TerminalTool::new_exact(
dir,
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted");
let parent = tool.with_registry(Arc::new(ToolRegistryBuilder::new().build(dir)));
(scripts, parent)
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn container_session_runs_the_main_agent_unconfined_and_a_subagent_confined() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let granted = dir.path().join("granted");
std::fs::create_dir_all(&granted).unwrap();
let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
.await
.expect("a directory inside the workspace can be granted");
assert_eq!(exit_code_of(&parent, "echo main-command").await, 0);
assert_eq!(exit_code_of(&child, "echo subagent-command").await, 0);
let scripts = scripts.lock().unwrap().clone();
let main = scripts
.iter()
.find(|script| script.contains("main-command"))
.expect("the main agent's command ran");
let sub = scripts
.iter()
.find(|script| script.contains("subagent-command"))
.expect("the subagent's command ran");
assert!(
!main.contains(" run --"),
"the container is the main agent's boundary: {main}"
);
assert!(sub.contains("\"$MAY_IPC_BIN\" run --working-dir"), "{sub}");
assert!(!sub.contains("--isolation permissive"), "{sub}");
let root = dunce::canonicalize(dir.path()).unwrap();
let space = child
.working_dir()
.strip_prefix(&root)
.unwrap()
.to_str()
.unwrap();
assert!(
sub.contains(&format!("--working-dir '/workspace/{space}'")),
"{sub}"
);
let granted_name = granted.file_name().unwrap().to_str().unwrap();
assert!(
sub.contains(&format!("--grant '/workspace/{granted_name}=rw'")),
"{sub}"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_containers_git_map_spells_the_worktree_and_gitdir_the_container_way() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let worktree =
crate::subagent::tests::repository_with_linked_worktree(dir.path(), "mapped");
let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
let _child = launch(
&parent,
SubagentGrant::new().with_committing_worktree(&worktree),
)
.await
.expect("the worktree can be granted with commit");
assert_eq!(exit_code_of(&parent, "echo mapped-worktree").await, 0);
let script = scripts
.lock()
.unwrap()
.iter()
.find(|script| script.contains("mapped-worktree"))
.expect("the main agent's command ran")
.clone();
assert!(
script.contains("export AITHER_GIT_WORKTREE_PATH_0=/workspace/mapped"),
"{script}"
);
assert!(
script.contains(
"export AITHER_GIT_WORKTREE_GITDIR_0=/workspace/repository/.git/worktrees/mapped"
),
"{script}"
);
let host = dunce::canonicalize(&worktree)
.unwrap()
.display()
.to_string();
assert!(
!script.contains(&host),
"the shim sees no host spelling: {script}"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_container_subagent_outside_the_workspace_mount_is_refused_at_launch() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let mounted = dir.path().join("mounted");
let granted = dir.path().join("granted");
std::fs::create_dir_all(&mounted).unwrap();
std::fs::create_dir_all(&granted).unwrap();
let (_scripts, parent) = recording_container_terminal(dir.path(), Some(&mounted)).await;
let error = launch(&parent, SubagentGrant::new().with_worktree(&granted))
.await
.expect_err("the subagent's paths are not inside the mount");
assert!(
matches!(error, SubagentGrantError::OutsideContainerMount { .. }),
"{error}"
);
let (_scripts, unmounted) = recording_container_terminal(dir.path(), None).await;
let error = launch(&unmounted, SubagentGrant::new())
.await
.expect_err("a container without a declared mount cannot confine a subagent");
assert!(
matches!(error, SubagentGrantError::NoContainerMount),
"{error}"
);
}
#[cfg(unix)]
async fn kill_guard_tool(
dir: &Path,
) -> (
crate::tool_runtime::tests::UnlockingTempDir,
TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
) {
let (cache, shell_sessions) = prepared_test_registry().await;
let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
TerminalTool::new_exact(
dir,
TestPermissionHandler::default(),
executor_core::tokio::TokioGlobal,
)
.await
.expect("terminal tool should initialize")
.adopt_prepared_tools(shell_sessions)
.await
.expect("prepared tools should be adopted")
.with_shell_runtime_availability(crate::ShellRuntimeAvailability {
local: true,
container: false,
ssh: false,
});
let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
(cache, tool.with_registry(registry))
}
#[cfg(unix)]
#[tokio::test]
async fn name_based_kills_are_refused_before_they_run() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = kill_guard_tool(dir.path()).await;
let marker = dir.path().join("ran");
for killer in [
"pkill -f anything",
"killall anything",
"/usr/bin/pkill -f anything",
"/usr/bin/killall anything",
"sudo pkill anything",
"env FOO=1 nice timeout 5 /usr/bin/killall anything",
"echo anything | xargs pkill",
"sh -c 'killall anything'",
"echo $(pkill anything)",
"(pkill anything)",
] {
let script = format!("touch {}; {killer}", marker.display());
let error = tool
.call(
terminal_args("name-based kill", &script),
ToolContext::new(),
)
.await
.expect_err("a name-based kill must be refused");
assert!(
error.to_string().contains("kill that PID"),
"`{killer}` refusal must tell the agent to kill by PID: {error}"
);
let error = tool
.run_background(terminal_args("name-based kill", &script))
.await
.expect_err("a background name-based kill must be refused");
assert!(
error.to_string().contains("kill that PID"),
"`{killer}` background refusal must tell the agent to kill by PID: {error}"
);
assert!(
!marker.exists(),
"`{killer}` must be refused before any part of the command runs"
);
}
}
#[cfg(unix)]
#[tokio::test]
async fn kill_by_pid_and_mentions_of_killers_still_run() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = kill_guard_tool(dir.path()).await;
let result = tool
.call(
terminal_args("mention a killer", "echo pkill killall"),
ToolContext::new(),
)
.await
.expect("a mention of a killer must not be refused");
assert!(
render_terminal_result(&result).contains("pkill killall"),
"{}",
render_terminal_result(&result)
);
let result = tool
.call(
terminal_args(
"kill by pid",
"sleep 300 & pid=$!; kill $pid; wait $pid; echo \"status=$?\"",
),
ToolContext::new(),
)
.await
.expect("kill by PID must not be refused");
assert!(
render_terminal_result(&result).contains("status=143"),
"kill <pid> must terminate the process it names: {}",
render_terminal_result(&result)
);
}
use crate::monitor::{MonitorArgs, MonitorEnd, MonitorLanguage, MonitorSource, MonitorTool};
async fn monitor_alerts(
receiver: &BackgroundTaskReceiver,
duration: Duration,
) -> Vec<JobAlert> {
let deadline = std::time::Instant::now() + duration;
let mut alerts = Vec::new();
while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
let Some(event) = receiver.recv_event_timeout(remaining).await else {
break;
};
let BackgroundTaskEvent::Alert(alert) = event else {
continue;
};
let ended = matches!(alert, JobAlert::MonitorEnded(_));
alerts.push(alert);
if ended {
break;
}
}
alerts
}
fn monitor_command(command: &str, timeout_secs: u64) -> MonitorArgs {
MonitorArgs {
source: MonitorSource::Command {
command: command.to_string(),
language: MonitorLanguage::Shell,
},
interval_secs: 1,
filter: None,
stop_on: None,
kill_on_stop: false,
stall_secs: None,
timeout_secs,
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn monitored_command_delivers_increments_and_its_exit() {
let dir = tempfile::tempdir().unwrap();
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(7200),
Duration::from_secs(600),
)
.await;
let monitor = MonitorTool::new(tool.clone());
monitor
.call(
monitor_command("echo a; sleep 2; echo b", 30),
ToolContext::new(),
)
.await
.expect("monitor starts");
let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(20)).await;
let increments: Vec<&[String]> = alerts
.iter()
.filter_map(|alert| match alert {
JobAlert::MonitorIncrement(increment) => Some(increment.lines.as_slice()),
_ => None,
})
.collect();
assert!(
increments.iter().any(|inc| *inc == ["a".to_string()]),
"the first line is delivered as it arrives: {alerts:?}"
);
assert!(
increments.iter().any(|inc| *inc == ["b".to_string()]),
"the later line is delivered in a following increment: {alerts:?}"
);
assert!(
alerts.iter().any(|alert| matches!(
alert,
JobAlert::MonitorEnded(ended)
if matches!(ended.end, MonitorEnd::Exited { exit_code: 0 })
)),
"the monitor reports the command's exit: {alerts:?}"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn monitor_filter_keeps_matching_lines_and_stop_on_ends() {
let dir = tempfile::tempdir().unwrap();
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(7200),
Duration::from_secs(600),
)
.await;
let monitor = MonitorTool::new(tool.clone());
let mut args = monitor_command(
"printf 'keep one\\ndrop\\nkeep two\\nlast\\n'; sleep 60",
30,
);
args.filter = Some("^keep".to_string());
args.stop_on = Some("two".to_string());
monitor
.call(args, ToolContext::new())
.await
.expect("monitor starts");
let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(20)).await;
let lines: Vec<&String> = alerts
.iter()
.filter_map(|alert| match alert {
JobAlert::MonitorIncrement(increment) => Some(&increment.lines),
_ => None,
})
.flatten()
.collect();
assert!(
lines.iter().all(|line| line.starts_with("keep")),
"filter drops non-matching lines: {lines:?}"
);
assert!(
!lines.iter().any(|line| *line == "last"),
"lines after the stop match are not delivered: {lines:?}"
);
assert!(
alerts.iter().any(|alert| matches!(
alert,
JobAlert::MonitorEnded(ended)
if matches!(&ended.end, MonitorEnd::StopMatched { line } if line == "keep two")
)),
"the first stop_on match ends the monitor: {alerts:?}"
);
tool.job_registry().kill_running().await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn monitor_rejects_a_timeout_over_the_cap_and_times_out_at_the_deadline() {
let dir = tempfile::tempdir().unwrap();
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(7200),
Duration::from_secs(600),
)
.await;
let monitor = MonitorTool::new(tool.clone());
let refused = monitor
.call(monitor_command("sleep 60", 7201), ToolContext::new())
.await;
assert!(refused.is_err(), "timeout_secs over the cap is refused");
monitor
.call(monitor_command("sleep 60", 2), ToolContext::new())
.await
.expect("monitor starts");
let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
assert!(
alerts.iter().any(|alert| matches!(
alert,
JobAlert::MonitorEnded(ended) if matches!(ended.end, MonitorEnd::TimedOut)
)),
"the deadline kills the run and reports a timeout: {alerts:?}"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn monitor_reports_a_stall_once() {
let dir = tempfile::tempdir().unwrap();
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(7200),
Duration::from_secs(600),
)
.await;
let monitor = MonitorTool::new(tool.clone());
let mut args = monitor_command("sleep 4; echo done", 30);
args.stall_secs = Some(1);
monitor
.call(args, ToolContext::new())
.await
.expect("monitor starts");
let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
let stalls = alerts
.iter()
.filter(|alert| matches!(alert, JobAlert::MonitorStalled(_)))
.count();
assert_eq!(stalls, 1, "a stall is reported once: {alerts:?}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn monitored_file_delivers_appends_and_refuses_an_unreadable_file() {
let dir = tempfile::tempdir().unwrap();
let (_cache, tool) = configured_test_terminal(
dir.path(),
Duration::from_secs(10),
Duration::from_secs(7200),
Duration::from_secs(600),
)
.await;
let monitor = MonitorTool::new(tool.clone());
let unreadable = monitor
.call(
MonitorArgs {
source: MonitorSource::File {
file: "/etc/sudoers".to_string(),
},
..monitor_command("true", 30)
},
ToolContext::new(),
)
.await;
assert!(
unreadable.is_err(),
"a file the sandbox may not read is refused"
);
let path = tool.working_dir().join("followed.log");
std::fs::write(&path, "existing\n").unwrap();
monitor
.call(
MonitorArgs {
source: MonitorSource::File {
file: "followed.log".to_string(),
},
..monitor_command("true", 30)
},
ToolContext::new(),
)
.await
.expect("monitor starts");
async_io::Timer::after(Duration::from_millis(1500)).await;
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(&path)
.unwrap();
std::io::Write::write_all(&mut file, b"appended\n").unwrap();
std::fs::rename(&path, tool.working_dir().join("followed.log.1")).unwrap();
std::fs::write(&path, "rotated\n").unwrap();
async_io::Timer::after(Duration::from_millis(500)).await;
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(&path)
.unwrap();
std::io::Write::write_all(&mut file, b"after\n").unwrap();
let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
let lines: Vec<&String> = alerts
.iter()
.filter_map(|alert| match alert {
JobAlert::MonitorIncrement(increment) => Some(&increment.lines),
_ => None,
})
.flatten()
.collect();
assert!(
!lines.iter().any(|line| *line == "existing"),
"content written before the monitor started is not delivered: {lines:?}"
);
for expected in ["appended", "rotated", "after"] {
assert!(
lines.iter().any(|line| *line == expected),
"appended line {expected:?} is delivered, across rotation: {lines:?}"
);
}
tool.job_registry().kill_running().await;
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_runtime_writable_grant_reaches_new_commands_not_running_ones() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let outside = tempfile::tempdir().expect("outside dir should be created");
let late_target = outside.path().join("late.txt");
let task_id = start_background_job(
&tool,
&format!("sleep 2; echo x > '{}'", late_target.display()),
)
.await;
let receiver = tool.background_receiver();
assert_ne!(
exit_code_of(
&tool,
&format!("echo x > '{}'", outside.path().join("denied.txt").display())
)
.await,
0,
"a write outside the sandbox is denied before the grant"
);
tool.grants().add_writable(outside.path());
assert_eq!(
exit_code_of(
&tool,
&format!(
"echo x > '{}'",
outside.path().join("granted.txt").display()
)
)
.await,
0,
"the command after the grant writes the approved dir"
);
let completed = wait_for_completed_task(&receiver, &task_id).await;
let _ = completed.result;
assert!(
!late_target.exists(),
"a command launched before the grant keeps its launch grants"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_cloned_terminal_sees_runtime_grants() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let clone = tool.clone();
let outside = tempfile::tempdir().expect("outside dir should be created");
tool.grants().add_writable(outside.path());
assert_eq!(
exit_code_of(
&clone,
&format!("touch '{}'", outside.path().join("shared.txt").display())
)
.await,
0,
"the clone's commands carry grants added through the original"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagent_sees_runtime_readable_but_never_writable_parent_grants() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, parent) = authority_terminal(dir.path()).await;
let readable_dir = tempfile::tempdir().expect("readable dir");
let writable_dir = tempfile::tempdir().expect("writable dir");
std::fs::write(readable_dir.path().join("r.txt"), "data").unwrap();
std::fs::write(writable_dir.path().join("w.txt"), "data").unwrap();
let child = launch(&parent, SubagentGrant::new())
.await
.expect("subagent launches");
parent.grants().add_readable(readable_dir.path());
parent.grants().add_writable(writable_dir.path());
assert_eq!(
exit_code_of(
&child,
&format!("cat '{}'", readable_dir.path().join("r.txt").display())
)
.await,
0,
"a runtime readable grant on the parent reaches the subagent"
);
assert_ne!(
exit_code_of(
&child,
&format!("cat '{}'", writable_dir.path().join("w.txt").display())
)
.await,
0,
"a writable grant added after launch grants the parent's sandbox alone"
);
assert_ne!(
exit_code_of(
&child,
&format!("touch '{}'", writable_dir.path().join("x.txt").display())
)
.await,
0,
"a parent writable grant is never writable inside the subagent"
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_running_shell_keeps_the_grants_it_started_with() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let (_cache, tool) = authority_terminal(dir.path()).await;
let outside = tempfile::tempdir().expect("outside dir should be created");
let shell_target = outside.path().join("from_shell.txt");
let task_id = start_background_job(
&tool,
&format!("sleep 2; touch '{}'", shell_target.display()),
)
.await;
let receiver = tool.background_receiver();
tool.grants().add_writable(outside.path());
let fresh_target = outside.path().join("fresh.txt");
assert_eq!(
exit_code_of(&tool, &format!("touch '{}'", fresh_target.display())).await,
0,
"a fresh command picks up the grant"
);
let _ = wait_for_completed_task(&receiver, &task_id).await;
assert!(
!shell_target.exists(),
"the shell launched before the grant is still sandboxed without it"
);
}
}