ag-agent 0.16.7

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
//! CLI subprocess [`AgentChannel`] adapter.
//!
//! Spawns a provider CLI process per turn, streams stdout line-by-line as
//! [`TurnEvent`]s, and parses the final process output when the process exits.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use ag_contracts::{
    AgentChannel, AgentError, AgentFuture, SessionRef, StartSessionRequest, TurnEvent, TurnRequest,
    TurnResult,
};
use ag_protocol::{AgentResponse, TurnPrompt, build_protocol_repair_prompt};
use ag_session::AgentKind;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::agent::cli::error;
use crate::agent::cli::execution::{
    self, CliExecutionError, CliExecutionObserver, CliExitStatus, CollectingCliObserver,
};
use crate::agent::{self as agent, AgentBackend, BuildCommandRequest};

/// [`AgentChannel`] adapter that spawns one CLI subprocess per agent turn.
///
/// Stdout lines are classified by
/// [`agent::parse_stream_output_line`] and transient loader updates are
/// forwarded as [`TurnEvent::ThoughtDelta`]. A kill signal transitions the
/// turn to a failed state with a `[Stopped]` banner. A spawn failure is
/// surfaced through [`AgentError`].
pub(crate) struct CliAgentChannel {
    /// Active turns whose provider resources belong to this adapter.
    active: Arc<Mutex<HashMap<String, CancellationToken>>>,
    /// Provider-specific command builder.
    backend: Arc<dyn AgentBackend>,
    /// Provider family used for stream and response parsing.
    kind: AgentKind,
}

impl CliAgentChannel {
    /// Creates a CLI channel backed by the given pre-built backend.
    ///
    /// Channel factories use this helper so transport selection can be done
    /// once before constructing the concrete channel. Tests also use it to
    /// inject a [`MockAgentBackend`] that controls command construction and
    /// process spawning without relying on a real provider binary.
    pub(crate) fn with_backend(backend: Arc<dyn agent::AgentBackend>, kind: AgentKind) -> Self {
        Self {
            active: Arc::default(),
            backend,
            kind,
        }
    }
}

/// Retains cancellation ownership until the execution future is dropped.
struct CliTurnLease {
    active: Arc<Mutex<HashMap<String, CancellationToken>>>,
    session_id: String,
}

impl CliTurnLease {
    fn acquire(
        active: Arc<Mutex<HashMap<String, CancellationToken>>>,
        session_id: String,
        cancellation: CancellationToken,
    ) -> Result<Self, AgentError> {
        {
            let mut turns = active
                .lock()
                .map_err(|error| AgentError::Runtime(error.to_string()))?;
            if turns.contains_key(&session_id) {
                return Err(AgentError::Runtime(
                    "Session already has an active turn".to_string(),
                ));
            }
            turns.insert(session_id.clone(), cancellation);
        }
        Ok(Self { active, session_id })
    }
}

impl Drop for CliTurnLease {
    fn drop(&mut self) {
        if let Ok(mut turns) = self.active.lock() {
            turns.remove(&self.session_id);
        }
    }
}

/// Bridges raw CLI execution observations into session turn events.
struct CliTurnObserver {
    /// Session event sink receiving PID and thought updates.
    events: mpsc::UnboundedSender<TurnEvent>,
    /// Provider family used to classify streamed stdout lines.
    kind: AgentKind,
}

impl CliExecutionObserver for CliTurnObserver {
    fn pid_updated(&self, child_pid: Option<u32>) {
        let _ = self.events.send(TurnEvent::PidUpdate(child_pid));
    }

    fn stdout_line(&self, line: &str) {
        let Some((text, is_response_content)) = agent::parse_stream_output_line(self.kind, line)
        else {
            return;
        };
        if is_response_content {
            return;
        }

        let trimmed_text = text.trim();
        if trimmed_text.is_empty() {
            return;
        }

        let _ = self
            .events
            .send(TurnEvent::ThoughtDelta(trimmed_text.to_string()));
    }
}

/// Builds the provider backend command request for one CLI turn.
fn build_command_request<'a>(
    request: &'a TurnRequest,
    prompt_text: &'a str,
) -> BuildCommandRequest<'a> {
    BuildCommandRequest {
        execution_policy: &request.execution_policy,
        attachments: &request.prompt.attachments,
        folder: &request.folder,
        main_checkout_root: request.main_checkout_root.as_deref(),
        replay_transcript: request.continuation.replay_transcript(),
        model: &request.model,
        permission_mode: request.permission_mode,
        personality_prompt: request.personality.current(),
        prompt: prompt_text,
        reasoning_level: request.reasoning_level,
        request_kind: &request.request_kind,
        speed_mode: request.speed_mode,
    }
}

