Skip to main content

artifactize_provider/
names.rs

1//! Identifiers at direct HTTP provider boundaries.
2
3use serde::{Deserialize, Serialize};
4
5/// A built-in direct HTTP provider (API key or Codex OAuth): never an ACP CLI or Claude Code.
6#[derive(
7    Debug,
8    Clone,
9    Copy,
10    PartialEq,
11    Eq,
12    PartialOrd,
13    Ord,
14    Hash,
15    Serialize,
16    Deserialize,
17    clap::ValueEnum,
18)]
19#[serde(rename_all = "lowercase")]
20pub enum HttpProvider {
21    Codex,
22    Openai,
23    Anthropic,
24    Gemini,
25}
26
27impl HttpProvider {
28    pub const ALL: [Self; 4] = [Self::Codex, Self::Openai, Self::Anthropic, Self::Gemini];
29
30    pub fn as_str(self) -> &'static str {
31        match self {
32            Self::Codex => "codex",
33            Self::Openai => "openai",
34            Self::Anthropic => "anthropic",
35            Self::Gemini => "gemini",
36        }
37    }
38
39    pub fn named(name: &str) -> Option<Self> {
40        Self::ALL
41            .into_iter()
42            .find(|provider| provider.as_str() == name)
43    }
44}
45
46impl std::fmt::Display for HttpProvider {
47    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        formatter.write_str(self.as_str())
49    }
50}
51
52/// Built-in provider names rejected at parse time by [`CustomBackendName`].
53const RESERVED_BUILTIN_NAMES: [&str; 6] = [
54    "codex",
55    "openai",
56    "anthropic",
57    "gemini",
58    "claude-agent",
59    "antigravity",
60];
61
62pub fn is_reserved_custom(name: &str) -> bool {
63    RESERVED_BUILTIN_NAMES.contains(&name)
64}
65
66/// Custom HTTP backend identifier that rejects all built-in provider names
67/// (`codex`, `openai`, `anthropic`, `gemini`, `claude-agent`, `antigravity`) at parse time.
68#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
69#[serde(transparent)]
70pub struct CustomBackendName(String);
71
72impl CustomBackendName {
73    pub fn as_str(&self) -> &str {
74        &self.0
75    }
76}
77
78impl std::str::FromStr for CustomBackendName {
79    type Err = String;
80
81    fn from_str(name: &str) -> Result<Self, Self::Err> {
82        if is_reserved_custom(name) {
83            return Err(format!(
84                "{name} is a built-in provider name and cannot be used as a custom HTTP backend."
85            ));
86        }
87        // These are provider identifiers, not filesystem basenames. Keep their existing
88        // spelling independent of display and path syntax.
89        const MAX_NAME_BYTES: usize = 64;
90        if name.is_empty()
91            || name.len() > MAX_NAME_BYTES
92            || !name.as_bytes()[0].is_ascii_alphanumeric()
93            || !name
94                .bytes()
95                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
96        {
97            return Err("custom backend must match [A-Za-z0-9][A-Za-z0-9_-]{0,63}.".into());
98        }
99        Ok(Self(name.to_owned()))
100    }
101}
102
103impl<'de> Deserialize<'de> for CustomBackendName {
104    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
105        String::deserialize(deserializer)?
106            .parse()
107            .map_err(serde::de::Error::custom)
108    }
109}
110
111impl std::borrow::Borrow<str> for CustomBackendName {
112    fn borrow(&self) -> &str {
113        self.as_str()
114    }
115}
116
117impl std::fmt::Display for CustomBackendName {
118    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        formatter.write_str(&self.0)
120    }
121}
122
123/// A built-in or machine-local custom HTTP backend.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(tag = "kind", rename_all = "camelCase")]
126pub enum DirectBackend {
127    Builtin {
128        provider: HttpProvider,
129    },
130    /// Resolved against the configured custom endpoints or aliases.
131    Custom {
132        name: CustomBackendName,
133    },
134}
135
136impl DirectBackend {
137    pub fn as_str(&self) -> &str {
138        match self {
139            Self::Builtin { provider } => provider.as_str(),
140            Self::Custom { name } => name.as_str(),
141        }
142    }
143}
144
145impl std::fmt::Display for DirectBackend {
146    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        formatter.write_str(self.as_str())
148    }
149}
150
151use std::{borrow::Borrow, fmt, ops::Deref, str::FromStr};
152
153macro_rules! identity {
154    ($name:ident, $valid:expr) => {
155        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
156        #[serde(transparent)]
157        pub struct $name(String);
158        impl FromStr for $name {
159            type Err = String;
160            fn from_str(value: &str) -> Result<Self, Self::Err> {
161                if ($valid)(value) {
162                    Ok(Self(value.to_owned()))
163                } else {
164                    Err(format!("Invalid {}: {value:?}", stringify!($name)))
165                }
166            }
167        }
168        impl<'de> Deserialize<'de> for $name {
169            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
170                use serde::de::Error;
171                String::deserialize(deserializer)?
172                    .parse()
173                    .map_err(D::Error::custom)
174            }
175        }
176        impl $name {
177            pub fn as_str(&self) -> &str {
178                &self.0
179            }
180        }
181        impl Deref for $name {
182            type Target = str;
183            fn deref(&self) -> &str {
184                &self.0
185            }
186        }
187        impl AsRef<str> for $name {
188            fn as_ref(&self) -> &str {
189                &self.0
190            }
191        }
192        impl Borrow<str> for $name {
193            fn borrow(&self) -> &str {
194                &self.0
195            }
196        }
197        impl Borrow<String> for $name {
198            fn borrow(&self) -> &String {
199                &self.0
200            }
201        }
202        impl fmt::Display for $name {
203            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204                self.0.fmt(f)
205            }
206        }
207        impl PartialEq<str> for $name {
208            fn eq(&self, other: &str) -> bool {
209                self.0 == other
210            }
211        }
212        impl PartialEq<&str> for $name {
213            fn eq(&self, other: &&str) -> bool {
214                self.0 == *other
215            }
216        }
217        impl PartialEq<String> for $name {
218            fn eq(&self, other: &String) -> bool {
219                &self.0 == other
220            }
221        }
222        impl PartialEq<$name> for String {
223            fn eq(&self, other: &$name) -> bool {
224                *self == other.0
225            }
226        }
227        impl PartialEq<$name> for str {
228            fn eq(&self, other: &$name) -> bool {
229                self == other.0
230            }
231        }
232        impl PartialEq<$name> for &str {
233            fn eq(&self, other: &$name) -> bool {
234                *self == other.0
235            }
236        }
237    };
238}
239identity!(ModelId, |value: &str| !value.trim().is_empty());
240
241// Bound routing and delivery bookkeeping for an opaque provider-generated identifier.
242pub(crate) const ITEM_ID_BYTES: usize = 1024;
243const OAUTH_STATE_HEX_BYTES: usize = 32;
244// The Codex OAuth sign-in's CSRF `state` correlation value (`auth::codex`): generated as
245// 128 bits of randomness, so always exactly 32 lowercase hex characters.
246identity!(OAuthState, |value: &str| value.len()
247    == OAUTH_STATE_HEX_BYTES
248    && value
249        .bytes()
250        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)));
251// A provider's own opaque identifier for one SSE reasoning-summary item, validated once
252// where it is decoded (`llm::delivery`) rather than carried as an unchecked String.
253identity!(ItemId, |value: &str| value.len() <= ITEM_ID_BYTES);
254identity!(CodexAccountId, |value: &str| !value.is_empty());