ag-agent 0.19.6

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Shared raw subprocess execution for CLI-backed agent transports.

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

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

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

/// Whitespace JSON permits around a value (RFC 8259 `ws`).
const JSON_WHITESPACE: [char; 4] = [' ', '\t', '\n', '\r'];

/// 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, without its terminator, while
    /// retaining the same line in the final raw output. `payload` carries the
    /// line's JSON, parsed once for every consumer.
    fn stdout_line(&self, line: &str, payload: &CliStdoutPayload);
}

/// JSON parsed once from one stdout line and shared by every line consumer.
///
/// Activity and trace observers read the exact line, while provider stream
/// parsers read it after trimming Unicode whitespace. One parse serves both
/// framings: the exact line parses exactly when only JSON whitespace
/// surrounds the trimmed text and that text parses.
pub(crate) struct CliStdoutPayload {
    /// Whether only JSON whitespace surrounds the trimmed line text.
    exact: bool,
    /// JSON value parsed from the Unicode-whitespace-trimmed line text.
    value: Option<Value>,
}

impl CliStdoutPayload {
    /// Parses one decoded stdout line.
    pub(crate) fn parse(line: &str) -> Self {
        let trimmed_line = line.trim();

        Self {
            // Unicode trimming removes a superset of JSON whitespace, so equal
            // lengths mean every removed character was JSON whitespace.
            exact: line.trim_matches(JSON_WHITESPACE).len() == trimmed_line.len(),
            value: serde_json::from_str(trimmed_line).ok(),
        }
    }

    /// Returns the value that parsing the exact line text yields.
    pub(crate) fn exact(&self) -> Option<&Value> {
        self.value.as_ref().filter(|_| self.exact)
    }

    /// Returns the value parsed after trimming Unicode whitespace, as
    /// provider stream parsers read it.
    pub(crate) fn trimmed(&self) -> Option<&Value> {
        self.value.as_ref()
    }
}

/// 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 span = ag_telemetry::Span::child("agent.attempt");
    span.attribute("agentty.transport", "cli");
    span.attribute("agentty.harness", kind.to_string());
    let result = async {
        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 startup = ag_telemetry::Span::child("agent.startup");
        let mut child = startup
            .run(
                async { tokio_command.spawn().map_err(CliExecutionError::Spawn) },
                |_| ag_telemetry::Outcome::Failed,
            )
            .await?;
        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, kind);
            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,
        })
    }
    .with_context(span.context())
    .await;
    span.finish(match &result {
        Ok(output) if output.exit_status == CliExitStatus::Success => {
            ag_telemetry::Outcome::Completed
        }
        Ok(_) | Err(_) => ag_telemetry::Outcome::Failed,
    });

    result
}

/// 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,
    kind: AgentKind,
) -> Result<String, CliExecutionError>
where
    Reader: AsyncBufRead + Unpin,
{
    let mut output = Vec::new();
    let mut line = Vec::new();
    let mut operation_trace = agent::trace::OperationTrace::new();

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

        if first_activity {
            ag_telemetry::milestone("first_activity");
            first_activity = false;
        }
        output.extend_from_slice(&line);
        let line_text = String::from_utf8_lossy(&line);
        let line_text_without_terminator = line_text.trim_end_matches(['\r', '\n']);
        let payload = CliStdoutPayload::parse(line_text_without_terminator);
        // Tracing reads raw bytes, which never parse as JSON when they are
        // not valid UTF-8, so lossily decoded lines stay out of the trace.
        if let Cow::Borrowed(_) = line_text
            && let Some(value) = payload.exact()
        {
            operation_trace.observe(kind, value);
        }
        observer.stdout_line(line_text_without_terminator, &payload);
    }

    Ok(decode_lossy(output))
}

/// 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(decode_lossy(output))
}

/// Decodes captured bytes like [`String::from_utf8_lossy`], reusing the
/// buffer instead of copying it when the bytes are valid UTF-8.
fn decode_lossy(bytes: Vec<u8>) -> String {
    String::from_utf8(bytes)
        .unwrap_or_else(|error| String::from_utf8_lossy(error.as_bytes()).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;