From 17f0e692b958f58a9ca0fabdb2a05d6b15ce3fe2 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Sun, 22 Nov 2026 23:51:03 -0600 Subject: [PATCH 01/19] feat(plugins): install the recommended plugin set by default in setup A fresh node got no plugins after #2977 stopped bundling them. The catalog can now publish named plugin sets in plugin-sets.jsonl beside plugins.jsonl; `mesh-llm plugins install --set NAME` installs a set's missing members from one catalog snapshot, and `mesh-llm setup` installs the `recommended` set by default, attended or not, with `--skip-plugin-install` as the opt-out. A plugin install problem (offline, slow catalog host, no such set, a failing member) warns with the retry command and never fails setup. The catalog set parsing, set resolution and one-snapshot install adapt the plugin-sets design from #2978. Co-authored-by: James Dumay Signed-off-by: Ethan Zhang --- .../mesh-llm-cli/src/parser/commands.rs | 11 +- .../src/parser/plugin_install_tests.rs | 36 ++ .../mesh-llm-cli/src/parser/setup_tests.rs | 16 + .../src/parser/subcommand_options.rs | 3 + mesh/crates/mesh-llm-commands/src/lib.rs | 1 + .../command_summary/administration.rs | 2 + .../command_summary/dispatch.rs | 2 + mesh/crates/mesh-llm-commands/src/plugin.rs | 37 +- .../mesh-llm-commands/src/plugin_sets.rs | 271 ++++++++++++ .../src/setup/cli_actions_tests.rs | 44 ++ .../mesh-llm-commands/src/setup/command.rs | 67 ++- .../src/setup/command_tests.rs | 9 +- .../src/setup/environment.rs | 2 + .../src/setup/github_tests.rs | 1 + .../crates/mesh-llm-commands/src/setup/mod.rs | 4 +- .../src/setup/orchestration_tests.rs | 3 + .../mesh-llm-commands/src/setup/plan.rs | 24 +- .../mesh-llm-commands/src/setup/planner.rs | 13 +- .../mesh-llm-commands/src/setup/summary.rs | 37 ++ .../mesh-llm-commands/src/setup/tests.rs | 95 +++- mesh/crates/mesh-llm-plugin-manager/README.md | 4 +- .../mesh-llm-plugin-manager/src/catalog.rs | 208 ++++++++- .../mesh-llm-plugin-manager/src/install.rs | 41 +- .../crates/mesh-llm-plugin-manager/src/lib.rs | 5 +- .../mesh-llm-plugin-manager/src/sets.rs | 415 ++++++++++++++++++ mesh/crates/mesh-llm/src/commands/setup.rs | 4 + .../content/plugins/plugin-architecture.mdx | 2 +- mesh/docs-site/content/reference/cli.mdx | 6 + mesh/docs/CLI.md | 6 + mesh/docs/plugins/README.md | 9 + mesh/docs/specs/mesh-setup-installer.md | 16 + 31 files changed, 1360 insertions(+), 34 deletions(-) create mode 100644 mesh/crates/mesh-llm-commands/src/plugin_sets.rs create mode 100644 mesh/crates/mesh-llm-plugin-manager/src/sets.rs diff --git a/mesh/crates/mesh-llm-cli/src/parser/commands.rs b/mesh/crates/mesh-llm-cli/src/parser/commands.rs index bd9438853e..cffc96a017 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/commands.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/commands.rs @@ -911,14 +911,17 @@ 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 missing members of a catalog plugin set, such as + /// `recommended`. 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/lib.rs b/mesh/crates/mesh-llm-commands/src/lib.rs index 580aff6d6b..a05cd8d874 100644 --- a/mesh/crates/mesh-llm-commands/src/lib.rs +++ b/mesh/crates/mesh-llm-commands/src/lib.rs @@ -13,6 +13,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/plugin.rs b/mesh/crates/mesh-llm-commands/src/plugin.rs index 9f136661ce..1309ac0a25 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,37 @@ 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?; + 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, reason) in &result.skipped { + writeln!(err, "Skipped {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 `mesh-llm plugins install --set {set}` 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 +551,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..26589c33a3 --- /dev/null +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -0,0 +1,271 @@ +//! `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::{ + 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, + /// The set resolved. Members may have been installed, left as they were + /// (already installed, or no release for this platform), or failed. + Finished { + installed: Vec, + skipped: Vec<(String, String)>, + failed: Vec<(String, String)>, + }, + /// 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 = Client::builder().timeout(timeout).build()?; + let sets_url = sets_url_for(&options.catalog_url); + PluginCatalog::fetch_with_sets(&client, &options.catalog_url, sets_url.as_deref()).await +} + +/// 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(set_name: &str, problem: Option) -> String { + match problem { + Some(problem) => format!("the plugin catalog has no set '{set_name}' ({problem})"), + None => format!("the plugin catalog has no set '{set_name}'"), + } +} + +/// `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(set_name, problem)); + } + install_set(&catalog, set_name, 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 work = async { + let (catalog, problem) = match read_catalog(options, catalog_timeout).await { + Ok(read) => read, + Err(error) => return SetupPluginsOutcome::Unavailable(format!("{error:#}")), + }; + if catalog.find_set(set_name).is_none() { + return SetupPluginsOutcome::Unavailable(no_set_reason(set_name, problem)); + } + match install_set(&catalog, set_name, options, progress).await { + Ok(result) => SetupPluginsOutcome::Finished { + installed: result + .installed + .into_iter() + .map(|outcome| outcome.metadata.name) + .collect(), + skipped: result.skipped, + 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", + 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`, or never answer when `stall`. + fn serve(routes: &'static [(&'static str, &'static str)], stall: bool) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + thread::spawn(move || { + let mut held = Vec::new(); + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + if stall { + held.push(stream); + continue; + } + 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"}"#; + + #[tokio::test] + async fn a_stalled_catalog_host_ends_setup_s_plugin_step_with_an_outcome() { + let temp = TempDir::new().unwrap(); + let base = serve(&[], true); + let outcome = install_set_for_setup( + "recommended", + &options(format!("{base}/plugins.jsonl"), temp.path()), + &mut |_| {}, + Duration::from_millis(200), + Duration::from_secs(30), + ) + .await; + assert!( + matches!(outcome, SetupPluginsOutcome::Unavailable(_)), + "{outcome:?}" + ); + } + + #[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)], false); + 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}"); + } + + #[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)], false); + 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 skipped. + #[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"]}"#, + ), + ], + false, + ); + 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, + skipped, + failed, + } = outcome + else { + panic!("expected Finished"); + }; + assert!(installed.is_empty() && failed.is_empty()); + assert_eq!(skipped.len(), 1); + assert_eq!(skipped[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..57df5c3b16 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 @@ -58,6 +58,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 +91,46 @@ 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]); + assert!(matches!( + actions.plugins_outcome, + crate::plugin_sets::SetupPluginsOutcome::Unavailable(_) + )); + assert!(prompter.prompts.is_empty()); +} diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index 57eeea024f..73c3e3db36 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -12,11 +12,13 @@ use super::{ 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::pin::Pin; @@ -70,9 +72,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 +111,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 +130,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 +204,27 @@ 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) -> Result<()> { + let options = match self.plugin_options.clone() { + Some(options) => Ok(options), + None => PluginInstallOptions::from_env(), + }; + 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); + self.plugins_outcome = outcome; + Ok(()) + } + fn install_service(&mut self) -> Result<()> { let context = match self.service_context.clone() { Some(context) => context, @@ -207,6 +245,30 @@ impl<'a> CliSetupActions<'a> { } } +fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { + let mut err = mesh_llm_events::console_err(); + let retry = format!( + "Retry with `mesh-llm plugins install --set {DEFAULT_SET}`, or pass --skip-plugin-install to setup to opt out." + ); + match outcome { + SetupPluginsOutcome::Unavailable(reason) => { + let _ = writeln!( + err, + "warning: could not install the {DEFAULT_SET} plugins: {reason}. {retry}" + ); + } + SetupPluginsOutcome::Finished { failed, .. } => { + for (name, reason) in failed { + let _ = writeln!(err, "warning: could not install plugin {name}: {reason}"); + } + if !failed.is_empty() { + let _ = writeln!(err, "{retry}"); + } + } + SetupPluginsOutcome::NotRequested => {} + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub(crate) enum SetupServiceOutcome { NotRequested, @@ -230,6 +292,7 @@ impl SetupActions for CliSetupActions<'_> { match step { SetupStep::InstallRuntime => self.install_runtime().await, SetupStep::PruneInactiveRuntimes => self.report_runtime_prune(), + SetupStep::InstallPlugins => self.install_plugins().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..71ee508a04 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command_tests.rs @@ -104,7 +104,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, + ] ); assert_eq!(actions.github, vec![SetupGitHubStarPlan::PromptIfEligible]); } @@ -166,6 +170,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 +185,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 +228,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..1be1f0d246 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/mod.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/mod.rs @@ -24,8 +24,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, 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..7988bc58bf 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/orchestration_tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/orchestration_tests.rs @@ -23,6 +23,7 @@ async fn run_setup_no_interactive_uses_guidance_step_and_hidden_star_without_pro vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins, SetupStep::PrintServiceGuidance, ] ); @@ -35,6 +36,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 +62,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..e90184a319 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, @@ -51,16 +61,26 @@ pub enum SetupGitHubStarSkipReason { pub enum SetupStep { InstallRuntime, PruneInactiveRuntimes, + /// Non-fatal: the action reports a failure and setup carries on. + InstallPlugins, 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) { + steps.push(SetupStep::InstallPlugins); + } 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/summary.rs b/mesh/crates/mesh-llm-commands/src/setup/summary.rs index c3e1fa4b62..8954c632d8 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,40 @@ 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::Unavailable(_)) => { + "not installed; see the warning above".to_string() + } + ( + _, + SetupPluginsOutcome::Finished { + installed, 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 parts.is_empty() { + "nothing to install".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. diff --git a/mesh/crates/mesh-llm-commands/src/setup/tests.rs b/mesh/crates/mesh-llm-commands/src/setup/tests.rs index f8bd9e2612..f3431b7ecc 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/tests.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/tests.rs @@ -46,6 +46,7 @@ fn interactive_unix_enter_accepts_default_yes_service_prompt() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins, SetupStep::InstallService, ] ); @@ -66,7 +67,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, + ] ); assert_eq!(prompter.prompts.len(), 1); } @@ -95,6 +100,7 @@ fn non_interactive_unix_never_prompts_and_prints_service_guidance() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, + SetupStep::InstallPlugins, SetupStep::PrintServiceGuidance, ] ); @@ -186,7 +192,10 @@ 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, SetupStep::InstallService] + ); } #[test] @@ -233,7 +242,87 @@ 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, + ] ); 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], "{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, SetupStep::InstallService] + ); +} 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/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..2478fd36a5 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/install.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/install.rs @@ -7,7 +7,7 @@ use sha2::Digest; use crate::{ archive::{ExtractedPluginArchive, stage_plugin_archive}, - catalog::PluginCatalog, + catalog::{CatalogEntry, PluginCatalog}, catalog_pin::CatalogPin, github::{GitHubReleaseAsset, GitHubReleaseClient}, infer_plugin_asset, select_plugin_asset, @@ -248,15 +248,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,6 +259,35 @@ 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. 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. +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).await +} + async fn install_resolved_plugin( resolved: ResolvedInstallSource, options: &PluginInstallOptions, 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..eb6d7a9c3c --- /dev/null +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -0,0 +1,415 @@ +//! 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, + }, + 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)>, + /// `(member, reason)` for members left alone: unavailable here, or + /// already installed. + pub skipped: Vec<(String, String)>, +} + +/// 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 { + if let MemberAvailability::Unavailable(reason) = &member.availability { + result.skipped.push((member.name.clone(), reason.clone())); + continue; + } + if let Some(installed) = store.load_optional(&member.name)? { + result.skipped.push(( + member.name.clone(), + format!("already installed ({})", installed.installed_version), + )); + continue; + } + match install_member(&member.name, progress).await { + Ok(outcome) => result.installed.push(outcome), + 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. +pub async fn install_set( + catalog: &PluginCatalog, + set_name: &str, + options: &PluginInstallOptions, + progress: &mut impl PluginProgressReporter, +) -> Result { + let resolution = resolve_set(catalog, set_name, options.target.triple())?; + 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"))?; + 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.skipped.len(), 1); + assert_eq!(first.skipped[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!( + second + .skipped + .iter() + .any(|(name, reason)| name == "alpha" && reason.contains("already installed")) + ); + } + + #[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( + &reqwest::Client::new(), + &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( + &reqwest::Client::new(), + &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/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..7429bc6915 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 it is installed from the catalog. `mesh-llm setup` installs the catalog's `recommended` plugin set by default (`--skip-plugin-install` opts out), and `mesh-llm plugins install` installs any plugin or set (`--set NAME`). 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..c311edfc38 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 in attended and unattended runs alike, with no prompt; an install problem prints a warning and the retry command `mesh-llm plugins install --set recommended`, and setup still succeeds. - `--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. 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..5576cd92bb 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 in attended and unattended runs alike, with no prompt; an install problem prints a warning and the retry command `mesh-llm plugins install --set recommended`, and setup still succeeds. - `--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. 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..faebf86416 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -300,6 +300,15 @@ 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 +(`--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. + Install multiple independent plugins in one command using catalog names, GitHub `owner/repo` references, or GitHub URLs: diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 48dc048d86..9c9cbcdb20 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,21 @@ 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, after the runtime and before the service, +so a node the service starts finds the plugins. The set's membership and each +member's pinned release and checksums come from the plugin catalog. + +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: From f0d34a7ee22fae58c5133fac4496cf8e7411a999 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Sun, 22 Nov 2026 23:55:15 -0600 Subject: [PATCH 02/19] fix(plugins): list the available sets when an unknown set is requested Signed-off-by: Ethan Zhang --- mesh/crates/mesh-llm-commands/src/plugin_sets.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 26589c33a3..8027bea4bd 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -49,10 +49,16 @@ async fn read_catalog( /// 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(set_name: &str, problem: Option) -> String { +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 => format!("the plugin catalog has no set '{set_name}'"), + None => { + let known: Vec<&str> = catalog.sets().iter().map(|set| set.name.as_str()).collect(); + format!( + "the plugin catalog has no set '{set_name}'; available sets: {}", + known.join(", ") + ) + } } } @@ -65,7 +71,7 @@ pub async fn install_set_command( ) -> Result { let (catalog, problem) = read_catalog(options, CATALOG_TIMEOUT).await?; if catalog.find_set(set_name).is_none() { - bail!("{}", no_set_reason(set_name, problem)); + bail!("{}", no_set_reason(&catalog, set_name, problem)); } install_set(&catalog, set_name, options, progress).await } @@ -100,7 +106,7 @@ async fn install_set_for_setup( Err(error) => return SetupPluginsOutcome::Unavailable(format!("{error:#}")), }; if catalog.find_set(set_name).is_none() { - return SetupPluginsOutcome::Unavailable(no_set_reason(set_name, problem)); + return SetupPluginsOutcome::Unavailable(no_set_reason(&catalog, set_name, problem)); } match install_set(&catalog, set_name, options, progress).await { Ok(result) => SetupPluginsOutcome::Finished { From 729ee0bb2b2e4d01843dbfa66359e182138d0106 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Sun, 22 Nov 2026 23:59:22 -0600 Subject: [PATCH 03/19] fix(plugins): report members unavailable on this platform and survive one unreadable record Setup now warns when a recommended-set member has no release for the platform instead of reporting "nothing to install", a corrupt installed record fails only its own member, and a timed-out setup says that finished installs stay. Signed-off-by: Ethan Zhang --- mesh/crates/mesh-llm-commands/src/plugin.rs | 7 +- .../mesh-llm-commands/src/plugin_sets.rs | 16 ++-- .../mesh-llm-commands/src/setup/command.rs | 12 ++- .../mesh-llm-commands/src/setup/summary.rs | 50 +++++++++++- .../mesh-llm-plugin-manager/src/sets.rs | 77 +++++++++++++++---- 5 files changed, 132 insertions(+), 30 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin.rs b/mesh/crates/mesh-llm-commands/src/plugin.rs index 1309ac0a25..b1957c3bc9 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin.rs @@ -268,8 +268,11 @@ async fn install_set_by_name(set: &str) -> Result<()> { outcome.metadata.name, outcome.metadata.installed_version )?; } - for (name, reason) in &result.skipped { - writeln!(err, "Skipped {name}: {reason}")?; + 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(()); diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 8027bea4bd..33c6a3873f 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -27,10 +27,10 @@ pub enum SetupPluginsOutcome { #[default] NotRequested, /// The set resolved. Members may have been installed, left as they were - /// (already installed, or no release for this platform), or failed. + /// (already installed), found unavailable on this platform, or failed. Finished { installed: Vec, - skipped: Vec<(String, String)>, + unavailable: Vec<(String, String)>, failed: Vec<(String, String)>, }, /// The set could not be read or the install did not finish; nothing @@ -115,7 +115,7 @@ async fn install_set_for_setup( .into_iter() .map(|outcome| outcome.metadata.name) .collect(), - skipped: result.skipped, + unavailable: result.unavailable, failed: result.failed, }, Err(error) => SetupPluginsOutcome::Unavailable(format!("{error:#}")), @@ -124,7 +124,7 @@ async fn install_set_for_setup( match tokio::time::timeout(install_timeout, work).await { Ok(outcome) => outcome, Err(_) => SetupPluginsOutcome::Unavailable(format!( - "timed out after {}s", + "timed out after {}s; plugins that finished installing before then stay installed (`mesh-llm plugins list`)", install_timeout.as_secs() )), } @@ -240,7 +240,7 @@ mod tests { } /// The members have no release for this platform, so nothing downloads: - /// the set install ends cleanly with every member skipped. + /// 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(); @@ -264,14 +264,14 @@ mod tests { .await; let SetupPluginsOutcome::Finished { installed, - skipped, + unavailable, failed, } = outcome else { panic!("expected Finished"); }; assert!(installed.is_empty() && failed.is_empty()); - assert_eq!(skipped.len(), 1); - assert_eq!(skipped[0].0, "alpha"); + assert_eq!(unavailable.len(), 1); + assert_eq!(unavailable[0].0, "alpha"); } } diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index 73c3e3db36..ccfd9742ca 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -257,7 +257,17 @@ fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { "warning: could not install the {DEFAULT_SET} plugins: {reason}. {retry}" ); } - SetupPluginsOutcome::Finished { failed, .. } => { + SetupPluginsOutcome::Finished { + unavailable, + failed, + .. + } => { + 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}"); } diff --git a/mesh/crates/mesh-llm-commands/src/setup/summary.rs b/mesh/crates/mesh-llm-commands/src/setup/summary.rs index 8954c632d8..84dba1211e 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/summary.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/summary.rs @@ -90,7 +90,9 @@ fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> ( _, SetupPluginsOutcome::Finished { - installed, failed, .. + installed, + unavailable, + failed, }, ) => { let mut parts = Vec::new(); @@ -100,8 +102,14 @@ fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> 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() { - "nothing to install".to_string() + "already installed".to_string() } else { parts.join("; ") } @@ -400,4 +408,42 @@ 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], + }; + 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-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index eb6d7a9c3c..04be8cb99e 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -46,9 +46,11 @@ pub struct SetInstallResult { pub installed: Vec, /// `(member, reason)` for members that were attempted and failed. pub failed: Vec<(String, String)>, - /// `(member, reason)` for members left alone: unavailable here, or - /// already installed. - pub skipped: 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)>, } /// Resolve `set_name` from one catalog snapshot for `target`. An unknown set @@ -111,15 +113,25 @@ pub async fn install_set_with

