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_protocol::TurnPromptAttachment;
7
8use crate::channel::AgentRequestKind;
9use crate::model::agent::ReasoningLevel;
10use crate::model::permission::PermissionMode;
11use crate::model::session::SpeedMode;
12
13/// Maximum concurrent subagents requested from providers with a native limit.
14///
15/// Excludes the parent agent. Provider exceptions still apply; this is not a
16/// host-wide CPU or memory limit.
17pub(super) const MAX_CONCURRENT_SUBAGENTS: usize = 2;
18
19/// Transport runtime used to execute turns for one backend.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum AgentTransport {
22    /// Provider runs through a managed session runtime.
23    AppServer,
24    /// Provider runs as direct CLI subprocess commands.
25    Cli,
26}
27
28impl AgentTransport {
29    /// Returns whether this transport uses managed runtime sessions.
30    pub fn uses_app_server(self) -> bool {
31        matches!(self, Self::AppServer)
32    }
33}
34
35/// Prompt delivery mode used by one provider backend.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub(crate) enum AgentPromptTransport {
38    /// Prompt is passed inline through argv.
39    Argv,
40    /// Prompt is streamed through stdin.
41    Stdin,
42}
43
44/// Managed-runtime thought-stream classification policy for one provider.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub(crate) enum AppServerThoughtPolicy {
47    /// Provider does not expose dedicated thought phases.
48    None,
49    /// Provider uses phase labels to distinguish thought chunks.
50    PhaseLabel,
51}
52
53/// Request payload used to build provider transport commands.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct BuildCommandRequest<'a> {
56    /// Ordered local image attachments referenced from the prompt body.
57    pub attachments: &'a [TurnPromptAttachment],
58    /// Working directory where the command will run.
59    pub folder: &'a Path,
60    /// Main repository checkout that must remain read-only during the turn,
61    /// when Agentty can resolve it.
62    pub main_checkout_root: Option<&'a Path>,
63    /// Provider-specific model identifier.
64    pub model: &'a str,
65    /// Filesystem and command permission policy for this turn.
66    pub permission_mode: PermissionMode,
67    /// Current personality body included during a full prompt bootstrap.
68    pub personality_prompt: Option<&'a str>,
69    /// User prompt to send.
70    pub prompt: &'a str,
71    /// Reasoning effort preference for this turn.
72    ///
73    /// Ignored by backends/models that do not support reasoning effort.
74    pub reasoning_level: ReasoningLevel,
75    /// Canonical request kind that drives execution and protocol semantics.
76    pub request_kind: &'a AgentRequestKind,
77    /// Replayable transcript text captured when the turn was queued.
78    pub replay_transcript: Option<&'a str>,
79    /// Response-speed preference for this turn.
80    pub speed_mode: SpeedMode,
81}
82
83/// Error type for backend setup and command construction failures.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum AgentBackendError {
86    /// One-time backend setup failure.
87    Setup(String),
88    /// Per-command build failure.
89    CommandBuild(String),
90}
91
92impl fmt::Display for AgentBackendError {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match self {
95            Self::Setup(message) | Self::CommandBuild(message) => {
96                write!(formatter, "{message}")
97            }
98        }
99    }
100}
101
102impl Error for AgentBackendError {}
103
104/// Builds and configures external agent CLI commands.
105#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
106pub trait AgentBackend: Send + Sync {
107    /// Performs one-time setup in an agent folder before first run.
108    ///
109    /// # Errors
110    /// Returns an error when one-time backend setup cannot be completed.
111    fn setup(&self, folder: &Path) -> Result<(), AgentBackendError>;
112
113    /// Builds one provider transport command.
114    ///
115    /// CLI-backed providers return the per-turn subprocess command. Managed
116    /// providers return the long-lived runtime command that owns later turn
117    /// execution over its native protocol.
118    ///
119    /// # Errors
120    /// Returns an error when prompt rendering or provider argument
121    /// construction fails.
122    fn build_command<'request>(
123        &'request self,
124        request: BuildCommandRequest<'request>,
125    ) -> Result<Command, AgentBackendError>;
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn test_agent_transport_app_server_uses_app_server() {
134        // Arrange
135        let transport = AgentTransport::AppServer;
136
137        // Act
138        let result = transport.uses_app_server();
139
140        // Assert
141        assert!(result);
142    }
143
144    #[test]
145    fn test_agent_transport_cli_does_not_use_app_server() {
146        // Arrange
147        let transport = AgentTransport::Cli;
148
149        // Act
150        let result = transport.uses_app_server();
151
152        // Assert
153        assert!(!result);
154    }
155
156    #[test]
157    fn test_agent_backend_error_setup_displays_message() {
158        // Arrange
159        let error = AgentBackendError::Setup("setup failed".to_string());
160
161        // Act
162        let display = format!("{error}");
163
164        // Assert
165        assert_eq!(display, "setup failed");
166    }
167
168    #[test]
169    fn test_agent_backend_error_command_build_displays_message() {
170        // Arrange
171        let error = AgentBackendError::CommandBuild("build failed".to_string());
172
173        // Act
174        let display = format!("{error}");
175
176        // Assert
177        assert_eq!(display, "build failed");
178    }
179
180    #[test]
181    fn test_agent_backend_error_implements_std_error() {
182        // Arrange
183        let error = AgentBackendError::Setup("test error".to_string());
184
185        // Act
186        let std_error: &dyn Error = &error;
187
188        // Assert
189        assert_eq!(std_error.to_string(), "test error");
190        assert!(std_error.source().is_none());
191    }
192
193    #[test]
194    fn test_agent_backend_error_setup_and_command_build_are_distinct() {
195        // Arrange
196        let setup_error = AgentBackendError::Setup("failure".to_string());
197        let build_error = AgentBackendError::CommandBuild("failure".to_string());
198
199        // Act / Assert
200        assert_ne!(setup_error, build_error);
201    }
202}