agentmux_srv_core/backend/
providers_custom.rs1use std::collections::HashMap;
15use std::path::Path;
16use std::sync::{LazyLock, Mutex};
17
18use sha2::{Digest, Sha256};
19
20use super::harness_manifest::{Auth, HarnessManifest, Install, ManifestError};
21use super::providers::{ControllerType, ProviderConfig, Tier};
22
23pub const MAX_LIVE: usize = 32;
25pub const MAX_LEAKED: usize = 128;
28pub const MAX_FOLDER_BYTES: u64 = 1024 * 1024;
30pub const MAX_ICON_BYTES: u64 = 64 * 1024;
32pub const MANIFEST_FILE: &str = "harness.json";
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum RegisterError {
38 Manifest(ManifestError),
40 TooManyLive,
42 TooManyRevisions,
44}
45
46impl std::fmt::Display for RegisterError {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 match self {
49 RegisterError::Manifest(e) => write!(f, "{e}"),
50 RegisterError::TooManyLive => write!(f, "at most {MAX_LIVE} custom harnesses; remove one first"),
51 RegisterError::TooManyRevisions => {
52 write!(f, "too many different manifests since AgentMux started; restart AgentMux, then register it")
53 }
54 }
55 }
56}
57
58impl std::error::Error for RegisterError {}
59
60impl From<ManifestError> for RegisterError {
61 fn from(e: ManifestError) -> Self {
62 RegisterError::Manifest(e)
63 }
64}
65
66#[derive(Debug, Default)]
68pub struct LoadReport {
69 pub loaded: Vec<String>,
71 pub refused: Vec<(String, String)>,
73}
74
75#[derive(Default)]
76struct Entry {
77 hash: String,
78 config: Option<&'static ProviderConfig>,
79}
80
81pub struct CustomLayer {
83 max_live: usize,
84 max_leaked: usize,
85 live: HashMap<String, Entry>,
86 leaked: HashMap<String, &'static ProviderConfig>,
87}
88
89impl CustomLayer {
90 pub fn new(max_live: usize, max_leaked: usize) -> Self {
91 CustomLayer { max_live, max_leaked, live: HashMap::new(), leaked: HashMap::new() }
92 }
93
94 pub fn register(&mut self, manifest: &HarnessManifest) -> Result<(&'static ProviderConfig, bool), RegisterError> {
97 manifest.validate()?;
98 let hash = manifest_hash(manifest);
99 let replacing = self.live.contains_key(&manifest.id);
100 if !replacing && self.live.len() >= self.max_live {
101 return Err(RegisterError::TooManyLive);
102 }
103 let command = launch_command(manifest, std::env::var_os("PATH").as_deref());
105 let revision = format!("{hash}\n{command}");
106 let config = match self.leaked.get(&revision) {
107 Some(config) => *config,
108 None => {
109 if self.leaked.len() >= self.max_leaked {
110 return Err(RegisterError::TooManyRevisions);
111 }
112 let config = leak_config(manifest, &command);
113 self.leaked.insert(revision, config);
114 config
115 }
116 };
117 let changed = self.live.get(&manifest.id).is_none_or(|e| e.hash != hash);
118 self.live.insert(manifest.id.clone(), Entry { hash, config: Some(config) });
119 Ok((config, changed))
120 }
121
122 pub fn remove(&mut self, id: &str) -> bool {
125 self.live.remove(id).is_some()
126 }
127
128 pub fn get(&self, id: &str) -> Option<&'static ProviderConfig> {
129 self.live.get(id).and_then(|e| e.config)
130 }
131
132 pub fn all(&self) -> Vec<&'static ProviderConfig> {
134 let mut all: Vec<_> = self.live.values().filter_map(|e| e.config).collect();
135 all.sort_by_key(|c| c.id);
136 all
137 }
138
139 pub fn hash_of(&self, id: &str) -> Option<&str> {
141 self.live.get(id).map(|e| e.hash.as_str())
142 }
143
144 pub fn load_dir(&mut self, dir: &Path) -> LoadReport {
147 let mut report = LoadReport::default();
148 let Ok(entries) = std::fs::read_dir(dir) else { return report };
149 let mut folders: Vec<_> = entries.flatten().filter(|e| e.path().is_dir()).collect();
150 folders.sort_by_key(|e| e.file_name());
151 for folder in folders {
152 let name = folder.file_name().to_string_lossy().into_owned();
153 match read_folder(&folder.path(), &name).and_then(|m| self.register(&m).map_err(|e| e.to_string())) {
154 Ok((config, _)) => report.loaded.push(config.id.to_string()),
155 Err(reason) => report.refused.push((name, reason)),
156 }
157 }
158 report
159 }
160}
161
162fn read_folder(path: &Path, folder_name: &str) -> Result<HarnessManifest, String> {
165 let mut total = 0u64;
166 for entry in std::fs::read_dir(path).map_err(|e| format!("cannot read the folder: {e}"))?.flatten() {
167 let meta = entry.metadata().map_err(|e| format!("cannot read the folder: {e}"))?;
168 if meta.is_file() {
169 total += meta.len();
170 }
171 }
172 if total > MAX_FOLDER_BYTES {
173 return Err(format!("the folder is larger than {MAX_FOLDER_BYTES} bytes"));
174 }
175 let text = std::fs::read_to_string(path.join(MANIFEST_FILE)).map_err(|e| format!("cannot read {MANIFEST_FILE}: {e}"))?;
176 let manifest = HarnessManifest::parse(&text).map_err(|e| e.to_string())?;
177 if manifest.id != folder_name {
178 return Err(format!("the folder is named {folder_name} but the id is {}", manifest.id));
179 }
180 if let Some(icon) = manifest.icon.as_deref().filter(|i| i.contains('.')) {
181 let size = std::fs::metadata(path.join(icon)).map_err(|e| format!("icon: cannot read {icon}: {e}"))?.len();
182 if size > MAX_ICON_BYTES {
183 return Err(format!("icon: {icon} is larger than {MAX_ICON_BYTES} bytes"));
184 }
185 }
186 Ok(manifest)
187}
188
189pub fn manifest_hash(manifest: &HarnessManifest) -> String {
192 let canonical = serde_json::to_string(manifest).unwrap_or_default();
193 hex::encode(Sha256::digest(canonical.as_bytes()))
194}
195
196fn leak_str(s: &str) -> &'static str {
197 Box::leak(s.to_string().into_boxed_str())
198}
199
200fn leak_strs(items: &[String]) -> &'static [&'static str] {
201 Box::leak(items.iter().map(|s| leak_str(s)).collect::<Vec<_>>().into_boxed_slice())
202}
203
204fn launch_command(m: &HarnessManifest, path: Option<&std::ffi::OsStr>) -> String {
212 let bare = !m.command.contains(['/', '\\']);
213 if !matches!(m.install, Install::Path) || !bare {
214 return m.command.clone();
215 }
216 let found = path.and_then(|p| which::which_in(&m.command, Some(p), std::env::current_dir().ok()?).ok());
217 match found {
218 Some(abs) if abs.is_absolute() => abs.to_string_lossy().into_owned(),
219 _ => m.command.clone(),
220 }
221}
222
223fn leak_config(m: &HarnessManifest, command: &str) -> &'static ProviderConfig {
226 let (npm_package, pinned_version) = match &m.install {
227 Install::Npm { package, version } => (leak_str(package), leak_str(version)),
228 _ => ("", ""),
229 };
230 let auth_config_dir_env_var = match &m.auth {
231 Auth::ConfigDir { env_var } => leak_str(env_var),
232 _ => "",
233 };
234 let extra_env: Vec<(&'static str, &'static str)> = m.env.iter().map(|(k, v)| (leak_str(k), leak_str(v))).collect();
235 let startup = m.startup_instructions.as_deref().map(leak_str);
236 let sources: Vec<&'static str> = startup.into_iter().collect();
237 Box::leak(Box::new(ProviderConfig {
238 id: leak_str(&m.id),
239 tier: Tier::Custom,
240 cli_command: leak_str(command),
241 controller_type: ControllerType::Acp,
242 app_server: None,
243 launch_args: leak_strs(&m.args),
244 persistent_launch_args: None,
245 resume_flag: None,
246 session_id_field: "sessionId",
247 styled_output_format: "acp",
248 auth_config_dir_env_var,
249 auth_dir_name: leak_str(&m.id),
250 history_native_subdir: None,
251 auth_extra_env: Box::leak(extra_env.into_boxed_slice()),
252 unset_env: &[],
253 npm_package,
254 pinned_version,
255 base_url_env_var: m.base_url_env_var.as_deref().map(leak_str),
256 supported_vendors: leak_strs(&m.vendors),
257 startup_instructions_filename: startup,
258 native_instruction_sources: Box::leak(sources.into_boxed_slice()),
259 native_instruction_dirs: &[],
260 }))
261}
262
263static LAYER: LazyLock<Mutex<CustomLayer>> = LazyLock::new(|| Mutex::new(CustomLayer::new(MAX_LIVE, MAX_LEAKED)));
266static LOADED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
267
268fn layer() -> std::sync::MutexGuard<'static, CustomLayer> {
269 LAYER.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
270}
271
272fn ensure_loaded() {
276 use std::sync::atomic::Ordering;
277 if LOADED.load(Ordering::Acquire) {
278 return;
279 }
280 let Some(dir) = crate::registry::shared_guard::shared_dir().map(|d| d.join("harnesses")) else { return };
281 let mut layer = layer();
282 if LOADED.swap(true, Ordering::AcqRel) {
283 return;
284 }
285 let report = layer.load_dir(&dir);
286 for (folder, reason) in &report.refused {
287 tracing::warn!(folder = %folder, "custom harness refused: {reason}");
288 }
289 if !report.loaded.is_empty() {
290 tracing::info!(count = report.loaded.len(), "custom harnesses loaded");
291 }
292}
293
294pub fn get_custom_provider(id: &str) -> Option<&'static ProviderConfig> {
296 if !id.starts_with(super::harness_manifest::ID_PREFIX) {
297 return None;
298 }
299 ensure_loaded();
300 layer().get(id)
301}
302
303pub fn all_custom_providers() -> Vec<&'static ProviderConfig> {
305 ensure_loaded();
306 layer().all()
307}
308
309pub fn register_custom(manifest: &HarnessManifest) -> Result<&'static ProviderConfig, RegisterError> {
311 ensure_loaded();
312 layer().register(manifest).map(|(config, _)| config)
313}
314
315pub fn remove_custom(id: &str) -> bool {
317 layer().remove(id)
318}
319
320#[cfg(test)]
321#[path = "providers_custom_tests.rs"]
322mod tests;