Skip to main content

agentmux_srv_core/backend/
providers_custom.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The runtime layer of the provider registry: custom harnesses registered by
5//! a manifest (`harness_manifest.rs`), asked after the built-ins.
6//!
7//! Every caller of the registry takes a `&'static ProviderConfig`, so a custom
8//! harness is turned into one by leaking its strings once. The leak is keyed by
9//! the manifest's content hash, so reading the same file again leaks nothing,
10//! and two caps bound what a machine can ever leak: live harnesses
11//! ([`MAX_LIVE`]) and distinct manifests seen since start ([`MAX_LEAKED`]).
12//! SPEC_BYO_HARNESS_CUSTOM_ACP_MANIFEST_2026_11_12.md §4.
13
14use 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
23/// Custom harnesses registered at once on one machine.
24pub const MAX_LIVE: usize = 32;
25/// Distinct manifests that may be turned into a config in one process: a
26/// manifest edited over and over cannot grow the leak without bound.
27pub const MAX_LEAKED: usize = 128;
28/// A harness folder larger than this is refused (it is a manifest and an icon).
29pub const MAX_FOLDER_BYTES: u64 = 1024 * 1024;
30/// An icon image larger than this is refused.
31pub const MAX_ICON_BYTES: u64 = 64 * 1024;
32/// The manifest's file name inside its folder.
33pub const MANIFEST_FILE: &str = "harness.json";
34
35/// Why a registration was refused.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum RegisterError {
38    /// A manifest rule is broken.
39    Manifest(ManifestError),
40    /// [`MAX_LIVE`] harnesses are registered already.
41    TooManyLive,
42    /// [`MAX_LEAKED`] distinct manifests were read since start.
43    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/// One folder's outcome when a directory of harnesses is read.
67#[derive(Debug, Default)]
68pub struct LoadReport {
69    /// Ids now registered from this directory.
70    pub loaded: Vec<String>,
71    /// Folders refused, with the reason.
72    pub refused: Vec<(String, String)>,
73}
74
75#[derive(Default)]
76struct Entry {
77    hash: String,
78    config: Option<&'static ProviderConfig>,
79}
80
81/// The harnesses registered and every config ever built, by content hash.
82pub 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    /// Register a manifest, replacing the harness of the same id. Returns the
95    /// config and whether the manifest's content changed (or is new).
96    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        // The same manifest whose command now resolves to another path (the program was installed since) is a new revision.
104        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    /// Take a harness out. The leaked config stays (it is never freed), but
123    /// nothing can look it up any more.
124    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    /// Every registered harness, by id.
133    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    /// The content hash a registered harness was built from.
140    pub fn hash_of(&self, id: &str) -> Option<&str> {
141        self.live.get(id).map(|e| e.hash.as_str())
142    }
143
144    /// Read every harness folder under `dir`, replacing what the layer holds
145    /// for those ids. A folder that is refused is reported and the rest load.
146    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
162/// A folder's manifest, after the folder rules: named as its id, under
163/// [`MAX_FOLDER_BYTES`], an icon file under [`MAX_ICON_BYTES`].
164fn 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
189/// SHA-256 of the manifest's canonical JSON (a map is ordered, so equal
190/// content hashes equal).
191pub 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
204/// The command a registered harness is launched with. A harness the person
205/// installed themselves (`install.kind` `path`) named by a bare command such
206/// as `demo-acp` is registered under the absolute path the command has on
207/// `path` now: the launch looks up a custom harness only in AgentMux's own
208/// install folders, so a bare name would never be found. A command that is
209/// not on `path` yet stays as written (it can be found once registration runs
210/// again), and every other install kind keeps the manifest's command.
211fn 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
223/// The built-in shape of an ACP harness, filled from the manifest. A custom
224/// harness gets the generic ACP defaults for everything the manifest omits.
225fn 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
263// ─── The process-wide layer ──────────────────────────────────────────────────
264
265static 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
272/// Read the machine's harness folder once, the first time a custom id is
273/// asked for. While the shared folder is not this srv's to use, nothing is
274/// read and the next ask tries again.
275fn 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
294/// A registered custom harness by id. Built-ins are asked first by the caller.
295pub 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
303/// Every registered custom harness, by id.
304pub fn all_custom_providers() -> Vec<&'static ProviderConfig> {
305    ensure_loaded();
306    layer().all()
307}
308
309/// Register a manifest in the process-wide layer.
310pub fn register_custom(manifest: &HarnessManifest) -> Result<&'static ProviderConfig, RegisterError> {
311    ensure_loaded();
312    layer().register(manifest).map(|(config, _)| config)
313}
314
315/// Take a custom harness out of the process-wide layer.
316pub fn remove_custom(id: &str) -> bool {
317    layer().remove(id)
318}
319
320#[cfg(test)]
321#[path = "providers_custom_tests.rs"]
322mod tests;