ag-agent 0.16.3

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
//! Shared raw subprocess execution for CLI-backed agent transports.

use std::io;
use std::os::unix::process::ExitStatusExt as _;
use std::process::ExitStatus;
use std::time::Duration;

use ag_session::AgentKind;
use rustix::process::{self, Pid, Signal, WaitId, WaitIdOptions};
use tokio::io::{AsyncBufRead, AsyncBufReadExt as _, AsyncRead, AsyncReadExt as _};

use super::stdin;
use crate::agent::{self as agent, AgentBackend, AgentBackendError, BuildCommandRequest};

/// Observer for execution details that are meaningful to a transport adapter.
pub(crate) trait CliExecutionObserver: Send + Sync {
    /// Reports the active child PID and clears it after process termination.
    fn pid_updated(&self, child_pid: Option<u32>);

    /// Reports one complete stdout line while retaining the same line in the
    /// final raw output.
    fn stdout_line(&self, line: &str);
}

/// Observer used by callers that only need the collected raw output.
pub(crate) struct CollectingCliObserver;

impl CliExecutionObserver for CollectingCliObserver {
    fn pid_updated(&self, _child_pid: Option<u32>) {}

    fn stdout_line(&self, _line: &str) {}
}

/// Classified process termination state independent of caller policy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CliExitStatus {
    /// Process exited unsuccessfully without a Unix signal.
    NonZero(Option<i32>),
    /// Process terminated after receiving a Unix signal.
    Signaled(i32),
    /// Process exited successfully.
    Success,
}

/// Raw subprocess output returned before provider-specific parsing.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct CliExecutionOutput {
    /// Classified process termination state.
    pub exit_status: CliExitStatus,
    /// Complete stderr captured from the child process.
    pub stderr: String,
    /// Complete stdout captured from the child process.
    pub stdout: String,
}

/// Infrastructure failure while preparing or running a CLI subprocess.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CliExecutionError {
    /// Provider backend could not construct the command.
    #[error("command build failed: {0}")]
    CommandBuild(AgentBackendError),
    /// A configured child pipe was unexpectedly unavailable.
    #[error("{0} pipe unavailable after spawn")]
    PipeUnavailable(&'static str),
    /// Child process could not be spawned.
    #[error("process spawn failed: {0}")]
    Spawn(io::Error),
    /// Stderr capture failed.
    #[error("stderr capture failed: {0}")]
    StderrRead(io::Error),
    /// Provider prompt could not be rendered for stdin delivery.
    #[error("stdin payload build failed: {0}")]
    StdinBuild(AgentBackendError),
    /// Stdin delivery failed after the child was spawned.
    #[error("stdin delivery failed: {0}")]
    StdinWrite(String),
    /// Stdout capture failed.
    #[error("stdout capture failed: {0}")]
    StdoutRead(io::Error),
    /// Child execution exceeded the caller-provided deadline.
    #[error("process timed out after {}s", .0.as_secs())]
    Timeout(Duration),
    /// Waiting for child termination failed.
    #[error("process wait failed: {0}")]
    Wait(io::Error),
}

