artifactize-provider 0.27.2

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Built-in API keys and machine-local HTTP endpoints and aliases.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use url::Url;

use super::storage::{Location, Storage};
use crate::{
    llm::EndpointApi,
    names::{CustomBackendName, HttpProvider},
    secret::{Inventory, history},
};

pub(crate) const FILE: &str = "providers.json";
/// Serialize read-modify-write updates across processes, as Codex refreshes are.
const LOCK: &str = "providers";
/// Bound a pasted key: provider keys are a few hundred bytes at most.
const MAX_KEY_BYTES: usize = 4096;

/// An API key. Debug always hides its value; serialization is for explicit credential use.
#[derive(Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct ApiKey(String);

/// A saved key passes the same checks as a typed one.
impl<'de> Deserialize<'de> for ApiKey {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

impl ApiKey {
    pub(crate) fn expose(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Debug for ApiKey {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("ApiKey(…)")
    }
}

impl std::str::FromStr for ApiKey {
    type Err = String;
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let key = value.trim();
        if (1..=MAX_KEY_BYTES).contains(&key.len())
            && key.bytes().all(|byte| byte.is_ascii_graphic())
        {
            Ok(Self(key.to_owned()))
        } else {
            Err("An API key is 1–4096 printable ASCII characters without spaces.".into())
        }
    }
}

/// A custom endpoint's API root: http(s), without credentials, a query or a fragment, which
/// belong in its key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndpointUrl(Option<Url>);

impl EndpointUrl {
    /// Empty in a public listing when presenting the URL would disclose a credential.
    pub fn as_str(&self) -> &str {
        self.0
            .as_ref()
            .map_or("", |url| url.as_str().trim_end_matches('/'))
    }

    pub(crate) fn into_url(self) -> Url {
        self.0.expect("only stored endpoint URLs may be routed")
    }

    fn visible(&self, inventory: &Inventory) -> Self {
        if inventory.contains(self.as_str()) {
            Self(None)
        } else {
            self.clone()
        }
    }
}

impl Serialize for EndpointUrl {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl std::str::FromStr for EndpointUrl {
    type Err = String;
    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let mut url = Url::parse(value.trim()).map_err(|_| "Enter a valid endpoint URL.")?;
        if !matches!(url.scheme(), "http" | "https") || url.host().is_none() {
            return Err("An endpoint URL uses http:// or https:// and names a host.".into());
        }
        if !url.username().is_empty()
            || url.password().is_some()
            || url.query().is_some()
            || url.fragment().is_some()
        {
            return Err(
                "An endpoint URL has no credentials, query or fragment; the key goes in its own field."
                    .into(),
            );
        }
        if url.path().len() > 1 && url.path().ends_with('/') {
            let path = url.path().trim_end_matches('/').to_owned();
            url.set_path(&path);
        }
        Ok(Self(Some(url)))
    }
}

impl<'de> Deserialize<'de> for EndpointUrl {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

/// What a custom provider reaches.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
pub enum Custom {
    /// A built-in provider under another name, with its sign-in or key.
    Alias { provider: HttpProvider },
    /// An API at a URL, with an optional key.
    Endpoint {
        api: EndpointApi,
        url: EndpointUrl,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        key: Option<ApiKey>,
    },
}

/// A custom provider as Settings and `provider list` show it: never its key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum CustomView {
    Alias {
        provider: HttpProvider,
    },
    Endpoint {
        api: EndpointApi,
        url: EndpointUrl,
        key: bool,
    },
}

impl From<&Custom> for CustomView {
    fn from(custom: &Custom) -> Self {
        let inventory = Inventory::new(match custom {
            Custom::Endpoint { key, .. } => key.as_ref().map(|key| key.expose().to_owned()),
            Custom::Alias { .. } => None,
        });
        Self::visible(custom, &inventory)
    }
}

impl CustomView {
    fn visible(custom: &Custom, inventory: &Inventory) -> Self {
        match custom {
            Custom::Alias { provider } => Self::Alias {
                provider: *provider,
            },
            Custom::Endpoint { api, url, key } => Self::Endpoint {
                api: *api,
                url: url.visible(inventory),
                key: key.is_some(),
            },
        }
    }
}

/// Where a built-in provider's key comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum KeySource {
    Environment,
    Saved,
    Absent,
}

#[derive(Debug, Clone, Copy)]
enum KeyAvailability {
    Absent,
    Saved,
    Environment { saved: bool },
}

/// A built-in API-key provider's key, as Settings and `doctor` show it.
#[derive(Debug, Clone)]
pub struct KeyStatus {
    provider: HttpProvider,
    variable: &'static str,
    availability: KeyAvailability,
}

impl KeyStatus {
    pub fn provider(&self) -> HttpProvider {
        self.provider
    }

    /// The environment variable read first.
    pub fn variable(&self) -> &'static str {
        self.variable
    }

    pub fn source(&self) -> KeySource {
        match self.availability {
            KeyAvailability::Absent => KeySource::Absent,
            KeyAvailability::Saved => KeySource::Saved,
            KeyAvailability::Environment { .. } => KeySource::Environment,
        }
    }

    /// Whether a key is saved here, also while the variable comes first.
    pub fn saved(&self) -> bool {
        match self.availability {
            KeyAvailability::Absent => false,
            KeyAvailability::Saved => true,
            KeyAvailability::Environment { saved } => saved,
        }
    }
}