impl AgentChannel for CliAgentChannel {
    /// Returns a [`SessionRef`] immediately; CLI turns are stateless.
    fn start_session(
        &self,
        req: StartSessionRequest,
    ) -> AgentFuture<Result<SessionRef, AgentError>> {
        let session_id = req.session_id;

        Box::pin(async move { Ok(SessionRef { session_id }) })
    }

    /// Spawns a CLI process for the turn and streams its output as events.
    ///
    /// Stdout lines are parsed with the provider-specific stream parser and
    /// loader-oriented interim text is forwarded as
    /// [`TurnEvent::ThoughtDelta`]. After the process exits, usage
    /// statistics are extracted from the raw stdout/stderr and the final
    /// parsed response is returned in [`TurnResult`].
    ///
    /// # Errors
    /// Returns [`AgentError`] when command construction fails, the process
    /// cannot be spawned, or the process is killed by a signal.
    fn run_turn(
        &self,
        session_id: String,
        req: TurnRequest,
        events: mpsc::UnboundedSender<TurnEvent>,
    ) -> AgentFuture<Result<TurnResult, AgentError>> {
        let kind = self.kind;
        let backend = Arc::clone(&self.backend);
        let active = Arc::clone(&self.active);

        Box::pin(async move {
            let cancellation = CancellationToken::new();
            let lease = CliTurnLease::acquire(active, session_id, cancellation.clone())?;
            let execution = async {
                let mut req = req;
                req.prompt = agent::apply_response_style_prompt(
                    req.prompt,
                    req.request_kind.protocol_profile(),
                    req.response_style,
                )
                .map_err(AgentError::from)?;
                let prompt_text = req.prompt.agent_text();
                let replay = agent::replay::ReplayContext::prepare(
                    req.folder.clone(),
                    req.continuation.replay_transcript().map(str::to_owned),
                )
                .await
                .map_err(|error| AgentError::Backend(error.to_string()))?;
                let mut build_request = build_command_request(&req, &prompt_text);
                build_request.replay_transcript = replay.text.as_deref();
                let observer = CliTurnObserver {
                    events: events.clone(),
                    kind,
                };
                let output = execution::execute_cli_command(
                    backend.as_ref(),
                    kind,
                    build_request,
                    &observer,
                    None,
                )
                .await
                .map_err(map_cli_turn_execution_error)?;

                match output.exit_status {
                    CliExitStatus::Signaled(_) => {
                        return Err(AgentError::Backend(
                            "[Stopped] Agent interrupted by user.".to_string(),
                        ));
                    }
                    CliExitStatus::NonZero(exit_code) => {
                        return Err(format_cli_turn_exit_error(
                            kind,
                            exit_code,
                            &output.stdout,
                            &output.stderr,
                        ));
                    }
                    CliExitStatus::Success => {}
                }

                let parsed = agent::parse_response(kind, &output.stdout, &output.stderr);
                let assistant_message =
                    parse_or_repair_cli_response(kind, &parsed.content, &req, &backend, &events)
                        .await?;

                Ok(TurnResult {
                    assistant_message,
                    context_reset: false,
                    input_tokens: parsed.stats.input_tokens,
                    output_tokens: parsed.stats.output_tokens,
                    provider_conversation_id: None,
                })
            };
            let result = tokio::select! {
                result = execution => result,
                () = cancellation.cancelled() => Err(AgentError::InterruptedByUser("[Stopped] Session interrupted by user.".to_string())),
            };
            drop(lease);
            result
        })
    }

    /// Cancels the owned execution; subprocess cleanup follows future drop.
    fn shutdown_session(&self, session_id: String) -> AgentFuture<Result<(), AgentError>> {
        let active = Arc::clone(&self.active);
        Box::pin(async move {
            let turns = active
                .lock()
                .map_err(|error| AgentError::Runtime(error.to_string()))?;
            if let Some(cancellation) = turns.get(&session_id) {
                cancellation.cancel();
            }
            Ok(())
        })
    }
}