/// Builds and executes one CLI backend command, returning unparsed output.
///
/// Command construction, prompt stdin rendering, pipe setup, concurrent stream
/// capture, PID lifetime, timeout enforcement, and exit classification all
/// live here. Callers remain responsible for interpreting output and applying
/// response-repair policy.
///
/// # Errors
/// Returns [`CliExecutionError`] when command preparation or subprocess I/O
/// fails, or when `timeout` expires.
pub(crate) async fn execute_cli_command(
    backend: &dyn AgentBackend,
    kind: AgentKind,
    build_request: BuildCommandRequest<'_>,
    observer: &dyn CliExecutionObserver,
    timeout: Option<Duration>,
) -> Result<CliExecutionOutput, CliExecutionError> {
    let command = backend
        .build_command(build_request)
        .map_err(CliExecutionError::CommandBuild)?;
    let stdin_payload = agent::build_command_stdin_payload(kind, build_request)
        .map_err(CliExecutionError::StdinBuild)?;
    let mut tokio_command = tokio::process::Command::from(command);
    // Agent tools must not refresh Git's index during read-only inspection.
    tokio_command
        .env("GIT_OPTIONAL_LOCKS", "0")
        .stdin(if stdin_payload.is_some() {
            std::process::Stdio::piped()
        } else {
            std::process::Stdio::null()
        })
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .process_group(0)
        .kill_on_drop(true);

    let mut child = tokio_command.spawn().map_err(CliExecutionError::Spawn)?;
    let mut process_group = ProcessGroupGuard(
        child
            .id()
            .and_then(|pid| i32::try_from(pid).ok())
            .and_then(Pid::from_raw),
    );
    let _pid_guard = ChildPidObserverGuard::new(observer, child.id());
    let stdout = require_pipe(child.stdout.take(), "stdout")?;
    let stderr = require_pipe(child.stderr.take(), "stderr")?;
    let mut stdin_write_task = stdin::spawn_optional_stdin_write(
        child.stdin.take(),
        stdin_payload,
        "stdin pipe unavailable after spawn",
        CliExecutionError::StdinWrite,
    );

    let _stdin_guard = StdinAbortGuard(
        stdin_write_task
            .as_ref()
            .map(tokio::task::JoinHandle::abort_handle),
    );

    let execution = async {
        let wait = async {
            process_group
                .wait_for_exit()
                .await
                .map_err(CliExecutionError::Wait)?;
            // Descendants can keep stdout/stderr open after the parent exits.
            // Terminate them before waiting for stream EOFs, then drain the
            // pipes. Keep the leader unreaped until group cleanup so its
            // numeric PID/PGID cannot be reused by an unrelated process.
            drop(process_group);

            child.wait().await.map_err(CliExecutionError::Wait)
        };
        let stdout_capture = capture_stdout(tokio::io::BufReader::new(stdout), observer);
        let stderr_capture = capture_stderr(stderr);
        let (exit_status, stdout, stderr) = tokio::try_join!(wait, stdout_capture, stderr_capture)?;

        Ok((exit_status, stdout, stderr))
    };
    let execution_result = match timeout {
        Some(timeout) => {
            let Ok(execution_result) = tokio::time::timeout(timeout, execution).await else {
                abort_stdin_write_task(&mut stdin_write_task).await;

                return Err(CliExecutionError::Timeout(timeout));
            };

            execution_result
        }
        None => execution.await,
    };
    let (exit_status, stdout, stderr) =
        finish_cli_execution(stdin_write_task, execution_result).await?;

    Ok(CliExecutionOutput {
        exit_status: classify_exit_status(exit_status),
        stderr,
        stdout,
    })
}

/// Owns the isolated process group, including tool descendants after parent
/// exit. Cancellation, timeout, errors, and normal completion all terminate
/// stragglers.
struct ProcessGroupGuard(Option<Pid>);

impl ProcessGroupGuard {
    /// Observes exit without reaping the leader. Nonblocking checks keep
    /// cancellation responsive without leaving a detached blocking waiter.
    async fn wait_for_exit(&mut self) -> io::Result<()> {
        let Some(leader) = self.0 else {
            return Ok(());
        };

        loop {
            let status = rustix::io::retry_on_intr(|| {
                process::waitid(
                    WaitId::Pid(leader),
                    WaitIdOptions::EXITED | WaitIdOptions::NOWAIT | WaitIdOptions::NOHANG,
                )
            });
            match status {
                Ok(Some(_)) => return Ok(()),
                Ok(None) => tokio::time::sleep(Duration::from_millis(10)).await,
                Err(error) => {
                    // Ownership can no longer be established (for example,
                    // another waiter reaped the leader). Never signal its ID.
                    self.0 = None;

                    return Err(error.into());
                }
            }
        }
    }
}

impl Drop for ProcessGroupGuard {
    fn drop(&mut self) {
        if let Some(group) = self.0 {
            let _ = process::kill_process_group(group, Signal::KILL);
        }
    }
}

