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