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