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_contracts::{
14    OneShotClient, OneShotError, OneShotRequest, OneShotSubmission, PermissionMode,
15    SessionDiffState, SessionStats,
16};
17use ag_protocol::{
18    AgentResponse, ProtocolRequestProfile, build_protocol_repair_prompt,
19    format_protocol_parse_debug_details, parse_protocol_response_strict,
20};
21use ag_session::AgentKind;
22use ag_telemetry::{Context, FutureExt as _};
23use async_trait::async_trait;
24use tokio_util::sync::CancellationToken;
25
26use super::backend::{AgentBackend, BuildCommandRequest};
27use super::cli::error;
28use super::cli::execution::{self, CliExecutionError, CliExecutionObserver, CliExitStatus};
29use super::submission_pool::{SubmissionLease, SubmissionPool};
30use super::{ParsedResponse, create_app_server_client, create_backend, parse_response};
31use crate::app_server::{AppServerClient, AppServerTurnRequest};
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    let trace = Context::current();
170    tokio::spawn(async move {
171        let session_id = lease.as_ref().map_or_else(
172            || format!("one-shot-{}", uuid::Uuid::new_v4()),
173            |lease| lease.0.session_id.clone(),
174        );
175        let pooled = lease.is_some();
176        let _lease = lease;
177        let child_pid = request.child_pid.clone();
178        let result = tokio::select! {
179            biased;
180            () = force_shutdown.cancelled() => Err("[Stopped] Agent runtime forced to shut down".to_string()),
181            result = finish_one_shot_app_server_submission(app_server_client, request, cancellation, session_id, pooled) => result,
182        };
183        clear_child_pid_slot(child_pid.as_deref());
184        result
185    }.with_context(trace))
186    .await
187    .map_err(|error| format!("One-shot cleanup task failed: {error}"))?
188}
189
190/// Retains the provider future while shutdown signals its active runtime.
191async fn finish_one_shot_app_server_submission(
192    app_server_client: Arc<dyn AppServerClient>,
193    request: OneShotRequest,
194    cancellation: CancellationToken,
195    session_id: String,
196    pooled: bool,
197) -> Result<OneShotSubmission, String> {
198    clear_child_pid_slot(request.child_pid.as_deref());
199    let work = execute_one_shot_app_server_turns(
200        app_server_client.as_ref(),
201        request,
202        &session_id,
203        &cancellation,
204        pooled,
205    );
206    tokio::pin!(work);
207    let work = poll_fn(|context| {
208        catch_unwind(AssertUnwindSafe(|| work.as_mut().poll(context)))
209            .unwrap_or_else(|_| Poll::Ready(Err("One-shot provider turn panicked".to_string())))
210    });
211    tokio::pin!(work);
212    tokio::select! {
213        biased;
214        result = &mut work => {
215            if !pooled || result.is_err() || cancellation.is_cancelled() {
216                app_server_client.shutdown_session(session_id.clone()).await;
217            }
218            result
219        }
220        () = cancellation.cancelled() => {
221            // Keep polling the turn so the adapter can observe shutdown and
222            // release the runtime it temporarily removed from its registry.
223            let _ = tokio::join!(app_server_client.shutdown_session(session_id.clone()), &mut work);
224            Err("[Stopped] Agent run canceled".to_string())
225        }
226    }
227}
228
229/// Executes the initial turn and optional protocol repair in the same session.
230async fn execute_one_shot_app_server_turns(
231    app_server_client: &dyn AppServerClient,
232    request: OneShotRequest,
233    session_id: &str,
234    cancellation: &CancellationToken,
235    pooled: bool,
236) -> Result<OneShotSubmission, String> {
237    if cancellation.is_cancelled() {
238        return Err("[Stopped] Agent run canceled".to_string());
239    }
240    let protocol_profile = request.request_kind.protocol_profile();
241    let (stream_tx, _stream_rx) = tokio::sync::mpsc::unbounded_channel();
242    let turn_request = AppServerTurnRequest {
243        execution_policy: request.execution_policy.clone(),
244        provider_call_budget: request.provider_call_budget.clone(),
245        folder: request.folder.clone(),
246        live_transcript: None,
247        main_checkout_root: None,
248        model: request.model.clone(),
249        permission_mode: request.permission_mode,
250        personality: ag_contracts::PersonalityPrompt::default(),
251        prompt: ag_protocol::TurnPrompt::from_agent_data(request.prompt.clone()),
252        request_kind: request.request_kind.clone(),
253        replay_transcript: None,
254        provider_conversation_id: None,
255        persisted_instruction_conversation_id: None,
256        reasoning_level: request.reasoning_level,
257        session_id: session_id.to_string(),
258        speed_mode: request.speed_mode,
259    };
260
261    let turn_result = if pooled {
262        app_server_client.run_isolated_turn(turn_request, stream_tx)
263    } else {
264        app_server_client.run_turn(turn_request, stream_tx)
265    }
266    .await
267    .map_err(|error| format!("Failed to execute one-shot app-server turn: {error}"))?;
268    if cancellation.is_cancelled() {
269        return Err("[Stopped] Agent run canceled".to_string());
270    }
271
272    let parse_result =
273        match parse_one_shot_response(&turn_result.assistant_message, protocol_profile) {
274            Ok(response) => Ok((response, 0, 0)),
275            Err(parse_error) => {
276                attempt_one_shot_app_server_repair(
277                    app_server_client,
278                    &parse_error,
279                    &turn_result.assistant_message,
280                    request,
281                    session_id,
282                    turn_result.provider_conversation_id.as_deref(),
283                    pooled,
284                )
285                .await
286            }
287        };
288
289    let (response, repair_input_tokens, repair_output_tokens) = parse_result?;
290
291    Ok(OneShotSubmission {
292        response,
293        stats: SessionStats {
294            added_lines: 0,
295            deleted_lines: 0,
296            diff_state: SessionDiffState::Unknown,
297            input_tokens: turn_result.input_tokens + repair_input_tokens,
298            output_tokens: turn_result.output_tokens + repair_output_tokens,
299        },
300    })
301}
302
303/// Executes one isolated prompt using the provided backend.
304///
305/// This shared helper keeps process execution behind the existing
306/// `AgentBackend` trait boundary so production callers and tests can reuse
307/// the same one-shot parsing path.
308///
309/// # Errors
310/// Returns an error when command construction fails, process execution fails,
311/// or the final output is empty or otherwise unusable.
312async fn submit_one_shot_with_backend(
313    backend: &dyn AgentBackend,
314    request: OneShotRequest,
315) -> Result<OneShotSubmission, String> {
316    let protocol_profile = request.request_kind.protocol_profile();
317    let parsed_response =
318        execute_one_shot_command(backend, &request.prompt, request.clone()).await?;
319    let (agent_response, repair_stats) =
320        match parse_one_shot_response(&parsed_response.content, protocol_profile) {
321            Ok(response) => (response, None),
322            Err(parse_error) => {
323                let repair_prompt =
324                    build_protocol_repair_prompt(&parse_error, &parsed_response.content)?;
325                let request = OneShotRequest {
326                    permission_mode: PermissionMode::ReadOnly,
327                    ..request
328                };
329                let repair_response = execute_one_shot_command(backend, &repair_prompt, request)
330                    .await
331                    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
332
333                let response = parse_one_shot_response(&repair_response.content, protocol_profile)
334                    .map_err(|error| {
335                        format!(
336                            "{parse_error}\nrepair retry also failed: \
337                             {error}\nrepair_response:\n{}",
338                            repair_response.content
339                        )
340                    })?;
341
342                (response, Some(repair_response.stats))
343            }
344        };
345
346    let mut stats = parsed_response.stats;
347    if let Some(repair) = repair_stats {
348        stats.input_tokens += repair.input_tokens;
349        stats.output_tokens += repair.output_tokens;
350    }
351
352    Ok(OneShotSubmission {
353        response: agent_response,
354        stats,
355    })
356}
357
358/// Parses one one-shot response strictly against the shared protocol schema.
359///
360/// # Errors
361/// Returns an error when the response is empty or not valid protocol JSON. The
362/// error carries the parse reason and derived diagnostics only, never the
363/// provider payload itself.
364fn parse_one_shot_response(
365    content: &str,
366    protocol_profile: ProtocolRequestProfile,
367) -> Result<AgentResponse, String> {
368    parse_protocol_response_strict(content, protocol_profile).map_err(|error| {
369        format!(
370            "One-shot agent output did not match the required JSON schema: \
371             {error}\ndebug_details:\n{}",
372            format_protocol_parse_debug_details(content)
373        )
374    })
375}
376
377/// Attempts one protocol-repair retry through the app-server transport for
378/// a one-shot prompt whose initial response failed schema validation.
379///
380/// The repair prompt is sent as a follow-up turn on the same session so the
381/// agent retains the original conversation context. The initial turn's
382/// `provider_conversation_id` is threaded through so providers that depend
383/// on conversation state can continue the same thread.
384/// Pooled repairs retain the runtime without resetting that context.
385///
386/// Returns the parsed response together with the repair turn's token usage
387/// so the caller can aggregate stats across both attempts.
388///
389/// # Errors
390/// Returns the combined original and repair error when the retry fails.
391async fn attempt_one_shot_app_server_repair(
392    app_server_client: &dyn AppServerClient,
393    parse_error: &str,
394    malformed_response: &str,
395    request: OneShotRequest,
396    session_id: &str,
397    provider_conversation_id: Option<&str>,
398    pooled: bool,
399) -> Result<(AgentResponse, u64, u64), String> {
400    let protocol_profile = request.request_kind.protocol_profile();
401    let repair_prompt = build_protocol_repair_prompt(parse_error, malformed_response)?;
402
403    let (repair_stream_tx, _repair_stream_rx) = tokio::sync::mpsc::unbounded_channel();
404    let repair_turn_request = AppServerTurnRequest {
405        execution_policy: request.execution_policy.clone(),
406        provider_call_budget: request.provider_call_budget.clone(),
407        folder: request.folder,
408        live_transcript: None,
409        main_checkout_root: None,
410        model: request.model.clone(),
411        permission_mode: request.permission_mode,
412        personality: ag_contracts::PersonalityPrompt::default(),
413        prompt: ag_protocol::TurnPrompt::from_agent_data(repair_prompt),
414        request_kind: request.request_kind,
415        replay_transcript: None,
416        provider_conversation_id: provider_conversation_id.map(String::from),
417        persisted_instruction_conversation_id: None,
418        reasoning_level: request.reasoning_level,
419        session_id: session_id.to_string(),
420        speed_mode: request.speed_mode,
421    };
422    let repair_result = if pooled {
423        app_server_client.run_retained_turn(repair_turn_request, repair_stream_tx)
424    } else {
425        app_server_client.run_turn(repair_turn_request, repair_stream_tx)
426    }
427    .await
428    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
429
430    let response = parse_one_shot_response(&repair_result.assistant_message, protocol_profile)
431        .map_err(|error| {
432            format!(
433                "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
434                repair_result.assistant_message
435            )
436        })?;
437
438    Ok((
439        response,
440        repair_result.input_tokens,
441        repair_result.output_tokens,
442    ))
443}
444
445/// Runs one one-shot backend command and returns the parsed provider content.
446///
447/// The spawned child is configured with `kill_on_drop(true)` so timeout-driven
448/// callers do not leave orphaned agent CLI processes behind when the future is
449/// canceled before completion.
450///
451/// # Errors
452/// Returns an error when the command cannot be built, run, or exits
453/// unsuccessfully.
454async fn execute_one_shot_command(
455    backend: &dyn AgentBackend,
456    prompt: &str,
457    request: OneShotRequest,
458) -> Result<ParsedResponse, String> {
459    if let Some(budget) = &request.provider_call_budget {
460        budget.consume().map_err(|error| error.to_string())?;
461    }
462    let prompt_payload = ag_protocol::TurnPrompt::from_agent_data(prompt.to_string());
463    let agent_kind = request.harness.parse::<AgentKind>()?;
464    let build_request = BuildCommandRequest {
465        execution_policy: &request.execution_policy,
466        attachments: &prompt_payload.attachments,
467        folder: &request.folder,
468        main_checkout_root: None,
469        replay_transcript: None,
470        model: &request.model,
471        permission_mode: request.permission_mode,
472        personality_prompt: None,
473        prompt,
474        reasoning_level: request.reasoning_level,
475        request_kind: &request.request_kind,
476        speed_mode: request.speed_mode,
477    };
478    let observer = OneShotCliObserver {
479        child_pid: request.child_pid,
480    };
481    let output =
482        execution::execute_cli_command(backend, agent_kind, build_request, &observer, None)
483            .await
484            .map_err(format_one_shot_execution_error)?;
485
486    match output.exit_status {
487        CliExitStatus::Signaled(_) => {
488            return Err("One-shot agent command was interrupted".to_string());
489        }
490        CliExitStatus::NonZero(exit_code) => {
491            return Err(format_one_shot_exit_error(
492                agent_kind,
493                exit_code,
494                &output.stdout,
495                &output.stderr,
496            ));
497        }
498        CliExitStatus::Success => {}
499    }
500
501    let parsed_response = parse_response(agent_kind, &output.stdout, &output.stderr);
502
503    Ok(parsed_response)
504}
505
506/// Preserves the established one-shot context around shared execution errors.
507fn format_one_shot_execution_error(error: CliExecutionError) -> String {
508    match error {
509        CliExecutionError::CommandBuild(error) => {
510            format!("Failed to build one-shot agent command: {error}")
511        }
512        CliExecutionError::StdinBuild(error) => {
513            format!("Failed to build one-shot agent stdin payload: {error}")
514        }
515        error => format!("Failed to execute one-shot agent command: {error}"),
516    }
517}
518
519/// Formats one non-zero one-shot command exit into a user-facing error.
520fn format_one_shot_exit_error(
521    agent_kind: AgentKind,
522    exit_code: Option<i32>,
523    stdout: &str,
524    stderr: &str,
525) -> String {
526    error::format_agent_cli_exit_error(
527        agent_kind,
528        "One-shot agent command",
529        exit_code,
530        stdout,
531        stderr,
532    )
533}
534
535/// Clears the shared one-shot child PID slot when one exists.
536fn clear_child_pid_slot(child_pid: Option<&Mutex<Option<u32>>>) {
537    let Some(child_pid) = child_pid else {
538        return;
539    };
540
541    if let Ok(mut guard) = child_pid.lock() {
542        *guard = None;
543    }
544}
545
546/// Bridges shared CLI PID observations into the one-shot accounting slot.
547struct OneShotCliObserver {
548    child_pid: Option<Arc<Mutex<Option<u32>>>>,
549}
550
551impl CliExecutionObserver for OneShotCliObserver {
552    fn pid_updated(&self, active_child_pid: Option<u32>) {
553        let Some(child_pid_slot) = self.child_pid.as_deref() else {
554            return;
555        };
556
557        if let Ok(mut guard) = child_pid_slot.lock() {
558            *guard = active_child_pid;
559        }
560    }
561
562    fn stdout_line(&self, _line: &str) {}
563}
564
565#[cfg(test)]
566#[path = "submission_test.rs"]
567mod tests;
568
569#[cfg(test)]
570#[path = "submission_budget_test.rs"]
571mod budget_tests;