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