impl Serialize for KeyStatus {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Wire {
            provider: HttpProvider,
            variable: &'static str,
            source: KeySource,
            saved: bool,
        }
        Wire {
            provider: self.provider(),
            variable: self.variable(),
            source: self.source(),
            saved: self.saved(),
        }
        .serialize(serializer)
    }
}

/// The providers this machine has set up.
#[derive(Debug, Clone, Serialize)]
pub struct Providers {
    #[serde(skip)]
    pub alias_targets: Vec<HttpProvider>,
    pub keys: Vec<KeyStatus>,
    pub custom: BTreeMap<CustomBackendName, CustomView>,
    /// Why nothing can be saved in this state, which holds nothing yet.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refused: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum KeyProvider {
    Openai,
    Anthropic,
    Gemini,
}

impl KeyProvider {
    fn of(provider: HttpProvider) -> Option<Self> {
        match provider {
            HttpProvider::Openai => Some(Self::Openai),
            HttpProvider::Anthropic => Some(Self::Anthropic),
            HttpProvider::Gemini => Some(Self::Gemini),
            HttpProvider::Codex => None,
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Saved {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    keys: BTreeMap<KeyProvider, ApiKey>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    custom: BTreeMap<CustomBackendName, Custom>,
}

impl Saved {
    fn secrets(&self) -> impl Iterator<Item = &str> {
        self.keys
            .values()
            .chain(self.custom.values().filter_map(|custom| match custom {
                Custom::Endpoint { key, .. } => key.as_ref(),
                Custom::Alias { .. } => None,
            }))
            .map(ApiKey::expose)
    }
}

/// The environment variable that holds an API-key provider's key; `None` for Codex and Claude
/// Code, which sign in instead.
pub fn key_variable(provider: HttpProvider) -> Option<&'static str> {
    match provider {
        HttpProvider::Openai => Some("OPENAI_API_KEY"),
        HttpProvider::Anthropic => Some("ANTHROPIC_API_KEY"),
        HttpProvider::Gemini => Some("GEMINI_API_KEY"),
        HttpProvider::Codex => None,
    }
}

/// The key in `provider`'s variable. A set variable is the key in use: an invalid value is
/// an error, never a reason to fall back to a saved key from another account.
fn environment_key(provider: HttpProvider) -> Option<Result<ApiKey, String>> {
    let variable = key_variable(provider)?;
    let value = crate::platform::var(variable)?;
    Some(
        crate::platform::as_text(&value)
            .map_err(str::to_owned)
            .and_then(str::parse)
            .map_err(|error| format!("{variable} is set but invalid: {error}")),
    )
}

enum Configuration {
    Saved(Saved),
    Refused(String),
}

impl Configuration {
    fn available(self) -> Saved {
        match self {
            Self::Saved(saved) => saved,
            Self::Refused(_) => Saved::default(),
        }
    }
}

/// Environment keys work in a refused state, but saved credentials do not.
fn read(location: &Location) -> Result<Configuration, String> {
    if let Some(refusal) = location.refusal(FILE)? {
        return Ok(Configuration::Refused(refusal));
    }
    let saved = Storage::inspect(location)?.read(FILE)?.unwrap_or_default();
    Ok(Configuration::Saved(saved))
}

/// What this profile has set up, without any key.
pub fn list(location: &Location) -> Result<Providers, String> {
    let mut inventory = Inventory::read(Some(location), Some(location));
    let configured = read(location).map_err(|error| inventory.scrub(&error))?;
    let (saved, refused) = match configured {
        Configuration::Saved(saved) => (saved, None),
        Configuration::Refused(refusal) => (Saved::default(), Some(refusal)),
    };
    inventory.merge(Inventory::new(saved.secrets().map(str::to_owned)));
    let available = HttpProvider::ALL
        .into_iter()
        .filter_map(|provider| {
            let variable = key_variable(provider)?;
            let key = KeyProvider::of(provider)?;
            Some((provider, variable, key, environment_key(provider).is_some()))
        })
        .collect::<Vec<_>>();
    Ok(Providers {
        alias_targets: HttpProvider::ALL.to_vec(),
        keys: available
            .into_iter()
            .map(|(provider, variable, key, in_environment)| {
                let stored = saved.keys.contains_key(&key);
                let availability = if in_environment {
                    KeyAvailability::Environment { saved: stored }
                } else if stored {
                    KeyAvailability::Saved
                } else {
                    KeyAvailability::Absent
                };
                KeyStatus {
                    provider,
                    variable,
                    availability,
                }
            })
            .collect(),
        custom: saved
            .custom
            .iter()
            .filter(|(name, _)| !inventory.contains(name.as_str()))
            .map(|(name, custom)| (name.clone(), CustomView::visible(custom, &inventory)))
            .collect(),
        refused: refused.map(|reason| inventory.scrub(&reason)),
    })
}

/// Explicitly request one built-in provider's API key by name. A sign-in provider has
/// no key here; this never exports sign-in tokens, another provider's key or an inventory.
pub fn key(
    provider: HttpProvider,
    location: Result<&Location, &str>,
) -> Result<Option<ApiKey>, String> {
    let Some(key_provider) = KeyProvider::of(provider) else {
        return Ok(None);
    };
    if let Some(key) = environment_key(provider) {
        return key.map(Some);
    }
    Ok(read(location?)?.available().keys.remove(&key_provider))
}

/// The custom provider `name`, if this machine has one.
pub(crate) fn custom(
    name: &CustomBackendName,
    location: &Location,
) -> Result<Option<Custom>, String> {
    Ok(read(location)?.available().custom.remove(name))
}

async fn update(
    location: &Location,
    change: impl FnOnce(&mut Saved) -> Result<(), String>,
) -> Result<(), String> {
    let storage = Storage::new(location)?;
    let _lock = storage.lock(LOCK).await?;
    let mut saved: Saved = storage.read(FILE)?.unwrap_or_default();
    let previous = saved.secrets().map(str::to_owned).collect::<Vec<_>>();
    change(&mut saved)?;
    history::publish(
        &storage,
        previous.iter().map(String::as_str).chain(saved.secrets()),
    )?;
    storage.save(FILE, &saved)
}

/// Save `key` for an API-key provider.
pub async fn save_key(
    location: &Location,
    provider: HttpProvider,
    key: ApiKey,
) -> Result<(), String> {
    let Some(key_provider) = KeyProvider::of(provider) else {
        return Err(format!(
            "{provider} signs in instead of using a key: artifactize login {provider}."
        ));
    };
    update(location, |saved| {
        saved.keys.insert(key_provider, key);
        Ok(())
    })
    .await
}

/// Forget the saved key of `provider`; its environment variable is untouched.
pub async fn remove_key(location: &Location, provider: HttpProvider) -> Result<(), String> {
    let Some(provider) = KeyProvider::of(provider) else {
        return Ok(());
    };
    update(location, |saved| {
        saved.keys.remove(&provider);
        Ok(())
    })
    .await
}

/// How a custom provider is saved: its key is replaced, kept from the provider it replaces,
/// or left out.
pub enum KeyChange {
    Set(ApiKey),
    Keep,
    None,
}

/// Add the custom provider `name`, or replace it.
pub async fn save_custom(
    location: &Location,
    name: CustomBackendName,
    mut custom: Custom,
    key: KeyChange,
) -> Result<(), String> {
    update(location, |saved| {
        if let Custom::Endpoint { url, key: slot, .. } = &mut custom {
            if url.0.is_none() {
                return Err("Enter a valid endpoint URL.".into());
            }
            *slot = match key {
                KeyChange::Set(key) => Some(key),
                KeyChange::Keep => match saved.custom.get(&name) {
                    Some(Custom::Endpoint { key, .. }) => key.clone(),
                    _ => None,
                },
                KeyChange::None => None,
            };
        }
        saved.custom.insert(name, custom);
        Ok(())
    })
    .await
}

/// Remove the custom provider `name`.
pub async fn remove_custom(location: &Location, name: &CustomBackendName) -> Result<(), String> {
    update(location, |saved| {
        saved
            .custom
            .remove(name)
            .map(drop)
            .ok_or_else(|| "No custom provider has that name.".into())
    })
    .await
}

#[cfg(test)]
mod tests;

/// Saved and configured API key values, including custom endpoints.
pub(crate) fn secret_values(
    location: Option<&Location>,
) -> Result<impl Iterator<Item = String>, String> {
    // Inventory is deliberately more tolerant than configuration loading: a malformed
    // provider entry or unknown field must not make intact secret fields unsafe to scrub.
    use crate::json::{Object, Optional};

    #[derive(Deserialize)]
    struct CredentialFields {
        #[serde(default)]
        keys: Optional<Object<BTreeMap<String, Optional<String>>>>,
        #[serde(default)]
        custom: Optional<Object<BTreeMap<String, Optional<Object<CustomField>>>>>,
    }
    #[derive(Deserialize)]
    struct CustomField {
        #[serde(default)]
        key: Optional<String>,
    }
    let stored = location
        .filter(|location| !location.is_refused())
        .map(|location| Storage::inspect(location)?.read::<Object<CredentialFields>>(FILE))
        .transpose()?
        .flatten()
        .into_iter()
        .flat_map(|Object(fields)| {
            let keys = fields
                .keys
                .0
                .into_iter()
                .flat_map(|Object(keys)| keys.into_values().filter_map(|value| value.0));
            let custom = fields.custom.0.into_iter().flat_map(|Object(custom)| {
                custom
                    .into_values()
                    .filter_map(|value| value.0.and_then(|Object(custom)| custom.key.0))
            });
            keys.chain(custom)
                .flat_map(|value| [value.trim().to_owned(), value])
        });
    let environment = HttpProvider::ALL
        .into_iter()
        .filter_map(key_variable)
        .filter_map(crate::platform::var_text)
        .flat_map(|value| [value.trim().to_owned(), value]);
    Ok(stored.chain(environment))
}