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 async_trait::async_trait;
23use tokio_util::sync::CancellationToken;
24
25use super::backend::{AgentBackend, BuildCommandRequest};
26use super::cli::error;
27use super::cli::execution::{self, CliExecutionError, CliExecutionObserver, CliExitStatus};
28use super::submission_pool::{SubmissionLease, SubmissionPool};
29use super::{ParsedResponse, create_app_server_client, create_backend, parse_response};
30use crate::app_server::{AppServerClient, AppServerTurnRequest};
31
32/// Production [`OneShotClient`] that routes through the selected provider.
33pub struct RealOneShotClient {
34    app_server_client_override: Option<Arc<dyn AppServerClient>>,
35    force_shutdown: CancellationToken,
36    pool: Mutex<Option<SubmissionPool>>,
37}
38
39impl RealOneShotClient {
40    /// Creates a client with an optional app-server override.
41    ///
42    /// Production passes `None` so each provider supplies its native client;
43    /// deterministic environments may inject a shared app-server boundary.
44    pub fn new(app_server_client_override: Option<Arc<dyn AppServerClient>>) -> Self {
45        Self {
46            app_server_client_override,
47            force_shutdown: CancellationToken::new(),
48            pool: Mutex::new(None),
49        }
50    }
51
52    /// Creates a scoped client that reuses idle app-server processes while
53    /// starting fresh conversation context for every submission. Call
54    /// [`OneShotClient::close`] after submissions and their cleanup finish.
55    pub fn pooled(app_server_client_override: Option<Arc<dyn AppServerClient>>) -> Self {
56        Self {
57            app_server_client_override,
58            force_shutdown: CancellationToken::new(),
59            pool: Mutex::new(Some(SubmissionPool::default())),
60        }
61    }
62}
63
64#[async_trait]
65impl OneShotClient for RealOneShotClient {
66    fn force_shutdown(&self) {
67        self.force_shutdown.cancel();
68        // Release idle registries immediately; active cleanup tasks keep their
69        // leases until the forced-shutdown signal drops their provider work.
70        self.pool
71            .lock()
72            .unwrap_or_else(std::sync::PoisonError::into_inner)
73            .take();
74    }
75
76    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError> {
77        self.submit_cancellable(request, CancellationToken::new())
78            .await
79    }
80
81    async fn submit_cancellable(
82        &self,
83        request: OneShotRequest,
84        cancellation: CancellationToken,
85    ) -> Result<OneShotSubmission, OneShotError> {
86        let agent_kind = request
87            .harness
88            .parse::<AgentKind>()
89            .map_err(OneShotError::new)?;
90        let lease = self
91            .pool
92            .lock()
93            .unwrap_or_else(std::sync::PoisonError::into_inner)
94            .as_ref()
95            .and_then(|pool| pool.acquire(agent_kind, self.app_server_client_override.clone()));
96        if let Some(lease) = lease {
97            return submit_app_server_session(
98                Arc::clone(&lease.0.client),
99                request,
100                cancellation,
101                self.force_shutdown.clone(),
102                Some(lease),
103            )
104            .await
105            .map_err(OneShotError::new);
106        }
107        let client = create_app_server_client(agent_kind, self.app_server_client_override.clone());
108        if let Some(client) = client {
109            return submit_one_shot_with_app_server_client(
110                client,
111                request,
112                cancellation,
113                self.force_shutdown.clone(),
114            )
115            .await
116            .map_err(OneShotError::new);
117        }
118        let backend = create_backend(agent_kind);
119        tokio::select! {
120            biased;
121            () = self.force_shutdown.cancelled() => Err(OneShotError::new("[Stopped] Agent runtime forced to shut down")),
122            () = cancellation.cancelled() => Err(OneShotError::new("[Stopped] Agent run canceled")),
123            result = submit_one_shot_with_backend(backend.as_ref(), request) => result.map_err(OneShotError::new),
124        }
125    }
126
127    async fn close(&self) {
128        let pool = self
129            .pool
130            .lock()
131            .unwrap_or_else(std::sync::PoisonError::into_inner)
132            .take();
133        if let Some(pool) = pool {
134            pool.close().await;
135        }
136    }
137}
138
139/// Executes an isolated app-server prompt in an owned cleanup task.
140/// Dropping the caller signals cancellation without dropping the provider turn;
141/// cooperative callers await this future until provider shutdown completes.
142async fn submit_one_shot_with_app_server_client(
143    app_server_client: Arc<dyn AppServerClient>,
144    request: OneShotRequest,
145    cancellation: CancellationToken,
146    force_shutdown: CancellationToken,
147) -> Result<OneShotSubmission, String> {
148    submit_app_server_session(
149        app_server_client,
150        request,
151        cancellation,
152        force_shutdown,
153        None,
154    )
155    .await
156}
157
158/// Holds a pooled lease until the owned turn and asynchronous cleanup settle.
159async fn submit_app_server_session(
160    app_server_client: Arc<dyn AppServerClient>,
161    request: OneShotRequest,
162    cancellation: CancellationToken,
163    force_shutdown: CancellationToken,
164    lease: Option<SubmissionLease>,
165) -> Result<OneShotSubmission, String> {
166    let cancellation = cancellation.child_token();
167    let _cancel_on_drop = cancellation.clone().drop_guard();
168    tokio::spawn(async move {
169        let session_id = lease.as_ref().map_or_else(
170            || format!("one-shot-{}", uuid::Uuid::new_v4()),
171            |lease| lease.0.session_id.clone(),
172        );
173        let pooled = lease.is_some();
174        let _lease = lease;
175        let child_pid = request.child_pid.clone();
176        let result = tokio::select! {
177            biased;
178            () = force_shutdown.cancelled() => Err("[Stopped] Agent runtime forced to shut down".to_string()),
179            result = finish_one_shot_app_server_submission(app_server_client, request, cancellation, session_id, pooled) => result,
180        };
181        clear_child_pid_slot(child_pid.as_deref());
182        result
183    })
184    .await
185    .map_err(|error| format!("One-shot cleanup task failed: {error}"))?
186}
187
188/// Retains the provider future while shutdown signals its active runtime.
189async fn finish_one_shot_app_server_submission(
190    app_server_client: Arc<dyn AppServerClient>,
191    request: OneShotRequest,
192    cancellation: CancellationToken,
193    session_id: String,
194    pooled: bool,
195) -> Result<OneShotSubmission, String> {
196    clear_child_pid_slot(request.child_pid.as_deref());
197    let work = execute_one_shot_app_server_turns(
198        app_server_client.as_ref(),
199        request,
200        &session_id,
201        &cancellation,
202        pooled,
203    );
204    tokio::pin!(work);
205    let work = poll_fn(|context| {
206        catch_unwind(AssertUnwindSafe(|| work.as_mut().poll(context)))
207            .unwrap_or_else(|_| Poll::Ready(Err("One-shot provider turn panicked".to_string())))
208    });
209    tokio::pin!(work);
210    tokio::select! {
211        biased;
212        result = &mut work => {
213            if !pooled || result.is_err() || cancellation.is_cancelled() {
214                app_server_client.shutdown_session(session_id.clone()).await;
215            }
216            result
217        }
218        () = cancellation.cancelled() => {
219            // Keep polling the turn so the adapter can observe shutdown and
220            // release the runtime it temporarily removed from its registry.
221            let _ = tokio::join!(app_server_client.shutdown_session(session_id.clone()), &mut work);
222            Err("[Stopped] Agent run canceled".to_string())
223        }
224    }
225}
226
227/// Executes the initial turn and optional protocol repair in the same session.
228async fn execute_one_shot_app_server_turns(
229    app_server_client: &dyn AppServerClient,
230    request: OneShotRequest,
231    session_id: &str,
232    cancellation: &CancellationToken,
233    pooled: bool,
234) -> Result<OneShotSubmission, String> {
235    if cancellation.is_cancelled() {
236        return Err("[Stopped] Agent run canceled".to_string());
237    }
238    let protocol_profile = request.request_kind.protocol_profile();
239    let (stream_tx, _stream_rx) = tokio::sync::mpsc::unbounded_channel();
240    let turn_request = AppServerTurnRequest {
241        execution_policy: request.execution_policy.clone(),
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: ag_contracts::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        execution_policy: request.execution_policy.clone(),
404        provider_call_budget: request.provider_call_budget.clone(),
405        folder: request.folder,
406        live_transcript: None,
407        main_checkout_root: None,
408        model: request.model.clone(),
409        permission_mode: request.permission_mode,
410        personality: ag_contracts::PersonalityPrompt::default(),
411        prompt: ag_protocol::TurnPrompt::from_agent_data(repair_prompt),
412        request_kind: request.request_kind,
413        replay_transcript: None,
414        provider_conversation_id: provider_conversation_id.map(String::from),
415        persisted_instruction_conversation_id: None,
416        reasoning_level: request.reasoning_level,
417        session_id: session_id.to_string(),
418        speed_mode: request.speed_mode,
419    };
420    let repair_result = if pooled {
421        app_server_client.run_retained_turn(repair_turn_request, repair_stream_tx)
422    } else {
423        app_server_client.run_turn(repair_turn_request, repair_stream_tx)
424    }
425    .await
426    .map_err(|error| format!("{parse_error}\nrepair transport failed: {error}"))?;
427
428    let response = parse_one_shot_response(&repair_result.assistant_message, protocol_profile)
429        .map_err(|error| {
430            format!(
431                "{parse_error}\nrepair retry also failed: {error}\nrepair_response:\n{}",
432                repair_result.assistant_message
433            )
434        })?;
435
436    Ok((
437        response,
438        repair_result.input_tokens,
439        repair_result.output_tokens,
440    ))
441}
442
443/// Runs one one-shot backend command and returns the parsed provider content.
444///
445/// The spawned child is configured with `kill_on_drop(true)` so timeout-driven
446/// callers do not leave orphaned agent CLI processes behind when the future is
447/// canceled before completion.
448///
449/// # Errors
450/// Returns an error when the command cannot be built, run, or exits
451/// unsuccessfully.
452async fn execute_one_shot_command(
453    backend: &dyn AgentBackend,
454    prompt: &str,
455    request: OneShotRequest,
456) -> Result<ParsedResponse, String> {
457    if let Some(budget) = &request.provider_call_budget {
458        budget.consume().map_err(|error| error.to_string())?;
459    }
460    let prompt_payload = ag_protocol::TurnPrompt::from_agent_data(prompt.to_string());
461    let agent_kind = request.harness.parse::<AgentKind>()?;
462    let build_request = BuildCommandRequest {
463        execution_policy: &request.execution_policy,
464        attachments: &prompt_payload.attachments,
465        folder: &request.folder,
466        main_checkout_root: None,
467        replay_transcript: None,
468        model: &request.model,
469        permission_mode: request.permission_mode,
470        personality_prompt: None,
471        prompt,
472        reasoning_level: request.reasoning_level,
473        request_kind: &request.request_kind,
474        speed_mode: request.speed_mode,
475    };
476    let observer = OneShotCliObserver {
477        child_pid: request.child_pid,
478    };
479    let output =
480        execution::execute_cli_command(backend, agent_kind, build_request, &observer, None)
481            .await
482            .map_err(format_one_shot_execution_error)?;
483
484    match output.exit_status {
485        CliExitStatus::Signaled(_) => {
486            return Err("One-shot agent command was interrupted".to_string());
487        }
488        CliExitStatus::NonZero(exit_code) => {
489            return Err(format_one_shot_exit_error(
490                agent_kind,
491                exit_code,
492                &output.stdout,
493                &output.stderr,
494            ));
495        }
496        CliExitStatus::Success => {}
497    }
498
499    let parsed_response = parse_response(agent_kind, &output.stdout, &output.stderr);
500
501    Ok(parsed_response)
502}
503
504/// Preserves the established one-shot context around shared execution errors.
505fn format_one_shot_execution_error(error: CliExecutionError) -> String {
506    match error {
507        CliExecutionError::CommandBuild(error) => {
508            format!("Failed to build one-shot agent command: {error}")
509        }
510        CliExecutionError::StdinBuild(error) => {
511            format!("Failed to build one-shot agent stdin payload: {error}")
512        }
513        error => format!("Failed to execute one-shot agent command: {error}"),
514    }
515}
516
517/// Formats one non-zero one-shot command exit into a user-facing error.
518fn format_one_shot_exit_error(
519    agent_kind: AgentKind,
520    exit_code: Option<i32>,
521    stdout: &str,
522    stderr: &str,
523) -> String {
524    error::format_agent_cli_exit_error(
525        agent_kind,
526        "One-shot agent command",
527        exit_code,
528        stdout,
529        stderr,
530    )
531}
532
533/// Clears the shared one-shot child PID slot when one exists.
534fn clear_child_pid_slot(child_pid: Option<&Mutex<Option<u32>>>) {
535    let Some(child_pid) = child_pid else {
536        return;
537    };
538
539    if let Ok(mut guard) = child_pid.lock() {
540        *guard = None;
541    }
542}
543
544/// Bridges shared CLI PID observations into the one-shot accounting slot.
545struct OneShotCliObserver {
546    child_pid: Option<Arc<Mutex<Option<u32>>>>,
547}
548
549impl CliExecutionObserver for OneShotCliObserver {
550    fn pid_updated(&self, active_child_pid: Option<u32>) {
551        let Some(child_pid_slot) = self.child_pid.as_deref() else {
552            return;
553        };
554
555        if let Ok(mut guard) = child_pid_slot.lock() {
556            *guard = active_child_pid;
557        }
558    }
559
560    fn stdout_line(&self, _line: &str) {}
561}
562
563#[cfg(test)]
564#[path = "submission_test.rs"]
565mod tests;
566
567#[cfg(test)]
568#[path = "submission_budget_test.rs"]
569mod budget_tests;