diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 615cf13d..6b9a8740 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -4875,29 +4875,43 @@ inside an app bundle or installation directory. The `plugins.commandInstallers.*` commands implement [Command installers](../../shared/plugins/contract/v1/README.md#command-installers). They revalidate the manifest, read nothing and start nothing. -`plugins.commandInstallers.requirements` accepts `{ manifest }` and returns -`requirements: { consumers: [{ kind, id, commands: [{ command, installer }] }], -installers: [{ id, commands, tool, minimumVersion, mayUseNetwork, targets }] }`. +`plugins.commandInstallers.requirements` accepts `{ manifest, platform?: { os, +arch } }` and returns `requirements: { consumers: [{ kind, id, commands: [{ +command, installer }] }], installers: [{ id, commands, tool, minimumVersion, +download: null | { version }, mayUseNetwork, targets }] }`. `kind` is `languageServer`, `buildProvider`, `vcsProvider`, `debugAdapter` or `backend`; `id` is the language, build system, VCS or adapter ID, `null` for -the backend; `installer` is `null` for a command no installer provides. +the backend; `installer` is `null` for a command no installer provides. With +`platform`, a download installer without an archive for it is left out of +`installers` and its commands have a `null` installer. `plugins.commandInstallers.plan` accepts `{ manifest, installerID, target: -"managed" | "toolDefault", installDirectory? }` and returns `plan: { installer, -target, commands, tool, minimumVersion, mayUseNetwork, timeoutMilliseconds, -arguments, environment, commandDirectory, directoryProbes: [{ arguments }] }`. -A `managed` plan needs the absolute directory the host made and expands +"managed" | "toolDefault", installDirectory?, platform? }` and returns `plan: { +installer, target, commands, tool, minimumVersion, mayUseNetwork, +timeoutMilliseconds, arguments, environment, commandDirectory, directoryProbes: +[{ arguments }], download }`. For a tool installer `download` is `null`. A +`managed` plan needs the absolute directory the host made and expands `${installDirectory}` in it; `commandDirectory` is that directory or the declared path below it, and `directoryProbes` is empty. A `toolDefault` plan takes no `installDirectory`, has a `null` `commandDirectory` and lists the -probes. `plugins.commandInstallers.defaultDirectory` accepts `{ manifest, +probes. A download installer's plan needs `platform`, takes no +`installDirectory`, has empty `arguments`, `environment` and +`directoryProbes`, a `null` `commandDirectory`, and `download: { installer, +version, os, arch, url, sha256, archive, stripPrefix, cacheKey, +commandDirectory, mirrors? }` for the platform's archive. `cacheKey` is the +lowercase SHA-256 of the compact JSON `{installer, version, os, arch, url, +sha256, archive, stripPrefix}`, mirrors left out; `commandDirectory` is +relative to the extracted root. `plugins.commandInstallers.defaultDirectory` accepts `{ manifest, installerID, outputs }`, one standard output per probe in plan order (`null` for a probe that failed), and returns `directory`: the first probe output that names an absolute directory, its first path-list entry for a `pathList` probe, with `append` joined; `null` when none does. Paths follow the platform Core runs on. Refusals are `plugin.commandInstaller.unknown`, `plugin.commandInstaller.targetUndeclared`, -`plugin.commandInstaller.directoryInvalid` and -`plugin.commandInstaller.probeOutputsInvalid`; the golden cases are +`plugin.commandInstaller.directoryInvalid`, +`plugin.commandInstaller.probeOutputsInvalid`, +`plugin.commandInstaller.platformInvalid` (an unsupported `platform`, or none +for a download plan) and `plugin.commandInstaller.unavailable` (no archive for +the platform); the golden cases are `shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`. The `plugins.managedRuntimes.*` commands implement diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 44c879df..308d06cc 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -67,6 +67,8 @@ const PROJECT_GENERATOR_TOOL_FIXTURE: &str = contract_file!("fixtures/project-generators/project-generator-tool-field.plugin.json"); const COMMAND_INSTALLER_FIXTURE: &str = contract_file!("fixtures/command-installers/command-installer.plugin.json"); +const COMMAND_INSTALLER_DOWNLOAD_FIXTURE: &str = + contract_file!("fixtures/command-installers/command-installer-download.plugin.json"); const COMMAND_INSTALLER_PLANS: &str = contract_file!("fixtures/command-installers/command-installer-plans.json"); const RUN_CONFIGURATION_TYPES_FIXTURE: &str = @@ -106,6 +108,7 @@ fn fixture(name: &str) -> Value { "project-generator.plugin.json" => PROJECT_GENERATOR_FIXTURE, "project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE, "command-installer.plugin.json" => COMMAND_INSTALLER_FIXTURE, + "command-installer-download.plugin.json" => COMMAND_INSTALLER_DOWNLOAD_FIXTURE, "run-configuration-types.plugin.json" => RUN_CONFIGURATION_TYPES_FIXTURE, "before-launch-tasks.plugin.json" => BEFORE_LAUNCH_TASKS_FIXTURE, other => panic!("unknown fixture {other}"), @@ -140,6 +143,7 @@ fn contract_fixtures_and_official_plugins_validate() { EDITOR_PROVIDERS_FIXTURE, PROJECT_GENERATOR_TOOL_FIXTURE, COMMAND_INSTALLER_FIXTURE, + COMMAND_INSTALLER_DOWNLOAD_FIXTURE, RUN_CONFIGURATION_TYPES_FIXTURE, BEFORE_LAUNCH_TASKS_FIXTURE, ] { @@ -279,7 +283,8 @@ fn command_installer_fixtures_match_on_this_host() { for case in plans["cases"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); let specific = &case["platforms"][platform]; - let mut payload = json!({ "manifest": fixture("command-installer.plugin.json") }); + let plugin = case.get("plugin").unwrap_or(&plans["plugin"]); + let mut payload = json!({ "manifest": fixture(plugin.as_str().unwrap()) }); for source in [&case["payload"], &specific["payload"]] { for (field, value) in source.as_object().into_iter().flatten() { payload[field] = value.clone(); @@ -342,6 +347,78 @@ fn command_installers_are_reviewed_programs() { assert_ne!(programs(changed), before); } +/// A download installer's review entry shows every archive it may fetch, so +/// a new URL or digest is a new program the user approves again; it runs no +/// tool, so the entry has no tool or arguments. +#[test] +fn download_installers_are_reviewed_programs() { + let programs = |manifest: Value| { + let outcome = lithe_plugin_marketplace::install_review_command(json!({ + "manifest": manifest, + })) + .expect("payload is well formed"); + outcome["review"]["programs"] + .as_array() + .unwrap() + .iter() + .filter(|program| program["kind"] == "commandInstaller") + .cloned() + .collect::>() + }; + let manifest = fixture("command-installer-download.plugin.json"); + let before = programs(manifest.clone()); + assert_eq!(before.len(), 1); + let program = &before[0]; + assert_eq!(program["installer"], "sample-lldb"); + assert_eq!(program["timeoutSeconds"], 900); + assert!(program.get("tool").is_none() && program.get("arguments").is_none()); + let artifacts = program["download"]["artifacts"].as_array().unwrap(); + assert_eq!(artifacts.len(), 3); + // The review lists the digest Core checks, in lowercase. + let macos = artifacts + .iter() + .find(|artifact| artifact["os"] == "macos") + .unwrap(); + assert_eq!( + macos["sha256"], + "2f114a990e1b368dd1dbd33c80c0e719767af2d228391ec0df0571c957f9ac91" + ); + for (pointer, value) in [ + ( + "/commandInstallers/0/download/artifacts/0/url", + json!("https://downloads.example.org/other.zip"), + ), + ( + "/commandInstallers/0/download/artifacts/1/sha256", + json!("0".repeat(64)), + ), + ("/commandInstallers/0/download/version", json!("1.2.4")), + ] { + let mut changed = manifest.clone(); + *changed.pointer_mut(pointer).unwrap() = value; + assert_ne!(programs(changed), before, "{pointer}"); + } +} + +/// A host that declares `commandInstallers` 0 does not know download +/// installers, so it refuses a plugin that needs them before installing it. +#[test] +fn download_installers_need_a_host_with_version_1() { + let manifest = fixture("command-installer-download.plugin.json"); + let host = json!({ "commandInstallers": [0], "debugAdapters": [0], "languages": [0] }); + let refused = validate_command(json!({ "manifest": manifest, "hostCapabilities": host })) + .expect("payload is well formed"); + assert_eq!( + refused["error"]["code"], "plugin.api.unsupported", + "{refused}" + ); + assert_eq!(refused["error"]["field"], "requires.commandInstallers"); + let host = json!({ "commandInstallers": [0, 1], "debugAdapters": [0], "languages": [0] }); + let accepted = validate_command(json!({ "manifest": manifest, "hostCapabilities": host })) + .expect("payload is well formed"); + assert_eq!(accepted["status"], "ok", "{accepted}"); +} + /// A malformed request is a Core failure, not a rejection. #[test] fn command_installer_requests_decode_strictly() { @@ -354,6 +431,20 @@ fn command_installer_requests_decode_strictly() { json!({ "manifest": manifest, "installerID": "sample-ls" }) ) .is_err()); + // A platform names a supported pair by its two fields and nothing else. + let manifest = fixture("command-installer-download.plugin.json"); + assert!(command_installer_plan_command(json!({ + "manifest": manifest, + "installerID": "sample-lldb", + "target": "managed", + "platform": { "os": "macos" } + })) + .is_err()); + assert!(command_installer_requirements_command(json!({ + "manifest": manifest, + "platform": { "os": "macos", "arch": "arm64", "libc": "musl" } + })) + .is_err()); } #[test] diff --git a/rust/crates/plugin-manifest/src/archives.rs b/rust/crates/plugin-manifest/src/archives.rs new file mode 100644 index 00000000..45aee66c --- /dev/null +++ b/rust/crates/plugin-manifest/src/archives.rs @@ -0,0 +1,159 @@ +//! Pinned download archives: the platform target, source URLs, digest, +//! format and layout paths that `managedRuntimes` dependencies and +//! `commandInstallers` downloads share. Core validates the declaration and +//! selects the archive for the host's platform; the host downloads, checks the +//! digest and extracts. + +use super::*; +use lithe_platform::Platform; +use url::Url; + +/// Most platform archives one dependency or download declares: one per +/// supported operating system and architecture. +pub(crate) const MAX_ARTIFACTS: usize = 6; + +/// Most fallback URLs one archive declares. +pub(crate) const MAX_MIRRORS: usize = 8; + +/// Operating systems an archive may target. +pub(crate) const ARCHIVE_OPERATING_SYSTEMS: &[&str] = &["macos", "windows", "linux"]; + +/// Longest archive URL, in bytes. +const MAX_URL_BYTES: usize = 4096; + +/// Longest layout path inside an archive, in bytes. +const MAX_LAYOUT_PATH_BYTES: usize = 512; + +/// Text that is not empty, at most `maximum` bytes, without surrounding +/// whitespace or control characters. +pub(crate) fn bounded_text(value: &str, maximum: usize) -> bool { + !value.is_empty() + && value.len() <= maximum + && value.trim() == value + && !value.chars().any(char::is_control) +} + +/// A layout path inside an archive: empty, or `/`-separated parts without an +/// empty, `.` or `..` part, backslash or colon, so it means the same on every +/// host. Native extraction also checks filesystem aliases and link targets. +pub(crate) fn is_archive_layout_path(value: &str) -> bool { + value.is_empty() + || (bounded_text(value, MAX_LAYOUT_PATH_BYTES) + && !value.contains(['\\', ':']) + && value + .split('/') + .all(|part| !part.is_empty() && part != "." && part != "..")) +} + +/// Whether `os` and `arch` name a platform an archive may target. +pub(crate) fn is_archive_platform(os: &str, arch: &str) -> bool { + ARCHIVE_OPERATING_SYSTEMS.contains(&os) && KNOWN_ARCHITECTURES.contains(&arch) +} + +/// The host platform a request selects an archive for. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ArchivePlatform { + /// macos, windows or linux. + pub(crate) os: String, + /// arm64 or x86_64. + pub(crate) arch: String, +} + +impl ArchivePlatform { + /// Whether an archive may target this platform. + pub(crate) fn is_supported(&self) -> bool { + is_archive_platform(&self.os, &self.arch) + } + + /// Whether an archive declared for `os` and `arch` is this platform's. + pub(crate) fn matches(&self, os: &str, arch: &str) -> bool { + self.os == os && self.arch == arch + } + + /// The path rules of this platform's filesystem. + pub(crate) fn native_paths(&self) -> Platform { + if self.os == "windows" { + Platform::Windows + } else { + Platform::Unix + } + } +} + +/// Where one archive comes from and how to read it. +pub(crate) struct ArchiveSource<'a> { + pub(crate) url: &'a str, + pub(crate) mirrors: &'a [String], + pub(crate) sha256: &'a mut String, + pub(crate) archive: &'a str, +} + +/// Checks one archive's URL, mirrors, digest and format, and lowercases the +/// digest. `mirrors_allowed` runs only when the archive declares mirrors and +/// rejects them when the manifest's capability version does not have them. +pub(crate) fn validate_archive_source( + field: &str, + source: ArchiveSource<'_>, + mirrors_allowed: impl FnOnce() -> Validation<()>, +) -> Validation<()> { + if !is_https_source(source.url) { + return Err(invalid( + format!("{field}.url"), + "An archive URL uses HTTPS without credentials or fragments.", + )); + } + if !source.mirrors.is_empty() { + mirrors_allowed()?; + if source.mirrors.len() > MAX_MIRRORS { + return Err(invalid( + format!("{field}.mirrors"), + format!("An archive declares at most {MAX_MIRRORS} mirror URLs."), + )); + } + let mut seen = BTreeSet::new(); + seen.insert(source.url); + for (index, mirror) in source.mirrors.iter().enumerate() { + let entry = format!("{field}.mirrors[{index}]"); + if !is_https_source(mirror) { + return Err(invalid( + entry, + "A mirror URL uses HTTPS without credentials or fragments.", + )); + } + if !seen.insert(mirror.as_str()) { + return Err(invalid( + entry, + "Mirror URLs are unique and differ from the primary URL.", + )); + } + } + } + if source.sha256.len() != 64 || !source.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(invalid( + format!("{field}.sha256"), + "An archive pins its complete SHA-256 digest.", + )); + } + source.sha256.make_ascii_lowercase(); + if !["zip", "tar.gz"].contains(&source.archive) { + return Err(invalid( + format!("{field}.archive"), + "An archive format is zip or tar.gz.", + )); + } + Ok(()) +} + +/// An HTTPS URL with a host, without credentials or a fragment. +fn is_https_source(value: &str) -> bool { + let Ok(url) = Url::parse(value) else { + return false; + }; + bounded_text(value, MAX_URL_BYTES) + && url.scheme() == "https" + && url.host_str().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() +} diff --git a/rust/crates/plugin-manifest/src/command_installers.rs b/rust/crates/plugin-manifest/src/command_installers.rs index f53dfc21..b0a827a4 100644 --- a/rust/crates/plugin-manifest/src/command_installers.rs +++ b/rust/crates/plugin-manifest/src/command_installers.rs @@ -1,20 +1,28 @@ //! `commandInstallers[]`: how the host installs a bare command that one of the //! plugin's `systemCommand` launches needs and the machine lacks. //! -//! The host never installs on its own. It shows the user the exact command -//! line, whether it uses the network and where the command will land, and -//! runs the installation only after the user confirms. The installation is -//! one process of a tool the plugin requires, run either into a directory -//! Lithe owns for the plugin (`managed`) or wherever the tool installs by -//! default (`toolDefault`). This module validates the declaration, lists which -//! launch needs which command, expands the plan for the chosen target, and -//! reads the directory a `toolDefault` installation uses from the output of -//! the tool's own probes. +//! The host never installs on its own. It shows the user what the +//! installation runs or downloads, whether it uses the network and where the +//! command will land, and installs only after the user confirms. A tool +//! installation is one process of a tool the plugin requires, run either into +//! a directory Lithe owns for the plugin (`managed`) or wherever the tool +//! installs by default (`toolDefault`). A download installation (version 1) +//! fetches a pinned archive for the host's platform, checks its SHA-256 +//! digest and extracts it into the plugin's managed directory; the archive +//! rules are those of `managedRuntimes`. This module validates the +//! declaration, lists which launch needs which command, expands the plan for +//! the chosen target, and reads the directory a `toolDefault` installation +//! uses from the output of the tool's own probes. //! //! Note: the decision is recorded in .agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md +use super::archives::{ + bounded_text, is_archive_layout_path, validate_archive_source, ArchivePlatform, ArchiveSource, + MAX_ARTIFACTS, +}; use super::*; use lithe_platform::{paths, Platform}; +use sha2::{Digest, Sha256}; /// Most installers one plugin may declare. const MAX_COMMAND_INSTALLERS: usize = 16; @@ -40,6 +48,12 @@ const DEFAULT_TIMEOUT_SECONDS: u64 = 600; /// Longest timeout an installation may declare. const MAX_TIMEOUT_SECONDS: u64 = 3600; +/// Longest upstream version of a download, in bytes. +const MAX_DOWNLOAD_VERSION_BYTES: usize = 128; + +/// First `commandInstallers` version with download installers. +const DOWNLOAD_VERSION: u32 = 1; + /// Program kinds of the `systemCommand` launches an installer may serve, the /// consumer kind the host shows, and the program key that names the consumer. /// A plugin backend has a single process and so no key. @@ -55,7 +69,9 @@ const SYSTEM_COMMAND_PROGRAMS: &[(&str, &str, Option<&str>)] = &[ ("systemVcsProvider", "vcsProvider", Some("vcs")), ]; -/// One way to install bare commands the plugin's launches name. +/// One way to install bare commands the plugin's launches name: a run of a +/// tool (`tool` and `arguments`) or a pinned download (`download`), never +/// both. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct CommandInstallerDeclaration { @@ -65,24 +81,68 @@ pub(crate) struct CommandInstallerDeclaration { /// `systemCommand` launch of this manifest and by no other installer. pub(crate) commands: Vec, /// Tool-definition ID, listed in `requiresTools`, whose executable runs - /// the installation. - pub(crate) tool: String, + /// the installation. Required unless the installer downloads. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) tool: Option, /// Lowest acceptable version of `tool`. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) minimum_version: Option, /// Arguments after the tool's executable, used by a target that does not - /// replace them. Literal: no template variables. - pub(crate) arguments: Vec, + /// replace them. Literal: no template variables. Required with `tool`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) arguments: Option>, + /// Pinned archives to download instead of running a tool; needs + /// `requires.commandInstallers` 1. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) download: Option, /// Whether the installation may download; the host shows it before the - /// user confirms. + /// user confirms. Always true for a download installer. pub(crate) may_use_network: bool, - /// How long the host lets the installation run, 1 to 3600 seconds. + /// How long the host lets the installation run, 1 to 3600 seconds. A + /// download installer's timeout covers the download and the extraction. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) timeout_seconds: Option, - /// Where the installation may put the commands; at least one target. + /// Where the installation may put the commands; at least one target. A + /// download installer has only `managed`. pub(crate) targets: InstallTargets, } +/// The archives of one upstream release, one per platform it supports. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct CommandDownload { + /// Upstream release identity the host shows, independent of the + /// plugin's own version. + version: String, + /// One archive per supported operating system and architecture, ordered + /// by platform after validation. + artifacts: Vec, +} + +/// One platform's archive. The rules are those of a `managedRuntimes` +/// artifact. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct CommandArchive { + /// macos, windows or linux. + os: String, + /// arm64 or x86_64. + arch: String, + /// HTTPS URL of the archive. + url: String, + /// Fallback HTTPS URLs serving the same bytes. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + mirrors: Vec, + /// SHA-256 digest of the archive, lowercased after validation. + sha256: String, + /// zip or tar.gz; the host never infers a format from a URL suffix. + archive: String, + /// Archive root removed while extracting; empty removes nothing. Every + /// entry lies below it. + #[serde(default)] + strip_prefix: String, +} + /// The locations the user may choose between. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -95,9 +155,10 @@ pub(crate) struct InstallTargets { pub(crate) tool_default: Option, } -/// Installation into the directory the host chose for the plugin. Its -/// arguments or environment must name `${installDirectory}`, which is the -/// only template variable of this contract. +/// Installation into the directory the host chose for the plugin. A tool +/// installer's arguments or environment must name `${installDirectory}`, +/// which is the only template variable of this contract. A download +/// installer's managed target sets only `commandDirectory`. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct ManagedTarget { @@ -109,7 +170,7 @@ pub(crate) struct ManagedTarget { environment: BTreeMap, /// Package-style relative path, below the install directory, of the /// directory the commands land in; the install directory itself when - /// absent. + /// absent. For a download, the path is below the extracted root. #[serde(default, skip_serializing_if = "Option::is_none")] command_directory: Option, } @@ -227,11 +288,14 @@ fn check_environment_names(environment: &BTreeMap, field: &str) } impl CommandInstallerDeclaration { + /// Checks one installer; `version` is the manifest's + /// `requires.commandInstallers`. fn validate( - &self, + &mut self, field: &str, launched: &BTreeSet, runtime_tools: RuntimeTools<'_>, + version: u32, ) -> Validation<()> { if !is_identifier(&self.id) || self.id.len() > 64 { return Err(invalid( @@ -264,10 +328,6 @@ impl CommandInstallerDeclaration { )); } } - runtime_tools.check(&self.tool, format!("{field}.tool"))?; - if let Some(version) = &self.minimum_version { - validate_minimum_version(version, &format!("{field}.minimumVersion"))?; - } if let Some(seconds) = self.timeout_seconds { if !(1..=MAX_TIMEOUT_SECONDS).contains(&seconds) { return Err(invalid( @@ -276,10 +336,6 @@ impl CommandInstallerDeclaration { )); } } - check_arguments(&self.arguments, &format!("{field}.arguments"))?; - for (index, argument) in self.arguments.iter().enumerate() { - check_literal(argument, &format!("{field}.arguments[{index}]"))?; - } let targets = format!("{field}.targets"); if self.targets.managed.is_none() && self.targets.tool_default.is_none() { return Err(invalid( @@ -287,6 +343,29 @@ impl CommandInstallerDeclaration { "An installer declares at least one target.", )); } + if self.download.is_some() { + return self.validate_download(field, version); + } + let Some(tool) = &self.tool else { + return Err(invalid( + format!("{field}.tool"), + "An installer runs a tool or, with requires.commandInstallers 1, downloads an archive.", + )); + }; + runtime_tools.check(tool, format!("{field}.tool"))?; + if let Some(version) = &self.minimum_version { + validate_minimum_version(version, &format!("{field}.minimumVersion"))?; + } + let Some(arguments) = &self.arguments else { + return Err(invalid( + format!("{field}.arguments"), + "A tool installer lists the arguments it passes to the tool.", + )); + }; + check_arguments(arguments, &format!("{field}.arguments"))?; + for (index, argument) in arguments.iter().enumerate() { + check_literal(argument, &format!("{field}.arguments[{index}]"))?; + } if let Some(managed) = &self.targets.managed { self.validate_managed(managed, &format!("{targets}.managed"))?; } @@ -296,6 +375,128 @@ impl CommandInstallerDeclaration { Ok(()) } + /// Checks a download installer: no tool, network use declared, only the + /// managed target with at most a command directory, and archives that + /// follow the `managedRuntimes` rules. + fn validate_download(&mut self, field: &str, version: u32) -> Validation<()> { + if version < DOWNLOAD_VERSION { + return Err(invalid( + "requires.commandInstallers", + "Download installers require requires.commandInstallers >= 1.", + )); + } + for (name, present) in [ + ("tool", self.tool.is_some()), + ("minimumVersion", self.minimum_version.is_some()), + ("arguments", self.arguments.is_some()), + ] { + if present { + return Err(invalid( + format!("{field}.{name}"), + "A download installer runs no tool; it declares download instead.", + )); + } + } + if !self.may_use_network { + return Err(invalid( + format!("{field}.mayUseNetwork"), + "A download installer uses the network.", + )); + } + let targets = format!("{field}.targets"); + if self.targets.tool_default.is_some() { + return Err(invalid( + format!("{targets}.toolDefault"), + "A download installer extracts only into the managed directory.", + )); + } + let Some(managed) = &self.targets.managed else { + return Err(invalid( + format!("{targets}.managed"), + "A download installer extracts into the managed directory.", + )); + }; + let managed_field = format!("{targets}.managed"); + if managed.arguments.is_some() { + return Err(invalid( + format!("{managed_field}.arguments"), + "A download installer runs no tool and passes no arguments.", + )); + } + if !managed.environment.is_empty() { + return Err(invalid( + format!("{managed_field}.environment"), + "A download installer runs no tool and sets no environment.", + )); + } + if let Some(directory) = &managed.command_directory { + if !is_safe_relative_path(directory) || !is_archive_layout_path(directory) { + return Err(invalid( + format!("{managed_field}.commandDirectory"), + "The command directory is a relative path inside the extracted archive.", + )); + } + } + let Some(download) = &mut self.download else { + return Ok(()); + }; + let field = format!("{field}.download"); + if !bounded_text(&download.version, MAX_DOWNLOAD_VERSION_BYTES) { + return Err(invalid( + format!("{field}.version"), + format!("A download version is a nonempty upstream identity of at most {MAX_DOWNLOAD_VERSION_BYTES} bytes."), + )); + } + if !(1..=MAX_ARTIFACTS).contains(&download.artifacts.len()) { + return Err(invalid( + format!("{field}.artifacts"), + format!("A download declares from 1 to {MAX_ARTIFACTS} platform archives."), + )); + } + let mut platforms = BTreeSet::new(); + for (index, artifact) in download.artifacts.iter_mut().enumerate() { + let field = format!("{field}.artifacts[{index}]"); + if !archives::is_archive_platform(&artifact.os, &artifact.arch) + || !platforms.insert((artifact.os.clone(), artifact.arch.clone())) + { + return Err(invalid( + &field, + "Archives have unique supported operating-system and architecture pairs.", + )); + } + validate_archive_source( + &field, + ArchiveSource { + url: &artifact.url, + mirrors: &artifact.mirrors, + sha256: &mut artifact.sha256, + archive: &artifact.archive, + }, + || Ok(()), + )?; + if !is_archive_layout_path(&artifact.strip_prefix) { + return Err(invalid( + format!("{field}.stripPrefix"), + "An archive path is a bounded relative path without traversal.", + )); + } + } + download + .artifacts + .sort_by(|left, right| (&left.os, &left.arch).cmp(&(&right.os, &right.arch))); + Ok(()) + } + + /// The archive of a download installer for `platform`, if it has one. + fn archive_for(&self, platform: &ArchivePlatform) -> Option<&CommandArchive> { + self.download.as_ref().and_then(|download| { + download + .artifacts + .iter() + .find(|artifact| platform.matches(&artifact.os, &artifact.arch)) + }) + } + fn validate_managed(&self, managed: &ManagedTarget, field: &str) -> Validation<()> { let mut names_directory = false; if let Some(arguments) = &managed.arguments { @@ -327,7 +528,10 @@ impl CommandInstallerDeclaration { } fn effective_arguments<'a>(&'a self, replacement: &'a Option>) -> &'a [String] { - replacement.as_deref().unwrap_or(&self.arguments) + replacement + .as_deref() + .or(self.arguments.as_deref()) + .unwrap_or_default() } fn timeout_milliseconds(&self) -> u64 { @@ -409,11 +613,16 @@ impl DeclarativePluginManifest { .into_iter() .flat_map(|consumer| consumer.commands) .collect(); + let version = self + .requires + .get(capabilities::COMMAND_INSTALLERS) + .copied() + .unwrap_or(0); let mut ids = BTreeSet::new(); let mut installed = BTreeSet::new(); - for (index, installer) in self.command_installers.iter().enumerate() { + for (index, installer) in self.command_installers.iter_mut().enumerate() { let field = format!("commandInstallers[{index}]"); - installer.validate(&field, &launched, runtime_tools)?; + installer.validate(&field, &launched, runtime_tools, version)?; if !ids.insert(installer.id.clone()) { return Err(invalid( format!("{field}.id"), @@ -480,8 +689,20 @@ struct CommandConsumer { } /// The install review entry of one installer: everything that decides what -/// the installation runs. +/// the installation runs or downloads. A tool installer's entry is the same +/// as in version 0. pub(crate) fn programs(installer: &CommandInstallerDeclaration) -> Value { + if let Some(download) = &installer.download { + return json!({ + "kind": "commandInstaller", + "installer": installer.id, + "commands": installer.commands, + "download": download, + "targets": installer.targets, + "mayUseNetwork": installer.may_use_network, + "timeoutSeconds": installer.timeout_seconds.unwrap_or(DEFAULT_TIMEOUT_SECONDS), + }); + } json!({ "kind": "commandInstaller", "installer": installer.id, @@ -499,10 +720,32 @@ pub(crate) fn programs(installer: &CommandInstallerDeclaration) -> Value { #[serde(rename_all = "camelCase", deny_unknown_fields)] struct RequirementsPayload { manifest: Value, + /// The host's platform. With it, a download installer without an + /// archive for the platform is left out. + #[serde(default)] + platform: Option, +} + +/// Rejects a platform no archive may target. +fn check_platform(platform: Option<&ArchivePlatform>) -> Validation<()> { + match platform { + Some(platform) if !platform.is_supported() => Err(platform_invalid()), + _ => Ok(()), + } +} + +fn platform_invalid() -> PluginRejection { + PluginRejection::at( + "plugin.commandInstaller.platformInvalid", + "platform", + "A download installation needs a supported operating system and architecture.", + ) } /// `plugins.commandInstallers.requirements`: lists every launch that starts -/// a bare command, the installer of each command, and the installers. +/// a bare command, the installer of each command, and the installers. Given +/// the host's platform, a download installer without an archive for it is +/// left out, and its commands have no installer. pub fn command_installer_requirements_command(payload: Value) -> Result { let payload: RequirementsPayload = decode_payload(payload, "plugins.commandInstallers.requirements")?; @@ -511,9 +754,17 @@ pub fn command_installer_requirements_command(payload: Value) -> Result Validation<(&'static str, Value)> { let manifest = validate_manifest_value(payload.manifest)?; + check_platform(payload.platform.as_ref())?; + let offered: Vec<&CommandInstallerDeclaration> = manifest + .command_installers + .iter() + .filter(|installer| match (&installer.download, &payload.platform) { + (Some(_), Some(platform)) => installer.archive_for(platform).is_some(), + _ => true, + }) + .collect(); let installer_of = |command: &str| { - manifest - .command_installers + offered .iter() .find(|installer| installer.commands.iter().any(|name| name == command)) .map(|installer| installer.id.clone()) @@ -532,8 +783,7 @@ fn requirements(payload: RequirementsPayload) -> Validation<(&'static str, Value }) }) .collect(); - let installers: Vec = manifest - .command_installers + let installers: Vec = offered .iter() .map(|installer| { json!({ @@ -541,6 +791,9 @@ fn requirements(payload: RequirementsPayload) -> Validation<(&'static str, Value "commands": installer.commands, "tool": installer.tool, "minimumVersion": installer.minimum_version, + "download": installer.download.as_ref().map(|download| json!({ + "version": download.version, + })), "mayUseNetwork": installer.may_use_network, "targets": installer.target_names(), }) @@ -559,16 +812,23 @@ struct PlanPayload { #[serde(rename = "installerID")] installer_id: String, target: InstallTarget, - /// Absolute directory the host made for a managed installation. + /// Absolute directory the host made for a managed tool installation. #[serde(default)] install_directory: Option, + /// The host's platform, which selects a download installer's archive. + #[serde(default)] + platform: Option, } /// `plugins.commandInstallers.plan`: expands one installer for the target -/// the user chose. The host resolves `tool`, runs it with `arguments` and -/// `environment` under the timeout, and then looks for the commands in -/// `commandDirectory`, or for `toolDefault` in the directory the probes -/// report. +/// the user chose. For a tool installer the host resolves `tool`, runs it +/// with `arguments` and `environment` under the timeout, and then looks for +/// the commands in `commandDirectory`, or for `toolDefault` in the directory +/// the probes report. For a download installer `download` names the archive +/// for the host's platform; the host downloads it, checks the digest, +/// extracts it into a directory of its own below the plugin's managed +/// directory under the timeout, and looks for the commands in +/// `download.commandDirectory` below the extracted root. pub fn command_installer_plan_command(payload: Value) -> Result { let payload: PlanPayload = decode_payload(payload, "plugins.commandInstallers.plan")?; Ok(outcome(plan(payload, Platform::HOST))) @@ -577,6 +837,7 @@ pub fn command_installer_plan_command(payload: Value) -> Result Validation<(&'static str, Value)> { let manifest = validate_manifest_value(payload.manifest)?; let installer = manifest.command_installer(&payload.installer_id)?; + check_platform(payload.platform.as_ref())?; let undeclared = || { PluginRejection::at( "plugin.commandInstaller.targetUndeclared", @@ -602,7 +863,37 @@ fn plan(payload: PlanPayload, platform: Platform) -> Validation<(&'static str, V "minimumVersion": installer.minimum_version, "mayUseNetwork": installer.may_use_network, "timeoutMilliseconds": installer.timeout_milliseconds(), + "download": Value::Null, }); + if installer.download.is_some() { + let managed = match payload.target { + InstallTarget::Managed => installer.targets.managed.as_ref(), + InstallTarget::ToolDefault => None, + } + .ok_or_else(undeclared)?; + if payload.install_directory.is_some() { + return Err(directory_invalid( + "A download installation takes no install directory; the host makes one for the archive.", + )); + } + let host = payload.platform.as_ref().ok_or_else(platform_invalid)?; + let artifact = installer.archive_for(host).ok_or_else(|| { + PluginRejection::at( + "plugin.commandInstaller.unavailable", + "platform", + format!( + "The command installer {} has no archive for this operating system and architecture.", + installer.id + ), + ) + })?; + plan["arguments"] = json!([]); + plan["environment"] = json!({}); + plan["commandDirectory"] = Value::Null; + plan["directoryProbes"] = json!([]); + plan["download"] = download_plan(installer, artifact, managed); + return Ok(("plan", plan)); + } match payload.target { InstallTarget::Managed => { let managed = installer.targets.managed.as_ref().ok_or_else(undeclared)?; @@ -668,6 +959,40 @@ fn plan(payload: PlanPayload, platform: Platform) -> Validation<(&'static str, V Ok(("plan", plan)) } +/// The selected archive of a download plan. `cacheKey` digests the fields +/// that decide the extracted content, so the host keeps one extraction per +/// archive; mirrors are left out of it, so adding a mirror reuses the +/// extraction. +fn download_plan( + installer: &CommandInstallerDeclaration, + artifact: &CommandArchive, + managed: &ManagedTarget, +) -> Value { + let version = installer + .download + .as_ref() + .map(|download| download.version.as_str()) + .unwrap_or_default(); + // Serialize this explicitly built object, not the input's field order. + let mut selected = json!({ + "installer": installer.id, + "version": version, + "os": artifact.os, + "arch": artifact.arch, + "url": artifact.url, + "sha256": artifact.sha256, + "archive": artifact.archive, + "stripPrefix": artifact.strip_prefix, + }); + let identity = Sha256::digest(selected.to_string().as_bytes()); + selected["cacheKey"] = json!(format!("{identity:x}")); + selected["commandDirectory"] = json!(managed.command_directory.as_deref().unwrap_or_default()); + if !artifact.mirrors.is_empty() { + selected["mirrors"] = json!(artifact.mirrors); + } + selected +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct DefaultDirectoryPayload { @@ -754,6 +1079,10 @@ mod tests { env!("CARGO_MANIFEST_DIR"), "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer.plugin.json" )); + const DOWNLOAD_PLUGIN: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer-download.plugin.json" + )); const PLANS: &str = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json" @@ -765,9 +1094,19 @@ mod tests { #[test] fn plan_fixtures_match_on_every_platform() { let plans: Value = serde_json::from_str(PLANS).unwrap(); - let plugin: Value = serde_json::from_str(PLUGIN).unwrap(); for case in plans["cases"].as_array().unwrap() { let name = case["name"].as_str().unwrap(); + let file = case + .get("plugin") + .unwrap_or(&plans["plugin"]) + .as_str() + .unwrap(); + let plugin: Value = serde_json::from_str(match file { + "command-installer.plugin.json" => PLUGIN, + "command-installer-download.plugin.json" => DOWNLOAD_PLUGIN, + other => panic!("unknown plugin fixture {other}"), + }) + .unwrap(); for (platform, key) in [(Platform::Unix, "unix"), (Platform::Windows, "windows")] { let specific = &case["platforms"][key]; let mut payload = json!({ "manifest": plugin }); diff --git a/rust/crates/plugin-manifest/src/lib.rs b/rust/crates/plugin-manifest/src/lib.rs index f37419e0..fb29c48f 100644 --- a/rust/crates/plugin-manifest/src/lib.rs +++ b/rust/crates/plugin-manifest/src/lib.rs @@ -31,6 +31,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; +mod archives; mod command_installers; mod commands; mod declarations; diff --git a/rust/crates/plugin-manifest/src/managed_runtimes.rs b/rust/crates/plugin-manifest/src/managed_runtimes.rs index 299c2a55..5bdeccf1 100644 --- a/rust/crates/plugin-manifest/src/managed_runtimes.rs +++ b/rust/crates/plugin-manifest/src/managed_runtimes.rs @@ -2,15 +2,16 @@ //! tool-specific qualification; hosts own downloads, filesystem evidence and //! atomic publication outside immutable plugin packages. +use super::archives::{ + bounded_text, is_archive_layout_path, is_archive_platform, validate_archive_source, + ArchivePlatform as RuntimePlatform, ArchiveSource, MAX_ARTIFACTS, +}; use super::*; -use lithe_platform::{paths, Platform}; +use lithe_platform::paths; use lithe_plugin_model::is_function_id; use sha2::{Digest, Sha256}; -use url::Url; const MAX_DEPENDENCIES: usize = 16; -const MAX_ARTIFACTS: usize = 6; -const MAX_MIRRORS: usize = 8; const DEFAULT_RESOLVE_TIMEOUT: u64 = 30_000; const MAX_RESOLVE_TIMEOUT: u64 = 120_000; const MAX_PATH_BYTES: usize = 4096; @@ -73,52 +74,16 @@ struct RuntimeArtifact { executable: String, } -#[derive(Debug, Clone, Deserialize, Serialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct RuntimePlatform { - os: String, - arch: String, -} - -impl RuntimePlatform { - fn validate(&self) -> Validation<()> { - if !["macos", "windows", "linux"].contains(&self.os.as_str()) - || !KNOWN_ARCHITECTURES.contains(&self.arch.as_str()) - { - return Err(PluginRejection::at( - "plugin.managedRuntime.unavailable", - "platform", - "Managed runtimes require a supported operating system and architecture.", - )); - } - Ok(()) +/// Rejects a platform no runtime archive may target. +fn validate_platform(platform: &RuntimePlatform) -> Validation<()> { + if !platform.is_supported() { + return Err(PluginRejection::at( + "plugin.managedRuntime.unavailable", + "platform", + "Managed runtimes require a supported operating system and architecture.", + )); } - - fn native_paths(&self) -> Platform { - if self.os == "windows" { - Platform::Windows - } else { - Platform::Unix - } - } -} - -fn bounded_text(value: &str, maximum: usize) -> bool { - !value.is_empty() - && value.len() <= maximum - && value.trim() == value - && !value.chars().any(char::is_control) -} - -/// These paths have the same portable meaning on every host. Native extraction -/// additionally checks filesystem aliases and symlink targets before writing. -fn relative_runtime_path(value: &str) -> bool { - value.is_empty() - || (bounded_text(value, 512) - && !value.contains(['\\', ':']) - && value - .split('/') - .all(|part| !part.is_empty() && part != "." && part != "..")) + Ok(()) } impl DeclarativePluginManifest { @@ -212,8 +177,7 @@ impl DeclarativePluginManifest { let mut targets = BTreeSet::new(); for (index, artifact) in dependency.artifacts.iter_mut().enumerate() { let field = format!("{field}.artifacts[{index}]"); - if !["macos", "windows", "linux"].contains(&artifact.os.as_str()) - || !KNOWN_ARCHITECTURES.contains(&artifact.arch.as_str()) + if !is_archive_platform(&artifact.os, &artifact.arch) || !targets.insert((artifact.os.clone(), artifact.arch.clone())) { return Err(invalid( @@ -221,85 +185,30 @@ impl DeclarativePluginManifest { "Artifacts have unique supported operating-system and architecture pairs.", )); } - let url = Url::parse(&artifact.url).map_err(|_| { - invalid( - format!("{field}.url"), - "A runtime archive needs an HTTPS URL.", - ) - })?; - if !bounded_text(&artifact.url, 4096) - || url.scheme() != "https" - || url.host_str().is_none() - || !url.username().is_empty() - || url.password().is_some() - || url.fragment().is_some() - { - return Err(invalid( - format!("{field}.url"), - "Runtime archive URLs use HTTPS without credentials or fragments.", - )); - } - if !artifact.mirrors.is_empty() { - if managed_runtimes_version < 1 { - return Err(invalid( - "requires.managedRuntimes", - "Managed runtime mirror URLs require requires.managedRuntimes >= 1.", - )); - } - if artifact.mirrors.len() > MAX_MIRRORS { - return Err(invalid( - format!("{field}.mirrors"), - "A runtime artifact declares at most 8 mirror URLs.", - )); - } - let mut seen_urls = BTreeSet::new(); - seen_urls.insert(artifact.url.as_str()); - for (mirror_index, mirror) in artifact.mirrors.iter().enumerate() { - let mirror_field = format!("{field}.mirrors[{mirror_index}]"); - let parsed = Url::parse(mirror).map_err(|_| { - invalid(mirror_field.clone(), "A runtime mirror needs an HTTPS URL.") - })?; - if !bounded_text(mirror, 4096) - || parsed.scheme() != "https" - || parsed.host_str().is_none() - || !parsed.username().is_empty() - || parsed.password().is_some() - || parsed.fragment().is_some() - { - return Err(invalid( - mirror_field, - "Runtime mirror URLs use HTTPS without credentials or fragments.", - )); - } - if !seen_urls.insert(mirror.as_str()) { + validate_archive_source( + &field, + ArchiveSource { + url: &artifact.url, + mirrors: &artifact.mirrors, + sha256: &mut artifact.sha256, + archive: &artifact.archive, + }, + || { + if managed_runtimes_version < 1 { return Err(invalid( - mirror_field, - "Runtime mirror URLs must be unique and differ from the primary URL.", + "requires.managedRuntimes", + "Managed runtime mirror URLs require requires.managedRuntimes >= 1.", )); } - } - } - if artifact.sha256.len() != 64 - || !artifact.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) - { - return Err(invalid( - format!("{field}.sha256"), - "A runtime archive pins its complete SHA-256 digest.", - )); - } - artifact.sha256.make_ascii_lowercase(); - if !["zip", "tar.gz"].contains(&artifact.archive.as_str()) { - return Err(invalid( - format!("{field}.archive"), - "A runtime archive format is zip or tar.gz.", - )); - } + Ok(()) + }, + )?; for (name, path) in [ ("stripPrefix", &artifact.strip_prefix), ("home", &artifact.home), ("executable", &artifact.executable), ] { - if !relative_runtime_path(path) { + if !is_archive_layout_path(path) { return Err(invalid( format!("{field}.{name}"), "Runtime paths are bounded relative paths without traversal.", @@ -344,7 +253,7 @@ impl ManagedRuntimes { let Some(artifact) = dependency .artifacts .iter() - .find(|artifact| artifact.os == platform.os && artifact.arch == platform.arch) + .find(|artifact| platform.matches(&artifact.os, &artifact.arch)) else { return Err(PluginRejection::at( "plugin.managedRuntime.unavailable", @@ -393,7 +302,7 @@ pub fn managed_runtime_plan_command(payload: Value) -> Result let request: PlanRequest = decode_payload(payload, "plugins.managedRuntimes.plan")?; Ok(outcome(validate_manifest_value(request.manifest).and_then( |manifest| { - request.platform.validate()?; + validate_platform(&request.platform)?; let plan = match manifest.managed_runtimes { Some(runtimes) => runtimes.plan(&request.platform)?, None => json!({"dependencies": []}), @@ -439,7 +348,7 @@ pub fn managed_runtime_resolution_command(payload: Value) -> Result}; manifestEdits replace the value at a JSON pointer of the manifest. A case whose result depends on the host's path rules lists platforms.unix and platforms.windows, each with its own payload fields and expected outcome. A rejection is matched by its code and field only.", + "description": "Golden results of plugins.commandInstallers.requirements, plan and defaultDirectory for the plugin file named by plugin; a case that names its own plugin uses that file instead. payload is merged into {\"manifest\": }; manifestEdits replace the value at a JSON pointer of the manifest. A case whose result depends on the host's path rules lists platforms.unix and platforms.windows, each with its own payload fields and expected outcome. A rejection is matched by its code and field only.", "plugin": "command-installer.plugin.json", "cases": [ { @@ -27,6 +27,7 @@ "commands": ["sample-dap"], "tool": "builder", "minimumVersion": null, + "download": null, "mayUseNetwork": true, "targets": ["managed"] }, @@ -35,6 +36,7 @@ "commands": ["sample-ls"], "tool": "builder", "minimumVersion": "1.2", + "download": null, "mayUseNetwork": true, "targets": ["managed", "toolDefault"] } @@ -73,6 +75,7 @@ "commands": ["sample-dap"], "tool": "builder", "minimumVersion": null, + "download": null, "mayUseNetwork": true, "targets": ["managed"] }, @@ -81,6 +84,7 @@ "commands": ["sample-ls"], "tool": "builder", "minimumVersion": "1.2", + "download": null, "mayUseNetwork": true, "targets": ["managed", "toolDefault"] } @@ -105,6 +109,7 @@ "minimumVersion": "1.2", "mayUseNetwork": true, "timeoutMilliseconds": 300000, + "download": null, "arguments": ["install", "example.org/sample-ls@latest"], "environment": { "BUILDER_BIN": "/data/lithe/commands/sample-ls" }, "commandDirectory": "/data/lithe/commands/sample-ls", @@ -124,6 +129,7 @@ "minimumVersion": "1.2", "mayUseNetwork": true, "timeoutMilliseconds": 300000, + "download": null, "arguments": ["install", "example.org/sample-ls@latest"], "environment": { "BUILDER_BIN": "C:\\Lithe\\commands\\sample-ls" }, "commandDirectory": "C:\\Lithe\\commands\\sample-ls", @@ -150,6 +156,7 @@ "minimumVersion": null, "mayUseNetwork": true, "timeoutMilliseconds": 600000, + "download": null, "arguments": ["install", "--prefix", "/data/lithe/commands/sample-dap", "example.org/sample-dap@latest"], "environment": {}, "commandDirectory": "/data/lithe/commands/sample-dap/bin", @@ -169,6 +176,7 @@ "minimumVersion": null, "mayUseNetwork": true, "timeoutMilliseconds": 600000, + "download": null, "arguments": ["install", "--prefix", "C:\\Lithe\\commands\\sample-dap", "example.org/sample-dap@latest"], "environment": {}, "commandDirectory": "C:\\Lithe\\commands\\sample-dap\\bin", @@ -192,6 +200,7 @@ "minimumVersion": "1.2", "mayUseNetwork": true, "timeoutMilliseconds": 300000, + "download": null, "arguments": ["install", "example.org/sample-ls@latest"], "environment": {}, "commandDirectory": null, @@ -294,6 +303,201 @@ "operation": "defaultDirectory", "payload": { "installerID": "sample-dap", "outputs": [] }, "expected": { "status": "rejected", "code": "plugin.commandInstaller.targetUndeclared", "field": "installerID" } + }, + { + "name": "a download installer is offered on a platform it has an archive for", + "plugin": "command-installer-download.plugin.json", + "operation": "requirements", + "payload": { "platform": { "os": "macos", "arch": "arm64" } }, + "expected": { + "status": "ok", + "requirements": { + "consumers": [ + { + "kind": "debugAdapter", + "id": "sample", + "commands": [{ "command": "sample-lldb", "installer": "sample-lldb" }] + } + ], + "installers": [ + { + "id": "sample-lldb", + "commands": ["sample-lldb"], + "tool": null, + "minimumVersion": null, + "download": { "version": "1.2.3" }, + "mayUseNetwork": true, + "targets": ["managed"] + } + ] + } + } + }, + { + "name": "without a platform every download installer is listed", + "plugin": "command-installer-download.plugin.json", + "operation": "requirements", + "payload": {}, + "expected": { + "status": "ok", + "requirements": { + "consumers": [ + { + "kind": "debugAdapter", + "id": "sample", + "commands": [{ "command": "sample-lldb", "installer": "sample-lldb" }] + } + ], + "installers": [ + { + "id": "sample-lldb", + "commands": ["sample-lldb"], + "tool": null, + "minimumVersion": null, + "download": { "version": "1.2.3" }, + "mayUseNetwork": true, + "targets": ["managed"] + } + ] + } + } + }, + { + "name": "a download installer without an archive for the platform is left out", + "plugin": "command-installer-download.plugin.json", + "operation": "requirements", + "payload": { "platform": { "os": "macos", "arch": "x86_64" } }, + "expected": { + "status": "ok", + "requirements": { + "consumers": [ + { + "kind": "debugAdapter", + "id": "sample", + "commands": [{ "command": "sample-lldb", "installer": null }] + } + ], + "installers": [] + } + } + }, + { + "name": "requirements refuse an unsupported platform", + "plugin": "command-installer-download.plugin.json", + "operation": "requirements", + "payload": { "platform": { "os": "freebsd", "arch": "x86_64" } }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.platformInvalid", "field": "platform" } + }, + { + "name": "a download plan names the platform's archive and its mirrors", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "managed", "platform": { "os": "macos", "arch": "arm64" } }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-lldb", + "target": "managed", + "commands": ["sample-lldb"], + "tool": null, + "minimumVersion": null, + "mayUseNetwork": true, + "timeoutMilliseconds": 900000, + "download": { + "installer": "sample-lldb", + "version": "1.2.3", + "os": "macos", + "arch": "arm64", + "url": "https://downloads.example.org/sample-lldb/1.2.3/sample-lldb-darwin-arm64.zip", + "sha256": "2f114a990e1b368dd1dbd33c80c0e719767af2d228391ec0df0571c957f9ac91", + "archive": "zip", + "stripPrefix": "", + "cacheKey": "de1c7271950564f1696dd15c7f23c87e2f8d9afc4311ca55d81c23eccb35250f", + "commandDirectory": "extension/adapter", + "mirrors": ["https://mirror.example.net/sample-lldb/1.2.3/sample-lldb-darwin-arm64.zip"] + }, + "arguments": [], + "environment": {}, + "commandDirectory": null, + "directoryProbes": [] + } + } + }, + { + "name": "a download plan carries the archive's strip prefix", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "managed", "platform": { "os": "linux", "arch": "x86_64" } }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-lldb", + "target": "managed", + "commands": ["sample-lldb"], + "tool": null, + "minimumVersion": null, + "mayUseNetwork": true, + "timeoutMilliseconds": 900000, + "download": { + "installer": "sample-lldb", + "version": "1.2.3", + "os": "linux", + "arch": "x86_64", + "url": "https://downloads.example.org/sample-lldb/1.2.3/sample-lldb-linux-x64.tar.gz", + "sha256": "1cd7f386598022b51a5b93b9ffa23e812b23f519cfe1833384ec4bef4bfd1be1", + "archive": "tar.gz", + "stripPrefix": "sample-lldb-1.2.3", + "cacheKey": "0484b60cdc12c632c91122f34138336b89e6b7c26d7f1ada09e232438d406e1e", + "commandDirectory": "extension/adapter" + }, + "arguments": [], + "environment": {}, + "commandDirectory": null, + "directoryProbes": [] + } + } + }, + { + "name": "a download installer has no toolDefault target", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "toolDefault", "platform": { "os": "macos", "arch": "arm64" } }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.targetUndeclared", "field": "target" } + }, + { + "name": "a download plan takes no install directory", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "managed", "platform": { "os": "macos", "arch": "arm64" }, "installDirectory": "/data/lithe/commands/sample-lldb" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.directoryInvalid", "field": "installDirectory" } + }, + { + "name": "a download plan needs the platform", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "managed" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.platformInvalid", "field": "platform" } + }, + { + "name": "a plan refuses an unsupported platform", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "managed", "platform": { "os": "freebsd", "arch": "x86_64" } }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.platformInvalid", "field": "platform" } + }, + { + "name": "a download plan for a platform without an archive is refused", + "plugin": "command-installer-download.plugin.json", + "operation": "plan", + "payload": { "installerID": "sample-lldb", "target": "managed", "platform": { "os": "macos", "arch": "x86_64" } }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.unavailable", "field": "platform" } + }, + { + "name": "a download installer has no default directory", + "plugin": "command-installer-download.plugin.json", + "operation": "defaultDirectory", + "payload": { "installerID": "sample-lldb", "outputs": [] }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.targetUndeclared", "field": "installerID" } } ] } diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index 267b8dfe..b0e682e3 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -948,6 +948,28 @@ {"name": "an installer states whether it uses the network", "base": "command-installer.plugin.json", "edits": [{"op": "remove", "path": "/commandInstallers/0/mayUseNetwork"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "command installers need commands.install", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["debug.launch", "languageServer.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, {"name": "commands.install needs a command installer", "base": "command-installer.plugin.json", "edits": [{"op": "remove", "path": "/commandInstallers"}], "expectedCode": "plugin.manifest.invalid"}, - {"name": "commandInstallers is listed in requires", "base": "command-installer.plugin.json", "edits": [{"op": "remove", "path": "/requires/commandInstallers"}], "expectedCode": "plugin.manifest.invalid"} + {"name": "commandInstallers is listed in requires", "base": "command-installer.plugin.json", "edits": [{"op": "remove", "path": "/requires/commandInstallers"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a tool installer names its tool", "base": "command-installer.plugin.json", "edits": [{"op": "remove", "path": "/commandInstallers/0/tool"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].tool"}, + {"name": "a tool installer lists its arguments", "base": "command-installer.plugin.json", "edits": [{"op": "remove", "path": "/commandInstallers/0/arguments"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].arguments"}, + {"name": "download installers need commandInstallers 1", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/requires/commandInstallers", "value": 0}], "expectedCode": "plugin.manifest.invalid", "expectedField": "requires.commandInstallers"}, + {"name": "a download installer runs no tool", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/tool", "value": "builder"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].tool"}, + {"name": "a download installer passes no arguments", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/arguments", "value": ["install"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].arguments"}, + {"name": "a download installer uses the network", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/mayUseNetwork", "value": false}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].mayUseNetwork"}, + {"name": "a download installer extracts only into the managed directory", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/toolDefault", "value": {"directory": [{"arguments": ["env", "SAMPLE_HOME"]}]}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.toolDefault"}, + {"name": "a download installer declares the managed target", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets", "value": {"toolDefault": {"directory": [{"arguments": ["env", "SAMPLE_HOME"]}]}}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.toolDefault"}, + {"name": "a download target passes no arguments", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed/arguments", "value": ["${installDirectory}"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.managed.arguments"}, + {"name": "a download target sets no environment", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed/environment", "value": {"SAMPLE_HOME": "${installDirectory}"}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.managed.environment"}, + {"name": "the command directory stays inside the extracted archive", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed/commandDirectory", "value": "../adapter"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.managed.commandDirectory"}, + {"name": "the command directory uses forward slashes", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed/commandDirectory", "value": "extension\\adapter"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.managed.commandDirectory"}, + {"name": "a download names its upstream version", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/version", "value": ""}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.version"}, + {"name": "a download declares at least one archive", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts"}, + {"name": "a download archive targets a supported platform", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/1/os", "value": "freebsd"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[1]"}, + {"name": "a download declares one archive per platform", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/2/os", "value": "macos"}, {"op": "set", "path": "/commandInstallers/0/download/artifacts/2/arch", "value": "arm64"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[2]"}, + {"name": "a download archive uses HTTPS", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/url", "value": "http://downloads.example.org/sample-lldb.zip"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].url"}, + {"name": "a download mirror uses HTTPS", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/mirrors", "value": ["http://mirror.example.net/sample-lldb.zip"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].mirrors[0]"}, + {"name": "a download mirror differs from the primary URL", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/mirrors", "value": ["https://downloads.example.org/sample-lldb/1.2.3/sample-lldb-darwin-arm64.zip"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].mirrors[0]"}, + {"name": "a download archive pins its SHA-256 digest", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/sha256", "value": "2f114a99"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].sha256"}, + {"name": "a download archive is zip or tar.gz", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/archive", "value": "7z"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].archive"}, + {"name": "a download strip prefix stays inside the archive", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/1/stripPrefix", "value": "../sample-lldb"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[1].stripPrefix"} ] } diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 6d85e865..785e958f 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -13,6 +13,7 @@ {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["beforeLaunchTasks"]}}}}, "then": {"properties": {"requires": {"required": ["beforeLaunchTasks"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["test"], "properties": {"test": {"required": ["discoveryCommand"]}}}}}}, "then": {"properties": {"requires": {"required": ["buildSystems"], "properties": {"buildSystems": {"const": 1}}}}}}, {"if": {"required": ["commandInstallers"]}, "then": {"required": ["permissions"], "properties": {"requires": {"required": ["commandInstallers"]}, "permissions": {"contains": {"const": "commands.install"}}}}}, + {"if": {"required": ["commandInstallers"], "properties": {"commandInstallers": {"contains": {"required": ["download"]}}}}, "then": {"properties": {"requires": {"properties": {"commandInstallers": {"const": 1}}}}}}, {"if": {"required": ["managedRuntimes"]}, "then": {"required": ["backend", "permissions"], "properties": {"requires": {"required": ["managedRuntimes", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "runtimes.install"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["toolchainProviders"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["toolchainProviders", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "toolchains.provide"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["pluginFunctions"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["pluginFunctions", "backend"]}}}}, @@ -37,7 +38,7 @@ "buildModelInputs": {"description": "Optional public model sharing between already enabled workspace plugins; no installation, private function, or process authority. Required exactly when modelSharing or modelInputs is used. Consumers require buildProviders. A producer cannot also consume inputs.", "enum": [0]}, "buildProviders": { "description": "Required exactly when any buildSystems[].provider is present, including own-process and shared language-server providers. Declares host support for Provider orchestration (task execution, test execution and discovery, run preparation, native debug preparation, optional read-only model inputs, non-sensitive native configuration sources, inline test reports, opaque semantic test selectors, typed run options and service/task preparation, registry-selected adapters and host-owned connection targets for service debugging), independent of declarative buildSystems. Version 1 adds entrypoint runs (lithe/build/runEntrypoints).", "enum": [0, 1] }, "buildSystems": { "description": "Declarative build detection, models, and command plans. Version 1 adds command-based test discovery. Neither version implies buildProviders support.", "enum": [0, 1] }, - "commandInstallers": { "description": "Required exactly when commandInstallers is non-empty: installations of bare commands that systemCommand launches name, run by the host only after the user confirms them.", "enum": [0] }, + "commandInstallers": { "description": "Required exactly when commandInstallers is non-empty: installations of bare commands that systemCommand launches name, run by the host only after the user confirms them. Version 1 adds download installers: pinned per-platform archives the host downloads, checks and extracts into the plugin's managed directory.", "enum": [0, 1] }, "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Covers bounded target argument and environment bindings and debugAdapters[].features and defaults. The DAP session itself is negotiated by the adapter in initialize.", "enum": [0] }, "executionProviders": { "enum": [0] }, "languageServers": { "description": "Required exactly when languageServers is non-empty. Covers languageServers[].workspaceConfiguration and the session fields requestMethods, commands, serializedCommands, forwardNotifications, state, and remote.", "enum": [0] }, @@ -1051,10 +1052,35 @@ "pattern": "^(?:[^/\\\\:]+(?:/[^/\\\\:]+)*)?$" }, "commandInstaller": { - "description": "One way to install bare commands. The host shows the tool, the expanded command line, the network use and the target directory, and runs it only after the user confirms.", + "description": "One way to install bare commands: run a tool, or, with requires.commandInstallers 1, download a pinned archive. The host shows the tool and the expanded command line, or the version and the archive URL, with the network use and the target directory, and installs only after the user confirms.", "type": "object", "additionalProperties": false, - "required": ["id", "commands", "tool", "arguments", "mayUseNetwork", "targets"], + "required": ["id", "commands", "mayUseNetwork", "targets"], + "oneOf": [ + { + "description": "A tool installer runs the tool with the arguments.", + "required": ["tool", "arguments"], + "not": { "required": ["download"] } + }, + { + "description": "A download installer runs no tool. It uses the network and extracts only into the managed target, which passes no arguments or environment.", + "required": ["download"], + "not": { "anyOf": [{ "required": ["tool"] }, { "required": ["minimumVersion"] }, { "required": ["arguments"] }] }, + "properties": { + "mayUseNetwork": { "const": true }, + "targets": { + "required": ["managed"], + "not": { "required": ["toolDefault"] }, + "properties": { + "managed": { + "not": { "required": ["arguments"] }, + "properties": { "environment": { "maxProperties": 0 } } + } + } + } + } + } + ], "properties": { "id": { "type": "string", "pattern": "^[a-z0-9-]+$", "maxLength": 64 }, "commands": { @@ -1068,7 +1094,8 @@ "tool": { "description": "The ID of a tool definition listed in requiresTools; its executable runs the installation and the directory probes.", "$ref": "#/$defs/toolchainToolID" }, "minimumVersion": { "$ref": "#/$defs/minimumVersion" }, "arguments": { "description": "Arguments after the tool's executable. Literal: no template variables.", "$ref": "#/$defs/commandInstallerArguments" }, - "mayUseNetwork": { "description": "Whether the installation may download; shown before the user confirms.", "type": "boolean" }, + "download": { "$ref": "#/$defs/commandInstallerDownload" }, + "mayUseNetwork": { "description": "Whether the installation may download; shown before the user confirms. Always true for a download installer.", "type": "boolean" }, "timeoutSeconds": { "type": "integer", "minimum": 1, "maximum": 3600, "default": 600 }, "targets": { "description": "Where the commands may land; the user chooses one when installing.", @@ -1083,7 +1110,7 @@ "properties": { "arguments": { "description": "Replaces the installer's arguments.", "$ref": "#/$defs/commandInstallerArguments" }, "environment": { "$ref": "#/$defs/commandInstallerEnvironment" }, - "commandDirectory": { "description": "Package-style relative path below the install directory where the commands land; the install directory itself when absent.", "$ref": "#/$defs/commandInstallerRelativePath" } + "commandDirectory": { "description": "Package-style relative path below the install directory where the commands land; the install directory itself when absent. For a download installer it is relative to the extracted archive root and also follows the archive layout rules: forward slashes, no empty, dot or parent components, no colon.", "$ref": "#/$defs/commandInstallerRelativePath" } } }, "toolDefault": { @@ -1114,6 +1141,35 @@ } } }, + "commandInstallerDownload": { + "description": "requires.commandInstallers 1: one pinned archive per platform. The host downloads the archive for its platform, checks the SHA-256 digest and extracts it into a directory of its own below the plugin's managed directory; the commands are in targets.managed.commandDirectory below the extracted root. On a platform without an archive the installer is not offered.", + "type": "object", + "additionalProperties": false, + "required": ["version", "artifacts"], + "properties": { + "version": { "description": "Upstream version of the archives, shown before the user confirms.", "type": "string", "minLength": 1, "maxLength": 128 }, + "artifacts": { "description": "At most one archive per os and arch. Sorted by os, then arch, when normalized.", "type": "array", "minItems": 1, "maxItems": 6, "items": { "$ref": "#/$defs/commandInstallerArchive" } } + } + }, + "commandInstallerArchive": { + "type": "object", "additionalProperties": false, + "required": ["os", "arch", "url", "sha256", "archive"], + "properties": { + "os": { "enum": ["macos", "windows", "linux"] }, + "arch": { "enum": ["arm64", "x86_64"] }, + "url": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^https://", "description": "HTTPS without credentials or fragments; semantic URL validation is performed by Core." }, + "mirrors": { + "type": "array", + "maxItems": 8, + "uniqueItems": true, + "description": "Optional fallback HTTPS URLs serving the exact same pinned SHA-256 archive, each different from url.", + "items": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^https://" } + }, + "sha256": { "description": "Digest of the whole archive; lowercased when normalized.", "type": "string", "pattern": "^[A-Fa-f0-9]{64}$" }, + "archive": { "enum": ["zip", "tar.gz"] }, + "stripPrefix": { "description": "Directory every entry of the archive is below, removed when extracting.", "$ref": "#/$defs/managedRuntimePath", "default": "" } + } + }, "commandInstallerArguments": { "type": "array", "maxItems": 64, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index cc9e247b..060c198d 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -46,7 +46,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-20 | 存储 | 部分完成 | 插件级 `${stateDir}`、后端和工作区的可写目录(`stateDirectory`)、网页状态;语言服务器按工作区的状态目录,按声明的 [`state.retention`](../contract/v1/README.md#plugin-owned-sessions) 由宿主在后台回收(Core 决定) | 统一的键值存储、配额;用户可见的状态重置入口 | [插件后端](domains/backend.md) | | API-21 | 凭据 | 既有能力 | [`credentials/get`、`set`、`delete`](../contract/v1/README.md#host-services),按插件隔离 | — | [插件后端](domains/backend.md) | | API-22 | 输出、日志、进度 | 部分完成 | [插件函数的进度和取消](../contract/v1/README.md#progress);面向开发者的[结构化诊断日志 `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics);[`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) 在宿主状态界面显示插件自己的语言服务器准备状态(只有消息和百分比,没有 actions);[`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers):插件声明的匹配器让 Run 与测试控制台的输出出现链接 | 独立的输出面板、面向用户的日志和进度 API | [插件后端](domains/backend.md) | -| API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`);[受管运行时](../contract/v1/README.md#managed-runtimes)(`managedRuntimes`,权限 `runtimes.install`,Core 计划与应答校验,无新增宿主 RPC) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `toolchainProviders` 和 `commandInstallers` | [工具链](domains/toolchains.md) | +| API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`;版本 1 增加[下载安装](../contract/v1/README.md#download-installers));[受管运行时](../contract/v1/README.md#managed-runtimes)(`managedRuntimes`,权限 `runtimes.install`,Core 计划与应答校验,无新增宿主 RPC) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `commandInstallers` 1(下载安装) | [工具链](domains/toolchains.md) | | API-24 | 终端 | 部分完成 | [插件自有原生终端](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`、`show`、`close`、`reopen`、`dispose`、`onExit`(本机工作区) | 向终端发送文本、读取终端输出 | [插件后端](domains/backend.md) | | API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 TextMate 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration)及[无后缀文件首行关联](../contract/v1/README.md#first-line-matching);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | | API-27 | 编辑器动作、主题、装饰 | 部分完成 | [独立编辑器动作 `editor/registerActions`](../contract/v1/README.md#independent-editor-actions),绑定普通函数和文件范围,不依赖 LSP、构建或运行;支持行首多图标、至多 4 个 `alternatives`、点击结果的 `reveal` | 主题、代码片段、其他装饰 | [编辑器](domains/editor.md) | @@ -219,7 +219,7 @@ Status meanings: | API-20 | Storage | Partial | The plugin-wide `${stateDir}`, writable backend and workspace directories (`stateDirectory`), web page state; a language server's per-workspace state directories, which the host prunes in the background by the declared [`state.retention`](../contract/v1/README.md#plugin-owned-sessions) (Core decides) | A unified key-value store, quotas; a user-facing way to reset state | [Plugin backend](domains/backend.md) | | API-21 | Credentials | Existing | [`credentials/get`, `set`, `delete`](../contract/v1/README.md#host-services), isolated per plugin | — | [Plugin backend](domains/backend.md) | | API-22 | Output, log, progress | Partial | [Plugin function progress and cancellation](../contract/v1/README.md#progress); developer-facing [structured diagnostics `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics); [`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) shows the plugin's own language server preparation state in the host's status UI (a message and a percentage only, no actions); [`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers): matchers a plugin declares make output in the Run and Test consoles clickable | A dedicated output panel, user-facing log and progress APIs | [Plugin backend](domains/backend.md) | -| API-23 | Toolchains and managed processes | Partial | [Process start](../contract/v1/README.md#process-start), runtime resolution, [shared executable candidates](../contract/v1/README.md#executable-resolution), tool definitions, toolchain providers (`toolchainProviders`); [references to runtimes by tool-definition ID](../contract/v1/README.md#tool-references) (manifest `requiresTools`); backend-started [`run/start`, `run/stop`, and the `run/didExit` notification](../contract/v1/README.md#run-and-debug-sessions), where the host owns the Run session (permission `run.start`; a tool that resolves to no executable returns `plugin.host.toolUnresolved`); [installing missing commands](../contract/v1/README.md#command-installers) (`commandInstallers`, permission `commands.install`); [managed runtimes](../contract/v1/README.md#managed-runtimes) (`managedRuntimes`, permission `runtimes.install`, Core plans and reply validation with no new host RPC) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `toolchainProviders` or `commandInstallers` | [Toolchains](domains/toolchains.md) | +| API-23 | Toolchains and managed processes | Partial | [Process start](../contract/v1/README.md#process-start), runtime resolution, [shared executable candidates](../contract/v1/README.md#executable-resolution), tool definitions, toolchain providers (`toolchainProviders`); [references to runtimes by tool-definition ID](../contract/v1/README.md#tool-references) (manifest `requiresTools`); backend-started [`run/start`, `run/stop`, and the `run/didExit` notification](../contract/v1/README.md#run-and-debug-sessions), where the host owns the Run session (permission `run.start`; a tool that resolves to no executable returns `plugin.host.toolUnresolved`); [installing missing commands](../contract/v1/README.md#command-installers) (`commandInstallers`, permission `commands.install`; version 1 adds [download installers](../contract/v1/README.md#download-installers)); [managed runtimes](../contract/v1/README.md#managed-runtimes) (`managedRuntimes`, permission `runtimes.install`, Core plans and reply validation with no new host RPC) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `commandInstallers` 1 (download installers) | [Toolchains](domains/toolchains.md) | | API-24 | Terminals | Partial | [Plugin-owned native terminals](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`, `show`, `close`, `reopen`, `dispose`, `onExit` (local workspaces) | Sending text to a terminal, reading its output | [Plugin backend](domains/backend.md) | | API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged TextMate grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration) and [first-line associations for extensionless files](../contract/v1/README.md#first-line-matching); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | | API-27 | Editor actions, themes, decorations | Partial | [Independent editor actions `editor/registerActions`](../contract/v1/README.md#independent-editor-actions), binding ordinary functions to file ranges without LSP, build, or run; several icons at a line start, up to 4 `alternatives`, and a `reveal` in the click result | Themes, snippets, other decorations | [Editor](domains/editor.md) | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 57a655e7..fb5c2ae8 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -60,6 +60,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `managedRuntimes` `0` | 固定归档、插件后端资格检查、跨版本缓存与安装前准备;权限 `runtimes.install` | ✅ | ✅ | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `managedRuntimes` `1` | 在 `0` 基础上允许每个平台归档声明最多 8 个 HTTPS `mirrors` 镜像地址,不改变 `cacheKey` | ✅ | 配套宿主接入后声明 | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动缺的裸命令,装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | ✅ | [工具链](domains/toolchains.md#安装缺失的命令) | +| `commandInstallers` `1` | 在 `0` 基础上新增[下载安装](../contract/v1/README.md#download-installers):`download` 固定上游版本和每个平台的 HTTPS 归档(SHA-256、`zip`/`tar.gz`、可选镜像和 `stripPrefix`),宿主下载、校验、解压到 Lithe 管理的目录,用户确认版本和地址后才下载;没有当前平台归档的安装不提供 | ✅ | 配套宿主接入后声明 | [工具链](domains/toolchains.md#安装缺失的命令) | | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | @@ -175,6 +176,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `managedRuntimes` `0` | Pinned archives, plugin-owned qualification, version-independent cache and install preflight; permission `runtimes.install` | ✅ | ✅ | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `managedRuntimes` `1` | Extends `0` with up to 8 optional HTTPS `mirrors` URLs per platform artifact without changing `cacheKey` | ✅ | Declared with companion host integration | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch lacks with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | ✅ | [Toolchains](domains/toolchains.md#installing-missing-commands) | +| `commandInstallers` `1` | Extends `0` with [download installers](../contract/v1/README.md#download-installers): `download` pins an upstream version and an HTTPS archive per platform (SHA-256, `zip`/`tar.gz`, optional mirrors and `stripPrefix`); the host downloads, checks and extracts it into a directory Lithe manages, only after the user confirms the version and URL; an installer without an archive for the platform is not offered | ✅ | Declared with companion host integration | [Toolchains](domains/toolchains.md#installing-missing-commands) | | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 4d0706c3..d2b2e686 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -115,17 +115,18 @@ ### 安装缺失的命令 -`systemCommand` 启动只写裸命令名(如 `dlv`、`gopls`),机器上没有时启动失败。清单顶层 `commandInstallers[]` 告诉宿主怎样用插件已经依赖的工具(`requiresTools` 里的工具定义)安装它,用户在插件管理里点安装即可,不用开终端。需要能力 `commandInstallers` 0 和权限 `commands.install`。 +`systemCommand` 启动只写裸命令名(如 `dlv`、`gopls`、`codelldb`),机器上没有时启动失败。清单顶层 `commandInstallers[]` 告诉宿主怎样安装它,用户在插件管理里点安装即可,不用开终端。安装有两种:**工具安装**用插件已经依赖的工具(`requiresTools` 里的工具定义)运行安装命令;**下载安装**(能力 `commandInstallers` 1)下载上游发布的固定归档,插件包里不用带这个命令。需要能力 `commandInstallers` 0(有下载安装时为 1)和权限 `commands.install`。 | 项目 | 规则 | | --- | --- | -| 声明 | `id`、`commands`(1–8 个本清单 `systemCommand` 启动用到的裸命令,一个命令只归一个安装)、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)、`targets` | +| 声明 | `id`、`commands`(1–8 个本清单 `systemCommand` 启动用到的裸命令,一个命令只归一个安装)、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)、`targets`;工具安装另有 `tool`、`minimumVersion?`、字面量 `arguments`,下载安装另有 `download` | +| 下载安装 | `download.version` 是上游版本;`download.artifacts` 1–6 个归档,每个 `os`/`arch` 最多一个,各有 HTTPS `url`、可选 `mirrors`(最多 8 个)、完整 `sha256`、`archive`(`zip` 或 `tar.gz`)、可选 `stripPrefix`。只能用 `managed` 目标,不带 `arguments`、`environment`;`commandDirectory` 相对解压根目录。`mayUseNetwork` 必须为 `true`。没有当前平台归档时不提供这个安装 | | `managed` 目标 | 装进宿主为插件管理的目录(应用数据目录,不在应用包、安装目录或插件包里,卸载插件时删除)。`arguments`(替换安装的参数)或 `environment` 必须用唯一的模板变量 `${installDirectory}`;`commandDirectory` 是命令所在的子目录 | | `toolDefault` 目标 | 装到工具默认位置,值都是字面量。`directory` 最多 4 个探针,按顺序用同一工具运行,第一个输出绝对目录的探针决定位置;`pathList` 取路径列表第一项,`append` 拼接子目录 | -| 宿主做什么 | `plugins.commandInstallers.requirements` 列出每个启动缺哪些命令、由哪个安装提供;`toolDefault` 先运行探针,把输出交给 `defaultDirectory`;向用户展示工具、完整命令行、是否联网和每个目标的目录,用户选定后用 `plan` 展开并运行,显示输出、可取消、超时停止,结束后确认命令确实在目录里 | +| 宿主做什么 | `plugins.commandInstallers.requirements` 带上本机 `platform`,列出每个启动缺哪些命令、由哪个安装提供;`toolDefault` 先运行探针,把输出交给 `defaultDirectory`;向用户展示工具和完整命令行(下载安装展示版本和下载地址)、是否联网和每个目标的目录,用户选定后用 `plan` 展开并运行,显示输出、可取消、超时停止,结束后确认命令确实在目录里。下载安装的 `plan` 带 `platform`,返回 `download`(选中平台的归档和 `cacheKey`);宿主依次尝试 `url` 和镜像下载,解压前校验 SHA-256,安全解压到受管目录下自己的子目录,保留文件权限 | | 之后的启动 | 宿主查找这个插件的 `systemCommand` 时,除 `PATH` 外还查插件的受管命令目录和记录下来的默认目录 | | 不覆盖 | 构建系统和执行提供者通过 `invocation.executables` 解析的可执行文件 | -| 安装审查 | 每个安装都是审查里的程序(`kind: "commandInstaller"`),改了要运行的内容需要重新批准 | +| 安装审查 | 每个安装都是审查里的程序(`kind: "commandInstaller"`),改了要运行的内容需要重新批准;下载安装的程序列出全部归档,改地址、镜像、摘要或版本也要重新批准 | ### 独立于插件版本的受管运行时 @@ -145,7 +146,7 @@ Core 的 `plugins.managedRuntimes.plan` 选择准确平台并生成缓存键,` | --- | --- | | 工具定义(`toolDefinitions`) | 已声明(macOS、Windows、Linux)。设置页发现、项目环境信任、目录固定保存,以及构建、运行、调试、语言服务器和新建项目选择工具,都通过共享 Core 解析器完成 | | 工具链提供者(`toolchainProviders`) | 未声明。提供者查询路线不可用,需要它的插件不会被提供安装 | -| 安装缺失的命令(`commandInstallers`) | 已声明。插件管理页展示工具、命令行、网络与目标目录,用户确认后安装到受管目录或工具默认目录 | +| 安装缺失的命令(`commandInstallers`) | 已声明 `0`。插件管理页展示工具、命令行、网络与目标目录,用户确认后安装到受管目录或工具默认目录;下载安装(`1`)由配套宿主接入后声明 | | 语言服务器的 `{kind: "tool"}` 启动 | 按工作区工具链四层选择解析后启动(见[语言](languages.md)) | | `toolchainConsumers`、提供者热激活 | 契约尚未提供 | @@ -302,17 +303,18 @@ When a plugin starts a process by tool-definition ID (a launch plan with `launch ### Installing missing commands -A `systemCommand` launch names only a bare command (such as `dlv` or `gopls`), and fails when the machine lacks it. The top-level `commandInstallers[]` tells the host how to install it with a tool the plugin already requires (a tool definition in `requiresTools`), so the user installs it from plugin management instead of a terminal. It requires the `commandInstallers` 0 capability and the `commands.install` permission. +A `systemCommand` launch names only a bare command (such as `dlv`, `gopls` or `codelldb`), and fails when the machine lacks it. The top-level `commandInstallers[]` tells the host how to install it, so the user installs it from plugin management instead of a terminal. A **tool installer** runs a tool the plugin already requires (a tool definition in `requiresTools`); a **download installer** (capability `commandInstallers` 1) downloads a pinned archive its upstream publishes, so the plugin package does not carry the command. It requires the `commandInstallers` 0 capability (1 with a download installer) and the `commands.install` permission. | Item | Rule | | --- | --- | -| Declaration | `id`, `commands` (1 to 8 bare commands that `systemCommand` launches of this manifest name; one installer per command), `tool`, `minimumVersion?`, literal `arguments`, `mayUseNetwork`, `timeoutSeconds?` (1 to 3600, 600 by default), `targets` | +| Declaration | `id`, `commands` (1 to 8 bare commands that `systemCommand` launches of this manifest name; one installer per command), `mayUseNetwork`, `timeoutSeconds?` (1 to 3600, 600 by default), `targets`; a tool installer adds `tool`, `minimumVersion?` and literal `arguments`, a download installer adds `download` | +| Download installer | `download.version` is the upstream version; `download.artifacts` holds 1 to 6 archives, at most one per `os`/`arch`, each with an HTTPS `url`, optional `mirrors` (up to 8), the full `sha256`, `archive` (`zip` or `tar.gz`) and optional `stripPrefix`. Only the `managed` target, without `arguments` or `environment`; `commandDirectory` is relative to the extracted root. `mayUseNetwork` is `true`. The installer is not offered on a platform without an archive | | `managed` target | Installs into a directory the host manages for the plugin (in application data, never in the app bundle, installation directory or plugin package; removed with the plugin). `arguments` (replacing the installer's) or `environment` must use `${installDirectory}`, the only template variable; `commandDirectory` is the subdirectory the commands land in | | `toolDefault` target | Installs wherever the tool installs by default; every value is literal. `directory` holds up to 4 probes run in order with the same tool; the first to print an absolute directory decides; `pathList` takes the first entry of a path list and `append` adds a subdirectory | -| Host steps | `plugins.commandInstallers.requirements` lists which commands each launch lacks and which installer provides them; for `toolDefault` the host runs the probes and sends their output to `defaultDirectory`; it shows the tool, the full command line, the network use and the directory of each target, then expands the chosen one with `plan` and runs it, showing the output, allowing cancel and stopping it at the timeout, and finally checks the commands are in the directory | +| Host steps | `plugins.commandInstallers.requirements`, sent with the host `platform`, lists which commands each launch lacks and which installer provides them; for `toolDefault` the host runs the probes and sends their output to `defaultDirectory`; it shows the tool and the full command line (for a download installer the version and download URL), the network use and the directory of each target, then expands the chosen one with `plan` and runs it, showing the output, allowing cancel and stopping it at the timeout, and finally checks the commands are in the directory. A download installer's `plan` takes `platform` and returns `download` (the platform's archive and its `cacheKey`); the host tries `url` and then the mirrors, checks the SHA-256 before extracting, and extracts safely into a directory of its own below the managed directory, keeping file modes | | Later launches | The host looks for the plugin's `systemCommand` launches in its managed command directory and the recorded default directories as well as on `PATH` | | Not covered | Executables of build systems and execution providers resolved through `invocation.executables` | -| Install review | Every installer is a reviewed program (`kind: "commandInstaller"`); a change to what it runs needs approval again | +| Install review | Every installer is a reviewed program (`kind: "commandInstaller"`); a change to what it runs needs approval again. A download installer's program lists every archive, so a new URL, mirror, digest or version needs approval again too | ### Managed runtimes independent of plugin version @@ -332,7 +334,7 @@ Core's `plugins.managedRuntimes.plan` selects the exact platform and generates c | --- | --- | | Tool definitions (`toolDefinitions`) | Declared (macOS, Windows, and Linux). Settings discovery, workspace project-environment trust, saving pins, and Build, Run, Debug, language-server, and project-generator tool selection all go through the shared Core resolver | | Toolchain providers (`toolchainProviders`) | Not declared. The provider query route is unavailable, and a plugin that needs it is not offered for installation | -| Installing missing commands (`commandInstallers`) | Declared. Plugin management displays the tool, command line, network use, and target directory, and installs into the managed directory or tool default directory after user confirmation | +| Installing missing commands (`commandInstallers`) | `0` declared. Plugin management displays the tool, command line, network use, and target directory, and installs into the managed directory or tool default directory after user confirmation; download installers (`1`) are declared with companion host integration | | Language server `{kind: "tool"}` launch | Resolved through the workspace's four toolchain layers and started (see [Languages](languages.md)) | | `toolchainConsumers`, live provider activation | Not provided by the contract yet | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index bd48a332..73354ba3 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,8 @@ ## 待合入 +- [#133](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/133),[@xiaoyumuxi](https://github.com/xiaoyumuxi),**`commandInstallers` 1**(API-23):命令安装新增[下载安装](../contract/v1/README.md#download-installers):安装声明 `download`(与 `tool`、`minimumVersion`、`arguments` 互斥),固定上游 `version` 和 1–6 个平台归档,每个归档有 `os`、`arch`、HTTPS `url`、可选 `mirrors`(最多 8 个)、完整 `sha256`、`archive`(`zip`/`tar.gz`)和可选 `stripPrefix`,规则与 `managedRuntimes` 归档相同;只能用 `managed` 目标,不带 `arguments`、`environment`,`commandDirectory` 相对解压根目录,`mayUseNetwork` 必须为 `true`。`plugins.commandInstallers.requirements` 和 `plan` 新增可选 `platform: {os, arch}`:带上时没有该平台归档的下载安装不提供;安装条目新增 `download: null | {version}`;计划新增 `download`(工具安装为 `null`,下载安装为选中平台的归档、`cacheKey` 和 `commandDirectory`)。新增 Core 错误码 `plugin.commandInstaller.platformInvalid`、`unavailable`,宿主错误码 `plugin.commandInstaller.downloadFailed`、`checksumMismatch`、`archiveInvalid`;`failed` 只指工具安装失败。下载安装的审查程序列出全部归档,改地址、镜像、摘要或版本需要重新批准;只声明 `commandInstallers` 0 的宿主拒绝安装带下载安装的插件。没有新增宿主方法、通知或 SDK 版本。用于 Rust Support 插件按需下载 CodeLLDB。 + - [#130](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/130),[@1lck](https://github.com/1lck),**工作区插件推荐**:市场契约新增同级推荐索引格式 `plugin-recommendations.schema.json`(`schemaVersion: 0`,独立于只增不破旧版的 `lithe-plugin-index.json`);`plugins.marketplace.resolveSource` 额外返回 `recommendationsURL`,并新增宿主内部 Core 命令 `plugins.marketplace.recommendForWorkspace`(不是插件 RPC),基于工作区采集文件名与已有市场索引匹配可安装的缺失插件。见 [1lck/Lithe-IDEA#2228](https://github.com/1lck/Lithe-IDEA/issues/2228)。 - [#127](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/127),[@Mucheen](https://github.com/Mucheen),**API-25**:从 `grammar.path` 指定的 TextMate 语法或独立的 `grammars/.first-line.json` 读取可选 `firstLineMatch`。独立文件可沿用宿主现有高亮。旧桌面仍可安装 `languages: 0` 的同一插件包。Core 解码返回可选提示并匹配完整首行,既有路径与用户关联优先。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 @@ -54,6 +56,7 @@ | `buildSystems` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildSystems` | 1 | 待合入 | [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112) | | `commandInstallers` | 0 | 2026-11-15 | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | +| `commandInstallers` | 1 | 待合入 | [#133](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/133) | | `debugAdapters` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `executionProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `keymapImportProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) |