/// Prevents a dropped execution future from detaching a blocked stdin writer.
struct StdinAbortGuard(Option<tokio::task::AbortHandle>);

impl Drop for StdinAbortGuard {
    fn drop(&mut self) {
        if let Some(writer) = &self.0 {
            writer.abort();
        }
    }
}

/// Finalizes stdin delivery without leaving its task detached after failure.
async fn finish_cli_execution(
    mut stdin_write_task: Option<tokio::task::JoinHandle<Result<(), CliExecutionError>>>,
    execution_result: Result<(ExitStatus, String, String), CliExecutionError>,
) -> Result<(ExitStatus, String, String), CliExecutionError> {
    if execution_result.is_err() {
        abort_stdin_write_task(&mut stdin_write_task).await;
    }

    stdin::await_optional_stdin_write(
        stdin_write_task,
        "stdin write task failed",
        CliExecutionError::StdinWrite,
    )
    .await?;

    execution_result
}

/// Cancels and joins one active stdin writer before an execution error exits.
async fn abort_stdin_write_task(
    stdin_write_task: &mut Option<tokio::task::JoinHandle<Result<(), CliExecutionError>>>,
) {
    let Some(stdin_write_task) = stdin_write_task.take() else {
        return;
    };

    stdin_write_task.abort();
    let _ = stdin_write_task.await;
}

/// Reports a spawned PID and guarantees a matching clear notification.
struct ChildPidObserverGuard<'a> {
    observer: &'a dyn CliExecutionObserver,
}

impl<'a> ChildPidObserverGuard<'a> {
    /// Creates a PID guard and reports the current child identifier.
    fn new(observer: &'a dyn CliExecutionObserver, child_pid: Option<u32>) -> Self {
        observer.pid_updated(child_pid);

        Self { observer }
    }
}

impl Drop for ChildPidObserverGuard<'_> {
    fn drop(&mut self) {
        self.observer.pid_updated(None);
    }
}

/// Returns one required child pipe or a typed infrastructure error.
fn require_pipe<Pipe>(
    pipe: Option<Pipe>,
    pipe_name: &'static str,
) -> Result<Pipe, CliExecutionError> {
    pipe.ok_or(CliExecutionError::PipeUnavailable(pipe_name))
}

/// Captures stdout exactly while reporting completed lines to the observer.
async fn capture_stdout<Reader>(
    mut reader: Reader,
    observer: &dyn CliExecutionObserver,
) -> Result<String, CliExecutionError>
where
    Reader: AsyncBufRead + Unpin,
{
    let mut output = Vec::new();
    let mut line = Vec::new();

    loop {
        line.clear();
        let bytes_read = reader
            .read_until(b'\n', &mut line)
            .await
            .map_err(CliExecutionError::StdoutRead)?;
        if bytes_read == 0 {
            break;
        }

        output.extend_from_slice(&line);
        let line_text = String::from_utf8_lossy(&line);
        observer.stdout_line(line_text.trim_end_matches(['\r', '\n']));
    }

    Ok(String::from_utf8_lossy(&output).into_owned())
}

/// Captures the complete stderr byte stream.
async fn capture_stderr<Reader>(mut reader: Reader) -> Result<String, CliExecutionError>
where
    Reader: AsyncRead + Unpin,
{
    let mut output = Vec::new();
    reader
        .read_to_end(&mut output)
        .await
        .map_err(CliExecutionError::StderrRead)?;

    Ok(String::from_utf8_lossy(&output).into_owned())
}

/// Converts an OS exit status into the transport-neutral classification.
fn classify_exit_status(exit_status: ExitStatus) -> CliExitStatus {
    if let Some(signal) = exit_status.signal() {
        return CliExitStatus::Signaled(signal);
    }
    if exit_status.success() {
        return CliExitStatus::Success;
    }

    CliExitStatus::NonZero(exit_status.code())
}

#[cfg(test)]
#[path = "execution_test.rs"]
mod tests;