diff --git a/Cargo.lock b/Cargo.lock index 2cece646a9..13cc7a5662 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4273,6 +4273,7 @@ dependencies = [ "anyhow", "dirs", "flate2", + "fs2", "futures-util", "hex", "mesh-llm-skills", diff --git a/mesh/crates/mesh-llm-cli/src/parser/commands.rs b/mesh/crates/mesh-llm-cli/src/parser/commands.rs index bd9438853e..28dca4f049 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/commands.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/commands.rs @@ -911,14 +911,18 @@ pub enum ConfigCommand { #[derive(Subcommand, Debug)] pub enum PluginCommand { - /// Install the default plugins from this release's bundled copy (no download). - /// A node also does this when it starts. - /// Install native plugins in order, or install one local release archive. + /// Install native plugins in order, install one local release archive, or + /// install a catalog plugin set. Install { /// Plugin catalog names, GitHub owner/repo references, or GitHub URLs. /// Stops on the first failure; earlier installs are kept. - #[arg(num_args = 1.., required_unless_present = "archive", conflicts_with_all = ["archive", "name", "version"])] + #[arg(num_args = 1.., required_unless_present_any = ["archive", "set"], conflicts_with_all = ["archive", "name", "version", "set"])] reference: Vec, + /// Install the members of a catalog plugin set, such as `recommended`, that + /// are not installed yet, including one you removed earlier. Members already + /// installed are left as they are. + #[arg(long, value_name = "NAME", conflicts_with_all = ["archive", "name", "version"])] + set: Option, /// Install a local .tar.gz or .zip release archive. Requires --name. #[arg(long, value_name = "PATH", requires = "name")] archive: Option, diff --git a/mesh/crates/mesh-llm-cli/src/parser/plugin_install_tests.rs b/mesh/crates/mesh-llm-cli/src/parser/plugin_install_tests.rs index 7572f520ea..c7787ec4f8 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/plugin_install_tests.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/plugin_install_tests.rs @@ -19,6 +19,7 @@ fn plugins_install_accepts_local_archive_options() { command: PluginCommand::Install { reference, + set: None, archive: Some(archive), name: Some(name), version: Some(version), @@ -66,6 +67,7 @@ fn accepts_one_or_multiple_references_in_order() { command: PluginCommand::Install { reference, + set: None, archive: None, name: None, version: None, @@ -98,3 +100,37 @@ fn rejects_missing_references_and_invalid_archive_options() { assert!(Cli::try_parse_from(&args).is_err(), "accepted {args:?}"); } } + +#[test] +fn plugins_install_accepts_a_catalog_set_alone() { + let cli = Cli::try_parse_from(["mesh-llm", "plugins", "install", "--set", "recommended"]) + .expect("--set parses by itself"); + match cli.command.expect("plugins command") { + Command::Plugin { + command: + PluginCommand::Install { + reference, + set: Some(set), + archive: None, + .. + }, + } => { + assert!(reference.is_empty()); + assert_eq!(set, "recommended"); + } + other => panic!("unexpected command: {other:?}"), + } +} + +#[test] +fn plugins_install_rejects_a_set_with_references_or_an_archive() { + for extra in [ + vec!["notes"], + vec!["--archive", "/tmp/demo.tar.gz", "--name", "demo"], + ] { + let mut args = vec!["mesh-llm", "plugins", "install", "--set", "recommended"]; + args.extend(extra); + let error = Cli::try_parse_from(args).expect_err("--set conflicts"); + assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict); + } +} diff --git a/mesh/crates/mesh-llm-cli/src/parser/setup_tests.rs b/mesh/crates/mesh-llm-cli/src/parser/setup_tests.rs index e7e8f95906..7c9c543b10 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/setup_tests.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/setup_tests.rs @@ -9,6 +9,7 @@ fn setup_command_parses_without_plugin_fallback() { "--yes", "--no-interactive", "--skip-runtime", + "--skip-plugin-install", "--verbose", ]); @@ -19,6 +20,7 @@ fn setup_command_parses_without_plugin_fallback() { service, no_service, skip_runtime, + skip_plugin_install, verbose, }) => { assert!(yes); @@ -26,6 +28,7 @@ fn setup_command_parses_without_plugin_fallback() { assert!(!service); assert!(!no_service); assert!(skip_runtime); + assert!(skip_plugin_install); assert!(verbose); } other => panic!("unexpected command: {other:?}"), @@ -50,3 +53,16 @@ fn setup_command_rejects_skip_doctor_flag() { assert_eq!(err.kind(), ErrorKind::UnknownArgument); assert!(err.to_string().contains("--skip-doctor")); } + +#[test] +fn setup_installs_plugins_by_default_and_skip_plugin_install_opts_out() { + for (flag, expected) in [(None, false), (Some("--skip-plugin-install"), true)] { + let mut args = vec!["mesh-llm", "setup"]; + args.extend(flag); + let cli = Cli::parse_from(args); + let Some(Command::Setup(setup)) = cli.command else { + panic!("setup command expected"); + }; + assert_eq!(setup.skip_plugin_install, expected); + } +} diff --git a/mesh/crates/mesh-llm-cli/src/parser/subcommand_options.rs b/mesh/crates/mesh-llm-cli/src/parser/subcommand_options.rs index 59b49d0afd..5c55528299 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/subcommand_options.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/subcommand_options.rs @@ -125,6 +125,9 @@ pub struct SetupArgs { /// Skip downloading or configuring the native runtime. #[arg(long = "skip-runtime")] pub skip_runtime: bool, + /// Do not install the catalog's `recommended` plugin set. + #[arg(long = "skip-plugin-install")] + pub skip_plugin_install: bool, /// Print detailed setup paths, commands, and follow-up guidance. #[arg(long)] pub verbose: bool, diff --git a/mesh/crates/mesh-llm-commands/src/capsules_witness.rs b/mesh/crates/mesh-llm-commands/src/capsules_witness.rs new file mode 100644 index 0000000000..a3690c64e7 --- /dev/null +++ b/mesh/crates/mesh-llm-commands/src/capsules_witness.rs @@ -0,0 +1,147 @@ +//! Keeps checkpoint delivery off for a capsules install made through a plugin +//! set. +//! +//! Capsules v0.1.25 and earlier send signed checkpoints to Action State's +//! hosted witness when the `witness` setting is unset; v0.1.26 and later +//! default to off. A plugin set installs capsules without the operator +//! choosing it (`mesh-llm setup` installs the `recommended` set with no +//! prompt), so a set install writes `witness = "off"` into the plugin's +//! settings whichever release the catalog pins, and an operator who wants a +//! witness sets it. Agreed on Mesh-LLM/mesh-llm#3219. + +use std::io::Write; + +use anyhow::{Context, Result}; +use mesh_llm_config::ConfigStore; +use toml_edit::{ArrayOfTables, DocumentMut, Item, Table, value}; + +const CAPSULES: &str = "capsules"; +const WITNESS_SETTING: &str = "witness"; + +/// For each newly installed set member that is capsules, keep its checkpoints +/// local. Never fails the install: a config that cannot be written is +/// reported with how to set it by hand. +pub fn keep_installed_capsules_local(installed: &[String]) { + if !installed.iter().any(|name| name == CAPSULES) { + return; + } + let mut err = mesh_llm_events::console_err(); + let outcome = ConfigStore::default_path().and_then(|store| keep_witness_off(&store)); + let _ = match outcome { + Ok(true) => writeln!( + err, + "Capsules keeps its checkpoints on this node: its witness is set to off. To send them to a witness, set `witness` in the capsules plugin settings (Configuration tab or `[plugin.settings]` in config.toml)." + ), + Ok(false) => Ok(()), + Err(error) => writeln!( + err, + "⚠️ Could not set the capsules witness to off ({error:#}). Until `witness = \"off\"` is set under `[plugin.settings]` for `capsules`, a capsules release before v0.1.26 sends signed checkpoints to Action State's hosted witness." + ), + }; +} + +/// Set `[[plugin]] name = "capsules"` `settings.witness = "off"` unless the +/// operator already set a witness. True when the file changed. +fn keep_witness_off(store: &ConfigStore) -> Result { + let mut changed = false; + store + .edit_preserving(|doc| { + changed = set_witness_off(doc)?; + Ok(()) + }) + .with_context(|| format!("update {}", store.path().display()))?; + Ok(changed) +} + +fn set_witness_off(doc: &mut DocumentMut) -> Result { + if doc.get("plugin").is_none() { + doc["plugin"] = Item::ArrayOfTables(ArrayOfTables::new()); + } + let plugins = doc["plugin"] + .as_array_of_tables_mut() + .context("`plugin` in the config is not a list of [[plugin]] tables")?; + let index = plugins + .iter() + .position(|plugin| plugin.get("name").and_then(Item::as_str) == Some(CAPSULES)); + let plugin = match index { + Some(index) => plugins.get_mut(index).context("capsules plugin entry")?, + None => { + let mut entry = Table::new(); + entry["name"] = value(CAPSULES); + plugins.push(entry); + let last = plugins.len() - 1; + plugins.get_mut(last).context("capsules plugin entry")? + } + }; + if plugin.get("settings").is_none() { + plugin["settings"] = Item::Table(Table::new()); + } + let settings = plugin["settings"] + .as_table_like_mut() + .context("capsules `settings` in the config is not a table")?; + if settings.contains_key(WITNESS_SETTING) { + return Ok(false); + } + settings.insert(WITNESS_SETTING, value("off")); + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(initial: Option<&str>) -> (bool, String) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + if let Some(initial) = initial { + std::fs::write(&path, initial).unwrap(); + } + let store = ConfigStore::open(&path); + let changed = keep_witness_off(&store).unwrap(); + (changed, std::fs::read_to_string(&path).unwrap()) + } + + #[test] + fn a_missing_config_gets_a_capsules_entry_with_the_witness_off() { + let (changed, text) = run(None); + assert!(changed); + let config = mesh_llm_config::parse_config_toml(&text).unwrap(); + assert_eq!(config.plugins.len(), 1); + assert_eq!(config.plugins[0].name, "capsules"); + assert_eq!(config.plugins[0].settings["witness"].as_str(), Some("off")); + } + + #[test] + fn an_operator_chosen_witness_is_left_alone() { + let initial = "[[plugin]]\nname = \"capsules\"\n\n[plugin.settings]\nwitness = \"https://witness.example.org\"\n"; + let (changed, text) = run(Some(initial)); + assert!(!changed); + assert_eq!(text, initial); + } + + #[test] + fn other_settings_and_comments_survive_and_other_plugins_are_untouched() { + let initial = "# my node\n[[plugin]]\nname = \"other\"\n\n[[plugin]]\nname = \"capsules\"\nenabled = true\n\n[plugin.settings]\nshare_record_at_completion = \"off\"\n"; + let (changed, text) = run(Some(initial)); + assert!(changed); + assert!(text.starts_with("# my node\n"), "{text}"); + let config = mesh_llm_config::parse_config_toml(&text).unwrap(); + assert_eq!(config.plugins.len(), 2); + let capsules = &config.plugins[1]; + assert_eq!(capsules.enabled, Some(true)); + assert_eq!(capsules.settings["witness"].as_str(), Some("off")); + assert_eq!( + capsules.settings["share_record_at_completion"].as_str(), + Some("off") + ); + assert!(config.plugins[0].settings.is_empty()); + } + + #[test] + fn a_second_run_changes_nothing() { + let (_, once) = run(None); + let (changed, twice) = run(Some(&once)); + assert!(!changed); + assert_eq!(once, twice); + } +} diff --git a/mesh/crates/mesh-llm-commands/src/lib.rs b/mesh/crates/mesh-llm-commands/src/lib.rs index 580aff6d6b..9217e6b27a 100644 --- a/mesh/crates/mesh-llm-commands/src/lib.rs +++ b/mesh/crates/mesh-llm-commands/src/lib.rs @@ -4,6 +4,7 @@ pub mod agent_cli; pub mod analytics; pub mod auth; pub mod benchmark; +mod capsules_witness; pub mod config; pub mod doctor; pub mod gpus; @@ -13,6 +14,7 @@ pub mod model_package; pub mod operational_logging; pub mod owner_control; pub mod plugin; +pub mod plugin_sets; pub mod private_nodes; pub mod runtime_native; pub mod setup; diff --git a/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/administration.rs b/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/administration.rs index 628d6aaea4..c61ed89941 100644 --- a/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/administration.rs +++ b/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/administration.rs @@ -112,12 +112,14 @@ pub(super) fn format_plugin(command: &mesh_llm_cli::PluginCommand, assembly: &mu match command { PluginCommand::Install { reference, + set, archive, name, version, } => { assembly.command.push_str(" plugins install"); assembly.redact("reference", !reference.is_empty()); + assembly.redact("--set", set.is_some()); assembly.redact("--archive", archive.is_some()); assembly.redact("--name", name.is_some()); assembly.redact("--version", version.is_some()); diff --git a/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/dispatch.rs b/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/dispatch.rs index ef1fa705a9..05b684023b 100644 --- a/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/dispatch.rs +++ b/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary/dispatch.rs @@ -62,6 +62,7 @@ pub(super) fn format_command(command: &Command, assembly: &mut SummaryAssembly) service, no_service, skip_runtime, + skip_plugin_install, verbose, }) => { assembly.command.push_str(" setup"); @@ -70,6 +71,7 @@ pub(super) fn format_command(command: &Command, assembly: &mut SummaryAssembly) assembly.flag("service", *service); assembly.flag("no-service", *no_service); assembly.flag("skip-runtime", *skip_runtime); + assembly.flag("skip-plugin-install", *skip_plugin_install); assembly.flag("verbose", *verbose); } Command::Uninstall(UninstallArgs { diff --git a/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary_tests.rs b/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary_tests.rs index 2b33eb2909..2e63b4e98e 100644 --- a/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/operational_logging/command_summary_tests.rs @@ -88,6 +88,36 @@ fn uninstall_boolean_flags_survive_producer_sanitization() { } } +#[test] +fn plugin_set_install_and_setup_plugin_opt_out_survive_producer_sanitization() { + let summaries = [ + parsed_summary(&["mesh-llm", "plugins", "install", "--set", "private-set"]), + parsed_summary(&[ + "mesh-llm", + "setup", + "--skip-runtime", + "--skip-plugin-install", + ]), + ]; + assert_eq!(summaries[0], "mesh-llm plugins install --set [REDACTED]"); + assert_eq!( + summaries[1], + "mesh-llm setup --skip-runtime --skip-plugin-install" + ); + for summary in summaries { + let sanitized = CliCommandSummary::sanitize(&summary) + .unwrap_or_else(|| panic!("producer omitted valid summary: {summary}")); + assert_eq!(sanitized.as_str(), summary); + } + // A set install names no reference or archive. + for invalid in [ + "mesh-llm plugins install reference [REDACTED] --set [REDACTED]", + "mesh-llm plugins install --set [REDACTED] --archive [REDACTED] --name [REDACTED]", + ] { + assert!(CliCommandSummary::sanitize(invalid).is_none(), "{invalid}"); + } +} + #[test] fn command_summary_retains_static_prefix_nested_names_and_redacts_plugin_values() { let summary = parsed_summary(&[ diff --git a/mesh/crates/mesh-llm-commands/src/plugin.rs b/mesh/crates/mesh-llm-commands/src/plugin.rs index 9f136661ce..c4786334b4 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin.rs @@ -162,8 +162,10 @@ pub async fn run_plugin_command( runtime_rows: Option<&PluginListRows>, ) -> Result { match command { + PluginCommand::Install { set: Some(set), .. } => install_set_by_name(set).await?, PluginCommand::Install { reference, + set: None, archive, name, version, @@ -250,6 +252,47 @@ async fn install( Ok(()) } +/// `plugins install --set NAME`: install the set's missing members from one +/// catalog snapshot, then fail if any member failed. +async fn install_set_by_name(set: &str) -> Result<()> { + let options = PluginInstallOptions::from_env()?; + let mut progress = CliPluginProgress::default(); + let result = crate::plugin_sets::install_set_command(set, &options, &mut progress).await; + progress.finish(); + let result = result?; + crate::capsules_witness::keep_installed_capsules_local( + &result + .installed + .iter() + .map(|outcome| outcome.metadata.name.clone()) + .collect::>(), + ); + let mut err = mesh_llm_events::console_err(); + for outcome in &result.installed { + writeln!( + err, + "✅ Installed {} {}", + outcome.metadata.name, outcome.metadata.installed_version + )?; + } + for name in &result.already_installed { + writeln!(err, "Already installed {name}")?; + } + for (name, reason) in &result.unavailable { + writeln!(err, "Unavailable on this platform: {name}: {reason}")?; + } + if result.failed.is_empty() { + return Ok(()); + } + for (name, reason) in &result.failed { + writeln!(err, "Failed {name}: {reason}")?; + } + bail!( + "{} of the plugins in set '{set}' failed to install; rerun the same `mesh-llm plugins install --set` command to retry the rest", + result.failed.len() + ) +} + async fn update(name: &str) -> Result<()> { let options = PluginInstallOptions::from_env()?; let mut progress = CliPluginProgress::default(); @@ -518,14 +561,14 @@ fn list(runtime_rows: &PluginListRows) -> Result<()> { } #[derive(Default)] -struct CliPluginProgress { +pub(crate) struct CliPluginProgress { spinner: Option, active_download: Option, last_percent: Option, } impl CliPluginProgress { - fn finish(&mut self) { + pub(crate) fn finish(&mut self) { if let Some(mut spinner) = self.spinner.take() { spinner.finish(); } diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs new file mode 100644 index 0000000000..a237aa243f --- /dev/null +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -0,0 +1,451 @@ +//! `plugins install --set` and the plugin step of `mesh-llm setup`: installing +//! a catalog plugin set against one catalog snapshot. + +use std::time::Duration; + +use anyhow::{Result, bail}; +use mesh_llm_plugin_manager::sets::{SetOffer, read_set_offer, record_set_offer}; +use mesh_llm_plugin_manager::{ + PluginCatalog, PluginInstallOptions, PluginProgressReporter, + catalog::sets_url_for, + sets::{SetInstallResult, install_set}, +}; +use reqwest::Client; + +/// The set setup installs unless the operator opts out. +pub const DEFAULT_SET: &str = "recommended"; + +/// Bound on reading the catalog and its sets file: setup must not hang on a +/// catalog host that accepts a connection and never answers. +const CATALOG_TIMEOUT: Duration = Duration::from_secs(30); +/// Bound on the whole default install in setup (release lookups and +/// downloads for every member). +const SETUP_INSTALL_TIMEOUT: Duration = Duration::from_secs(600); + +/// What setup's plugin step ended with. Setup never fails on it. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub enum SetupPluginsOutcome { + #[default] + NotRequested, + /// Setup already offered the set for this plugin store: it installs a set once, + /// so nothing is attempted, reinstalled or warned about. + AlreadyOffered, + /// The set resolved. Members may have been installed, left as they were + /// (already installed), found unavailable on this platform, or failed. + /// `record_error` says why the offer record could not be written; the + /// next setup then offers the set again. + Finished { + installed: Vec, + unavailable: Vec<(String, String)>, + failed: Vec<(String, String)>, + record_error: Option, + }, + /// The set could not be read or the install did not finish; nothing + /// further was attempted. + Unavailable(String), +} + +async fn read_catalog( + options: &PluginInstallOptions, + timeout: Duration, +) -> Result<(PluginCatalog, Option)> { + let client = catalog_client(timeout)?; + let sets_url = sets_url_for(&options.catalog_url); + PluginCatalog::fetch_with_sets(&client, &options.catalog_url, sets_url.as_deref()).await +} + +fn catalog_client(timeout: Duration) -> Result { + let builder = Client::builder().timeout(timeout); + // Tests serve the catalog on loopback; a proxy the build environment + // sets must not take those requests. Real catalog reads keep the proxy. + #[cfg(test)] + let builder = builder.no_proxy(); + Ok(builder.build()?) +} + +/// Why a catalog without the requested set has none: the reason the sets file +/// could not be read, which names a custom catalog URL when that is the cause. +fn no_set_reason(catalog: &PluginCatalog, set_name: &str, problem: Option) -> String { + match problem { + Some(problem) => format!("the plugin catalog has no set '{set_name}' ({problem})"), + None => { + let known: Vec<&str> = catalog.sets().iter().map(|set| set.name.as_str()).collect(); + if known.is_empty() { + format!("the plugin catalog has no set '{set_name}' (it lists no sets)") + } else { + format!( + "the plugin catalog has no set '{set_name}'; available sets: {}", + known.join(", ") + ) + } + } + } +} + +/// `mesh-llm plugins install --set NAME`: install the set's missing members. +/// Fails when the set is unknown or any member fails, after attempting all. +pub async fn install_set_command( + set_name: &str, + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, +) -> Result { + let (catalog, problem) = read_catalog(options, CATALOG_TIMEOUT).await?; + if catalog.find_set(set_name).is_none() { + bail!("{}", no_set_reason(&catalog, set_name, problem)); + } + install_set( + &catalog, + set_name, + &SetOffer::default(), + false, + options, + progress, + ) + .await +} + +/// Setup's plugin step. Every failure (offline, a slow catalog host, no such +/// set, a failing member) becomes an outcome the caller reports with a retry +/// command: an optional plugin never fails setup. +pub async fn install_default_set_for_setup( + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, +) -> SetupPluginsOutcome { + install_set_for_setup( + DEFAULT_SET, + options, + progress, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await +} + +async fn install_set_for_setup( + set_name: &str, + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, + catalog_timeout: Duration, + install_timeout: Duration, +) -> SetupPluginsOutcome { + let offer = match read_set_offer(&options.store_root, set_name) { + Ok(offer) => offer, + Err(error) => return SetupPluginsOutcome::Unavailable(format!("{error:#}")), + }; + if offer.complete { + return SetupPluginsOutcome::AlreadyOffered; + } + let work = async { + let (catalog, problem) = match read_catalog(options, catalog_timeout).await { + Ok(read) => read, + Err(error) => return SetupPluginsOutcome::Unavailable(format!("{error:#}")), + }; + let Some(set) = catalog.find_set(set_name) else { + return SetupPluginsOutcome::Unavailable(no_set_reason(&catalog, set_name, problem)); + }; + let set_members = set.plugins.clone(); + match install_set(&catalog, set_name, &offer, true, options, progress).await { + Ok(result) => { + crate::capsules_witness::keep_installed_capsules_local( + &result + .installed + .iter() + .map(|outcome| outcome.metadata.name.clone()) + .collect::>(), + ); + let recorded = record_set_offer( + &options.store_root, + set_name, + offer.after(&set_members, &result), + ); + SetupPluginsOutcome::Finished { + record_error: recorded.err().map(|error| format!("{error:#}")), + installed: result + .installed + .into_iter() + .map(|outcome| outcome.metadata.name) + .collect(), + unavailable: result.unavailable, + failed: result.failed, + } + } + Err(error) => SetupPluginsOutcome::Unavailable(format!("{error:#}")), + } + }; + match tokio::time::timeout(install_timeout, work).await { + Ok(outcome) => outcome, + Err(_) => SetupPluginsOutcome::Unavailable(format!( + "timed out after {}s; plugins that finished installing before then stay installed (`mesh-llm plugins list`)", + install_timeout.as_secs() + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + thread, + }; + use tempfile::TempDir; + + fn options(catalog_url: String, root: &std::path::Path) -> PluginInstallOptions { + PluginInstallOptions { + store_root: root.to_path_buf(), + install_root: root.join("installed"), + catalog_url, + target: mesh_llm_plugin_manager::PluginTarget::current().unwrap(), + } + } + + /// Answer each request from `routes`. + fn serve(routes: &'static [(&'static str, &'static str)]) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let mut header = String::new(); + while reader.read_line(&mut header).is_ok() && !header.trim().is_empty() { + header.clear(); + } + let path = line.split_whitespace().nth(1).unwrap_or("/").to_string(); + let (status, body) = match routes.iter().find(|(route, _)| *route == path) { + Some((_, body)) => ("200 OK", *body), + None => ("404 Not Found", ""), + }; + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + base + } + + const PLUGINS: &str = r#"{"name":"alpha","description":"A","github_url":"https://github.com/acme/alpha","author_email":"d@example.com","author_name":"Acme"}"#; + + /// The catalog read's own deadline, not setup's outer one, ends a read + /// from a host that accepts the connection and never answers. + #[tokio::test] + async fn a_stalled_catalog_host_ends_setup_s_plugin_step_with_an_outcome() { + let temp = TempDir::new().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let (accepted, connections) = std::sync::mpsc::channel(); + thread::spawn(move || { + let mut held = Vec::new(); + for stream in listener.incoming().flatten() { + held.push(stream); + let _ = accepted.send(()); + } + }); + let started = std::time::Instant::now(); + let outcome = install_set_for_setup( + "recommended", + &options(format!("{base}/plugins.jsonl"), temp.path()), + &mut |_| {}, + Duration::from_millis(200), + Duration::from_secs(60), + ) + .await; + let SetupPluginsOutcome::Unavailable(reason) = &outcome else { + panic!("a stalled catalog is unavailable: {outcome:?}"); + }; + assert!(connections.try_recv().is_ok(), "the host accepted the read"); + assert!( + !reason.starts_with("timed out after"), + "the catalog deadline, not setup's, ended it: {reason}" + ); + assert!( + started.elapsed() < Duration::from_secs(60), + "{:?}", + started.elapsed() + ); + } + + /// Setup offers the set once per plugin store: after it resolved, a later run + /// attempts nothing (not even a catalog read), so a plugin the operator + /// removed stays removed. + #[tokio::test] + async fn a_set_is_offered_once_per_machine() { + let temp = TempDir::new().unwrap(); + let base = serve(&[ + ("/plugins.jsonl", PLUGINS), + ( + "/plugin-sets.jsonl", + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ), + ]); + let options = options(format!("{base}/plugins.jsonl"), temp.path()); + let first = install_set_for_setup( + "recommended", + &options, + &mut |_| {}, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await; + assert!( + matches!(first, SetupPluginsOutcome::Finished { .. }), + "{first:?}" + ); + + let dead = self::options("http://127.0.0.1:9/plugins.jsonl".to_string(), temp.path()); + let second = install_set_for_setup( + "recommended", + &dead, + &mut |_| {}, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await; + assert_eq!(second, SetupPluginsOutcome::AlreadyOffered); + } + + /// A set that could not be read is not recorded as offered, so the next + /// setup tries again. + #[tokio::test] + async fn an_unreadable_set_is_not_recorded_as_offered() { + let temp = TempDir::new().unwrap(); + let dead = options("http://127.0.0.1:9/plugins.jsonl".to_string(), temp.path()); + let outcome = install_set_for_setup( + "recommended", + &dead, + &mut |_| {}, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await; + assert!(matches!(outcome, SetupPluginsOutcome::Unavailable(_))); + assert_eq!( + read_set_offer(temp.path(), "recommended").unwrap(), + SetOffer::default() + ); + } + + #[tokio::test] + async fn a_catalog_without_the_set_is_an_outcome_not_a_failure() { + let temp = TempDir::new().unwrap(); + let base = serve(&[("/plugins.jsonl", PLUGINS)]); + let outcome = install_set_for_setup( + "recommended", + &options(format!("{base}/plugins.jsonl"), temp.path()), + &mut |_| {}, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await; + let SetupPluginsOutcome::Unavailable(reason) = outcome else { + panic!("expected Unavailable"); + }; + assert!(reason.contains("no set 'recommended'"), "{reason}"); + } + + #[test] + fn a_catalog_that_lists_no_sets_says_so() { + let catalog = PluginCatalog::parse_jsonl(PLUGINS).unwrap(); + let reason = no_set_reason(&catalog, "recommended", None); + assert!(reason.ends_with("(it lists no sets)"), "{reason}"); + } + + /// When the offer record cannot be written, setup still reports the set's + /// result, plus the record error, rather than claiming nothing installed. + #[tokio::test] + async fn a_failed_offer_record_keeps_the_set_result() { + let temp = TempDir::new().unwrap(); + // A directory where the record's temporary file goes makes the write fail. + std::fs::create_dir_all( + temp.path() + .join(format!("offered-sets.json.{}.tmp", std::process::id())), + ) + .unwrap(); + let base = serve(&[ + ("/plugins.jsonl", PLUGINS), + ( + "/plugin-sets.jsonl", + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ), + ]); + let outcome = install_set_for_setup( + "recommended", + &options(format!("{base}/plugins.jsonl"), temp.path()), + &mut |_| {}, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await; + let SetupPluginsOutcome::Finished { + unavailable, + record_error, + .. + } = outcome + else { + panic!("expected Finished, got {outcome:?}"); + }; + assert_eq!(unavailable.len(), 1); + assert!(record_error.is_some()); + assert_eq!( + read_set_offer(temp.path(), "recommended").unwrap(), + SetOffer::default() + ); + } + + #[tokio::test] + async fn a_custom_catalog_url_says_sets_are_unavailable_for_it() { + let temp = TempDir::new().unwrap(); + let base = serve(&[("/custom.json", PLUGINS)]); + let error = install_set_command( + "recommended", + &options(format!("{base}/custom.json"), temp.path()), + &mut |_| {}, + ) + .await + .unwrap_err() + .to_string(); + assert!( + error.contains("no plugin-sets.jsonl beside the catalog URL"), + "{error}" + ); + } + + /// The members have no release for this platform, so nothing downloads: + /// the set install ends cleanly with every member unavailable. + #[tokio::test] + async fn a_set_whose_members_have_no_release_here_installs_nothing() { + let temp = TempDir::new().unwrap(); + let base = serve(&[ + ("/plugins.jsonl", PLUGINS), + ( + "/plugin-sets.jsonl", + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ), + ]); + let outcome = install_set_for_setup( + "recommended", + &options(format!("{base}/plugins.jsonl"), temp.path()), + &mut |_| {}, + CATALOG_TIMEOUT, + SETUP_INSTALL_TIMEOUT, + ) + .await; + let SetupPluginsOutcome::Finished { + installed, + unavailable, + failed, + .. + } = outcome + else { + panic!("expected Finished"); + }; + assert!(installed.is_empty() && failed.is_empty()); + assert_eq!(unavailable.len(), 1); + assert_eq!(unavailable[0].0, "alpha"); + } +} diff --git a/mesh/crates/mesh-llm-commands/src/setup/cli_actions_tests.rs b/mesh/crates/mesh-llm-commands/src/setup/cli_actions_tests.rs index 150feb4643..cd50750aed 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/cli_actions_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/cli_actions_tests.rs @@ -1,3 +1,4 @@ +use super::SetupPluginStore; use super::command::{CliSetupActions, SetupServiceOutcome}; use super::github::SetupGitHubOutcome; use super::github_runner::{GhCommand, GhCommandError}; @@ -58,6 +59,7 @@ async fn run_setup_with_cli_actions_records_nonfatal_github_failure() { let mut prompter = FakePrompter::with_replies([None]); let options = SetupOptions { skip_runtime: true, + skip_plugin_install: true, no_service: true, ..SetupOptions::default() }; @@ -90,3 +92,80 @@ async fn run_setup_with_cli_actions_records_nonfatal_github_failure() { ] ); } + +/// The plugin step is optional: with the catalog unreachable it records why +/// and setup carries on, with the later steps still run. +#[tokio::test] +async fn a_failing_plugin_install_never_fails_setup() { + let (_temp, context) = service_context_fixture(); + let mut actions = CliSetupActions::with_service_support( + SetupEnvironment { + platform: SetupPlatform::Linux, + interactive: false, + }, + NativeRuntimeConfigSelection::default(), + context, + Box::new(FakeServiceRunner), + Box::new(SharedGhRunner::new([]).0), + ); + let mut prompter = FakePrompter::default(); + let options = SetupOptions { + skip_runtime: true, + no_service: true, + no_interactive: true, + ..SetupOptions::default() + }; + + let plan = run_setup( + options, + SetupEnvironment { + platform: SetupPlatform::Linux, + interactive: false, + }, + &mut prompter, + &mut actions, + ) + .await + .expect("an unreachable plugin catalog must not fail setup"); + + assert_eq!( + plan.core_steps, + vec![SetupStep::InstallPlugins(SetupPluginStore::Invoking)] + ); + assert!(matches!( + actions.plugins_outcome, + crate::plugin_sets::SetupPluginsOutcome::Unavailable(_) + )); + assert!(prompter.prompts.is_empty()); +} + +/// `plugins install` uses the invoking shell's store, so when setup installed +/// into the service's store the retry command names that store. +#[test] +fn the_retry_hint_names_the_store_setup_installed_into() { + use super::command::RetryStore; + use std::path::PathBuf; + + assert!( + RetryStore::Invoking + .hint() + .starts_with("Retry with `mesh-llm plugins install --set recommended`") + ); + assert!( + RetryStore::Service(PathBuf::from("/srv/mesh/plugins")) + .hint() + .starts_with( + "Retry with `MESH_LLM_PLUGIN_DIR=/srv/mesh/plugins mesh-llm plugins install --set recommended`" + ) + ); + assert!( + RetryStore::Service(PathBuf::from("/Users/a b/it's")) + .hint() + .contains("`MESH_LLM_PLUGIN_DIR='/Users/a b/it'\\''s' mesh-llm") + ); + assert!( + RetryStore::UnknownService + .hint() + .contains("MESH_LLM_PLUGIN_DIR=") + ); +} diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index 57eeea024f..280a4e1d30 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -1,24 +1,28 @@ use super::prompt::confirm_yes_no; use super::service_paths::ServiceInstallContext; +use super::service_plugin_store::service_plugin_store; use super::service_runner::{CliServiceCommandRunner, ServiceCommandRunner}; use super::summary::{ print_runtime_install_result, print_service_install_result, print_setup_summary, }; use super::{ SetupActions, SetupConfirmPrompt, SetupEnvironment, SetupGitHubStarPlan, SetupOptions, - SetupPlan, SetupPrompter, SetupStep, + SetupPlan, SetupPluginStore, SetupPrompter, SetupStep, github::{SetupGitHubOutcome, execute_github_star_plan}, github_runner::{GhCommandRunner, ProcessGhCommandRunner}, plan_setup, service::{ServiceInstallReport, install_service}, }; +use crate::plugin_sets::{DEFAULT_SET, SetupPluginsOutcome, install_default_set_for_setup}; use crate::runtime_native::{ NativeRuntimeConfigSelection, SetupNativeRuntimeOptions, SetupNativeRuntimeOutcome, SetupNativeRuntimePruneResult, install_and_prune_native_runtime_for_setup, }; use anyhow::{Result, anyhow}; +use mesh_llm_plugin_manager::PluginInstallOptions; use std::future::Future; use std::io::Write; +use std::path::PathBuf; use std::pin::Pin; #[derive(Clone, Copy, Debug)] @@ -70,9 +74,12 @@ pub(crate) struct CliSetupActions<'a> { environment: SetupEnvironment, configured: NativeRuntimeConfigSelection<'a>, pub(crate) runtime_outcome: Option, + pub(crate) plugins_outcome: SetupPluginsOutcome, service_context: Option, service_runner: Box, github_runner: Box, + /// Where the plugin step reads the catalog; `None` reads the environment's. + plugin_options: Option, pub(crate) service_outcome: SetupServiceOutcome, pub(crate) github_outcome: SetupGitHubOutcome, verbose: bool, @@ -106,9 +113,11 @@ impl<'a> CliSetupActions<'a> { environment, configured, runtime_outcome: None, + plugins_outcome: SetupPluginsOutcome::NotRequested, service_context, service_runner, github_runner, + plugin_options: None, service_outcome: SetupServiceOutcome::NotRequested, github_outcome: SetupGitHubOutcome::NotEvaluated, verbose, @@ -123,14 +132,24 @@ impl<'a> CliSetupActions<'a> { service_runner: Box, github_runner: Box, ) -> Self { - Self::with_support( + let mut actions = Self::with_support( environment, configured, Some(service_context), service_runner, github_runner, false, - ) + ); + // A refused loopback port: the plugin step fails at once and tests + // never reach the network or a real plugin store. + actions.plugin_options = Some(PluginInstallOptions { + store_root: std::env::temp_dir().join("mesh-llm-setup-test-unused-plugins"), + install_root: std::env::temp_dir().join("mesh-llm-setup-test-unused-plugins/installed"), + catalog_url: "http://127.0.0.1:9/plugins.jsonl".to_string(), + target: mesh_llm_plugin_manager::PluginTarget::current() + .expect("tests run on a supported plugin target"), + }); + actions } async fn install_runtime(&mut self) -> Result<()> { @@ -187,6 +206,75 @@ impl<'a> CliSetupActions<'a> { Ok(()) } + /// Install the default plugin set. Never fails setup: what went wrong is + /// printed with the command that retries it, and kept for the summary. + async fn install_plugins(&mut self, store: SetupPluginStore) -> Result<()> { + let (options, retry) = match self.plugin_options.clone() { + Some(options) => (Ok(options), RetryStore::Invoking), + None => match self.plugin_install_options(store) { + Ok((options, retry)) => (Ok(options), retry), + Err(error) if store == SetupPluginStore::Service => { + (Err(error), RetryStore::UnknownService) + } + Err(error) => (Err(error), RetryStore::Invoking), + }, + }; + let outcome = match options { + Ok(options) => { + let mut progress = crate::plugin::CliPluginProgress::default(); + let outcome = install_default_set_for_setup(&options, &mut progress).await; + progress.finish(); + outcome + } + Err(error) => SetupPluginsOutcome::Unavailable(format!("{error:#}")), + }; + print_plugins_warnings(&outcome, &retry); + self.plugins_outcome = outcome; + Ok(()) + } + + /// Install into the store the node will read: the invoking shell's, or, + /// when setup also installs and starts the service, the service's. Also + /// returns where a retry has to install. + fn plugin_install_options( + &self, + store: SetupPluginStore, + ) -> Result<(PluginInstallOptions, RetryStore)> { + let mut options = PluginInstallOptions::from_env()?; + let mut retry = RetryStore::Invoking; + if store == SetupPluginStore::Service { + let context = match self.service_context.clone() { + Some(context) => context, + None => ServiceInstallContext::detect(self.environment.platform, true)?, + }; + // Windows has no service.env: the task keeps the user's own + // environment but starts in the home directory, so a relative + // store names a place there, not under setup's directory. + let root = match service_plugin_store(&context)? { + Some(root) => Some(root), + None if options.store_root.is_relative() => { + Some(context.home_dir.join(&options.store_root)) + } + None => None, + }; + if let Some(root) = root + && root != options.store_root + { + options.install_root = root.join("installed"); + options.store_root = root.clone(); + retry = RetryStore::Service(root); + } + } + if self.verbose { + let _ = writeln!( + mesh_llm_events::console_err(), + "Plugin store: {}", + options.store_root.display() + ); + } + Ok((options, retry)) + } + fn install_service(&mut self) -> Result<()> { let context = match self.service_context.clone() { Some(context) => context, @@ -207,6 +295,87 @@ impl<'a> CliSetupActions<'a> { } } +/// Where the printed retry command has to install the set: `plugins install` +/// uses the invoking shell's store, which is not always the one setup chose. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum RetryStore { + Invoking, + /// The service reads this store, not the invoking shell's. + Service(PathBuf), + /// The service's store could not be determined. + UnknownService, +} + +impl RetryStore { + pub(crate) fn hint(&self) -> String { + let opt_out = "or pass --skip-plugin-install to setup to opt out."; + match self { + Self::Invoking => { + format!("Retry with `mesh-llm plugins install --set {DEFAULT_SET}`, {opt_out}") + } + Self::Service(root) => format!( + "Retry with `MESH_LLM_PLUGIN_DIR={} mesh-llm plugins install --set {DEFAULT_SET}` to install into the store the service reads, {opt_out}", + shell_quote(&root.to_string_lossy()) + ), + Self::UnknownService => format!( + "Once the service's plugin store can be read, retry with `MESH_LLM_PLUGIN_DIR= mesh-llm plugins install --set {DEFAULT_SET}`, {opt_out}" + ), + } + } +} + +/// `value` as one POSIX shell word. The service store is only chosen on Linux +/// and macOS, where the retry runs in a POSIX shell. +fn shell_quote(value: &str) -> String { + if !value.is_empty() + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || "/._-+:@%".contains(c)) + { + return value.to_string(); + } + format!("'{}'", value.replace('\'', "'\\''")) +} + +fn print_plugins_warnings(outcome: &SetupPluginsOutcome, retry: &RetryStore) { + let mut err = mesh_llm_events::console_err(); + let retry = retry.hint(); + match outcome { + SetupPluginsOutcome::Unavailable(reason) => { + let _ = writeln!( + err, + "warning: could not install the `{DEFAULT_SET}` plugin set: {reason}. {retry}" + ); + } + SetupPluginsOutcome::Finished { + unavailable, + failed, + record_error, + .. + } => { + for (name, reason) in unavailable { + let _ = writeln!( + err, + "warning: plugin {name} is not available on this platform: {reason}" + ); + } + for (name, reason) in failed { + let _ = writeln!(err, "warning: could not install plugin {name}: {reason}"); + } + if !failed.is_empty() { + let _ = writeln!(err, "{retry}"); + } + if let Some(error) = record_error { + let _ = writeln!( + err, + "warning: could not record that setup offered the `{DEFAULT_SET}` plugin set, so the next setup offers it again: {error}" + ); + } + } + SetupPluginsOutcome::NotRequested | SetupPluginsOutcome::AlreadyOffered => {} + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum SetupServiceOutcome { NotRequested, @@ -230,6 +399,7 @@ impl SetupActions for CliSetupActions<'_> { match step { SetupStep::InstallRuntime => self.install_runtime().await, SetupStep::PruneInactiveRuntimes => self.report_runtime_prune(), + SetupStep::InstallPlugins(store) => self.install_plugins(store).await, SetupStep::InstallService => self.install_service(), SetupStep::PrintServiceGuidance => { self.service_outcome = SetupServiceOutcome::PrintedGuidance; diff --git a/mesh/crates/mesh-llm-commands/src/setup/command_tests.rs b/mesh/crates/mesh-llm-commands/src/setup/command_tests.rs index 3b642a3689..ad5fa7862d 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command_tests.rs @@ -1,3 +1,4 @@ +use super::SetupPluginStore; use super::service_paths::ServiceInstallContext; use super::service_runner::{ServiceCommand, ServiceCommandRunner}; use super::{ @@ -104,7 +105,11 @@ async fn run_setup_executes_planned_steps_and_github_star_action() { assert_eq!(plan.service, SetupServicePlan::Skip); assert_eq!( actions.steps, - vec![SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes] + vec![ + SetupStep::InstallRuntime, + SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), + ] ); assert_eq!(actions.github, vec![SetupGitHubStarPlan::PromptIfEligible]); } @@ -166,6 +171,7 @@ async fn run_setup_suppresses_github_star_for_yes_mode() { fn github_summary_reports_authenticated_star_success() { let plan = super::SetupPlan::new( super::SetupRuntimePlan::Skip, + super::SetupPluginsPlan::Skip, super::SetupServicePlan::Skip, SetupGitHubStarPlan::PromptIfEligible, ); @@ -180,6 +186,7 @@ fn github_summary_reports_authenticated_star_success() { async fn service_summary_reports_real_service_installation() { let plan = super::SetupPlan::new( super::SetupRuntimePlan::Skip, + super::SetupPluginsPlan::Skip, super::SetupServicePlan::Install, SetupGitHubStarPlan::Skip(SetupGitHubStarSkipReason::AutomaticYes), ); @@ -222,6 +229,7 @@ async fn service_summary_reports_real_service_installation() { fn github_summary_reports_nonfatal_star_request_failure() { let plan = super::SetupPlan::new( super::SetupRuntimePlan::Skip, + super::SetupPluginsPlan::Skip, super::SetupServicePlan::Skip, SetupGitHubStarPlan::PromptIfEligible, ); diff --git a/mesh/crates/mesh-llm-commands/src/setup/environment.rs b/mesh/crates/mesh-llm-commands/src/setup/environment.rs index c81de7c4e0..40cf9cdb60 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/environment.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/environment.rs @@ -5,6 +5,8 @@ pub struct SetupOptions { pub service: bool, pub no_service: bool, pub skip_runtime: bool, + /// Opt out of installing the catalog's `recommended` plugin set. + pub skip_plugin_install: bool, pub verbose: bool, } diff --git a/mesh/crates/mesh-llm-commands/src/setup/github_tests.rs b/mesh/crates/mesh-llm-commands/src/setup/github_tests.rs index f4f09553aa..ef7a45e0fa 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/github_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/github_tests.rs @@ -244,6 +244,7 @@ fn eligible_explicit_no_skips_star_command() { fn summary_reports_nonfatal_eligibility_failures_honestly() { let plan = SetupPlan::new( super::SetupRuntimePlan::Skip, + super::SetupPluginsPlan::Skip, super::SetupServicePlan::Skip, prompt_plan(), ); diff --git a/mesh/crates/mesh-llm-commands/src/setup/mod.rs b/mesh/crates/mesh-llm-commands/src/setup/mod.rs index 6c4cbc3d6a..c2e69d11ca 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/mod.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/mod.rs @@ -13,6 +13,7 @@ pub(crate) mod service_host; #[cfg(windows)] mod service_host_windows; pub(crate) mod service_paths; +mod service_plugin_store; pub(crate) mod service_runner; // Only the Windows service host runs it; its tests run everywhere. #[cfg(any(windows, test))] @@ -24,8 +25,8 @@ pub use actions::SetupActions; pub use command::{SetupCommandArgs, run_setup, run_setup_command}; pub use environment::{SetupEnvironment, SetupOptions, SetupPlatform}; pub use plan::{ - SetupGitHubStarPlan, SetupGitHubStarSkipReason, SetupPlan, SetupRuntimePlan, SetupServicePlan, - SetupStep, + SetupGitHubStarPlan, SetupGitHubStarSkipReason, SetupPlan, SetupPluginStore, SetupPluginsPlan, + SetupRuntimePlan, SetupServicePlan, SetupStep, }; pub use planner::{SetupPlanError, plan_setup}; pub use prompt::{SetupConfirmPrompt, SetupPromptDefault, SetupPromptKind, SetupPrompter}; diff --git a/mesh/crates/mesh-llm-commands/src/setup/orchestration_tests.rs b/mesh/crates/mesh-llm-commands/src/setup/orchestration_tests.rs index 5052d34148..36f7b38e45 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/orchestration_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/orchestration_tests.rs @@ -1,3 +1,4 @@ +use super::SetupPluginStore; use super::test_support::{FakePrompter, RecordingActions}; use super::{SetupEnvironment, SetupOptions, SetupPlatform, SetupStep, run_setup}; @@ -23,6 +24,7 @@ async fn run_setup_no_interactive_uses_guidance_step_and_hidden_star_without_pro vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), SetupStep::PrintServiceGuidance, ] ); @@ -35,6 +37,7 @@ async fn run_setup_no_interactive_uses_guidance_step_and_hidden_star_without_pro async fn run_setup_skip_runtime_and_no_service_runs_no_hidden_core_side_effects() { let options = SetupOptions { skip_runtime: true, + skip_plugin_install: true, no_service: true, yes: true, ..SetupOptions::default() @@ -60,6 +63,7 @@ async fn run_setup_skip_runtime_and_no_service_runs_no_hidden_core_side_effects( async fn run_setup_service_failure_is_core_fatal_and_skips_github() { let options = SetupOptions { skip_runtime: true, + skip_plugin_install: true, service: true, ..SetupOptions::default() }; diff --git a/mesh/crates/mesh-llm-commands/src/setup/plan.rs b/mesh/crates/mesh-llm-commands/src/setup/plan.rs index 867418a693..3ba381d107 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/plan.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/plan.rs @@ -1,6 +1,7 @@ #[derive(Clone, Debug, Eq, PartialEq)] pub struct SetupPlan { pub runtime: SetupRuntimePlan, + pub plugins: SetupPluginsPlan, pub service: SetupServicePlan, pub github_star: SetupGitHubStarPlan, pub core_steps: Vec, @@ -9,12 +10,14 @@ pub struct SetupPlan { impl SetupPlan { pub fn new( runtime: SetupRuntimePlan, + plugins: SetupPluginsPlan, service: SetupServicePlan, github_star: SetupGitHubStarPlan, ) -> Self { - let core_steps = build_core_steps(runtime, service); + let core_steps = build_core_steps(runtime, plugins, service); Self { runtime, + plugins, service, github_star, core_steps, @@ -28,6 +31,13 @@ pub enum SetupRuntimePlan { Skip, } +/// Whether setup installs the catalog's default plugin set. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SetupPluginsPlan { + InstallDefaultSet, + Skip, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SetupServicePlan { Install, @@ -47,20 +57,45 @@ pub enum SetupGitHubStarSkipReason { HiddenPrompt, } +/// Which plugin store setup installs the default set into. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SetupPluginStore { + /// The store the invoking environment names (`MESH_LLM_PLUGIN_DIR`). + Invoking, + /// The store the service this setup installs and starts reads: its + /// `service.env` decides, not the invoking shell. + Service, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SetupStep { InstallRuntime, PruneInactiveRuntimes, + /// Non-fatal: the action reports a failure and setup carries on. + InstallPlugins(SetupPluginStore), InstallService, PrintServiceGuidance, } -fn build_core_steps(runtime: SetupRuntimePlan, service: SetupServicePlan) -> Vec { +fn build_core_steps( + runtime: SetupRuntimePlan, + plugins: SetupPluginsPlan, + service: SetupServicePlan, +) -> Vec { let mut steps = Vec::new(); if matches!(runtime, SetupRuntimePlan::InstallAndPrune) { steps.push(SetupStep::InstallRuntime); steps.push(SetupStep::PruneInactiveRuntimes); } + // Before the service so a node it starts already finds the plugins. + if matches!(plugins, SetupPluginsPlan::InstallDefaultSet) { + let store = if matches!(service, SetupServicePlan::Install) { + SetupPluginStore::Service + } else { + SetupPluginStore::Invoking + }; + steps.push(SetupStep::InstallPlugins(store)); + } match service { SetupServicePlan::Install => steps.push(SetupStep::InstallService), SetupServicePlan::PrintGuidance => steps.push(SetupStep::PrintServiceGuidance), diff --git a/mesh/crates/mesh-llm-commands/src/setup/planner.rs b/mesh/crates/mesh-llm-commands/src/setup/planner.rs index 3cf70c2e31..b20c3ff3b9 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/planner.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/planner.rs @@ -1,7 +1,7 @@ use super::{ SetupConfirmPrompt, SetupEnvironment, SetupGitHubStarPlan, SetupGitHubStarSkipReason, - SetupOptions, SetupPlan, SetupPlatform, SetupPromptDefault, SetupPromptKind, SetupPrompter, - SetupRuntimePlan, SetupServicePlan, + SetupOptions, SetupPlan, SetupPlatform, SetupPluginsPlan, SetupPromptDefault, SetupPromptKind, + SetupPrompter, SetupRuntimePlan, SetupServicePlan, }; use std::error::Error; use std::fmt::{self, Display, Formatter}; @@ -49,9 +49,16 @@ pub fn plan_setup( } else { SetupRuntimePlan::InstallAndPrune }; + // The default set installs in attended and unattended setup alike, with + // no prompt; `--skip-plugin-install` is the opt-out. + let plugins = if options.skip_plugin_install { + SetupPluginsPlan::Skip + } else { + SetupPluginsPlan::InstallDefaultSet + }; let service = plan_service(options, environment, prompter); let github_star = plan_github_star(options, environment); - Ok(SetupPlan::new(runtime, service, github_star)) + Ok(SetupPlan::new(runtime, plugins, service, github_star)) } fn plan_service( diff --git a/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs new file mode 100644 index 0000000000..f7391dea55 --- /dev/null +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -0,0 +1,309 @@ +//! The plugin store the setup-installed service reads. +//! +//! systemd and launchd start the node with the service's own environment, +//! not the shell that ran setup: `MESH_LLM_PLUGIN_DIR` comes from +//! `service.env`, and without it the node uses the default store. Setup +//! installs the default plugin set there when it also installs the service, +//! so the node it starts finds them. +use super::SetupPlatform; +use super::service_paths::{ServiceInstallContext, ServicePaths}; +use anyhow::{Context, Result, bail}; +use std::path::{Path, PathBuf}; + +const PLUGIN_DIR_VAR: &str = "MESH_LLM_PLUGIN_DIR"; + +/// The plugin store root of the service `context` describes. `None` on +/// Windows, whose scheduled task starts with the user's own environment, as +/// the shell that ran setup did. +pub(crate) fn service_plugin_store(context: &ServiceInstallContext) -> Result> { + if context.platform == SetupPlatform::Windows { + return Ok(None); + } + let env_file = ServicePaths::from_context(context).service_env_file; + let configured = match std::fs::read_to_string(&env_file) { + Ok(contents) => plugin_dir_from_env_file(&contents, context.platform) + .with_context(|| format!("read {PLUGIN_DIR_VAR} from {}", env_file.display()))?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + return Err(error).with_context(|| format!("read {}", env_file.display())); + } + }; + // systemd (`WorkingDirectory=%h`) and launchd (`WorkingDirectory`) start + // the node in the home directory, so a relative value names a store there, + // wherever setup itself runs. + Ok(Some(match configured { + Some(path) => context.home_dir.join(path), + None => default_plugin_store(&context.home_dir), + })) +} + +/// What the node uses when nothing sets `MESH_LLM_PLUGIN_DIR`, as +/// `mesh_llm_plugin_manager::default_store_root` computes it. +fn default_plugin_store(home_dir: &Path) -> PathBuf { + home_dir.join(".mesh-llm").join("plugins") +} + +/// `MESH_LLM_PLUGIN_DIR` from a `service.env` of plain `KEY=value` lines, +/// the format its template asks for. The last assignment wins; an empty +/// value counts as unset, as it does for the node. Matching quotes around +/// the value are removed, as systemd and the launchd runner's shell do. +/// +/// The two readers differ past that: systemd's `EnvironmentFile=` treats +/// `$` literally, while the macOS runner sources the file with bash, which +/// expands variables, command substitutions and a leading `~` outside single +/// quotes. Both process backslash escapes and join adjacent quoted parts. A +/// value whose meaning depends on any of this is an error rather than a +/// guess, so setup never installs into a store the service does not read. +fn plugin_dir_from_env_file(contents: &str, platform: SetupPlatform) -> Result> { + let mut value = None; + for line in contents.lines() { + let line = line.trim(); + if line.starts_with('#') { + continue; + } + // The macOS runner sources the file with bash, where `export` plus + // any whitespace precedes an assignment. systemd has no such word: + // `export KEY=value` there sets a variable named `export KEY`, which + // the node never reads, so the store is the default one. + let line = match line.strip_prefix("export") { + Some(rest) if platform == SetupPlatform::MacOs && rest.starts_with([' ', '\t']) => { + rest.trim_start() + } + _ => line, + }; + let Some((key, raw)) = line.split_once('=') else { + continue; + }; + if key == PLUGIN_DIR_VAR { + value = Some(raw); + } + } + let Some(raw) = value else { + return Ok(None); + }; + let (inner, quoting) = unquote(raw); + if !value_is_literal(inner, quoting, platform) { + bail!( + "the service reads `{PLUGIN_DIR_VAR}={raw}` in a way setup does not reproduce; \ + set it to an absolute path, plain or in single quotes, without variables, `~`, backslashes or other shell syntax" + ); + } + Ok(Some(inner) + .filter(|value| !value.is_empty()) + .map(PathBuf::from)) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Quoting { + None, + Single, + Double, +} + +fn unquote(value: &str) -> (&str, Quoting) { + for (quote, quoting) in [('"', Quoting::Double), ('\'', Quoting::Single)] { + if let Some(inner) = value + .strip_prefix(quote) + .and_then(|rest| rest.strip_suffix(quote)) + { + return (inner, quoting); + } + } + (value, Quoting::None) +} + +/// Whether the service reads `inner` as exactly these characters. Anything +/// that is not plainly literal for that reader is refused, not interpreted: +/// a quote inside the value (mixed quoting such as `'/a/'"$USER"`), an +/// unquoted value with characters a shell or systemd treats specially, and, +/// outside single quotes, backslashes and (for the macOS runner's bash) `$` +/// and backticks. +fn value_is_literal(inner: &str, quoting: Quoting, platform: SetupPlatform) -> bool { + if inner.contains('\'') || inner.contains('"') { + return false; + } + match quoting { + Quoting::Single => true, + Quoting::Double => { + !inner.contains('\\') + && (platform != SetupPlatform::MacOs + || !(inner.contains('$') || inner.contains('`'))) + } + Quoting::None => inner + .chars() + .all(|c| c.is_alphanumeric() || "/._-+:@%,=".contains(c)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn context(platform: SetupPlatform, root: &Path) -> ServiceInstallContext { + ServiceInstallContext { + platform, + home_dir: root.join("home"), + config_root: root.join("config"), + local_data_root: root.join("local"), + binary_path: root.join("bin/mesh-llm"), + user_id: String::new(), + start_service: true, + } + } + + fn write_env(context: &ServiceInstallContext, contents: &str) { + let path = ServicePaths::from_context(context).service_env_file; + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + } + + #[test] + fn the_service_env_file_names_the_store() { + let temp = tempfile::tempdir().unwrap(); + // Absolute on the host running the test (a Windows host has no + // drive-less absolute paths), as it is on the service's host; single + // quotes keep a Windows host's backslashes literal. + let store = temp.path().join("srv").join("plugins"); + for platform in [SetupPlatform::Linux, SetupPlatform::MacOs] { + let context = context(platform, temp.path()); + write_env( + &context, + &format!( + "# MESH_LLM_PLUGIN_DIR=/commented\nRUST_LOG=info\nMESH_LLM_PLUGIN_DIR='{}'\n", + store.display() + ), + ); + assert_eq!(service_plugin_store(&context).unwrap(), Some(store.clone())); + } + } + + #[test] + fn without_a_setting_the_service_uses_the_default_store() { + let temp = tempfile::tempdir().unwrap(); + let context = context(SetupPlatform::Linux, temp.path()); + let default = Some(temp.path().join("home/.mesh-llm/plugins")); + // No service.env yet: setup writes the template later. + assert_eq!(service_plugin_store(&context).unwrap(), default); + // An empty value, as from a line that clears it, is unset. + write_env(&context, "MESH_LLM_PLUGIN_DIR=/old\nMESH_LLM_PLUGIN_DIR=\n"); + assert_eq!(service_plugin_store(&context).unwrap(), default); + } + + /// The service runs in the home directory, so a relative value is a + /// store there, not under the directory setup was started from. + #[test] + fn a_relative_value_names_a_store_in_the_service_home() { + let temp = tempfile::tempdir().unwrap(); + for platform in [SetupPlatform::Linux, SetupPlatform::MacOs] { + let context = context(platform, temp.path()); + write_env(&context, "MESH_LLM_PLUGIN_DIR=plugins\n"); + assert_eq!( + service_plugin_store(&context).unwrap(), + Some(temp.path().join("home/plugins")), + "{platform:?}" + ); + } + } + + /// macOS sources the file with bash (`export` plus any whitespace); + /// systemd has no `export` and reads that line as another variable. + #[test] + fn export_is_read_as_the_platform_reads_it() { + let temp = tempfile::tempdir().unwrap(); + let store = temp.path().join("srv").join("plugins"); + let line = format!("export\tMESH_LLM_PLUGIN_DIR='{}'\n", store.display()); + let mac = context(SetupPlatform::MacOs, temp.path()); + write_env(&mac, &line); + assert_eq!(service_plugin_store(&mac).unwrap(), Some(store)); + let linux = context(SetupPlatform::Linux, temp.path()); + write_env(&linux, &line); + assert_eq!( + service_plugin_store(&linux).unwrap(), + Some(temp.path().join("home/.mesh-llm/plugins")) + ); + } + + #[test] + fn windows_uses_the_invoking_store() { + let temp = tempfile::tempdir().unwrap(); + let context = context(SetupPlatform::Windows, temp.path()); + assert_eq!(service_plugin_store(&context).unwrap(), None); + } + + #[test] + fn env_file_values_parse_as_the_service_reads_them() { + for platform in [SetupPlatform::Linux, SetupPlatform::MacOs] { + let parse = |contents| plugin_dir_from_env_file(contents, platform).unwrap(); + // `export` is bash's, so only the macOS runner reads it. + assert_eq!( + parse("export MESH_LLM_PLUGIN_DIR='/a b'\n"), + (platform == SetupPlatform::MacOs).then(|| PathBuf::from("/a b")) + ); + assert_eq!( + parse(" MESH_LLM_PLUGIN_DIR=/x\nOTHER=/y\n"), + Some(PathBuf::from("/x")) + ); + assert_eq!(parse("MESH_LLM_PLUGIN_DIRS=/y\n"), None); + // Single quotes keep everything literal for both readers. + assert_eq!( + parse("MESH_LLM_PLUGIN_DIR='$HOME/p'\n"), + Some(PathBuf::from("$HOME/p")) + ); + // Both readers process backslash escapes. + assert!(plugin_dir_from_env_file("MESH_LLM_PLUGIN_DIR=/a\\ b\n", platform).is_err()); + } + } + + /// systemd keeps `$` and `~` literally; the macOS runner's bash expands + /// them, so setup reports the value instead of installing elsewhere. + #[test] + fn values_the_macos_runner_expands_are_reported() { + for contents in [ + "MESH_LLM_PLUGIN_DIR=\"$HOME/custom-plugins\"\n", + "MESH_LLM_PLUGIN_DIR=${HOME}/p\n", + "MESH_LLM_PLUGIN_DIR=`pwd`/p\n", + "MESH_LLM_PLUGIN_DIR=~/p\n", + ] { + let error = plugin_dir_from_env_file(contents, SetupPlatform::MacOs).unwrap_err(); + assert!( + error.to_string().contains("absolute path"), + "{contents}: {error}" + ); + } + // Mixed quoting: bash reads `/tmp//plugins`, so neither the + // outer quotes nor the text between them is the value. + for platform in [SetupPlatform::Linux, SetupPlatform::MacOs] { + for contents in [ + "MESH_LLM_PLUGIN_DIR='/tmp/'\"$USER\"'/plugins'\n", + "MESH_LLM_PLUGIN_DIR=\"/tmp/\"'x'\"/p\"\n", + "MESH_LLM_PLUGIN_DIR=/tmp/'x'/p\n", + "MESH_LLM_PLUGIN_DIR=/a b\n", + "MESH_LLM_PLUGIN_DIR=/a;b\n", + ] { + assert!( + plugin_dir_from_env_file(contents, platform).is_err(), + "{platform:?}: {contents}" + ); + } + } + assert_eq!( + plugin_dir_from_env_file("MESH_LLM_PLUGIN_DIR=\"$HOME/p\"\n", SetupPlatform::Linux) + .unwrap(), + Some(PathBuf::from("$HOME/p")) + ); + assert_eq!( + plugin_dir_from_env_file("MESH_LLM_PLUGIN_DIR=\"~/p\"\n", SetupPlatform::MacOs) + .unwrap(), + Some(PathBuf::from("~/p")) + ); + } + + #[test] + fn an_unreadable_value_fails_the_lookup() { + let temp = tempfile::tempdir().unwrap(); + let context = context(SetupPlatform::MacOs, temp.path()); + write_env(&context, "MESH_LLM_PLUGIN_DIR=$HOME/p\n"); + let error = format!("{:#}", service_plugin_store(&context).unwrap_err()); + assert!(error.contains("service.env"), "{error}"); + } +} diff --git a/mesh/crates/mesh-llm-commands/src/setup/summary.rs b/mesh/crates/mesh-llm-commands/src/setup/summary.rs index c3e1fa4b62..2d78e0fa64 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/summary.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/summary.rs @@ -1,6 +1,7 @@ use super::SetupPlan; use super::command::{CliSetupActions, SetupServiceOutcome}; use super::service::ServiceInstallStatus; +use crate::plugin_sets::SetupPluginsOutcome; use crate::runtime_native::{ SetupNativeRuntimeOutcome, SetupNativeRuntimePruneResult, SetupNativeRuntimeStatus, }; @@ -53,6 +54,7 @@ pub(crate) fn print_setup_summary(plan: &SetupPlan, actions: &CliSetupActions<'_ if verbose { let _ = writeln!(err, "Setup summary"); let _ = writeln!(err, "- Runtime: {}", runtime_summary(plan, actions)); + let _ = writeln!(err, "- Plugins: {}", plugins_summary(plan, actions)); let _ = writeln!(err, "- Service: {}", service_summary(plan, actions)); let _ = writeln!( err, @@ -65,6 +67,7 @@ pub(crate) fn print_setup_summary(plan: &SetupPlan, actions: &CliSetupActions<'_ let _ = writeln!(err, "{} Mesh setup complete", style_ok("✓")); let _ = writeln!(err, " Runtime {}", runtime_brief(plan, actions)); + let _ = writeln!(err, " Plugins {}", plugins_summary(plan, actions)); let _ = writeln!(err, " Service {}", service_brief(plan, actions)); if let Some(github) = github_brief(actions) { let _ = writeln!(err, " GitHub star {github}"); @@ -72,6 +75,53 @@ pub(crate) fn print_setup_summary(plan: &SetupPlan, actions: &CliSetupActions<'_ let _ = writeln!(err, " Next {}", next_step(actions)); } +/// One line for the plugin step: what landed, or why nothing did. +fn plugins_summary(plan: &SetupPlan, actions: &CliSetupActions<'_>) -> String { + plugins_line(plan.plugins, &actions.plugins_outcome) +} + +fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> String { + match (plan, outcome) { + (super::SetupPluginsPlan::Skip, _) => "skipped by --skip-plugin-install".to_string(), + (_, SetupPluginsOutcome::NotRequested) => "not recorded".to_string(), + (_, SetupPluginsOutcome::AlreadyOffered) => { + "recommended set already offered for this plugin store; plugins left as they are" + .to_string() + } + (_, SetupPluginsOutcome::Unavailable(_)) => { + "not installed; see the warning above".to_string() + } + ( + _, + SetupPluginsOutcome::Finished { + installed, + unavailable, + failed, + .. + }, + ) => { + let mut parts = Vec::new(); + if !installed.is_empty() { + parts.push(format!("installed: {}", installed.join(", "))); + } + if !failed.is_empty() { + parts.push(format!("{} failed; see the warning above", failed.len())); + } + if !unavailable.is_empty() { + parts.push(format!( + "{} not available on this platform; see the warning above", + unavailable.len() + )); + } + if parts.is_empty() { + "already installed".to_string() + } else { + parts.join("; ") + } + } + } +} + /// What to run after setup. An installed service runs `serve` on the default /// ports, now or once started, so another `serve` there would fail: point at /// starting the service and loading a model into its node instead. @@ -363,4 +413,43 @@ mod tests { Some("skipped; gh not authenticated".to_string()) ); } + + #[test] + fn plugins_line_says_what_landed_and_what_did_not() { + use super::super::SetupPluginsPlan::{InstallDefaultSet, Skip}; + let finished = + |installed: &[&str], unavailable: usize, failed: usize| SetupPluginsOutcome::Finished { + installed: installed.iter().map(|name| name.to_string()).collect(), + unavailable: vec![("x".to_string(), "no release".to_string()); unavailable], + failed: vec![("y".to_string(), "boom".to_string()); failed], + record_error: None, + }; + assert_eq!( + plugins_line(Skip, &SetupPluginsOutcome::NotRequested), + "skipped by --skip-plugin-install" + ); + assert_eq!( + plugins_line(InstallDefaultSet, &finished(&["capsules"], 0, 0)), + "installed: capsules" + ); + assert_eq!( + plugins_line(InstallDefaultSet, &finished(&[], 2, 0)), + "2 not available on this platform; see the warning above" + ); + assert_eq!( + plugins_line(InstallDefaultSet, &finished(&["capsules"], 0, 1)), + "installed: capsules; 1 failed; see the warning above" + ); + assert_eq!( + plugins_line(InstallDefaultSet, &finished(&[], 0, 0)), + "already installed" + ); + assert_eq!( + plugins_line( + InstallDefaultSet, + &SetupPluginsOutcome::Unavailable("offline".to_string()) + ), + "not installed; see the warning above" + ); + } } diff --git a/mesh/crates/mesh-llm-commands/src/setup/tests.rs b/mesh/crates/mesh-llm-commands/src/setup/tests.rs index f8bd9e2612..85f461644e 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/tests.rs @@ -1,3 +1,4 @@ +use super::SetupPluginStore; use super::{ SetupConfirmPrompt, SetupEnvironment, SetupGitHubStarPlan, SetupGitHubStarSkipReason, SetupOptions, SetupPlatform, SetupPrompter, SetupRuntimePlan, SetupServicePlan, SetupStep, @@ -46,6 +47,7 @@ fn interactive_unix_enter_accepts_default_yes_service_prompt() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins(SetupPluginStore::Service), SetupStep::InstallService, ] ); @@ -66,7 +68,11 @@ fn interactive_unix_explicit_no_skips_service_prompt() { assert_eq!(plan.service, SetupServicePlan::Skip); assert_eq!( plan.core_steps, - vec![SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes] + vec![ + SetupStep::InstallRuntime, + SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), + ] ); assert_eq!(prompter.prompts.len(), 1); } @@ -95,6 +101,7 @@ fn non_interactive_unix_never_prompts_and_prints_service_guidance() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), SetupStep::PrintServiceGuidance, ] ); @@ -186,7 +193,13 @@ fn skip_runtime_omits_install_and_prune_steps() { let plan = plan_setup(options, environment, &mut prompter).expect("plan should succeed"); assert_eq!(plan.runtime, SetupRuntimePlan::Skip); - assert_eq!(plan.core_steps, vec![SetupStep::InstallService]); + assert_eq!( + plan.core_steps, + vec![ + SetupStep::InstallPlugins(SetupPluginStore::Service), + SetupStep::InstallService + ] + ); } #[test] @@ -233,7 +246,94 @@ fn yes_and_no_service_keeps_explicit_service_skip_without_prompt() { ); assert_eq!( plan.core_steps, - vec![SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes] + vec![ + SetupStep::InstallRuntime, + SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), + ] ); assert!(prompter.prompts.is_empty()); } + +fn plugin_steps(options: SetupOptions, interactive: bool) -> (Vec, usize) { + let mut prompter = FakePrompter::default(); + let plan = plan_setup( + options, + SetupEnvironment { + platform: SetupPlatform::Linux, + interactive, + }, + &mut prompter, + ) + .expect("setup plan"); + (plan.core_steps, prompter.prompts.len()) +} + +/// The recommended set installs by default, attended or not, and never asks. +#[test] +fn the_default_plugin_set_installs_without_a_prompt_in_every_mode() { + let base = SetupOptions { + skip_runtime: true, + no_service: true, + ..SetupOptions::default() + }; + for (options, interactive) in [ + (base, true), + (base, false), + ( + SetupOptions { + no_interactive: true, + ..base + }, + true, + ), + (SetupOptions { yes: true, ..base }, true), + ] { + let (steps, prompts) = plugin_steps(options, interactive); + assert_eq!( + steps, + vec![SetupStep::InstallPlugins(SetupPluginStore::Invoking)], + "{options:?}" + ); + assert_eq!(prompts, 0, "{options:?}"); + } +} + +#[test] +fn skip_plugin_install_opts_out_in_every_mode() { + let base = SetupOptions { + skip_runtime: true, + no_service: true, + skip_plugin_install: true, + ..SetupOptions::default() + }; + for (options, interactive) in [ + (base, true), + (base, false), + (SetupOptions { yes: true, ..base }, false), + ] { + let (steps, _) = plugin_steps(options, interactive); + assert!(steps.is_empty(), "{options:?}"); + } +} + +/// Plugins land before the service starts, so its node finds them, and +/// skipping the runtime does not skip them. +#[test] +fn plugins_install_before_the_service_and_independently_of_the_runtime() { + let (steps, _) = plugin_steps( + SetupOptions { + service: true, + skip_runtime: true, + ..SetupOptions::default() + }, + true, + ); + assert_eq!( + steps, + vec![ + SetupStep::InstallPlugins(SetupPluginStore::Service), + SetupStep::InstallService + ] + ); +} diff --git a/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/plugins_benchmark.rs b/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/plugins_benchmark.rs index 17d6756fe1..df326e2a7c 100644 --- a/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/plugins_benchmark.rs +++ b/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/plugins_benchmark.rs @@ -1,6 +1,12 @@ use super::{Descriptor, NONE, REDACTED_NAME, RawKind, descriptor, descriptor_with_conflicts}; -const PLUGIN_INSTALL_CONFLICTS: &[&[&str]] = &[&["reference", "--archive"]]; +const PLUGIN_INSTALL_CONFLICTS: &[&[&str]] = &[ + &["reference", "--archive"], + &["reference", "--set"], + &["--set", "--archive"], + &["--set", "--name"], + &["--set", "--version"], +]; const TUNE_FLAGS: &[&str] = &[ "--json", "--no-speculative-tune", @@ -25,7 +31,7 @@ pub(super) const PLUGIN_DESCRIPTORS: &[Descriptor] = &[ descriptor_with_conflicts( &["mesh-llm", "plugins", "install"], NONE, - &["reference", "--archive", "--name", "--version"], + &["reference", "--set", "--archive", "--name", "--version"], PLUGIN_INSTALL_CONFLICTS, false, RawKind::None, diff --git a/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/top_level.rs b/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/top_level.rs index 609a8b9014..a295f4e5d1 100644 --- a/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/top_level.rs +++ b/mesh/crates/mesh-llm-events/src/command_summary_grammar/descriptors/top_level.rs @@ -8,6 +8,7 @@ const SETUP_FLAGS: &[&str] = &[ "--service", "--no-service", "--skip-runtime", + "--skip-plugin-install", "--verbose", ]; const UNINSTALL_FLAGS: &[&str] = &[ diff --git a/mesh/crates/mesh-llm-events/src/command_summary_grammar/vocabulary.rs b/mesh/crates/mesh-llm-events/src/command_summary_grammar/vocabulary.rs index e5d0b35ac2..1418764609 100644 --- a/mesh/crates/mesh-llm-events/src/command_summary_grammar/vocabulary.rs +++ b/mesh/crates/mesh-llm-events/src/command_summary_grammar/vocabulary.rs @@ -87,6 +87,7 @@ pub(super) fn is_boolean_option(token: &str) -> bool { | "--service" | "--no-service" | "--skip-runtime" + | "--skip-plugin-install" | "--verbose" | "--dry-run" | "--keep-cache" @@ -154,6 +155,7 @@ pub(super) fn is_redacted_marker(token: &str) -> bool { | "--output-dir" | "--agent" | "--archive" + | "--set" | "--quant" | "--target" | "--model-id" diff --git a/mesh/crates/mesh-llm-plugin-manager/Cargo.toml b/mesh/crates/mesh-llm-plugin-manager/Cargo.toml index 14a68df244..4e83c2db9a 100644 --- a/mesh/crates/mesh-llm-plugin-manager/Cargo.toml +++ b/mesh/crates/mesh-llm-plugin-manager/Cargo.toml @@ -17,6 +17,7 @@ anyhow.workspace = true dirs = "6" flate2 = "1" futures-util = "0.3" +fs2 = "0.4" mesh-llm-skills.workspace = true reqwest = { version = "0.13", features = ["json", "stream"] } serde.workspace = true diff --git a/mesh/crates/mesh-llm-plugin-manager/README.md b/mesh/crates/mesh-llm-plugin-manager/README.md index 7799618eb8..bb25afb2fb 100644 --- a/mesh/crates/mesh-llm-plugin-manager/README.md +++ b/mesh/crates/mesh-llm-plugin-manager/README.md @@ -2,7 +2,9 @@ Plugin package management primitives for Mesh LLM. -This crate owns install-reference parsing, platform target naming, native +This crate owns catalog parsing (plugin entries from `plugins.jsonl`, named +plugin sets from `plugin-sets.jsonl`), set resolution and installation +(`sets`), install-reference parsing, platform target naming, native release asset selection, validation of packaged plugin manifest metadata (including local web UI bundle roots and entry scripts), and local installed-plugin metadata. Catalog/GitHub installs use `install_plugin`; diff --git a/mesh/crates/mesh-llm-plugin-manager/src/archive.rs b/mesh/crates/mesh-llm-plugin-manager/src/archive.rs index 6c3ce7fc9a..25739097cf 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/archive.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/archive.rs @@ -95,8 +95,8 @@ pub fn stage_plugin_archive( } /// Stage and commit in one step: extract, validate, and put in place. Product -/// code goes through `install::extract_for_install`, which checks the staged -/// package against the installed plugins before committing it. +/// code stages through `install::stage_for_install` and commits under the +/// plugin store's write lock. #[cfg(test)] pub fn extract_plugin_archive( archive_path: &Path, diff --git a/mesh/crates/mesh-llm-plugin-manager/src/catalog.rs b/mesh/crates/mesh-llm-plugin-manager/src/catalog.rs index 54fafa5430..90838cc7db 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/catalog.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/catalog.rs @@ -91,9 +91,20 @@ pub(crate) fn is_sha256_hex(digest: &str) -> bool { .all(|ch| ch.is_ascii_digit() || ('a'..='f').contains(&ch)) } +/// A named, curated group of catalog plugins, such as `recommended`. A set +/// carries no releases or checksums: each member's own catalog entry pin stays +/// the authority for what installing it means. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CatalogSet { + pub name: String, + pub description: String, + pub plugins: Vec, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct PluginCatalog { entries: Vec, + sets: Vec, } impl PluginCatalog { @@ -113,7 +124,105 @@ impl PluginCatalog { } entries.sort_by(|left, right| left.name.cmp(&right.name)); ensure_unique_names(&entries)?; - Ok(Self { entries }) + Ok(Self { + entries, + sets: Vec::new(), + }) + } + + /// Parse `plugin-sets.jsonl`: named set records only. They live in their + /// own file so a catalog that publishes sets stays parseable for hosts + /// built before sets existed. Whether members exist is checked by + /// [`Self::with_sets`]. + pub fn parse_sets_jsonl(input: &str) -> Result> { + let mut sets = Vec::new(); + for (index, line) in input.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let context = format!("plugin-sets.jsonl line {}", index + 1); + let set: CatalogSet = serde_json::from_str(line).with_context(|| context.clone())?; + validate_set(&set).with_context(|| context)?; + sets.push(set); + } + sets.sort_by(|left, right| left.name.cmp(&right.name)); + for pair in sets.windows(2) { + if pair[0].name == pair[1].name { + bail!("duplicate plugin set '{}'", pair[0].name); + } + } + Ok(sets) + } + + /// Attach named sets, refusing sets that name a plugin this catalog does + /// not list. + pub fn with_sets(mut self, sets: Vec) -> Result { + for set in &sets { + for member in &set.plugins { + if self.find_exact(member).is_none() { + bail!( + "plugin set '{}' names '{member}', which is not in the plugin catalog", + set.name + ); + } + } + } + self.sets = sets; + Ok(self) + } + + /// Fetch the plugin entries, then the sets from `sets_url`. Anything wrong + /// on the sets side (absent, unreachable, malformed, naming unknown + /// plugins) yields a catalog with no sets and the reason: a broken sets + /// file is never a broken plugin catalog. + pub async fn fetch_with_sets( + client: &Client, + plugins_url: &str, + sets_url: Option<&str>, + ) -> Result<(Self, Option)> { + let catalog = Self::fetch(client, plugins_url).await?; + let Some(sets_url) = sets_url else { + return Ok(( + catalog, + Some(format!( + "no plugin-sets.jsonl beside the catalog URL {plugins_url}" + )), + )); + }; + match Self::fetch_sets(client, sets_url).await { + Ok(sets) => match catalog.clone().with_sets(sets) { + Ok(with_sets) => Ok((with_sets, None)), + Err(error) => Ok((catalog, Some(format!("{error:#}")))), + }, + Err(error) => Ok((catalog, Some(format!("{error:#}")))), + } + } + + async fn fetch_sets(client: &Client, sets_url: &str) -> Result> { + let response = client + .get(sets_url) + .header(reqwest::header::USER_AGENT, crate::github::USER_AGENT) + .send() + .await + .with_context(|| format!("fetch plugin sets {sets_url}"))?; + let status = response.status(); + if !status.is_success() { + bail!("plugin sets request failed: {status} {sets_url}"); + } + let body = response + .text() + .await + .with_context(|| format!("read plugin sets {sets_url}"))?; + Self::parse_sets_jsonl(&body) + } + + pub fn sets(&self) -> &[CatalogSet] { + &self.sets + } + + pub fn find_set(&self, name: &str) -> Option<&CatalogSet> { + self.sets.iter().find(|set| set.name == name) } pub async fn fetch(client: &Client, url: &str) -> Result { @@ -158,6 +267,29 @@ impl PluginCatalog { } } +/// Where the sets for the catalog at `catalog_url` live: the same location +/// with the final `plugins.jsonl` replaced by `plugin-sets.jsonl`. `None` for +/// a catalog URL that does not end that way (a custom catalog), which has no +/// sibling file by convention. +pub fn sets_url_for(catalog_url: &str) -> Option { + catalog_url + .strip_suffix("/plugins.jsonl") + .map(|base| format!("{base}/plugin-sets.jsonl")) +} + +fn validate_set(set: &CatalogSet) -> Result<()> { + if set.name.trim().is_empty() { + bail!("plugin set has an empty name"); + } + let mut seen = std::collections::BTreeSet::new(); + for member in &set.plugins { + if !seen.insert(member.as_str()) { + bail!("plugin set '{}' lists '{member}' twice", set.name); + } + } + Ok(()) +} + fn ensure_unique_names(entries: &[CatalogEntry]) -> Result<()> { for pair in entries.windows(2) { if pair[0].name == pair[1].name { @@ -278,4 +410,78 @@ mod tests { .unwrap_err(); assert!(err.to_string().contains("duplicate")); } + + const SET_ENTRIES: &str = r#"{"name":"capsules","description":"Audit records","github_url":"https://github.com/Mesh-LLM/capsules","author_email":"m@meshllm.cloud","author_name":"Mesh LLM"} +{"name":"notes","description":"Team notes","github_url":"https://github.com/acme/notes","author_email":"dev@example.com","author_name":"Acme"}"#; + + #[test] + fn parses_sets_and_attaches_them_to_the_catalog() { + let sets = PluginCatalog::parse_sets_jsonl( + r#"{"name":"recommended","description":"Start here","plugins":["capsules"]} +{"name":"extras","description":"More","plugins":["notes","capsules"]} +"#, + ) + .unwrap(); + let catalog = PluginCatalog::parse_jsonl(SET_ENTRIES) + .unwrap() + .with_sets(sets) + .unwrap(); + assert_eq!( + catalog + .sets() + .iter() + .map(|s| s.name.as_str()) + .collect::>(), + ["extras", "recommended"] + ); + assert_eq!( + catalog.find_set("recommended").unwrap().plugins, + ["capsules"] + ); + assert!(catalog.find_set("missing").is_none()); + } + + #[test] + fn rejects_invalid_sets() { + let duplicate_name = PluginCatalog::parse_sets_jsonl( + "{\"name\":\"a\",\"description\":\"\",\"plugins\":[]}\n{\"name\":\"a\",\"description\":\"\",\"plugins\":[]}", + ) + .unwrap_err(); + assert!(duplicate_name.to_string().contains("duplicate plugin set")); + + let duplicate_member = + PluginCatalog::parse_sets_jsonl(r#"{"name":"a","description":"","plugins":["x","x"]}"#) + .unwrap_err(); + assert!(format!("{duplicate_member:#}").contains("twice")); + + let unknown_member = PluginCatalog::parse_jsonl(SET_ENTRIES) + .unwrap() + .with_sets( + PluginCatalog::parse_sets_jsonl( + r#"{"name":"a","description":"","plugins":["ghost"]}"#, + ) + .unwrap(), + ) + .unwrap_err(); + assert!( + unknown_member + .to_string() + .contains("not in the plugin catalog") + ); + } + + #[test] + fn sets_live_beside_the_default_catalog_file_only() { + assert_eq!( + sets_url_for( + "https://huggingface.co/datasets/meshllm/plugin-catalog/resolve/main/plugins.jsonl" + ) + .as_deref(), + Some( + "https://huggingface.co/datasets/meshllm/plugin-catalog/resolve/main/plugin-sets.jsonl" + ) + ); + assert_eq!(sets_url_for("http://127.0.0.1:1/custom-catalog.json"), None); + assert_eq!(sets_url_for("plugins.jsonl"), None); + } } diff --git a/mesh/crates/mesh-llm-plugin-manager/src/install.rs b/mesh/crates/mesh-llm-plugin-manager/src/install.rs index ed2a4a176a..919485f112 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/install.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/install.rs @@ -6,8 +6,8 @@ use reqwest::Client; use sha2::Digest; use crate::{ - archive::{ExtractedPluginArchive, stage_plugin_archive}, - catalog::PluginCatalog, + archive::{ExtractedPluginArchive, StagedPluginArchive, stage_plugin_archive}, + catalog::{CatalogEntry, PluginCatalog}, catalog_pin::CatalogPin, github::{GitHubReleaseAsset, GitHubReleaseClient}, infer_plugin_asset, select_plugin_asset, @@ -114,7 +114,7 @@ pub async fn install_plugin( ) -> Result { let parsed = parse_install_ref(reference)?; let resolved = resolve_install_source(parsed, options, progress).await?; - install_resolved_plugin(resolved, options, progress, None).await + install_resolved_plugin(resolved, options, progress, None, CommitMode::Replace).await } pub fn install_plugin_archive( @@ -146,8 +146,12 @@ pub fn install_plugin_archive( asset: asset_name.clone(), }); let store = PluginStore::new(&options.store_root); + let staged = stage_for_install(&archive_path, archive_ext, name, options)?; + // The reporter runs after the lock is released: the lock is not + // reentrant, and a reporter may change the store itself. + let lock = store.lock_writes()?; let current = store.load_optional(name)?; - let extracted = extract_for_install(&archive_path, archive_ext, name, options)?; + let extracted = staged.commit()?; let metadata = InstalledPluginMetadata { name: name.to_string(), source_repository: format!("local:{}", archive_path.display()), @@ -163,6 +167,7 @@ pub fn install_plugin_archive( verified_sha256: None, }; store.save(&metadata)?; + drop(lock); progress.report(PluginProgressEvent::Installed { installed: Box::new(metadata.clone()), }); @@ -174,21 +179,21 @@ pub fn install_plugin_archive( /// Every install path extracts through here, so the executable it checks is /// named for `options.target`, as `InstalledPluginMetadata::executable_path` -/// names the one the host launches. -pub(crate) fn extract_for_install( +/// names the one the host launches. The caller commits the staged package +/// under the store's write lock. +pub(crate) fn stage_for_install( archive_path: &std::path::Path, archive_ext: ArchiveExt, name: &str, options: &PluginInstallOptions, -) -> Result { - let staged = stage_plugin_archive( +) -> Result { + stage_plugin_archive( archive_path, archive_ext, options.target.executable_suffix(), name, &options.install_root, - )?; - staged.commit() + ) } fn local_archive_ext(path: &std::path::Path) -> Result { @@ -219,7 +224,14 @@ pub async fn update_plugin( version: None, pin: None, }; - install_resolved_plugin(resolved, options, progress, Some(current)).await + install_resolved_plugin( + resolved, + options, + progress, + Some(current), + CommitMode::Replace, + ) + .await } struct ResolvedInstallSource { @@ -248,15 +260,7 @@ async fn resolve_install_source( let entry = catalog .find_exact(&name) .with_context(|| format!("plugin '{name}' was not found in the catalog"))?; - let source = GitHubPluginSource::from_url(&entry.github_url)?; - let pin = CatalogPin::for_entry(entry, options.target.triple())?; - pin.ensure_matches_request(version.as_ref())?; - Ok(ResolvedInstallSource { - plugin_name: entry.name.clone(), - source, - version: Some(pin.version().clone()), - pin: Some(pin), - }) + resolve_catalog_entry(entry, version.as_ref(), options) } PluginInstallRef::GitHub { source, version } => Ok(ResolvedInstallSource { plugin_name: source.plugin_name().to_string(), @@ -267,11 +271,91 @@ async fn resolve_install_source( } } +fn resolve_catalog_entry( + entry: &CatalogEntry, + requested: Option<&PluginVersion>, + options: &PluginInstallOptions, +) -> Result { + let source = GitHubPluginSource::from_url(&entry.github_url)?; + let pin = CatalogPin::for_entry(entry, options.target.triple())?; + pin.ensure_matches_request(requested)?; + Ok(ResolvedInstallSource { + plugin_name: entry.name.clone(), + source, + version: Some(pin.version().clone()), + pin: Some(pin), + }) +} + +/// Install `entry` at the release the catalog snapshot it came from pins, +/// without fetching the catalog again, only if it is still not installed +/// when the package is put in place. A caller that resolved several entries +/// from one snapshot installs each through this, so a catalog that changes +/// mid-operation cannot change what the operation installs. A plugin that +/// someone else installed while this one downloaded is left exactly as it +/// is, and the outcome is that plugin with `changed: false`. +pub async fn install_catalog_entry( + entry: &CatalogEntry, + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, +) -> Result { + let resolved = resolve_catalog_entry(entry, None, options)?; + install_resolved_plugin(resolved, options, progress, None, CommitMode::CreateOnly).await +} + +/// `install_catalog_entry` for setup's offer of `set`: also leaves the plugin +/// out when the set's offer record lists it when the package is put in place +/// (checked under the same lock as the write). Another setup that finished +/// while this one downloaded recorded it, and an operator who removed it +/// since must not get it back. Fails with [`OfferedMeanwhile`] then. +pub async fn install_catalog_entry_unless_offered( + entry: &CatalogEntry, + set: &str, + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, +) -> Result { + let resolved = resolve_catalog_entry(entry, None, options)?; + install_resolved_plugin( + resolved, + options, + progress, + None, + CommitMode::CreateUnlessOffered { set }, + ) + .await +} + +/// The set offer record already lists the plugin: nothing was installed. +#[derive(Debug, PartialEq, Eq)] +pub struct OfferedMeanwhile; + +impl std::fmt::Display for OfferedMeanwhile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("another setup run offered this plugin while it downloaded") + } +} + +impl std::error::Error for OfferedMeanwhile {} + +/// Whether an install may replace a plugin that is installed when its +/// package is put in place. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CommitMode<'a> { + Replace, + /// Keep a plugin that appeared since the install started. + CreateOnly, + /// `CreateOnly`, and leave out a plugin the offer record of this set lists. + CreateUnlessOffered { + set: &'a str, + }, +} + async fn install_resolved_plugin( resolved: ResolvedInstallSource, options: &PluginInstallOptions, progress: &mut impl PluginProgressReporter, current: Option, + mode: CommitMode<'_>, ) -> Result { let release_client = GitHubReleaseClient::new()?; progress.report(PluginProgressEvent::ResolvingGitHub { @@ -342,24 +426,41 @@ async fn install_resolved_plugin( progress.report(PluginProgressEvent::Extracting { asset: asset.name.clone(), }); - let extracted = extract_for_install( + let staged = stage_for_install( &archive_path, options.target.archive_ext(), &resolved.plugin_name, options, - )?; + ); let _ = fs::remove_file(&archive_path); + let staged = staged?; - let metadata = build_installed_metadata( - &resolved, - &release.tag_name, - asset, - &options.target, - extracted, - current.as_ref(), - Some(verified_sha256), - ); - PluginStore::new(&options.store_root).save(&metadata)?; + let store = PluginStore::new(&options.store_root); + let committed = commit_staged(&store, staged, &resolved.plugin_name, mode, |extracted| { + build_installed_metadata( + &resolved, + &release.tag_name, + asset, + &options.target, + extracted, + current.as_ref(), + Some(verified_sha256), + ) + })?; + let metadata = match committed { + Committed::Placed(metadata) => metadata, + Committed::Offered => return Err(OfferedMeanwhile.into()), + Committed::Kept(present) => { + progress.report(PluginProgressEvent::AlreadyCurrent { + name: present.name.clone(), + version: present.installed_version.clone(), + }); + return Ok(InstallOutcome { + metadata: present, + changed: false, + }); + } + }; if let Some(current) = current { progress.report(PluginProgressEvent::Updated { @@ -379,6 +480,43 @@ async fn install_resolved_plugin( }) } +#[derive(Debug, PartialEq)] +enum Committed { + /// The staged package is in place and recorded with this metadata. + Placed(InstalledPluginMetadata), + /// `CommitMode::CreateOnly` found this plugin installed and left it. + Kept(InstalledPluginMetadata), + /// `CommitMode::CreateUnlessOffered` found the plugin offered and left it out. + Offered, +} + +/// Put `staged` in place and record it, under the store's write lock, so no +/// other writer changes `name` between the check and the write. +fn commit_staged( + store: &PluginStore, + staged: StagedPluginArchive, + name: &str, + mode: CommitMode<'_>, + metadata_for: impl FnOnce(ExtractedPluginArchive) -> InstalledPluginMetadata, +) -> Result { + let _lock = store.lock_writes()?; + if let CommitMode::CreateUnlessOffered { set } = mode + && crate::sets::offered_members(store.root(), set)? + .iter() + .any(|offered| offered == name) + { + return Ok(Committed::Offered); + } + if mode != CommitMode::Replace + && let Some(present) = store.load_optional(name)? + { + return Ok(Committed::Kept(present)); + } + let metadata = metadata_for(staged.commit()?); + store.save(&metadata)?; + Ok(Committed::Placed(metadata)) +} + fn build_installed_metadata( resolved: &ResolvedInstallSource, release_tag: &str, @@ -995,6 +1133,122 @@ mod tests { } } + /// A set member staged while the operator installed the same plugin: + /// the operator's package and metadata stay as they are. + #[test] + fn a_create_only_commit_keeps_a_plugin_installed_meanwhile() { + let temp = TempDir::new().unwrap(); + let options = options_for(temp.path(), "linux", "x86_64"); + let archive_path = temp.path().join("demo.tar.gz"); + write_archive_with(&archive_path, "demo"); + let staged = stage_for_install(&archive_path, ArchiveExt::TarGz, "demo", &options).unwrap(); + + // The operator's install lands, disabled, while the member was staged. + install_plugin_archive("demo", "9.9.9", &archive_path, &options, &mut |_| {}).unwrap(); + let store = PluginStore::new(&options.store_root); + let theirs = store.set_enabled("demo", false).unwrap(); + std::fs::write(theirs.install_path.join("operator-marker"), b"").unwrap(); + + let committed = commit_staged(&store, staged, "demo", CommitMode::CreateOnly, |_| { + panic!("a create-only commit must not build metadata over an installed plugin") + }) + .unwrap(); + assert_eq!(committed, Committed::Kept(theirs.clone())); + assert_eq!(store.load("demo").unwrap(), theirs); + assert!(theirs.install_path.join("operator-marker").is_file()); + } + + /// A plugin the operator removed after another setup offered it is not + /// put back by a setup that was downloading it meanwhile. + #[test] + fn a_commit_unless_offered_leaves_out_a_plugin_offered_meanwhile() { + let temp = TempDir::new().unwrap(); + let options = options_for(temp.path(), "linux", "x86_64"); + let archive_path = temp.path().join("demo.tar.gz"); + write_archive_with(&archive_path, "demo"); + let staged = stage_for_install(&archive_path, ArchiveExt::TarGz, "demo", &options).unwrap(); + crate::sets::record_set_offer( + &options.store_root, + "recommended", + crate::sets::SetOffer { + complete: true, + snapshot: vec!["demo".to_string()], + members: vec!["demo".to_string()], + }, + ) + .unwrap(); + let store = PluginStore::new(&options.store_root); + let mode = CommitMode::CreateUnlessOffered { set: "recommended" }; + let committed = commit_staged(&store, staged, "demo", mode, |_| { + panic!("an offered plugin is not installed") + }) + .unwrap(); + assert_eq!(committed, Committed::Offered); + assert!(store.load_optional("demo").unwrap().is_none()); + } + + /// The lock is not reentrant, so a reporter that changes the store when + /// told a plugin is installed must not run while the install holds it. + #[test] + fn a_reporter_can_change_the_store_when_told_a_plugin_is_installed() { + let temp = TempDir::new().unwrap(); + let options = options_for(temp.path(), "linux", "x86_64"); + let archive_path = temp.path().join("demo.tar.gz"); + write_archive_with(&archive_path, "demo"); + let (done, finished) = std::sync::mpsc::channel(); + let install_options = options.clone(); + std::thread::spawn(move || { + let store = PluginStore::new(&install_options.store_root); + let result = install_plugin_archive( + "demo", + "9.9.9", + &archive_path, + &install_options, + &mut |event| { + if let PluginProgressEvent::Installed { installed } = event { + store.set_enabled(&installed.name, false).unwrap(); + } + }, + ); + let _ = done.send(result.map(|outcome| outcome.changed)); + }); + let changed = finished + .recv_timeout(std::time::Duration::from_secs(120)) + .expect("the install returns while its reporter changes the store") + .unwrap(); + assert!(changed); + let store = PluginStore::new(&options.store_root); + assert!(!store.load("demo").unwrap().enabled); + } + + #[test] + fn a_replace_commit_puts_the_staged_package_in_place() { + let temp = TempDir::new().unwrap(); + let options = options_for(temp.path(), "linux", "x86_64"); + let archive_path = temp.path().join("demo.tar.gz"); + write_archive_with(&archive_path, "demo"); + let theirs = + install_plugin_archive("demo", "9.9.9", &archive_path, &options, &mut |_| {}).unwrap(); + std::fs::write(theirs.metadata.install_path.join("old-marker"), b"").unwrap(); + let staged = stage_for_install(&archive_path, ArchiveExt::TarGz, "demo", &options).unwrap(); + let store = PluginStore::new(&options.store_root); + + let committed = commit_staged(&store, staged, "demo", CommitMode::Replace, |extracted| { + InstalledPluginMetadata { + installed_version: "1.0.0".to_string(), + install_path: extracted.install_path, + ..theirs.metadata.clone() + } + }) + .unwrap(); + let Committed::Placed(placed) = committed else { + panic!("a replace commit places the package: {committed:?}"); + }; + assert_eq!(store.load("demo").unwrap(), placed); + assert_eq!(placed.installed_version, "1.0.0"); + assert!(!placed.install_path.join("old-marker").exists()); + } + #[test] fn a_plugin_toml_that_names_another_plugin_is_refused() { let temp = tempfile::tempdir().unwrap(); diff --git a/mesh/crates/mesh-llm-plugin-manager/src/lib.rs b/mesh/crates/mesh-llm-plugin-manager/src/lib.rs index 4673e20778..7a92090ff4 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/lib.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/lib.rs @@ -7,17 +7,18 @@ pub mod install; mod package_identity; mod placement; pub mod plugin_toml; +pub mod sets; pub mod skills; pub mod source_ref; pub mod store; pub mod target; pub use asset::{AssetMatchKind, PluginAsset, infer_plugin_asset, select_plugin_asset}; -pub use catalog::{CatalogEntry, PinnedRelease, PluginCatalog}; +pub use catalog::{CatalogEntry, CatalogSet, PinnedRelease, PluginCatalog}; pub use github::{GitHubRelease, GitHubReleaseAsset, GitHubReleaseClient}; pub use install::{ InstallOutcome, PluginInstallOptions, PluginProgressEvent, PluginProgressReporter, - install_plugin, update_plugin, + install_catalog_entry, install_plugin, update_plugin, }; pub use mesh_llm_skills::{ SkillAgent, SkillInstallAction, SkillInstallReport, SkillInstallStatus, SkillPackage, diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs new file mode 100644 index 0000000000..9517315ee1 --- /dev/null +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -0,0 +1,884 @@ +//! Catalog plugin sets: resolving what a named set means on this machine and +//! installing its members once. +//! +//! A set resolves against one catalog snapshot per operation. Installing a +//! set installs the members that are missing and then stops caring: it does +//! not subscribe the machine to future membership changes, and it never +//! updates, enables or re-enables a plugin that is already installed. +//! Design adapted from the catalog-sets design in Mesh-LLM/mesh-llm#2978. + +use anyhow::{Context, Result}; + +use crate::{ + catalog::{CatalogEntry, PluginCatalog}, + install::{ + InstallOutcome, PluginInstallOptions, PluginProgressReporter, install_catalog_entry, + install_catalog_entry_unless_offered, + }, + store::PluginStore, +}; + +/// Whether one set member can be installed on this platform, and why not. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MemberAvailability { + Available, + Unavailable(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SetMember { + pub name: String, + /// The release the catalog pins for this member, when it pins one. + pub version: Option, + pub availability: MemberAvailability, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SetResolution { + pub name: String, + pub description: String, + pub members: Vec, +} + +/// What installing a set did. Every member is attempted, so one failure never +/// hides the others; the caller decides what a partial result means. +#[derive(Debug, Default)] +pub struct SetInstallResult { + pub installed: Vec, + /// `(member, reason)` for members that were attempted and failed. + pub failed: Vec<(String, String)>, + /// Members already installed, left exactly as they are. + pub already_installed: Vec, + /// `(member, reason)` for members this platform cannot install: no catalog + /// entry, release or checksum for it. + pub unavailable: Vec<(String, String)>, + /// Members another setup run offered while this one downloaded them: + /// not installed here, and counted as offered. + pub offered_elsewhere: Vec, +} + +const OFFERED_FILE: &str = "offered-sets.json"; + +/// What setup has already done with one set in this plugin store. A set is offered +/// once: a member the operator later removes is never put back by setup, and +/// members added to the set later are not installed by it either. A member +/// that failed is not recorded, so the next setup retries it. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct SetOffer { + /// True once an offer finished with no failed member: setup then leaves + /// the set alone without reading the catalog. + pub complete: bool, + /// The set's membership when it was first offered. Later runs only + /// retry members of this snapshot, so a member added to the set after the + /// one offer is never installed by setup, even while a failed one retries. + #[serde(default)] + pub snapshot: Vec, + /// Members installed, already present, or unavailable here when offered. + pub members: Vec, +} + +impl SetOffer { + /// The offer after `result`: a member that landed, was already there or + /// has no release here counts as offered; a failed one is not, so the + /// next setup retries it, and the set is complete only when none failed. + /// A snapshot member the set (`set_members`) no longer lists counts as + /// offered: there is nothing left to offer for it. + pub fn after(&self, set_members: &[String], result: &SetInstallResult) -> SetOffer { + let mut members = self.members.clone(); + members.extend(result.installed.iter().map(|o| o.metadata.name.clone())); + members.extend(result.already_installed.iter().cloned()); + members.extend(result.unavailable.iter().map(|(name, _)| name.clone())); + members.extend(result.offered_elsewhere.iter().cloned()); + members.extend( + self.snapshot + .iter() + .filter(|member| !set_members.contains(member)) + .cloned(), + ); + members.sort(); + members.dedup(); + let snapshot = if self.snapshot.is_empty() { + set_members.to_vec() + } else { + self.snapshot.clone() + }; + SetOffer { + complete: result.failed.is_empty(), + snapshot, + members, + } + } + + /// What two runs recorded, together: neither can take back what the + /// other recorded. A member either recorded stays recorded and the first + /// snapshot stays. The merge is complete when a run completed and every + /// member of the kept snapshot is recorded: a run that read another + /// snapshot cannot complete a member it never offered, which the next + /// setup then retries. + fn merged_with(self, other: SetOffer) -> SetOffer { + let mut members = self.members; + members.extend(other.members); + members.sort(); + members.dedup(); + let snapshot = if self.snapshot.is_empty() { + other.snapshot + } else { + self.snapshot + }; + let snapshot_offered = snapshot.iter().all(|member| members.contains(member)); + SetOffer { + complete: (self.complete || other.complete) && snapshot_offered, + snapshot, + members, + } + } +} + +pub fn read_set_offer(store_root: &std::path::Path, set_name: &str) -> Result { + Ok(read_offers(store_root)? + .remove(set_name) + .unwrap_or_default()) +} + +/// The members the record lists as offered for `set_name`. +pub(crate) fn offered_members(store_root: &std::path::Path, set_name: &str) -> Result> { + Ok(read_set_offer(store_root, set_name)?.members) +} + +/// Record `offer` for `set_name`, merged with the record as it is now under +/// the store's write lock: another setup run may have recorded more since +/// this one read it, and what it recorded is kept. +pub fn record_set_offer( + store_root: &std::path::Path, + set_name: &str, + offer: SetOffer, +) -> Result<()> { + let _lock = PluginStore::new(store_root).lock_writes()?; + let mut offers = read_offers(store_root)?; + let merged = match offers.remove(set_name) { + Some(latest) => latest.merged_with(offer), + None => offer, + }; + offers.insert(set_name.to_string(), merged); + let path = store_root.join(OFFERED_FILE); + // Write beside the record and rename over it, so a crash never leaves a + // torn file. + let temp = store_root.join(format!("{OFFERED_FILE}.{}.tmp", std::process::id())); + std::fs::write(&temp, serde_json::to_vec(&offers)?) + .with_context(|| format!("write {}", temp.display()))?; + std::fs::rename(&temp, &path).with_context(|| format!("replace {}", path.display())) +} + +fn read_offers( + store_root: &std::path::Path, +) -> Result> { + let path = store_root.join(OFFERED_FILE); + match std::fs::read(&path) { + // An unreadable record counts as none: the next setup offers the set + // again (members already installed are left alone) instead of warning + // forever about a file only setup writes. + Ok(bytes) => Ok(serde_json::from_slice(&bytes).unwrap_or_default()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Default::default()), + Err(error) => Err(error).with_context(|| format!("read {}", path.display())), + } +} + +impl SetResolution { + /// Keep only the members of the snapshot the set was first offered with. + pub fn only_members(mut self, snapshot: &[String]) -> Self { + self.members + .retain(|member| snapshot.contains(&member.name)); + self + } + + /// Drop the members setup already offered for this plugin store. + pub fn without_members(mut self, offered: &[String]) -> Self { + self.members + .retain(|member| !offered.contains(&member.name)); + self + } +} + +/// Resolve `set_name` from one catalog snapshot for `target`. An unknown set +/// is an error, never an empty resolution. +pub fn resolve_set(catalog: &PluginCatalog, set_name: &str, target: &str) -> Result { + let set = catalog.find_set(set_name).with_context(|| { + let known: Vec<&str> = catalog.sets().iter().map(|set| set.name.as_str()).collect(); + if known.is_empty() { + format!( + "the plugin catalog publishes no plugin set named '{set_name}' (it lists no sets)" + ) + } else { + format!( + "the plugin catalog publishes no plugin set named '{set_name}'; available sets: {}", + known.join(", ") + ) + } + })?; + let members = set + .plugins + .iter() + .map(|member| member_status(catalog.find_exact(member), member, target)) + .collect(); + Ok(SetResolution { + name: set.name.clone(), + description: set.description.clone(), + members, + }) +} + +fn member_status(entry: Option<&CatalogEntry>, name: &str, target: &str) -> SetMember { + let Some(entry) = entry else { + return SetMember { + name: name.to_string(), + version: None, + availability: MemberAvailability::Unavailable("not in the plugin catalog".to_string()), + }; + }; + let availability = match entry.pinned_release(target) { + Ok(_) => MemberAvailability::Available, + Err(error) => MemberAvailability::Unavailable(format!("{error:#}")), + }; + SetMember { + name: entry.name.clone(), + version: entry.version.clone(), + availability, + } +} + +/// Install the members of `resolution` that are available and not yet +/// installed, one at a time through `install_member`, which receives the +/// shared progress reporter. Retrying is safe: members that landed are +/// skipped as already installed. +pub async fn install_set_with

( + resolution: &SetResolution, + store: &PluginStore, + progress: &mut P, + mut install_member: impl AsyncFnMut(&str, &mut P) -> Result, +) -> Result { + let mut result = SetInstallResult::default(); + for member in &resolution.members { + // Installed first: a member installed from an archive has no catalog + // pin, and is still installed. One member's unreadable record fails + // that member only. + match store.load_optional(&member.name) { + Ok(Some(_)) => { + result.already_installed.push(member.name.clone()); + continue; + } + Ok(None) => {} + Err(error) => { + result.failed.push(( + member.name.clone(), + format!("cannot read its installed record: {error:#}"), + )); + continue; + } + } + if let MemberAvailability::Unavailable(reason) = &member.availability { + result + .unavailable + .push((member.name.clone(), reason.clone())); + continue; + } + match install_member(&member.name, progress).await { + // Installed by someone else while this member downloaded: theirs + // is kept, as for a member that was already there. + Ok(outcome) if !outcome.changed => { + result.already_installed.push(member.name.clone()); + } + Ok(outcome) => result.installed.push(outcome), + Err(error) if error.is::() => { + result.offered_elsewhere.push(member.name.clone()); + } + Err(error) => result + .failed + .push((member.name.clone(), format!("{error:#}"))), + } + } + Ok(result) +} + +/// Install a set from one catalog snapshot: every member is installed at the +/// release that snapshot pins. `respect_offer_record` is setup's: a member +/// the offer record lists by commit time is left out (see +/// [`install_catalog_entry_unless_offered`]); `plugins install --set` is an +/// explicit request and ignores the record. +pub async fn install_set( + catalog: &PluginCatalog, + set_name: &str, + offer: &SetOffer, + respect_offer_record: bool, + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, +) -> Result { + let mut resolution = resolve_set(catalog, set_name, options.target.triple())?; + if !offer.snapshot.is_empty() { + resolution = resolution.only_members(&offer.snapshot); + } + let resolution = resolution.without_members(&offer.members); + let store = PluginStore::new(&options.store_root); + install_set_with(&resolution, &store, progress, async |name, progress| { + let entry = catalog + .find_exact(name) + .with_context(|| format!("'{name}' is not in the plugin catalog"))?; + if respect_offer_record { + install_catalog_entry_unless_offered(entry, set_name, options, progress).await + } else { + install_catalog_entry(entry, options, progress).await + } + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::InstalledPluginMetadata; + use anyhow::bail; + use std::{ + io::{BufRead, BufReader, Read, Write}, + net::TcpListener, + path::PathBuf, + thread, + }; + use tempfile::TempDir; + + const TARGET: &str = "x86_64-unknown-linux-gnu"; + const SHA: &str = "abababababababababababababababababababababababababababababababab"; + + fn entry_line(name: &str, pinned: bool) -> String { + let pin = if pinned { + format!(r#","version":"v1.0.0","sha256":{{"{TARGET}":"{SHA}"}}"#) + } else { + String::new() + }; + format!( + r#"{{"name":"{name}","description":"{name} plugin","github_url":"https://github.com/acme/{name}","author_email":"dev@example.com","author_name":"Acme"{pin}}}"# + ) + } + + fn catalog(entries: &[(&str, bool)], sets: &str) -> PluginCatalog { + let body = entries + .iter() + .map(|(name, pinned)| entry_line(name, *pinned)) + .collect::>() + .join("\n"); + PluginCatalog::parse_jsonl(&body) + .unwrap() + .with_sets(PluginCatalog::parse_sets_jsonl(sets).unwrap()) + .unwrap() + } + + const RECOMMENDED: &str = + r#"{"name":"recommended","description":"Start here","plugins":["alpha","beta","gamma"]}"#; + + fn installed(name: &str) -> InstalledPluginMetadata { + InstalledPluginMetadata { + name: name.to_string(), + source_repository: format!("https://github.com/acme/{name}"), + installed_version: "v1.0.0".to_string(), + target_triple: TARGET.to_string(), + downloaded_asset_name: format!("{name}.tar.gz"), + install_path: PathBuf::from("/nonexistent"), + enabled: true, + manifest: None, + last_protocol_version: None, + last_status: None, + last_error: None, + verified_sha256: None, + } + } + + #[test] + fn resolving_reports_availability_per_member() { + let catalog = catalog( + &[("alpha", true), ("beta", false)], + r#"{"name":"recommended","description":"d","plugins":["alpha","beta"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET).unwrap(); + assert_eq!( + resolution.members[0].availability, + MemberAvailability::Available + ); + assert!(matches!( + &resolution.members[1].availability, + MemberAvailability::Unavailable(reason) if reason.contains("pins no version") + )); + let other = resolve_set(&catalog, "recommended", "aarch64-apple-darwin").unwrap(); + assert!(matches!( + &other.members[0].availability, + MemberAvailability::Unavailable(reason) if reason.contains("no sha256") + )); + } + + #[test] + fn an_unknown_set_is_an_error_naming_the_available_ones() { + let catalog = catalog( + &[("alpha", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ); + let error = resolve_set(&catalog, "nope", TARGET) + .unwrap_err() + .to_string(); + assert!( + error.contains("'nope'") && error.contains("recommended"), + "{error}" + ); + let none = PluginCatalog::parse_jsonl(&entry_line("alpha", true)).unwrap(); + let error = resolve_set(&none, "recommended", TARGET) + .unwrap_err() + .to_string(); + assert!(error.contains("lists no sets"), "{error}"); + } + + /// One member fails, one lands, one is unavailable: every member is still + /// attempted, and a retry installs only the member that failed. + #[tokio::test] + async fn a_partial_install_reports_each_member_and_a_retry_skips_what_landed() { + let catalog = catalog( + &[("alpha", true), ("beta", true), ("gamma", false)], + RECOMMENDED, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET).unwrap(); + let temp = TempDir::new().unwrap(); + let store = PluginStore::new(temp.path()); + let mut attempts = Vec::new(); + + let first = install_set_with(&resolution, &store, &mut (), async |name, _| { + attempts.push(name.to_string()); + if name == "beta" { + bail!("download failed"); + } + let metadata = installed(name); + store.save(&metadata)?; + Ok(InstallOutcome { + metadata, + changed: true, + }) + }) + .await + .unwrap(); + assert_eq!(attempts, ["alpha", "beta"]); + assert_eq!(first.installed.len(), 1); + assert_eq!( + first.failed, + [("beta".to_string(), "download failed".to_string())] + ); + assert_eq!(first.unavailable.len(), 1); + assert_eq!(first.unavailable[0].0, "gamma"); + + let mut retried = Vec::new(); + let second = install_set_with(&resolution, &store, &mut (), async |name, _| { + retried.push(name.to_string()); + let metadata = installed(name); + store.save(&metadata)?; + Ok(InstallOutcome { + metadata, + changed: true, + }) + }) + .await + .unwrap(); + assert_eq!(retried, ["beta"]); + assert_eq!(second.already_installed, ["alpha"]); + } + + /// A member installed from an archive has no catalog pin on this platform + /// and is still reported as installed, not unavailable. + #[tokio::test] + async fn an_installed_member_without_a_pin_is_installed_not_unavailable() { + let catalog = catalog( + &[("alpha", false)], + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET).unwrap(); + let temp = TempDir::new().unwrap(); + let store = PluginStore::new(temp.path()); + store.save(&installed("alpha")).unwrap(); + let result = install_set_with(&resolution, &store, &mut (), async |_, _| { + panic!("an installed member is not installed again") + }) + .await + .unwrap(); + assert_eq!(result.already_installed, ["alpha"]); + assert!(result.unavailable.is_empty()); + } + + /// A member another setup run offered while this one downloaded is not + /// installed by this one and counts as offered. + #[tokio::test] + async fn a_member_offered_meanwhile_is_counted_as_offered() { + let catalog = catalog( + &[("alpha", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET).unwrap(); + let temp = TempDir::new().unwrap(); + let store = PluginStore::new(temp.path()); + let result = install_set_with(&resolution, &store, &mut (), async |_, _| { + Err(crate::install::OfferedMeanwhile.into()) + }) + .await + .unwrap(); + assert_eq!(result.offered_elsewhere, ["alpha"]); + assert!(result.failed.is_empty()); + let offer = SetOffer::default().after(&["alpha".to_string()], &result); + assert!(offer.complete && offer.members == ["alpha"]); + } + + /// A corrupt installed record fails that member only; the rest of the set + /// still installs. + #[tokio::test] + async fn an_unreadable_installed_record_does_not_stop_the_other_members() { + let catalog = catalog( + &[("alpha", true), ("beta", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha","beta"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET).unwrap(); + let temp = TempDir::new().unwrap(); + let store = PluginStore::new(temp.path()); + store.save(&installed("alpha")).unwrap(); + let record = std::fs::read_dir(temp.path()) + .unwrap() + .flatten() + .flat_map(|entry| std::fs::read_dir(entry.path()).unwrap().flatten()) + .map(|entry| entry.path()) + .find(|path| path.extension().is_some_and(|ext| ext == "json")) + .expect("alpha's metadata file"); + std::fs::write(&record, "{not json").unwrap(); + + let result = install_set_with(&resolution, &store, &mut (), async |name, _| { + let metadata = installed(name); + Ok(InstallOutcome { + metadata, + changed: true, + }) + }) + .await + .unwrap(); + assert_eq!(result.failed.len(), 1); + assert_eq!(result.failed[0].0, "alpha"); + assert_eq!(result.installed.len(), 1); + assert_eq!(result.installed[0].metadata.name, "beta"); + } + + #[test] + fn a_set_offer_is_recorded_per_set_and_survives() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("plugins"); + assert_eq!( + read_set_offer(&root, "recommended").unwrap(), + SetOffer::default() + ); + let offer = SetOffer { + complete: false, + snapshot: vec!["alpha".to_string(), "beta".to_string()], + members: vec!["alpha".to_string()], + }; + record_set_offer(&root, "recommended", offer.clone()).unwrap(); + record_set_offer( + &root, + "extras", + SetOffer { + complete: true, + snapshot: vec![], + members: vec![], + }, + ) + .unwrap(); + assert_eq!(read_set_offer(&root, "recommended").unwrap(), offer); + assert!(read_set_offer(&root, "extras").unwrap().complete); + assert_eq!(read_set_offer(&root, "other").unwrap(), SetOffer::default()); + // The record is a file in the store root, not a plugin. + assert!(PluginStore::new(&root).list().unwrap().is_empty()); + } + + /// Two setup runs read the same record; the one that finished writes + /// first, the slower partial one second. The record keeps both. + #[test] + fn a_slower_partial_run_cannot_take_back_a_completed_offer() { + let temp = TempDir::new().unwrap(); + let snapshot = vec!["alpha".to_string(), "beta".to_string()]; + let completed = SetOffer { + complete: true, + snapshot: snapshot.clone(), + members: snapshot.clone(), + }; + record_set_offer(temp.path(), "recommended", completed.clone()).unwrap(); + record_set_offer( + temp.path(), + "recommended", + SetOffer { + complete: false, + snapshot: snapshot.clone(), + members: vec!["alpha".to_string()], + }, + ) + .unwrap(); + assert_eq!( + read_set_offer(temp.path(), "recommended").unwrap(), + completed + ); + } + + /// A member another run installed meanwhile is reported as already + /// installed, not as installed by this run. + #[tokio::test] + async fn a_member_installed_meanwhile_counts_as_already_installed() { + let temp = TempDir::new().unwrap(); + let store = PluginStore::new(temp.path()); + let resolution = resolve_set( + &catalog( + &[("alpha", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ), + "recommended", + TARGET, + ) + .unwrap(); + let result = install_set_with(&resolution, &store, &mut (), async |name, _| { + Ok(InstallOutcome { + metadata: installed(name), + changed: false, + }) + }) + .await + .unwrap(); + assert_eq!(result.already_installed, ["alpha"]); + assert!(result.installed.is_empty()); + } + + /// A run that read a different snapshot cannot complete a member of the + /// kept snapshot it never offered; the next setup offers it and, once the + /// set no longer lists it, counts it as offered. + #[test] + fn a_merged_offer_completes_only_when_its_snapshot_is_offered() { + let temp = TempDir::new().unwrap(); + let both = vec!["alpha".to_string(), "beta".to_string()]; + // Run A offered both; beta failed. + record_set_offer( + temp.path(), + "recommended", + SetOffer { + complete: false, + snapshot: both.clone(), + members: vec!["alpha".to_string()], + }, + ) + .unwrap(); + // Run B read no record and saw the set as [alpha] only. + record_set_offer( + temp.path(), + "recommended", + SetOffer { + complete: true, + snapshot: vec!["alpha".to_string()], + members: vec!["alpha".to_string()], + }, + ) + .unwrap(); + let merged = read_set_offer(temp.path(), "recommended").unwrap(); + assert!(!merged.complete); + assert_eq!(merged.snapshot, both); + + // The next setup sees the set as [alpha]: beta is no longer listed, + // so it counts as offered and the set completes. + let next = merged.after(&["alpha".to_string()], &SetInstallResult::default()); + assert!(next.complete); + assert_eq!(next.members, both); + // While the set still lists beta, a run that installs it completes it. + let installed_beta = SetInstallResult { + installed: vec![InstallOutcome { + metadata: installed("beta"), + changed: true, + }], + ..SetInstallResult::default() + }; + let retried = merged.after(&both, &installed_beta); + assert!(retried.complete); + assert_eq!(retried.members, both); + } + + /// A failed member is not offered, so the next setup retries it, and the + /// set is complete only once nothing failed. + #[test] + fn a_failed_member_stays_unoffered_until_it_lands() { + let mut result = SetInstallResult { + already_installed: vec!["alpha".to_string()], + unavailable: vec![("gamma".to_string(), "no release".to_string())], + failed: vec![("beta".to_string(), "download failed".to_string())], + ..SetInstallResult::default() + }; + let set = ["alpha", "beta", "gamma"].map(String::from); + let first = SetOffer::default().after(&set, &result); + assert!(!first.complete); + assert_eq!(first.members, ["alpha", "gamma"]); + assert_eq!(first.snapshot, set); + + result.failed.clear(); + result.installed.push(InstallOutcome { + metadata: installed("beta"), + changed: true, + }); + // The set gained `delta` since the first offer: the snapshot keeps it + // out of the retry. + let grown = ["alpha", "beta", "gamma", "delta"].map(String::from); + let second = first.after(&grown, &result); + assert!(second.complete); + assert_eq!(second.members, ["alpha", "beta", "gamma"]); + assert_eq!(second.snapshot, set); + } + + /// A torn or corrupt record counts as none instead of wedging setup, and + /// recording over it repairs it. + #[test] + fn a_corrupt_offer_record_counts_as_none_and_is_repaired() { + let temp = TempDir::new().unwrap(); + std::fs::write(temp.path().join(OFFERED_FILE), "{torn").unwrap(); + assert_eq!( + read_set_offer(temp.path(), "recommended").unwrap(), + SetOffer::default() + ); + let offer = SetOffer { + complete: true, + ..SetOffer::default() + }; + record_set_offer(temp.path(), "recommended", offer.clone()).unwrap(); + assert_eq!(read_set_offer(temp.path(), "recommended").unwrap(), offer); + } + + #[test] + fn a_resolution_keeps_only_the_snapshot_members_that_are_not_offered() { + let catalog = catalog( + &[("alpha", true), ("beta", true), ("gamma", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha","beta","gamma"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET) + .unwrap() + .only_members(&["alpha".to_string(), "beta".to_string()]) + .without_members(&["alpha".to_string()]); + let names: Vec<&str> = resolution.members.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["beta"]); + } + + #[test] + fn offered_members_are_dropped_from_a_resolution() { + let catalog = catalog( + &[("alpha", true), ("beta", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha","beta"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET) + .unwrap() + .without_members(&["alpha".to_string()]); + assert_eq!(resolution.members.len(), 1); + assert_eq!(resolution.members[0].name, "beta"); + } + + #[tokio::test] + async fn a_set_install_never_touches_an_installed_member() { + let catalog = catalog( + &[("alpha", true)], + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ); + let resolution = resolve_set(&catalog, "recommended", TARGET).unwrap(); + let temp = TempDir::new().unwrap(); + let store = PluginStore::new(temp.path()); + let mut disabled = installed("alpha"); + disabled.enabled = false; + store.save(&disabled).unwrap(); + let result = install_set_with( + &resolution, + &store, + &mut (), + async |_, _| -> Result { + panic!("an installed member must not be reinstalled") + }, + ) + .await + .unwrap(); + assert!(result.installed.is_empty() && result.failed.is_empty()); + assert!(!store.load("alpha").unwrap().enabled); + } + + /// Serve `routes` (path -> body) from a local server so catalog fetches + /// never reach the network; unlisted paths answer 404. + fn serve(routes: &'static [(&'static str, &'static str)]) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut request_line = String::new(); + reader.read_line(&mut request_line).unwrap(); + let mut header = String::new(); + while reader.read_line(&mut header).is_ok() && header.trim() != "" { + header.clear(); + } + let path = request_line + .split_whitespace() + .nth(1) + .unwrap_or("/") + .to_string(); + let found = routes.iter().find(|(route, _)| *route == path); + let (status, body) = match found { + Some((_, body)) => ("200 OK", *body), + None => ("404 Not Found", ""), + }; + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = reader.read(&mut [0u8; 0]); + } + }); + base + } + + const PLUGINS: &str = r#"{"name":"alpha","description":"A","github_url":"https://github.com/acme/alpha","author_email":"d@example.com","author_name":"Acme"}"#; + + #[tokio::test] + async fn fetching_reads_plugins_and_sets_from_the_catalog_location() { + let base = serve(&[ + ("/plugins.jsonl", PLUGINS), + ( + "/plugin-sets.jsonl", + r#"{"name":"recommended","description":"d","plugins":["alpha"]}"#, + ), + ]); + let plugins_url = format!("{base}/plugins.jsonl"); + let sets_url = crate::catalog::sets_url_for(&plugins_url); + let (catalog, problem) = PluginCatalog::fetch_with_sets( + // Loopback fixture: an inherited HTTP_PROXY must not take it. + &reqwest::Client::builder().no_proxy().build().unwrap(), + &plugins_url, + sets_url.as_deref(), + ) + .await + .unwrap(); + assert_eq!(problem, None); + assert_eq!(catalog.find_set("recommended").unwrap().plugins, ["alpha"]); + } + + /// A missing or broken sets file leaves a usable plugin catalog with no + /// sets and says why; it never fails the plugin catalog read. + #[tokio::test] + async fn a_broken_sets_file_leaves_the_plugin_catalog_readable() { + let base = serve(&[("/plugins.jsonl", PLUGINS)]); + let plugins_url = format!("{base}/plugins.jsonl"); + let sets_url = crate::catalog::sets_url_for(&plugins_url); + let (catalog, problem) = PluginCatalog::fetch_with_sets( + // Loopback fixture: an inherited HTTP_PROXY must not take it. + &reqwest::Client::builder().no_proxy().build().unwrap(), + &plugins_url, + sets_url.as_deref(), + ) + .await + .unwrap(); + assert!(catalog.find_exact("alpha").is_some()); + assert!(catalog.sets().is_empty()); + assert!(problem.unwrap().contains("404")); + } +} diff --git a/mesh/crates/mesh-llm-plugin-manager/src/store.rs b/mesh/crates/mesh-llm-plugin-manager/src/store.rs index 386e4bc3e9..65737acd66 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/store.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/store.rs @@ -10,7 +10,10 @@ use crate::source_ref::is_valid_name; mod control_behavior; mod exchange_access; +mod write_lock; + pub use exchange_access::InstalledOpenAiExchangeAccess; +pub use write_lock::StoreWriteLock; pub use control_behavior::{ InstalledPluginConditionOperator, InstalledPluginConditionValue, @@ -345,6 +348,13 @@ impl PluginStore { &self.root } + /// Wait until no other writer is changing this store, and keep it that + /// way until the guard drops. `save` does not take it itself, so an + /// install can check, place its package and save under one lock. + pub fn lock_writes(&self) -> Result { + StoreWriteLock::acquire(&self.root) + } + pub fn save(&self, metadata: &InstalledPluginMetadata) -> Result<()> { validate_plugin_name(&metadata.name)?; let plugin_dir = self.plugin_dir(&metadata.name); @@ -418,6 +428,7 @@ impl PluginStore { } pub fn set_enabled(&self, name: &str, enabled: bool) -> Result { + let _lock = self.lock_writes()?; let mut metadata = self.load(name)?; metadata.enabled = enabled; self.save(&metadata)?; @@ -426,6 +437,7 @@ impl PluginStore { pub fn delete(&self, name: &str) -> Result<()> { validate_plugin_name(name)?; + let _lock = self.lock_writes()?; let metadata = self.load(name).ok(); if let Some(metadata) = metadata && metadata.install_path.exists() diff --git a/mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs b/mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs new file mode 100644 index 0000000000..67903527a0 --- /dev/null +++ b/mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs @@ -0,0 +1,116 @@ +//! One writer at a time in a plugin store. +//! +//! Every write to installed packages, their metadata or the set offer record +//! takes this lock, so a check made under it (is this plugin installed? what +//! does the offer record say?) still holds when the write lands. Writers hold +//! it only for the write itself, never across a download. +//! +//! The wait is bounded: a writer that is suspended while holding the lock +//! must not hang a caller that runs under a deadline (setup), so a wait that +//! outlasts the bound fails and names the store. +use std::{ + fs, + fs::OpenOptions, + path::Path, + time::{Duration, Instant}, +}; + +use anyhow::{Context, Result}; + +const LOCK_FILE: &str = ".write.lock"; +/// Holders keep the lock for one small write, so a wait this long means the +/// holder is stuck, not busy. +const LOCK_WAIT: Duration = Duration::from_secs(10); +const LOCK_POLL: Duration = Duration::from_millis(25); + +/// Held until dropped. Advisory: it orders plugin store writers, which all +/// take it; readers do not. +#[derive(Debug)] +pub struct StoreWriteLock { + file: fs::File, +} + +impl StoreWriteLock { + /// Wait for the store's write lock. A lock is per open file, so a holder + /// must not take it again: the second wait would fail after the bound. + pub(crate) fn acquire(store_root: &Path) -> Result { + Self::acquire_within(store_root, LOCK_WAIT) + } + + pub(crate) fn acquire_within(store_root: &Path, wait: Duration) -> Result { + fs::create_dir_all(store_root) + .with_context(|| format!("create plugin store {}", store_root.display()))?; + let path = store_root.join(LOCK_FILE); + let file = OpenOptions::new() + .create(true) + .read(true) + .write(true) + .truncate(false) + .open(&path) + .with_context(|| format!("open plugin store lock {}", path.display()))?; + let started = Instant::now(); + loop { + match fs2::FileExt::try_lock_exclusive(&file) { + Ok(()) => return Ok(Self { file }), + Err(error) if error.kind() == fs2::lock_contended_error().kind() => { + if started.elapsed() >= wait { + anyhow::bail!( + "plugin store {} is busy: another mesh-llm process has held its write lock for {}s", + store_root.display(), + wait.as_secs() + ); + } + std::thread::sleep(LOCK_POLL); + } + Err(error) => { + return Err(error) + .with_context(|| format!("lock plugin store {}", path.display())); + } + } + } + } +} + +impl Drop for StoreWriteLock { + fn drop(&mut self) { + let _ = fs2::FileExt::unlock(&self.file); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{sync::mpsc, thread, time::Duration}; + + #[test] + fn a_second_writer_waits_for_the_first() -> Result<()> { + let dir = tempfile::tempdir()?; + let first = StoreWriteLock::acquire(dir.path())?; + let root = dir.path().to_path_buf(); + let (sent, received) = mpsc::channel(); + let waiter = thread::spawn(move || { + let lock = StoreWriteLock::acquire(&root); + sent.send(()).ok(); + lock.map(drop) + }); + // The waiter cannot get the lock while `first` holds it. + assert!(received.recv_timeout(Duration::from_millis(200)).is_err()); + drop(first); + received.recv_timeout(Duration::from_secs(60))?; + waiter.join().expect("waiter thread")?; + Ok(()) + } + + #[test] + fn a_wait_for_a_stuck_holder_ends_with_an_error_naming_the_store() -> Result<()> { + let dir = tempfile::tempdir()?; + let _holder = StoreWriteLock::acquire(dir.path())?; + let started = Instant::now(); + let error = StoreWriteLock::acquire_within(dir.path(), Duration::from_millis(100)) + .unwrap_err() + .to_string(); + assert!(error.contains("is busy"), "{error}"); + assert!(started.elapsed() < Duration::from_secs(30)); + Ok(()) + } +} diff --git a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptor-options.ts b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptor-options.ts index ca32a62cb2..63f690d655 100644 --- a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptor-options.ts +++ b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptor-options.ts @@ -9,6 +9,7 @@ export const SETUP_FLAGS = [ '--service', '--no-service', '--skip-runtime', + '--skip-plugin-install', '--verbose' ] as const export const UNINSTALL_FLAGS = [ @@ -58,7 +59,13 @@ export const SETUP_CONFLICTS = [['--service', '--no-service']] as const export const UNINSTALL_CONFLICTS = [['--purge-config', '--keep-config']] as const export const AUTH_INIT_CONFLICTS = [['--no-passphrase', '--keychain']] as const export const UPDATE_CONFLICTS = [['--flavor', '--detect-flavor']] as const -export const PLUGIN_INSTALL_CONFLICTS = [['reference', '--archive']] as const +export const PLUGIN_INSTALL_CONFLICTS = [ + ['reference', '--archive'], + ['reference', '--set'], + ['--set', '--archive'], + ['--set', '--name'], + ['--set', '--version'] +] as const export const SKILLS_INSTALL_CONFLICTS = [['--agent', '--all']] as const export const MODEL_SEARCH_CONFLICTS = [['--gguf', '--mlx']] as const export const TUNE_CONFLICTS = [ diff --git a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptors-plugins-benchmark.ts b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptors-plugins-benchmark.ts index cb14178639..f9f21b8fed 100644 --- a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptors-plugins-benchmark.ts +++ b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-descriptors-plugins-benchmark.ts @@ -12,7 +12,7 @@ export const PLUGIN_DESCRIPTORS: readonly SummaryDescriptor[] = [ descriptor( ['mesh-llm', 'plugins', 'install'], NONE, - ['reference', '--archive', '--name', '--version'], + ['reference', '--set', '--archive', '--name', '--version'], false, 'none', PLUGIN_INSTALL_CONFLICTS diff --git a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-vocabulary.ts b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-vocabulary.ts index e3606080fa..c92c165ec9 100644 --- a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-vocabulary.ts +++ b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary-vocabulary.ts @@ -73,6 +73,7 @@ export const BOOLEAN_SUMMARY_TOKENS: ReadonlySet = new Set([ '--service', '--no-service', '--skip-runtime', + '--skip-plugin-install', '--verbose', '--dry-run', '--keep-cache', @@ -137,6 +138,7 @@ export const REDACTED_SUMMARY_TOKENS: ReadonlySet = new Set([ '--output-dir', '--agent', '--archive', + '--set', '--quant', '--target', '--model-id', diff --git a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary.test.ts b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary.test.ts index d62e6ae70b..c0dc394856 100644 --- a/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary.test.ts +++ b/mesh/crates/mesh-llm-ui/src/features/logs/api/command-summary.test.ts @@ -30,6 +30,15 @@ describe('command summary grammar', () => { expect(isSafeCommandSummary('mesh-llm models list --json')).toBe(true) }) + it('accepts plugin set installs and the setup plugin opt-out', () => { + expect(isSafeCommandSummary('mesh-llm plugins install --set [REDACTED]')).toBe(true) + expect(isSafeCommandSummary('mesh-llm setup --skip-runtime --skip-plugin-install')).toBe(true) + expect(isSafeCommandSummary('mesh-llm plugins install reference [REDACTED] --set [REDACTED]')).toBe(false) + expect( + isSafeCommandSummary('mesh-llm plugins install --set [REDACTED] --archive [REDACTED] --name [REDACTED]') + ).toBe(false) + }) + it('rejects private values, controls, bounds, and deep malformed prefixes', () => { const malformedSummaries = [ 'mesh-llm load private-value', diff --git a/mesh/crates/mesh-llm/src/commands/setup.rs b/mesh/crates/mesh-llm/src/commands/setup.rs index 652143f2ac..63d3bc94d9 100644 --- a/mesh/crates/mesh-llm/src/commands/setup.rs +++ b/mesh/crates/mesh-llm/src/commands/setup.rs @@ -28,6 +28,7 @@ fn setup_command_args<'a>( service, no_service, skip_runtime, + skip_plugin_install, verbose, }) = cmd else { @@ -41,6 +42,7 @@ fn setup_command_args<'a>( service: *service, no_service: *no_service, skip_runtime: *skip_runtime, + skip_plugin_install: *skip_plugin_install, verbose: *verbose, }, environment: SetupEnvironment { @@ -77,6 +79,7 @@ mod tests { service: true, no_service: false, skip_runtime: true, + skip_plugin_install: true, verbose: true, }), mesh_llm_commands::runtime_native::NativeRuntimeConfigSelection::default(), @@ -91,6 +94,7 @@ mod tests { service: true, no_service: false, skip_runtime: true, + skip_plugin_install: true, verbose: true, } ); diff --git a/mesh/docs-site/content/plugins/plugin-architecture.mdx b/mesh/docs-site/content/plugins/plugin-architecture.mdx index 595ba833dc..e4b6b7a8e2 100644 --- a/mesh/docs-site/content/plugins/plugin-architecture.mdx +++ b/mesh/docs-site/content/plugins/plugin-architecture.mdx @@ -63,7 +63,7 @@ There is no separate top-level `services` section in the preferred DSL. ### 1. Plugins Are Explicit -MeshLLM ships no bundled plugins: a plugin reaches a node only when its operator installs it with `mesh-llm plugins install`. +MeshLLM ships no bundled plugins: a plugin reaches a node only when its operator installs it. `mesh-llm setup` installs the catalog's `recommended` plugin set by default, once per plugin store (`MESH_LLM_PLUGIN_DIR`, by default `~/.mesh-llm/plugins`, so once per user) (`--skip-plugin-install` opts out). `mesh-llm plugins install` installs a catalog plugin, a GitHub reference, or a local archive (`--archive` with `--name`), and `mesh-llm plugins install --set NAME` installs a catalog set. What is not acceptable is embedding one plugin's runtime behavior directly into core mesh logic. Core mesh transport and state should stay generic. diff --git a/mesh/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index bce0ad3eb0..18deac1fad 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,6 +217,7 @@ Switches: - `--service`: install and enable the background service. - `--no-service`: skip installing and enabling the background service. - `--skip-runtime`: skip downloading or configuring the native runtime. +- `--skip-plugin-install`: do not install the catalog's `recommended` plugin set. Without it, setup installs that set once per plugin store (`MESH_LLM_PLUGIN_DIR`, by default `~/.mesh-llm/plugins`, so once per user); when setup also installs the service on Linux or macOS, it installs into the store that service reads (`MESH_LLM_PLUGIN_DIR` in `service.env`, where a relative path is resolved under the service's home directory, otherwise the default; on macOS the line may be written `export KEY=value`, on Linux systemd does not read `export`; a value with variables, `~`, backslashes, mixed quoting or other shell syntax is reported instead), in attended and unattended runs alike, with no prompt. When the set installs capsules, setup writes `witness = "off"` for it in `config.toml` (an operator-set `witness` is kept), so checkpoints stay local until you set a witness. A plugin you remove is not reinstalled by later setup runs, and members added to the set later are not installed by setup. An install problem prints a warning and the retry command `mesh-llm plugins install --set recommended` (prefixed with `MESH_LLM_PLUGIN_DIR=` when setup installed into the service's store), and setup still succeeds; a member that failed is retried by the next setup run. - `--verbose`: print detailed service paths, commands, log locations, and setup status. On Windows, the background service is a per-user scheduled task that starts at @@ -1010,6 +1011,11 @@ Subcommands: names, GitHub `owner/repository` references, or GitHub URLs. List each required plugin in the command. Installation follows the order given and stops at the first failure. Plugins installed earlier in the command stay installed. +- `plugins install --set `: install the members of a catalog plugin set, + such as `recommended`, that are not installed yet, including one you removed + earlier. Installed members are left as they are; a failing member does not stop the others, and the command exits + non-zero so you can retry. The sets come from `plugin-sets.jsonl` beside the + catalog's `plugins.jsonl`. `--set` conflicts with `...` and `--archive`. - `plugins install --archive --name [--version ]`: install a local `.tar.gz` or `.zip` release archive. `--name` is required; `--version` defaults to `dev`. These flags conflict with `...`. diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index db34ade33e..af5629fd75 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,6 +111,7 @@ Switches: - `--service`: install and enable the background service. - `--no-service`: skip installing and enabling the background service. - `--skip-runtime`: skip downloading or configuring the native runtime. +- `--skip-plugin-install`: do not install the catalog's `recommended` plugin set. Without it, setup installs that set once per plugin store (`MESH_LLM_PLUGIN_DIR`, by default `~/.mesh-llm/plugins`, so once per user); when setup also installs the service on Linux or macOS, it installs into the store that service reads (`MESH_LLM_PLUGIN_DIR` in `service.env`, where a relative path is resolved under the service's home directory, otherwise the default; on macOS the line may be written `export KEY=value`, on Linux systemd does not read `export`; a value with variables, `~`, backslashes, mixed quoting or other shell syntax is reported instead), in attended and unattended runs alike, with no prompt. When the set installs capsules, setup writes `witness = "off"` for it in `config.toml` (an operator-set `witness` is kept), so checkpoints stay local until you set a witness. A plugin you remove is not reinstalled by later setup runs, and members added to the set later are not installed by setup. An install problem prints a warning and the retry command `mesh-llm plugins install --set recommended` (prefixed with `MESH_LLM_PLUGIN_DIR=` when setup installed into the service's store), and setup still succeeds; a member that failed is retried by the next setup run. - `--verbose`: print detailed service paths, commands, log locations, and setup status. On Windows, the background service is a per-user scheduled task that starts at @@ -869,6 +870,11 @@ Subcommands: to the same plugin share one install directory and metadata record, so the later reference replaces the earlier version. To install plugins together, list them in one command: `mesh-llm plugins install `. +- `plugins install --set `: install the members of a catalog plugin set, + such as `recommended`, that are not installed yet, including one you removed + earlier. Installed members are left as they are; a failing member does not stop the others, and the command exits + non-zero so you can retry. The sets come from `plugin-sets.jsonl` beside the + catalog's `plugins.jsonl`. `--set` conflicts with `...` and `--archive`. - `plugins install --archive --name [--version ]`: install a local `.tar.gz` or `.zip` release archive. `--name` is required; `--version` defaults to `dev`. These flags conflict with `...`. diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index fa04ec1df2..28ee2c0a42 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -300,6 +300,16 @@ handlers for pages and config sections. - use the exemplar's self-contained `bundle/host-contract.d.ts` for author types; do not import private types from `mesh/crates/mesh-llm-ui` +Install a catalog plugin set (a curated group, such as `recommended`) with +`mesh-llm plugins install --set recommended`. Sets are named in +`plugin-sets.jsonl`, next to the catalog's `plugins.jsonl`; a set carries only +member names, and each member's catalog entry stays the authority for its +release and checksums. `mesh-llm setup` installs `recommended` by default, +once per plugin store (`MESH_LLM_PLUGIN_DIR`, by default `~/.mesh-llm/plugins`, so once per user) (`--skip-plugin-install` opts out). A set install only adds what is missing: it +never updates, enables or re-enables a plugin that is already installed, and +membership changes later install nothing on their own. When a set installs +capsules, it also writes `witness = "off"` for it (see Capsules below). + Install multiple independent plugins in one command using catalog names, GitHub `owner/repo` references, or GitHub URLs: @@ -564,7 +574,17 @@ the installed archive, extracted files, and local plugin metadata. `capsules` is a reviewed plugin that keeps a signed record of each request this node serves, on the node's own disk. By default it keeps SHA-256 digests of the request and response, never their text; it sees no OpenAI exchange text. -It makes no network calls unless the operator configures a witness URL. +From capsules v0.1.26 the `witness` setting defaults to off: the plugin makes no +network calls unless the operator names a witness. A witness receives the +signed checkpoint only (log size, root commitment, the previous one, a timestamp +and the log's identity; never prompts, outputs or request contents). Capsules +v0.1.25 and earlier sent checkpoints to Action State's hosted witness when +`witness` was unset, so installing capsules through a plugin set (`mesh-llm +setup`, or `mesh-llm plugins install --set`) also writes `witness = "off"` into +its `[plugin.settings]` in `config.toml`: a node whose operator never chose it +keeps its checkpoints local whichever release it gets, until the operator sets a +witness (Configuration tab, or `witness` under `[plugin.settings]`). A `witness` +the operator already set is left alone. Install it like any plugin: ```bash diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 48dc048d86..318072941e 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -60,6 +60,7 @@ Supported flags: - `--service`: request background service setup where supported. - `--no-service`: skip background service setup. - `--skip-runtime`: skip native-runtime install and prune. +- `--skip-plugin-install`: skip installing the catalog's `recommended` plugin set. - `--verbose`: print detailed setup paths, commands, log locations, and status. Default setup output is concise and formatted for interactive use. @@ -84,6 +85,50 @@ Runtime install failure is a core setup failure. Runtime prune failure after a successful install is reported as a warning because the installed runtime is usable. +## Plugin Setup + +Unless `--skip-plugin-install` is passed, setup installs the missing members of +the catalog plugin set named `recommended` (`plugins install --set recommended`). +It does so with and without prompts, once per plugin store (recorded in that +store, `MESH_LLM_PLUGIN_DIR` or by default `~/.mesh-llm/plugins`, as `offered-sets.json`: a member counts as offered once it is installed, +already present, or has no release for this platform; a member that failed, and +a set that could not be read, are not recorded and are tried again by the next +setup run), after the runtime and before the service, so a node the service +starts finds the plugins. When setup also installs the service on Linux or macOS, +the store is the one that service reads: `MESH_LLM_PLUGIN_DIR` from its +`service.env` (a relative value under the home directory, where the service +starts), otherwise the default store, not the invoking shell's. systemd +reads `$` literally while the macOS runner's bash expands it, so a value with +variables, a leading `~`, backslashes, mixed quoting or other shell syntax is reported as a plugin warning rather +than guessed, and the retry command names the service's store with +`MESH_LLM_PLUGIN_DIR=`. A set +member someone else installs while setup downloads it is kept as they +installed it: every plugin store write (install, enable, disable, delete and +the offer record) takes the store's write lock, and a set member is placed +only if it is still missing under that lock. Concurrent setup runs merge +their offer records, so neither takes back what the other recorded. Later setup runs leave plugins as they are: a plugin +the operator removed is not reinstalled and members added to the set later are +not installed by setup. A member of that first snapshot that the set drops before +it was offered counts as offered. Two limits: a setup that times out records nothing, so +a member the operator removes before the next run is installed again, and an +unreadable record counts as none, so the next setup offers the set again. The set's membership and each +member's pinned release and checksums come from the plugin catalog. + +When the set installs the `capsules` plugin, setup also writes `witness = "off"` +under that plugin's `[plugin.settings]` in `config.toml`, unless a `witness` is +already set, so a node whose operator never chose capsules does not send +checkpoints to a witness, whichever release the catalog pins (capsules v0.1.26 +and later default to off; v0.1.25 and earlier defaulted to Action State's hosted +witness); the operator opts in by setting a witness. A direct +`plugins install capsules` keeps the plugin's own default. + +Plugin install is optional and never fails setup: an unreachable or slow +catalog (reads are bounded), a catalog that publishes no `recommended` set, a +member with no release for this platform or a member that fails to install +prints a warning with the retry command and setup finishes. A plugin that is +already installed is left alone, including a disabled one. Each installed +package's granted access is disclosed as it lands, as for `plugins install`. + ## Service Setup Service setup is supported for: