Skip to main content

ag_agent/agent/
backend.rs

1//! Agent backend trait for provider setup and command construction, with its
2//! request, error, and transport types.
3
4use std::error::Error;
5use std::fmt;
6use std::path::Path;
7use std::process::Command;
8
9use ag_contracts::{AgentRequestKind, PermissionMode, ReasoningLevel, SpeedMode};
10use ag_protocol::TurnPromptAttachment;
11
12/// Transport runtime used to execute turns for one backend.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum AgentTransport {
15    /// Provider runs through a managed session runtime.
16    AppServer,
17    /// Provider runs as direct CLI subprocess commands.
18    Cli,
19    /// Provider runs in process through `ag-harness`, when the host configures
20    /// it.
21    Native,
22}
23
24impl AgentTransport {
25    /// Returns whether this transport uses managed runtime sessions.
26    pub fn uses_app_server(self) -> bool {
27        matches!(self, Self::AppServer)
28    }
29}
30
31/// Prompt delivery mode used by one provider backend.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub(crate) enum AgentPromptTransport {
34    /// Prompt is passed inline through argv.
35    Argv,
36    /// Prompt is streamed through stdin.
37    Stdin,
38}
39
40/// Managed-runtime thought-stream classification policy for one provider.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum AppServerThoughtPolicy {
43    /// Provider does not expose dedicated thought phases.
44    None,
45    /// Provider uses phase labels to distinguish thought chunks.
46    PhaseLabel,
47}
48
49/// Request payload used to build provider transport commands.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct BuildCommandRequest<'a> {
52    /// Ordered local image attachments referenced from the prompt body.
53    pub attachments: &'a [TurnPromptAttachment],
54    /// Worker-selected policy translated into provider startup settings.
55    pub execution_policy: &'a ag_contracts::ExecutionPolicy,
56    /// Working directory where the command will run.
57    pub folder: &'a Path,
58    /// Main repository checkout that must remain read-only during the turn,
59    /// when Agentty can resolve it.
60    pub main_checkout_root: Option<&'a Path>,
61    /// Provider-specific model identifier.
62    pub model: &'a str,
63    /// Filesystem and command permission policy for this turn.
64    pub permission_mode: PermissionMode,
65    /// Current agent body included during a full prompt bootstrap.
66    pub agent_profile_prompt: Option<&'a str>,
67    /// Agent change that must reach prompt rendering, including withdrawal
68    /// guidance when continuing a previously configured session.
69    pub agent_profile_update: &'a ag_contracts::AgentDefinitionPromptUpdate,
70    /// User prompt to send.
71    pub prompt: &'a str,
72    /// Reasoning effort preference for this turn.
73    ///
74    /// Ignored by backends/models that do not support reasoning effort.
75    pub reasoning_level: ReasoningLevel,
76    /// Replayable transcript text captured when the turn was queued.
77    pub replay_transcript: Option<&'a str>,
78    /// Canonical request kind that drives execution and protocol semantics.
79    pub request_kind: &'a AgentRequestKind,
80    /// Response-speed preference for this turn.
81    pub speed_mode: SpeedMode,
82}
83
84/// Error type for backend setup and command construction failures.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum AgentBackendError {
87    /// One-time backend setup failure.
88    Setup(String),
89    /// Per-command build failure.
90    CommandBuild(String),
91}
92
93impl AgentBackendError {
94    /// Wraps one command-construction failure, such as an unrepresentable
95    /// prompt image path or a prompt template rendering error, as
96    /// [`AgentBackendError::CommandBuild`].
97    pub(crate) fn command_build(error: impl fmt::Display) -> Self {
98        Self::CommandBuild(error.to_string())
99    }
100}
101
102impl fmt::Display for AgentBackendError {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            Self::Setup(message) | Self::CommandBuild(message) => {
106                write!(formatter, "{message}")
107            }
108        }
109    }
110}
111
112impl Error for AgentBackendError {}
113
114impl From<AgentBackendError> for ag_contracts::AgentError {
115    fn from(error: AgentBackendError) -> Self {
116        Self::Backend(error.to_string())
117    }
118}
119
120/// Builds and configures external agent CLI commands.
121#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
122pub trait AgentBackend: Send + Sync {
123    /// Performs one-time setup in an agent folder before first run.
124    ///
125    /// # Errors
126    /// Returns an error when one-time backend setup cannot be completed.
127    fn setup(&self, folder: &Path) -> Result<(), AgentBackendError>;
128
129    /// Builds one provider transport command.
130    ///
131    /// CLI-backed providers return the per-turn subprocess command. Managed
132    /// providers return the long-lived runtime command that owns later turn
133    /// execution over its native protocol.
134    ///
135    /// # Errors
136    /// Returns an error when prompt rendering or provider argument
137    /// construction fails.
138    fn build_command<'request>(
139        &'request self,
140        request: BuildCommandRequest<'request>,
141    ) -> Result<Command, AgentBackendError>;
142}
143
144#[cfg(test)]
145#[path = "backend_test.rs"]
146mod tests;