agent_provider_config/
management.rs1use 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#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
20pub struct ProviderSnapshot {
21 pub config: ProviderConfig,
22 pub revision: String,
23}
24
25pub type AdminFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, ModelError>> + Send + 'a>>;
28
29pub 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 fn list_models(&self, profile_id: String) -> AdminFuture<'_, Vec<ModelDescriptor>>;
45}
46
47pub fn snapshot() -> Result<ProviderSnapshot, ModelError> {
53 let config = ProviderConfig::load();
54 validate(&config)?;
55 revision(config)
56}
57
58pub 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
79pub const SETTERS: &[&str] = &[
83 "settings/agent-providers-person#set-*",
84 "devices/*/settings/agent-providers#set-*",
85];
86
87pub 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
109fn 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 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
136fn 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
154fn 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 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}