ag-agent 0.15.15

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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! One-shot agent prompt execution helpers.
//!
//! These helpers run isolated utility prompts outside the long-lived session
//! turn flow. They require the shared structured response protocol on every
//! transport so one-shot callers enforce the same schema contract as normal
//! session turns.

use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use ag_protocol::{
    AgentResponse, ProtocolRequestProfile, build_protocol_repair_prompt,
    format_protocol_parse_debug_details, parse_protocol_response_strict,
};
use async_trait::async_trait;

use super::backend::{AgentBackend, BuildCommandRequest};
use super::cli::error;
use super::cli::execution::{self, CliExecutionError, CliExecutionObserver, CliExitStatus};
use super::{
    ParsedResponse, create_app_server_client, create_backend, parse_response, transport_mode,
};
use crate::app_server::{AppServerClient, AppServerTurnRequest};
use crate::channel::AgentRequestKind;
use crate::model::agent::{AgentKind, AgentModel, ReasoningLevel};
use crate::model::permission::PermissionMode;
use crate::model::session::{SessionDiffState, SessionStats, SpeedMode};

/// Input payload for one isolated prompt that prefers structured protocol
/// output.
#[derive(Clone, Debug)]
pub struct OneShotRequest {
    /// Provider backend used for command construction, stdin shaping, and
    /// response parsing.
    pub agent_kind: AgentKind,
    /// Optional PID slot used by cancel/stop flows to terminate the spawned
    /// subprocess while a one-shot prompt is running.
    pub child_pid: Option<Arc<Mutex<Option<u32>>>>,
    /// Working directory where the prompt command runs.
    pub folder: PathBuf,
    /// Provider-specific model used for command construction and parsing.
    pub model: AgentModel,
    /// Filesystem and command permission policy for this isolated prompt.
    pub permission_mode: PermissionMode,
    /// Prompt text submitted to the agent.
    pub prompt: String,
    /// Optional shared limit, charged for every provider turn including
    /// repairs.
    pub provider_call_budget: Option<crate::ProviderCallBudget>,
    /// Reasoning effort preference for the one-shot prompt.
    pub reasoning_level: ReasoningLevel,
    /// Canonical request kind for this isolated prompt.
    pub request_kind: AgentRequestKind,
    /// Response-speed preference for the one-shot prompt.
    pub speed_mode: SpeedMode,
}

/// Parsed result returned by one isolated prompt execution.
#[derive(Clone, Debug, PartialEq)]
pub struct OneShotSubmission {
    /// Structured protocol response parsed from the final successful attempt.
    pub response: AgentResponse,
    /// Aggregated token usage for the one-shot prompt execution.
    pub stats: SessionStats,
}

/// Typed failure returned by [`OneShotClient`] submissions.
///
/// The concrete transport, protocol-repair, and provider diagnostics remain
/// available through [`std::fmt::Display`] without exposing transport-specific
/// variants to callers.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error("{message}")]
pub struct OneShotError {
    message: String,
}

