Skip to main content

artifactize_core/config/
backend.rs

1//! Built-in eval/direct providers, strict HTTP backend types, and machine-configured backend names.
2
3use super::identifier;
4use serde::{Deserialize, Serialize};
5
6/// A built-in direct HTTP provider (API key or Codex OAuth): never an ACP CLI or Claude Code.
7#[derive(
8    Debug,
9    Clone,
10    Copy,
11    PartialEq,
12    Eq,
13    PartialOrd,
14    Ord,
15    Hash,
16    Serialize,
17    Deserialize,
18    clap::ValueEnum,
19)]
20#[serde(rename_all = "lowercase")]
21pub enum HttpProvider {
22    Codex,
23    Openai,
24    Anthropic,
25    Gemini,
26}
27
28impl HttpProvider {
29    pub const ALL: [Self; 4] = [Self::Codex, Self::Openai, Self::Anthropic, Self::Gemini];
30
31    pub fn as_str(self) -> &'static str {
32        match self {
33            Self::Codex => "codex",
34            Self::Openai => "openai",
35            Self::Anthropic => "anthropic",
36            Self::Gemini => "gemini",
37        }
38    }
39
40    pub fn named(name: &str) -> Option<Self> {
41        Self::ALL
42            .into_iter()
43            .find(|provider| provider.as_str() == name)
44    }
45}
46
47impl From<HttpProvider> for Provider {
48    fn from(provider: HttpProvider) -> Self {
49        match provider {
50            HttpProvider::Codex => Self::Codex,
51            HttpProvider::Openai => Self::Openai,
52            HttpProvider::Anthropic => Self::Anthropic,
53            HttpProvider::Gemini => Self::Gemini,
54        }
55    }
56}
57
58impl TryFrom<Provider> for HttpProvider {
59    type Error = String;
60
61    fn try_from(provider: Provider) -> Result<Self, Self::Error> {
62        match provider {
63            Provider::Codex => Ok(Self::Codex),
64            Provider::Openai => Ok(Self::Openai),
65            Provider::Anthropic => Ok(Self::Anthropic),
66            Provider::Gemini => Ok(Self::Gemini),
67            Provider::ClaudeAgent => {
68                Err("claude-agent runs through its native CLI, not a direct HTTP provider.".into())
69            }
70        }
71    }
72}
73
74impl std::fmt::Display for HttpProvider {
75    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        formatter.write_str(self.as_str())
77    }
78}
79
80/// Built-in provider names rejected at parse time by [`CustomBackendName`].
81const RESERVED_BUILTIN_NAMES: [&str; 6] = [
82    "codex",
83    "openai",
84    "anthropic",
85    "gemini",
86    "claude-agent",
87    "antigravity",
88];
89
90/// Custom HTTP backend identifier that rejects all built-in provider names
91/// (`codex`, `openai`, `anthropic`, `gemini`, `claude-agent`, `antigravity`) at parse time.
92#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
93#[serde(transparent)]
94pub struct CustomBackendName(String);
95
96impl CustomBackendName {
97    pub fn as_str(&self) -> &str {
98        &self.0
99    }
100}
101
102impl std::str::FromStr for CustomBackendName {
103    type Err = String;
104
105    fn from_str(name: &str) -> Result<Self, Self::Err> {
106        if RESERVED_BUILTIN_NAMES.contains(&name) {
107            return Err(format!(
108                "{name} is a built-in provider name and cannot be used as a custom HTTP backend."
109            ));
110        }
111        identifier(name, "custom backend")?;
112        Ok(Self(name.to_owned()))
113    }
114}
115
116impl<'de> Deserialize<'de> for CustomBackendName {
117    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
118        String::deserialize(deserializer)?
119            .parse()
120            .map_err(serde::de::Error::custom)
121    }
122}
123
124impl std::fmt::Display for CustomBackendName {
125    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        formatter.write_str(&self.0)
127    }
128}
129
130/// Direct HTTP backend for Chat (`ChatTarget::Direct`): either a built-in [`HttpProvider`] or a
131/// machine-local custom HTTP provider in `$STATE/auth/providers.json`.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133#[serde(tag = "kind", rename_all = "camelCase")]
134pub enum DirectBackend {
135    Builtin {
136        provider: HttpProvider,
137    },
138    /// Resolved at runtime exclusively against `$STATE/auth/providers.json`
139    /// `Custom::Endpoint` or `Custom::Alias(HttpProvider)`.
140    Custom {
141        name: CustomBackendName,
142    },
143}
144
145impl DirectBackend {
146    pub fn as_str(&self) -> &str {
147        match self {
148            Self::Builtin { provider } => provider.as_str(),
149            Self::Custom { name } => name.as_str(),
150        }
151    }
152
153    pub fn to_backend(&self) -> Backend {
154        match self {
155            Self::Builtin { provider } => Backend::from(Provider::from(*provider)),
156            Self::Custom { name } => Backend(name.as_str().to_owned()),
157        }
158    }
159}
160
161impl std::fmt::Display for DirectBackend {
162    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        formatter.write_str(self.as_str())
164    }
165}
166
167/// A built-in eval/direct provider: one artifactize reaches with a sign-in, an API key, or
168/// isolated Claude Code (`claude-agent`). Chat-only ACP agents (including Antigravity) live
169/// under `crate::acp` and are never part of `Provider`.
170#[derive(
171    Debug,
172    Clone,
173    Copy,
174    PartialEq,
175    Eq,
176    PartialOrd,
177    Ord,
178    Hash,
179    Serialize,
180    Deserialize,
181    clap::ValueEnum,
182)]
183#[serde(rename_all = "lowercase")]
184pub enum Provider {
185    /// The ChatGPT/Codex account (artifactize login codex).
186    Codex,
187    /// The user's own Claude Code and its login (claude auth login).
188    #[serde(rename = "claude-agent")]
189    #[value(name = "claude-agent")]
190    ClaudeAgent,
191    /// The OpenAI API (OPENAI_API_KEY or a saved key).
192    Openai,
193    /// The Anthropic API (ANTHROPIC_API_KEY or a saved key).
194    Anthropic,
195    /// The Gemini API (GEMINI_API_KEY or a saved key).
196    Gemini,
197}
198
199impl Provider {
200    /// In the order Settings → Providers lists them.
201    pub const ALL: [Self; 5] = [
202        Self::Codex,
203        Self::ClaudeAgent,
204        Self::Openai,
205        Self::Anthropic,
206        Self::Gemini,
207    ];
208
209    pub fn as_str(self) -> &'static str {
210        match self {
211            Self::Anthropic => "anthropic",
212            Self::ClaudeAgent => "claude-agent",
213            Self::Codex => "codex",
214            Self::Gemini => "gemini",
215            Self::Openai => "openai",
216        }
217    }
218
219    pub fn named(name: &str) -> Option<Self> {
220        Self::ALL
221            .into_iter()
222            .find(|provider| provider.as_str() == name)
223    }
224}
225
226impl std::fmt::Display for Provider {
227    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        formatter.write_str(self.as_str())
229    }
230}
231
232/// Backends that 0.5.0 removed; a declaration naming one fails with its replacements.
233const REMOVED_BACKENDS: [&str; 2] = ["chatgpt", "claude"];
234/// Chat-only Antigravity backend name, statically rejected in `.artf` eval declarations.
235pub(crate) const ANTIGRAVITY_BACKEND: &str = "antigravity";
236/// Static refusal message when an eval declaration or override names `antigravity`.
237pub(crate) const ANTIGRAVITY_EVAL_REFUSAL: &str = "Antigravity is available for Chat only: Google's consumer plans don't cover automated evaluation and the CLI can't be confined to an eval's tools; use the `gemini` API-key backend";
238
239/// What an Agent profile's `backend` names: a built-in [`Provider`], or a custom provider
240/// set up on the machine that runs the eval. The project only declares the name.
241#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
242#[serde(transparent)]
243pub struct Backend(String);
244
245impl Backend {
246    pub fn as_str(&self) -> &str {
247        &self.0
248    }
249
250    /// The built-in provider this names, or `None` for a custom provider.
251    pub fn builtin(&self) -> Option<Provider> {
252        Provider::named(&self.0)
253    }
254
255    /// Statically reject Chat-only `antigravity` in `.artf` declarations and profile overrides.
256    /// Other ACP preset names are NOT statically rejected here because v11 users may already
257    /// have custom HTTP backends with those names in `providers.json`.
258    pub(crate) fn validate_eval(&self) -> Result<(), String> {
259        if self.0 == ANTIGRAVITY_BACKEND {
260            Err(ANTIGRAVITY_EVAL_REFUSAL.to_owned())
261        } else {
262            Ok(())
263        }
264    }
265
266    /// Whether this name is reserved and cannot be used for a custom HTTP provider.
267    pub(crate) fn is_reserved_custom(&self) -> bool {
268        RESERVED_BUILTIN_NAMES.contains(&self.0.as_str())
269    }
270}
271
272impl From<Provider> for Backend {
273    fn from(provider: Provider) -> Self {
274        Self(provider.as_str().to_owned())
275    }
276}
277
278impl From<HttpProvider> for Backend {
279    fn from(provider: HttpProvider) -> Self {
280        Self(provider.as_str().to_owned())
281    }
282}
283
284impl std::str::FromStr for Backend {
285    type Err = String;
286    fn from_str(name: &str) -> Result<Self, Self::Err> {
287        if REMOVED_BACKENDS.contains(&name) {
288            return Err(format!(
289                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"#
290            ));
291        }
292        identifier(name, "backend")?;
293        Ok(Self(name.to_owned()))
294    }
295}
296
297impl<'de> Deserialize<'de> for Backend {
298    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
299        String::deserialize(deserializer)?
300            .parse()
301            .map_err(serde::de::Error::custom)
302    }
303}
304
305impl std::fmt::Display for Backend {
306    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        formatter.write_str(&self.0)
308    }
309}