Skip to main content

aither_sandbox/
terminal.rs

1//! Terminal command tool implementation with heel sandboxing.
2//!
3//! Provides the main `terminal` tool that LLMs use to execute terminal work.
4//! Despite the historical tool name, execution does not have to go through a
5//! literal `terminal` process: simple commands may be executed directly, while shell
6//! syntax falls back to a real shell when needed.
7//! Commands run in a sandbox with configurable permission modes.
8//!
9//! Each `TerminalTool` creates a shared working directory with four random words
10//! (e.g., `amber-forest-thunder-pearl/`). All terminal executions share this
11//! directory, but each execution gets a fresh sandbox (new TTY/process).
12
13use std::{
14    borrow::Cow,
15    io::{Read, Write},
16    net::{SocketAddr, TcpListener as StdTcpListener, TcpStream as StdTcpStream},
17    path::{Path, PathBuf},
18    process::Stdio,
19    sync::{
20        Arc,
21        atomic::{AtomicBool, AtomicUsize, Ordering},
22    },
23    time::Duration,
24};
25
26use aither_core::llm::ToolContext;
27use aither_core::llm::{IntoToolResult, Tool, ToolResult};
28use askama::Template;
29use async_channel::{Receiver, Sender};
30use async_io::Async;
31use executor_core::{Executor, Task};
32use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
33use heel::{
34    Access, AllowAll, Audited, CpuPriority, DomainRequest, Grant, IoPriority, IpcRouter,
35    NetworkAuditLog, NetworkPolicy, ProcessPriority, Sandbox, SandboxConfig, SecurityConfig,
36    StdioConfig, WorkingDir,
37};
38use schemars::JsonSchema;
39use serde::{Deserialize, Serialize};
40use shell_words::split as split_shell_words;
41use tracing::{debug, info, warn};
42
43use crate::{
44    ContainerPath, PreparedTools, ToolDistribution, ToolRuntimeError,
45    builtin::builtin_router,
46    command::ToolRegistry,
47    job_registry::{JobRegistry, job_registry_channel},
48    output::{
49        Content, INLINE_OUTPUT_LIMIT, MediaResolution, OutputEntry, OutputFormat, OutputStore,
50        save_raw_to_file,
51    },
52    permission::{PermissionError, PermissionHandler, TerminalMode},
53    shell_session::{
54        BridgeAddress, ContainerShellRuntime, ShellBackend, ShellRuntimeAvailability,
55        ShellSessionRegistry, SshRuntimeProfile,
56    },
57    stdin_watch::{
58        STDIN_WATCH_INTERVAL, TERMINAL_STDIN_BLOCKED_NOTICE, detect_stdin_blocked_for_local_pid,
59    },
60};
61
62fn erase_terminal_tool<T>(tool: T) -> crate::command::DynTerminalToolEntry
63where
64    T: Tool + 'static,
65{
66    use crate::command::{DynTerminalToolEntry, DynToolHandler};
67    use aither_core::llm::tool::ToolDefinition;
68
69    let definition = ToolDefinition::new(&tool);
70    let tool = Arc::new(tool);
71    let handler: DynToolHandler = Arc::new(move |args: &str, cx: ToolContext| {
72        let tool = tool.clone();
73        let args = args.to_string();
74        Box::pin(async move {
75            let parsed = match serde_json::from_str::<T::Arguments>(&args) {
76                Ok(parsed) => parsed,
77                Err(error) => return ToolResult::error(format!("Parse error: {error}")),
78            };
79            match tool.call(parsed, cx).await {
80                Ok(output) => output
81                    .into_tool_result()
82                    .unwrap_or_else(|error| ToolResult::error(format!("Error: {error}"))),
83                Err(error) => ToolResult::error(format!("Error: {error}")),
84            }
85        })
86    });
87
88    DynTerminalToolEntry {
89        definition,
90        handler,
91    }
92}
93
94/// Generate a random four-word ID (e.g., "amber-forest-thunder-pearl").
95fn random_task_id() -> String {
96    crate::naming::random_word_slug(4)
97}
98
99/// Opens a daily-rotated network audit log under `dir`, creating the directory if needed.
100///
101/// Keeps at most `max_files` rotated files. Attach the log with
102/// [`TerminalTool::with_network_audit_log`] to record every sandboxed
103/// network policy decision.
104///
105/// # Errors
106/// Returns an error when the directory cannot be created or the log cannot
107/// be opened.
108pub async fn open_network_audit_log(
109    dir: impl AsRef<Path>,
110    max_files: usize,
111) -> Result<NetworkAuditLog, TerminalError> {
112    let dir = dir.as_ref();
113    async_fs::create_dir_all(dir).await?;
114    NetworkAuditLog::rolling_daily(dir, max_files).map_err(|error| {
115        TerminalError::SandboxSetup(format!("failed to open network audit log: {error}"))
116    })
117}
118
119const fn supports_stdin_blocked_notice(backend: ShellBackend) -> bool {
120    matches!(backend, ShellBackend::Container)
121        || (cfg!(target_os = "linux") && matches!(backend, ShellBackend::Local))
122}
123
124#[derive(Clone)]
125struct PermissionNetworkPolicy<P> {
126    permission_handler: Arc<P>,
127}
128
129impl<P: PermissionHandler + 'static> NetworkPolicy for PermissionNetworkPolicy<P> {
130    async fn check(&self, request: &DomainRequest) -> bool {
131        self.permission_handler
132            .check_domain(request.host(), request.port())
133            .await
134    }
135}
136
137fn parse_direct_command(script: &str) -> Result<(String, Vec<String>), TerminalError> {
138    let parts = split_shell_words(script)
139        .map_err(|error| TerminalError::Execution(format!("failed to parse command: {error}")))?;
140    let Some((program, args)) = parts.split_first() else {
141        return Err(TerminalError::Execution(
142            "command must not be empty".to_string(),
143        ));
144    };
145    Ok((program.clone(), args.to_vec()))
146}
147
148enum TerminalLaunch {
149    Direct { program: String, args: Vec<String> },
150    Shell { program: String, args: Vec<String> },
151}
152
153fn script_requires_shell(script: &str) -> bool {
154    let mut in_single = false;
155    let mut in_double = false;
156    let mut escaped = false;
157
158    for ch in script.chars() {
159        if escaped {
160            escaped = false;
161            continue;
162        }
163
164        match ch {
165            '\\' if !in_single => escaped = true,
166            '\'' if !in_double => in_single = !in_single,
167            '"' if !in_single => in_double = !in_double,
168            '\n' | '\r' | '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '*' | '?' | '['
169            | ']' | '{' | '}' | '!' | '~'
170                if !in_single && !in_double =>
171            {
172                return true;
173            }
174            _ => {}
175        }
176    }
177
178    false
179}
180
181fn looks_like_env_assignment(token: &str) -> bool {
182    let Some((name, _value)) = token.split_once('=') else {
183        return false;
184    };
185    !name.is_empty() && name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
186}
187
188fn is_shell_builtin(program: &str) -> bool {
189    matches!(
190        program,
191        "alias"
192            | "bg"
193            | "break"
194            | "cd"
195            | "command"
196            | "continue"
197            | "eval"
198            | "exec"
199            | "exit"
200            | "export"
201            | "fg"
202            | "jobs"
203            | "read"
204            | "readonly"
205            | "return"
206            | "set"
207            | "shift"
208            | "source"
209            | "times"
210            | "trap"
211            | "type"
212            | "ulimit"
213            | "umask"
214            | "unalias"
215            | "unset"
216    )
217}
218
219fn shell_launch(script: &str) -> (String, Vec<String>) {
220    #[cfg(windows)]
221    {
222        let shell = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string());
223        return (shell, vec!["/C".to_string(), script.to_string()]);
224    }
225
226    #[cfg(not(windows))]
227    {
228        ("sh".to_string(), vec!["-c".to_string(), script.to_string()])
229    }
230}
231
232fn build_terminal_launch(script: &str) -> Result<TerminalLaunch, TerminalError> {
233    let script = script.trim();
234    if script.is_empty() {
235        return Err(TerminalError::Execution(
236            "command must not be empty".to_string(),
237        ));
238    }
239
240    if script_requires_shell(script) {
241        let (program, args) = shell_launch(script);
242        return Ok(TerminalLaunch::Shell { program, args });
243    }
244
245    let (program, args) = parse_direct_command(script)?;
246    if looks_like_env_assignment(&program) || is_shell_builtin(&program) {
247        let (program, args) = shell_launch(script);
248        return Ok(TerminalLaunch::Shell { program, args });
249    }
250
251    Ok(TerminalLaunch::Direct { program, args })
252}
253
254async fn ensure_mode_allowed<P: PermissionHandler>(
255    permission_handler: &P,
256    mode: TerminalMode,
257    script: &str,
258) -> Result<(), TerminalError> {
259    if !mode.requires_approval() {
260        return Ok(());
261    }
262
263    let allowed = permission_handler.check(mode, script).await?;
264    if allowed {
265        Ok(())
266    } else {
267        Err(TerminalError::PermissionDenied(mode))
268    }
269}
270
271/// Execute terminal commands in a sandboxed environment.
272///
273/// The primary interface to all system capabilities. Scripts run in a sandbox
274/// with full read access to the host filesystem but writes contained to a
275/// dedicated working directory.
276///
277/// ## Output Handling
278///
279/// By default, stdout is **compressed** before being returned. Compression
280/// is semantics-preserving: the meaning is identical to the raw output, but
281/// the representation may differ. Specifically:
282///
283/// - **JSON** outputs (arrays of objects or single objects) are automatically
284///   converted to **TSV** with dot-notation flattened column headers, but
285///   only when the TSV is smaller than the original JSON.
286/// - **Source code** outputs (detected via content analysis) are folded
287///   using syntax-aware block folding with line numbers. The full raw
288///   output is saved to a file whose URL is included in the result.
289/// - **Empty lines** and **invisible/control characters** are stripped.
290///
291/// If you need the exact verbatim output (e.g., for checksums, binary
292/// protocols, or diffing), either set `raw: true`, pipe through further
293/// processing in the script, or redirect to a file within the script.
294///
295/// Large outputs are automatically saved to file to manage context. When this
296/// happens, you receive the file path and can process it using standard Unix
297/// tools (head, tail, grep, less) or pipe through `ask` for summarization.
298///
299/// ## Built-in Commands
300///
301/// IPC-backed commands are configured by the host application and are exposed
302/// inside the terminal runtime as ordinary CLI commands. Inspect the
303/// application-provided command list and each command's `--help` output instead
304/// of assuming a fixed built-in command inventory.
305///
306/// ## Execution Modes
307///
308/// `terminal` is stateless. Each call selects its own runtime mode.
309#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
310pub struct TerminalArgs {
311    /// Short human-readable explanation of what this command is doing.
312    /// This is shown in the UI instead of echoing the shell source.
313    pub description: String,
314
315    /// The terminal command payload to execute.
316    pub script: String,
317
318    /// Runtime execution mode.
319    /// - "default": local runtime execution with network enabled
320    /// - "sandboxed": local runtime execution with network denied
321    /// - "unsafe": direct host execution (heel profile only)
322    /// - "ssh": execute on a preconfigured SSH server (`ssh_server_id` required when multiple are configured)
323    #[serde(default)]
324    pub mode: TerminalExecutionMode,
325
326    /// SSH server identifier used when `mode` is `ssh`.
327    /// Optional when exactly one SSH server is configured.
328    #[serde(default)]
329    pub ssh_server_id: Option<String>,
330
331    /// Expected output format for proper handling.
332    /// - "text" (default): plain text
333    /// - "image": image data (auto-loaded to context)
334    /// - "video": video data
335    /// - "binary": binary data
336    /// - "auto": auto-detect
337    #[serde(default)]
338    pub expect: OutputFormat,
339
340    /// Requested delivery resolution for media returned to the model.
341    /// - "auto" (default): preserve the source resolution
342    /// - "low": downscale to a 512px bounding box
343    /// - "medium": downscale to a 1024px bounding box
344    /// - "high": downscale to a 2048px bounding box
345    /// - "native": preserve original media bytes without resizing
346    #[serde(default)]
347    pub resolution: MediaResolution,
348
349    /// Per-command timeout in seconds.
350    /// - 0: run in background immediately
351    /// - >0: run foreground up to timeout, then move to background on timeout
352    pub timeout: u64,
353
354    /// Maximum number of output lines to include inline.
355    /// For foreground-complete executions, this is the inline line budget
356    /// before output offloads to file.
357    /// For timeout-promoted background executions, only the first `max_lines`
358    /// are returned immediately, while full output is redirected to file.
359    /// Clamped to 800 max.
360    /// Default: 200.
361    #[serde(default = "default_max_lines")]
362    pub max_lines: u32,
363
364    /// When true, skip all output compression and return the verbatim
365    /// stdout bytes. Use this when you need exact byte-level fidelity
366    /// (checksums, binary protocols, diff inputs). Default: false.
367    #[serde(default)]
368    pub raw: bool,
369}
370
371/// Requested terminal execution backend.
372#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
373#[serde(rename_all = "snake_case")]
374pub enum TerminalExecutionMode {
375    /// Use the tool default.
376    #[default]
377    Default,
378    /// Use the sandboxed backend.
379    Sandboxed,
380    /// Use unsafe local execution.
381    Unsafe,
382    /// Use SSH execution.
383    Ssh,
384}
385
386const fn default_max_lines() -> u32 {
387    200
388}
389
390const MAX_LINES_CEILING: u32 = 800;
391
392/// Why a foreground terminal command was promoted to the background.
393///
394/// Propagated to the UI so the background shelf can render a meaningful
395/// caption ("Promoted after 2s timeout" vs "Waiting for input" vs explicit).
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397#[serde(tag = "kind", rename_all = "snake_case")]
398pub enum BackgroundReason {
399    /// Exceeded the per-call foreground timeout budget.
400    Timeout {
401        /// Timeout in seconds as configured by the caller.
402        configured_seconds: u64,
403    },
404    /// stdin-blocked detector fired — process is waiting for input that
405    /// will not arrive via the foreground path.
406    StdinBlocked {
407        /// Human-readable notice from the detector, suitable for display.
408        notice: String,
409    },
410    /// Caller explicitly asked to run in the background (`timeout == 0`).
411    Explicit,
412}
413
414/// Result of a terminal execution.
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct TerminalResult {
417    /// stdout output.
418    pub stdout: OutputEntry,
419
420    /// stderr output (if non-empty).
421    #[serde(skip_serializing_if = "Option::is_none")]
422    pub stderr: Option<OutputEntry>,
423
424    /// Exit code of the script.
425    pub exit_code: i32,
426
427    /// Task ID for background execution.
428    /// Four random words like "amber-forest-thunder-pearl".
429    #[serde(skip_serializing_if = "Option::is_none")]
430    pub task_id: Option<String>,
431
432    /// Status for background tasks.
433    #[serde(skip_serializing_if = "Option::is_none")]
434    pub status: Option<String>,
435
436    /// Why the command was moved to the background (only populated when
437    /// `status == "running"`).
438    #[serde(skip_serializing_if = "Option::is_none")]
439    pub background_reason: Option<BackgroundReason>,
440}
441
442enum ForegroundDecision {
443    Completed(Box<Result<TerminalResult, String>>),
444    PromoteToBackground(BackgroundReason),
445}
446
447#[derive(Clone)]
448struct BackgroundStartup {
449    tx: async_channel::Sender<Result<(), String>>,
450    reported: Arc<AtomicBool>,
451}
452
453impl BackgroundStartup {
454    fn new(tx: async_channel::Sender<Result<(), String>>) -> Self {
455        Self {
456            tx,
457            reported: Arc::new(AtomicBool::new(false)),
458        }
459    }
460
461    async fn report_ready(&self) {
462        if self
463            .reported
464            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
465            .is_ok()
466        {
467            let _ = self.tx.send(Ok(())).await;
468        }
469    }
470
471    async fn report_failure(&self, error: &TerminalError) {
472        if self
473            .reported
474            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
475            .is_ok()
476        {
477            let _ = self.tx.send(Err(error.to_string())).await;
478        }
479    }
480}
481
482/// A completed background task result.
483#[derive(Debug)]
484pub struct CompletedTask {
485    /// The task ID (four random words like "amber-forest-thunder-pearl").
486    pub task_id: String,
487    /// The original script that was executed.
488    pub script: String,
489    /// The result of execution.
490    pub result: Result<TerminalResult, TerminalError>,
491}
492
493/// Stage of a permission-lifecycle event for `terminal`.
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub enum PermissionEventStage {
496    /// Permission request is waiting for a decision.
497    Waiting,
498    /// Permission request has been resolved.
499    Resolved,
500}
501
502/// Permission-lifecycle event emitted by `terminal` while waiting for approval.
503#[derive(Debug, Clone)]
504pub struct PermissionEvent {
505    /// Requested terminal mode.
506    pub mode: TerminalMode,
507    /// Script awaiting permission.
508    pub script: String,
509    /// Permission lifecycle stage.
510    pub stage: PermissionEventStage,
511}
512
513/// Receiver for completed background tasks.
514///
515/// This can be cloned and used independently of the `TerminalTool` to poll for
516/// completed background tasks. Multiple receivers share the same channel,
517/// so completed tasks are distributed among receivers.
518#[derive(Clone)]
519pub struct BackgroundTaskReceiver {
520    rx: Receiver<CompletedTask>,
521    running_tasks: Arc<AtomicUsize>,
522}
523
524impl BackgroundTaskReceiver {
525    /// Takes all completed background tasks without blocking.
526    ///
527    /// Returns an empty vector if no tasks have completed.
528    #[must_use]
529    pub fn take_completed(&self) -> Vec<CompletedTask> {
530        let mut completed = Vec::new();
531        while let Ok(task) = self.rx.try_recv() {
532            completed.push(task);
533        }
534        completed
535    }
536
537    /// Checks if there are any completed tasks waiting.
538    #[must_use]
539    pub fn has_completed(&self) -> bool {
540        !self.rx.is_empty()
541    }
542
543    /// Checks if there are any background tasks still running.
544    ///
545    /// This works by checking the sender count - `TerminalTool` holds one sender,
546    /// and each running background task holds a cloned sender.
547    #[must_use]
548    pub fn has_running(&self) -> bool {
549        self.running_tasks.load(Ordering::Acquire) > 0
550    }
551
552    /// Waits for the next completed task.
553    ///
554    /// Returns `None` if the channel is closed (all senders dropped).
555    pub async fn recv(&self) -> Option<CompletedTask> {
556        self.rx.recv().await.ok()
557    }
558
559    /// Waits for a completed task with a timeout.
560    ///
561    /// Returns `None` if no task completes within the timeout or if the channel is closed.
562    pub async fn recv_timeout(&self, duration: std::time::Duration) -> Option<CompletedTask> {
563        futures_lite::future::or(async { self.rx.recv().await.ok() }, async {
564            futures_lite::future::yield_now().await;
565            async_io::Timer::after(duration).await;
566            None
567        })
568        .await
569    }
570}
571
572impl std::fmt::Debug for BackgroundTaskReceiver {
573    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
574        f.debug_struct("BackgroundTaskReceiver")
575            .field("pending", &self.rx.len())
576            .field("running_tasks", &self.running_tasks.load(Ordering::Acquire))
577            .finish()
578    }
579}
580
581/// Receiver for permission wait/resume events.
582#[derive(Clone)]
583pub struct PermissionEventReceiver {
584    rx: Receiver<PermissionEvent>,
585}
586
587impl PermissionEventReceiver {
588    /// Takes pending permission events without blocking.
589    #[must_use]
590    pub fn take_pending(&self) -> Vec<PermissionEvent> {
591        let mut events = Vec::new();
592        while let Ok(event) = self.rx.try_recv() {
593            events.push(event);
594        }
595        events
596    }
597
598    /// Waits for the next permission event.
599    pub async fn recv(&self) -> Option<PermissionEvent> {
600        self.rx.recv().await.ok()
601    }
602}
603
604impl std::fmt::Debug for PermissionEventReceiver {
605    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
606        f.debug_struct("PermissionEventReceiver")
607            .field("pending", &self.rx.len())
608            .finish()
609    }
610}
611
612/// Factory for creating child terminal tools asynchronously.
613#[derive(Clone, Debug)]
614pub struct TerminalToolFactory {
615    tx: Sender<Sender<crate::command::DynTerminalTool>>,
616}
617
618/// Receiver that serves terminal tool creation requests.
619#[derive(Debug)]
620pub struct TerminalToolFactoryReceiver {
621    rx: Receiver<Sender<crate::command::DynTerminalTool>>,
622}
623
624/// Errors that can occur when requesting a child terminal tool.
625#[derive(Debug, thiserror::Error)]
626pub enum TerminalToolFactoryError {
627    /// The factory service is not running.
628    #[error("terminal tool factory is not available")]
629    Unavailable,
630    /// The factory failed to return a tool.
631    #[error("terminal tool factory failed to return a tool")]
632    NoResponse,
633}
634
635/// Creates a factory channel pair for spawning child terminal tools.
636#[must_use]
637pub fn terminal_tool_factory_channel() -> (TerminalToolFactory, TerminalToolFactoryReceiver) {
638    let (tx, rx) = async_channel::unbounded();
639    (
640        TerminalToolFactory { tx },
641        TerminalToolFactoryReceiver { rx },
642    )
643}
644
645impl TerminalToolFactory {
646    /// Requests a new child terminal tool from the factory service.
647    ///
648    /// # Errors
649    /// Returns an error when the factory service is unavailable or does not respond.
650    pub async fn create(
651        &self,
652    ) -> Result<crate::command::DynTerminalTool, TerminalToolFactoryError> {
653        let (reply_tx, reply_rx) = async_channel::bounded(1);
654        self.tx
655            .send(reply_tx)
656            .await
657            .map_err(|_| TerminalToolFactoryError::Unavailable)?;
658        reply_rx
659            .recv()
660            .await
661            .map_err(|_| TerminalToolFactoryError::NoResponse)
662    }
663}
664
665impl TerminalToolFactoryReceiver {
666    async fn serve<P, E>(self, terminal_tool: TerminalTool<P, E, Configured>)
667    where
668        P: PermissionHandler + 'static,
669        E: Executor + Clone + 'static,
670    {
671        while let Ok(reply_tx) = self.rx.recv().await {
672            let tool = terminal_tool.child().to_dyn();
673            if reply_tx.send(tool).await.is_err() {
674                warn!("terminal tool factory response channel dropped");
675            }
676        }
677    }
678}
679
680/// The terminal tool for executing scripts in a sandbox.
681///
682/// Creates a shared working directory with four random words that persists
683/// across all executions. Each execution creates a fresh sandbox but shares
684/// the working directory.
685///
686/// The executor type `E` determines how async tasks are spawned for the IPC server.
687/// Use `TokioExecutor` when running in a tokio runtime.
688/// Marker type for a terminal tool without a configured registry.
689#[derive(Clone, Debug)]
690pub struct Unconfigured;
691
692/// Marker type for a terminal tool with a configured registry.
693#[derive(Clone, Debug)]
694pub struct Configured {
695    registry: Arc<ToolRegistry>,
696}
697
698/// Registry state that can be rebound to a different job registry.
699///
700/// Sealed: declared `pub` only so it may bound the public `TerminalTool`
701/// impl; it lives in this private module and is not re-exported.
702pub trait RegistryState: Clone {
703    /// Returns this state with its terminal controls bound to `jobs`.
704    fn for_jobs(&self, jobs: JobRegistry, output_dir: PathBuf) -> Self;
705}
706
707impl RegistryState for Unconfigured {
708    fn for_jobs(&self, _jobs: JobRegistry, _output_dir: PathBuf) -> Self {
709        Self
710    }
711}
712
713impl RegistryState for Configured {
714    fn for_jobs(&self, jobs: JobRegistry, output_dir: PathBuf) -> Self {
715        Self {
716            registry: Arc::new(
717                ToolRegistry::clone(&self.registry).with_terminal_controls(jobs, output_dir),
718            ),
719        }
720    }
721}
722
723/// The terminal tool for executing scripts in a sandbox.
724pub struct TerminalTool<P, E, State = Unconfigured> {
725    /// Shared working directory (four random words, e.g., `amber-forest-thunder-pearl/`)
726    working_dir: PathBuf,
727    /// Runtime registry for container and ssh execution metadata.
728    shell_sessions: ShellSessionRegistry,
729    /// Permission handler wrapped in Arc for sharing between parent and child tools.
730    permission_handler: Arc<P>,
731    executor: E,
732    output_store: Arc<OutputStore>,
733    job_registry: JobRegistry,
734    /// Channel for receiving completed background tasks.
735    completed_rx: Receiver<CompletedTask>,
736    /// Channel for sending completed background tasks (cloned for each background task).
737    completed_tx: Sender<CompletedTask>,
738    /// Number of still-running spawned executions associated with this tool.
739    running_tasks: Arc<AtomicUsize>,
740    /// Channel for permission lifecycle events.
741    permission_rx: Receiver<PermissionEvent>,
742    /// Channel sender for permission lifecycle events.
743    permission_tx: Sender<PermissionEvent>,
744    /// Additional paths that should be writable in the sandbox.
745    writable_paths: Vec<PathBuf>,
746    /// Additional paths that should be readable (but not writable) in the sandbox.
747    readable_paths: Vec<PathBuf>,
748    /// Rolling audit log recording every sandboxed network policy decision.
749    network_audit: Option<NetworkAuditLog>,
750    /// Scheduling priority applied to every sandboxed execution.
751    priority: ProcessPriority,
752    /// Tool registry state.
753    registry: State,
754}
755
756// Manual Clone impl because P doesn't need to be Clone (we use Arc<P>)
757impl<P, E: Clone, State: Clone> Clone for TerminalTool<P, E, State> {
758    fn clone(&self) -> Self {
759        Self {
760            working_dir: self.working_dir.clone(),
761            shell_sessions: self.shell_sessions.clone(),
762            permission_handler: self.permission_handler.clone(),
763            executor: self.executor.clone(),
764            output_store: self.output_store.clone(),
765            job_registry: self.job_registry.clone(),
766            completed_rx: self.completed_rx.clone(),
767            completed_tx: self.completed_tx.clone(),
768            running_tasks: self.running_tasks.clone(),
769            permission_rx: self.permission_rx.clone(),
770            permission_tx: self.permission_tx.clone(),
771            writable_paths: self.writable_paths.clone(),
772            readable_paths: self.readable_paths.clone(),
773            network_audit: self.network_audit.clone(),
774            priority: self.priority,
775            registry: self.registry.clone(),
776        }
777    }
778}
779
780impl<P, E: Executor + Clone + 'static> TerminalTool<P, E, Unconfigured> {
781    /// Injects the runtime configuration used by `terminal` execution mode resolution.
782    ///
783    /// The registry is configuration to prepare with [`Self::initialize_tools`];
784    /// a registry that is already prepared is installed with
785    /// [`Self::adopt_prepared_tools`], which checks it against this terminal.
786    ///
787    /// # Panics
788    /// Panics if `sessions` is already prepared.
789    #[must_use]
790    pub fn with_shell_sessions(mut self, sessions: ShellSessionRegistry) -> Self {
791        assert!(
792            sessions.prepared_tools.is_none(),
793            "a prepared shell session registry is installed with adopt_prepared_tools"
794        );
795        self.shell_sessions = sessions;
796        self
797    }
798
799    /// Sets dynamic runtime availability for terminal execution.
800    #[must_use]
801    pub fn with_shell_runtime_availability(
802        mut self,
803        availability: crate::shell_session::ShellRuntimeAvailability,
804    ) -> Self {
805        self.shell_sessions = self.shell_sessions.with_availability(availability);
806        self
807    }
808
809    /// Adds container runtime metadata for container-backed terminal execution.
810    #[must_use]
811    pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
812        self.shell_sessions = self.shell_sessions.with_container_runtime(runtime);
813        self
814    }
815
816    /// Records every sandboxed network policy decision — allowed or denied —
817    /// into the given rolling audit log.
818    #[must_use]
819    pub fn with_network_audit_log(mut self, log: NetworkAuditLog) -> Self {
820        self.network_audit = Some(log);
821        self
822    }
823
824    /// Creates a new terminal tool with permission handler and executor.
825    ///
826    /// Creates a random four-word working directory under the specified parent directory.
827    /// The executor is used to spawn async tasks for the IPC server.
828    ///
829    /// # Errors
830    /// Returns an error when the working directory or output store cannot be created.
831    pub async fn new_in(
832        parent_dir: impl AsRef<std::path::Path>,
833        permission_handler: P,
834        executor: E,
835    ) -> Result<Self, TerminalError> {
836        let parent_dir = parent_dir.as_ref();
837
838        // Ensure parent directory exists
839        async_fs::create_dir_all(parent_dir).await?;
840
841        // Create random four-word working directory
842        let working_dir = WorkingDir::random_in(parent_dir).map_err(|e| {
843            TerminalError::SandboxSetup(format!("failed to create working dir: {e}"))
844        })?;
845        let working_dir_path = working_dir.path().to_path_buf();
846
847        info!(working_dir = %working_dir_path.display(), "created terminal tool working directory");
848
849        // Create outputs directory inside working dir
850        let outputs_dir = working_dir_path.join("outputs");
851        async_fs::create_dir_all(&outputs_dir).await?;
852
853        // Create output store
854        let output_store = Arc::new(OutputStore::new(&outputs_dir).await?);
855
856        // Start job registry service
857        let (job_registry, job_registry_service) = job_registry_channel();
858        executor
859            .spawn(async move { job_registry_service.serve().await })
860            .detach();
861
862        // Create channel for background task completion (unbounded to not block spawned tasks)
863        let (completed_tx, completed_rx) = async_channel::unbounded();
864        let running_tasks = Arc::new(AtomicUsize::new(0));
865        let (permission_tx, permission_rx) = async_channel::unbounded();
866
867        Ok(Self {
868            working_dir: working_dir_path,
869            shell_sessions: ShellSessionRegistry::new(ShellRuntimeAvailability::default()),
870            permission_handler: Arc::new(permission_handler),
871            executor,
872            output_store,
873            job_registry,
874            completed_rx,
875            completed_tx,
876            running_tasks,
877            permission_rx,
878            permission_tx,
879            writable_paths: Vec::new(),
880            readable_paths: Vec::new(),
881            network_audit: None,
882            priority: ProcessPriority::default(),
883            registry: Unconfigured,
884        })
885    }
886
887    /// Creates a new terminal tool with permission handler and executor,
888    /// using the provided directory directly as the working directory.
889    ///
890    /// Unlike `new_in` which creates a random subdirectory, this method
891    /// uses the exact path provided. Use this when you want explicit control
892    /// over the working directory location.
893    ///
894    /// # Errors
895    /// Returns an error when the working directory or output store cannot be created.
896    pub async fn new_exact(
897        working_dir: impl AsRef<std::path::Path>,
898        permission_handler: P,
899        executor: E,
900    ) -> Result<Self, TerminalError> {
901        let working_dir_path = working_dir.as_ref().to_path_buf();
902
903        // Ensure working directory exists
904        async_fs::create_dir_all(&working_dir_path).await?;
905
906        // Create outputs directory inside working dir
907        let outputs_dir = working_dir_path.join("outputs");
908        async_fs::create_dir_all(&outputs_dir).await?;
909
910        // Create output store
911        let output_store = Arc::new(OutputStore::new(&outputs_dir).await?);
912
913        // Start job registry service
914        let (job_registry, job_registry_service) = job_registry_channel();
915        executor
916            .spawn(async move { job_registry_service.serve().await })
917            .detach();
918
919        // Create channel for background task completion (unbounded to not block spawned tasks)
920        let (completed_tx, completed_rx) = async_channel::unbounded();
921        let running_tasks = Arc::new(AtomicUsize::new(0));
922        let (permission_tx, permission_rx) = async_channel::unbounded();
923
924        Ok(Self {
925            working_dir: working_dir_path,
926            shell_sessions: ShellSessionRegistry::new(ShellRuntimeAvailability::default()),
927            permission_handler: Arc::new(permission_handler),
928            executor,
929            output_store,
930            job_registry,
931            completed_rx,
932            completed_tx,
933            running_tasks,
934            permission_rx,
935            permission_tx,
936            writable_paths: Vec::new(),
937            readable_paths: Vec::new(),
938            network_audit: None,
939            priority: ProcessPriority::default(),
940            registry: Unconfigured,
941        })
942    }
943
944    /// Attaches a tool registry to this terminal tool, enabling IPC command dispatch.
945    #[must_use]
946    pub fn with_registry(self, registry: Arc<ToolRegistry>) -> TerminalTool<P, E, Configured> {
947        let registry = Arc::new(
948            Arc::unwrap_or_clone(registry)
949                .with_terminal_controls(self.job_registry(), self.outputs_dir()),
950        );
951        TerminalTool {
952            working_dir: self.working_dir,
953            shell_sessions: self.shell_sessions,
954            permission_handler: self.permission_handler,
955            executor: self.executor,
956            output_store: self.output_store,
957            job_registry: self.job_registry,
958            completed_rx: self.completed_rx,
959            completed_tx: self.completed_tx,
960            running_tasks: self.running_tasks,
961            permission_rx: self.permission_rx,
962            permission_tx: self.permission_tx,
963            writable_paths: self.writable_paths,
964            readable_paths: self.readable_paths,
965            network_audit: self.network_audit,
966            priority: self.priority,
967            registry: Configured { registry },
968        }
969    }
970}
971
972impl<P, E, State> TerminalTool<P, E, State>
973where
974    E: Executor + Clone + 'static,
975    State: Clone,
976{
977    /// Adds additional writable paths to the sandbox configuration.
978    ///
979    /// These paths will be writable in sandboxed and network modes.
980    #[must_use]
981    pub fn with_writable_paths(
982        mut self,
983        paths: impl IntoIterator<Item = impl Into<PathBuf>>,
984    ) -> Self {
985        self.writable_paths
986            .extend(paths.into_iter().map(Into::into));
987        self
988    }
989
990    /// Adds additional readable (but not writable) paths to the sandbox configuration.
991    ///
992    /// These paths will be readable in all sandbox modes, even in strict
993    /// filesystem mode where reads outside the sandbox are normally denied.
994    #[must_use]
995    pub fn with_readable_paths(
996        mut self,
997        paths: impl IntoIterator<Item = impl Into<PathBuf>>,
998    ) -> Self {
999        self.readable_paths
1000            .extend(paths.into_iter().map(Into::into));
1001        self
1002    }
1003
1004    /// Lowers the scheduling priority of the commands this tool runs.
1005    ///
1006    /// The priority is applied to every sandbox the tool creates — one-shot
1007    /// commands, persistent shell sessions and background jobs — and is
1008    /// inherited by everything they spawn. Container executions run the script
1009    /// through the image's own `heel run`, so the image needs a `heel` binary
1010    /// when a non-normal priority is configured. SSH executions are not
1011    /// affected: the remote host runs its own `heel`, managed outside this
1012    /// configuration.
1013    #[must_use]
1014    pub const fn with_process_priority(mut self, priority: ProcessPriority) -> Self {
1015        self.priority = priority;
1016        self
1017    }
1018
1019    /// Initializes tools before agent construction or command execution.
1020    ///
1021    /// # Errors
1022    /// Rejects preparation failures and writable grants that expose managed tools.
1023    pub async fn initialize_tools(
1024        mut self,
1025        distribution: &ToolDistribution,
1026        cache_root: &Path,
1027    ) -> Result<Self, ToolRuntimeError>
1028    where
1029        P: PermissionHandler,
1030        State: Send,
1031    {
1032        self.shell_sessions = self
1033            .shell_sessions
1034            .initialize_tools(distribution, cache_root)
1035            .await?;
1036        if let Some(tools) = self.local_home_tools()? {
1037            tools.ensure_readonly(self.writable_grants()).await?;
1038            tools.verify_local_versions(self.executor.clone()).await?;
1039        }
1040        Ok(self)
1041    }
1042
1043    /// Adopts a registry that [`Self::initialize_tools`] already prepared for
1044    /// another terminal.
1045    ///
1046    /// Only the checks that depend on this terminal run again: its working
1047    /// directory and writable paths must not expose the managed tool
1048    /// directory. Artifact downloads, integrity hashing, version probes and SSH
1049    /// bootstrap — with its connection consent — are not repeated.
1050    ///
1051    /// # Errors
1052    /// Rejects a registry that is not prepared, one whose home backend,
1053    /// container or SSH server set changed after preparation, and writable
1054    /// grants that expose the managed tools.
1055    pub async fn adopt_prepared_tools(
1056        mut self,
1057        sessions: ShellSessionRegistry,
1058    ) -> Result<Self, ToolRuntimeError>
1059    where
1060        P: PermissionHandler,
1061        State: Send,
1062    {
1063        sessions.prepared_catalog()?;
1064        self.shell_sessions = sessions;
1065        if let Some(tools) = self.local_home_tools()? {
1066            tools.ensure_readonly(self.writable_grants()).await?;
1067        }
1068        Ok(self)
1069    }
1070
1071    /// Prepared tools of the local home backend, when this terminal runs on it.
1072    fn local_home_tools(&self) -> Result<Option<&PreparedTools<PathBuf>>, ToolRuntimeError> {
1073        match self.shell_sessions.resolve_local_backend() {
1074            Ok(ShellBackend::Local) => self.shell_sessions.local_tools().map(Some),
1075            _ => Ok(None),
1076        }
1077    }
1078
1079    /// The paths this terminal grants write access to, which must not expose
1080    /// the managed tools.
1081    fn writable_grants(&self) -> impl Iterator<Item = &PathBuf> + Send {
1082        std::iter::once(&self.working_dir).chain(self.writable_paths.iter())
1083    }
1084
1085    /// Initialized session configuration shared with child terminals.
1086    #[must_use]
1087    pub const fn shell_sessions(&self) -> &ShellSessionRegistry {
1088        &self.shell_sessions
1089    }
1090
1091    /// Operational context from successfully initialized environments.
1092    ///
1093    /// # Errors
1094    /// Fails when no tools are prepared or a backend configuration has changed.
1095    pub fn prepared_tools_context(&self) -> Result<String, ToolRuntimeError> {
1096        self.shell_sessions.prepared_catalog()?.render()
1097    }
1098
1099    /// Returns the working directory path.
1100    pub const fn working_dir(&self) -> &PathBuf {
1101        &self.working_dir
1102    }
1103
1104    /// Returns the outputs directory path.
1105    pub fn outputs_dir(&self) -> PathBuf {
1106        self.working_dir.join("outputs")
1107    }
1108
1109    /// Returns the output store.
1110    pub const fn output_store(&self) -> &Arc<OutputStore> {
1111        &self.output_store
1112    }
1113
1114    /// Returns the job registry handle.
1115    pub fn job_registry(&self) -> JobRegistry {
1116        self.job_registry.clone()
1117    }
1118
1119    /// Returns a receiver for completed background tasks.
1120    ///
1121    /// The returned `BackgroundTaskReceiver` can be used independently of the `TerminalTool`
1122    /// to poll for completed background tasks. This is useful for integrating with
1123    /// the Agent's main loop.
1124    pub fn background_receiver(&self) -> BackgroundTaskReceiver {
1125        BackgroundTaskReceiver {
1126            rx: self.completed_rx.clone(),
1127            running_tasks: self.running_tasks.clone(),
1128        }
1129    }
1130
1131    /// Returns a receiver for permission lifecycle events.
1132    pub fn permission_receiver(&self) -> PermissionEventReceiver {
1133        PermissionEventReceiver {
1134            rx: self.permission_rx.clone(),
1135        }
1136    }
1137
1138    /// Takes all completed background tasks without blocking.
1139    ///
1140    /// Returns an empty vector if no tasks have completed.
1141    /// The agent should call this after each turn to check for completed background tasks.
1142    pub fn take_completed(&self) -> Vec<CompletedTask> {
1143        let mut completed = Vec::new();
1144        while let Ok(task) = self.completed_rx.try_recv() {
1145            completed.push(task);
1146        }
1147        completed
1148    }
1149
1150    /// Checks if there are any pending background tasks.
1151    pub fn has_pending_tasks(&self) -> bool {
1152        !self.completed_rx.is_empty() || self.running_tasks.load(Ordering::Acquire) > 0
1153    }
1154}
1155
1156impl<P, E, State> TerminalTool<P, E, State>
1157where
1158    E: Executor + Clone + 'static,
1159    State: RegistryState,
1160{
1161    /// Creates a child `TerminalTool` that shares the same sandbox and permission handler
1162    /// but has independent background task tracking.
1163    ///
1164    /// Use this to create terminal tools for subagents that:
1165    /// - Share the same working directory and output store
1166    /// - Share the same permission handler (security policies enforced consistently)
1167    /// - Have independent completion channels (no message mixup)
1168    #[must_use]
1169    pub fn child(&self) -> Self {
1170        let (completed_tx, completed_rx) = async_channel::unbounded();
1171        let running_tasks = Arc::new(AtomicUsize::new(0));
1172        let (permission_tx, permission_rx) = async_channel::unbounded();
1173        let (job_registry, job_registry_service) = job_registry_channel();
1174        self.executor
1175            .spawn(async move { job_registry_service.serve().await })
1176            .detach();
1177        Self {
1178            working_dir: self.working_dir.clone(),
1179            shell_sessions: self.shell_sessions.clone(),
1180            permission_handler: self.permission_handler.clone(), // Arc clone - shares handler
1181            executor: self.executor.clone(),
1182            output_store: self.output_store.clone(),
1183            completed_rx,
1184            completed_tx,
1185            running_tasks,
1186            permission_rx,
1187            permission_tx,
1188            writable_paths: self.writable_paths.clone(),
1189            readable_paths: self.readable_paths.clone(),
1190            network_audit: self.network_audit.clone(),
1191            priority: self.priority,
1192            registry: self
1193                .registry
1194                .for_jobs(job_registry.clone(), self.outputs_dir()),
1195            job_registry,
1196        }
1197    }
1198}
1199
1200impl<P, E> TerminalTool<P, E, Configured>
1201where
1202    P: PermissionHandler + 'static,
1203    E: Executor + Clone + 'static,
1204{
1205    const fn registry(&self) -> &Arc<ToolRegistry> {
1206        &self.registry.registry
1207    }
1208
1209    /// Starts a background service that produces child terminal tools on demand.
1210    pub fn start_factory_service(&self, receiver: TerminalToolFactoryReceiver) {
1211        let tool = self.clone();
1212        self.executor
1213            .spawn(async move { receiver.serve(tool).await })
1214            .detach();
1215    }
1216
1217    /// Converts this `TerminalTool` into a type-erased `DynTerminalTool`.
1218    ///
1219    /// This is useful for creating child terminal tools for subagents where
1220    /// the concrete type cannot be known at compile time.
1221    ///
1222    /// # Panics
1223    /// Panics when execution environments have not completed tool initialization.
1224    pub fn to_dyn(self) -> crate::command::DynTerminalTool {
1225        use crate::command::DynTerminalTool;
1226
1227        let background_receiver = self.background_receiver();
1228        let permission_receiver = self.permission_receiver();
1229        let job_registry = self.job_registry();
1230        let working_dir = self.working_dir().clone();
1231        let command_names = self.registry().registered_tool_names();
1232        let prepared_tools = self
1233            .shell_sessions
1234            .prepared_catalog()
1235            .expect("terminal tools must be initialized before exposing child capabilities")
1236            .clone();
1237        let entries = vec![erase_terminal_tool(self)];
1238
1239        DynTerminalTool {
1240            entries,
1241            background_receiver,
1242            permission_receiver,
1243            job_registry,
1244            working_dir,
1245            command_names,
1246            prepared_tools,
1247        }
1248    }
1249
1250    fn resolve_execution_target(
1251        &self,
1252        arguments: &TerminalArgs,
1253    ) -> Result<ExecutionTarget, TerminalError> {
1254        match arguments.mode {
1255            TerminalExecutionMode::Default => self.resolve_default_target(),
1256            TerminalExecutionMode::Sandboxed => self.resolve_home_target(TerminalMode::Sandboxed),
1257            TerminalExecutionMode::Unsafe => self.resolve_home_target(TerminalMode::Unsafe),
1258            TerminalExecutionMode::Ssh => {
1259                self.resolve_ssh_target(arguments.ssh_server_id.as_deref())
1260            }
1261        }
1262    }
1263
1264    fn resolve_default_target(&self) -> Result<ExecutionTarget, TerminalError> {
1265        if self.shell_sessions.resolve_local_backend().is_ok() {
1266            self.resolve_home_target(TerminalMode::Sandboxed)
1267        } else {
1268            self.resolve_ssh_target(None)
1269        }
1270    }
1271
1272    fn resolve_home_target(&self, mode: TerminalMode) -> Result<ExecutionTarget, TerminalError> {
1273        let backend = self
1274            .shell_sessions
1275            .resolve_local_backend()
1276            .map_err(TerminalError::InvalidTarget)?;
1277        if mode == TerminalMode::Unsafe && backend != ShellBackend::Local {
1278            return Err(TerminalError::InvalidTarget(
1279                "unsafe mode is only available in heel local runtime".into(),
1280            ));
1281        }
1282        let backend = match backend {
1283            ShellBackend::Local => {
1284                ExecutionBackend::Local(self.shell_sessions.local_tools()?.clone())
1285            }
1286            ShellBackend::Container => ExecutionBackend::Container {
1287                runtime: self
1288                    .shell_sessions
1289                    .container_runtime()
1290                    .cloned()
1291                    .ok_or(ToolRuntimeError::MissingContainerRuntime)?,
1292                tools: self.shell_sessions.container_tools()?.clone(),
1293            },
1294            ShellBackend::Ssh => unreachable!("the home backend is never SSH"),
1295        };
1296        Ok(ExecutionTarget { mode, backend })
1297    }
1298
1299    fn resolve_ssh_target(
1300        &self,
1301        ssh_server_id: Option<&str>,
1302    ) -> Result<ExecutionTarget, TerminalError> {
1303        self.shell_sessions
1304            .ensure_ssh_available()
1305            .map_err(TerminalError::InvalidTarget)?;
1306        let server = ssh_server_id
1307            .map_or_else(
1308                || self.shell_sessions.default_ssh_server(),
1309                |id| self.shell_sessions.resolve_ssh_server(id),
1310            )
1311            .map_err(TerminalError::InvalidTarget)?;
1312        let (runtime, tools) = self.shell_sessions.ssh_tools(&server)?;
1313        Ok(ExecutionTarget {
1314            mode: TerminalMode::Sandboxed,
1315            backend: ExecutionBackend::Ssh {
1316                target: server.target,
1317                runtime: runtime.clone(),
1318                tools: tools.clone(),
1319            },
1320        })
1321    }
1322
1323    async fn ensure_permission_allowed(
1324        &self,
1325        mode: TerminalMode,
1326        script: &str,
1327    ) -> anyhow::Result<()> {
1328        let permission_waits = self
1329            .permission_handler
1330            .will_wait_for_approval(mode, script)
1331            .await;
1332        if permission_waits {
1333            self.emit_permission_event(mode, script, PermissionEventStage::Waiting)
1334                .await;
1335        }
1336        let permission_result =
1337            ensure_mode_allowed(self.permission_handler.as_ref(), mode, script).await;
1338        if permission_waits {
1339            self.emit_permission_event(mode, script, PermissionEventStage::Resolved)
1340                .await;
1341        }
1342        permission_result.map_err(anyhow::Error::new)
1343    }
1344
1345    async fn emit_permission_event(
1346        &self,
1347        mode: TerminalMode,
1348        script: &str,
1349        stage: PermissionEventStage,
1350    ) {
1351        let _ = self
1352            .permission_tx
1353            .send(PermissionEvent {
1354                mode,
1355                script: script.to_string(),
1356                stage,
1357            })
1358            .await;
1359    }
1360
1361    fn spawn_terminal_execution(&self, request: TerminalSpawnRequest) -> SpawnedTerminal {
1362        let TerminalSpawnRequest {
1363            target,
1364            task_id,
1365            execution_id,
1366            script,
1367            expect,
1368            resolution,
1369            max_lines,
1370            raw,
1371            timeout,
1372        } = request;
1373        let ExecutionTarget { mode, backend } = target;
1374        let (result_tx, result_rx) = async_channel::bounded(1);
1375        let (startup_tx, startup_rx) = async_channel::bounded(1);
1376        let (stdin_blocked_tx, stdin_blocked_rx) = async_channel::bounded(1);
1377        let background_mode = Arc::new(AtomicBool::new(timeout == 0));
1378        let stdin_blocked_notice = if supports_stdin_blocked_notice(backend.kind()) {
1379            Some(stdin_blocked_tx)
1380        } else {
1381            None
1382        };
1383
1384        let background_startup = BackgroundStartup::new(startup_tx);
1385        let background_mode_for_spawn = background_mode.clone();
1386        let background_mode_for_completion = background_mode.clone();
1387        let running_tasks = self.running_tasks.clone();
1388        let completed_tx = self.completed_tx.clone();
1389
1390        running_tasks.fetch_add(1, Ordering::AcqRel);
1391        self.executor
1392            .spawn(execute_terminal_task(SpawnedTerminalTask {
1393                working_dir: self.working_dir.clone(),
1394                writable_paths: self.writable_paths.clone(),
1395                readable_paths: self.readable_paths.clone(),
1396                executor: self.executor.clone(),
1397                registry: self.registry().clone(),
1398                permission_handler: self.permission_handler.clone(),
1399                job_registry: self.job_registry.clone(),
1400                task_id,
1401                execution_id,
1402                background_mode: background_mode_for_spawn,
1403                script,
1404                mode,
1405                backend,
1406                stdin_blocked_notice,
1407                background_startup,
1408                expect,
1409                resolution,
1410                store_dir: self.output_store.dir().to_path_buf(),
1411                max_lines,
1412                raw,
1413                result_tx,
1414                completed_tx,
1415                background_mode_for_completion,
1416                running_tasks,
1417                network_audit: self.network_audit.clone(),
1418                priority: self.priority,
1419            }))
1420            .detach();
1421
1422        SpawnedTerminal {
1423            result_rx,
1424            startup_rx,
1425            stdin_blocked_rx,
1426            background_mode,
1427        }
1428    }
1429}
1430
1431impl<P: PermissionHandler + 'static, E: Executor + Clone + 'static> Tool
1432    for TerminalTool<P, E, Configured>
1433{
1434    fn name(&self) -> Cow<'static, str> {
1435        "terminal".into()
1436    }
1437
1438    type Arguments = TerminalArgs;
1439    type Res = ToolResult;
1440
1441    async fn call(
1442        &self,
1443        arguments: Self::Arguments,
1444        _cx: ToolContext,
1445    ) -> aither_core::Result<Self::Res> {
1446        if arguments.description.trim().is_empty() {
1447            return Err(anyhow::anyhow!("terminal description must not be empty"));
1448        }
1449        let task_id = random_task_id();
1450        let script = arguments.script.clone();
1451        let execution_id = format!("exec-{task_id}");
1452        let expect = arguments.expect;
1453        let resolution = arguments.resolution;
1454        let max_lines = arguments.max_lines.min(MAX_LINES_CEILING) as usize;
1455        let raw = arguments.raw;
1456        let timeout = arguments.timeout;
1457
1458        let target = self.resolve_execution_target(&arguments)?;
1459        if let ExecutionBackend::Local(tools) = &target.backend {
1460            tools
1461                .ensure_readonly(
1462                    std::iter::once(&self.working_dir).chain(self.writable_paths.iter()),
1463                )
1464                .await?;
1465        }
1466        self.ensure_permission_allowed(target.mode, &script).await?;
1467        let store_dir = self.output_store.dir().to_path_buf();
1468        let spawned = self.spawn_terminal_execution(TerminalSpawnRequest {
1469            target,
1470            task_id: task_id.clone(),
1471            execution_id,
1472            script,
1473            expect,
1474            resolution,
1475            max_lines,
1476            raw,
1477            timeout,
1478        });
1479
1480        if timeout == 0 {
1481            let reason = BackgroundReason::Explicit;
1482            wait_for_background_startup(&spawned.startup_rx).await?;
1483            return background_terminal_result(
1484                &self.job_registry,
1485                &store_dir,
1486                &task_id,
1487                max_lines,
1488                reason,
1489            )
1490            .await;
1491        }
1492
1493        let configured_timeout_seconds = timeout;
1494        let immediate = wait_for_foreground_decision(
1495            &spawned.result_rx,
1496            &spawned.stdin_blocked_rx,
1497            timeout,
1498            configured_timeout_seconds,
1499        )
1500        .await;
1501
1502        let (reason, pre_registered) = match immediate {
1503            Some(ForegroundDecision::Completed(result)) => match *result {
1504                Ok(mut result) => {
1505                    result.task_id = None;
1506                    result.status = None;
1507                    result.background_reason = None;
1508                    return ToolResult::json(&result);
1509                }
1510                Err(err) => return Err(anyhow::anyhow!(err)),
1511            },
1512            Some(ForegroundDecision::PromoteToBackground(reason)) => (reason, false),
1513            None => (BackgroundReason::Explicit, false),
1514        };
1515
1516        tracing::info!(
1517            target: "may::background_promotion",
1518            reason = ?reason,
1519            configured_timeout_seconds,
1520            "promoting terminal command to background"
1521        );
1522
1523        spawned.background_mode.store(true, Ordering::Release);
1524        if !pre_registered {
1525            wait_for_background_startup(&spawned.startup_rx).await?;
1526        }
1527        background_terminal_result(&self.job_registry, &store_dir, &task_id, max_lines, reason)
1528            .await
1529    }
1530}
1531
1532async fn wait_for_background_startup(
1533    startup_rx: &Receiver<Result<(), String>>,
1534) -> anyhow::Result<()> {
1535    match startup_rx.recv().await {
1536        Ok(Ok(())) => Ok(()),
1537        Ok(Err(err)) => Err(anyhow::anyhow!(err)),
1538        Err(_) => Err(anyhow::anyhow!(
1539            "background startup channel dropped before registration"
1540        )),
1541    }
1542}
1543
1544async fn wait_for_foreground_decision(
1545    result_rx: &Receiver<Result<TerminalResult, String>>,
1546    stdin_blocked_rx: &Receiver<String>,
1547    timeout: u64,
1548    configured_timeout_seconds: u64,
1549) -> Option<ForegroundDecision> {
1550    let timeout = std::time::Duration::from_secs(timeout);
1551    futures_lite::future::or(
1552        async {
1553            result_rx
1554                .recv()
1555                .await
1556                .ok()
1557                .map(Box::new)
1558                .map(ForegroundDecision::Completed)
1559        },
1560        async {
1561            futures_lite::future::or(
1562                async {
1563                    match stdin_blocked_rx.recv().await {
1564                        Ok(notice) => Some(ForegroundDecision::PromoteToBackground(
1565                            BackgroundReason::StdinBlocked { notice },
1566                        )),
1567                        Err(_) => std::future::pending().await,
1568                    }
1569                },
1570                async {
1571                    async_io::Timer::after(timeout).await;
1572                    if let Ok(result) = result_rx.try_recv() {
1573                        return Some(ForegroundDecision::Completed(Box::new(result)));
1574                    }
1575                    Some(ForegroundDecision::PromoteToBackground(
1576                        BackgroundReason::Timeout {
1577                            configured_seconds: configured_timeout_seconds,
1578                        },
1579                    ))
1580                },
1581            )
1582            .await
1583        },
1584    )
1585    .await
1586}
1587
1588async fn background_terminal_result(
1589    job_registry: &JobRegistry,
1590    store_dir: &Path,
1591    task_id: &str,
1592    max_lines: usize,
1593    reason: BackgroundReason,
1594) -> aither_core::Result<ToolResult> {
1595    let stdout = start_background_output_redirect(
1596        job_registry,
1597        store_dir,
1598        task_id,
1599        max_lines,
1600        Some(&reason),
1601    )
1602    .await?;
1603    ToolResult::json(&TerminalResult {
1604        stdout,
1605        stderr: None,
1606        exit_code: 0,
1607        task_id: Some(task_id.to_string()),
1608        status: Some("running".to_string()),
1609        background_reason: Some(reason),
1610    })
1611}
1612
1613async fn start_background_output_redirect(
1614    job_registry: &JobRegistry,
1615    store_dir: &Path,
1616    task_id: &str,
1617    max_lines: usize,
1618    promotion_reason: Option<&BackgroundReason>,
1619) -> Result<OutputEntry, anyhow::Error> {
1620    let (url, output_path) = save_raw_to_file(store_dir, &[]).await?;
1621    let output_path_string = output_path.display().to_string();
1622    let snapshot = job_registry
1623        .start_output_redirect(task_id, output_path)
1624        .await
1625        .map_err(anyhow::Error::msg)?;
1626    let (preview, truncated) = preview_first_lines(&snapshot, max_lines);
1627    let text = match (
1628        promotion_reason.map(background_reason_preview),
1629        preview.is_empty(),
1630    ) {
1631        (Some(reason), true) => reason,
1632        (Some(reason), false) => format!("{reason}\n{preview}"),
1633        (None, true) => "(no output yet)".to_string(),
1634        (None, false) => preview,
1635    };
1636    Ok(OutputEntry::Stored {
1637        path: output_path_string,
1638        url,
1639        content: Some(Content::Text { text, truncated }),
1640    })
1641}
1642
1643fn background_reason_preview(reason: &BackgroundReason) -> String {
1644    match reason {
1645        BackgroundReason::Timeout { configured_seconds } => {
1646            format!("Foreground timeout of {configured_seconds}s elapsed — promoted to background.")
1647        }
1648        BackgroundReason::StdinBlocked { notice } => notice.clone(),
1649        BackgroundReason::Explicit => "Started in background (timeout=0 requested).".to_string(),
1650    }
1651}
1652
1653struct StandaloneExecution<P, E> {
1654    working_dir: PathBuf,
1655    writable_paths: Vec<PathBuf>,
1656    readable_paths: Vec<PathBuf>,
1657    executor: E,
1658    registry: Arc<ToolRegistry>,
1659    permission_handler: Arc<P>,
1660    job_registry: JobRegistry,
1661    task_id: String,
1662    execution_id: String,
1663    background_mode: Arc<AtomicBool>,
1664    script: String,
1665    mode: TerminalMode,
1666    backend: ExecutionBackend,
1667    stdin_blocked_notice: Option<Sender<String>>,
1668    background_startup: BackgroundStartup,
1669    network_audit: Option<NetworkAuditLog>,
1670    priority: ProcessPriority,
1671    expect: OutputFormat,
1672    resolution: MediaResolution,
1673    store_dir: PathBuf,
1674    max_lines: usize,
1675    raw: bool,
1676}
1677
1678struct StandaloneStart<'a, P, E> {
1679    working_dir: &'a Path,
1680    writable_paths: &'a [PathBuf],
1681    readable_paths: &'a [PathBuf],
1682    executor: E,
1683    registry: &'a Arc<ToolRegistry>,
1684    permission_handler: Arc<P>,
1685    job_registry: &'a JobRegistry,
1686    task_id: &'a str,
1687    execution_id: &'a str,
1688    script: &'a str,
1689    mode: TerminalMode,
1690    backend: &'a ExecutionBackend,
1691    stdin_blocked_notice: Option<Sender<String>>,
1692    background_startup: &'a BackgroundStartup,
1693    network_audit: Option<NetworkAuditLog>,
1694    priority: ProcessPriority,
1695}
1696
1697struct LocalBackgroundExecution<'a, E> {
1698    prepared_tools: &'a PreparedTools<PathBuf>,
1699    working_dir: &'a Path,
1700    writable_paths: &'a [PathBuf],
1701    readable_paths: &'a [PathBuf],
1702    executor: E,
1703    registry: &'a Arc<ToolRegistry>,
1704    task_id: &'a str,
1705    execution_id: &'a str,
1706    script: &'a str,
1707    mode: TerminalMode,
1708    job_registry: &'a JobRegistry,
1709    stdin_blocked_notice: Option<Sender<String>>,
1710    background_startup: &'a BackgroundStartup,
1711    priority: ProcessPriority,
1712}
1713
1714struct ContainerBackgroundExecution<'a, E> {
1715    executor: E,
1716    registry: &'a Arc<ToolRegistry>,
1717    task_id: &'a str,
1718    execution_id: &'a str,
1719    script: &'a str,
1720    mode: TerminalMode,
1721    container_runtime: &'a ContainerShellRuntime,
1722    prepared_tools: &'a PreparedTools<ContainerPath>,
1723    ipc_commands: &'a [String],
1724    job_registry: &'a JobRegistry,
1725    stdin_blocked_notice: Option<Sender<String>>,
1726    background_startup: &'a BackgroundStartup,
1727    priority: ProcessPriority,
1728}
1729
1730struct SshBackgroundExecution<'a> {
1731    prepared_tools: &'a PreparedTools<PathBuf>,
1732    task_id: &'a str,
1733    execution_id: &'a str,
1734    script: &'a str,
1735    mode: TerminalMode,
1736    ssh_target: &'a str,
1737    ssh_runtime: &'a SshRuntimeProfile,
1738    job_registry: &'a JobRegistry,
1739    background_startup: &'a BackgroundStartup,
1740}
1741
1742struct CompletedProcessOutput<'a> {
1743    job_registry: &'a JobRegistry,
1744    pid: u32,
1745    output: std::process::Output,
1746    background_output: bool,
1747    store_dir: &'a Path,
1748    expect: OutputFormat,
1749    resolution: MediaResolution,
1750    max_lines: usize,
1751    raw: bool,
1752}
1753
1754/// Where a command runs, with the tools prepared for exactly that environment.
1755enum ExecutionBackend {
1756    /// The local sandbox, whose tools live at a host path.
1757    Local(PreparedTools<PathBuf>),
1758    /// A container, whose tools are mounted at a container path.
1759    Container {
1760        runtime: ContainerShellRuntime,
1761        tools: PreparedTools<ContainerPath>,
1762    },
1763    /// A remote host over SSH.
1764    Ssh {
1765        target: String,
1766        runtime: SshRuntimeProfile,
1767        tools: PreparedTools<PathBuf>,
1768    },
1769}
1770
1771impl ExecutionBackend {
1772    const fn kind(&self) -> ShellBackend {
1773        match self {
1774            Self::Local(_) => ShellBackend::Local,
1775            Self::Container { .. } => ShellBackend::Container,
1776            Self::Ssh { .. } => ShellBackend::Ssh,
1777        }
1778    }
1779}
1780
1781struct ExecutionTarget {
1782    mode: TerminalMode,
1783    backend: ExecutionBackend,
1784}
1785
1786struct TerminalSpawnRequest {
1787    target: ExecutionTarget,
1788    task_id: String,
1789    execution_id: String,
1790    script: String,
1791    expect: OutputFormat,
1792    resolution: MediaResolution,
1793    max_lines: usize,
1794    raw: bool,
1795    timeout: u64,
1796}
1797
1798struct SpawnedTerminal {
1799    result_rx: Receiver<Result<TerminalResult, String>>,
1800    startup_rx: Receiver<Result<(), String>>,
1801    stdin_blocked_rx: Receiver<String>,
1802    background_mode: Arc<AtomicBool>,
1803}
1804
1805struct SpawnedTerminalTask<P, E> {
1806    working_dir: PathBuf,
1807    writable_paths: Vec<PathBuf>,
1808    readable_paths: Vec<PathBuf>,
1809    executor: E,
1810    registry: Arc<ToolRegistry>,
1811    permission_handler: Arc<P>,
1812    job_registry: JobRegistry,
1813    task_id: String,
1814    execution_id: String,
1815    background_mode: Arc<AtomicBool>,
1816    script: String,
1817    mode: TerminalMode,
1818    backend: ExecutionBackend,
1819    stdin_blocked_notice: Option<Sender<String>>,
1820    background_startup: BackgroundStartup,
1821    expect: OutputFormat,
1822    resolution: MediaResolution,
1823    store_dir: PathBuf,
1824    max_lines: usize,
1825    raw: bool,
1826    result_tx: Sender<Result<TerminalResult, String>>,
1827    completed_tx: Sender<CompletedTask>,
1828    background_mode_for_completion: Arc<AtomicBool>,
1829    running_tasks: Arc<AtomicUsize>,
1830    network_audit: Option<NetworkAuditLog>,
1831    priority: ProcessPriority,
1832}
1833
1834async fn execute_terminal_task<P, E>(task: SpawnedTerminalTask<P, E>)
1835where
1836    P: PermissionHandler + 'static,
1837    E: Executor + Clone + 'static,
1838{
1839    let SpawnedTerminalTask {
1840        working_dir,
1841        writable_paths,
1842        readable_paths,
1843        executor,
1844        registry,
1845        permission_handler,
1846        job_registry,
1847        task_id,
1848        execution_id,
1849        background_mode,
1850        script,
1851        mode,
1852        backend,
1853        stdin_blocked_notice,
1854        background_startup,
1855        expect,
1856        resolution,
1857        store_dir,
1858        max_lines,
1859        raw,
1860        result_tx,
1861        completed_tx,
1862        background_mode_for_completion,
1863        running_tasks,
1864        network_audit,
1865        priority,
1866    } = task;
1867    let result = execute_script_standalone(StandaloneExecution {
1868        working_dir,
1869        writable_paths,
1870        readable_paths,
1871        executor,
1872        registry,
1873        permission_handler,
1874        job_registry,
1875        task_id: task_id.clone(),
1876        execution_id,
1877        background_mode,
1878        script: script.clone(),
1879        mode,
1880        backend,
1881        stdin_blocked_notice,
1882        background_startup,
1883        network_audit,
1884        priority,
1885        expect,
1886        resolution,
1887        store_dir,
1888        max_lines,
1889        raw,
1890    })
1891    .await;
1892
1893    let quick_result = match &result {
1894        Ok(ok) => Ok(ok.clone()),
1895        Err(err) => Err(err.to_string()),
1896    };
1897    let _ = result_tx.send(quick_result).await;
1898    if background_mode_for_completion.load(Ordering::Acquire) {
1899        let _ = completed_tx
1900            .send(CompletedTask {
1901                task_id,
1902                script,
1903                result,
1904            })
1905            .await;
1906    }
1907    running_tasks.fetch_sub(1, Ordering::AcqRel);
1908}
1909
1910/// Standalone script execution that can be spawned in a background task.
1911async fn execute_script_standalone<P, E>(
1912    request: StandaloneExecution<P, E>,
1913) -> Result<TerminalResult, TerminalError>
1914where
1915    P: PermissionHandler + 'static,
1916    E: Executor + Clone + 'static,
1917{
1918    let StandaloneExecution {
1919        working_dir,
1920        writable_paths,
1921        readable_paths,
1922        executor,
1923        registry,
1924        permission_handler,
1925        job_registry,
1926        task_id,
1927        execution_id,
1928        background_mode,
1929        script,
1930        mode,
1931        backend,
1932        stdin_blocked_notice,
1933        background_startup,
1934        network_audit,
1935        priority,
1936        expect,
1937        resolution,
1938        store_dir,
1939        max_lines,
1940        raw,
1941    } = request;
1942
1943    info!(
1944        script_len = script.len(),
1945        ?mode,
1946        "executing background terminal command"
1947    );
1948    debug!(script = %script, "script content");
1949    let start_result = start_standalone_execution(StandaloneStart {
1950        working_dir: &working_dir,
1951        writable_paths: &writable_paths,
1952        readable_paths: &readable_paths,
1953        executor,
1954        registry: &registry,
1955        permission_handler,
1956        job_registry: &job_registry,
1957        task_id: &task_id,
1958        execution_id: &execution_id,
1959        script: &script,
1960        mode,
1961        backend: &backend,
1962        stdin_blocked_notice,
1963        background_startup: &background_startup,
1964        network_audit,
1965        priority,
1966    })
1967    .await;
1968    let (pid, output) = match start_result {
1969        Ok(started) => started,
1970        Err(error) => {
1971            background_startup.report_failure(&error).await;
1972            return Err(error);
1973        }
1974    };
1975
1976    let result = save_completed_process_output(CompletedProcessOutput {
1977        job_registry: &job_registry,
1978        pid,
1979        output,
1980        background_output: background_mode.load(Ordering::Acquire),
1981        store_dir: &store_dir,
1982        expect,
1983        resolution,
1984        max_lines,
1985        raw,
1986    })
1987    .await?;
1988    let exit_code = result.exit_code;
1989
1990    debug!(exit_code, "background script completed");
1991
1992    let output_path = result.stdout.stored_path(&store_dir);
1993    job_registry.complete(pid, exit_code, output_path).await;
1994
1995    Ok(result)
1996}
1997
1998async fn start_standalone_execution<P, E>(
1999    request: StandaloneStart<'_, P, E>,
2000) -> Result<(u32, std::process::Output), TerminalError>
2001where
2002    P: PermissionHandler + 'static,
2003    E: Executor + Clone + 'static,
2004{
2005    let prepared_tools = match request.backend {
2006        ExecutionBackend::Local(tools) => tools,
2007        ExecutionBackend::Container { runtime, tools } => {
2008            let ipc_commands = request.registry.registered_tool_names();
2009            return execute_container_background(ContainerBackgroundExecution {
2010                executor: request.executor,
2011                registry: request.registry,
2012                task_id: request.task_id,
2013                execution_id: request.execution_id,
2014                script: request.script,
2015                mode: request.mode,
2016                container_runtime: runtime,
2017                prepared_tools: tools,
2018                ipc_commands: &ipc_commands,
2019                job_registry: request.job_registry,
2020                stdin_blocked_notice: request.stdin_blocked_notice,
2021                background_startup: request.background_startup,
2022                priority: request.priority,
2023            })
2024            .await;
2025        }
2026        ExecutionBackend::Ssh {
2027            target,
2028            runtime,
2029            tools,
2030        } => {
2031            return execute_ssh_background(SshBackgroundExecution {
2032                prepared_tools: tools,
2033                task_id: request.task_id,
2034                execution_id: request.execution_id,
2035                script: request.script,
2036                mode: request.mode,
2037                ssh_target: target,
2038                ssh_runtime: runtime,
2039                job_registry: request.job_registry,
2040                background_startup: request.background_startup,
2041            })
2042            .await;
2043        }
2044    };
2045    let local = LocalBackgroundExecution {
2046        prepared_tools,
2047        working_dir: request.working_dir,
2048        writable_paths: request.writable_paths,
2049        readable_paths: request.readable_paths,
2050        executor: request.executor,
2051        registry: request.registry,
2052        task_id: request.task_id,
2053        execution_id: request.execution_id,
2054        script: request.script,
2055        mode: request.mode,
2056        job_registry: request.job_registry,
2057        stdin_blocked_notice: request.stdin_blocked_notice,
2058        background_startup: request.background_startup,
2059        priority: request.priority,
2060    };
2061    match request.mode {
2062        TerminalMode::Sandboxed => {
2063            execute_audited_sandboxed_background(
2064                local,
2065                PermissionNetworkPolicy {
2066                    permission_handler: request.permission_handler,
2067                },
2068                request.network_audit,
2069            )
2070            .await
2071        }
2072        TerminalMode::Unsafe => execute_unsafe_background(local).await,
2073    }
2074}
2075
2076/// Runs a sandboxed execution, recording policy verdicts when an audit log is
2077/// configured. Unsafe mode bypasses the proxy entirely, so it cannot be
2078/// audited at this layer.
2079async fn execute_audited_sandboxed_background<E, N>(
2080    local: LocalBackgroundExecution<'_, E>,
2081    policy: N,
2082    audit: Option<NetworkAuditLog>,
2083) -> Result<(u32, std::process::Output), TerminalError>
2084where
2085    E: Executor + Clone + 'static,
2086    N: NetworkPolicy + 'static,
2087{
2088    match audit {
2089        Some(log) => execute_sandboxed_background(local, Audited::new(policy, log)).await,
2090        None => execute_sandboxed_background(local, policy).await,
2091    }
2092}
2093
2094async fn save_completed_process_output(
2095    request: CompletedProcessOutput<'_>,
2096) -> Result<TerminalResult, TerminalError> {
2097    let CompletedProcessOutput {
2098        job_registry,
2099        pid,
2100        output,
2101        background_output,
2102        store_dir,
2103        expect,
2104        resolution,
2105        max_lines,
2106        raw,
2107    } = request;
2108    let stdout = save_completed_stdout(
2109        job_registry,
2110        pid,
2111        &output.stdout,
2112        CompletedStdoutFormat {
2113            background_output,
2114            store_dir,
2115            expect,
2116            resolution,
2117            max_lines,
2118            raw,
2119        },
2120    )
2121    .await?;
2122    let stderr = save_completed_stderr(job_registry, pid, store_dir, &output.stderr).await?;
2123    let exit_code = output.status.code().unwrap_or(-1);
2124
2125    Ok(TerminalResult {
2126        stdout,
2127        stderr,
2128        exit_code,
2129        task_id: None,
2130        status: None,
2131        background_reason: None,
2132    })
2133}
2134
2135struct CompletedStdoutFormat<'a> {
2136    background_output: bool,
2137    store_dir: &'a Path,
2138    expect: OutputFormat,
2139    resolution: MediaResolution,
2140    max_lines: usize,
2141    raw: bool,
2142}
2143
2144async fn save_completed_stdout(
2145    job_registry: &JobRegistry,
2146    pid: u32,
2147    stdout: &[u8],
2148    format: CompletedStdoutFormat<'_>,
2149) -> Result<OutputEntry, TerminalError> {
2150    let byte_limit = Some(INLINE_OUTPUT_LIMIT);
2151    let data_to_save = if format.background_output {
2152        Cow::Borrowed(stdout)
2153    } else {
2154        compressed_stdout_data(format.store_dir, stdout, format.expect, format.raw).await?
2155    };
2156
2157    match crate::output::save_text_with_line_limit(
2158        format.store_dir,
2159        data_to_save.as_ref(),
2160        format.expect,
2161        format.resolution,
2162        format.max_lines,
2163        byte_limit,
2164    )
2165    .await
2166    {
2167        Ok(entry) => Ok(entry),
2168        Err(err) => {
2169            job_registry.fail(pid, &err.to_string(), None).await;
2170            Err(TerminalError::Io(err))
2171        }
2172    }
2173}
2174
2175/// Runs the output cleaning pipeline over a completed command's stdout.
2176///
2177/// `raw: true` bypasses it entirely, as do non-text formats and output that
2178/// is not valid UTF-8, so the model sees exactly the bytes the command wrote.
2179async fn compressed_stdout_data<'a>(
2180    store_dir: &Path,
2181    stdout: &'a [u8],
2182    expect: OutputFormat,
2183    raw: bool,
2184) -> Result<Cow<'a, [u8]>, TerminalError> {
2185    let is_text = matches!(expect, OutputFormat::Text | OutputFormat::Auto);
2186    if raw || !is_text || stdout.is_empty() {
2187        return Ok(Cow::Borrowed(stdout));
2188    }
2189    let Ok(text) = std::str::from_utf8(stdout) else {
2190        return Ok(Cow::Borrowed(stdout));
2191    };
2192
2193    let cleaned = crate::output_compress::compress_text(store_dir, text)
2194        .await
2195        .map_err(TerminalError::Io)?;
2196    Ok(cleaned.map_or(Cow::Borrowed(stdout), |cleaned| {
2197        Cow::Owned(cleaned.into_bytes())
2198    }))
2199}
2200
2201async fn save_completed_stderr(
2202    job_registry: &JobRegistry,
2203    pid: u32,
2204    store_dir: &Path,
2205    stderr: &[u8],
2206) -> Result<Option<OutputEntry>, TerminalError> {
2207    if stderr.is_empty() {
2208        return Ok(None);
2209    }
2210    match OutputStore::save_to_dir_with_limit(
2211        store_dir,
2212        stderr,
2213        OutputFormat::Text,
2214        MediaResolution::Auto,
2215        Some(INLINE_OUTPUT_LIMIT),
2216    )
2217    .await
2218    {
2219        Ok(entry) => Ok(Some(entry)),
2220        Err(err) => {
2221            job_registry.fail(pid, &err.to_string(), None).await;
2222            Err(TerminalError::Io(err))
2223        }
2224    }
2225}
2226
2227fn local_path_grants<'a>(
2228    writable: &'a [PathBuf],
2229    readable: &'a [PathBuf],
2230    tools: &'a PreparedTools<PathBuf>,
2231) -> impl Iterator<Item = Grant> + 'a {
2232    writable
2233        .iter()
2234        .map(|path| Grant::new(path, Access::WRITE))
2235        .chain(readable.iter().map(|path| Grant::new(path, Access::READ)))
2236        .chain(std::iter::once(Grant::new(tools.bin_dir(), Access::EXEC)))
2237}
2238
2239async fn execute_sandboxed_background<E, N>(
2240    context: LocalBackgroundExecution<'_, E>,
2241    policy: N,
2242) -> Result<(u32, std::process::Output), TerminalError>
2243where
2244    E: Executor + Clone + 'static,
2245    N: NetworkPolicy + 'static,
2246{
2247    let runtime_environment =
2248        prepare_session_runtime_environment(context.working_dir, context.prepared_tools).await?;
2249    let config_builder = SandboxConfig::builder()
2250        .network(policy)
2251        .working_dir(context.working_dir)
2252        .grants(local_path_grants(
2253            context.writable_paths,
2254            context.readable_paths,
2255            context.prepared_tools,
2256        ))
2257        .security(SecurityConfig::interactive())
2258        .priority(context.priority);
2259    // `ipc` changes the builder's type, so both arms build where they are.
2260    let config = match create_ipc_router(context.registry) {
2261        Some(router) => config_builder.ipc(router).build(),
2262        None => config_builder.build(),
2263    };
2264
2265    let sandbox = Sandbox::with_config_and_executor(config, context.executor.clone())
2266        .await
2267        .map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;
2268
2269    let launch = build_terminal_launch(context.script)?;
2270    let (program, args) = match &launch {
2271        TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
2272            (program, args)
2273        }
2274    };
2275
2276    let child = sandbox
2277        .command(program)
2278        .args(args)
2279        .envs(runtime_environment)
2280        .stdin(StdioConfig::Piped)
2281        .stdout(StdioConfig::Piped)
2282        .stderr(StdioConfig::Piped)
2283        .spawn()
2284        .await
2285        .map_err(|e| TerminalError::Execution(e.to_string()))?;
2286
2287    let pid = child.id();
2288    context
2289        .job_registry
2290        .register(
2291            pid,
2292            context.task_id,
2293            context.execution_id,
2294            context.script,
2295            context.mode,
2296            None,
2297        )
2298        .await;
2299    context.background_startup.report_ready().await;
2300
2301    let output = collect_local_process_output(
2302        child,
2303        context.executor,
2304        context.job_registry,
2305        pid,
2306        context.stdin_blocked_notice,
2307        "missing stdout pipe for sandbox process",
2308        "missing stderr pipe for sandbox process",
2309    )
2310    .await?;
2311
2312    Ok((pid, output))
2313}
2314
2315async fn execute_unsafe_background<E: Executor + Clone + 'static>(
2316    context: LocalBackgroundExecution<'_, E>,
2317) -> Result<(u32, std::process::Output), TerminalError> {
2318    let runtime_environment =
2319        prepare_session_runtime_environment(context.working_dir, context.prepared_tools).await?;
2320    let config_builder = SandboxConfig::builder()
2321        .network(AllowAll)
2322        .working_dir(context.working_dir)
2323        .grants(local_path_grants(
2324            context.writable_paths,
2325            context.readable_paths,
2326            context.prepared_tools,
2327        ))
2328        .security(SecurityConfig::interactive())
2329        .priority(context.priority);
2330    // `ipc` changes the builder's type, so both arms build where they are.
2331    let config = match create_ipc_gateway_router(context.registry) {
2332        Some(router) => config_builder.ipc(router).build(),
2333        None => config_builder.build(),
2334    };
2335
2336    let sandbox = Sandbox::with_config_and_executor(config, context.executor.clone())
2337        .await
2338        .map_err(|e| TerminalError::SandboxSetup(e.to_string()))?;
2339
2340    let launch = build_terminal_launch(context.script)?;
2341    let (program, args) = match &launch {
2342        TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
2343            (program, args)
2344        }
2345    };
2346
2347    let child = sandbox
2348        .command(program)
2349        .args(args)
2350        .envs(runtime_environment)
2351        .stdin(StdioConfig::Piped)
2352        .stdout(StdioConfig::Piped)
2353        .stderr(StdioConfig::Piped)
2354        .spawn()
2355        .await
2356        .map_err(|e| TerminalError::Execution(e.to_string()))?;
2357
2358    let pid = child.id();
2359    context
2360        .job_registry
2361        .register(
2362            pid,
2363            context.task_id,
2364            context.execution_id,
2365            context.script,
2366            context.mode,
2367            None,
2368        )
2369        .await;
2370    context.background_startup.report_ready().await;
2371
2372    let output = collect_local_process_output(
2373        child,
2374        context.executor,
2375        context.job_registry,
2376        pid,
2377        context.stdin_blocked_notice,
2378        "missing stdout pipe for unsafe process",
2379        "missing stderr pipe for unsafe process",
2380    )
2381    .await?;
2382
2383    Ok((pid, output))
2384}
2385
2386async fn collect_local_process_output<E: Executor + Clone + 'static>(
2387    mut child: heel::Child,
2388    executor: E,
2389    job_registry: &JobRegistry,
2390    pid: u32,
2391    stdin_blocked_notice: Option<async_channel::Sender<String>>,
2392    missing_stdout_message: &'static str,
2393    missing_stderr_message: &'static str,
2394) -> Result<std::process::Output, TerminalError> {
2395    if let Some(stdin) = child.take_stdin() {
2396        let input_tx = spawn_terminal_stdin_writer(stdin);
2397        job_registry.attach_terminal_input(pid, input_tx).await;
2398    }
2399
2400    let stdout = child
2401        .take_stdout()
2402        .ok_or_else(|| TerminalError::Execution(missing_stdout_message.into()))?;
2403    let stderr = child
2404        .take_stderr()
2405        .ok_or_else(|| TerminalError::Execution(missing_stderr_message.into()))?;
2406
2407    let (chunk_tx, chunk_rx) = async_channel::unbounded();
2408    spawn_terminal_reader(stdout, chunk_tx.clone(), false);
2409    spawn_terminal_reader(stderr, chunk_tx.clone(), true);
2410    drop(chunk_tx);
2411    executor
2412        .spawn(drain_terminal_chunks(job_registry.clone(), pid, chunk_rx))
2413        .detach();
2414
2415    let status = match wait_for_local_process_exit(&mut child, pid, stdin_blocked_notice).await {
2416        Ok(status) => status,
2417        Err(error) => {
2418            job_registry.close_stdout(pid).await;
2419            job_registry.close_stderr(pid).await;
2420            return Err(error);
2421        }
2422    };
2423    wait_for_terminal_stream_close(job_registry, pid).await;
2424    let (stdout, stderr) = job_registry.terminal_output(pid).await.ok_or_else(|| {
2425        TerminalError::Execution(format!("missing terminal output for pid {pid}"))
2426    })?;
2427    let output = std::process::Output {
2428        status,
2429        stdout,
2430        stderr,
2431    };
2432
2433    Ok(output)
2434}
2435
2436async fn wait_for_local_process_exit(
2437    child: &mut heel::Child,
2438    pid: u32,
2439    stdin_blocked_notice: Option<async_channel::Sender<String>>,
2440) -> Result<std::process::ExitStatus, TerminalError> {
2441    if stdin_blocked_notice.is_none() {
2442        return child
2443            .wait()
2444            .await
2445            .map_err(|error| TerminalError::Execution(error.to_string()));
2446    }
2447
2448    let mut notice_sent = false;
2449    loop {
2450        if let Some(status) = child
2451            .try_wait()
2452            .map_err(|error| TerminalError::Execution(error.to_string()))?
2453        {
2454            return Ok(status);
2455        }
2456
2457        if !notice_sent {
2458            match detect_stdin_blocked_for_local_pid(pid).await {
2459                Ok(true) => {
2460                    if let Some(notice_tx) = stdin_blocked_notice.as_ref() {
2461                        let _ = notice_tx.try_send(TERMINAL_STDIN_BLOCKED_NOTICE.to_string());
2462                    }
2463                    notice_sent = true;
2464                }
2465                Ok(false) => {}
2466                Err(error) => {
2467                    tracing::debug!(error = %error, pid, "stdin watchdog probe failed");
2468                }
2469            }
2470        }
2471
2472        async_io::Timer::after(STDIN_WATCH_INTERVAL).await;
2473    }
2474}
2475
2476async fn execute_container_background<E: Executor + Clone + 'static>(
2477    context: ContainerBackgroundExecution<'_, E>,
2478) -> Result<(u32, std::process::Output), TerminalError> {
2479    let container_runtime = context.container_runtime;
2480    let exec = container_runtime.exec();
2481
2482    // Use lower 32 bits of a UUID as a synthetic PID for job tracking.
2483    let pid = u32::from_le_bytes(
2484        uuid::Uuid::new_v4().as_u128().to_le_bytes()[..4]
2485            .try_into()
2486            .expect("uuid byte slice has four bytes"),
2487    );
2488    let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
2489    let (input_tx, input_rx) = async_channel::unbounded::<Vec<u8>>();
2490    context
2491        .job_registry
2492        .register(
2493            pid,
2494            context.task_id,
2495            context.execution_id,
2496            context.script,
2497            context.mode,
2498            None,
2499        )
2500        .await;
2501    context
2502        .job_registry
2503        .attach_terminal_input(pid, input_tx)
2504        .await;
2505    context.background_startup.report_ready().await;
2506    context.job_registry.attach_kill_switch(pid, kill_tx).await;
2507
2508    let ipc_bridge = if context.ipc_commands.is_empty() {
2509        None
2510    } else {
2511        Some(start_container_ipc_bridge(
2512            context.executor,
2513            Arc::clone(context.registry),
2514            container_runtime.ipc_route().bind(),
2515        )?)
2516    };
2517    let script = context.prepared_tools.wrap_script(context.script)?;
2518    let wrapped_script = wrap_container_script(
2519        &script,
2520        context.ipc_commands,
2521        ipc_bridge.as_ref().map(|bridge| ContainerIpcEndpoint {
2522            host: container_runtime.ipc_route().host(),
2523            port: bridge.port(),
2524        }),
2525        context.priority,
2526        context.prepared_tools.bin_dir(),
2527        CONTAINER_EXEC_WORKING_DIR,
2528    )?;
2529
2530    let execution = exec
2531        .exec_boxed(
2532            container_runtime.container_id(),
2533            &wrapped_script,
2534            CONTAINER_EXEC_WORKING_DIR,
2535            kill_rx,
2536            input_rx,
2537            context.stdin_blocked_notice,
2538        )
2539        .await;
2540
2541    if let Some(bridge) = ipc_bridge {
2542        bridge.stop().await;
2543    }
2544
2545    match execution {
2546        Ok(crate::shell_session::ContainerExecOutcome::Completed(output)) => {
2547            if !output.stdout.is_empty() {
2548                context
2549                    .job_registry
2550                    .append_stdout(pid, output.stdout.clone())
2551                    .await;
2552            }
2553            if !output.stderr.is_empty() {
2554                context
2555                    .job_registry
2556                    .append_stderr(pid, output.stderr.clone())
2557                    .await;
2558            }
2559            context.job_registry.close_stdout(pid).await;
2560            context.job_registry.close_stderr(pid).await;
2561            Ok((pid, output))
2562        }
2563        Ok(crate::shell_session::ContainerExecOutcome::Killed) => {
2564            context.job_registry.close_stdout(pid).await;
2565            context.job_registry.close_stderr(pid).await;
2566            Err(TerminalError::Execution("container job killed".to_string()))
2567        }
2568        Err(err) => {
2569            context.job_registry.fail(pid, &err, None).await;
2570            context.job_registry.close_stdout(pid).await;
2571            context.job_registry.close_stderr(pid).await;
2572            Err(TerminalError::Execution(err))
2573        }
2574    }
2575}
2576
2577#[derive(Template)]
2578#[template(path = "ssh_tool_execution.sh", escape = "none")]
2579struct SshToolExecutionTemplate<'a> {
2580    binary: Cow<'a, str>,
2581    tools_dir: Cow<'a, str>,
2582    program: Cow<'a, str>,
2583    arguments: String,
2584}
2585
2586async fn execute_ssh_background(
2587    context: SshBackgroundExecution<'_>,
2588) -> Result<(u32, std::process::Output), TerminalError> {
2589    let target = context.ssh_target;
2590    let remote_cmd = match (context.ssh_runtime, context.mode) {
2591        (SshRuntimeProfile::Heel { binary }, TerminalMode::Sandboxed) => {
2592            let script = context.prepared_tools.wrap_script(context.script)?;
2593            let (program, args) = shell_launch(&script);
2594            let directory = context.prepared_tools.script_bin_dir()?;
2595            SshToolExecutionTemplate {
2596                binary: shell_words::quote(binary),
2597                tools_dir: shell_words::quote(directory),
2598                program: shell_words::quote(&program),
2599                arguments: shell_words::join(&args),
2600            }
2601            .render()
2602            .map_err(ToolRuntimeError::from)?
2603        }
2604        (SshRuntimeProfile::Heel { .. }, TerminalMode::Unsafe) => {
2605            return Err(TerminalError::InvalidTarget(
2606                "unsafe mode is not supported for ssh backend".into(),
2607            ));
2608        }
2609    };
2610
2611    let mut command = std::process::Command::new("ssh");
2612    command
2613        .arg("-o")
2614        .arg("BatchMode=yes")
2615        .arg("-o")
2616        .arg("ConnectTimeout=10")
2617        .arg(target)
2618        .arg(remote_cmd)
2619        .stdin(Stdio::null())
2620        .stdout(Stdio::piped())
2621        .stderr(Stdio::piped());
2622    #[cfg(unix)]
2623    std::os::unix::process::CommandExt::process_group(&mut command, 0);
2624
2625    let child = async_process::Command::from(command)
2626        .spawn()
2627        .map_err(|e| TerminalError::Execution(e.to_string()))?;
2628
2629    let pid = child.id();
2630    context
2631        .job_registry
2632        .register(
2633            pid,
2634            context.task_id,
2635            context.execution_id,
2636            context.script,
2637            context.mode,
2638            None,
2639        )
2640        .await;
2641    context.background_startup.report_ready().await;
2642
2643    match child.output().await {
2644        Ok(output) => {
2645            if !output.stdout.is_empty() {
2646                context
2647                    .job_registry
2648                    .append_stdout(pid, output.stdout.clone())
2649                    .await;
2650            }
2651            if !output.stderr.is_empty() {
2652                context
2653                    .job_registry
2654                    .append_stderr(pid, output.stderr.clone())
2655                    .await;
2656            }
2657            context.job_registry.close_stdout(pid).await;
2658            context.job_registry.close_stderr(pid).await;
2659            Ok((pid, output))
2660        }
2661        Err(err) => {
2662            context.job_registry.fail(pid, &err.to_string(), None).await;
2663            context.job_registry.close_stdout(pid).await;
2664            context.job_registry.close_stderr(pid).await;
2665            Err(TerminalError::Execution(err.to_string()))
2666        }
2667    }
2668}
2669
2670fn shell_escape(value: &str) -> String {
2671    let escaped = value.replace('\'', "'\"'\"'");
2672    let mut output = String::with_capacity(escaped.len() + 2);
2673    output.push('\'');
2674    output.push_str(&escaped);
2675    output.push('\'');
2676    output
2677}
2678
2679async fn prepare_session_runtime_environment(
2680    working_dir: &Path,
2681    tools: &PreparedTools<PathBuf>,
2682) -> Result<Vec<(String, String)>, TerminalError> {
2683    let session_tmp = working_dir.join("tmp");
2684    let session_cache = working_dir.join(".cache");
2685    let bun_cache = session_cache.join("bun");
2686    let session_config = working_dir.join(".config");
2687    let playwright_cache = session_cache.join("ms-playwright");
2688    let python_path = working_dir.join("skills").join("python");
2689
2690    for directory in [
2691        &session_tmp,
2692        &session_cache,
2693        &bun_cache,
2694        &session_config,
2695        &playwright_cache,
2696    ] {
2697        async_fs::create_dir_all(directory).await?;
2698    }
2699
2700    let tmp = path_environment_value("TMPDIR", &session_tmp)?;
2701    let cache = path_environment_value("XDG_CACHE_HOME", &session_cache)?;
2702    let bun = path_environment_value("BUN_INSTALL_CACHE_DIR", &bun_cache)?;
2703    let config = path_environment_value("XDG_CONFIG_HOME", &session_config)?;
2704    let playwright = path_environment_value("PLAYWRIGHT_BROWSERS_PATH", &playwright_cache)?;
2705    let home = path_environment_value("HOME", working_dir)?;
2706    let python = std::env::var_os("PYTHONPATH").map_or_else(
2707        || Ok::<_, TerminalError>(python_path.clone().into_os_string()),
2708        |existing| {
2709            std::env::join_paths(
2710                std::iter::once(python_path.clone()).chain(std::env::split_paths(&existing)),
2711            )
2712            .map_err(|error| {
2713                TerminalError::Execution(format!("failed to construct session PYTHONPATH: {error}"))
2714            })
2715        },
2716    )?;
2717    let python = python.into_string().map_err(|value| {
2718        TerminalError::Execution(format!(
2719            "session PYTHONPATH is not valid UTF-8: {}",
2720            value.to_string_lossy()
2721        ))
2722    })?;
2723
2724    let sandbox_path = heel::default_sandbox_path();
2725    let path = tools
2726        .prepend_path(Some(std::ffi::OsStr::new(&sandbox_path)))?
2727        .into_string()
2728        .map_err(|_| ToolRuntimeError::InvalidCache(tools.bin_dir().clone()))?;
2729    Ok(vec![
2730        ("PATH".to_string(), path),
2731        ("TMPDIR".to_string(), tmp.clone()),
2732        ("TMP".to_string(), tmp.clone()),
2733        ("TEMP".to_string(), tmp),
2734        ("HOME".to_string(), home),
2735        ("XDG_CACHE_HOME".to_string(), cache),
2736        ("XDG_CONFIG_HOME".to_string(), config),
2737        ("BUN_INSTALL_CACHE_DIR".to_string(), bun),
2738        ("PLAYWRIGHT_BROWSERS_PATH".to_string(), playwright),
2739        ("PYTHONPATH".to_string(), python),
2740    ])
2741}
2742
2743fn path_environment_value(name: &str, path: &Path) -> Result<String, TerminalError> {
2744    path.to_str().map(str::to_string).ok_or_else(|| {
2745        TerminalError::Execution(format!(
2746            "session environment path for {name} is not valid UTF-8: {}",
2747            path.display()
2748        ))
2749    })
2750}
2751
2752#[derive(Template)]
2753#[template(path = "container_ipc_wrapper.sh", escape = "none")]
2754struct ContainerIpcWrapperTemplate<'a> {
2755    escaped_commands: &'a str,
2756    ipc_host: &'a str,
2757    ipc_port: u16,
2758    script: &'a str,
2759}
2760
2761#[derive(Clone, Copy)]
2762struct ContainerIpcEndpoint<'a> {
2763    host: &'a str,
2764    port: u16,
2765}
2766
2767/// Working directory container executions run their scripts in.
2768const CONTAINER_EXEC_WORKING_DIR: &str = "/workspace";
2769
2770#[derive(Template)]
2771#[template(path = "container_heel_run.sh", escape = "none")]
2772struct ContainerHeelRunTemplate<'a> {
2773    heel_bin: &'a str,
2774    resolve_heel: bool,
2775    escaped_working_dir: &'a str,
2776    escaped_tools_dir: &'a str,
2777    escaped_ipc_endpoint: Option<String>,
2778    nice: Option<u8>,
2779    io_priority: Option<&'static str>,
2780    escaped_script: &'a str,
2781}
2782
2783/// Renders the command that runs `script` inside the container at the
2784/// configured scheduling priority.
2785///
2786/// The priority goes through heel's own sandbox configuration: the container
2787/// image's `heel` binary runs the script under `heel run`, so the settings are
2788/// the same flags the CLI takes everywhere — `nice`/`ionice` are never
2789/// reimplemented here. `heel_bin` is the shell expression that resolves the
2790/// image's `heel` (`$MAY_IPC_BIN` once the IPC wrapper has resolved it, or
2791/// `$MAY_HEEL_BIN` the template resolves itself when `resolve_heel` is set)
2792/// and `working_dir` is the exact directory the execution runs in, matching
2793/// the directory the container exec applies.
2794///
2795/// The container is already the isolation boundary, so the invocation asks for
2796/// `permissive` isolation: the script keeps the filesystem permissions it had
2797/// as the container caller. The ruleset still exec-denies everything outside
2798/// the system directories, so `--executable` grants the mounted tools
2799/// directory read-execute — without it every prepared tool fails with
2800/// Permission denied. `PATH` and `HOME` are forwarded so the generated
2801/// `heel ipc` shims still resolve and the script sees its usual environment.
2802/// Networking keeps heel's deny-all default, and no rule is bent to pass the
2803/// IPC transport: `--ipc-endpoint` has heel relay the sandbox's local IPC
2804/// socket to the bridge endpoint from outside the sandbox, so the sandboxed
2805/// `heel ipc` never needs TCP access of its own.
2806fn heel_run_container_command(
2807    script: &str,
2808    priority: ProcessPriority,
2809    heel_bin: &str,
2810    resolve_heel: bool,
2811    ipc_endpoint: Option<ContainerIpcEndpoint<'_>>,
2812    tools_dir: &ContainerPath,
2813    working_dir: &str,
2814) -> Result<String, TerminalError> {
2815    let nice = match priority.cpu() {
2816        CpuPriority::Nice(level) => Some(level.get()),
2817        CpuPriority::Normal => None,
2818    };
2819    let io_priority = match priority.io() {
2820        IoPriority::Utility => Some("utility"),
2821        IoPriority::Background => Some("background"),
2822        IoPriority::Normal => None,
2823    };
2824    let escaped_working_dir = shell_escape(working_dir);
2825    let escaped_tools_dir = shell_escape(tools_dir.as_str());
2826    let escaped_ipc_endpoint = ipc_endpoint
2827        .map(|endpoint| format!("tcp://{}:{}", endpoint.host, endpoint.port))
2828        .map(|endpoint| shell_escape(&endpoint));
2829    let escaped_script = shell_escape(script);
2830    ContainerHeelRunTemplate {
2831        heel_bin,
2832        resolve_heel,
2833        escaped_working_dir: &escaped_working_dir,
2834        escaped_tools_dir: &escaped_tools_dir,
2835        escaped_ipc_endpoint,
2836        nice,
2837        io_priority,
2838        escaped_script: &escaped_script,
2839    }
2840    .render()
2841    .map_err(|error| {
2842        TerminalError::Execution(format!("failed to render container heel command: {error}"))
2843    })
2844}
2845
2846fn prioritized_container_script(
2847    script: &str,
2848    priority: ProcessPriority,
2849    tools_dir: &ContainerPath,
2850    working_dir: &str,
2851) -> Result<String, TerminalError> {
2852    if priority.is_normal() {
2853        return Ok(script.to_string());
2854    }
2855    // Outside the IPC wrapper no `heel` binary has been resolved yet; the
2856    // template resolves it the same way the wrapper does and fails when the
2857    // image lacks one.
2858    heel_run_container_command(
2859        script,
2860        priority,
2861        "\"$MAY_HEEL_BIN\"",
2862        true,
2863        None,
2864        tools_dir,
2865        working_dir,
2866    )
2867}
2868
2869fn wrap_container_script(
2870    script: &str,
2871    ipc_commands: &[String],
2872    ipc_endpoint: Option<ContainerIpcEndpoint<'_>>,
2873    priority: ProcessPriority,
2874    tools_dir: &ContainerPath,
2875    working_dir: &str,
2876) -> Result<String, TerminalError> {
2877    if ipc_commands.is_empty() {
2878        return prioritized_container_script(script, priority, tools_dir, working_dir);
2879    }
2880
2881    let endpoint = ipc_endpoint.ok_or_else(|| {
2882        TerminalError::Execution(
2883            "missing container IPC endpoint for wrapped script execution".to_string(),
2884        )
2885    })?;
2886
2887    for name in ipc_commands {
2888        if !name
2889            .chars()
2890            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
2891        {
2892            return Err(TerminalError::Execution(format!(
2893                "invalid ipc command name for container wrapper: {name}"
2894            )));
2895        }
2896    }
2897
2898    let escaped_commands = ipc_commands
2899        .iter()
2900        .map(|name| shell_escape(name))
2901        .collect::<Vec<_>>()
2902        .join(" ");
2903    let script = if priority.is_normal() {
2904        script.to_string()
2905    } else {
2906        // The generated shims are written under the shared temp directory,
2907        // which stays execute-denied even at `permissive` isolation: the
2908        // render below grants them read-and-execute so the sandboxed `PATH`
2909        // resolves them — the wrapper writes them before `heel run`, so the
2910        // sandbox itself never writes the directory.
2911        heel_run_container_command(
2912            script,
2913            priority,
2914            "\"$MAY_IPC_BIN\"",
2915            false,
2916            Some(endpoint),
2917            tools_dir,
2918            working_dir,
2919        )?
2920    };
2921    ContainerIpcWrapperTemplate {
2922        escaped_commands: &escaped_commands,
2923        ipc_host: endpoint.host,
2924        ipc_port: endpoint.port,
2925        script: &script,
2926    }
2927    .render()
2928    .map_err(|error| {
2929        TerminalError::Execution(format!("failed to render container IPC wrapper: {error}"))
2930    })
2931}
2932
2933struct ContainerIpcBridge {
2934    shutdown_tx: Sender<()>,
2935    port: u16,
2936}
2937
2938impl ContainerIpcBridge {
2939    const fn port(&self) -> u16 {
2940        self.port
2941    }
2942
2943    async fn stop(self) {
2944        tracing::debug!("stopping container IPC bridge");
2945        let _ = self.shutdown_tx.send(()).await;
2946    }
2947}
2948
2949fn start_container_ipc_bridge<E: Executor + Clone + 'static>(
2950    executor: E,
2951    registry: Arc<ToolRegistry>,
2952    bind: BridgeAddress,
2953) -> Result<ContainerIpcBridge, TerminalError> {
2954    // The bridge executes host IPC commands for whoever connects, so it binds
2955    // only the address the container route names — never a wildcard.
2956    let listener = StdTcpListener::bind(SocketAddr::new(bind.ip(), 0)).map_err(|e| {
2957        TerminalError::Execution(format!("failed to bind container IPC tcp port: {e}"))
2958    })?;
2959    let local_addr = listener.local_addr().map_err(|e| {
2960        TerminalError::Execution(format!("failed to resolve container IPC tcp endpoint: {e}"))
2961    })?;
2962    tracing::debug!(
2963        bind = %local_addr,
2964        "starting container IPC bridge"
2965    );
2966    listener.set_nonblocking(true).map_err(|e| {
2967        TerminalError::Execution(format!(
2968            "failed to set IPC tcp listener nonblocking mode: {e}"
2969        ))
2970    })?;
2971    let listener = Async::new(listener).map_err(|e| {
2972        TerminalError::Execution(format!(
2973            "failed to register IPC tcp listener with async reactor: {e}"
2974        ))
2975    })?;
2976
2977    let (shutdown_tx, shutdown_rx) = async_channel::bounded::<()>(1);
2978    let bridge_executor = executor.clone();
2979    executor
2980        .spawn(async move {
2981            tracing::debug!(bind = %local_addr, "container IPC bridge listening");
2982            if let Err(error) =
2983                run_container_ipc_bridge(listener, registry, shutdown_rx, bridge_executor).await
2984            {
2985                tracing::debug!(error = %error, "container IPC bridge stopped with error");
2986            }
2987            tracing::debug!(bind = %local_addr, "container IPC bridge stopped");
2988        })
2989        .detach();
2990
2991    Ok(ContainerIpcBridge {
2992        shutdown_tx,
2993        port: local_addr.port(),
2994    })
2995}
2996
2997enum ContainerIpcBridgeEvent {
2998    Accept(std::io::Result<(Async<StdTcpStream>, std::net::SocketAddr)>),
2999    Shutdown,
3000}
3001
3002async fn run_container_ipc_bridge<E: Executor + Clone + 'static>(
3003    listener: Async<StdTcpListener>,
3004    registry: Arc<ToolRegistry>,
3005    shutdown_rx: Receiver<()>,
3006    executor: E,
3007) -> Result<(), String> {
3008    loop {
3009        let event = futures_lite::future::or(
3010            async { ContainerIpcBridgeEvent::Accept(listener.accept().await) },
3011            async {
3012                let _ = shutdown_rx.recv().await;
3013                ContainerIpcBridgeEvent::Shutdown
3014            },
3015        )
3016        .await;
3017
3018        match event {
3019            ContainerIpcBridgeEvent::Shutdown => break,
3020            ContainerIpcBridgeEvent::Accept(Ok((stream, _addr))) => {
3021                tracing::debug!("container IPC bridge accepted connection");
3022                let registry = registry.clone();
3023                executor
3024                    .spawn(async move {
3025                        if let Err(error) = handle_container_ipc_connection(stream, registry).await
3026                        {
3027                            tracing::debug!(error = %error, "container IPC connection failed");
3028                        }
3029                    })
3030                    .detach();
3031            }
3032            ContainerIpcBridgeEvent::Accept(Err(error))
3033                if error.kind() == std::io::ErrorKind::Interrupted => {}
3034            ContainerIpcBridgeEvent::Accept(Err(error)) => {
3035                return Err(format!("container IPC accept failed: {error}"));
3036            }
3037        }
3038    }
3039    Ok(())
3040}
3041
3042async fn handle_container_ipc_connection(
3043    mut stream: Async<StdTcpStream>,
3044    registry: Arc<ToolRegistry>,
3045) -> Result<(), String> {
3046    loop {
3047        let mut length_bytes = [0_u8; 4];
3048        match stream.read_exact(&mut length_bytes).await {
3049            Ok(()) => {}
3050            Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(()),
3051            Err(error) => return Err(format!("failed to read IPC request length: {error}")),
3052        }
3053        let body_length = u32::from_be_bytes(length_bytes) as usize;
3054        if body_length == 0 || body_length > 16 * 1024 * 1024 {
3055            return Err(format!("invalid IPC request length: {body_length}"));
3056        }
3057
3058        let mut body = vec![0_u8; body_length];
3059        stream
3060            .read_exact(&mut body)
3061            .await
3062            .map_err(|e| format!("failed to read IPC request body: {e}"))?;
3063
3064        if body.is_empty() {
3065            write_container_ipc_error(&mut stream, "empty IPC request body").await?;
3066            continue;
3067        }
3068
3069        let method_length = body[0] as usize;
3070        if method_length == 0 {
3071            write_container_ipc_error(&mut stream, "empty IPC method name").await?;
3072            continue;
3073        }
3074        if body.len() < 1 + method_length {
3075            write_container_ipc_error(&mut stream, "invalid IPC request framing").await?;
3076            continue;
3077        }
3078
3079        let method = std::str::from_utf8(&body[1..=method_length])
3080            .map_err(|e| format!("invalid IPC method name utf8: {e}"))?;
3081        let params = &body[1 + method_length..];
3082        let cli_args = decode_container_ipc_args(params)?;
3083        let response = registry.query_tool_handler(method, &cli_args).await;
3084        write_container_ipc_success(&mut stream, &response).await?;
3085    }
3086}
3087
3088fn decode_container_ipc_args(params: &[u8]) -> Result<Vec<String>, String> {
3089    let parsed: serde_json::Value =
3090        rmp_serde::from_slice(params).map_err(|e| format!("invalid IPC params: {e}"))?;
3091    let args = parsed
3092        .as_object()
3093        .ok_or_else(|| "container IPC params must be a map".to_string())?;
3094    let args = args
3095        .iter()
3096        .map(|(key, value)| (key.clone(), value.clone()))
3097        .collect::<std::collections::HashMap<_, _>>();
3098    Ok(crate::command::flatten_args_to_cli(&args))
3099}
3100
3101async fn write_container_ipc_success(
3102    stream: &mut Async<StdTcpStream>,
3103    response: &crate::command::CommandEnvelope,
3104) -> Result<(), String> {
3105    let payload = rmp_serde::to_vec_named(response)
3106        .map_err(|e| format!("failed to encode IPC success payload: {e}"))?;
3107    write_container_ipc_response(stream, true, &payload).await
3108}
3109
3110async fn write_container_ipc_error(
3111    stream: &mut Async<StdTcpStream>,
3112    message: &str,
3113) -> Result<(), String> {
3114    let payload = rmp_serde::to_vec_named(&message.to_string())
3115        .map_err(|e| format!("failed to encode IPC error payload: {e}"))?;
3116    write_container_ipc_response(stream, false, &payload).await
3117}
3118
3119async fn write_container_ipc_response(
3120    stream: &mut Async<StdTcpStream>,
3121    success: bool,
3122    payload: &[u8],
3123) -> Result<(), String> {
3124    let body_length = 1usize
3125        .checked_add(payload.len())
3126        .ok_or_else(|| "IPC response payload length overflow".to_string())?;
3127    let response_length = u32::try_from(body_length)
3128        .map_err(|_| format!("IPC response body too large: {body_length} bytes"))?;
3129
3130    stream
3131        .write_all(&response_length.to_be_bytes())
3132        .await
3133        .map_err(|e| format!("failed to write IPC response length: {e}"))?;
3134    stream
3135        .write_all(&[u8::from(success)])
3136        .await
3137        .map_err(|e| format!("failed to write IPC success flag: {e}"))?;
3138    stream
3139        .write_all(payload)
3140        .await
3141        .map_err(|e| format!("failed to write IPC payload: {e}"))?;
3142    stream
3143        .flush()
3144        .await
3145        .map_err(|e| format!("failed to flush IPC payload: {e}"))
3146}
3147
3148fn preview_first_lines(data: &[u8], max_lines: usize) -> (String, bool) {
3149    if data.is_empty() || max_lines == 0 {
3150        return (String::new(), !data.is_empty() && max_lines == 0);
3151    }
3152
3153    let text = String::from_utf8_lossy(data);
3154    let mut preview = String::new();
3155    let mut total_lines = 0usize;
3156
3157    for line in text.lines() {
3158        total_lines += 1;
3159        if total_lines <= max_lines {
3160            if !preview.is_empty() {
3161                preview.push('\n');
3162            }
3163            preview.push_str(line);
3164        }
3165    }
3166
3167    let truncated = total_lines > max_lines;
3168    (preview, truncated)
3169}
3170
3171enum TerminalChunk {
3172    Stdout(Vec<u8>),
3173    Stderr(Vec<u8>),
3174    StdoutClosed,
3175    StderrClosed,
3176}
3177
3178fn spawn_terminal_reader<R>(
3179    mut reader: R,
3180    tx: async_channel::Sender<TerminalChunk>,
3181    is_stderr: bool,
3182) where
3183    R: Read + Send + 'static,
3184{
3185    std::thread::spawn(move || {
3186        let mut buffer = vec![0_u8; 8192];
3187        loop {
3188            match reader.read(&mut buffer) {
3189                Ok(0) => {
3190                    let _ = tx.send_blocking(if is_stderr {
3191                        TerminalChunk::StderrClosed
3192                    } else {
3193                        TerminalChunk::StdoutClosed
3194                    });
3195                    break;
3196                }
3197                Ok(count) => {
3198                    let chunk = buffer[..count].to_vec();
3199                    let _ = tx.send_blocking(if is_stderr {
3200                        TerminalChunk::Stderr(chunk)
3201                    } else {
3202                        TerminalChunk::Stdout(chunk)
3203                    });
3204                }
3205                Err(error) => {
3206                    warn!(error = %error, is_stderr, "terminal reader failed");
3207                    let _ = tx.send_blocking(if is_stderr {
3208                        TerminalChunk::StderrClosed
3209                    } else {
3210                        TerminalChunk::StdoutClosed
3211                    });
3212                    break;
3213                }
3214            }
3215        }
3216    });
3217}
3218
3219fn spawn_terminal_stdin_writer<W>(mut writer: W) -> async_channel::Sender<Vec<u8>>
3220where
3221    W: Write + Send + 'static,
3222{
3223    let (tx, rx) = async_channel::unbounded::<Vec<u8>>();
3224    std::thread::spawn(move || {
3225        while let Ok(bytes) = rx.recv_blocking() {
3226            if bytes.is_empty() {
3227                continue;
3228            }
3229            if let Err(error) = writer.write_all(&bytes) {
3230                warn!(error = %error, "terminal stdin write failed");
3231                break;
3232            }
3233            if let Err(error) = writer.flush() {
3234                warn!(error = %error, "terminal stdin flush failed");
3235                break;
3236            }
3237        }
3238    });
3239    tx
3240}
3241
3242async fn drain_terminal_chunks(
3243    job_registry: JobRegistry,
3244    pid: u32,
3245    rx: async_channel::Receiver<TerminalChunk>,
3246) {
3247    while let Ok(chunk) = rx.recv().await {
3248        match chunk {
3249            TerminalChunk::Stdout(bytes) => job_registry.append_stdout(pid, bytes).await,
3250            TerminalChunk::Stderr(bytes) => job_registry.append_stderr(pid, bytes).await,
3251            TerminalChunk::StdoutClosed => job_registry.close_stdout(pid).await,
3252            TerminalChunk::StderrClosed => job_registry.close_stderr(pid).await,
3253        }
3254    }
3255}
3256
3257async fn wait_for_terminal_stream_close(job_registry: &JobRegistry, pid: u32) {
3258    while !job_registry.terminal_streams_closed(pid).await {
3259        async_io::Timer::after(Duration::from_millis(10)).await;
3260    }
3261}
3262
3263/// Creates the IPC router with built-in and tool commands (standalone version).
3264fn create_ipc_router(registry: &Arc<ToolRegistry>) -> Option<IpcRouter> {
3265    let mut router = builtin_router();
3266
3267    // Register all configured tools as IPC commands
3268    let tool_names = registry.registered_tool_names();
3269    tracing::info!(tools = ?tool_names, "Creating IPC router with registered tools");
3270    for name in tool_names {
3271        router = crate::register_tool_command(router, Arc::clone(registry), &name);
3272    }
3273
3274    let has_methods = router.methods().next().is_some();
3275    has_methods.then_some(router)
3276}
3277
3278fn create_ipc_gateway_router(registry: &Arc<ToolRegistry>) -> Option<IpcRouter> {
3279    let mut router = crate::register_ipc_gateway_command(IpcRouter::new(), Arc::clone(registry));
3280
3281    // In unsafe mode, keep tool commands usable (websearch/webfetch/ask/task/todo...),
3282    // but never override native shell task/process commands like kill/jobs.
3283    let blocked = ["kill", "jobs"];
3284    let tool_names = registry.registered_tool_names();
3285    for name in tool_names {
3286        if blocked.contains(&name.as_str()) {
3287            continue;
3288        }
3289        router = crate::register_tool_command(router, Arc::clone(registry), &name);
3290    }
3291
3292    let has_methods = router.methods().next().is_some();
3293    has_methods.then_some(router)
3294}
3295
3296/// Errors that can occur during terminal execution.
3297#[derive(Debug, thiserror::Error)]
3298pub enum TerminalError {
3299    /// Execution environment or mode is not configured.
3300    #[error("invalid terminal execution target: {0}")]
3301    InvalidTarget(String),
3302    /// Required tool runtime is unavailable or unsafe to expose.
3303    #[error(transparent)]
3304    Tools(#[from] ToolRuntimeError),
3305    /// Permission denied for the requested mode.
3306    #[error(
3307        "sandbox blocked {mode} execution; approval is required to escalate this terminal command",
3308        mode = .0.description()
3309    )]
3310    PermissionDenied(TerminalMode),
3311
3312    /// Permission check failed.
3313    #[error("permission error: {0}")]
3314    Permission(#[from] PermissionError),
3315
3316    /// Sandbox setup failed.
3317    #[error("sandbox setup failed: {0}")]
3318    SandboxSetup(String),
3319
3320    /// Script execution failed.
3321    #[error("execution failed: {0}")]
3322    Execution(String),
3323
3324    /// IO error.
3325    #[error("io error: {0}")]
3326    Io(#[from] std::io::Error),
3327}
3328
3329impl<P, E, State> std::fmt::Debug for TerminalTool<P, E, State> {
3330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3331        f.debug_struct("TerminalTool")
3332            .field("working_dir", &self.working_dir)
3333            .finish_non_exhaustive()
3334    }
3335}
3336
3337#[cfg(test)]
3338mod tests {
3339    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
3340    use std::time::Duration;
3341
3342    use super::*;
3343    use crate::ToolRegistryBuilder;
3344    use crate::builtin::{InputTerminalArgs, InputTerminalTool};
3345    use heel::{DenyAll, NiceLevel};
3346
3347    async fn prepared_test_registry() -> (tempfile::TempDir, ShellSessionRegistry) {
3348        let cache = tempfile::tempdir().unwrap();
3349        let tools = crate::tool_runtime::tests::bundle()
3350            .prepare_local(cache.path())
3351            .await
3352            .unwrap();
3353        let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
3354            local: true,
3355            container: false,
3356            ssh: false,
3357        })
3358        .with_test_tools(tools);
3359        (cache, registry)
3360    }
3361
3362    /// Counts the consent prompts an SSH authorizer receives and denies each.
3363    #[derive(Default)]
3364    struct CountingSshAuthorizer {
3365        connects: AtomicUsize,
3366        installs: AtomicUsize,
3367    }
3368
3369    impl crate::SshSessionAuthorizer for CountingSshAuthorizer {
3370        fn authorize_connect(
3371            &self,
3372            _target: &str,
3373        ) -> impl std::future::Future<Output = Result<bool, crate::SshAuthorizationError>> + Send
3374        {
3375            self.connects.fetch_add(1, AtomicOrdering::SeqCst);
3376            std::future::ready(Ok(false))
3377        }
3378
3379        fn authorize_runtime_install(
3380            &self,
3381            _target: &str,
3382            _details: &str,
3383        ) -> impl std::future::Future<Output = Result<bool, crate::SshAuthorizationError>> + Send
3384        {
3385            self.installs.fetch_add(1, AtomicOrdering::SeqCst);
3386            std::future::ready(Ok(false))
3387        }
3388    }
3389
3390    /// A container executor for registries whose container is never reached.
3391    struct UnreachableContainerExec;
3392
3393    impl crate::ContainerExec for UnreachableContainerExec {
3394        fn exec(
3395            &self,
3396            _container_id: &str,
3397            _script: &str,
3398            _working_dir: &str,
3399            _kill_rx: Receiver<()>,
3400            _stdin_rx: Receiver<Vec<u8>>,
3401            _stdin_blocked_notice: Option<Sender<String>>,
3402        ) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
3403        {
3404            std::future::ready(Err("adoption never executes in the container".to_string()))
3405        }
3406    }
3407
3408    fn test_container_runtime(container_id: &str) -> ContainerShellRuntime {
3409        ContainerShellRuntime::new(
3410            container_id,
3411            crate::ContainerIpcRoute::new(
3412                "host.docker.internal",
3413                crate::BridgeAddress::try_from(std::net::IpAddr::from([127, 0, 0, 1]))
3414                    .expect("loopback binds the bridge"),
3415            ),
3416            crate::AnyContainerExec::new(Arc::new(UnreachableContainerExec)),
3417        )
3418    }
3419
3420    fn build_server() -> crate::SshServer {
3421        crate::SshServer {
3422            name: "build".to_string(),
3423            target: "builder@build.internal".to_string(),
3424        }
3425    }
3426
3427    /// Local and SSH configuration gated by `authorizer`, not yet prepared.
3428    fn local_and_ssh_registry(authorizer: &Arc<CountingSshAuthorizer>) -> ShellSessionRegistry {
3429        ShellSessionRegistry::new(ShellRuntimeAvailability {
3430            local: true,
3431            container: false,
3432            ssh: true,
3433        })
3434        .with_ssh_servers(vec![build_server()])
3435        .expect("ssh server should configure")
3436        .with_ssh_authorizer(Arc::clone(authorizer))
3437    }
3438
3439    async fn fresh_terminal(
3440        dir: &Path,
3441    ) -> TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> {
3442        TerminalTool::new_exact(
3443            dir,
3444            TestPermissionHandler::default(),
3445            executor_core::tokio::TokioGlobal,
3446        )
3447        .await
3448        .expect("terminal tool should initialize")
3449    }
3450
3451    /// A trusted manifest serving `script` for every managed tool at version 1.0.0.
3452    #[cfg(unix)]
3453    async fn script_distribution(directory: &Path, script: &[u8]) -> ToolDistribution {
3454        let path = directory.join("baseline-tool");
3455        async_fs::write(&path, script).await.unwrap();
3456        let artifacts = crate::ManagedTool::ALL
3457            .into_iter()
3458            .map(|tool| crate::ToolArtifact {
3459                tool,
3460                version: "1.0.0".into(),
3461                target: crate::ToolTarget::native().unwrap(),
3462                url: crate::ToolArtifactLocation::Download(
3463                    url::Url::from_file_path(&path).unwrap(),
3464                ),
3465                sha256: hex::encode(crate::tool_runtime::digest(script)),
3466                encoding: crate::ToolArtifactFormat::Executable,
3467            })
3468            .collect::<Vec<_>>();
3469        ToolDistribution::from_json(
3470            &serde_json::to_vec(&serde_json::json!({ "artifacts": artifacts })).unwrap(),
3471        )
3472        .unwrap()
3473    }
3474
3475    #[cfg(unix)]
3476    #[tokio::test(flavor = "multi_thread")]
3477    async fn adopted_registry_runs_baseline_tools_without_ssh_consent_or_version_probes() {
3478        let authorizer = Arc::new(CountingSshAuthorizer::default());
3479
3480        // Full preparation asks the authorizer before connecting to every
3481        // server; the denial ends it.
3482        let artifacts = tempfile::tempdir().unwrap();
3483        let distribution = script_distribution(
3484            artifacts.path(),
3485            b"#!/bin/sh\nprintf '%s\\n' 'tool 1.0.0'\n",
3486        )
3487        .await;
3488        let first = tempfile::tempdir().unwrap();
3489        let cache = tempfile::tempdir().unwrap();
3490        let denied = fresh_terminal(first.path())
3491            .await
3492            .with_shell_sessions(local_and_ssh_registry(&authorizer))
3493            .initialize_tools(&distribution, cache.path())
3494            .await;
3495        assert!(
3496            matches!(denied, Err(ToolRuntimeError::SshBootstrap(_))),
3497            "a denied connection must fail preparation"
3498        );
3499        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
3500
3501        // Tools pinned to a version their commands do not report: the version
3502        // probe of full preparation rejects them.
3503        let tools_cache = tempfile::tempdir().unwrap();
3504        let tools = crate::tool_runtime::tests::bundle_pinned("2.0.0")
3505            .prepare_local(tools_cache.path())
3506            .await
3507            .unwrap();
3508        assert!(matches!(
3509            tools
3510                .verify_local_versions(executor_core::tokio::TokioGlobal)
3511                .await,
3512            Err(ToolRuntimeError::VersionMismatch(_))
3513        ));
3514        let prepared = local_and_ssh_registry(&authorizer)
3515            .with_test_tools(tools.clone())
3516            .with_test_ssh(build_server(), tools);
3517
3518        let second = tempfile::tempdir().unwrap();
3519        let terminal = fresh_terminal(second.path())
3520            .await
3521            .adopt_prepared_tools(prepared)
3522            .await
3523            .expect("a prepared registry should be adopted without probing or consent");
3524        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
3525        assert_eq!(authorizer.installs.load(AtomicOrdering::SeqCst), 0);
3526
3527        let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
3528        let terminal = terminal.with_registry(registry);
3529        let result = terminal
3530            .call(
3531                TerminalArgs {
3532                    description: "run every baseline command".to_string(),
3533                    script: "apply_patch --version && rg --version && ast-grep --version && jq --version"
3534                        .to_string(),
3535                    mode: TerminalExecutionMode::Sandboxed,
3536                    ssh_server_id: None,
3537                    expect: OutputFormat::Text,
3538                    resolution: MediaResolution::Auto,
3539                    timeout: 30,
3540                    max_lines: 50,
3541                    raw: true,
3542                },
3543                ToolContext::new(),
3544            )
3545            .await
3546            .expect("baseline commands should run");
3547        let payload = parse_terminal_tool_result(&result);
3548        assert_eq!(payload.exit_code, 0, "{payload:?}");
3549        let stdout = output_text(&payload.stdout).unwrap_or_default();
3550        for command in ["apply_patch", "rg", "ast-grep", "jq"] {
3551            assert!(
3552                stdout.contains(&format!("{command} 1.0.0")),
3553                "{command} should run from the adopted tools; stdout: {stdout}"
3554            );
3555        }
3556        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 1);
3557        assert_eq!(authorizer.installs.load(AtomicOrdering::SeqCst), 0);
3558    }
3559
3560    #[tokio::test]
3561    async fn adoption_rejects_a_registry_changed_after_preparation() {
3562        let authorizer = Arc::new(CountingSshAuthorizer::default());
3563        let tools_cache = tempfile::tempdir().unwrap();
3564        let tools = crate::tool_runtime::tests::bundle()
3565            .prepare_local(tools_cache.path())
3566            .await
3567            .unwrap();
3568        let prepared = local_and_ssh_registry(&authorizer)
3569            .with_test_tools(tools.clone())
3570            .with_test_ssh(build_server(), tools.clone());
3571        let staging = crate::SshServer {
3572            name: "staging".to_string(),
3573            target: "deploy@staging.internal".to_string(),
3574        };
3575        let retargeted = crate::SshServer {
3576            target: "builder@build-2.internal".to_string(),
3577            ..build_server()
3578        };
3579        let container = ShellSessionRegistry::new(ShellRuntimeAvailability {
3580            local: false,
3581            container: true,
3582            ssh: false,
3583        })
3584        .with_container_runtime(test_container_runtime("aither-tools-a"))
3585        .with_test_container_tools(
3586            crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::bundle()),
3587            "aither-tools-a".to_string(),
3588        );
3589
3590        let dir = tempfile::tempdir().unwrap();
3591        let adopt = |sessions: ShellSessionRegistry| {
3592            let dir = dir.path().to_path_buf();
3593            async move {
3594                fresh_terminal(&dir)
3595                    .await
3596                    .adopt_prepared_tools(sessions)
3597                    .await
3598            }
3599        };
3600
3601        assert!(adopt(prepared.clone()).await.is_ok());
3602        assert!(adopt(container.clone()).await.is_ok());
3603        assert!(matches!(
3604            adopt(local_and_ssh_registry(&authorizer)).await,
3605            Err(ToolRuntimeError::NotInitialized(_))
3606        ));
3607        for servers in [vec![build_server(), staging], Vec::new(), vec![retargeted]] {
3608            assert!(matches!(
3609                adopt(prepared.clone().with_ssh_servers(servers).unwrap()).await,
3610                Err(ToolRuntimeError::EnvironmentChanged(
3611                    crate::PreparedEnvironment::SshServers
3612                ))
3613            ));
3614        }
3615        assert!(matches!(
3616            adopt(container.with_container_runtime(test_container_runtime("aither-tools-b"))).await,
3617            Err(ToolRuntimeError::EnvironmentChanged(
3618                crate::PreparedEnvironment::Container
3619            ))
3620        ));
3621        assert!(matches!(
3622            adopt(prepared.with_availability(ShellRuntimeAvailability {
3623                local: true,
3624                container: true,
3625                ssh: true,
3626            }))
3627            .await,
3628            Err(ToolRuntimeError::EnvironmentChanged(
3629                crate::PreparedEnvironment::HomeBackend
3630            ))
3631        ));
3632        assert_eq!(authorizer.connects.load(AtomicOrdering::SeqCst), 0);
3633    }
3634
3635    #[tokio::test]
3636    async fn adoption_rechecks_this_terminals_writable_paths() {
3637        let (cache, prepared) = prepared_test_registry().await;
3638        let dir = tempfile::tempdir().unwrap();
3639        let exposed = fresh_terminal(dir.path())
3640            .await
3641            .with_writable_paths([cache.path()])
3642            .adopt_prepared_tools(prepared)
3643            .await;
3644        assert!(matches!(
3645            exposed,
3646            Err(ToolRuntimeError::WritableToolDirectory(_))
3647        ));
3648    }
3649
3650    fn parse_terminal_tool_result(result: &ToolResult) -> TerminalResult {
3651        serde_json::from_str(
3652            &result
3653                .render_for_model()
3654                .expect("terminal result should render"),
3655        )
3656        .expect("terminal tool output should decode")
3657    }
3658
3659    #[cfg(unix)]
3660    #[test]
3661    fn shell_launch_uses_a_stable_posix_contract() {
3662        let script = "printf '%s\\n' hello | sed -n '1p'";
3663        let (program, args) = shell_launch(script);
3664
3665        assert_eq!(program, "sh");
3666        assert_eq!(args, ["-c", script]);
3667    }
3668
3669    #[tokio::test]
3670    async fn session_runtime_environment_is_prepared_without_wrapping_the_script() {
3671        let dir = tempfile::tempdir().expect("temp dir should be created");
3672        let cache = tempfile::tempdir().unwrap();
3673        let ready = crate::tool_runtime::tests::bundle()
3674            .prepare_local(cache.path())
3675            .await
3676            .unwrap();
3677        let environment = prepare_session_runtime_environment(dir.path(), &ready)
3678            .await
3679            .expect("session runtime environment should be prepared");
3680        let value = |name: &str| {
3681            environment
3682                .iter()
3683                .find_map(|(key, value)| (key == name).then_some(value.as_str()))
3684                .unwrap_or_else(|| panic!("missing session environment variable {name}"))
3685        };
3686
3687        assert_eq!(value("HOME"), dir.path().to_str().expect("UTF-8 temp path"));
3688        assert_eq!(
3689            value("TMPDIR"),
3690            dir.path().join("tmp").to_str().expect("UTF-8 temp path")
3691        );
3692        assert_eq!(value("TMP"), value("TMPDIR"));
3693        assert_eq!(value("TEMP"), value("TMPDIR"));
3694        assert!(dir.path().join("tmp").is_dir());
3695        assert!(dir.path().join(".cache/bun").is_dir());
3696        assert!(dir.path().join(".cache/ms-playwright").is_dir());
3697        assert!(dir.path().join(".config").is_dir());
3698    }
3699
3700    fn output_text(output: &OutputEntry) -> Option<&str> {
3701        match output {
3702            OutputEntry::Inline { content } | OutputEntry::Loaded { content, .. } => {
3703                match content {
3704                    Content::Text { text, .. } => Some(text.as_str()),
3705                    Content::Image { .. } => None,
3706                }
3707            }
3708            OutputEntry::Stored { content, .. } => match content.as_ref() {
3709                Some(Content::Text { text, .. }) => Some(text.as_str()),
3710                Some(Content::Image { .. }) | None => None,
3711            },
3712            OutputEntry::Empty => None,
3713        }
3714    }
3715
3716    async fn wait_for_completed_task(
3717        receiver: &BackgroundTaskReceiver,
3718        task_id: &str,
3719    ) -> CompletedTask {
3720        tokio::time::timeout(Duration::from_secs(5), async {
3721            loop {
3722                if let Some(task) = receiver
3723                    .take_completed()
3724                    .into_iter()
3725                    .find(|task| task.task_id == task_id)
3726                {
3727                    return task;
3728                }
3729                tokio::time::sleep(Duration::from_millis(50)).await;
3730            }
3731        })
3732        .await
3733        .expect("background task should complete after terminal input")
3734    }
3735
3736    #[derive(Default)]
3737    struct TestPermissionHandler {
3738        mode_checks: AtomicUsize,
3739        domain_checks: AtomicUsize,
3740        allow_domain: bool,
3741    }
3742
3743    impl PermissionHandler for TestPermissionHandler {
3744        fn check(
3745            &self,
3746            mode: TerminalMode,
3747            _script: &str,
3748        ) -> impl std::future::Future<Output = Result<bool, PermissionError>> + Send {
3749            self.mode_checks.fetch_add(1, AtomicOrdering::Relaxed);
3750            std::future::ready(Ok(match mode {
3751                TerminalMode::Sandboxed => true,
3752                TerminalMode::Unsafe => false,
3753            }))
3754        }
3755
3756        fn check_domain(
3757            &self,
3758            _domain: &str,
3759            _port: u16,
3760        ) -> impl std::future::Future<Output = bool> + Send {
3761            self.domain_checks.fetch_add(1, AtomicOrdering::Relaxed);
3762            std::future::ready(self.allow_domain)
3763        }
3764    }
3765
3766    #[tokio::test]
3767    async fn test_terminal_args_defaults() {
3768        let args: TerminalArgs = serde_json::from_str(
3769            r#"{"description":"print a greeting","script":"echo hello","timeout":1}"#,
3770        )
3771        .unwrap();
3772        assert_eq!(args.expect, OutputFormat::Text);
3773        assert_eq!(args.resolution, MediaResolution::Auto);
3774        assert_eq!(args.timeout, 1);
3775        assert_eq!(args.mode, TerminalExecutionMode::Default);
3776    }
3777
3778    #[tokio::test]
3779    async fn test_terminal_result_serialization() {
3780        use crate::output::Content;
3781
3782        let result = TerminalResult {
3783            stdout: OutputEntry::Stored {
3784                url: "outputs/bold-oak-calm-river.txt".to_string(),
3785                path: "/tmp/outputs/bold-oak-calm-river.txt".to_string(),
3786                content: Some(Content::Text {
3787                    text: "preview text".to_string(),
3788                    truncated: true,
3789                }),
3790            },
3791            stderr: None,
3792            exit_code: 0,
3793            task_id: None,
3794            status: None,
3795            background_reason: None,
3796        };
3797
3798        let json = serde_json::to_string(&result).unwrap();
3799        assert!(json.contains("bold-oak-calm-river.txt"));
3800        assert!(!json.contains("stderr")); // should be skipped when None
3801        assert!(!json.contains("task_id")); // should be skipped when None
3802
3803        // Test inline output (no URL)
3804        let result_inline = TerminalResult {
3805            stdout: OutputEntry::Inline {
3806                content: Content::Text {
3807                    text: "done".to_string(),
3808                    truncated: false,
3809                },
3810            },
3811            stderr: None,
3812            exit_code: 0,
3813            task_id: None,
3814            status: None,
3815            background_reason: None,
3816        };
3817        let json_inline = serde_json::to_string(&result_inline).unwrap();
3818        assert!(!json_inline.contains("\"url\""));
3819        assert!(json_inline.contains("\"content\""));
3820
3821        // Test background task result
3822        let result_background = TerminalResult {
3823            stdout: OutputEntry::Empty,
3824            stderr: None,
3825            exit_code: 0,
3826            task_id: Some("amber-forest-thunder-pearl".to_string()),
3827            status: Some("running".to_string()),
3828            background_reason: Some(BackgroundReason::Timeout {
3829                configured_seconds: 30,
3830            }),
3831        };
3832        let json_bg = serde_json::to_string(&result_background).unwrap();
3833        assert!(json_bg.contains("\"task_id\":\"amber-forest-thunder-pearl\""));
3834        assert!(json_bg.contains("\"status\":\"running\""));
3835    }
3836
3837    #[tokio::test]
3838    async fn test_terminal_args_timeout() {
3839        let args: TerminalArgs = serde_json::from_str(
3840            r#"{"description":"print a greeting","script":"echo hello","timeout":0}"#,
3841        )
3842        .unwrap();
3843        assert_eq!(args.timeout, 0);
3844
3845        let args_default = serde_json::from_str::<TerminalArgs>(
3846            r#"{"description":"print a greeting","script":"echo hello"}"#,
3847        )
3848        .unwrap_err();
3849        assert!(args_default.to_string().contains("timeout"));
3850
3851        let missing_description =
3852            serde_json::from_str::<TerminalArgs>(r#"{"script":"echo hello","timeout":1}"#)
3853                .unwrap_err();
3854        assert!(missing_description.to_string().contains("description"));
3855    }
3856
3857    /// The tools bin directory a container execution passes to the wrapper.
3858    fn container_tools_dir() -> ContainerPath {
3859        crate::tool_runtime::tests::container_tools(&crate::tool_runtime::tests::bundle())
3860            .bin_dir()
3861            .clone()
3862    }
3863
3864    #[test]
3865    fn wrap_container_script_refreshes_command_hash_table() {
3866        let wrapped = wrap_container_script(
3867            "websearch \"gold price\"",
3868            &[String::from("websearch")],
3869            Some(ContainerIpcEndpoint {
3870                host: "host.docker.internal",
3871                port: 9000,
3872            }),
3873            ProcessPriority::default(),
3874            &container_tools_dir(),
3875            CONTAINER_EXEC_WORKING_DIR,
3876        )
3877        .expect("wrap script");
3878        assert!(wrapped.contains("hash -r;"));
3879        assert!(wrapped.contains("MAY_IPC_DIR"));
3880        assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
3881    }
3882
3883    #[test]
3884    fn wrap_container_script_preserves_user_script_semantics() {
3885        let script = "echo '$5,040' && subagent --subagent .skills/slide/subagents/art_direction.md --prompt 'x'";
3886        let wrapped = wrap_container_script(
3887            script,
3888            &[String::from("subagent")],
3889            Some(ContainerIpcEndpoint {
3890                host: "host.docker.internal",
3891                port: 9000,
3892            }),
3893            ProcessPriority::default(),
3894            &container_tools_dir(),
3895            CONTAINER_EXEC_WORKING_DIR,
3896        )
3897        .expect("wrap script");
3898        assert!(wrapped.contains(script));
3899        assert!(!wrapped.contains("set -euo pipefail"));
3900    }
3901
3902    #[test]
3903    fn wrap_container_script_rejects_invalid_ipc_command_names() {
3904        let error = wrap_container_script(
3905            "echo ok",
3906            &[String::from("bad name")],
3907            Some(ContainerIpcEndpoint {
3908                host: "host.docker.internal",
3909                port: 9000,
3910            }),
3911            ProcessPriority::default(),
3912            &container_tools_dir(),
3913            CONTAINER_EXEC_WORKING_DIR,
3914        )
3915        .expect_err("invalid command name must fail");
3916        assert!(
3917            error
3918                .to_string()
3919                .contains("invalid ipc command name for container wrapper")
3920        );
3921    }
3922
3923    #[test]
3924    fn wrap_container_script_renders_expected_endpoint() {
3925        let wrapped = wrap_container_script(
3926            "environment --query deployment",
3927            &[String::from("environment"), String::from("session")],
3928            Some(ContainerIpcEndpoint {
3929                host: "host.containers.internal",
3930                port: 43123,
3931            }),
3932            ProcessPriority::default(),
3933            &container_tools_dir(),
3934            CONTAINER_EXEC_WORKING_DIR,
3935        )
3936        .expect("wrap script");
3937        assert!(wrapped.contains("tcp://host.containers.internal:43123"));
3938        assert!(wrapped.contains("for cmd in 'environment' 'session'; do"));
3939    }
3940
3941    #[tokio::test]
3942    async fn ensure_mode_allowed_requires_unsafe_approval() {
3943        let handler = TestPermissionHandler {
3944            allow_domain: true,
3945            ..Default::default()
3946        };
3947        let err = ensure_mode_allowed(&handler, TerminalMode::Unsafe, "rm -rf /tmp/demo")
3948            .await
3949            .expect_err("unsafe mode should be denied");
3950        assert!(matches!(
3951            err,
3952            TerminalError::PermissionDenied(TerminalMode::Unsafe)
3953        ));
3954        assert_eq!(handler.mode_checks.load(AtomicOrdering::Relaxed), 1);
3955    }
3956
3957    #[tokio::test]
3958    async fn permission_network_policy_delegates_domain_checks() {
3959        let handler = Arc::new(TestPermissionHandler {
3960            allow_domain: true,
3961            ..Default::default()
3962        });
3963        let policy = PermissionNetworkPolicy {
3964            permission_handler: handler.clone(),
3965        };
3966        let request = DomainRequest::new("example.com", 443);
3967        assert!(policy.check(&request).await);
3968        assert_eq!(handler.domain_checks.load(AtomicOrdering::Relaxed), 1);
3969    }
3970
3971    #[test]
3972    fn sandboxed_execution_mode_deserializes() {
3973        let mode: TerminalExecutionMode =
3974            serde_json::from_str("\"sandboxed\"").expect("sandboxed mode must deserialize");
3975        assert_eq!(mode, TerminalExecutionMode::Sandboxed);
3976    }
3977
3978    #[tokio::test]
3979    async fn uninitialized_terminal_rejects_execution_and_catalog() {
3980        let dir = tempfile::tempdir().unwrap();
3981        let tool = TerminalTool::new_exact(
3982            dir.path(),
3983            TestPermissionHandler::default(),
3984            executor_core::tokio::TokioGlobal,
3985        )
3986        .await
3987        .unwrap();
3988        assert!(matches!(
3989            tool.prepared_tools_context(),
3990            Err(ToolRuntimeError::NotInitialized(_))
3991        ));
3992        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
3993        let tool = tool.with_registry(registry);
3994        assert!(matches!(
3995            tool.resolve_default_target(),
3996            Err(TerminalError::Tools(ToolRuntimeError::NotInitialized(_)))
3997        ));
3998    }
3999
4000    #[tokio::test]
4001    async fn child_terminal_exposes_controls_with_isolated_jobs() {
4002        let dir = tempfile::tempdir().expect("temp dir should be created");
4003        let (_cache, shell_sessions) = prepared_test_registry().await;
4004        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4005            TerminalTool::new_exact(
4006                dir.path(),
4007                TestPermissionHandler::default(),
4008                executor_core::tokio::TokioGlobal,
4009            )
4010            .await
4011            .expect("terminal tool should initialize")
4012            .adopt_prepared_tools(shell_sessions)
4013            .await
4014            .expect("prepared tools should be adopted");
4015        tool.job_registry()
4016            .register(
4017                424_242,
4018                "parent-task",
4019                "parent-execution",
4020                "sleep 30",
4021                TerminalMode::Sandboxed,
4022                None,
4023            )
4024            .await;
4025
4026        let child = tool.child();
4027        assert_eq!(
4028            tool.prepared_tools_context().unwrap(),
4029            child.prepared_tools_context().unwrap()
4030        );
4031        assert!(child.job_registry().list().await.is_empty());
4032        let parent_registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4033        let parent = tool.with_registry(parent_registry);
4034        let child = child.with_registry(parent.registry().clone());
4035        for name in ["terminal_kill", "terminal_input", "terminal_read"] {
4036            assert!(child.registry().is_tool_configured(name));
4037        }
4038        let args = vec!["--task-id".to_string(), "parent-task".to_string()];
4039        let parent_output = serde_json::to_value(
4040            parent
4041                .registry()
4042                .query_tool_handler("terminal_read", &args)
4043                .await,
4044        )
4045        .unwrap();
4046        let child_output = serde_json::to_value(
4047            child
4048                .registry()
4049                .query_tool_handler("terminal_read", &args)
4050                .await,
4051        )
4052        .unwrap();
4053        assert!(parent_output.to_string().contains("running"));
4054        assert!(!child_output.to_string().contains("running"));
4055        let names = child
4056            .to_dyn()
4057            .into_entries()
4058            .into_iter()
4059            .map(|entry| entry.definition.name().to_string())
4060            .collect::<Vec<_>>();
4061
4062        assert_eq!(names, vec!["terminal"]);
4063    }
4064
4065    async fn query_control(
4066        registry: &ToolRegistry,
4067        name: &str,
4068        args: &[&str],
4069    ) -> serde_json::Value {
4070        let args = args.iter().map(ToString::to_string).collect::<Vec<_>>();
4071        serde_json::to_value(registry.query_tool_handler(name, &args).await)
4072            .expect("command envelope should serialize")
4073    }
4074
4075    #[cfg(unix)]
4076    #[tokio::test]
4077    async fn configured_child_terminal_controls_address_child_jobs() {
4078        let dir = tempfile::tempdir().expect("temp dir should be created");
4079        let (_cache, shell_sessions) = prepared_test_registry().await;
4080        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4081            TerminalTool::new_exact(
4082                dir.path(),
4083                TestPermissionHandler::default(),
4084                executor_core::tokio::TokioGlobal,
4085            )
4086            .await
4087            .expect("terminal tool should initialize")
4088            .adopt_prepared_tools(shell_sessions)
4089            .await
4090            .expect("prepared tools should be adopted")
4091            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
4092                local: true,
4093                container: false,
4094                ssh: false,
4095            });
4096        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4097        let parent = tool.with_registry(registry);
4098        let child = parent.child();
4099
4100        let result = child
4101            .call(
4102                TerminalArgs {
4103                    description: "echo one stdin line then sleep".to_string(),
4104                    script: "read line; printf 'got %s\\n' \"$line\"; sleep 30".to_string(),
4105                    mode: TerminalExecutionMode::Sandboxed,
4106                    ssh_server_id: None,
4107                    expect: OutputFormat::Text,
4108                    resolution: MediaResolution::Auto,
4109                    timeout: 0,
4110                    max_lines: 50,
4111                    raw: false,
4112                },
4113                ToolContext::new(),
4114            )
4115            .await
4116            .expect("terminal call should succeed");
4117        let payload = parse_terminal_tool_result(&result);
4118        assert_eq!(payload.status.as_deref(), Some("running"));
4119        let task_id = payload
4120            .task_id
4121            .expect("timeout=0 should return a background task id");
4122
4123        let input = query_control(
4124            child.registry(),
4125            "terminal_input",
4126            &["--task-id", &task_id, "--input", "ping"],
4127        )
4128        .await;
4129        assert_eq!(input["ok"], true, "child terminal_input failed: {input}");
4130
4131        let echoed = tokio::time::timeout(Duration::from_secs(10), async {
4132            loop {
4133                let read =
4134                    query_control(child.registry(), "terminal_read", &["--task-id", &task_id])
4135                        .await;
4136                assert_eq!(read["ok"], true, "child terminal_read failed: {read}");
4137                if read.to_string().contains("got ping") {
4138                    return read;
4139                }
4140                tokio::time::sleep(Duration::from_millis(50)).await;
4141            }
4142        })
4143        .await
4144        .expect("child terminal_read should observe the echoed line");
4145        assert!(echoed.to_string().contains("running"), "{echoed}");
4146
4147        let parent_read =
4148            query_control(parent.registry(), "terminal_read", &["--task-id", &task_id]).await;
4149        assert_eq!(parent_read["ok"], false, "{parent_read}");
4150        assert!(
4151            parent_read["error"]
4152                .as_str()
4153                .is_some_and(|error| error.contains("unknown task_id")),
4154            "parent terminal_read must not see the child's task: {parent_read}"
4155        );
4156        let parent_kill =
4157            query_control(parent.registry(), "terminal_kill", &["--task-id", &task_id]).await;
4158        assert!(
4159            parent_kill.to_string().contains("\"killed\":false"),
4160            "parent terminal_kill must not reach the child's task: {parent_kill}"
4161        );
4162
4163        let kill = query_control(child.registry(), "terminal_kill", &["--task-id", &task_id]).await;
4164        assert!(
4165            kill.to_string().contains("\"killed\":true"),
4166            "child terminal_kill should stop its task: {kill}"
4167        );
4168        let stopped =
4169            query_control(child.registry(), "terminal_read", &["--task-id", &task_id]).await;
4170        assert!(
4171            stopped.to_string().contains("\"kind\":\"killed\""),
4172            "child task should be reported killed: {stopped}"
4173        );
4174    }
4175
4176    // These four drive a real sandbox running `/bin/pwd`. `heel` reports
4177    // `UnsupportedPlatform` off Unix, and the binary they run does not exist
4178    // there either, so there is nothing for them to exercise on Windows.
4179    #[cfg(unix)]
4180    #[tokio::test]
4181    async fn sandboxed_command_output_executes_pwd() {
4182        let dir = tempfile::tempdir().expect("temp dir should be created");
4183        let config = SandboxConfig::builder()
4184            .network(DenyAll)
4185            .working_dir(dir.path())
4186            .security(SecurityConfig::interactive())
4187            .build();
4188        let sandbox = Sandbox::with_config_and_executor(config, executor_core::tokio::TokioGlobal)
4189            .await
4190            .expect("sandbox should initialize");
4191
4192        let output = sandbox
4193            .command("/bin/pwd")
4194            .output()
4195            .await
4196            .expect("sandbox command output should succeed");
4197        eprintln!("PWD OUTPUT STATUS: {:?}", output.status);
4198        eprintln!(
4199            "PWD OUTPUT STDOUT: {:?}",
4200            String::from_utf8_lossy(&output.stdout)
4201        );
4202        assert_eq!(output.status.code(), Some(0));
4203    }
4204
4205    #[cfg(unix)]
4206    #[tokio::test]
4207    async fn sandboxed_terminal_executes_pwd() {
4208        let dir = tempfile::tempdir().expect("temp dir should be created");
4209        let (_cache, shell_sessions) = prepared_test_registry().await;
4210        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4211            TerminalTool::new_exact(
4212                dir.path(),
4213                TestPermissionHandler::default(),
4214                executor_core::tokio::TokioGlobal,
4215            )
4216            .await
4217            .expect("terminal tool should initialize")
4218            .adopt_prepared_tools(shell_sessions)
4219            .await
4220            .expect("prepared tools should be adopted");
4221        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4222        let job_registry = tool.job_registry();
4223        let (startup_tx, _startup_rx) = async_channel::bounded(1);
4224        let result = execute_script_standalone(StandaloneExecution {
4225            working_dir: tool.working_dir().clone(),
4226            writable_paths: Vec::new(),
4227            readable_paths: Vec::new(),
4228            executor: executor_core::tokio::TokioGlobal,
4229            registry,
4230            permission_handler: Arc::new(TestPermissionHandler::default()),
4231            job_registry,
4232            task_id: "task-test".to_string(),
4233            execution_id: "exec-test".to_string(),
4234            background_mode: Arc::new(AtomicBool::new(false)),
4235            script: "/bin/pwd".to_string(),
4236            mode: TerminalMode::Sandboxed,
4237            backend: ExecutionBackend::Local(tool.shell_sessions.local_tools().unwrap().clone()),
4238            stdin_blocked_notice: None,
4239            background_startup: BackgroundStartup::new(startup_tx),
4240            network_audit: None,
4241            priority: ProcessPriority::default(),
4242            expect: OutputFormat::Text,
4243            resolution: MediaResolution::Auto,
4244            store_dir: tool.outputs_dir(),
4245            max_lines: 50,
4246            raw: false,
4247        })
4248        .await;
4249        match result {
4250            Ok(ok) => {
4251                eprintln!("PWD RESULT: {ok:?}");
4252                assert_eq!(ok.exit_code, 0, "unexpected terminal result: {ok:?}");
4253            }
4254            Err(error) => panic!("sandboxed pwd should succeed, got error: {error}"),
4255        }
4256    }
4257
4258    #[cfg(unix)]
4259    #[tokio::test]
4260    async fn failed_command_returns_json_with_nonzero_exit_code() {
4261        let dir = tempfile::tempdir().expect("temp dir should be created");
4262        let (_cache, shell_sessions) = prepared_test_registry().await;
4263        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4264            TerminalTool::new_exact(
4265                dir.path(),
4266                TestPermissionHandler::default(),
4267                executor_core::tokio::TokioGlobal,
4268            )
4269            .await
4270            .expect("terminal tool should initialize")
4271            .adopt_prepared_tools(shell_sessions)
4272            .await
4273            .expect("prepared tools should be adopted")
4274            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
4275                local: true,
4276                container: false,
4277                ssh: false,
4278            });
4279        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4280        let tool = tool.with_registry(registry);
4281
4282        let result = tool
4283            .call(
4284                TerminalArgs {
4285                    description: "exit with non-zero status".to_string(),
4286                    script: "exit 42".to_string(),
4287                    mode: TerminalExecutionMode::Sandboxed,
4288                    ssh_server_id: None,
4289                    expect: OutputFormat::Text,
4290                    resolution: MediaResolution::Auto,
4291                    timeout: 30,
4292                    max_lines: 50,
4293                    raw: false,
4294                },
4295                ToolContext::new(),
4296            )
4297            .await
4298            .expect("terminal call should not be promoted to transport error on non-zero exit");
4299
4300        assert!(
4301            !result.is_error(),
4302            "non-zero exit must not produce ToolResult::Error, got: {result:?}"
4303        );
4304        let payload = parse_terminal_tool_result(&result);
4305        assert_eq!(payload.exit_code, 42, "exit code should round-trip");
4306        assert!(
4307            payload.task_id.is_none(),
4308            "foreground completion must not carry a task id"
4309        );
4310        assert!(
4311            payload.status.is_none(),
4312            "foreground completion must not carry a running status"
4313        );
4314    }
4315
4316    #[cfg(unix)]
4317    #[tokio::test]
4318    async fn background_terminal_accepts_terminal_input() {
4319        let dir = tempfile::tempdir().expect("temp dir should be created");
4320        let (_cache, shell_sessions) = prepared_test_registry().await;
4321        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4322            TerminalTool::new_exact(
4323                dir.path(),
4324                TestPermissionHandler::default(),
4325                executor_core::tokio::TokioGlobal,
4326            )
4327            .await
4328            .expect("terminal tool should initialize")
4329            .adopt_prepared_tools(shell_sessions)
4330            .await
4331            .expect("prepared tools should be adopted")
4332            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
4333                local: true,
4334                container: false,
4335                ssh: false,
4336            });
4337        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4338        let tool = tool.with_registry(registry);
4339        let background_receiver = tool.background_receiver();
4340        let input_tool = InputTerminalTool::new(tool.job_registry());
4341
4342        let result = tool
4343            .call(
4344                TerminalArgs {
4345                    description: "wait for terminal input and echo it back".to_string(),
4346                    script: "printf 'name? '; read name; printf 'hello %s\\n' \"$name\""
4347                        .to_string(),
4348                    mode: TerminalExecutionMode::Sandboxed,
4349                    ssh_server_id: None,
4350                    expect: OutputFormat::Text,
4351                    resolution: MediaResolution::Auto,
4352                    timeout: 0,
4353                    max_lines: 50,
4354                    raw: false,
4355                },
4356                ToolContext::new(),
4357            )
4358            .await
4359            .expect("terminal call should succeed");
4360
4361        let payload = parse_terminal_tool_result(&result);
4362        assert_eq!(payload.status.as_deref(), Some("running"));
4363        let task_id = payload
4364            .task_id
4365            .clone()
4366            .expect("timeout=0 should return a background task id");
4367
4368        input_tool
4369            .call(
4370                InputTerminalArgs {
4371                    task_id: task_id.clone(),
4372                    input: "lexo".to_string(),
4373                    append_newline: true,
4374                },
4375                ToolContext::new(),
4376            )
4377            .await
4378            .expect("terminal_input should succeed");
4379
4380        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
4381        let terminal_result = completed
4382            .result
4383            .expect("background task should complete successfully after stdin input");
4384        let stdout =
4385            output_text(&terminal_result.stdout).expect("completed task should include stdout");
4386        assert!(
4387            stdout.contains("hello lexo"),
4388            "stdin input should reach the terminal process, got: {stdout}"
4389        );
4390    }
4391
4392    #[cfg(unix)]
4393    #[tokio::test]
4394    async fn killing_background_terminal_kills_descendant_processes() {
4395        let dir = tempfile::tempdir().expect("temp dir should be created");
4396        let (_cache, shell_sessions) = prepared_test_registry().await;
4397        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4398            TerminalTool::new_exact(
4399                dir.path(),
4400                TestPermissionHandler::default(),
4401                executor_core::tokio::TokioGlobal,
4402            )
4403            .await
4404            .expect("terminal tool should initialize")
4405            .adopt_prepared_tools(shell_sessions)
4406            .await
4407            .expect("prepared tools should be adopted")
4408            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
4409                local: true,
4410                container: false,
4411                ssh: false,
4412            });
4413        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4414        let tool = tool.with_registry(registry);
4415        let child_pid_path = dir.path().join("child.pid");
4416
4417        let result = tool
4418            .call(
4419                TerminalArgs {
4420                    description: "start a descendant process".to_string(),
4421                    script: "sleep 30 & echo $! > child.pid; wait".to_string(),
4422                    mode: TerminalExecutionMode::Sandboxed,
4423                    ssh_server_id: None,
4424                    expect: OutputFormat::Text,
4425                    resolution: MediaResolution::Auto,
4426                    timeout: 0,
4427                    max_lines: 50,
4428                    raw: false,
4429                },
4430                ToolContext::new(),
4431            )
4432            .await
4433            .expect("terminal call should succeed");
4434        let payload = parse_terminal_tool_result(&result);
4435        assert_eq!(payload.status.as_deref(), Some("running"));
4436
4437        let mut child_pid = None;
4438        for _ in 0..100 {
4439            // `echo $! > child.pid` creates the file before writing to it,
4440            // so a successful read can still yield empty or partial
4441            // content — poll until the pid actually parses.
4442            let parsed = match async_fs::read_to_string(&child_pid_path).await {
4443                Ok(value) => value.trim().parse::<i32>().ok(),
4444                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
4445                Err(error) => panic!("failed to read child pid: {error}"),
4446            };
4447            if let Some(pid) = parsed {
4448                child_pid = Some(pid);
4449                break;
4450            }
4451            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
4452        }
4453        let child_pid = child_pid.expect("descendant pid should be written before timeout");
4454
4455        assert_eq!(tool.job_registry().kill_running().await, 1);
4456
4457        for _ in 0..100 {
4458            let exists = unsafe { libc::kill(child_pid, 0) } == 0;
4459            if !exists {
4460                return;
4461            }
4462            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
4463        }
4464        panic!("descendant process {child_pid} survived terminal cancellation");
4465    }
4466
4467    #[cfg(target_os = "linux")]
4468    #[tokio::test]
4469    async fn sandboxed_terminal_auto_promotes_stdin_wait_and_accepts_input() {
4470        let dir = tempfile::tempdir().expect("temp dir should be created");
4471        let (_cache, shell_sessions) = prepared_test_registry().await;
4472        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4473            TerminalTool::new_exact(
4474                dir.path(),
4475                TestPermissionHandler::default(),
4476                executor_core::tokio::TokioGlobal,
4477            )
4478            .await
4479            .expect("terminal tool should initialize")
4480            .adopt_prepared_tools(shell_sessions)
4481            .await
4482            .expect("prepared tools should be adopted")
4483            .with_shell_runtime_availability(crate::ShellRuntimeAvailability {
4484                local: true,
4485                container: false,
4486                ssh: false,
4487            });
4488        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4489        let tool = tool.with_registry(registry);
4490        let background_receiver = tool.background_receiver();
4491        let input_tool = InputTerminalTool::new(tool.job_registry());
4492
4493        let result = tool
4494            .call(
4495                TerminalArgs {
4496                    description: "wait for terminal input and echo it back".to_string(),
4497                    script: "printf 'name? '; read name; printf 'hello %s\\n' \"$name\""
4498                        .to_string(),
4499                    mode: TerminalExecutionMode::Sandboxed,
4500                    ssh_server_id: None,
4501                    expect: OutputFormat::Text,
4502                    resolution: MediaResolution::Auto,
4503                    timeout: 30,
4504                    max_lines: 50,
4505                    raw: false,
4506                },
4507                ToolContext::new(),
4508            )
4509            .await
4510            .expect("terminal call should succeed");
4511
4512        let payload = parse_terminal_tool_result(&result);
4513        assert_eq!(payload.status.as_deref(), Some("running"));
4514        let task_id = payload
4515            .task_id
4516            .clone()
4517            .expect("stdin-blocked process should promote to background");
4518        let notice = output_text(&payload.stdout).expect("background preview should include text");
4519        assert!(
4520            notice.starts_with(TERMINAL_STDIN_BLOCKED_NOTICE),
4521            "unexpected promotion notice: {notice}"
4522        );
4523
4524        input_tool
4525            .call(
4526                InputTerminalArgs {
4527                    task_id: task_id.clone(),
4528                    input: "lexo".to_string(),
4529                    append_newline: true,
4530                },
4531                ToolContext::new(),
4532            )
4533            .await
4534            .expect("terminal_input should succeed");
4535
4536        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
4537        let terminal_result = completed
4538            .result
4539            .expect("background task should complete successfully after stdin input");
4540        let stdout =
4541            output_text(&terminal_result.stdout).expect("completed task should include stdout");
4542        assert!(
4543            stdout.contains("hello lexo"),
4544            "stdin input should reach the terminal process, got: {stdout}"
4545        );
4546    }
4547
4548    /// The nice value `level` steps below this test process lands at, capped
4549    /// at the kernel's lowest priority — the same computation heel applies.
4550    #[cfg(unix)]
4551    fn expected_lowered_nice(level: u8) -> i64 {
4552        // SAFETY: reads the calling process's own nice value.
4553        let current = unsafe { libc::getpriority(libc::PRIO_PROCESS as _, 0) };
4554        i64::from(current + i32::from(level)).min(19)
4555    }
4556
4557    #[cfg(unix)]
4558    fn test_nice_priority() -> ProcessPriority {
4559        ProcessPriority::new(
4560            CpuPriority::Nice(NiceLevel::new(10).expect("nice level 10 is in range")),
4561            IoPriority::Normal,
4562        )
4563    }
4564
4565    /// A terminal tool with prepared local tools and `priority` applied. The
4566    /// returned `TempDir` owns the prepared tools' cache; it must outlive the
4567    /// tool.
4568    #[cfg(unix)]
4569    async fn prioritized_terminal_tool(
4570        dir: &Path,
4571        priority: ProcessPriority,
4572    ) -> (
4573        tempfile::TempDir,
4574        TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal, Configured>,
4575    ) {
4576        let (cache, shell_sessions) = prepared_test_registry().await;
4577        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
4578            TerminalTool::new_exact(
4579                dir,
4580                TestPermissionHandler::default(),
4581                executor_core::tokio::TokioGlobal,
4582            )
4583            .await
4584            .expect("terminal tool should initialize")
4585            .adopt_prepared_tools(shell_sessions)
4586            .await
4587            .expect("prepared tools should be adopted")
4588            .with_process_priority(priority);
4589        let registry = Arc::new(ToolRegistryBuilder::new().build(tool.outputs_dir()));
4590        (cache, tool.with_registry(registry))
4591    }
4592
4593    /// A probe script made only of `sh` builtins: a strict sandbox executes
4594    /// nothing but the launched shell, the prepared tools and granted paths,
4595    /// so it reports its own `$$` into `pid` and waits for the host's `go`
4596    /// marker instead of running `nice`.
4597    #[cfg(unix)]
4598    fn pid_probe_args(timeout: u64) -> TerminalArgs {
4599        TerminalArgs {
4600            description: "report the process pid and wait".to_string(),
4601            script: concat!(
4602                "printf '%s\\n' $$ > \"$PWD/pid\"; ",
4603                "while [ ! -f \"$PWD/go\" ]; do :; done"
4604            )
4605            .to_string(),
4606            mode: TerminalExecutionMode::Sandboxed,
4607            ssh_server_id: None,
4608            expect: OutputFormat::Text,
4609            resolution: MediaResolution::Auto,
4610            timeout,
4611            max_lines: 50,
4612            raw: false,
4613        }
4614    }
4615
4616    /// Reads the pid the sandboxed probe wrote, retrying while the sandbox
4617    /// starts.
4618    #[cfg(unix)]
4619    async fn probe_pid(dir: &Path) -> u32 {
4620        let path = dir.join("pid");
4621        for _ in 0..150 {
4622            if let Ok(text) = std::fs::read_to_string(&path)
4623                && let Ok(pid) = text.trim().parse()
4624            {
4625                return pid;
4626            }
4627            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4628        }
4629        panic!("the sandboxed probe did not write {}", path.display());
4630    }
4631
4632    /// The `pid`'s nice level, read from the host while the probe is alive.
4633    #[cfg(unix)]
4634    fn probe_nice(pid: u32) -> i64 {
4635        // SAFETY: queries the kernel for the named process's priority.
4636        i64::from(unsafe { libc::getpriority(libc::PRIO_PROCESS as _, pid as _) })
4637    }
4638
4639    /// Releases the sandboxed probe by creating the `go` marker it polls for.
4640    #[cfg(unix)]
4641    fn release_probe(dir: &Path) {
4642        std::fs::File::create(dir.join("go")).expect("create the probe marker");
4643    }
4644
4645    #[cfg(unix)]
4646    #[tokio::test]
4647    async fn foreground_command_runs_with_configured_nice() {
4648        let dir = tempfile::tempdir().expect("temp dir should be created");
4649        let (_tools_cache, tool) =
4650            prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
4651
4652        let call = tool.call(pid_probe_args(30), ToolContext::new());
4653        let probe = async {
4654            let pid = probe_pid(dir.path()).await;
4655            assert_eq!(
4656                probe_nice(pid),
4657                expected_lowered_nice(10),
4658                "foreground command should run at the configured nice level"
4659            );
4660            release_probe(dir.path());
4661        };
4662        let (result, ()) = futures::join!(call, probe);
4663        let payload = parse_terminal_tool_result(&result.expect("terminal call should succeed"));
4664        assert_eq!(payload.exit_code, 0);
4665    }
4666
4667    #[cfg(unix)]
4668    #[tokio::test]
4669    async fn persistent_session_runs_with_configured_nice() {
4670        let dir = tempfile::tempdir().expect("temp dir should be created");
4671        let (_tools_cache, tool) =
4672            prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
4673        let background_receiver = tool.background_receiver();
4674        let input_tool = InputTerminalTool::new(tool.job_registry());
4675
4676        // `exec` keeps `$$` — the pid the probe wrote — on the interactive
4677        // shell the session then drives.
4678        let result = tool
4679            .call(
4680                TerminalArgs {
4681                    description: "start a persistent shell".to_string(),
4682                    script: "printf '%s\\n' $$ > \"$PWD/pid\"; exec sh".to_string(),
4683                    mode: TerminalExecutionMode::Sandboxed,
4684                    ssh_server_id: None,
4685                    expect: OutputFormat::Text,
4686                    resolution: MediaResolution::Auto,
4687                    timeout: 0,
4688                    max_lines: 50,
4689                    raw: false,
4690                },
4691                ToolContext::new(),
4692            )
4693            .await
4694            .expect("terminal call should succeed");
4695        let payload = parse_terminal_tool_result(&result);
4696        assert_eq!(payload.status.as_deref(), Some("running"));
4697        let task_id = payload
4698            .task_id
4699            .clone()
4700            .expect("timeout=0 should return a background task id");
4701
4702        let pid = probe_pid(dir.path()).await;
4703        assert_eq!(
4704            probe_nice(pid),
4705            expected_lowered_nice(10),
4706            "persistent session should run at the configured nice level"
4707        );
4708
4709        input_tool
4710            .call(
4711                InputTerminalArgs {
4712                    task_id: task_id.clone(),
4713                    input: "exit".to_string(),
4714                    append_newline: true,
4715                },
4716                ToolContext::new(),
4717            )
4718            .await
4719            .expect("terminal_input should succeed");
4720
4721        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
4722        let terminal_result = completed
4723            .result
4724            .expect("persistent shell should exit cleanly after input");
4725        assert_eq!(terminal_result.exit_code, 0);
4726    }
4727
4728    #[cfg(unix)]
4729    #[tokio::test]
4730    async fn background_job_runs_with_configured_nice() {
4731        let dir = tempfile::tempdir().expect("temp dir should be created");
4732        let (_tools_cache, tool) =
4733            prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
4734        let background_receiver = tool.background_receiver();
4735
4736        let result = tool
4737            .call(pid_probe_args(0), ToolContext::new())
4738            .await
4739            .expect("terminal call should succeed");
4740        let payload = parse_terminal_tool_result(&result);
4741        assert_eq!(payload.status.as_deref(), Some("running"));
4742        let task_id = payload
4743            .task_id
4744            .clone()
4745            .expect("timeout=0 should return a background task id");
4746
4747        let pid = probe_pid(dir.path()).await;
4748        assert_eq!(
4749            probe_nice(pid),
4750            expected_lowered_nice(10),
4751            "background job should run at the configured nice level"
4752        );
4753        release_probe(dir.path());
4754
4755        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
4756        let terminal_result = completed
4757            .result
4758            .expect("background job should complete successfully");
4759        assert_eq!(terminal_result.exit_code, 0);
4760    }
4761
4762    #[test]
4763    fn wrap_container_script_applies_configured_priority() {
4764        let priority = ProcessPriority::new(
4765            CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
4766            IoPriority::Background,
4767        );
4768        let tools_dir = container_tools_dir();
4769        let executable = format!("--executable {}", shell_escape(tools_dir.as_str()));
4770        let wrapped = wrap_container_script(
4771            "echo ok",
4772            &[String::from("websearch")],
4773            Some(ContainerIpcEndpoint {
4774                host: "host.docker.internal",
4775                port: 9000,
4776            }),
4777            priority,
4778            &tools_dir,
4779            "/workspace",
4780        )
4781        .expect("wrap script");
4782        assert!(wrapped.contains(
4783            "\"$MAY_IPC_BIN\" run --isolation permissive --working-dir '/workspace' \
4784             --env-passthrough PATH --env-passthrough HOME"
4785        ));
4786        assert!(wrapped.contains(&executable));
4787        assert!(wrapped.contains(
4788            "--ipc-endpoint 'tcp://host.docker.internal:9000' --grant \"$MAY_IPC_DIR=rx\" \
4789             --nice 5 --io-priority background -- sh -c 'echo ok'"
4790        ));
4791        assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
4792
4793        let bare = wrap_container_script("echo ok", &[], None, priority, &tools_dir, "/workspace")
4794            .expect("wrap script");
4795        assert!(bare.contains("MAY_HEEL_BIN=\"$(command -v heel || true)\""));
4796        assert!(bare.contains(
4797            "\"$MAY_HEEL_BIN\" run --isolation permissive --working-dir '/workspace' \
4798             --env-passthrough PATH --env-passthrough HOME"
4799        ));
4800        assert!(bare.contains(&executable));
4801        assert!(bare.contains("--nice 5 --io-priority background -- sh -c 'echo ok'"));
4802
4803        let normal = wrap_container_script(
4804            "echo ok",
4805            &[],
4806            None,
4807            ProcessPriority::default(),
4808            &tools_dir,
4809            "/workspace",
4810        )
4811        .expect("wrap script");
4812        assert_eq!(normal, "echo ok");
4813    }
4814
4815    #[test]
4816    fn wrap_container_script_prioritizes_each_half_independently() {
4817        let io_only = wrap_container_script(
4818            "echo ok",
4819            &[],
4820            None,
4821            ProcessPriority::new(CpuPriority::Normal, IoPriority::Utility),
4822            &container_tools_dir(),
4823            "/workspace",
4824        )
4825        .expect("wrap script");
4826        assert!(io_only.contains(" --io-priority utility -- sh -c 'echo ok'"));
4827        assert!(!io_only.contains("--nice"));
4828
4829        let cpu_only = wrap_container_script(
4830            "echo ok",
4831            &[],
4832            None,
4833            ProcessPriority::new(
4834                CpuPriority::Nice(NiceLevel::new(9).expect("nice level 9 is in range")),
4835                IoPriority::Normal,
4836            ),
4837            &container_tools_dir(),
4838            "/workspace",
4839        )
4840        .expect("wrap script");
4841        assert!(cpu_only.contains(" --nice 9 -- sh -c 'echo ok'"));
4842        assert!(!cpu_only.contains("--io-priority"));
4843    }
4844
4845    /// Probe tool for the container acceptance test: it answers an IPC call
4846    /// with the marker it was invoked with, so a request that actually reached
4847    /// the live handler is unmistakable.
4848    #[derive(Debug, Deserialize, JsonSchema)]
4849    struct ProbeEchoArgs {
4850        /// Marker echoed back to the caller.
4851        marker: String,
4852    }
4853
4854    struct ProbeEchoTool;
4855
4856    impl Tool for ProbeEchoTool {
4857        fn name(&self) -> Cow<'static, str> {
4858            "probe_echo".into()
4859        }
4860
4861        type Arguments = ProbeEchoArgs;
4862        type Res = ToolResult;
4863
4864        fn call(
4865            &self,
4866            arguments: Self::Arguments,
4867            _cx: ToolContext,
4868        ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
4869            std::future::ready(ToolResult::json(&serde_json::json!({
4870                "marker": arguments.marker,
4871            })))
4872        }
4873    }
4874
4875    /// Host side of the container IPC transport on every platform: a client
4876    /// speaking the bridge's framing over loopback TCP reaches the registry's
4877    /// live handler and gets its envelope back.
4878    #[tokio::test(flavor = "multi_thread")]
4879    async fn container_ipc_bridge_round_trips_a_command_over_tcp() {
4880        let outputs = tempfile::tempdir().expect("outputs dir should be created");
4881        let mut builder = ToolRegistryBuilder::new();
4882        builder.configure_tool(ProbeEchoTool);
4883        let registry = Arc::new(builder.build(outputs.path()));
4884        let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
4885        let bridge = start_container_ipc_bridge(
4886            executor_core::tokio::TokioGlobal,
4887            registry,
4888            BridgeAddress::try_from(loopback).expect("loopback binds the bridge"),
4889        )
4890        .expect("bridge should start on loopback");
4891
4892        let mut stream = Async::<StdTcpStream>::connect(SocketAddr::new(loopback, bridge.port()))
4893            .await
4894            .expect("client should connect to the bridge");
4895
4896        let method = b"probe_echo";
4897        let params = rmp_serde::to_vec_named(&serde_json::json!({ "marker": "pong" }))
4898            .expect("params should encode");
4899        let mut request = vec![u8::try_from(method.len()).expect("method name fits a byte")];
4900        request.extend_from_slice(method);
4901        request.extend_from_slice(&params);
4902        let request_length = u32::try_from(request.len()).expect("request fits the frame");
4903        stream
4904            .write_all(&request_length.to_be_bytes())
4905            .await
4906            .expect("request length should be written");
4907        stream
4908            .write_all(&request)
4909            .await
4910            .expect("request body should be written");
4911
4912        let mut length_bytes = [0_u8; 4];
4913        stream
4914            .read_exact(&mut length_bytes)
4915            .await
4916            .expect("response length should be read");
4917        let mut response = vec![0_u8; u32::from_be_bytes(length_bytes) as usize];
4918        stream
4919            .read_exact(&mut response)
4920            .await
4921            .expect("response body should be read");
4922
4923        let (success, payload) = response
4924            .split_first()
4925            .expect("response carries a success flag");
4926        assert_eq!(*success, 1, "bridge should report success");
4927        let envelope: serde_json::Value =
4928            rmp_serde::from_slice(payload).expect("response should decode as msgpack");
4929        assert_eq!(
4930            envelope,
4931            serde_json::to_value(crate::command::CommandEnvelope {
4932                ok: true,
4933                payload: Some(crate::command::CommandPayload::Json {
4934                    value: serde_json::json!({ "marker": "pong" }),
4935                }),
4936                error: None,
4937            })
4938            .expect("envelope should convert to JSON"),
4939            "probe_echo should answer from the live handler with field names, as heel's router does"
4940        );
4941
4942        drop(stream);
4943        bridge.stop().await;
4944    }
4945
4946    /// Scratch `ubuntu:24.04` container used by the acceptance test; removed
4947    /// on drop.
4948    #[cfg(all(unix, aither_container_acceptance))]
4949    struct TestDockerContainer(String);
4950
4951    #[cfg(all(unix, aither_container_acceptance))]
4952    impl TestDockerContainer {
4953        /// Starts a container with `heel_bin` mounted at `/usr/local/bin/heel`,
4954        /// the prepared tool bundle mounted read-only where production mounts
4955        /// it, and `host.docker.internal` resolving to the docker host gateway,
4956        /// and prepares the `/workspace` directory container executions run
4957        /// in. Returns `None` when docker cannot start the container.
4958        fn start(heel_bin: &Path, tools: &crate::MountSpec) -> Option<Self> {
4959            let name = format!("aither-test-{}", uuid::Uuid::new_v4().simple());
4960            let mount = format!("{}:/usr/local/bin/heel:ro", heel_bin.display());
4961            let tools_mount = format!("{}:{}:ro", tools.host_path.display(), tools.container_path);
4962            let output = std::process::Command::new("docker")
4963                .args([
4964                    "run",
4965                    "-d",
4966                    "--name",
4967                    &name,
4968                    "--add-host=host.docker.internal:host-gateway",
4969                    "-v",
4970                    &mount,
4971                    "-v",
4972                    &tools_mount,
4973                    "ubuntu:24.04",
4974                    "tail",
4975                    "-f",
4976                    "/dev/null",
4977                ])
4978                .output()
4979                .ok()?;
4980            if !output.status.success() {
4981                return None;
4982            }
4983            let prepared = std::process::Command::new("docker")
4984                .args(["exec", &name, "mkdir", "-p", CONTAINER_EXEC_WORKING_DIR])
4985                .output()
4986                .is_ok_and(|output| output.status.success());
4987            if !prepared {
4988                let _ = std::process::Command::new("docker")
4989                    .args(["rm", "-f", &name])
4990                    .output();
4991                return None;
4992            }
4993            Some(Self(name))
4994        }
4995    }
4996
4997    #[cfg(all(unix, aither_container_acceptance))]
4998    impl Drop for TestDockerContainer {
4999        fn drop(&mut self) {
5000            let _ = std::process::Command::new("docker")
5001                .args(["rm", "-f", &self.0])
5002                .output();
5003        }
5004    }
5005
5006    /// The docker `bridge` network's gateway as the host owns it — the
5007    /// address `host.docker.internal` resolves to inside the container via
5008    /// `--add-host …:host-gateway`, so it is the address the IPC bridge binds.
5009    #[cfg(all(unix, aither_container_acceptance))]
5010    async fn container_bridge_address(
5011        client: &bollard::Docker,
5012        container_id: &str,
5013    ) -> BridgeAddress {
5014        client
5015            .inspect_container(
5016                container_id,
5017                None::<bollard::query_parameters::InspectContainerOptions>,
5018            )
5019            .await
5020            .expect("container acceptance should inspect the container")
5021            .network_settings
5022            .and_then(|settings| settings.networks)
5023            .and_then(|mut networks| networks.remove("bridge"))
5024            .and_then(|endpoint| endpoint.gateway)
5025            .expect("container acceptance requires the bridge network gateway")
5026            .parse::<std::net::IpAddr>()
5027            .expect("the bridge gateway should parse as an IP address")
5028            .try_into()
5029            .expect("the bridge gateway should be a usable bridge address")
5030    }
5031
5032    /// A Linux `heel` binary for the container under test: `HEEL_BIN` wins,
5033    /// then a `heel` already on `PATH`.
5034    #[cfg(all(unix, aither_container_acceptance))]
5035    fn container_test_heel_binary() -> Option<PathBuf> {
5036        std::env::var_os("HEEL_BIN")
5037            .map(PathBuf::from)
5038            .filter(|path| path.is_file())
5039            .or_else(|| {
5040                std::process::Command::new("sh")
5041                    .args(["-c", "command -v heel"])
5042                    .output()
5043                    .ok()
5044                    .filter(|output| output.status.success())
5045                    .and_then(|output| String::from_utf8(output.stdout).ok())
5046                    .map(|resolved| PathBuf::from(resolved.trim()))
5047            })
5048            .filter(|path| path.is_file())
5049    }
5050
5051    /// End-to-end container path: `TerminalTool` execs the wrapped script in a
5052    /// real container through `BollardContainerExec`, and the script fires a
5053    /// real `heel ipc` request at the live host bridge.
5054    ///
5055    /// The wrapped `heel run` carries the configured priority through heel's
5056    /// own sandbox configuration, and `--ipc-endpoint` relays the nested
5057    /// sandbox's local IPC socket to the host bridge, so `probe_echo` answers
5058    /// from the live handler rather than failing at the transport.
5059    ///
5060    /// Compiled only with `--cfg aither_container_acceptance`: the test needs
5061    /// a real docker daemon and a Linux `heel` binary, which the dedicated CI
5062    /// job provides and the feature matrices do not. A missing daemon or
5063    /// binary fails the test — it is never skipped silently.
5064    /// Starts the acceptance container with the test bundle staged and
5065    /// mounted read-only as production mounts it, so the wrapped script runs
5066    /// a prepared command from that mount. The returned directory holds the
5067    /// staged bundle and must outlive the container.
5068    #[cfg(all(unix, aither_container_acceptance))]
5069    async fn start_acceptance_container() -> (
5070        TestDockerContainer,
5071        crate::tool_runtime::ToolBundle,
5072        tempfile::TempDir,
5073    ) {
5074        let docker_ready = std::process::Command::new("docker")
5075            .arg("info")
5076            .output()
5077            .is_ok_and(|output| output.status.success());
5078        assert!(
5079            docker_ready,
5080            "container acceptance requires a docker daemon"
5081        );
5082        let heel_bin = container_test_heel_binary()
5083            .expect("container acceptance requires a Linux heel binary (set HEEL_BIN)");
5084        let bundle = crate::tool_runtime::tests::bundle();
5085        let tools_cache = tempfile::tempdir().expect("tool cache dir should be created");
5086        let (tools_mount, _) = bundle
5087            .prepare_container_mount(tools_cache.path())
5088            .await
5089            .expect("test bundle should stage for a container mount");
5090        let container = TestDockerContainer::start(&heel_bin, &tools_mount)
5091            .expect("container acceptance could not start ubuntu:24.04");
5092        (container, bundle, tools_cache)
5093    }
5094
5095    #[cfg(all(unix, aither_container_acceptance))]
5096    #[tokio::test]
5097    async fn container_command_runs_with_configured_nice_and_reaches_ipc() {
5098        let (container, bundle, _tools_cache) = start_acceptance_container().await;
5099
5100        let client = Arc::new(
5101            bollard::Docker::connect_with_local_defaults().expect("docker client should connect"),
5102        );
5103        // The bridge binds the container network's gateway as the host owns
5104        // it (docker0), because native Linux Docker resolves
5105        // `host.docker.internal` (via `--add-host …:host-gateway`) to exactly
5106        // that address.
5107        let bind = container_bridge_address(&client, &container.0).await;
5108        println!("ipc bridge bind: {}", bind.ip());
5109        let exec = crate::AnyContainerExec::new(Arc::new(crate::BollardContainerExec::new(client)));
5110        let runtime = ContainerShellRuntime::new(
5111            container.0.clone(),
5112            crate::ContainerIpcRoute::new("host.docker.internal", bind),
5113            exec,
5114        );
5115
5116        // The container backend needs its own prepared tools: the registry
5117        // entry names the container and its `/opt/aither/tools` bin dir, which
5118        // the wrapped script puts on `PATH` and heel must grant execute on.
5119        let container_tools = crate::tool_runtime::tests::container_tools(&bundle);
5120        let shell_sessions = ShellSessionRegistry::new(ShellRuntimeAvailability {
5121            local: false,
5122            container: true,
5123            ssh: false,
5124        })
5125        .with_container_runtime(runtime)
5126        .with_test_container_tools(container_tools, container.0.clone());
5127
5128        let dir = tempfile::tempdir().expect("temp dir should be created");
5129        let tool: TerminalTool<TestPermissionHandler, executor_core::tokio::TokioGlobal> =
5130            TerminalTool::new_exact(
5131                dir.path(),
5132                TestPermissionHandler::default(),
5133                executor_core::tokio::TokioGlobal,
5134            )
5135            .await
5136            .expect("terminal tool should initialize")
5137            .adopt_prepared_tools(shell_sessions)
5138            .await
5139            .expect("prepared tools should be adopted")
5140            .with_process_priority(ProcessPriority::new(
5141                CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
5142                IoPriority::Normal,
5143            ));
5144        let mut builder = ToolRegistryBuilder::new();
5145        builder.configure_tool(ProbeEchoTool);
5146        let registry = Arc::new(builder.build(tool.outputs_dir()));
5147        let tool = tool.with_registry(registry);
5148
5149        let result = tool
5150            .call(
5151                TerminalArgs {
5152                    description: "probe container priority and IPC transport".to_string(),
5153                    script: concat!(
5154                        "printf 'nice=%s\\n' \"$(nice)\"; ",
5155                        "jq --version; ",
5156                        "probe_echo --marker pong; ",
5157                        "printf 'probe_exit=%s\\n' \"$?\""
5158                    )
5159                    .to_string(),
5160                    mode: TerminalExecutionMode::Sandboxed,
5161                    ssh_server_id: None,
5162                    expect: OutputFormat::Text,
5163                    resolution: MediaResolution::Auto,
5164                    timeout: 60,
5165                    max_lines: 50,
5166                    raw: false,
5167                },
5168                ToolContext::new(),
5169            )
5170            .await
5171            .expect("container terminal call should succeed");
5172        let payload = parse_terminal_tool_result(&result);
5173        let stdout = output_text(&payload.stdout).unwrap_or_default();
5174        assert_eq!(
5175            payload.exit_code,
5176            0,
5177            "container command failed; stdout: {stdout}; stderr: {:?}",
5178            payload.stderr.as_ref().and_then(output_text)
5179        );
5180        // The CI job runs the test with --nocapture so the container's output
5181        // — the applied nice level and the live probe reply — lands in the
5182        // job log.
5183        println!("container script output:\n{stdout}");
5184        assert!(
5185            stdout.contains("nice=5"),
5186            "container command should run at the configured nice level; stdout: {stdout}"
5187        );
5188        assert!(
5189            stdout.contains("jq 1.0.0"),
5190            "a prepared command should run from the read-only tools mount; stdout: {stdout}"
5191        );
5192        assert!(
5193            stdout.contains("pong"),
5194            "probe_echo should answer from the live handler; stdout: {stdout}"
5195        );
5196        assert!(
5197            stdout.contains("probe_exit=0"),
5198            "heel ipc should exit 0 through the relayed endpoint; stdout: {stdout}"
5199        );
5200    }
5201}