impl OneShotError {
    /// Creates an error from one already formatted submission diagnostic.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

/// Provider-neutral boundary for isolated structured agent prompts.
///
/// Implementations own transport selection, protocol repair, temporary
/// app-server lifecycle, and usage aggregation so callers submit one request
/// without selecting a CLI or app-server execution helper.
#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
#[async_trait]
pub trait OneShotClient: Send + Sync {
    /// Executes one isolated prompt and returns its parsed response and usage.
    /// Implementations must enforce `provider_call_budget` for every underlying
    /// provider attempt, including protocol repairs and transport retries.
    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError>;
}

/// Production [`OneShotClient`] that routes through the selected provider.
pub struct RealOneShotClient {
    app_server_client_override: Option<Arc<dyn AppServerClient>>,
}

impl RealOneShotClient {
    /// Creates a client with an optional app-server override.
    ///
    /// Production passes `None` so each provider supplies its native client;
    /// deterministic environments may inject a shared app-server boundary.
    pub fn new(app_server_client_override: Option<Arc<dyn AppServerClient>>) -> Self {
        Self {
            app_server_client_override,
        }
    }
}

#[async_trait]
impl OneShotClient for RealOneShotClient {
    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError> {
        let app_server_client_override = self.app_server_client_override.as_ref().map(Arc::clone);

        submit_one_shot_with_stats_and_app_server_client(request, app_server_client_override)
            .await
            .map_err(OneShotError::new)
    }
}

/// Executes one isolated prompt and returns the parsed response plus
/// aggregated usage statistics, optionally overriding the backend-owned
/// app-server client.
///
/// # Errors
/// Returns an error when command construction fails, process execution fails,
/// or the final output is empty or otherwise unusable.
async fn submit_one_shot_with_stats_and_app_server_client(
    request: OneShotRequest,
    app_server_client_override: Option<Arc<dyn AppServerClient>>,
) -> Result<OneShotSubmission, String> {
    let backend = create_backend(request.agent_kind);

    if transport_mode(request.agent_kind).uses_app_server() {
        let app_server_client =
            create_app_server_client(request.agent_kind, app_server_client_override).ok_or_else(
                || {
                    format!(
                        "{} provider did not provide an app-server client",
                        request.agent_kind
                    )
                },
            )?;

        return submit_one_shot_with_app_server_client(app_server_client.as_ref(), request).await;
    }

    submit_one_shot_with_backend(backend.as_ref(), request).await
}

/// Executes one isolated prompt through the shared app-server transport.
///
/// The temporary app-server session is shut down after the utility prompt
/// finishes so one-shot helpers do not keep a provider runtime alive after the
/// result has been parsed.
///
/// # Errors
/// Returns an error when app-server turn execution fails or the final output
/// is empty or otherwise unusable.
async fn submit_one_shot_with_app_server_client(
    app_server_client: &dyn AppServerClient,
    request: OneShotRequest,
) -> Result<OneShotSubmission, String> {
    clear_child_pid_slot(request.child_pid.as_deref());

    let session_id = format!("one-shot-{}", uuid::Uuid::new_v4());
    let protocol_profile = request.request_kind.protocol_profile();
    let (stream_tx, _stream_rx) = tokio::sync::mpsc::unbounded_channel();
    let turn_request = AppServerTurnRequest {
        provider_call_budget: request.provider_call_budget.clone(),
        folder: request.folder.clone(),
        live_transcript: None,
        main_checkout_root: None,
        model: request.model.provider_model_str().to_string(),
        permission_mode: request.permission_mode,
        personality: crate::channel::PersonalityPrompt::default(),
        prompt: ag_protocol::TurnPrompt::from_agent_data(request.prompt.clone()),
        request_kind: request.request_kind.clone(),
        replay_transcript: None,
        provider_conversation_id: None,
        persisted_instruction_conversation_id: None,
        reasoning_level: request.reasoning_level,
        session_id: session_id.clone(),
        speed_mode: request.speed_mode,
    };

    let turn_result = app_server_client.run_turn(turn_request, stream_tx).await;

    let child_pid = request.child_pid.as_ref().map(Arc::clone);

    let turn_result = match turn_result {
        Ok(result) => result,
        Err(error) => {
            app_server_client.shutdown_session(session_id).await;
            clear_child_pid_slot(child_pid.as_deref());

            return Err(format!(
                "Failed to execute one-shot app-server turn: {error}"
            ));
        }
    };

    let parse_result =
        match parse_one_shot_response(&turn_result.assistant_message, protocol_profile) {
            Ok(response) => Ok((response, 0, 0)),
            Err(parse_error) => {
                attempt_one_shot_app_server_repair(
                    app_server_client,
                    &parse_error,
                    &turn_result.assistant_message,
                    request,
                    &session_id,
                    turn_result.provider_conversation_id.as_deref(),
                )
                .await
            }
        };

    app_server_client.shutdown_session(session_id).await;
    clear_child_pid_slot(child_pid.as_deref());

    let (response, repair_input_tokens, repair_output_tokens) = parse_result?;

    Ok(OneShotSubmission {
        response,
        stats: SessionStats {
            added_lines: 0,
            deleted_lines: 0,
            diff_state: SessionDiffState::Unknown,
            input_tokens: turn_result.input_tokens + repair_input_tokens,
            output_tokens: turn_result.output_tokens + repair_output_tokens,
        },
    })
}

/// Executes one isolated prompt using the provided backend.
///
/// This shared helper keeps process execution behind the existing
/// `AgentBackend` trait boundary so production callers and tests can reuse
/// the same one-shot parsing path.
///
/// # Errors
/// Returns an error when command construction fails, process execution fails,
/// or the final output is empty or otherwise unusable.
async fn submit_one_shot_with_backend(
    backend: &dyn AgentBackend,
    request: OneShotRequest,
) -> Result<OneShotSubmission, String> {
    let protocol_profile = request.request_kind.protocol_profile();
    let parsed_response =
        execute_one_shot_command(backend, &request.prompt, request.clone()).await?;
    let (agent_response, repair_stats) =
        match parse_one_shot_response(&parsed_response.content, protocol_profile) {
            Ok(response) => (response, None),
            Err(parse_error) => {
                let repair_prompt =
                    build_protocol_repair_prompt(&parse_error, &parsed_response.content)?;
                let request = OneShotRequest {
                    permission_mode: PermissionMode::ReadOnly,
                    ..request
                };
                let repair_response = execute_one_shot_command(backend, &repair_prompt, request)
                    .await
                    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;

                let response = parse_one_shot_response(&repair_response.content, protocol_profile)
                    .map_err(|error| {
                        format!(
                            "{parse_error}\nrepair retry also failed: \
                             {error}\nrepair_response:\n{}",
                            repair_response.content
                        )
                    })?;

                (response, Some(repair_response.stats))
            }
        };

    let mut stats = parsed_response.stats;
    if let Some(repair) = repair_stats {
        stats.input_tokens += repair.input_tokens;
        stats.output_tokens += repair.output_tokens;
    }

    Ok(OneShotSubmission {
        response: agent_response,
        stats,
    })
}

/// Parses one one-shot response strictly against the shared protocol schema.
///
/// # Errors
/// Returns an error when the response is empty or not valid protocol JSON. The
/// error carries the parse reason and derived diagnostics only, never the
/// provider payload itself.
fn parse_one_shot_response(
    content: &str,
    protocol_profile: ProtocolRequestProfile,
) -> Result<AgentResponse, String> {
    parse_protocol_response_strict(content, protocol_profile).map_err(|error| {
        format!(
            "One-shot agent output did not match the required JSON schema: \
             {error}\ndebug_details:\n{}",
            format_protocol_parse_debug_details(content)
        )
    })
}

/// Attempts one protocol-repair retry through the app-server transport for
/// a one-shot prompt whose initial response failed schema validation.
///
/// The repair prompt is sent as a follow-up turn on the same session so the
/// agent retains the original conversation context. The initial turn's
/// `provider_conversation_id` is threaded through so providers that depend
/// on conversation state can continue the same thread.
///
/// Returns the parsed response together with the repair turn's token usage
/// so the caller can aggregate stats across both attempts.
///
/// # Errors
/// Returns the combined original and repair error when the retry fails.
async fn attempt_one_shot_app_server_repair(
    app_server_client: &dyn AppServerClient,
    parse_error: &str,
    malformed_response: &str,
    request: OneShotRequest,
    session_id: &str,
    provider_conversation_id: Option<&str>,
) -> Result<(AgentResponse, u64, u64), String> {
    let protocol_profile = request.request_kind.protocol_profile();
    let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response)?;

