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    /// Replayable transcript text captured when the turn was queued.
76    pub replay_transcript: Option<&'a str>,
77    /// Canonical request kind that drives execution and protocol semantics.
78    pub request_kind: &'a AgentRequestKind,
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
104impl From<AgentBackendError> for ag_runtime::AgentError {
105    fn from(error: AgentBackendError) -> Self {
106        Self::Backend(error.to_string())
107    }
108}
109
110/// Builds and configures external agent CLI commands.
111#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
112pub trait AgentBackend: Send + Sync {
113    /// Performs one-time setup in an agent folder before first run.
114    ///
115    /// # Errors
116    /// Returns an error when one-time backend setup cannot be completed.
117    fn setup(&self, folder: &Path) -> Result<(), AgentBackendError>;
118
119    /// Builds one provider transport command.
120    ///
121    /// CLI-backed providers return the per-turn subprocess command. Managed
122    /// providers return the long-lived runtime command that owns later turn
123    /// execution over its native protocol.
124    ///
125    /// # Errors
126    /// Returns an error when prompt rendering or provider argument
127    /// construction fails.
128    fn build_command<'request>(
129        &'request self,
130        request: BuildCommandRequest<'request>,
131    ) -> Result<Command, AgentBackendError>;
132}
133
134#[cfg(test)]
135#[path = "backend_test.rs"]
136mod tests;