/// Parses one CLI turn response strictly, falling back to a single
/// protocol-repair retry when the initial parse fails.
///
/// When repair is attempted, a concise [`TurnEvent::ThoughtDelta`] is emitted
/// so the user can see that schema repair is in progress without flooding the
/// session output with parser diagnostics unless the turn ultimately fails.
async fn parse_or_repair_cli_response(
    kind: AgentKind,
    content: &str,
    req: &TurnRequest,
    backend: &Arc<dyn AgentBackend>,
    events: &mpsc::UnboundedSender<TurnEvent>,
) -> Result<AgentResponse, AgentError> {
    let span = ag_telemetry::Span::child("response.validate");
    span.run(
        async {
            let protocol_profile = req.request_kind.protocol_profile();

            let parse_error = match agent::parse_turn_response(kind, content, protocol_profile) {
                Ok(response) => return Ok(response),
                Err(error) => error,
            };

            let _ = events.send(TurnEvent::ThoughtDelta(format!(
                "Protocol parse error; retrying schema repair for {kind}."
            )));

            ag_telemetry::milestone("schema_repair");
            let repair_prompt =
                build_protocol_repair_prompt(&parse_error, content).map_err(AgentError::Backend)?;

            let repair_content =
                execute_cli_repair_turn(backend.as_ref(), kind, req, &repair_prompt)
                    .await
                    .map_err(|error| {
                        AgentError::Backend(format!(
                            "{parse_error}\nprotocol repair transport failed: {error}"
                        ))
                    })?;

            agent::parse_turn_response(kind, &repair_content, protocol_profile).map_err(
                |repair_error| {
                    AgentError::Backend(format!(
                        "{parse_error}\nprotocol repair retry also failed: {repair_error}"
                    ))
                },
            )
        },
        |_| ag_telemetry::Outcome::Failed,
    )
    .await
}

/// Maximum wall-clock time for one protocol-repair CLI subprocess.
///
/// Repair turns ask the agent to re-emit a single JSON object, so they
/// should complete quickly. The timeout prevents a hung subprocess from
/// blocking the parent turn indefinitely. `kill_on_drop(true)` on the
/// child ensures the process is terminated when the future is dropped.
const REPAIR_TURN_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(1);

/// Spawns a fresh CLI process for one protocol-repair retry and returns
/// the parsed provider content string.
///
/// This helper strips down the full turn-execution pipeline to the minimum
/// needed for repair: command build, spawn, stdout/stderr collection, and
/// provider response parsing. No streaming, PID tracking, or signal
/// handling is performed because the repair is a transparent one-shot
/// correction, not a user-visible turn. A [`REPAIR_TURN_TIMEOUT`] guard
/// ensures a stuck process does not block the parent turn indefinitely.
async fn execute_cli_repair_turn(
    backend: &dyn AgentBackend,
    kind: AgentKind,
    request: &TurnRequest,
    repair_prompt: &str,
) -> Result<String, String> {
    let prompt_payload = TurnPrompt::from_agent_data(repair_prompt.to_string());
    let build_request = BuildCommandRequest {
        execution_policy: &request.execution_policy,
        attachments: &prompt_payload.attachments,
        folder: &request.folder,
        main_checkout_root: None,
        replay_transcript: None,
        model: &request.model,
        permission_mode: ag_contracts::PermissionMode::ReadOnly,
        personality_prompt: None,
        prompt: repair_prompt,
        reasoning_level: request.reasoning_level,
        request_kind: &request.request_kind,
        speed_mode: request.speed_mode,
    };
    execute_cli_repair_command(backend, kind, build_request, REPAIR_TURN_TIMEOUT).await
}

/// Executes one prepared repair command with an explicit deadline.
async fn execute_cli_repair_command(
    backend: &dyn AgentBackend,
    kind: AgentKind,
    build_request: BuildCommandRequest<'_>,
    timeout: std::time::Duration,
) -> Result<String, String> {
    let output = execution::execute_cli_command(
        backend,
        kind,
        build_request,
        &CollectingCliObserver,
        Some(timeout),
    )
    .await
    .map_err(|error| format!("repair {error}"))?;

    match output.exit_status {
        CliExitStatus::NonZero(exit_code) => {
            return Err(format!(
                "repair process exited with code {}",
                exit_code.map_or_else(|| "unknown".to_string(), |code| code.to_string())
            ));
        }
        CliExitStatus::Signaled(signal) => {
            return Err(format!("repair process was interrupted by signal {signal}"));
        }
        CliExitStatus::Success => {}
    }

    let parsed = agent::parse_response(kind, &output.stdout, &output.stderr);

    Ok(parsed.content)
}

/// Maps shared execution failures into the existing channel error categories.
fn map_cli_turn_execution_error(error: CliExecutionError) -> AgentError {
    match error {
        CliExecutionError::CommandBuild(error) => {
            AgentError::Backend(format!("Failed to build command: {error}"))
        }
        CliExecutionError::Spawn(error) => {
            AgentError::Io(format!("Failed to spawn process: {error}"))
        }
        CliExecutionError::StdinBuild(error) => {
            AgentError::Backend(format!("Failed to build command stdin payload: {error}"))
        }
        error => AgentError::Io(error.to_string()),
    }
}

/// Formats one failed CLI turn into a user-facing error.
fn format_cli_turn_exit_error(
    kind: AgentKind,
    exit_code: Option<i32>,
    stdout: &str,
    stderr: &str,
) -> AgentError {
    AgentError::Backend(error::format_agent_cli_exit_error(
        kind,
        "Agent command",
        exit_code,
        stdout,
        stderr,
    ))
}

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