Skip to main content

ag_agent/agent/
backend.rs

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