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