Skip to main content

ag_runtime/
one_shot.rs

1use std::path::PathBuf;
2use std::sync::{Arc, Mutex};
3
4use ag_protocol::AgentResponse;
5use async_trait::async_trait;
6use tokio_util::sync::CancellationToken;
7
8use crate::{AgentRequestKind, PermissionMode, ReasoningLevel, SessionStats, SpeedMode};
9
10/// Input payload for one isolated prompt that prefers structured protocol
11/// output.
12#[derive(Clone, Debug)]
13pub struct OneShotRequest {
14    /// Optional PID slot for resource accounting while a prompt is running.
15    /// Subprocess lifetime and cancellation belong to the runtime adapter.
16    pub child_pid: Option<Arc<Mutex<Option<u32>>>>,
17    /// Working directory where the prompt command runs.
18    pub folder: PathBuf,
19    /// Harness identifier resolved by the host-selected runtime implementation.
20    pub harness: String,
21    /// Provider-specific model used for command construction and parsing.
22    pub model: String,
23    /// Filesystem and command permission policy for this isolated prompt.
24    pub permission_mode: PermissionMode,
25    /// Prompt text submitted to the agent.
26    pub prompt: String,
27    /// Optional shared limit, charged for every provider turn including
28    /// repairs.
29    pub provider_call_budget: Option<crate::ProviderCallBudget>,
30    /// Reasoning effort preference for the one-shot prompt.
31    pub reasoning_level: ReasoningLevel,
32    /// Canonical request kind for this isolated prompt.
33    pub request_kind: AgentRequestKind,
34    /// Response-speed preference for the one-shot prompt.
35    pub speed_mode: SpeedMode,
36}
37
38/// Parsed result returned by one isolated prompt execution.
39#[derive(Clone, Debug, PartialEq)]
40pub struct OneShotSubmission {
41    /// Structured protocol response parsed from the final successful attempt.
42    pub response: AgentResponse,
43    /// Aggregated token usage for the one-shot prompt execution.
44    pub stats: SessionStats,
45}
46
47/// Typed failure returned by [`OneShotClient`] submissions.
48///
49/// The concrete transport, protocol-repair, and provider diagnostics remain
50/// available through [`std::fmt::Display`] without exposing transport-specific
51/// variants to callers.
52#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
53#[error("{message}")]
54pub struct OneShotError {
55    message: String,
56}
57
58impl OneShotError {
59    /// Creates an error from one already formatted submission diagnostic.
60    pub fn new(message: impl Into<String>) -> Self {
61        Self {
62            message: message.into(),
63        }
64    }
65}
66
67/// Provider-neutral boundary for isolated structured agent prompts.
68///
69/// Implementations own transport selection, protocol repair, temporary
70/// app-server lifecycle, and usage aggregation so callers submit one request
71/// without selecting a CLI or app-server execution helper.
72#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
73#[async_trait]
74pub trait OneShotClient: Send + Sync {
75    /// Escalates application shutdown after its graceful deadline. This must
76    /// return immediately and permanently stop detached submission tasks.
77    /// The owner also drops in-flight submission futures; adapters whose
78    /// resources are owned entirely by those futures need no extra action.
79    fn force_shutdown(&self) {}
80
81    /// Executes one isolated prompt and returns its parsed response and usage.
82    /// Dropping this future must initiate cleanup of owned provider resources.
83    /// Use `submit_cancellable` to wait for asynchronous cleanup on
84    /// cancellation. Implementations must enforce `provider_call_budget`
85    /// for every underlying provider attempt, including protocol repairs
86    /// and transport retries.
87    async fn submit(&self, request: OneShotRequest) -> Result<OneShotSubmission, OneShotError>;
88
89    /// Cancels an isolated prompt and waits for adapter cleanup before
90    /// returning. The default drops `submit`, suitable for transports with
91    /// synchronous drop cleanup. Adapters requiring asynchronous shutdown
92    /// must override this method.
93    async fn submit_cancellable(
94        &self,
95        request: OneShotRequest,
96        cancellation: CancellationToken,
97    ) -> Result<OneShotSubmission, OneShotError> {
98        tokio::select! {
99            biased;
100            () = cancellation.cancelled() => Err(OneShotError::new("[Stopped] Agent run canceled")),
101            result = self.submit(request) => result,
102        }
103    }
104
105    /// Releases retained provider resources after all submissions and their
106    /// asynchronous cancellation cleanup have finished. Stateless adapters need
107    /// no cleanup.
108    async fn close(&self) {}
109}
110
111#[cfg(test)]
112#[path = "one_shot_test.rs"]
113mod tests;