    let (repair_stream_tx, _repair_stream_rx) = tokio::sync::mpsc::unbounded_channel();
    let repair_turn_request = AppServerTurnRequest {
        provider_call_budget: request.provider_call_budget.clone(),
        folder: request.folder,
        live_transcript: None,
        main_checkout_root: None,
        model: request.model.provider_model_str().to_string(),
        permission_mode: request.permission_mode,
        personality: crate::channel::PersonalityPrompt::default(),
        prompt: ag_protocol::TurnPrompt::from_agent_data(repair_prompt),
        request_kind: request.request_kind,
        replay_transcript: None,
        provider_conversation_id: provider_conversation_id.map(String::from),
        persisted_instruction_conversation_id: None,
        reasoning_level: request.reasoning_level,
        session_id: session_id.to_string(),
        speed_mode: request.speed_mode,
    };
    let repair_result = app_server_client
        .run_turn(repair_turn_request, repair_stream_tx)
        .await
        .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;

    let response = parse_one_shot_response(&repair_result.assistant_message, protocol_profile)
        .map_err(|error| {
            format!(
                "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
                repair_result.assistant_message
            )
        })?;

    Ok((
        response,
        repair_result.input_tokens,
        repair_result.output_tokens,
    ))
}

/// Runs one one-shot backend command and returns the parsed provider content.
///
/// The spawned child is configured with `kill_on_drop(true)` so timeout-driven
/// callers do not leave orphaned agent CLI processes behind when the future is
/// canceled before completion.
///
/// # Errors
/// Returns an error when the command cannot be built, run, or exits
/// unsuccessfully.
async fn execute_one_shot_command(
    backend: &dyn AgentBackend,
    prompt: &str,
    request: OneShotRequest,
) -> Result<ParsedResponse, String> {
    if let Some(budget) = &request.provider_call_budget {
        budget.consume().map_err(|error| error.to_string())?;
    }
    let prompt_payload = ag_protocol::TurnPrompt::from_agent_data(prompt.to_string());
    let build_request = BuildCommandRequest {
        attachments: &prompt_payload.attachments,
        folder: &request.folder,
        main_checkout_root: None,
        replay_transcript: None,
        model: request.model.provider_model_str(),
        permission_mode: request.permission_mode,
        personality_prompt: None,
        prompt,
        reasoning_level: request.reasoning_level,
        request_kind: &request.request_kind,
        speed_mode: request.speed_mode,
    };
    let observer = OneShotCliObserver {
        child_pid: request.child_pid,
    };
    let output =
        execution::execute_cli_command(backend, request.agent_kind, build_request, &observer, None)
            .await
            .map_err(format_one_shot_execution_error)?;

    match output.exit_status {
        CliExitStatus::Signaled(_) => {
            return Err("One-shot agent command was interrupted".to_string());
        }
        CliExitStatus::NonZero(exit_code) => {
            return Err(format_one_shot_exit_error(
                request.agent_kind,
                exit_code,
                &output.stdout,
                &output.stderr,
            ));
        }
        CliExitStatus::Success => {}
    }

    let parsed_response = parse_response(request.agent_kind, &output.stdout, &output.stderr);

    Ok(parsed_response)
}

