Skip to main content

artifactize_harness/
backend.rs

1//! Built-in eval/direct providers, strict HTTP backend types, and machine-configured backend names.
2
3use serde::{Deserialize, Serialize};
4
5use crate::error::{Code, Failure};
6
7impl From<HttpProvider> for Provider {
8    fn from(provider: HttpProvider) -> Self {
9        match provider {
10            HttpProvider::Codex => Self::Codex,
11            HttpProvider::Openai => Self::Openai,
12            HttpProvider::Anthropic => Self::Anthropic,
13            HttpProvider::Gemini => Self::Gemini,
14        }
15    }
16}
17
18impl TryFrom<Provider> for HttpProvider {
19    type Error = String;
20
21    fn try_from(provider: Provider) -> Result<Self, Self::Error> {
22        match provider {
23            Provider::Codex => Ok(Self::Codex),
24            Provider::Openai => Ok(Self::Openai),
25            Provider::Anthropic => Ok(Self::Anthropic),
26            Provider::Gemini => Ok(Self::Gemini),
27            Provider::ClaudeAgent => {
28                Err("claude runs through Claude Code, not a direct HTTP provider.".into())
29            }
30        }
31    }
32}
33
34pub use artifactize_provider::names::{CustomBackendName, DirectBackend, HttpProvider};
35
36/// A built-in eval backend: an agent of the provider's agent catalog that has a reviewer
37/// harness (Claude, Codex), or an API provider. No other agent can join this list.
38#[derive(
39    Debug,
40    Clone,
41    Copy,
42    PartialEq,
43    Eq,
44    PartialOrd,
45    Ord,
46    Hash,
47    Serialize,
48    Deserialize,
49    clap::ValueEnum,
50)]
51#[serde(rename_all = "lowercase")]
52pub enum Provider {
53    /// The Codex CLI's own ChatGPT sign-in (codex login).
54    Codex,
55    /// The user's own Claude Code and its login (claude auth login). `claude-agent` is its
56    /// earlier name.
57    #[serde(rename = "claude", alias = "claude-agent")]
58    #[value(name = "claude", alias = "claude-agent")]
59    ClaudeAgent,
60    /// The OpenAI API (OPENAI_API_KEY or a saved key).
61    Openai,
62    /// The Anthropic API (ANTHROPIC_API_KEY or a saved key).
63    Anthropic,
64    /// The Gemini API (GEMINI_API_KEY or a saved key).
65    Gemini,
66}
67
68impl Provider {
69    /// In the order Settings → Agents lists them: the agents, then the API providers.
70    pub const ALL: [Self; 5] = [
71        Self::ClaudeAgent,
72        Self::Codex,
73        Self::Openai,
74        Self::Anthropic,
75        Self::Gemini,
76    ];
77
78    pub fn as_str(self) -> &'static str {
79        match self {
80            Self::Anthropic => "anthropic",
81            Self::ClaudeAgent => "claude",
82            Self::Codex => "codex",
83            Self::Gemini => "gemini",
84            Self::Openai => "openai",
85        }
86    }
87
88    /// The provider with this name, or with an earlier name of the same agent.
89    pub fn named(name: &str) -> Option<Self> {
90        let name = artifactize_provider::agents::agent(name).map_or(name, |agent| agent.id);
91        Self::ALL
92            .into_iter()
93            .find(|provider| provider.as_str() == name)
94    }
95}
96
97impl std::fmt::Display for Provider {
98    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        formatter.write_str(self.as_str())
100    }
101}
102
103/// Backends that 0.5.0 removed; a declaration naming one fails with its replacements.
104const REMOVED_BACKENDS: [&str; 1] = ["chatgpt"];
105
106/// What an Agent profile's `backend` names: a built-in [`Provider`], or a custom provider
107/// set up on the machine that runs the eval. The project only declares the name.
108#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
109#[serde(transparent)]
110pub struct Backend(String);
111
112impl Backend {
113    pub fn as_str(&self) -> &str {
114        &self.0
115    }
116
117    /// The built-in provider this names, or `None` for a custom provider.
118    pub fn builtin(&self) -> Option<Provider> {
119        Provider::named(&self.0)
120    }
121
122    /// A custom HTTP registration may live on a different machine from the parser.
123    pub fn validate_eval(&self) -> Result<(), String> {
124        self.selection().map(|_| ())
125    }
126
127    pub fn selection(&self) -> Result<Selection, String> {
128        if let Some(agent) = artifactize_provider::agents::agent(&self.0)
129            && let artifactize_provider::agents::Review::ChatOnly { reason } = agent.review
130        {
131            return Err(format!(
132                "Backend {self} is not an evaluation backend: {} is Chat only. {reason}",
133                agent.name
134            ));
135        }
136        Ok(match self.builtin() {
137            Some(Provider::ClaudeAgent) => Selection::ClaudeAgent,
138            Some(provider) => Selection::Http(DirectBackend::Builtin {
139                provider: provider.try_into().expect("direct HTTP provider"),
140            }),
141            None => Selection::Http(DirectBackend::Custom {
142                name: self.0.parse().map_err(|error| {
143                    format!("Backend {self} is not an evaluation backend: {error}")
144                })?,
145            }),
146        })
147    }
148
149    /// Check that a Run can admit the declared backend, without resolving credentials.
150    /// Only custom HTTP names need to be checked against the local provider registrations.
151    pub fn admit(
152        &self,
153        registered: impl FnOnce(&CustomBackendName) -> Result<bool, String>,
154    ) -> Result<(), Failure> {
155        match self.selection()? {
156            Selection::Http(DirectBackend::Custom { name }) if !registered(&name)? => {
157                Err(Failure::new(Code::Authentication, self.not_registered()))
158            }
159            _ => Ok(()),
160        }
161    }
162
163    pub fn not_registered(&self) -> String {
164        format!(
165            "Backend {self} is not an evaluation backend on this machine. No provider named {self} is set up on this machine; add it in Settings → Agents or with `artifactize provider add {self}`."
166        )
167    }
168
169    /// Whether this name is reserved and cannot be used for a custom HTTP provider.
170    pub fn is_reserved_custom(&self) -> bool {
171        artifactize_provider::names::is_reserved_custom(&self.0)
172    }
173}
174
175impl From<Provider> for Backend {
176    fn from(provider: Provider) -> Self {
177        Self(provider.as_str().to_owned())
178    }
179}
180
181impl From<HttpProvider> for Backend {
182    fn from(provider: HttpProvider) -> Self {
183        Self(provider.as_str().to_owned())
184    }
185}
186
187impl std::str::FromStr for Backend {
188    type Err = String;
189    fn from_str(name: &str) -> Result<Self, Self::Err> {
190        if REMOVED_BACKENDS.contains(&name) {
191            return Err(format!(
192                r#"backend "{name}" was removed in 0.5.0; use "openai", "anthropic" or "gemini" with an API key, "codex" with the Codex CLI's sign-in, or "claude" with your Claude Code login"#
193            ));
194        }
195        // Machine-local backend names use the same identifier grammar as HTTP registrations.
196        const MAX_NAME_BYTES: usize = 64;
197        if name.is_empty()
198            || name.len() > MAX_NAME_BYTES
199            || !name.as_bytes()[0].is_ascii_alphanumeric()
200            || !name
201                .bytes()
202                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
203        {
204            return Err("backend must match [A-Za-z0-9][A-Za-z0-9_-]{0,63}.".into());
205        }
206        Ok(Self(name.to_owned()))
207    }
208}
209
210impl<'de> Deserialize<'de> for Backend {
211    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
212        String::deserialize(deserializer)?
213            .parse()
214            .map_err(serde::de::Error::custom)
215    }
216}
217
218impl std::fmt::Display for Backend {
219    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        formatter.write_str(&self.0)
221    }
222}
223
224impl From<&DirectBackend> for Backend {
225    fn from(direct: &DirectBackend) -> Self {
226        Self(direct.as_str().to_owned())
227    }
228}
229
230/// The only two ways to run an Agent eval; there is no generic agent process route.
231pub enum Selection {
232    ClaudeAgent,
233    Http(DirectBackend),
234}
235
236#[cfg(test)]
237mod tests;