Skip to main content

agent_provider_config/
management.rs

1//! Host-authorized provider administration, separate from inference authority.
2//! No provider key passes here: keys are kept where the person's workspace
3//! is, and set there (`tilo.models`). The descriptions are settings of the
4//! person and the device: [`snapshot`] reads them from this process's
5//! settings and [`replace`] sets them there, as the settings app's own
6//! setters do.
7
8use std::{future::Future, pin::Pin};
9
10use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value};
12
13use crate::{
14    ModelDescriptor, ProviderConfig,
15    protocol::{ErrorKind, ModelError},
16};
17
18/// Authoritative backend settings and their compare-and-swap revision.
19#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
20pub struct ProviderSnapshot {
21    pub config: ProviderConfig,
22    pub revision: String,
23}
24
25/// Administration returns data rather than borrowing UI callbacks. Browser
26/// transports preserve this contract using the platform's Send-safe fetch API.
27pub type AdminFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, ModelError>> + Send + 'a>>;
28
29/// An explicitly granted capability, not part of an ordinary model session.
30/// Hosts bind the authenticated user before providing this interface. Every
31/// operation remains subject to backend authorization and durable-write checks.
32/// Dropping a mutation abandons its response, not its durable commit. Refresh
33/// configuration/status before deciding whether an interrupted write needs retry.
34pub trait ProviderAdmin: Send + Sync {
35    fn get_config(&self) -> AdminFuture<'_, ProviderSnapshot>;
36    fn set_config(
37        &self,
38        expected_revision: String,
39        config: ProviderConfig,
40    ) -> AdminFuture<'_, ProviderSnapshot>;
41    /// The models the provider lists, asked as its sign-in or, for a local
42    /// server, as itself: also the proof that the endpoint answers.
43    /// [`crate::protocol::ErrorKind::Unsupported`] when it lists none.
44    fn list_models(&self, profile_id: String) -> AdminFuture<'_, Vec<ModelDescriptor>>;
45}
46
47/// The descriptions this process's settings hold, with their revision: what an edit is checked
48/// against.
49///
50/// # Errors
51/// The stored descriptions are out of bounds.
52pub fn snapshot() -> Result<ProviderSnapshot, ModelError> {
53    let config = ProviderConfig::load();
54    validate(&config)?;
55    revision(config)
56}
57
58/// Set the descriptions to `config` if they are still those at `expected_revision`.
59///
60/// # Errors
61/// [`ErrorKind::Conflict`] when they changed since, [`ErrorKind::PermissionDenied`] when the edit
62/// would mint or retarget a model the provisioner installed, [`ErrorKind::InvalidRequest`] when
63/// `config` is out of bounds, [`ErrorKind::Unavailable`] when the settings refused the write.
64pub fn replace(
65    expected_revision: &str,
66    config: ProviderConfig,
67) -> Result<ProviderSnapshot, ModelError> {
68    let previous = ProviderConfig::load();
69    if revision(previous.clone())?.revision != expected_revision {
70        return Err(ModelError::new(ErrorKind::Conflict));
71    }
72    admitted(&previous, &config)?;
73    config
74        .save()
75        .map_err(|_| ModelError::new(ErrorKind::Unavailable))?;
76    revision(config)
77}
78
79/// The setters an app that administers the model providers besides Settings (Model Providers)
80/// may invoke: those of the person's hosted providers and of each device's own, as grant
81/// patterns over their addresses. Each write of theirs is held to [`check_write`].
82pub const SETTERS: &[&str] = &[
83    "settings/agent-providers-person#set-*",
84    "devices/*/settings/agent-providers#set-*",
85];
86
87/// Whether writing `values` to `section` of the settings `document` keeps the providers within
88/// bounds and the provisioner's metadata its own; any other section passes.
89///
90/// # Errors
91/// What the write would break.
92pub fn check_write(
93    document: &Map<String, Value>,
94    section: &str,
95    values: &Map<String, Value>,
96) -> Result<(), String> {
97    if section != crate::SETTINGS_SECTION && section != crate::HOSTED_SECTION {
98        return Ok(());
99    }
100    let mut written = document.clone();
101    settings_store::merge_section(&mut written, section, values.clone());
102    admitted(
103        &ProviderConfig::from_document(document),
104        &ProviderConfig::from_document(&written),
105    )
106    .map_err(|error| format!("the model providers refuse the change: {error}"))
107}
108
109/// Whether the providers may go from `previous` to `config`.
110fn admitted(previous: &ProviderConfig, config: &ProviderConfig) -> Result<(), ModelError> {
111    validate(config)?;
112    for profile in &config.profiles {
113        let old = previous.profiles.iter().find(|old| old.id == profile.id);
114        let same_endpoint = old.is_some_and(|old| {
115            old.endpoint == profile.endpoint
116                && old.protocol == profile.protocol
117                && old.location == profile.location
118        });
119        // Signed installation metadata is the provisioner's: an edit never mints a pinned
120        // model, retargets one, or changes the models of a profile that holds one.
121        let minted = profile.models.iter().any(|model| {
122            model.revision.is_some()
123                && !(same_endpoint && old.is_some_and(|old| old.models.contains(model)))
124        });
125        let retargeted = old.is_some_and(|old| {
126            old.models.iter().any(|model| model.revision.is_some())
127                && (!same_endpoint || old.models != profile.models)
128        });
129        if minted || retargeted {
130            return Err(ModelError::new(ErrorKind::PermissionDenied));
131        }
132    }
133    Ok(())
134}
135
136/// `config` with the revision an edit names it by: a digest of what it says.
137fn revision(config: ProviderConfig) -> Result<ProviderSnapshot, ModelError> {
138    use sha2::Digest as _;
139    let bytes =
140        serde_json::to_vec(&config).map_err(|_| ModelError::new(ErrorKind::InvalidRequest))?;
141    if bytes.len() > 256 * 1024 {
142        return Err(ModelError::new(ErrorKind::InvalidRequest));
143    }
144    Ok(ProviderSnapshot {
145        config,
146        revision: hex::encode(sha2::Sha256::digest(bytes)),
147    })
148}
149
150fn bounded(value: &str, limit: usize) -> bool {
151    value.len() <= limit && !value.chars().any(char::is_control)
152}
153
154/// Whether `config` stays within what a description may say: sizes, and no credential in an
155/// endpoint.
156fn validate(config: &ProviderConfig) -> Result<(), ModelError> {
157    let invalid = || ModelError::new(ErrorKind::InvalidRequest);
158    let bytes = serde_json::to_vec(config).map_err(|_| invalid())?;
159    if bytes.len() > 256 * 1024
160        || config.profiles.len() > 64
161        || !config.validation_errors().is_empty()
162        || config.agent_models.len() > 256
163        || config.agent_models.keys().any(|agent| !bounded(agent, 256))
164    {
165        return Err(invalid());
166    }
167    for profile in &config.profiles {
168        if !bounded(&profile.id, 128)
169            || !bounded(&profile.label, 256)
170            || !bounded(&profile.endpoint, 2048)
171            || profile.models.len() > 256
172            || profile
173                .models
174                .iter()
175                .any(|model| !bounded(&model.id, 256) || !bounded(&model.label, 256))
176        {
177            return Err(invalid());
178        }
179        // Endpoint userinfo, queries and fragments can contain credentials.
180        let url = url::Url::parse(&profile.endpoint).map_err(|_| invalid())?;
181        if !url.username().is_empty()
182            || url.password().is_some()
183            || url.query().is_some()
184            || url.fragment().is_some()
185        {
186            return Err(invalid());
187        }
188    }
189    Ok(())
190}