/// Preserves the established one-shot context around shared execution errors.
fn format_one_shot_execution_error(error: CliExecutionError) -> String {
    match error {
        CliExecutionError::CommandBuild(error) => {
            format!("Failed to build one-shot agent command: {error}")
        }
        CliExecutionError::StdinBuild(error) => {
            format!("Failed to build one-shot agent stdin payload: {error}")
        }
        error => format!("Failed to execute one-shot agent command: {error}"),
    }
}

/// Formats one non-zero one-shot command exit into a user-facing error.
fn format_one_shot_exit_error(
    agent_kind: AgentKind,
    exit_code: Option<i32>,
    stdout: &str,
    stderr: &str,
) -> String {
    error::format_agent_cli_exit_error(
        agent_kind,
        "One-shot agent command",
        exit_code,
        stdout,
        stderr,
    )
}

/// Clears the shared one-shot child PID slot when one exists.
fn clear_child_pid_slot(child_pid: Option<&Mutex<Option<u32>>>) {
    let Some(child_pid) = child_pid else {
        return;
    };

    if let Ok(mut guard) = child_pid.lock() {
        *guard = None;
    }
}

/// Bridges shared CLI PID observations into the one-shot cancellation slot.
struct OneShotCliObserver {
    child_pid: Option<Arc<Mutex<Option<u32>>>>,
}

impl CliExecutionObserver for OneShotCliObserver {
    fn pid_updated(&self, active_child_pid: Option<u32>) {
        let Some(child_pid_slot) = self.child_pid.as_deref() else {
            return;
        };

        if let Ok(mut guard) = child_pid_slot.lock() {
            *guard = active_child_pid;
        }
    }

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

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

#[cfg(test)]
#[path = "submission_budget_test.rs"]
mod budget_tests;