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 personality body included during a full prompt bootstrap.
63 pub personality_prompt: Option<&'a str>,
64 /// User prompt to send.
65 pub prompt: &'a str,
66 /// Reasoning effort preference for this turn.
67 ///
68 /// Ignored by backends/models that do not support reasoning effort.
69 pub reasoning_level: ReasoningLevel,
70 /// Replayable transcript text captured when the turn was queued.
71 pub replay_transcript: Option<&'a str>,
72 /// Canonical request kind that drives execution and protocol semantics.
73 pub request_kind: &'a AgentRequestKind,
74 /// Response-speed preference for this turn.
75 pub speed_mode: SpeedMode,
76}
77
78/// Error type for backend setup and command construction failures.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum AgentBackendError {
81 /// One-time backend setup failure.
82 Setup(String),
83 /// Per-command build failure.
84 CommandBuild(String),
85}
86
87impl fmt::Display for AgentBackendError {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 match self {
90 Self::Setup(message) | Self::CommandBuild(message) => {
91 write!(formatter, "{message}")
92 }
93 }
94 }
95}
96
97impl Error for AgentBackendError {}
98
99impl From<AgentBackendError> for ag_contracts::AgentError {
100 fn from(error: AgentBackendError) -> Self {
101 Self::Backend(error.to_string())
102 }
103}
104
105/// Builds and configures external agent CLI commands.
106#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
107pub trait AgentBackend: Send + Sync {
108 /// Performs one-time setup in an agent folder before first run.
109 ///
110 /// # Errors
111 /// Returns an error when one-time backend setup cannot be completed.
112 fn setup(&self, folder: &Path) -> Result<(), AgentBackendError>;
113
114 /// Builds one provider transport command.
115 ///
116 /// CLI-backed providers return the per-turn subprocess command. Managed
117 /// providers return the long-lived runtime command that owns later turn
118 /// execution over its native protocol.
119 ///
120 /// # Errors
121 /// Returns an error when prompt rendering or provider argument
122 /// construction fails.
123 fn build_command<'request>(
124 &'request self,
125 request: BuildCommandRequest<'request>,
126 ) -> Result<Command, AgentBackendError>;
127}
128
129#[cfg(test)]
130#[path = "backend_test.rs"]
131mod tests;