( let mut result = SetInstallResult::default(); for member in &resolution.members { if let MemberAvailability::Unavailable(reason) = &member.availability { - result.skipped.push((member.name.clone(), reason.clone())); + result + .unavailable + .push((member.name.clone(), reason.clone())); continue; } - if let Some(installed) = store.load_optional(&member.name)? { - result.skipped.push(( - member.name.clone(), - format!("already installed ({})", installed.installed_version), - )); - continue; + // 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; + } } match install_member(&member.name, progress).await { Ok(outcome) => result.installed.push(outcome), @@ -284,8 +296,8 @@ mod tests { first.failed, [("beta".to_string(), "download failed".to_string())] ); - assert_eq!(first.skipped.len(), 1); - assert_eq!(first.skipped[0].0, "gamma"); + 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, _| { @@ -300,12 +312,43 @@ mod tests { .await .unwrap(); assert_eq!(retried, ["beta"]); - assert!( - second - .skipped - .iter() - .any(|(name, reason)| name == "alpha" && reason.contains("already installed")) + assert_eq!(second.already_installed, ["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"); } #[tokio::test] From f0d23d002ac8c87e38316912274417951a5ec73a Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Mon, 23 Nov 2026 00:05:38 -0600 Subject: [PATCH 04/19] feat(plugins): offer the recommended set once per machine Setup installs the set once, records that it was offered, and never puts back a plugin the operator removed on a later run. A set that could not be read is not recorded and is tried again. Clearer wording for the summary and warning. Signed-off-by: Ethan Zhang --- .../mesh-llm-cli/src/parser/commands.rs | 5 +- .../mesh-llm-commands/src/plugin_sets.rs | 97 +++++++++++++++++-- .../mesh-llm-commands/src/setup/command.rs | 4 +- .../mesh-llm-commands/src/setup/summary.rs | 9 +- .../mesh-llm-plugin-manager/src/sets.rs | 51 ++++++++++ .../content/plugins/plugin-architecture.mdx | 2 +- mesh/docs-site/content/reference/cli.mdx | 6 +- mesh/docs/CLI.md | 6 +- mesh/docs/plugins/README.md | 4 +- mesh/docs/specs/mesh-setup-installer.md | 8 +- 10 files changed, 165 insertions(+), 27 deletions(-) diff --git a/mesh/crates/mesh-llm-cli/src/parser/commands.rs b/mesh/crates/mesh-llm-cli/src/parser/commands.rs index cffc96a017..28dca4f049 100644 --- a/mesh/crates/mesh-llm-cli/src/parser/commands.rs +++ b/mesh/crates/mesh-llm-cli/src/parser/commands.rs @@ -918,8 +918,9 @@ pub enum PluginCommand { /// Stops on the first failure; earlier installs are kept. #[arg(num_args = 1.., required_unless_present_any = ["archive", "set"], conflicts_with_all = ["archive", "name", "version", "set"])] reference: Vec, - /// Install the missing members of a catalog plugin set, such as - /// `recommended`. Members already installed are left as they are. + /// 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. diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 33c6a3873f..0f227d6585 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -26,6 +26,9 @@ const SETUP_INSTALL_TIMEOUT: Duration = Duration::from_secs(600); pub enum SetupPluginsOutcome { #[default] NotRequested, + /// Setup already offered the set on this machine: 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. Finished { @@ -100,6 +103,11 @@ async fn install_set_for_setup( catalog_timeout: Duration, install_timeout: Duration, ) -> SetupPluginsOutcome { + match mesh_llm_plugin_manager::sets::set_was_offered(&options.store_root, set_name) { + Ok(true) => return SetupPluginsOutcome::AlreadyOffered, + Ok(false) => {} + Err(error) => return SetupPluginsOutcome::Unavailable(format!("{error:#}")), + } let work = async { let (catalog, problem) = match read_catalog(options, catalog_timeout).await { Ok(read) => read, @@ -109,15 +117,24 @@ async fn install_set_for_setup( return SetupPluginsOutcome::Unavailable(no_set_reason(&catalog, set_name, problem)); } match install_set(&catalog, set_name, options, progress).await { - Ok(result) => SetupPluginsOutcome::Finished { - installed: result - .installed - .into_iter() - .map(|outcome| outcome.metadata.name) - .collect(), - unavailable: result.unavailable, - failed: result.failed, - }, + Ok(result) => { + // Offered now, whatever each member did: a failed member is + // retried by the explicit command, never by a later setup. + if let Err(error) = + mesh_llm_plugin_manager::sets::record_set_offered(&options.store_root, set_name) + { + return SetupPluginsOutcome::Unavailable(format!("{error:#}")); + } + SetupPluginsOutcome::Finished { + installed: result + .installed + .into_iter() + .map(|outcome| outcome.metadata.name) + .collect(), + unavailable: result.unavailable, + failed: result.failed, + } + } Err(error) => SetupPluginsOutcome::Unavailable(format!("{error:#}")), } }; @@ -203,6 +220,68 @@ mod tests { ); } + /// Setup offers the set once per machine: 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"]}"#, + ), + ], + false, + ); + 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!( + !mesh_llm_plugin_manager::sets::set_was_offered(temp.path(), "recommended").unwrap() + ); + } + #[tokio::test] async fn a_catalog_without_the_set_is_an_outcome_not_a_failure() { let temp = TempDir::new().unwrap(); diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index ccfd9742ca..cf560f7c8b 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -254,7 +254,7 @@ fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { SetupPluginsOutcome::Unavailable(reason) => { let _ = writeln!( err, - "warning: could not install the {DEFAULT_SET} plugins: {reason}. {retry}" + "warning: could not install the `{DEFAULT_SET}` plugin set: {reason}. {retry}" ); } SetupPluginsOutcome::Finished { @@ -275,7 +275,7 @@ fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { let _ = writeln!(err, "{retry}"); } } - SetupPluginsOutcome::NotRequested => {} + SetupPluginsOutcome::NotRequested | SetupPluginsOutcome::AlreadyOffered => {} } } diff --git a/mesh/crates/mesh-llm-commands/src/setup/summary.rs b/mesh/crates/mesh-llm-commands/src/setup/summary.rs index 84dba1211e..8ab69118d2 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/summary.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/summary.rs @@ -84,6 +84,9 @@ fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> 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 on this machine; plugins left as they are".to_string() + } (_, SetupPluginsOutcome::Unavailable(_)) => { "not installed; see the warning above".to_string() } @@ -97,7 +100,7 @@ fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> ) => { let mut parts = Vec::new(); if !installed.is_empty() { - parts.push(format!("installed {}", installed.join(", "))); + parts.push(format!("installed: {}", installed.join(", "))); } if !failed.is_empty() { parts.push(format!("{} failed; see the warning above", failed.len())); @@ -424,7 +427,7 @@ mod tests { ); assert_eq!( plugins_line(InstallDefaultSet, &finished(&["capsules"], 0, 0)), - "installed capsules" + "installed: capsules" ); assert_eq!( plugins_line(InstallDefaultSet, &finished(&[], 2, 0)), @@ -432,7 +435,7 @@ mod tests { ); assert_eq!( plugins_line(InstallDefaultSet, &finished(&["capsules"], 0, 1)), - "installed capsules; 1 failed; see the warning above" + "installed: capsules; 1 failed; see the warning above" ); assert_eq!( plugins_line(InstallDefaultSet, &finished(&[], 0, 0)), diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 04be8cb99e..3ea46dbfa1 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -53,6 +53,42 @@ pub struct SetInstallResult { pub unavailable: Vec<(String, String)>, } +const OFFERED_FILE: &str = "offered-sets.json"; + +/// Whether setup already offered `set_name` on this machine. A set is offered +/// once per machine: a plugin the operator later removes is never put back by +/// setup, and members added to the set later are not installed by it either. +pub fn set_was_offered(store_root: &std::path::Path, set_name: &str) -> Result { + Ok(read_offered(store_root)? + .iter() + .any(|name| name == set_name)) +} + +/// Record that `set_name` was offered on this machine. +pub fn record_set_offered(store_root: &std::path::Path, set_name: &str) -> Result<()> { + let mut offered = read_offered(store_root)?; + if offered.iter().any(|name| name == set_name) { + return Ok(()); + } + offered.push(set_name.to_string()); + std::fs::create_dir_all(store_root) + .with_context(|| format!("create plugin store {}", store_root.display()))?; + let path = store_root.join(OFFERED_FILE); + std::fs::write(&path, serde_json::to_vec(&offered)?) + .with_context(|| format!("write {}", path.display())) +} + +fn read_offered(store_root: &std::path::Path) -> Result> { + let path = store_root.join(OFFERED_FILE); + match std::fs::read(&path) { + Ok(bytes) => { + serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display())) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(error) => Err(error).with_context(|| format!("read {}", path.display())), + } +} + /// 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 { @@ -351,6 +387,21 @@ mod tests { assert_eq!(result.installed[0].metadata.name, "beta"); } + #[test] + fn a_set_is_offered_once_and_the_record_survives() { + let temp = TempDir::new().unwrap(); + let root = temp.path().join("plugins"); + assert!(!set_was_offered(&root, "recommended").unwrap()); + record_set_offered(&root, "recommended").unwrap(); + record_set_offered(&root, "recommended").unwrap(); + record_set_offered(&root, "extras").unwrap(); + assert!(set_was_offered(&root, "recommended").unwrap()); + assert!(set_was_offered(&root, "extras").unwrap()); + assert!(!set_was_offered(&root, "other").unwrap()); + // The record is a file in the store root, not a plugin. + assert!(PluginStore::new(&root).list().unwrap().is_empty()); + } + #[tokio::test] async fn a_set_install_never_touches_an_installed_member() { let catalog = catalog( diff --git a/mesh/docs-site/content/plugins/plugin-architecture.mdx b/mesh/docs-site/content/plugins/plugin-architecture.mdx index 7429bc6915..508ed48301 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 it is installed from the catalog. `mesh-llm setup` installs the catalog's `recommended` plugin set by default (`--skip-plugin-install` opts out), and `mesh-llm plugins install` installs any plugin or set (`--set NAME`). +MeshLLM ships no bundled plugins: a plugin reaches a node only when it is installed from the catalog. `mesh-llm setup` installs the catalog's `recommended` plugin set by default, once per machine (`--skip-plugin-install` opts out), and `mesh-llm plugins install` installs any plugin or set (`--set NAME`). 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 c311edfc38..28250fbf98 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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 in attended and unattended runs alike, with no prompt; an install problem prints a warning and the retry command `mesh-llm plugins install --set recommended`, and setup still succeeds. +- `--skip-plugin-install`: do not install the catalog's `recommended` plugin set. Without it, setup installs that set once per machine, in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds. - `--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 @@ -1012,8 +1012,8 @@ Subcommands: 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. Installed members are left - as they are; a failing member does not stop the others, and the command exits + 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 ]`: diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 5576cd92bb..86a3a15883 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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 in attended and unattended runs alike, with no prompt; an install problem prints a warning and the retry command `mesh-llm plugins install --set recommended`, and setup still succeeds. +- `--skip-plugin-install`: do not install the catalog's `recommended` plugin set. Without it, setup installs that set once per machine, in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds. - `--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 @@ -871,8 +871,8 @@ Subcommands: 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. Installed members are left - as they are; a failing member does not stop the others, and the command exits + 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 ]`: diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index faebf86416..a64211cd5f 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -304,8 +304,8 @@ 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 -(`--skip-plugin-install` opts out). A set install only adds what is missing: it +release and checksums. `mesh-llm setup` installs `recommended` by default, +once per machine (`--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. diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 9c9cbcdb20..16dacb1cab 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -89,8 +89,12 @@ usable. 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, after the runtime and before the service, -so a node the service starts finds the plugins. The set's membership and each +It does so with and without prompts, once per machine (recorded in the plugin +store as `offered-sets.json`; a set that could not be read is not recorded and +is tried again), after the runtime and before the service, so a node the +service starts finds the plugins. 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. The set's membership and each member's pinned release and checksums come from the plugin catalog. Plugin install is optional and never fails setup: an unreachable or slow From 3719e63191d7f425d6fae2d87fad7f4397fc91cb Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Mon, 23 Nov 2026 00:11:42 -0600 Subject: [PATCH 05/19] fix(plugins): retry a failed recommended-set member at the next setup Setup records a member as offered only once it is installed, already present or has no release for the platform. A member that failed is not recorded, so the next setup retries it; the set counts as complete (no catalog read on later runs) only when no member failed. Signed-off-by: Ethan Zhang --- .../mesh-llm-commands/src/plugin_sets.rs | 27 ++-- .../mesh-llm-plugin-manager/src/sets.rs | 142 +++++++++++++++--- mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- mesh/docs/specs/mesh-setup-installer.md | 6 +- 5 files changed, 138 insertions(+), 41 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 0f227d6585..dae3985a49 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -4,6 +4,7 @@ use std::time::Duration; use anyhow::{Result, bail}; +use mesh_llm_plugin_manager::sets::{read_set_offer, record_set_offer}; use mesh_llm_plugin_manager::{ PluginCatalog, PluginInstallOptions, PluginProgressReporter, catalog::sets_url_for, @@ -76,7 +77,7 @@ pub async fn install_set_command( if catalog.find_set(set_name).is_none() { bail!("{}", no_set_reason(&catalog, set_name, problem)); } - install_set(&catalog, set_name, options, progress).await + install_set(&catalog, set_name, &[], options, progress).await } /// Setup's plugin step. Every failure (offline, a slow catalog host, no such @@ -103,10 +104,12 @@ async fn install_set_for_setup( catalog_timeout: Duration, install_timeout: Duration, ) -> SetupPluginsOutcome { - match mesh_llm_plugin_manager::sets::set_was_offered(&options.store_root, set_name) { - Ok(true) => return SetupPluginsOutcome::AlreadyOffered, - Ok(false) => {} + 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 { @@ -116,13 +119,11 @@ async fn install_set_for_setup( if catalog.find_set(set_name).is_none() { return SetupPluginsOutcome::Unavailable(no_set_reason(&catalog, set_name, problem)); } - match install_set(&catalog, set_name, options, progress).await { + match install_set(&catalog, set_name, &offer.members, options, progress).await { Ok(result) => { - // Offered now, whatever each member did: a failed member is - // retried by the explicit command, never by a later setup. - if let Err(error) = - mesh_llm_plugin_manager::sets::record_set_offered(&options.store_root, set_name) - { + let recorded = + record_set_offer(&options.store_root, set_name, offer.after(&result)); + if let Err(error) = recorded { return SetupPluginsOutcome::Unavailable(format!("{error:#}")); } SetupPluginsOutcome::Finished { @@ -150,6 +151,7 @@ async fn install_set_for_setup( #[cfg(test)] mod tests { use super::*; + use mesh_llm_plugin_manager::sets::SetOffer; use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, @@ -277,8 +279,9 @@ mod tests { ) .await; assert!(matches!(outcome, SetupPluginsOutcome::Unavailable(_))); - assert!( - !mesh_llm_plugin_manager::sets::set_was_offered(temp.path(), "recommended").unwrap() + assert_eq!( + read_set_offer(temp.path(), "recommended").unwrap(), + SetOffer::default() ); } diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 3ea46dbfa1..29f9da9c16 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -55,40 +55,79 @@ pub struct SetInstallResult { const OFFERED_FILE: &str = "offered-sets.json"; -/// Whether setup already offered `set_name` on this machine. A set is offered -/// once per machine: a plugin the operator later removes is never put back by -/// setup, and members added to the set later are not installed by it either. -pub fn set_was_offered(store_root: &std::path::Path, set_name: &str) -> Result { - Ok(read_offered(store_root)? - .iter() - .any(|name| name == set_name)) +/// What setup has already done with one set on this machine. 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, + /// Members installed, already present, or unavailable here when offered. + pub members: Vec, } -/// Record that `set_name` was offered on this machine. -pub fn record_set_offered(store_root: &std::path::Path, set_name: &str) -> Result<()> { - let mut offered = read_offered(store_root)?; - if offered.iter().any(|name| name == set_name) { - return Ok(()); +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. + pub fn after(&self, 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.sort(); + members.dedup(); + SetOffer { + complete: result.failed.is_empty(), + members, + } } - offered.push(set_name.to_string()); +} + +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()) +} + +pub fn record_set_offer( + store_root: &std::path::Path, + set_name: &str, + offer: SetOffer, +) -> Result<()> { + let mut offers = read_offers(store_root)?; + offers.insert(set_name.to_string(), offer); std::fs::create_dir_all(store_root) .with_context(|| format!("create plugin store {}", store_root.display()))?; let path = store_root.join(OFFERED_FILE); - std::fs::write(&path, serde_json::to_vec(&offered)?) + std::fs::write(&path, serde_json::to_vec(&offers)?) .with_context(|| format!("write {}", path.display())) } -fn read_offered(store_root: &std::path::Path) -> Result> { +fn read_offers( + store_root: &std::path::Path, +) -> Result> { let path = store_root.join(OFFERED_FILE); match std::fs::read(&path) { Ok(bytes) => { serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display())) } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Default::default()), Err(error) => Err(error).with_context(|| format!("read {}", path.display())), } } +impl SetResolution { + /// Drop the members setup already offered on this machine. + 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 { @@ -184,10 +223,12 @@ pub async fn install_set_with

( pub async fn install_set( catalog: &PluginCatalog, set_name: &str, + already_offered: &[String], options: &PluginInstallOptions, progress: &mut impl PluginProgressReporter, ) -> Result { - let resolution = resolve_set(catalog, set_name, options.target.triple())?; + let resolution = + resolve_set(catalog, set_name, options.target.triple())?.without_members(already_offered); let store = PluginStore::new(&options.store_root); install_set_with(&resolution, &store, progress, async |name, progress| { let entry = catalog @@ -388,20 +429,71 @@ mod tests { } #[test] - fn a_set_is_offered_once_and_the_record_survives() { + fn a_set_offer_is_recorded_per_set_and_survives() { let temp = TempDir::new().unwrap(); let root = temp.path().join("plugins"); - assert!(!set_was_offered(&root, "recommended").unwrap()); - record_set_offered(&root, "recommended").unwrap(); - record_set_offered(&root, "recommended").unwrap(); - record_set_offered(&root, "extras").unwrap(); - assert!(set_was_offered(&root, "recommended").unwrap()); - assert!(set_was_offered(&root, "extras").unwrap()); - assert!(!set_was_offered(&root, "other").unwrap()); + assert_eq!( + read_set_offer(&root, "recommended").unwrap(), + SetOffer::default() + ); + let offer = SetOffer { + complete: false, + members: vec!["alpha".to_string()], + }; + record_set_offer(&root, "recommended", offer.clone()).unwrap(); + record_set_offer( + &root, + "extras", + SetOffer { + complete: true, + 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()); } + /// 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 first = SetOffer::default().after(&result); + assert!(!first.complete); + assert_eq!(first.members, ["alpha", "gamma"]); + + result.failed.clear(); + result.installed.push(InstallOutcome { + metadata: installed("beta"), + changed: true, + }); + let second = first.after(&result); + assert!(second.complete); + assert_eq!(second.members, ["alpha", "beta", "gamma"]); + } + + #[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( diff --git a/mesh/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index 28250fbf98..da499bf9b4 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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 machine, in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds. +- `--skip-plugin-install`: do not install the catalog's `recommended` plugin set. Without it, setup installs that set once per machine, in attended and unattended runs alike, with no prompt. 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`, 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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 86a3a15883..5a961a4f82 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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 machine, in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds. +- `--skip-plugin-install`: do not install the catalog's `recommended` plugin set. Without it, setup installs that set once per machine, in attended and unattended runs alike, with no prompt. 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`, 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 diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 16dacb1cab..b592efb722 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -90,8 +90,10 @@ usable. 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 machine (recorded in the plugin -store as `offered-sets.json`; a set that could not be read is not recorded and -is tried again), after the runtime and before the service, so a node the +store 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. 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. The set's membership and each From 7738935e463a6c709fbd14435eab9d0c384d6c66 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Mon, 23 Nov 2026 02:10:38 -0600 Subject: [PATCH 06/19] fix(plugins): keep later-added members out of a retried set offer and tolerate a torn offer record The offer record keeps the set's membership at the first offer, so retrying a failed member never installs a member added to the set afterwards. The record is written atomically and an unreadable one counts as none instead of warning on every setup. Signed-off-by: Ethan Zhang --- .../mesh-llm-commands/src/plugin_sets.rs | 19 ++-- .../mesh-llm-plugin-manager/src/sets.rs | 88 ++++++++++++++++--- 2 files changed, 88 insertions(+), 19 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index dae3985a49..d3567bdebf 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -4,7 +4,7 @@ use std::time::Duration; use anyhow::{Result, bail}; -use mesh_llm_plugin_manager::sets::{read_set_offer, record_set_offer}; +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, @@ -77,7 +77,7 @@ pub async fn install_set_command( if catalog.find_set(set_name).is_none() { bail!("{}", no_set_reason(&catalog, set_name, problem)); } - install_set(&catalog, set_name, &[], options, progress).await + install_set(&catalog, set_name, &SetOffer::default(), options, progress).await } /// Setup's plugin step. Every failure (offline, a slow catalog host, no such @@ -116,13 +116,17 @@ async fn install_set_for_setup( Ok(read) => read, Err(error) => return SetupPluginsOutcome::Unavailable(format!("{error:#}")), }; - if catalog.find_set(set_name).is_none() { + let Some(set) = catalog.find_set(set_name) else { return SetupPluginsOutcome::Unavailable(no_set_reason(&catalog, set_name, problem)); - } - match install_set(&catalog, set_name, &offer.members, options, progress).await { + }; + let set_members = set.plugins.clone(); + match install_set(&catalog, set_name, &offer, options, progress).await { Ok(result) => { - let recorded = - record_set_offer(&options.store_root, set_name, offer.after(&result)); + let recorded = record_set_offer( + &options.store_root, + set_name, + offer.after(&set_members, &result), + ); if let Err(error) = recorded { return SetupPluginsOutcome::Unavailable(format!("{error:#}")); } @@ -151,7 +155,6 @@ async fn install_set_for_setup( #[cfg(test)] mod tests { use super::*; - use mesh_llm_plugin_manager::sets::SetOffer; use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 29f9da9c16..b27ac5c2aa 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -64,6 +64,11 @@ 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, } @@ -72,15 +77,21 @@ 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. - pub fn after(&self, result: &SetInstallResult) -> SetOffer { + 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.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, } } @@ -102,8 +113,12 @@ pub fn record_set_offer( std::fs::create_dir_all(store_root) .with_context(|| format!("create plugin store {}", store_root.display()))?; let path = store_root.join(OFFERED_FILE); - std::fs::write(&path, serde_json::to_vec(&offers)?) - .with_context(|| format!("write {}", path.display())) + // 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::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( @@ -111,15 +126,23 @@ fn read_offers( ) -> Result> { let path = store_root.join(OFFERED_FILE); match std::fs::read(&path) { - Ok(bytes) => { - serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display())) - } + // 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 on this machine. pub fn without_members(mut self, offered: &[String]) -> Self { self.members @@ -223,12 +246,15 @@ pub async fn install_set_with

( pub async fn install_set( catalog: &PluginCatalog, set_name: &str, - already_offered: &[String], + offer: &SetOffer, options: &PluginInstallOptions, progress: &mut impl PluginProgressReporter, ) -> Result { - let resolution = - resolve_set(catalog, set_name, options.target.triple())?.without_members(already_offered); + 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 @@ -438,6 +464,7 @@ mod tests { ); 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(); @@ -446,6 +473,7 @@ mod tests { "extras", SetOffer { complete: true, + snapshot: vec![], members: vec![], }, ) @@ -467,18 +495,56 @@ mod tests { failed: vec![("beta".to_string(), "download failed".to_string())], ..SetInstallResult::default() }; - let first = SetOffer::default().after(&result); + 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, }); - let second = first.after(&result); + // 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] From 5c4b87fd6abce89daa268cecce2486476703f3ba Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Mon, 23 Nov 2026 02:11:35 -0600 Subject: [PATCH 07/19] fix(plugins): use a per-process temp file for the offer record and document its limits Signed-off-by: Ethan Zhang --- mesh/crates/mesh-llm-plugin-manager/src/sets.rs | 2 +- mesh/docs/specs/mesh-setup-installer.md | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index b27ac5c2aa..5f0d4b0dce 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -115,7 +115,7 @@ pub fn record_set_offer( 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")); + 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())) diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index b592efb722..6bb6f450ce 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -93,10 +93,12 @@ It does so with and without prompts, once per machine (recorded in the plugin store 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. 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. The set's membership and each +setup run), after the runtime and before the service, so a node the service +starts finds the plugins. 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. 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. Plugin install is optional and never fails setup: an unreachable or slow From a95e4816e95573a8cc38f6d2d565bed8a4c0facc Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Tue, 24 Nov 2026 19:20:16 -0600 Subject: [PATCH 08/19] fix(plugins): keep setup's plugin result when the offer record cannot be written A failed write of offered-sets.json made setup say the recommended set was not installed even though its members were. Setup now reports what the set did and warns separately that the next setup offers the set again. A catalog whose sets file lists no sets now says so instead of an empty list. Signed-off-by: Ethan Zhang --- .../mesh-llm-commands/src/plugin_sets.rs | 72 +++++++++++++++++-- .../mesh-llm-commands/src/setup/command.rs | 7 ++ .../mesh-llm-commands/src/setup/summary.rs | 2 + 3 files changed, 74 insertions(+), 7 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index d3567bdebf..fab10b9fc1 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -32,10 +32,13 @@ pub enum SetupPluginsOutcome { 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. @@ -58,10 +61,14 @@ fn no_set_reason(catalog: &PluginCatalog, set_name: &str, problem: Option 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(); - format!( - "the plugin catalog has no set '{set_name}'; available sets: {}", - known.join(", ") - ) + 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(", ") + ) + } } } } @@ -127,10 +134,8 @@ async fn install_set_for_setup( set_name, offer.after(&set_members, &result), ); - if let Err(error) = recorded { - return SetupPluginsOutcome::Unavailable(format!("{error:#}")); - } SetupPluginsOutcome::Finished { + record_error: recorded.err().map(|error| format!("{error:#}")), installed: result .installed .into_iter() @@ -306,6 +311,58 @@ mod tests { 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"]}"#, + ), + ], + false, + ); + 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(); @@ -351,6 +408,7 @@ mod tests { installed, unavailable, failed, + .. } = outcome else { panic!("expected Finished"); diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index cf560f7c8b..b33aa87cac 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -260,6 +260,7 @@ fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { SetupPluginsOutcome::Finished { unavailable, failed, + record_error, .. } => { for (name, reason) in unavailable { @@ -274,6 +275,12 @@ fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { 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 => {} } diff --git a/mesh/crates/mesh-llm-commands/src/setup/summary.rs b/mesh/crates/mesh-llm-commands/src/setup/summary.rs index 8ab69118d2..1032a8a6c6 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/summary.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/summary.rs @@ -96,6 +96,7 @@ fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> installed, unavailable, failed, + .. }, ) => { let mut parts = Vec::new(); @@ -420,6 +421,7 @@ mod tests { 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), From 27b2c25b0e8b1478f25642e46058020bcc1aa2a8 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Tue, 24 Nov 2026 19:33:36 -0600 Subject: [PATCH 09/19] docs(plugins): keep every install path in the plugin architecture page The page said a plugin reaches a node only from the catalog; GitHub references and local archives install too. Signed-off-by: Ethan Zhang --- mesh/docs-site/content/plugins/plugin-architecture.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mesh/docs-site/content/plugins/plugin-architecture.mdx b/mesh/docs-site/content/plugins/plugin-architecture.mdx index 508ed48301..773eb14659 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 it is installed from the catalog. `mesh-llm setup` installs the catalog's `recommended` plugin set by default, once per machine (`--skip-plugin-install` opts out), and `mesh-llm plugins install` installs any plugin or set (`--set NAME`). +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 machine (`--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. From 7da780fa970fcd363e939434b1799fe147ede714 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Tue, 24 Nov 2026 20:05:18 -0600 Subject: [PATCH 10/19] docs(plugins): say the recommended set is offered once per plugin store The offer record lives in the plugin store (MESH_LLM_PLUGIN_DIR, by default ~/.mesh-llm/plugins), so each user's store is offered the set once, not each machine. Signed-off-by: Ethan Zhang --- mesh/crates/mesh-llm-commands/src/plugin_sets.rs | 4 ++-- mesh/crates/mesh-llm-commands/src/setup/summary.rs | 3 ++- mesh/crates/mesh-llm-plugin-manager/src/sets.rs | 4 ++-- mesh/docs-site/content/plugins/plugin-architecture.mdx | 2 +- mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- mesh/docs/plugins/README.md | 2 +- mesh/docs/specs/mesh-setup-installer.md | 4 ++-- 8 files changed, 12 insertions(+), 11 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index fab10b9fc1..38dcf12abb 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -27,7 +27,7 @@ const SETUP_INSTALL_TIMEOUT: Duration = Duration::from_secs(600); pub enum SetupPluginsOutcome { #[default] NotRequested, - /// Setup already offered the set on this machine: it installs a set once, + /// 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 @@ -230,7 +230,7 @@ mod tests { ); } - /// Setup offers the set once per machine: after it resolved, a later run + /// 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] diff --git a/mesh/crates/mesh-llm-commands/src/setup/summary.rs b/mesh/crates/mesh-llm-commands/src/setup/summary.rs index 1032a8a6c6..2d78e0fa64 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/summary.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/summary.rs @@ -85,7 +85,8 @@ fn plugins_line(plan: super::SetupPluginsPlan, outcome: &SetupPluginsOutcome) -> (super::SetupPluginsPlan::Skip, _) => "skipped by --skip-plugin-install".to_string(), (_, SetupPluginsOutcome::NotRequested) => "not recorded".to_string(), (_, SetupPluginsOutcome::AlreadyOffered) => { - "recommended set already offered on this machine; plugins left as they are".to_string() + "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() diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 5f0d4b0dce..87234e6790 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -55,7 +55,7 @@ pub struct SetInstallResult { const OFFERED_FILE: &str = "offered-sets.json"; -/// What setup has already done with one set on this machine. A set is offered +/// 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. @@ -143,7 +143,7 @@ impl SetResolution { self } - /// Drop the members setup already offered on this machine. + /// 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)); diff --git a/mesh/docs-site/content/plugins/plugin-architecture.mdx b/mesh/docs-site/content/plugins/plugin-architecture.mdx index 773eb14659..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. `mesh-llm setup` installs the catalog's `recommended` plugin set by default, once per machine (`--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. +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 da499bf9b4..27311d5fdf 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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 machine, in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds; a member that failed is retried by the next setup run. +- `--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), in attended and unattended runs alike, with no prompt. 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`, 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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 5a961a4f82..29ecc2bd57 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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 machine, in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds; a member that failed is retried by the next setup run. +- `--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), in attended and unattended runs alike, with no prompt. 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`, 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 diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index a64211cd5f..fec0cb4fba 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -305,7 +305,7 @@ Install a catalog plugin set (a curated group, such as `recommended`) with `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 machine (`--skip-plugin-install` opts out). A set install only adds what is missing: it +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. diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 6bb6f450ce..ea7a4c31ea 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -89,8 +89,8 @@ usable. 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 machine (recorded in the plugin -store as `offered-sets.json`: a member counts as offered once it is installed, +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 From 26cc4c2f74a55018916073ff5cb20e609244d0cf Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 10:08:42 -0600 Subject: [PATCH 11/19] fix(plugins): keep concurrent plugin changes and install into the service's store - Every plugin store write takes a store-wide write lock. A set member is placed only if it is still missing under that lock, so a plugin the operator installs while setup downloads it is kept as they installed it. - The offer record merges with the latest record under the lock, so a slower partial setup run cannot take back a completed offer or members another run recorded. - When setup also installs the service on Linux or macOS, it installs the recommended set into the store that service reads (MESH_LLM_PLUGIN_DIR in service.env, otherwise the default store). - The command summary grammars (Rust and console) accept `plugins install --set` and `setup --skip-plugin-install`. Signed-off-by: Ethan Zhang --- Cargo.lock | 1 + .../command_summary_tests.rs | 30 ++++ .../src/setup/cli_actions_tests.rs | 6 +- .../mesh-llm-commands/src/setup/command.rs | 33 +++- .../src/setup/command_tests.rs | 3 +- .../crates/mesh-llm-commands/src/setup/mod.rs | 5 +- .../src/setup/orchestration_tests.rs | 3 +- .../mesh-llm-commands/src/setup/plan.rs | 19 +- .../src/setup/service_plugin_store.rs | 144 +++++++++++++++ .../mesh-llm-commands/src/setup/tests.rs | 25 ++- .../descriptors/plugins_benchmark.rs | 10 +- .../descriptors/top_level.rs | 1 + .../src/command_summary_grammar/vocabulary.rs | 2 + .../crates/mesh-llm-plugin-manager/Cargo.toml | 1 + .../mesh-llm-plugin-manager/src/archive.rs | 4 +- .../mesh-llm-plugin-manager/src/install.rs | 169 +++++++++++++++--- .../mesh-llm-plugin-manager/src/sets.rs | 93 +++++++++- .../mesh-llm-plugin-manager/src/store.rs | 12 ++ .../src/store/write_lock.rs | 69 +++++++ .../api/command-summary-descriptor-options.ts | 9 +- ...d-summary-descriptors-plugins-benchmark.ts | 2 +- .../logs/api/command-summary-vocabulary.ts | 2 + .../features/logs/api/command-summary.test.ts | 9 + mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- mesh/docs/specs/mesh-setup-installer.md | 9 +- 26 files changed, 610 insertions(+), 55 deletions(-) create mode 100644 mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs create mode 100644 mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs 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-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/setup/cli_actions_tests.rs b/mesh/crates/mesh-llm-commands/src/setup/cli_actions_tests.rs index 57df5c3b16..4a2add0c10 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}; @@ -127,7 +128,10 @@ async fn a_failing_plugin_install_never_fails_setup() { .await .expect("an unreachable plugin catalog must not fail setup"); - assert_eq!(plan.core_steps, vec![SetupStep::InstallPlugins]); + assert_eq!( + plan.core_steps, + vec![SetupStep::InstallPlugins(SetupPluginStore::Invoking)] + ); assert!(matches!( actions.plugins_outcome, crate::plugin_sets::SetupPluginsOutcome::Unavailable(_) diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index b33aa87cac..834016d454 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -1,12 +1,13 @@ 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, @@ -206,10 +207,10 @@ impl<'a> CliSetupActions<'a> { /// 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) -> Result<()> { + async fn install_plugins(&mut self, store: SetupPluginStore) -> Result<()> { let options = match self.plugin_options.clone() { Some(options) => Ok(options), - None => PluginInstallOptions::from_env(), + None => self.plugin_install_options(store), }; let outcome = match options { Ok(options) => { @@ -225,6 +226,30 @@ impl<'a> CliSetupActions<'a> { 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. + fn plugin_install_options(&self, store: SetupPluginStore) -> Result { + let mut options = PluginInstallOptions::from_env()?; + if store == SetupPluginStore::Service { + let context = match self.service_context.clone() { + Some(context) => context, + None => ServiceInstallContext::detect(self.environment.platform, true)?, + }; + if let Some(root) = service_plugin_store(&context)? { + options.install_root = root.join("installed"); + options.store_root = root; + } + } + if self.verbose { + let _ = writeln!( + mesh_llm_events::console_err(), + "Plugin store: {}", + options.store_root.display() + ); + } + Ok(options) + } + fn install_service(&mut self) -> Result<()> { let context = match self.service_context.clone() { Some(context) => context, @@ -309,7 +334,7 @@ impl SetupActions for CliSetupActions<'_> { match step { SetupStep::InstallRuntime => self.install_runtime().await, SetupStep::PruneInactiveRuntimes => self.report_runtime_prune(), - SetupStep::InstallPlugins => self.install_plugins().await, + 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 71ee508a04..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::{ @@ -107,7 +108,7 @@ async fn run_setup_executes_planned_steps_and_github_star_action() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, - SetupStep::InstallPlugins, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), ] ); assert_eq!(actions.github, vec![SetupGitHubStarPlan::PromptIfEligible]); diff --git a/mesh/crates/mesh-llm-commands/src/setup/mod.rs b/mesh/crates/mesh-llm-commands/src/setup/mod.rs index 1be1f0d246..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, SetupPluginsPlan, 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 7988bc58bf..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,7 +24,7 @@ async fn run_setup_no_interactive_uses_guidance_step_and_hidden_star_without_pro vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, - SetupStep::InstallPlugins, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), SetupStep::PrintServiceGuidance, ] ); diff --git a/mesh/crates/mesh-llm-commands/src/setup/plan.rs b/mesh/crates/mesh-llm-commands/src/setup/plan.rs index e90184a319..3ba381d107 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/plan.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/plan.rs @@ -57,12 +57,22 @@ 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, + InstallPlugins(SetupPluginStore), InstallService, PrintServiceGuidance, } @@ -79,7 +89,12 @@ fn build_core_steps( } // Before the service so a node it starts already finds the plugins. if matches!(plugins, SetupPluginsPlan::InstallDefaultSet) { - steps.push(SetupStep::InstallPlugins); + 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), 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..b87e1882cf --- /dev/null +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -0,0 +1,144 @@ +//! 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}; +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), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + return Err(error).with_context(|| format!("read {}", env_file.display())); + } + }; + Ok(Some(configured.unwrap_or_else(|| { + 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. +fn plugin_dir_from_env_file(contents: &str) -> Option { + let mut value = None; + for line in contents.lines() { + let line = line.trim(); + if line.starts_with('#') { + continue; + } + let line = line.strip_prefix("export ").unwrap_or(line); + let Some((key, raw)) = line.split_once('=') else { + continue; + }; + if key == PLUGIN_DIR_VAR { + value = Some(unquote(raw).to_string()); + } + } + value.filter(|value| !value.is_empty()).map(PathBuf::from) +} + +fn unquote(value: &str) -> &str { + for quote in ['"', '\''] { + if let Some(inner) = value + .strip_prefix(quote) + .and_then(|rest| rest.strip_suffix(quote)) + { + return inner; + } + } + value +} + +#[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(); + for platform in [SetupPlatform::Linux, SetupPlatform::MacOs] { + let context = context(platform, temp.path()); + write_env( + &context, + "# MESH_LLM_PLUGIN_DIR=/commented\nRUST_LOG=info\nMESH_LLM_PLUGIN_DIR=\"/srv/plugins\"\n", + ); + assert_eq!( + service_plugin_store(&context).unwrap(), + Some(PathBuf::from("/srv/plugins")) + ); + } + } + + #[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); + } + + #[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() { + assert_eq!( + plugin_dir_from_env_file("export MESH_LLM_PLUGIN_DIR='/a b'\n"), + Some(PathBuf::from("/a b")) + ); + assert_eq!( + plugin_dir_from_env_file(" MESH_LLM_PLUGIN_DIR=/x\nOTHER=/y\n"), + Some(PathBuf::from("/x")) + ); + assert_eq!(plugin_dir_from_env_file("MESH_LLM_PLUGIN_DIRS=/y\n"), None); + } +} diff --git a/mesh/crates/mesh-llm-commands/src/setup/tests.rs b/mesh/crates/mesh-llm-commands/src/setup/tests.rs index f3431b7ecc..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,7 +47,7 @@ fn interactive_unix_enter_accepts_default_yes_service_prompt() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, - SetupStep::InstallPlugins, + SetupStep::InstallPlugins(SetupPluginStore::Service), SetupStep::InstallService, ] ); @@ -70,7 +71,7 @@ fn interactive_unix_explicit_no_skips_service_prompt() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, - SetupStep::InstallPlugins, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), ] ); assert_eq!(prompter.prompts.len(), 1); @@ -100,7 +101,7 @@ fn non_interactive_unix_never_prompts_and_prints_service_guidance() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, - SetupStep::InstallPlugins, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), SetupStep::PrintServiceGuidance, ] ); @@ -194,7 +195,10 @@ fn skip_runtime_omits_install_and_prune_steps() { assert_eq!(plan.runtime, SetupRuntimePlan::Skip); assert_eq!( plan.core_steps, - vec![SetupStep::InstallPlugins, SetupStep::InstallService] + vec![ + SetupStep::InstallPlugins(SetupPluginStore::Service), + SetupStep::InstallService + ] ); } @@ -245,7 +249,7 @@ fn yes_and_no_service_keeps_explicit_service_skip_without_prompt() { vec![ SetupStep::InstallRuntime, SetupStep::PruneInactiveRuntimes, - SetupStep::InstallPlugins, + SetupStep::InstallPlugins(SetupPluginStore::Invoking), ] ); assert!(prompter.prompts.is_empty()); @@ -286,7 +290,11 @@ fn the_default_plugin_set_installs_without_a_prompt_in_every_mode() { (SetupOptions { yes: true, ..base }, true), ] { let (steps, prompts) = plugin_steps(options, interactive); - assert_eq!(steps, vec![SetupStep::InstallPlugins], "{options:?}"); + assert_eq!( + steps, + vec![SetupStep::InstallPlugins(SetupPluginStore::Invoking)], + "{options:?}" + ); assert_eq!(prompts, 0, "{options:?}"); } } @@ -323,6 +331,9 @@ fn plugins_install_before_the_service_and_independently_of_the_runtime() { ); assert_eq!( steps, - vec![SetupStep::InstallPlugins, SetupStep::InstallService] + 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/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/install.rs b/mesh/crates/mesh-llm-plugin-manager/src/install.rs index 2478fd36a5..690c2ec2f6 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/install.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/install.rs @@ -6,7 +6,7 @@ use reqwest::Client; use sha2::Digest; use crate::{ - archive::{ExtractedPluginArchive, stage_plugin_archive}, + archive::{ExtractedPluginArchive, StagedPluginArchive, stage_plugin_archive}, catalog::{CatalogEntry, PluginCatalog}, catalog_pin::CatalogPin, github::{GitHubReleaseAsset, GitHubReleaseClient}, @@ -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,10 @@ 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)?; + 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()), @@ -174,21 +176,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 +221,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 { @@ -276,16 +285,28 @@ fn resolve_catalog_entry( } /// Install `entry` at the release the catalog snapshot it came from pins, -/// without fetching the catalog again. A caller that resolved several entries +/// 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. +/// 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).await + install_resolved_plugin(resolved, options, progress, None, CommitMode::CreateOnly).await +} + +/// 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 { + Replace, + /// Keep a plugin that appeared since the install started. + CreateOnly, } async fn install_resolved_plugin( @@ -293,6 +314,7 @@ async fn install_resolved_plugin( options: &PluginInstallOptions, progress: &mut impl PluginProgressReporter, current: Option, + mode: CommitMode, ) -> Result { let release_client = GitHubReleaseClient::new()?; progress.report(PluginProgressEvent::ResolvingGitHub { @@ -363,24 +385,40 @@ 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::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 { @@ -400,6 +438,34 @@ 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), +} + +/// 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 mode == CommitMode::CreateOnly + && 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, @@ -1016,6 +1082,59 @@ 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()); + } + + #[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/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 87234e6790..954a0a2e09 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -97,21 +97,48 @@ impl SetOffer { } } +impl SetOffer { + /// What two runs recorded, together: neither can take back what the + /// other recorded. A set completed by either stays complete, a member + /// either recorded stays recorded, and the first snapshot stays. + fn merged_with(self, other: SetOffer) -> SetOffer { + let mut members = self.members; + members.extend(other.members); + members.sort(); + members.dedup(); + SetOffer { + complete: self.complete || other.complete, + snapshot: if self.snapshot.is_empty() { + other.snapshot + } else { + self.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()) } +/// 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)?; - offers.insert(set_name.to_string(), offer); - std::fs::create_dir_all(store_root) - .with_context(|| format!("create plugin store {}", store_root.display()))?; + 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. @@ -232,6 +259,11 @@ pub async fn install_set_with

( } } 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) => result .failed @@ -485,6 +517,61 @@ mod tests { 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 failed member is not offered, so the next setup retries it, and the /// set is complete only once nothing failed. #[test] 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..8e22a23b88 --- /dev/null +++ b/mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs @@ -0,0 +1,69 @@ +//! 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. +use std::{fs, fs::OpenOptions, path::Path}; + +use anyhow::{Context, Result}; + +const LOCK_FILE: &str = ".write.lock"; + +/// 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 never end. + pub(crate) fn acquire(store_root: &Path) -> 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()))?; + fs2::FileExt::lock_exclusive(&file) + .with_context(|| format!("lock plugin store {}", path.display()))?; + Ok(Self { file }) + } +} + +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(()) + } +} 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/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index 27311d5fdf..dcc146dc46 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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), in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds; a member that failed is retried by the next setup run. +- `--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`, otherwise the default), in attended and unattended runs alike, with no prompt. 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`, 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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 29ecc2bd57..8ac55d75e4 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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), in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds; a member that failed is retried by the next setup run. +- `--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`, otherwise the default), in attended and unattended runs alike, with no prompt. 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`, 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 diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index ea7a4c31ea..00dfbe3b90 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -94,7 +94,14 @@ store, `MESH_LLM_PLUGIN_DIR` or by default `~/.mesh-llm/plugins`, as `offered-se 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. Later setup runs leave plugins as they are: a plugin +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`, otherwise the default store, not the invoking shell's. 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. Two limits: a setup that times out records nothing, so a member the operator removes before the next run is installed again, and an From 7e47a52d3c00905c4ccff275cd05e6f994d1df82 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 11:04:49 -0600 Subject: [PATCH 12/19] fix(plugins): complete a merged set offer only when its snapshot is offered Two setup runs that read different set snapshots could merge into a complete offer that never offered a member of the kept snapshot, so later setups skipped the set and that member stayed uninstalled. A merged offer is now complete only when a run completed and every member of the kept snapshot is recorded. A snapshot member the set no longer lists counts as offered, so such an offer still completes on the next setup. Signed-off-by: Ethan Zhang --- .../mesh-llm-plugin-manager/src/sets.rs | 82 ++++++++++++++++--- mesh/docs/specs/mesh-setup-installer.md | 3 +- 2 files changed, 74 insertions(+), 11 deletions(-) diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 954a0a2e09..6658e47389 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -77,11 +77,19 @@ 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( + self.snapshot + .iter() + .filter(|member| !set_members.contains(member)) + .cloned(), + ); members.sort(); members.dedup(); let snapshot = if self.snapshot.is_empty() { @@ -95,24 +103,27 @@ impl SetOffer { members, } } -} -impl SetOffer { /// What two runs recorded, together: neither can take back what the - /// other recorded. A set completed by either stays complete, a member - /// either recorded stays recorded, and the first snapshot stays. + /// 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: if self.snapshot.is_empty() { - other.snapshot - } else { - self.snapshot - }, + complete: (self.complete || other.complete) && snapshot_offered, + snapshot, members, } } @@ -572,6 +583,57 @@ mod tests { 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] diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 00dfbe3b90..98c1fc78ad 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -103,7 +103,8 @@ 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. Two limits: a setup that times out records nothing, so +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. From ed1de3b887ea9943a38aedb579507952a20ac2ac Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 15:37:13 -0600 Subject: [PATCH 13/19] fix(setup): name the service's plugin store and keep reporters off the store lock - The retry hint setup prints after a plugin problem names the store setup installed into (MESH_LLM_PLUGIN_DIR=) when that is the service's store rather than the invoking shell's. - A service.env value the service reads differently from its literal text (variables, a leading ~ or backslashes, which the macOS runner's bash expands) is reported as a plugin warning instead of installing elsewhere; systemd keeps $ literally. - A local archive install releases the store write lock before it reports Installed, so a reporter that changes the store cannot deadlock it. Signed-off-by: Ethan Zhang --- .../src/setup/cli_actions_tests.rs | 31 +++++ .../mesh-llm-commands/src/setup/command.rs | 81 ++++++++++-- .../src/setup/service_plugin_store.rs | 118 +++++++++++++++--- .../mesh-llm-plugin-manager/src/install.rs | 39 +++++- mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- mesh/docs/specs/mesh-setup-installer.md | 6 +- 7 files changed, 248 insertions(+), 31 deletions(-) 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 4a2add0c10..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 @@ -138,3 +138,34 @@ async fn a_failing_plugin_install_never_fails_setup() { )); 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 834016d454..3982bc53d8 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -22,6 +22,7 @@ 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)] @@ -208,9 +209,15 @@ impl<'a> CliSetupActions<'a> { /// 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 = match self.plugin_options.clone() { - Some(options) => Ok(options), - None => self.plugin_install_options(store), + 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) => { @@ -221,23 +228,31 @@ impl<'a> CliSetupActions<'a> { } Err(error) => SetupPluginsOutcome::Unavailable(format!("{error:#}")), }; - print_plugins_warnings(&outcome); + 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. - fn plugin_install_options(&self, store: SetupPluginStore) -> Result { + /// 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)?, }; - if let Some(root) = service_plugin_store(&context)? { + if let Some(root) = service_plugin_store(&context)? + && root != options.store_root + { options.install_root = root.join("installed"); - options.store_root = root; + options.store_root = root.clone(); + retry = RetryStore::Service(root); } } if self.verbose { @@ -247,7 +262,7 @@ impl<'a> CliSetupActions<'a> { options.store_root.display() ); } - Ok(options) + Ok((options, retry)) } fn install_service(&mut self) -> Result<()> { @@ -270,11 +285,51 @@ impl<'a> CliSetupActions<'a> { } } -fn print_plugins_warnings(outcome: &SetupPluginsOutcome) { +/// 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 = format!( - "Retry with `mesh-llm plugins install --set {DEFAULT_SET}`, or pass --skip-plugin-install to setup to opt out." - ); + let retry = retry.hint(); match outcome { SetupPluginsOutcome::Unavailable(reason) => { let _ = writeln!( 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 index b87e1882cf..45e0001d73 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -7,7 +7,7 @@ //! so the node it starts finds them. use super::SetupPlatform; use super::service_paths::{ServiceInstallContext, ServicePaths}; -use anyhow::{Context, Result}; +use anyhow::{Context, Result, bail}; use std::path::{Path, PathBuf}; const PLUGIN_DIR_VAR: &str = "MESH_LLM_PLUGIN_DIR"; @@ -21,7 +21,8 @@ pub(crate) fn service_plugin_store(context: &ServiceInstallContext) -> Result plugin_dir_from_env_file(&contents), + 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())); @@ -42,7 +43,14 @@ fn default_plugin_store(home_dir: &Path) -> PathBuf { /// 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. -fn plugin_dir_from_env_file(contents: &str) -> Option { +/// +/// 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. A value whose meaning depends on +/// these 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(); @@ -54,22 +62,57 @@ fn plugin_dir_from_env_file(contents: &str) -> Option { continue; }; if key == PLUGIN_DIR_VAR { - value = Some(unquote(raw).to_string()); + value = Some(raw); } } - value.filter(|value| !value.is_empty()).map(PathBuf::from) + 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 without variables, `~` or backslashes" + ); + } + Ok(Some(inner) + .filter(|value| !value.is_empty()) + .map(PathBuf::from)) } -fn unquote(value: &str) -> &str { - for quote in ['"', '\''] { +#[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; + return (inner, quoting); } } - value + (value, Quoting::None) +} + +/// Whether the service reads `inner` as exactly these characters. +fn value_is_literal(inner: &str, quoting: Quoting, platform: SetupPlatform) -> bool { + if quoting == Quoting::Single { + return true; + } + if inner.contains('\\') { + return false; + } + if platform != SetupPlatform::MacOs { + return true; + } + let expands = inner.contains('$') || inner.contains('`'); + let tilde = quoting == Quoting::None && inner.starts_with('~'); + !expands && !tilde } #[cfg(test)] @@ -131,14 +174,61 @@ mod tests { #[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(); + assert_eq!( + parse("export MESH_LLM_PLUGIN_DIR='/a b'\n"), + Some(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}" + ); + } assert_eq!( - plugin_dir_from_env_file("export MESH_LLM_PLUGIN_DIR='/a b'\n"), - Some(PathBuf::from("/a b")) + 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=/x\nOTHER=/y\n"), - Some(PathBuf::from("/x")) + plugin_dir_from_env_file("MESH_LLM_PLUGIN_DIR=\"~/p\"\n", SetupPlatform::MacOs) + .unwrap(), + Some(PathBuf::from("~/p")) ); - assert_eq!(plugin_dir_from_env_file("MESH_LLM_PLUGIN_DIRS=/y\n"), None); + } + + #[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-plugin-manager/src/install.rs b/mesh/crates/mesh-llm-plugin-manager/src/install.rs index 690c2ec2f6..ed6b107b3f 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/install.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/install.rs @@ -147,7 +147,9 @@ pub fn install_plugin_archive( }); let store = PluginStore::new(&options.store_root); let staged = stage_for_install(&archive_path, archive_ext, name, options)?; - let _lock = store.lock_writes()?; + // 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 = staged.commit()?; let metadata = InstalledPluginMetadata { @@ -165,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()), }); @@ -1107,6 +1110,40 @@ mod tests { assert!(theirs.install_path.join("operator-marker").is_file()); } + /// 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(); diff --git a/mesh/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index dcc146dc46..b53f4b9838 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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`, otherwise the default), in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds; a member that failed is retried by the next setup run. +- `--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` as an absolute path, otherwise the default; a value with variables, `~` or backslashes is reported instead), in attended and unattended runs alike, with no prompt. 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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 8ac55d75e4..424d12a67d 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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`, otherwise the default), in attended and unattended runs alike, with no prompt. 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`, and setup still succeeds; a member that failed is retried by the next setup run. +- `--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` as an absolute path, otherwise the default; a value with variables, `~` or backslashes is reported instead), in attended and unattended runs alike, with no prompt. 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 diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index 98c1fc78ad..b6bce4bd34 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -96,7 +96,11 @@ 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`, otherwise the default store, not the invoking shell's. A set +`service.env`, 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 `~` or backslashes 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 From 7d1b3d81e932c598e67366f7fe66e706ba444a42 Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 16:08:30 -0600 Subject: [PATCH 14/19] fix(setup): refuse mixed quoting in service.env and isolate catalog tests from proxies - A MESH_LLM_PLUGIN_DIR value with a quote inside it (such as '/tmp/'"$USER"'/plugins', which bash joins and expands) or an unquoted value with shell syntax is reported instead of read literally. - Loopback catalog test clients ignore an inherited HTTP proxy. - The stalled-catalog test checks that the host accepted the read and that the catalog deadline, not setup's outer one, ended it. Signed-off-by: Ethan Zhang --- .../mesh-llm-commands/src/plugin_sets.rs | 104 ++++++++++-------- .../src/setup/service_plugin_store.rs | 51 ++++++--- .../mesh-llm-plugin-manager/src/sets.rs | 6 +- mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- mesh/docs/specs/mesh-setup-installer.md | 2 +- 6 files changed, 104 insertions(+), 63 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 38dcf12abb..111bfbf64a 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -49,11 +49,20 @@ async fn read_catalog( options: &PluginInstallOptions, timeout: Duration, ) -> Result<(PluginCatalog, Option)> { - let client = Client::builder().timeout(timeout).build()?; + 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 { @@ -176,18 +185,13 @@ mod tests { } } - /// Answer each request from `routes`, or never answer when `stall`. - fn serve(routes: &'static [(&'static str, &'static str)], stall: bool) -> String { + /// 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 || { - let mut held = Vec::new(); for stream in listener.incoming() { let Ok(mut stream) = stream else { return }; - if stall { - held.push(stream); - continue; - } let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut line = String::new(); reader.read_line(&mut line).unwrap(); @@ -212,21 +216,42 @@ mod tests { 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 base = serve(&[], true); + 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(30), + 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!( - matches!(outcome, SetupPluginsOutcome::Unavailable(_)), - "{outcome:?}" + started.elapsed() < Duration::from_secs(60), + "{:?}", + started.elapsed() ); } @@ -236,16 +261,13 @@ mod tests { #[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"]}"#, - ), - ], - false, - ); + 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", @@ -296,7 +318,7 @@ mod tests { #[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)], false); + let base = serve(&[("/plugins.jsonl", PLUGINS)]); let outcome = install_set_for_setup( "recommended", &options(format!("{base}/plugins.jsonl"), temp.path()), @@ -329,16 +351,13 @@ mod tests { .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"]}"#, - ), - ], - false, - ); + 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()), @@ -366,7 +385,7 @@ mod tests { #[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)], false); + let base = serve(&[("/custom.json", PLUGINS)]); let error = install_set_command( "recommended", &options(format!("{base}/custom.json"), temp.path()), @@ -386,16 +405,13 @@ mod tests { #[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"]}"#, - ), - ], - false, - ); + 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()), 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 index 45e0001d73..2d8eb067e3 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -47,9 +47,9 @@ fn default_plugin_store(home_dir: &Path) -> PathBuf { /// 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. A value whose meaning depends on -/// these is an error rather than a guess, so setup never installs into a -/// store the service does not read. +/// 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() { @@ -72,7 +72,7 @@ fn plugin_dir_from_env_file(contents: &str, platform: SetupPlatform) -> Result (&str, Quoting) { (value, Quoting::None) } -/// Whether the service reads `inner` as exactly these characters. +/// 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 quoting == Quoting::Single { - return true; - } - if inner.contains('\\') { + if inner.contains('\'') || inner.contains('"') { return false; } - if platform != SetupPlatform::MacOs { - return true; + 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)), } - let expands = inner.contains('$') || inner.contains('`'); - let tilde = quoting == Quoting::None && inner.starts_with('~'); - !expands && !tilde } #[cfg(test)] @@ -211,6 +218,22 @@ mod tests { "{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(), diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 6658e47389..064b416182 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -785,7 +785,8 @@ mod tests { let plugins_url = format!("{base}/plugins.jsonl"); let sets_url = crate::catalog::sets_url_for(&plugins_url); let (catalog, problem) = PluginCatalog::fetch_with_sets( - &reqwest::Client::new(), + // Loopback fixture: an inherited HTTP_PROXY must not take it. + &reqwest::Client::builder().no_proxy().build().unwrap(), &plugins_url, sets_url.as_deref(), ) @@ -803,7 +804,8 @@ mod tests { let plugins_url = format!("{base}/plugins.jsonl"); let sets_url = crate::catalog::sets_url_for(&plugins_url); let (catalog, problem) = PluginCatalog::fetch_with_sets( - &reqwest::Client::new(), + // Loopback fixture: an inherited HTTP_PROXY must not take it. + &reqwest::Client::builder().no_proxy().build().unwrap(), &plugins_url, sets_url.as_deref(), ) diff --git a/mesh/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index b53f4b9838..f7486f215d 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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` as an absolute path, otherwise the default; a value with variables, `~` or backslashes is reported instead), in attended and unattended runs alike, with no prompt. 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. +- `--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` as an absolute path, otherwise the default; a value with variables, `~`, backslashes, mixed quoting or other shell syntax is reported instead), in attended and unattended runs alike, with no prompt. 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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 424d12a67d..46f39fee85 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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` as an absolute path, otherwise the default; a value with variables, `~` or backslashes is reported instead), in attended and unattended runs alike, with no prompt. 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. +- `--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` as an absolute path, otherwise the default; a value with variables, `~`, backslashes, mixed quoting or other shell syntax is reported instead), in attended and unattended runs alike, with no prompt. 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 diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index b6bce4bd34..e6bc8c45e3 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -98,7 +98,7 @@ 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`, 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 `~` or backslashes is reported as a plugin warning rather +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 From d83634cc1798edb17fbd36e07e897ae2587be79e Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 17:06:22 -0600 Subject: [PATCH 15/19] fix(setup): resolve a relative service plugin store against the service's home systemd and launchd start the node in the home directory, so a relative MESH_LLM_PLUGIN_DIR in service.env names a store there, not under the directory setup was started from. Signed-off-by: Ethan Zhang --- .../src/setup/service_plugin_store.rs | 26 ++++++++++++++++--- mesh/docs/specs/mesh-setup-installer.md | 3 ++- 2 files changed, 25 insertions(+), 4 deletions(-) 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 index 2d8eb067e3..249808d274 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -28,9 +28,13 @@ pub(crate) fn service_plugin_store(context: &ServiceInstallContext) -> Result context.home_dir.join(path), + None => default_plugin_store(&context.home_dir), + })) } /// What the node uses when nothing sets `MESH_LLM_PLUGIN_DIR`, as @@ -172,6 +176,22 @@ mod tests { 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:?}" + ); + } + } + #[test] fn windows_uses_the_invoking_store() { let temp = tempfile::tempdir().unwrap(); diff --git a/mesh/docs/specs/mesh-setup-installer.md b/mesh/docs/specs/mesh-setup-installer.md index e6bc8c45e3..5ab24f5d64 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -96,7 +96,8 @@ 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`, otherwise the default store, not the invoking shell's. systemd +`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 From 6b7eb21452ffd5e91401e1892d3bb5a2ee16fc3f Mon Sep 17 00:00:00 2001 From: Ethan Zhang Date: Thu, 26 Nov 2026 18:07:35 -0600 Subject: [PATCH 16/19] test(setup): use a host-absolute store path in the service.env test On a Windows host /srv/plugins is not absolute, so joining it to the service home gave C:/srv/plugins and failed the windows-unit check. Signed-off-by: Ethan Zhang --- .../src/setup/service_plugin_store.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) 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 index 249808d274..689705fc82 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -151,16 +151,20 @@ mod tests { #[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, - "# MESH_LLM_PLUGIN_DIR=/commented\nRUST_LOG=info\nMESH_LLM_PLUGIN_DIR=\"/srv/plugins\"\n", - ); - assert_eq!( - service_plugin_store(&context).unwrap(), - Some(PathBuf::from("/srv/plugins")) + &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())); } } From 9c901480e25f26bc0372485575462729004d3d20 Mon Sep 17 00:00:00 2001 From: "Yiqun (Ethan) Zhang" Date: Mon, 30 Nov 2026 19:37:51 +0900 Subject: [PATCH 17/19] fix(setup): keep setup's plugin install inside its deadline and offer record Check the set offer record under the commit lock so a slow setup run cannot reinstall a plugin another run offered and the operator then removed. Bound the store write lock wait so a suspended writer cannot hold setup past its deadline. Read service.env `export` the way each platform does, resolve a relative plugin store against the Windows service's home, report an archive-installed member as installed, and tell users to rerun the original `plugins install --set` command. Signed-off-by: Yiqun (Ethan) Zhang --- mesh/crates/mesh-llm-commands/src/plugin.rs | 2 +- .../mesh-llm-commands/src/plugin_sets.rs | 12 ++- .../mesh-llm-commands/src/setup/command.rs | 12 ++- .../src/setup/service_plugin_store.rs | 32 ++++++- .../mesh-llm-plugin-manager/src/install.rs | 85 ++++++++++++++++++- .../mesh-llm-plugin-manager/src/sets.rs | 84 ++++++++++++++++-- .../src/store/write_lock.rs | 57 +++++++++++-- mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- 9 files changed, 262 insertions(+), 26 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/plugin.rs b/mesh/crates/mesh-llm-commands/src/plugin.rs index b1957c3bc9..7d63a202c5 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin.rs @@ -281,7 +281,7 @@ async fn install_set_by_name(set: &str) -> Result<()> { writeln!(err, "Failed {name}: {reason}")?; } bail!( - "{} of the plugins in set '{set}' failed to install; rerun `mesh-llm plugins install --set {set}` to retry the rest", + "{} 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() ) } diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 111bfbf64a..2bf0229558 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -93,7 +93,15 @@ pub async fn install_set_command( if catalog.find_set(set_name).is_none() { bail!("{}", no_set_reason(&catalog, set_name, problem)); } - install_set(&catalog, set_name, &SetOffer::default(), options, progress).await + install_set( + &catalog, + set_name, + &SetOffer::default(), + false, + options, + progress, + ) + .await } /// Setup's plugin step. Every failure (offline, a slow catalog host, no such @@ -136,7 +144,7 @@ async fn install_set_for_setup( return SetupPluginsOutcome::Unavailable(no_set_reason(&catalog, set_name, problem)); }; let set_members = set.plugins.clone(); - match install_set(&catalog, set_name, &offer, options, progress).await { + match install_set(&catalog, set_name, &offer, true, options, progress).await { Ok(result) => { let recorded = record_set_offer( &options.store_root, diff --git a/mesh/crates/mesh-llm-commands/src/setup/command.rs b/mesh/crates/mesh-llm-commands/src/setup/command.rs index 3982bc53d8..280a4e1d30 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/command.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/command.rs @@ -247,7 +247,17 @@ impl<'a> CliSetupActions<'a> { Some(context) => context, None => ServiceInstallContext::detect(self.environment.platform, true)?, }; - if let Some(root) = service_plugin_store(&context)? + // 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"); 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 index 689705fc82..f7391dea55 100644 --- a/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs +++ b/mesh/crates/mesh-llm-commands/src/setup/service_plugin_store.rs @@ -61,7 +61,16 @@ fn plugin_dir_from_env_file(contents: &str, platform: SetupPlatform) -> Result { + rest.trim_start() + } + _ => line, + }; let Some((key, raw)) = line.split_once('=') else { continue; }; @@ -196,6 +205,24 @@ mod tests { } } + /// 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(); @@ -207,9 +234,10 @@ mod tests { 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"), - Some(PathBuf::from("/a b")) + (platform == SetupPlatform::MacOs).then(|| PathBuf::from("/a b")) ); assert_eq!( parse(" MESH_LLM_PLUGIN_DIR=/x\nOTHER=/y\n"), diff --git a/mesh/crates/mesh-llm-plugin-manager/src/install.rs b/mesh/crates/mesh-llm-plugin-manager/src/install.rs index ed6b107b3f..919485f112 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/install.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/install.rs @@ -303,13 +303,51 @@ pub async fn install_catalog_entry( 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 { +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( @@ -317,7 +355,7 @@ async fn install_resolved_plugin( options: &PluginInstallOptions, progress: &mut impl PluginProgressReporter, current: Option, - mode: CommitMode, + mode: CommitMode<'_>, ) -> Result { let release_client = GitHubReleaseClient::new()?; progress.report(PluginProgressEvent::ResolvingGitHub { @@ -411,6 +449,7 @@ async fn install_resolved_plugin( })?; 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(), @@ -447,6 +486,8 @@ enum Committed { 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 @@ -455,11 +496,18 @@ fn commit_staged( store: &PluginStore, staged: StagedPluginArchive, name: &str, - mode: CommitMode, + mode: CommitMode<'_>, metadata_for: impl FnOnce(ExtractedPluginArchive) -> InstalledPluginMetadata, ) -> Result { let _lock = store.lock_writes()?; - if mode == CommitMode::CreateOnly + 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)); @@ -1110,6 +1158,35 @@ mod tests { 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] diff --git a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs index 064b416182..9517315ee1 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/sets.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/sets.rs @@ -13,6 +13,7 @@ use crate::{ catalog::{CatalogEntry, PluginCatalog}, install::{ InstallOutcome, PluginInstallOptions, PluginProgressReporter, install_catalog_entry, + install_catalog_entry_unless_offered, }, store::PluginStore, }; @@ -51,6 +52,9 @@ pub struct SetInstallResult { /// `(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"; @@ -84,6 +88,7 @@ impl SetOffer { 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() @@ -135,6 +140,11 @@ pub fn read_set_offer(store_root: &std::path::Path, set_name: &str) -> Result 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. @@ -248,13 +258,9 @@ pub async fn install_set_with

( ) -> Result { let mut result = SetInstallResult::default(); for member in &resolution.members { - if let MemberAvailability::Unavailable(reason) = &member.availability { - result - .unavailable - .push((member.name.clone(), reason.clone())); - continue; - } - // One member's unreadable record fails that member only. + // 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()); @@ -269,6 +275,12 @@ pub async fn install_set_with

( 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. @@ -276,6 +288,9 @@ pub async fn install_set_with

( 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:#}"))), @@ -285,11 +300,15 @@ pub async fn install_set_with

( } /// Install a set from one catalog snapshot: every member is installed at the -/// release that snapshot pins. +/// 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 { @@ -303,7 +322,11 @@ pub async fn install_set( let entry = catalog .find_exact(name) .with_context(|| format!("'{name}' is not in the plugin catalog"))?; - install_catalog_entry(entry, options, progress).await + if respect_offer_record { + install_catalog_entry_unless_offered(entry, set_name, options, progress).await + } else { + install_catalog_entry(entry, options, progress).await + } }) .await } @@ -461,6 +484,49 @@ mod tests { 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] 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 index 8e22a23b88..67903527a0 100644 --- a/mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs +++ b/mesh/crates/mesh-llm-plugin-manager/src/store/write_lock.rs @@ -4,11 +4,24 @@ //! 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. -use std::{fs, fs::OpenOptions, path::Path}; +//! +//! 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. @@ -19,8 +32,12 @@ pub struct StoreWriteLock { 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 never end. + /// 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); @@ -31,9 +48,26 @@ impl StoreWriteLock { .truncate(false) .open(&path) .with_context(|| format!("open plugin store lock {}", path.display()))?; - fs2::FileExt::lock_exclusive(&file) - .with_context(|| format!("lock plugin store {}", path.display()))?; - Ok(Self { file }) + 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())); + } + } + } } } @@ -66,4 +100,17 @@ mod tests { 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/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index f7486f215d..95a86ec465 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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` as an absolute path, otherwise the default; a value with variables, `~`, backslashes, mixed quoting or other shell syntax is reported instead), in attended and unattended runs alike, with no prompt. 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. +- `--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. 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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 46f39fee85..0f64646ae5 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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` as an absolute path, otherwise the default; a value with variables, `~`, backslashes, mixed quoting or other shell syntax is reported instead), in attended and unattended runs alike, with no prompt. 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. +- `--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. 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 From 0a32c99cbf721bb27af78bf9454973ae6429d1ff Mon Sep 17 00:00:00 2001 From: "Yiqun (Ethan) Zhang" Date: Tue, 1 Dec 2026 14:20:30 +0900 Subject: [PATCH 18/19] feat(setup): keep capsules checkpoints local when a plugin set installs it A plugin set installs capsules without the operator choosing it, and the plugin sends signed checkpoints to Action State's hosted witness when its witness setting is unset. Setup and `plugins install --set` now write `witness = "off"` under the capsules plugin settings when they install it, unless the operator already set a witness. A direct `plugins install capsules` keeps the plugin's own default. The plugins README no longer says the plugin makes no network calls without a configured witness. Signed-off-by: Yiqun (Ethan) Zhang --- .../mesh-llm-commands/src/capsules_witness.rs | 147 ++++++++++++++++++ mesh/crates/mesh-llm-commands/src/lib.rs | 1 + mesh/crates/mesh-llm-commands/src/plugin.rs | 7 + .../mesh-llm-commands/src/plugin_sets.rs | 7 + mesh/docs-site/content/reference/cli.mdx | 2 +- mesh/docs/CLI.md | 2 +- mesh/docs/plugins/README.md | 14 +- mesh/docs/specs/mesh-setup-installer.md | 6 + 8 files changed, 182 insertions(+), 4 deletions(-) create mode 100644 mesh/crates/mesh-llm-commands/src/capsules_witness.rs 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..cf0d281152 --- /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. +//! +//! The capsules plugin sends signed checkpoints to Action State's hosted +//! witness when its `witness` setting is unset. A plugin set installs it +//! 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. Steven and Ethan ruled this +//! on Mesh-LLM/mesh-llm#3219: the hosted default stays for an operator who +//! installs capsules directly, and the operator who wants a witness sets it. + +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`, it 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 a05cd8d874..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; diff --git a/mesh/crates/mesh-llm-commands/src/plugin.rs b/mesh/crates/mesh-llm-commands/src/plugin.rs index 7d63a202c5..c4786334b4 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin.rs @@ -260,6 +260,13 @@ async fn install_set_by_name(set: &str) -> Result<()> { 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!( diff --git a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs index 2bf0229558..a237aa243f 100644 --- a/mesh/crates/mesh-llm-commands/src/plugin_sets.rs +++ b/mesh/crates/mesh-llm-commands/src/plugin_sets.rs @@ -146,6 +146,13 @@ async fn install_set_for_setup( 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, diff --git a/mesh/docs-site/content/reference/cli.mdx b/mesh/docs-site/content/reference/cli.mdx index 95a86ec465..18deac1fad 100644 --- a/mesh/docs-site/content/reference/cli.mdx +++ b/mesh/docs-site/content/reference/cli.mdx @@ -217,7 +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. 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. +- `--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 diff --git a/mesh/docs/CLI.md b/mesh/docs/CLI.md index 0f64646ae5..af5629fd75 100644 --- a/mesh/docs/CLI.md +++ b/mesh/docs/CLI.md @@ -111,7 +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. 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. +- `--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 diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index fec0cb4fba..7bf3c6e66f 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -307,7 +307,8 @@ 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. +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: @@ -573,7 +574,16 @@ 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. +A node that installed capsules by itself sends signed checkpoints (log size, +root commitment, the previous one, a timestamp and the log's identity; never +prompts, outputs or request contents) to Action State's hosted witness once it +has activity, unless the `witness` setting is `off` or names other witnesses. +Installing capsules through a plugin set (`mesh-llm setup`, or +`mesh-llm plugins install --set`) writes `witness = "off"` into its +`[plugin.settings]` in `config.toml`, so a node whose operator never chose it +keeps its checkpoints local 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 5ab24f5d64..893f24bb75 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -114,6 +114,12 @@ 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 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 From 1373538d7915c6b81863e3a76fa0420cfb0eb4b7 Mon Sep 17 00:00:00 2001 From: "Yiqun (Ethan) Zhang" Date: Tue, 1 Dec 2026 16:26:26 +0900 Subject: [PATCH 19/19] docs(plugins): describe capsules v0.1.26's witness default and why setup still writes off Signed-off-by: Yiqun (Ethan) Zhang --- .../mesh-llm-commands/src/capsules_witness.rs | 16 +++++++------- mesh/docs/plugins/README.md | 21 ++++++++++--------- mesh/docs/specs/mesh-setup-installer.md | 6 ++++-- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/mesh/crates/mesh-llm-commands/src/capsules_witness.rs b/mesh/crates/mesh-llm-commands/src/capsules_witness.rs index cf0d281152..a3690c64e7 100644 --- a/mesh/crates/mesh-llm-commands/src/capsules_witness.rs +++ b/mesh/crates/mesh-llm-commands/src/capsules_witness.rs @@ -1,13 +1,13 @@ //! Keeps checkpoint delivery off for a capsules install made through a plugin //! set. //! -//! The capsules plugin sends signed checkpoints to Action State's hosted -//! witness when its `witness` setting is unset. A plugin set installs it -//! 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. Steven and Ethan ruled this -//! on Mesh-LLM/mesh-llm#3219: the hosted default stays for an operator who -//! installs capsules directly, and the operator who wants a witness sets it. +//! 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; @@ -35,7 +35,7 @@ pub fn keep_installed_capsules_local(installed: &[String]) { 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`, it sends signed checkpoints to Action State's hosted witness." + "⚠️ 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." ), }; } diff --git a/mesh/docs/plugins/README.md b/mesh/docs/plugins/README.md index 7bf3c6e66f..28ee2c0a42 100644 --- a/mesh/docs/plugins/README.md +++ b/mesh/docs/plugins/README.md @@ -574,16 +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. -A node that installed capsules by itself sends signed checkpoints (log size, -root commitment, the previous one, a timestamp and the log's identity; never -prompts, outputs or request contents) to Action State's hosted witness once it -has activity, unless the `witness` setting is `off` or names other witnesses. -Installing capsules through a plugin set (`mesh-llm setup`, or -`mesh-llm plugins install --set`) writes `witness = "off"` into its -`[plugin.settings]` in `config.toml`, so a node whose operator never chose it -keeps its checkpoints local until the operator sets a witness (Configuration -tab, or `witness` under `[plugin.settings]`). A `witness` the operator already -set is left alone. +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 893f24bb75..318072941e 100644 --- a/mesh/docs/specs/mesh-setup-installer.md +++ b/mesh/docs/specs/mesh-setup-installer.md @@ -117,8 +117,10 @@ 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 Action State's hosted witness; the operator opts in by setting -a witness. A direct `plugins install capsules` keeps the plugin's own default. +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