Skip to main content

ag_agent/agent/
submission.rs

1//! One-shot agent prompt execution helpers.
2//!
3//! These helpers run isolated utility prompts outside the long-lived session
4//! turn flow. They require the shared structured response protocol on every
5//! transport so one-shot callers enforce the same schema contract as normal
6//! session turns.
7
8use std::future::poll_fn;
9use std::panic::{AssertUnwindSafe, catch_unwind};
10use std::sync::{Arc, Mutex};
11use std::task::Poll;
12
13use ag_protocol::{
14    AgentResponse, ProtocolRequestProfile, build_protocol_repair_prompt,
15    format_protocol_parse_debug_details, parse_protocol_response_strict,
16};
17#[cfg(any(test, feature = "test-utils"))]
18pub use ag_runtime::MockOneShotClient;
19use ag_runtime::PermissionMode;
20pub use ag_runtime::{OneShotClient, OneShotError, OneShotRequest, OneShotSubmission};
21use async_trait::async_trait;
22use tokio_util::sync::CancellationToken;
23
24use super::backend::{AgentBackend, BuildCommandRequest};
25use super::cli::error;
26use super::cli::execution::{self, CliExecutionError, CliExecutionObserver, CliExitStatus};
27use super::submission_pool::{SubmissionLease, SubmissionPool};
28use super::{ParsedResponse, create_app_server_client, create_backend, parse_response};
29use crate::app_server::{AppServerClient, AppServerTurnRequest};
30use crate::model::agent::AgentKind;
31use crate::model::session::{SessionDiffState, SessionStats};
32
33/// Production [`OneShotClient`] that routes through the selected provider.
34pub struct RealOneShotClient {
35    app_server_client_override: Option<Arc<dyn AppServerClient>>,
36    force_shutdown: CancellationToken,
37    pool: Mutex<Option<SubmissionPool>>,
38}
39
40impl RealOneShotClient {
41    /// Creates a client with an optional app-server override.
42    ///
43    /// Production passes `None` so each provider supplies its native client;
44    /// deterministic environments may inject a shared app-server boundary.
45    pub fn new(app_server_client_override: Option<Arc<dyn AppServerClient>>) -> Self {
46        Self {
47            app_server_client_override,
48            force_shutdown: CancellationToken::new(),
49            pool: Mutex::new(None),
50        }
51    }
52
53    /// Creates a scoped client that reuses idle app-server processes while
54    /// starting fresh conversation context for every submission. Call
55    /// [`OneShotClient::close`] after submissions and their cleanup finish.
56    pub fn pooled(app_server_client_override: Option<Arc<dyn AppServerClient>>) -> Self {
57        Self {
58            app_server_client_override,
59            force_shutdown: CancellationToken::new(),
60            pool: Mutex::new(Some(SubmissionPool::default())),
61        }
62    }
63}
64
65#[async_trait]
66impl OneShotClient for RealOneShotClient {
67    fn force_shutdown(&self) {
68        self.force_shutdown.cancel();
69        // Release idle registries immediately; active cleanup tasks keep their
70        // leases until the forced-shutdown signal drops their provider work.
71        self.pool
72            .lock()
73            .unwrap_or_else(std::sync::PoisonError::into_inner)
74            .take();
75    }
76
77    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError> {
78        self.submit_cancellable(request, CancellationToken::new())
79            .await
80    }
81
82    async fn submit_cancellable(
83        &self,
84        request: OneShotRequest,
85        cancellation: CancellationToken,
86    ) -> Result<OneShotSubmission, OneShotError> {
87        let agent_kind = request
88            .harness
89            .parse::<AgentKind>()
90            .map_err(OneShotError::new)?;
91        let lease = self
92            .pool
93            .lock()
94            .unwrap_or_else(std::sync::PoisonError::into_inner)
95            .as_ref()
96            .and_then(|pool| pool.acquire(agent_kind, self.app_server_client_override.clone()));
97        if let Some(lease) = lease {
98            return submit_app_server_session(
99                Arc::clone(&lease.0.client),
100                request,
101                cancellation,
102                self.force_shutdown.clone(),
103                Some(lease),
104            )
105            .await
106            .map_err(OneShotError::new);
107        }
108        let client = create_app_server_client(agent_kind, self.app_server_client_override.clone());
109        if let Some(client) = client {
110            return submit_one_shot_with_app_server_client(
111                client,
112                request,
113                cancellation,
114                self.force_shutdown.clone(),
115            )
116            .await
117            .map_err(OneShotError::new);
118        }
119        let backend = create_backend(agent_kind);
120        tokio::select! {
121            biased;
122            () = self.force_shutdown.cancelled() => Err(OneShotError::new("[Stopped] Agent runtime forced to shut down")),
123            () = cancellation.cancelled() => Err(OneShotError::new("[Stopped] Agent run canceled")),
124            result = submit_one_shot_with_backend(backend.as_ref(), request) => result.map_err(OneShotError::new),
125        }
126    }
127
128    async fn close(&self) {
129        let pool = self
130            .pool
131            .lock()
132            .unwrap_or_else(std::sync::PoisonError::into_inner)
133            .take();
134        if let Some(pool) = pool {
135            pool.close().await;
136        }
137    }
138}
139
140/// Executes an isolated app-server prompt in an owned cleanup task.
141/// Dropping the caller signals cancellation without dropping the provider turn;
142/// cooperative callers await this future until provider shutdown completes.
143async fn submit_one_shot_with_app_server_client(
144    app_server_client: Arc<dyn AppServerClient>,
145    request: OneShotRequest,
146    cancellation: CancellationToken,
147    force_shutdown: CancellationToken,
148) -> Result<OneShotSubmission, String> {
149    submit_app_server_session(
150        app_server_client,
151        request,
152        cancellation,
153        force_shutdown,
154        None,
155    )
156    .await
157}
158
159/// Holds a pooled lease until the owned turn and asynchronous cleanup settle.
160async fn submit_app_server_session(
161    app_server_client: Arc<dyn AppServerClient>,
162    request: OneShotRequest,
163    cancellation: CancellationToken,
164    force_shutdown: CancellationToken,
165    lease: Option<SubmissionLease>,
166) -> Result<OneShotSubmission, String> {
167    let cancellation = cancellation.child_token();
168    let _cancel_on_drop = cancellation.clone().drop_guard();
169    tokio::spawn(async move {
170        let session_id = lease.as_ref().map_or_else(
171            || format!("one-shot-{}", uuid::Uuid::new_v4()),
172            |lease| lease.0.session_id.clone(),
173        );
174        let pooled = lease.is_some();
175        let _lease = lease;
176        let child_pid = request.child_pid.clone();
177        let result = tokio::select! {
178            biased;
179            () = force_shutdown.cancelled() => Err("[Stopped] Agent runtime forced to shut down".to_string()),
180            result = finish_one_shot_app_server_submission(app_server_client, request, cancellation, session_id, pooled) => result,
181        };
182        clear_child_pid_slot(child_pid.as_deref());
183        result
184    })
185    .await
186    .map_err(|error| format!("One-shot cleanup task failed: {error}"))?
187}
188
189/// Retains the provider future while shutdown signals its active runtime.
190async fn finish_one_shot_app_server_submission(
191    app_server_client: Arc<dyn AppServerClient>,
192    request: OneShotRequest,
193    cancellation: CancellationToken,
194    session_id: String,
195    pooled: bool,
196) -> Result<OneShotSubmission, String> {
197    clear_child_pid_slot(request.child_pid.as_deref());
198    let work = execute_one_shot_app_server_turns(
199        app_server_client.as_ref(),
200        request,
201        &session_id,
202        &cancellation,
203        pooled,
204    );
205    tokio::pin!(work);
206    let work = poll_fn(|context| {
207        catch_unwind(AssertUnwindSafe(|| work.as_mut().poll(context)))
208            .unwrap_or_else(|_| Poll::Ready(Err("One-shot provider turn panicked".to_string())))
209    });
210    tokio::pin!(work);
211    tokio::select! {
212        biased;
213        result = &mut work => {
214            if !pooled || result.is_err() || cancellation.is_cancelled() {
215                app_server_client.shutdown_session(session_id.clone()).await;
216            }
217            result
218        }
219        () = cancellation.cancelled() => {
220            // Keep polling the turn so the adapter can observe shutdown and
221            // release the runtime it temporarily removed from its registry.
222            let _ = tokio::join!(app_server_client.shutdown_session(session_id.clone()), &mut work);
223            Err("[Stopped] Agent run canceled".to_string())
224        }
225    }
226}
227
228/// Executes the initial turn and optional protocol repair in the same session.
229async fn execute_one_shot_app_server_turns(
230    app_server_client: &dyn AppServerClient,
231    request: OneShotRequest,
232    session_id: &str,
233    cancellation: &CancellationToken,
234    pooled: bool,
235) -> Result<OneShotSubmission, String> {
236    if cancellation.is_cancelled() {
237        return Err("[Stopped] Agent run canceled".to_string());
238    }
239    let protocol_profile = request.request_kind.protocol_profile();
240    let (stream_tx, _stream_rx) = tokio::sync::mpsc::unbounded_channel();
241    let turn_request = AppServerTurnRequest {
242        provider_call_budget: request.provider_call_budget.clone(),
243        folder: request.folder.clone(),
244        live_transcript: None,
245        main_checkout_root: None,
246        model: request.model.clone(),
247        permission_mode: request.permission_mode,
248        personality: crate::channel::PersonalityPrompt::default(),
249        prompt: ag_protocol::TurnPrompt::from_agent_data(request.prompt.clone()),
250        request_kind: request.request_kind.clone(),
251        replay_transcript: None,
252        provider_conversation_id: None,
253        persisted_instruction_conversation_id: None,
254        reasoning_level: request.reasoning_level,
255        session_id: session_id.to_string(),
256        speed_mode: request.speed_mode,
257    };
258
259    let turn_result = if pooled {
260        app_server_client.run_isolated_turn(turn_request, stream_tx)
261    } else {
262        app_server_client.run_turn(turn_request, stream_tx)
263    }
264    .await
265    .map_err(|error| format!("Failed to execute one-shot app-server turn: {error}"))?;
266    if cancellation.is_cancelled() {
267        return Err("[Stopped] Agent run canceled".to_string());
268    }
269
270    let parse_result =
271        match parse_one_shot_response(&turn_result.assistant_message, protocol_profile) {
272            Ok(response) => Ok((response, 0, 0)),
273            Err(parse_error) => {
274                attempt_one_shot_app_server_repair(
275                    app_server_client,
276                    &parse_error,
277                    &turn_result.assistant_message,
278                    request,
279                    session_id,
280                    turn_result.provider_conversation_id.as_deref(),
281                    pooled,
282                )
283                .await
284            }
285        };
286
287    let (response, repair_input_tokens, repair_output_tokens) = parse_result?;
288
289    Ok(OneShotSubmission {
290        response,
291        stats: SessionStats {
292            added_lines: 0,
293            deleted_lines: 0,
294            diff_state: SessionDiffState::Unknown,
295            input_tokens: turn_result.input_tokens + repair_input_tokens,
296            output_tokens: turn_result.output_tokens + repair_output_tokens,
297        },
298    })
299}
300
301/// Executes one isolated prompt using the provided backend.
302///
303/// This shared helper keeps process execution behind the existing
304/// `AgentBackend` trait boundary so production callers and tests can reuse
305/// the same one-shot parsing path.
306///
307/// # Errors
308/// Returns an error when command construction fails, process execution fails,
309/// or the final output is empty or otherwise unusable.
310async fn submit_one_shot_with_backend(
311    backend: &dyn AgentBackend,
312    request: OneShotRequest,
313) -> Result<OneShotSubmission, String> {
314    let protocol_profile = request.request_kind.protocol_profile();
315    let parsed_response =
316        execute_one_shot_command(backend, &request.prompt, request.clone()).await?;
317    let (agent_response, repair_stats) =
318        match parse_one_shot_response(&parsed_response.content, protocol_profile) {
319            Ok(response) => (response, None),
320            Err(parse_error) => {
321                let repair_prompt =
322                    build_protocol_repair_prompt(&parse_error, &parsed_response.content)?;
323                let request = OneShotRequest {
324                    permission_mode: PermissionMode::ReadOnly,
325                    ..request
326                };
327                let repair_response = execute_one_shot_command(backend, &repair_prompt, request)
328                    .await
329                    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
330
331                let response = parse_one_shot_response(&repair_response.content, protocol_profile)
332                    .map_err(|error| {
333                        format!(
334                            "{parse_error}\nrepair retry also failed: \
335                             {error}\nrepair_response:\n{}",
336                            repair_response.content
337                        )
338                    })?;
339
340                (response, Some(repair_response.stats))
341            }
342        };
343
344    let mut stats = parsed_response.stats;
345    if let Some(repair) = repair_stats {
346        stats.input_tokens += repair.input_tokens;
347        stats.output_tokens += repair.output_tokens;
348    }
349
350    Ok(OneShotSubmission {
351        response: agent_response,
352        stats,
353    })
354}
355
356/// Parses one one-shot response strictly against the shared protocol schema.
357///
358/// # Errors
359/// Returns an error when the response is empty or not valid protocol JSON. The
360/// error carries the parse reason and derived diagnostics only, never the
361/// provider payload itself.
362fn parse_one_shot_response(
363    content: &str,
364    protocol_profile: ProtocolRequestProfile,
365) -> Result<AgentResponse, String> {
366    parse_protocol_response_strict(content, protocol_profile).map_err(|error| {
367        format!(
368            "One-shot agent output did not match the required JSON schema: \
369             {error}\ndebug_details:\n{}",
370            format_protocol_parse_debug_details(content)
371        )
372    })
373}
374
375/// Attempts one protocol-repair retry through the app-server transport for
376/// a one-shot prompt whose initial response failed schema validation.
377///
378/// The repair prompt is sent as a follow-up turn on the same session so the
379/// agent retains the original conversation context. The initial turn's
380/// `provider_conversation_id` is threaded through so providers that depend
381/// on conversation state can continue the same thread.
382/// Pooled repairs retain the runtime without resetting that context.
383///
384/// Returns the parsed response together with the repair turn's token usage
385/// so the caller can aggregate stats across both attempts.
386///
387/// # Errors
388/// Returns the combined original and repair error when the retry fails.
389async fn attempt_one_shot_app_server_repair(
390    app_server_client: &dyn AppServerClient,
391    parse_error: &str,
392    malformed_response: &str,
393    request: OneShotRequest,
394    session_id: &str,
395    provider_conversation_id: Option<&str>,
396    pooled: bool,
397) -> Result<(AgentResponse, u64, u64), String> {
398    let protocol_profile = request.request_kind.protocol_profile();
399    let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response)?;
400
401    let (repair_stream_tx, _repair_stream_rx) = tokio::sync::mpsc::unbounded_channel();
402    let repair_turn_request = AppServerTurnRequest {
403        provider_call_budget: request.provider_call_budget.clone(),
404        folder: request.folder,
405        live_transcript: None,
406        main_checkout_root: None,
407        model: request.model.clone(),
408        permission_mode: request.permission_mode,
409        personality: crate::channel::PersonalityPrompt::default(),
410        prompt: ag_protocol::TurnPrompt::from_agent_data(repair_prompt),
411        request_kind: request.request_kind,
412        replay_transcript: None,
413        provider_conversation_id: provider_conversation_id.map(String::from),
414        persisted_instruction_conversation_id: None,
415        reasoning_level: request.reasoning_level,
416        session_id: session_id.to_string(),
417        speed_mode: request.speed_mode,
418    };
419    let repair_result = if pooled {
420        app_server_client.run_retained_turn(repair_turn_request, repair_stream_tx)
421    } else {
422        app_server_client.run_turn(repair_turn_request, repair_stream_tx)
423    }
424    .await
425    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
426
427    let response = parse_one_shot_response(&repair_result.assistant_message, protocol_profile)
428        .map_err(|error| {
429            format!(
430                "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
431                repair_result.assistant_message
432            )
433        })?;
434
435    Ok((
436        response,
437        repair_result.input_tokens,
438        repair_result.output_tokens,
439    ))
440}
441
442/// Runs one one-shot backend command and returns the parsed provider content.
443///
444/// The spawned child is configured with `kill_on_drop(true)` so timeout-driven
445/// callers do not leave orphaned agent CLI processes behind when the future is
446/// canceled before completion.
447///
448/// # Errors
449/// Returns an error when the command cannot be built, run, or exits
450/// unsuccessfully.
451async fn execute_one_shot_command(
452    backend: &dyn AgentBackend,
453    prompt: &str,
454    request: OneShotRequest,
455) -> Result<ParsedResponse, String> {
456    if let Some(budget) = &request.provider_call_budget {
457        budget.consume().map_err(|error| error.to_string())?;
458    }
459    let prompt_payload = ag_protocol::TurnPrompt::from_agent_data(prompt.to_string());
460    let agent_kind = request.harness.parse::<AgentKind>()?;
461    let build_request = BuildCommandRequest {
462        attachments: &prompt_payload.attachments,
463        folder: &request.folder,
464        main_checkout_root: None,
465        replay_transcript: None,
466        model: &request.model,
467        permission_mode: request.permission_mode,
468        personality_prompt: None,
469        prompt,
470        reasoning_level: request.reasoning_level,
471        request_kind: &request.request_kind,
472        speed_mode: request.speed_mode,
473    };
474    let observer = OneShotCliObserver {
475        child_pid: request.child_pid,
476    };
477    let output =
478        execution::execute_cli_command(backend, agent_kind, build_request, &observer, None)
479            .await
480            .map_err(format_one_shot_execution_error)?;
481
482    match output.exit_status {
483        CliExitStatus::Signaled(_) => {
484            return Err("One-shot agent command was interrupted".to_string());
485        }
486        CliExitStatus::NonZero(exit_code) => {
487            return Err(format_one_shot_exit_error(
488                agent_kind,
489                exit_code,
490                &output.stdout,
491                &output.stderr,
492            ));
493        }
494        CliExitStatus::Success => {}
495    }
496
497    let parsed_response = parse_response(agent_kind, &output.stdout, &output.stderr);
498
499    Ok(parsed_response)
500}
501
502/// Preserves the established one-shot context around shared execution errors.
503fn format_one_shot_execution_error(error: CliExecutionError) -> String {
504    match error {
505        CliExecutionError::CommandBuild(error) => {
506            format!("Failed to build one-shot agent command: {error}")
507        }
508        CliExecutionError::StdinBuild(error) => {
509            format!("Failed to build one-shot agent stdin payload: {error}")
510        }
511        error => format!("Failed to execute one-shot agent command: {error}"),
512    }
513}
514
515/// Formats one non-zero one-shot command exit into a user-facing error.
516fn format_one_shot_exit_error(
517    agent_kind: AgentKind,
518    exit_code: Option<i32>,
519    stdout: &str,
520    stderr: &str,
521) -> String {
522    error::format_agent_cli_exit_error(
523        agent_kind,
524        "One-shot agent command",
525        exit_code,
526        stdout,
527        stderr,
528    )
529}
530
531/// Clears the shared one-shot child PID slot when one exists.
532fn clear_child_pid_slot(child_pid: Option<&Mutex<Option<u32>>>) {
533    let Some(child_pid) = child_pid else {
534        return;
535    };
536
537    if let Ok(mut guard) = child_pid.lock() {
538        *guard = None;
539    }
540}
541
542/// Bridges shared CLI PID observations into the one-shot accounting slot.
543struct OneShotCliObserver {
544    child_pid: Option<Arc<Mutex<Option<u32>>>>,
545}
546
547impl CliExecutionObserver for OneShotCliObserver {
548    fn pid_updated(&self, active_child_pid: Option<u32>) {
549        let Some(child_pid_slot) = self.child_pid.as_deref() else {
550            return;
551        };
552
553        if let Ok(mut guard) = child_pid_slot.lock() {
554            *guard = active_child_pid;
555        }
556    }
557
558    fn stdout_line(&self, _line: &str) {}
559}
560
561#[cfg(test)]
562#[path = "submission_test.rs"]
563mod tests;
564
565#[cfg(test)]
566#[path = "submission_budget_test.rs"]
567mod budget_tests;