From 19548b594bb5ce96837040d66f90f23f082d5330 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 15:00:36 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(plugins):=20commandInstallers=20?= =?UTF-8?q?=E8=AE=A9=E5=AE=BF=E4=B8=BB=E5=AE=89=E8=A3=85=20systemCommand?= =?UTF-8?q?=20=E5=90=AF=E5=8A=A8=E7=BC=BA=E7=9A=84=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 插件清单新增顶层 commandInstallers[](能力 commandInstallers 0、权限 commands.install),声明怎样用插件已依赖的工具安装 systemCommand 启动用到的 裸命令,例如用 go install 装 dlv。目标有两个:managed 装进宿主为插件管理的 目录(唯一模板变量 ${installDirectory}),toolDefault 装到工具默认位置,并 用探针读出目录。 新增宿主命令 plugins.commandInstallers.requirements、plan、defaultDirectory, Core 错误码 plugin.commandInstaller.unknown、targetUndeclared、 directoryInvalid、probeOutputsInvalid;安装声明进入安装审查。 lithe-platform 增加 path_list_separator、is_absolute_path、join_native; is_environment_name 收到 plugin-model::names 一处。 契约 README、schema、fixture、rust-core-api.md、协议更新记录、能力版本、 API 总表和工具链领域页同步更新。 --- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 31 + rust/crates/build/src/manifest.rs | 6 +- rust/crates/build/src/manifest/checks.rs | 12 - rust/crates/build/src/plans.rs | 2 +- rust/crates/core/src/protocol/command.rs | 18 + .../core/src/runtime/dispatcher/plugins.rs | 15 + .../core/src/tests/declarative_plugins.rs | 99 +- rust/crates/platform/src/paths.rs | 96 +- rust/crates/plugin-manifest/Cargo.toml | 1 + .../plugin-manifest/src/command_installers.rs | 864 ++++++++++++++++++ rust/crates/plugin-manifest/src/lib.rs | 11 +- rust/crates/plugin-manifest/src/manifest.rs | 7 + .../crates/plugin-manifest/src/permissions.rs | 17 + rust/crates/plugin-manifest/src/validation.rs | 7 + rust/crates/plugin-model/src/capabilities.rs | 6 + rust/crates/plugin-model/src/lib.rs | 7 +- rust/crates/plugin-model/src/names.rs | 14 +- .../crates/project-generators/src/manifest.rs | 12 +- shared/plugins/contract/v1/README.md | 106 +++ .../command-installer-plans.json | 299 ++++++ .../command-installer.plugin.json | 100 ++ .../fixtures/manifest/invalid-manifests.json | 22 +- .../contract/v1/plugin-manifest.schema.json | 91 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 2 + .../plugins/reference/domains/toolchains.md | 34 + .../plugins/reference/protocol-changelog.md | 2 + 28 files changed, 1844 insertions(+), 42 deletions(-) create mode 100644 rust/crates/plugin-manifest/src/command_installers.rs create mode 100644 shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json create mode 100644 shared/plugins/contract/v1/fixtures/command-installers/command-installer.plugin.json diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 38d43bf4..b17a586f 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1285,6 +1285,7 @@ version = "0.1.0" dependencies = [ "lithe-build", "lithe-debug", + "lithe-platform", "lithe-plugin-backend", "lithe-plugin-functions", "lithe-plugin-grammar", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 504143cc..583483e4 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -447,6 +447,9 @@ or removing a command fails until the table changes in the same commit. | `plugins.declarative.languageServerLaunchPlan` | Expand a declarative plugin's language-server, build-provider, VCS-provider, backend, or debug-adapter launch with host directories and architecture | | `plugins.languageServers.decodeLaunch` | Bound the answer of a plugin backend that resolved a language server's launch and return the plan the host starts | | `plugins.languageServers.stateRetention` | Choose which inactive per-workspace state directories of a plugin language server the host deletes | +| `plugins.commandInstallers.requirements` | List each `systemCommand` launch of a plugin with its commands and the installer that provides each | +| `plugins.commandInstallers.plan` | Expand one command installer for the target the user chose | +| `plugins.commandInstallers.defaultDirectory` | Read where a `toolDefault` installation puts its commands from the output of its directory probes | | `plugins.contentProviders.decode` | Bound the answer of a plugin content provider function and return the document text | | `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments | | `debug.validateAdapterEndpoint` | Validate an IDE-to-DAP TCP endpoint and classify whether remote consent is required; performs no DNS or network I/O | @@ -4040,6 +4043,34 @@ those older than `maxAgeDays` and those beyond the newest that fit are listed. The host lists and deletes only directories under its own state storage, never 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 }] }`. +`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. +`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 +`${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, +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 +`shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`. + `plugins.contentProviders.decode` accepts `{ result }`, the value a plugin function returned for a document of its content scheme, and returns `{ content }`. `result` is a string, or an object whose only member is diff --git a/rust/crates/build/src/manifest.rs b/rust/crates/build/src/manifest.rs index b9b89730..b676d8ba 100644 --- a/rust/crates/build/src/manifest.rs +++ b/rust/crates/build/src/manifest.rs @@ -15,9 +15,9 @@ use super::template::{self, Allowed, Availability, BuildArgument, Variable}; use lithe_plugin_model::process::{ServerProcess, ServerRole}; use lithe_plugin_model::settings::is_setting_identifier; use lithe_plugin_model::{ - invalid, invalid_template as template_error, is_bare_command, is_identifier, - is_safe_relative_path, sorted_unique, validate_minimum_version, PluginRejection, UIIcon, - Validation, + invalid, invalid_template as template_error, is_bare_command, is_environment_name, + is_identifier, is_safe_relative_path, sorted_unique, validate_minimum_version, PluginRejection, + UIIcon, Validation, }; use regex::Regex; use serde::{Deserialize, Deserializer, Serialize}; diff --git a/rust/crates/build/src/manifest/checks.rs b/rust/crates/build/src/manifest/checks.rs index 558d485c..6b8b5cef 100644 --- a/rust/crates/build/src/manifest/checks.rs +++ b/rust/crates/build/src/manifest/checks.rs @@ -107,18 +107,6 @@ pub(crate) fn is_tag(value: &str) -> bool { is_identifier(value) && value.len() <= MAX_IDENTIFIER } -pub(crate) fn is_environment_name(value: &str) -> bool { - !value.is_empty() - && value.len() <= MAX_IDENTIFIER - && value - .chars() - .next() - .is_some_and(|first| first.is_ascii_uppercase() || first == '_') - && value.chars().all(|character| { - character.is_ascii_uppercase() || character.is_ascii_digit() || character == '_' - }) -} - /// A file name with no directory part. pub(crate) fn is_file_name(value: &str) -> bool { is_safe_relative_path(value) && !value.contains('/') && value != "." diff --git a/rust/crates/build/src/plans.rs b/rust/crates/build/src/plans.rs index 83b0e56f..86042eed 100644 --- a/rust/crates/build/src/plans.rs +++ b/rust/crates/build/src/plans.rs @@ -187,7 +187,7 @@ pub(crate) fn provider_hints(request: &OutputPlanRequest) -> Validation 64 || tool.environment.iter().any(|(key, value)| { - !super::manifest::is_environment_name(key) + !lithe_plugin_model::is_environment_name(key) || value.len() > 32768 || value.contains('\0') }) diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index d8660234..298cfa2a 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -235,6 +235,12 @@ pub enum PluginsCommand { LanguageServersDecodeLaunch, /// Picks the stored language-server state the host may delete (`plugins.languageServers.stateRetention`). LanguageServersStateRetention, + /// Lists the bare commands a plugin's launches need and their installers (`plugins.commandInstallers.requirements`). + CommandInstallersRequirements, + /// Expands a command installer for the target the user chose (`plugins.commandInstallers.plan`). + CommandInstallersPlan, + /// Reads where a `toolDefault` installation puts its commands (`plugins.commandInstallers.defaultDirectory`). + CommandInstallersDefaultDirectory, /// Checks a plugin content provider's answer (`plugins.contentProviders.decode`). ContentProvidersDecode, /// Merges a plugin's stored setting layers into effective values (`plugins.declarative.resolveSettings`). @@ -994,6 +1000,15 @@ impl CoreCommand { "plugins.languageServers.stateRetention" => { Some(Self::Plugins(PluginsCommand::LanguageServersStateRetention)) } + "plugins.commandInstallers.requirements" => { + Some(Self::Plugins(PluginsCommand::CommandInstallersRequirements)) + } + "plugins.commandInstallers.plan" => { + Some(Self::Plugins(PluginsCommand::CommandInstallersPlan)) + } + "plugins.commandInstallers.defaultDirectory" => Some(Self::Plugins( + PluginsCommand::CommandInstallersDefaultDirectory, + )), "plugins.contentProviders.decode" => { Some(Self::Plugins(PluginsCommand::ContentProvidersDecode)) } @@ -1601,6 +1616,9 @@ mod tests { "lsp.pluginServerNotify", "plugins.languageServers.decodeLaunch", "plugins.languageServers.stateRetention", + "plugins.commandInstallers.requirements", + "plugins.commandInstallers.plan", + "plugins.commandInstallers.defaultDirectory", "plugins.contentProviders.decode", "lsp.cancelOperation", "lsp.pollEvents", diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index 60ba2fea..65348442 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -63,6 +63,21 @@ pub(super) fn dispatch( payload, lithe_plugin_language_servers::state_retention_command, ), + PluginsCommand::CommandInstallersRequirements => plugin_response( + id, + payload, + lithe_plugin_manifest::command_installer_requirements_command, + ), + PluginsCommand::CommandInstallersPlan => plugin_response( + id, + payload, + lithe_plugin_manifest::command_installer_plan_command, + ), + PluginsCommand::CommandInstallersDefaultDirectory => plugin_response( + id, + payload, + lithe_plugin_manifest::command_installer_default_directory_command, + ), PluginsCommand::ContentProvidersDecode => plugin_response( id, payload, diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index a525027c..a5e3fae0 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -1,6 +1,8 @@ use lithe_plugin_manifest::{ - discover_tests_command, language_server_launch_plan_command, resolve_settings_command, - run_plan_command, test_plan_command, validate_command, workspace_configuration_command, + command_installer_default_directory_command, command_installer_plan_command, + command_installer_requirements_command, discover_tests_command, + language_server_launch_plan_command, resolve_settings_command, run_plan_command, + test_plan_command, validate_command, workspace_configuration_command, }; use serde_json::{json, Value}; @@ -63,6 +65,10 @@ const PROJECT_GENERATOR_FIXTURE: &str = contract_file!("fixtures/project-generators/project-generator.plugin.json"); 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_PLANS: &str = + contract_file!("fixtures/command-installers/command-installer-plans.json"); const INVALID_MANIFESTS: &str = contract_file!("fixtures/manifest/invalid-manifests.json"); const COMMAND_PLANS: &str = contract_file!("fixtures/languages/command-plans.json"); @@ -95,6 +101,7 @@ fn fixture(name: &str) -> Value { "editor-providers.plugin.json" => EDITOR_PROVIDERS_FIXTURE, "project-generator.plugin.json" => PROJECT_GENERATOR_FIXTURE, "project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE, + "command-installer.plugin.json" => COMMAND_INSTALLER_FIXTURE, other => panic!("unknown fixture {other}"), }; serde_json::from_str(source).expect("fixture manifest is JSON") @@ -126,6 +133,7 @@ fn contract_fixtures_and_official_plugins_validate() { LANGUAGE_SERVER_BACKEND_FIXTURE, EDITOR_PROVIDERS_FIXTURE, PROJECT_GENERATOR_TOOL_FIXTURE, + COMMAND_INSTALLER_FIXTURE, ] { let outcome = validate(serde_json::from_str(source).unwrap()); assert_eq!(outcome["status"], "ok", "{outcome}"); @@ -253,6 +261,93 @@ fn invalid_manifest_fixtures_report_their_stable_codes() { } } +/// The command-installer commands answer the golden cases for this host's +/// platform; `lithe-plugin-manifest` checks the same cases for every +/// platform. +#[test] +fn command_installer_fixtures_match_on_this_host() { + let plans: Value = serde_json::from_str(COMMAND_INSTALLER_PLANS).unwrap(); + let platform = if cfg!(windows) { "windows" } else { "unix" }; + 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") }); + for source in [&case["payload"], &specific["payload"]] { + for (field, value) in source.as_object().into_iter().flatten() { + payload[field] = value.clone(); + } + } + for edit in case["manifestEdits"].as_array().into_iter().flatten() { + let pointer = edit["path"].as_str().unwrap(); + *payload["manifest"].pointer_mut(pointer).unwrap() = edit["value"].clone(); + } + let outcome = match case["operation"].as_str().unwrap() { + "requirements" => command_installer_requirements_command(payload), + "plan" => command_installer_plan_command(payload), + "defaultDirectory" => command_installer_default_directory_command(payload), + other => panic!("unknown operation {other}"), + } + .expect("payload is well formed"); + let expected = if specific.get("expected").is_some() { + &specific["expected"] + } else { + &case["expected"] + }; + if expected["status"] == "rejected" { + assert_eq!(outcome["status"], "rejected", "{name}: {outcome}"); + assert_eq!( + outcome["error"]["code"], expected["code"], + "{name}: {outcome}" + ); + assert_eq!( + outcome["error"]["field"], expected["field"], + "{name}: {outcome}" + ); + } else { + assert_eq!(&outcome, expected, "{name}"); + } + } +} + +/// The install review shows everything an installer runs, so changing its +/// arguments or targets is a new program the user approves again. +#[test] +fn command_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().clone() + }; + let manifest = fixture("command-installer.plugin.json"); + let before = programs(manifest.clone()); + let installers: Vec<&Value> = before + .iter() + .filter(|program| program["kind"] == "commandInstaller") + .collect(); + assert_eq!(installers.len(), 2); + assert_eq!(installers[0]["installer"], "sample-dap"); + assert_eq!(installers[1]["timeoutSeconds"], 300); + let mut changed = manifest; + changed["commandInstallers"][0]["arguments"] = json!(["install", "example.org/other@latest"]); + assert_ne!(programs(changed), before); +} + +/// A malformed request is a Core failure, not a rejection. +#[test] +fn command_installer_requests_decode_strictly() { + let manifest = fixture("command-installer.plugin.json"); + assert!(command_installer_plan_command( + json!({ "manifest": manifest, "installerID": "sample-ls", "target": "elsewhere" }) + ) + .is_err()); + assert!(command_installer_default_directory_command( + json!({ "manifest": manifest, "installerID": "sample-ls" }) + ) + .is_err()); +} + #[test] fn command_plan_fixtures_match_golden_expansions() { let fixtures: Value = serde_json::from_str(COMMAND_PLANS).unwrap(); diff --git a/rust/crates/platform/src/paths.rs b/rust/crates/platform/src/paths.rs index d4e18c79..632af47d 100644 --- a/rust/crates/platform/src/paths.rs +++ b/rust/crates/platform/src/paths.rs @@ -1,8 +1,9 @@ //! Path text that follows platform rules. //! //! Core identifies workspace files by `/`-separated paths. These helpers -//! compare such paths and convert native path text the way the given -//! platform's file systems would. +//! compare such paths, convert native path text the way the given platform's +//! file systems would, and read the native absolute paths and path lists a +//! tool prints. use crate::Platform; use std::borrow::Cow; @@ -40,6 +41,51 @@ pub fn slash_separated(path: &str, platform: Platform) -> Cow<'_, str> { } } +/// Separator between the entries of a path list such as `PATH`. +pub const fn path_list_separator(platform: Platform) -> char { + match platform { + Platform::Windows => ';', + Platform::Unix => ':', + } +} + +/// Whether native path text is absolute, judged from the text alone. +/// +/// Unix paths start with `/`. Windows paths start with a drive letter and a +/// separator (`C:\`, `C:/`) or are UNC paths (`\\server\share`); a bare `C:` +/// or a rooted `\dir` still depends on the current drive and is not absolute. +pub fn is_absolute_path(path: &str, platform: Platform) -> bool { + match platform { + Platform::Unix => path.starts_with('/'), + Platform::Windows => { + let bytes = path.as_bytes(); + let drive = bytes.len() >= 3 + && bytes[0].is_ascii_alphabetic() + && bytes[1] == b':' + && matches!(bytes[2], b'\\' | b'/'); + drive || path.starts_with(r"\\") || path.starts_with("//") + } + } +} + +/// Appends a `/`-separated relative path to a native directory with the +/// platform's separator, dropping separators that already end `directory`. +pub fn join_native(directory: &str, relative: &str, platform: Platform) -> String { + let is_separator = + |character: char| character == '/' || (platform.is_windows() && character == '\\'); + let trimmed = directory.trim_end_matches(is_separator); + let (separator, relative) = if platform.is_windows() { + ('\\', relative.replace('/', "\\")) + } else { + ('/', relative.to_owned()) + }; + // The root directory is only separators; keep it as it is. + if trimmed.is_empty() { + return format!("{directory}{relative}"); + } + format!("{trimmed}{separator}{relative}") +} + /// Reads a path stored as bytes, such as a NUL-separated Git path list. /// /// Unix paths are arbitrary bytes. Other platforms accept only UTF-8 and @@ -58,7 +104,10 @@ pub fn native_path_from_bytes(bytes: &[u8]) -> Option<&Path> { #[cfg(test)] mod tests { - use super::{native_path_from_bytes, relative_path_contains, slash_separated}; + use super::{ + is_absolute_path, join_native, native_path_from_bytes, path_list_separator, + relative_path_contains, slash_separated, + }; use crate::Platform; #[test] @@ -113,6 +162,47 @@ mod tests { assert_eq!(slash_separated("a/b", Platform::Windows), "a/b"); } + #[test] + fn path_lists_use_the_platform_separator() { + assert_eq!(path_list_separator(Platform::Unix), ':'); + assert_eq!(path_list_separator(Platform::Windows), ';'); + } + + #[test] + fn absolute_paths_follow_the_platform() { + assert!(is_absolute_path("/home/me/go", Platform::Unix)); + assert!(!is_absolute_path("go/bin", Platform::Unix)); + assert!(!is_absolute_path(r"C:\Users\me", Platform::Unix)); + assert!(is_absolute_path(r"C:\Users\me\go", Platform::Windows)); + assert!(is_absolute_path("C:/Users/me/go", Platform::Windows)); + assert!(is_absolute_path(r"\\server\share\go", Platform::Windows)); + assert!(!is_absolute_path("C:", Platform::Windows)); + assert!(!is_absolute_path("C:go", Platform::Windows)); + assert!(!is_absolute_path(r"\go", Platform::Windows)); + assert!(!is_absolute_path("go", Platform::Windows)); + } + + #[test] + fn joined_paths_use_the_platform_separator() { + assert_eq!( + join_native("/home/me/go", "bin", Platform::Unix), + "/home/me/go/bin" + ); + assert_eq!( + join_native("/home/me/go/", "a/b", Platform::Unix), + "/home/me/go/a/b" + ); + assert_eq!(join_native("/", "bin", Platform::Unix), "/bin"); + assert_eq!( + join_native(r"C:\Users\me\go\", "a/b", Platform::Windows), + r"C:\Users\me\go\a\b" + ); + assert_eq!( + join_native("C:/Users/me/go", "bin", Platform::Windows), + r"C:/Users/me/go\bin" + ); + } + #[test] fn utf8_path_bytes_read_on_every_platform() { let path = native_path_from_bytes("src/äpfel.rs".as_bytes()).expect("UTF-8 path"); diff --git a/rust/crates/plugin-manifest/Cargo.toml b/rust/crates/plugin-manifest/Cargo.toml index bf73e7eb..0794fdd9 100644 --- a/rust/crates/plugin-manifest/Cargo.toml +++ b/rust/crates/plugin-manifest/Cargo.toml @@ -8,6 +8,7 @@ description = "Declarative plugin manifests: validation, normalization and the r [dependencies] lithe-build = { path = "../build" } lithe-debug = { path = "../debug" } +lithe-platform = { path = "../platform" } lithe-plugin-backend = { path = "../plugin-backend" } lithe-plugin-functions = { path = "../plugin-functions" } lithe-plugin-grammar = { path = "../plugin-grammar" } diff --git a/rust/crates/plugin-manifest/src/command_installers.rs b/rust/crates/plugin-manifest/src/command_installers.rs new file mode 100644 index 00000000..f53dfc21 --- /dev/null +++ b/rust/crates/plugin-manifest/src/command_installers.rs @@ -0,0 +1,864 @@ +//! `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. +//! +//! Note: the decision is recorded in .agents/notes/implemented/architecture/2026-11-15-plugin-command-installers.md + +use super::*; +use lithe_platform::{paths, Platform}; + +/// Most installers one plugin may declare. +const MAX_COMMAND_INSTALLERS: usize = 16; + +/// Most commands one installation may provide. +const MAX_INSTALLER_COMMANDS: usize = 8; + +/// Most arguments of an installation or a directory probe. +const MAX_INSTALLER_ARGUMENTS: usize = 64; + +/// Longest single argument or environment value, in bytes. +const MAX_INSTALLER_VALUE_BYTES: usize = 4096; + +/// Most environment variables one target may set. +const MAX_INSTALLER_ENVIRONMENT: usize = 16; + +/// Most directory probes of a `toolDefault` target. +const MAX_DIRECTORY_PROBES: usize = 4; + +/// Timeout of an installation that declares none. +const DEFAULT_TIMEOUT_SECONDS: u64 = 600; + +/// Longest timeout an installation may declare. +const MAX_TIMEOUT_SECONDS: u64 = 3600; + +/// 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. +const SYSTEM_COMMAND_PROGRAMS: &[(&str, &str, Option<&str>)] = &[ + ("systemBackend", "backend", None), + ( + "systemBuildProvider", + "buildProvider", + Some("buildSystemID"), + ), + ("systemDebugAdapter", "debugAdapter", Some("debugAdapter")), + ("systemLanguageServer", "languageServer", Some("languageID")), + ("systemVcsProvider", "vcsProvider", Some("vcs")), +]; + +/// One way to install bare commands the plugin's launches name. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct CommandInstallerDeclaration { + /// Lowercase letters, digits, and hyphens; unique within the plugin. + pub(crate) id: String, + /// Bare commands the installation provides. Each is named by a + /// `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, + /// 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, + /// Whether the installation may download; the host shows it before the + /// user confirms. + pub(crate) may_use_network: bool, + /// How long the host lets the installation run, 1 to 3600 seconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) timeout_seconds: Option, + /// Where the installation may put the commands; at least one target. + pub(crate) targets: InstallTargets, +} + +/// The locations the user may choose between. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct InstallTargets { + /// A directory Lithe owns for the plugin, removed with it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) managed: Option, + /// Wherever the tool installs when it is told nothing. + #[serde(default, skip_serializing_if = "Option::is_none")] + 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. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ManagedTarget { + /// Replaces the installer's `arguments`. + #[serde(default, skip_serializing_if = "Option::is_none")] + arguments: Option>, + /// Variables set for the installation, over the tool's environment. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + environment: BTreeMap, + /// Package-style relative path, below the install directory, of the + /// directory the commands land in; the install directory itself when + /// absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + command_directory: Option, +} + +/// Installation where the tool installs by default. Its directory probes +/// tell the host, and through it the user, where that is. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ToolDefaultTarget { + /// Replaces the installer's `arguments`. Literal. + #[serde(default, skip_serializing_if = "Option::is_none")] + arguments: Option>, + /// Variables set for the installation, over the tool's environment. + /// Literal. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + environment: BTreeMap, + /// Probes, tried in order, that print the directory the commands land + /// in. Without probes the host can say only that the tool decides. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + directory: Vec, +} + +/// One run of the installer's tool that prints a directory. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct DirectoryProbe { + /// Arguments after the tool's executable. Literal and not empty. + arguments: Vec, + /// The output is a path list in the host's separator; its first entry + /// counts. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + path_list: bool, + /// Package-style relative path appended to the printed directory. + #[serde(default, skip_serializing_if = "Option::is_none")] + append: Option, +} + +/// The target a plan expands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +enum InstallTarget { + Managed, + ToolDefault, +} + +/// The single variable a managed target may use. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct InstallDirectory; + +fn parse_install_template(value: &str) -> Option>> { + parse_template_with(value, |name| { + (name == "installDirectory").then_some(InstallDirectory) + }) +} + +/// Checks one value that may not use any template. +fn check_literal(value: &str, field: &str) -> Validation<()> { + if value.contains("${") { + return Err(invalid_template( + field.to_string(), + "Only targets.managed may use ${installDirectory}; other installer values are literal.", + )); + } + check_value_size(value, field) +} + +fn check_value_size(value: &str, field: &str) -> Validation<()> { + if value.len() > MAX_INSTALLER_VALUE_BYTES || value.contains('\0') { + return Err(invalid( + field.to_string(), + format!("An installer value is at most {MAX_INSTALLER_VALUE_BYTES} bytes without NUL."), + )); + } + Ok(()) +} + +/// Checks one managed value and reports whether it names the directory. +fn check_managed_value(value: &str, field: &str) -> Validation { + check_value_size(value, field)?; + let parts = parse_install_template(value).ok_or_else(|| { + invalid_template( + field.to_string(), + "A managed value may use only ${installDirectory}.", + ) + })?; + Ok(parts + .iter() + .any(|part| matches!(part, TemplatePart::Variable(_)))) +} + +fn check_arguments(arguments: &[String], field: &str) -> Validation<()> { + if arguments.len() > MAX_INSTALLER_ARGUMENTS { + return Err(invalid( + field.to_string(), + format!("An installer passes at most {MAX_INSTALLER_ARGUMENTS} arguments."), + )); + } + Ok(()) +} + +fn check_environment_names(environment: &BTreeMap, field: &str) -> Validation<()> { + if environment.len() > MAX_INSTALLER_ENVIRONMENT { + return Err(invalid( + field.to_string(), + format!("A target sets at most {MAX_INSTALLER_ENVIRONMENT} environment variables."), + )); + } + match environment.keys().find(|name| !is_environment_name(name)) { + Some(name) => Err(invalid( + format!("{field}.{name}"), + "An environment variable name uses uppercase letters, digits, and _.", + )), + None => Ok(()), + } +} + +impl CommandInstallerDeclaration { + fn validate( + &self, + field: &str, + launched: &BTreeSet, + runtime_tools: RuntimeTools<'_>, + ) -> Validation<()> { + if !is_identifier(&self.id) || self.id.len() > 64 { + return Err(invalid( + format!("{field}.id"), + "An installer ID uses lowercase letters, digits, and hyphens.", + )); + } + if self.commands.is_empty() || self.commands.len() > MAX_INSTALLER_COMMANDS { + return Err(invalid( + format!("{field}.commands"), + format!("An installer provides 1 to {MAX_INSTALLER_COMMANDS} commands."), + )); + } + let mut seen = BTreeSet::new(); + for (index, command) in self.commands.iter().enumerate() { + let entry = format!("{field}.commands[{index}]"); + if !is_bare_command(command) { + return Err(invalid( + entry, + "An installed command is a bare command name.", + )); + } + if !seen.insert(command) { + return Err(invalid(entry, "A command is listed more than once.")); + } + if !launched.contains(command) { + return Err(invalid( + entry, + format!("No systemCommand launch of this plugin names {command}."), + )); + } + } + 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( + format!("{field}.timeoutSeconds"), + format!("An installation times out after 1 to {MAX_TIMEOUT_SECONDS} seconds."), + )); + } + } + 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( + targets, + "An installer declares at least one target.", + )); + } + if let Some(managed) = &self.targets.managed { + self.validate_managed(managed, &format!("{targets}.managed"))?; + } + if let Some(tool_default) = &self.targets.tool_default { + validate_tool_default(tool_default, &format!("{targets}.toolDefault"))?; + } + Ok(()) + } + + fn validate_managed(&self, managed: &ManagedTarget, field: &str) -> Validation<()> { + let mut names_directory = false; + if let Some(arguments) = &managed.arguments { + check_arguments(arguments, &format!("{field}.arguments"))?; + for (index, argument) in arguments.iter().enumerate() { + names_directory |= + check_managed_value(argument, &format!("{field}.arguments[{index}]"))?; + } + } + check_environment_names(&managed.environment, &format!("{field}.environment"))?; + for (name, value) in &managed.environment { + names_directory |= check_managed_value(value, &format!("{field}.environment.{name}"))?; + } + if !names_directory { + return Err(invalid_template( + field.to_string(), + "A managed target passes ${installDirectory} in its arguments or environment.", + )); + } + if let Some(directory) = &managed.command_directory { + if !is_safe_relative_path(directory) { + return Err(invalid( + format!("{field}.commandDirectory"), + "The command directory is a relative path inside the install directory.", + )); + } + } + Ok(()) + } + + fn effective_arguments<'a>(&'a self, replacement: &'a Option>) -> &'a [String] { + replacement.as_deref().unwrap_or(&self.arguments) + } + + fn timeout_milliseconds(&self) -> u64 { + self.timeout_seconds.unwrap_or(DEFAULT_TIMEOUT_SECONDS) * 1000 + } + + /// The targets the host offers, in a stable order. + fn target_names(&self) -> Vec { + let mut targets = Vec::new(); + if self.targets.managed.is_some() { + targets.push(InstallTarget::Managed); + } + if self.targets.tool_default.is_some() { + targets.push(InstallTarget::ToolDefault); + } + targets + } +} + +fn validate_tool_default(target: &ToolDefaultTarget, field: &str) -> Validation<()> { + if let Some(arguments) = &target.arguments { + check_arguments(arguments, &format!("{field}.arguments"))?; + for (index, argument) in arguments.iter().enumerate() { + check_literal(argument, &format!("{field}.arguments[{index}]"))?; + } + } + check_environment_names(&target.environment, &format!("{field}.environment"))?; + for (name, value) in &target.environment { + check_literal(value, &format!("{field}.environment.{name}"))?; + } + if target.directory.len() > MAX_DIRECTORY_PROBES { + return Err(invalid( + format!("{field}.directory"), + format!("A target probes its directory at most {MAX_DIRECTORY_PROBES} ways."), + )); + } + for (index, probe) in target.directory.iter().enumerate() { + let entry = format!("{field}.directory[{index}]"); + if probe.arguments.is_empty() { + return Err(invalid( + format!("{entry}.arguments"), + "A directory probe passes at least one argument.", + )); + } + check_arguments(&probe.arguments, &format!("{entry}.arguments"))?; + for (position, argument) in probe.arguments.iter().enumerate() { + check_literal(argument, &format!("{entry}.arguments[{position}]"))?; + } + if let Some(append) = &probe.append { + if !is_safe_relative_path(append) { + return Err(invalid( + format!("{entry}.append"), + "The appended path is relative and stays below the printed directory.", + )); + } + } + } + Ok(()) +} + +impl DeclarativePluginManifest { + /// Checks `commandInstallers` against the plugin's own launches and + /// `requiresTools`, then orders the installers by ID. + pub(crate) fn validate_command_installers( + &mut self, + runtime_tools: RuntimeTools<'_>, + ) -> Validation<()> { + if self.command_installers.is_empty() { + return Ok(()); + } + if self.command_installers.len() > MAX_COMMAND_INSTALLERS { + return Err(invalid( + "commandInstallers", + format!("A plugin declares at most {MAX_COMMAND_INSTALLERS} command installers."), + )); + } + let launched: BTreeSet = self + .command_consumers() + .into_iter() + .flat_map(|consumer| consumer.commands) + .collect(); + let mut ids = BTreeSet::new(); + let mut installed = BTreeSet::new(); + for (index, installer) in self.command_installers.iter().enumerate() { + let field = format!("commandInstallers[{index}]"); + installer.validate(&field, &launched, runtime_tools)?; + if !ids.insert(installer.id.clone()) { + return Err(invalid( + format!("{field}.id"), + "An installer ID is declared more than once.", + )); + } + for (position, command) in installer.commands.iter().enumerate() { + if !installed.insert(command.clone()) { + return Err(invalid( + format!("{field}.commands[{position}]"), + format!("{command} already has an installer."), + )); + } + } + } + self.command_installers + .sort_by(|left, right| left.id.cmp(&right.id)); + Ok(()) + } + + /// Every `systemCommand` launch the host may start, in the order of the + /// reviewed program list. + fn command_consumers(&self) -> Vec { + self.programs() + .iter() + .filter_map(|program| { + let kind = program["kind"].as_str()?; + let (_, consumer, key) = SYSTEM_COMMAND_PROGRAMS + .iter() + .find(|(program_kind, _, _)| *program_kind == kind)?; + let commands = program["commands"] + .as_array()? + .iter() + .filter_map(|command| command.as_str().map(str::to_string)) + .collect(); + Some(CommandConsumer { + kind: consumer, + id: key.and_then(|key| program[key].as_str().map(str::to_string)), + commands, + }) + }) + .collect() + } + + fn command_installer(&self, id: &str) -> Validation<&CommandInstallerDeclaration> { + self.command_installers + .iter() + .find(|installer| installer.id == id) + .ok_or_else(|| { + PluginRejection::at( + "plugin.commandInstaller.unknown", + "installerID", + format!("The plugin declares no command installer {id}."), + ) + }) + } +} + +/// One launch that starts a bare command. +struct CommandConsumer { + kind: &'static str, + id: Option, + commands: Vec, +} + +/// The install review entry of one installer: everything that decides what +/// the installation runs. +pub(crate) fn programs(installer: &CommandInstallerDeclaration) -> Value { + json!({ + "kind": "commandInstaller", + "installer": installer.id, + "commands": installer.commands, + "tool": installer.tool, + "minimumVersion": installer.minimum_version, + "arguments": installer.arguments, + "targets": installer.targets, + "mayUseNetwork": installer.may_use_network, + "timeoutSeconds": installer.timeout_seconds.unwrap_or(DEFAULT_TIMEOUT_SECONDS), + }) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RequirementsPayload { + manifest: Value, +} + +/// `plugins.commandInstallers.requirements`: lists every launch that starts +/// a bare command, the installer of each command, and the installers. +pub fn command_installer_requirements_command(payload: Value) -> Result { + let payload: RequirementsPayload = + decode_payload(payload, "plugins.commandInstallers.requirements")?; + Ok(outcome(requirements(payload))) +} + +fn requirements(payload: RequirementsPayload) -> Validation<(&'static str, Value)> { + let manifest = validate_manifest_value(payload.manifest)?; + let installer_of = |command: &str| { + manifest + .command_installers + .iter() + .find(|installer| installer.commands.iter().any(|name| name == command)) + .map(|installer| installer.id.clone()) + }; + let consumers: Vec = manifest + .command_consumers() + .into_iter() + .map(|consumer| { + json!({ + "kind": consumer.kind, + "id": consumer.id, + "commands": consumer.commands.iter().map(|command| json!({ + "command": command, + "installer": installer_of(command), + })).collect::>(), + }) + }) + .collect(); + let installers: Vec = manifest + .command_installers + .iter() + .map(|installer| { + json!({ + "id": installer.id, + "commands": installer.commands, + "tool": installer.tool, + "minimumVersion": installer.minimum_version, + "mayUseNetwork": installer.may_use_network, + "targets": installer.target_names(), + }) + }) + .collect(); + Ok(( + "requirements", + json!({ "consumers": consumers, "installers": installers }), + )) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PlanPayload { + manifest: Value, + #[serde(rename = "installerID")] + installer_id: String, + target: InstallTarget, + /// Absolute directory the host made for a managed installation. + #[serde(default)] + install_directory: 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. +pub fn command_installer_plan_command(payload: Value) -> Result { + let payload: PlanPayload = decode_payload(payload, "plugins.commandInstallers.plan")?; + Ok(outcome(plan(payload, Platform::HOST))) +} + +fn plan(payload: PlanPayload, platform: Platform) -> Validation<(&'static str, Value)> { + let manifest = validate_manifest_value(payload.manifest)?; + let installer = manifest.command_installer(&payload.installer_id)?; + let undeclared = || { + PluginRejection::at( + "plugin.commandInstaller.targetUndeclared", + "target", + format!( + "The command installer {} does not declare this target.", + installer.id + ), + ) + }; + let directory_invalid = |message: &str| { + PluginRejection::at( + "plugin.commandInstaller.directoryInvalid", + "installDirectory", + message.to_string(), + ) + }; + let mut plan = json!({ + "installer": installer.id, + "target": payload.target, + "commands": installer.commands, + "tool": installer.tool, + "minimumVersion": installer.minimum_version, + "mayUseNetwork": installer.may_use_network, + "timeoutMilliseconds": installer.timeout_milliseconds(), + }); + match payload.target { + InstallTarget::Managed => { + let managed = installer.targets.managed.as_ref().ok_or_else(undeclared)?; + let directory = payload + .install_directory + .as_deref() + .filter(|directory| { + paths::is_absolute_path(directory, platform) + && !directory.contains(['\n', '\r', '\0']) + }) + .ok_or_else(|| { + directory_invalid( + "A managed installation needs the absolute directory the host made.", + ) + })?; + let expand = |value: &str| { + parse_install_template(value) + .unwrap_or_default() + .into_iter() + .map(|part| match part { + TemplatePart::Text(text) => text, + TemplatePart::Variable(InstallDirectory) => directory.to_string(), + }) + .collect::() + }; + plan["arguments"] = json!(installer + .effective_arguments(&managed.arguments) + .iter() + .map(|argument| expand(argument)) + .collect::>()); + plan["environment"] = json!(managed + .environment + .iter() + .map(|(name, value)| (name.clone(), expand(value))) + .collect::>()); + plan["commandDirectory"] = json!(match &managed.command_directory { + Some(relative) => paths::join_native(directory, relative, platform), + None => directory.to_string(), + }); + plan["directoryProbes"] = json!([]); + } + InstallTarget::ToolDefault => { + let target = installer + .targets + .tool_default + .as_ref() + .ok_or_else(undeclared)?; + if payload.install_directory.is_some() { + return Err(directory_invalid( + "A toolDefault installation takes no install directory.", + )); + } + plan["arguments"] = json!(installer.effective_arguments(&target.arguments)); + plan["environment"] = json!(target.environment); + plan["commandDirectory"] = Value::Null; + plan["directoryProbes"] = json!(target + .directory + .iter() + .map(|probe| json!({ "arguments": probe.arguments })) + .collect::>()); + } + } + Ok(("plan", plan)) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct DefaultDirectoryPayload { + manifest: Value, + #[serde(rename = "installerID")] + installer_id: String, + /// Standard output of each directory probe in plan order; `null` for a + /// probe that did not exit successfully. + outputs: Vec>, +} + +/// `plugins.commandInstallers.defaultDirectory`: the directory a +/// `toolDefault` installation puts its commands in, read from the output of +/// the first probe that names an absolute directory; `null` when none does. +pub fn command_installer_default_directory_command(payload: Value) -> Result { + let payload: DefaultDirectoryPayload = + decode_payload(payload, "plugins.commandInstallers.defaultDirectory")?; + Ok(outcome(default_directory(payload, Platform::HOST))) +} + +fn default_directory( + payload: DefaultDirectoryPayload, + platform: Platform, +) -> Validation<(&'static str, Value)> { + let manifest = validate_manifest_value(payload.manifest)?; + let installer = manifest.command_installer(&payload.installer_id)?; + let target = installer.targets.tool_default.as_ref().ok_or_else(|| { + PluginRejection::at( + "plugin.commandInstaller.targetUndeclared", + "installerID", + format!( + "The command installer {} does not declare toolDefault.", + installer.id + ), + ) + })?; + if payload.outputs.len() != target.directory.len() { + return Err(PluginRejection::at( + "plugin.commandInstaller.probeOutputsInvalid", + "outputs", + format!( + "The installer has {} directory probes; send one output for each.", + target.directory.len() + ), + )); + } + let directory = target + .directory + .iter() + .zip(&payload.outputs) + .find_map(|(probe, output)| probe_directory(probe, output.as_deref()?, platform)); + Ok(("directory", json!(directory))) +} + +/// The directory one probe's output names, or `None` when it names no +/// absolute directory. +fn probe_directory(probe: &DirectoryProbe, output: &str, platform: Platform) -> Option { + let output = output.trim(); + let directory = if probe.path_list { + output + .split(paths::path_list_separator(platform)) + .map(str::trim) + .find(|entry| !entry.is_empty())? + } else { + output + }; + if directory.is_empty() + || directory.contains(['\n', '\r', '\0']) + || !paths::is_absolute_path(directory, platform) + { + return None; + } + Some(match &probe.append { + Some(relative) => paths::join_native(directory, relative, platform), + None => directory.to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PLUGIN: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer.plugin.json" + )); + const PLANS: &str = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json" + )); + + /// Every golden case, on both platforms: path rules are the platform's, + /// so a case whose result depends on them carries one input and result + /// per platform. + #[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(); + for (platform, key) in [(Platform::Unix, "unix"), (Platform::Windows, "windows")] { + let specific = &case["platforms"][key]; + let mut payload = json!({ "manifest": plugin }); + for source in [&case["payload"], &specific["payload"]] { + if let Some(fields) = source.as_object() { + for (field, value) in fields { + payload[field] = value.clone(); + } + } + } + for edit in case["manifestEdits"].as_array().into_iter().flatten() { + let pointer = edit["path"].as_str().unwrap(); + *payload["manifest"].pointer_mut(pointer).unwrap() = edit["value"].clone(); + } + let result = match case["operation"].as_str().unwrap() { + "requirements" => requirements(serde_json::from_value(payload).unwrap()), + "plan" => plan(serde_json::from_value(payload).unwrap(), platform), + "defaultDirectory" => { + default_directory(serde_json::from_value(payload).unwrap(), platform) + } + other => panic!("unknown operation {other}"), + }; + let expected = if specific.get("expected").is_some() { + &specific["expected"] + } else { + &case["expected"] + }; + let outcome = outcome(result); + // A rejection is matched by its stable code and field; the + // message is English prose that may be reworded. + if expected["status"] == "rejected" { + assert_eq!(outcome["status"], "rejected", "{name} on {key}: {outcome}"); + assert_eq!( + outcome["error"]["code"], expected["code"], + "{name} on {key}: {outcome}" + ); + assert_eq!( + outcome["error"]["field"], expected["field"], + "{name} on {key}: {outcome}" + ); + } else { + assert_eq!(&outcome, expected, "{name} on {key}"); + } + } + } + } + + fn probe(path_list: bool, append: Option<&str>) -> DirectoryProbe { + DirectoryProbe { + arguments: vec!["env".to_string()], + path_list, + append: append.map(str::to_string), + } + } + + #[test] + fn a_probe_reads_the_first_path_list_entry_and_appends() { + assert_eq!( + probe_directory( + &probe(true, Some("bin")), + ":/home/me/go:/opt/go\n", + Platform::Unix + ), + Some("/home/me/go/bin".to_string()) + ); + assert_eq!( + probe_directory( + &probe(true, Some("bin")), + "C:\\Users\\me\\go;D:\\go\r\n", + Platform::Windows + ), + Some("C:\\Users\\me\\go\\bin".to_string()) + ); + } + + #[test] + fn a_probe_without_an_absolute_directory_names_none() { + for output in ["", " \n", "relative/bin", "/a\n/b"] { + assert_eq!( + probe_directory(&probe(false, None), output, Platform::Unix), + None, + "{output:?}" + ); + } + assert_eq!( + probe_directory(&probe(false, None), "/home/me/bin\n", Platform::Unix), + Some("/home/me/bin".to_string()) + ); + assert_eq!( + probe_directory(&probe(false, None), "/home/me/bin", Platform::Windows), + None + ); + } +} diff --git a/rust/crates/plugin-manifest/src/lib.rs b/rust/crates/plugin-manifest/src/lib.rs index 89abef8c..7b370b42 100644 --- a/rust/crates/plugin-manifest/src/lib.rs +++ b/rust/crates/plugin-manifest/src/lib.rs @@ -21,16 +21,17 @@ use lithe_plugin_model::settings::{ MAX_SETTINGS, MAX_SETTING_ACTIONS, }; use lithe_plugin_model::{ - decode_payload, invalid, invalid_template, is_bare_command, is_identifier, + decode_payload, invalid, invalid_template, is_bare_command, is_environment_name, is_identifier, is_official_namespace, is_plugin_id, is_safe_relative_path, is_semantic_version, outcome, - parse_template_with, regex_literal, sorted_unique, PluginRejection, TemplatePart, UIIcon, - Validation, + parse_template_with, regex_literal, sorted_unique, validate_minimum_version, PluginRejection, + TemplatePart, UIIcon, Validation, }; use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; +mod command_installers; mod commands; mod declarations; mod launch; @@ -45,6 +46,10 @@ mod templates; mod ui; mod validation; +pub use command_installers::{ + command_installer_default_directory_command, command_installer_plan_command, + command_installer_requirements_command, +}; pub use commands::*; pub use launch::*; pub use manifest::*; diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 6fd4fce9..68f3f5e6 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -57,6 +57,10 @@ pub struct DeclarativePluginManifest { /// live in `lithe_debug::adapters`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) debug_adapters: Vec, + /// How the host installs bare commands the plugin's `systemCommand` + /// launches need; see `command_installers`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) command_installers: Vec, /// Entries of the New Project window. The shape and its validation live /// in `lithe_project_generators`. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -450,6 +454,9 @@ impl DeclarativePluginManifest { if let Some(backend) = &self.backend { programs.extend(lithe_plugin_backend::programs(backend)); } + for installer in &self.command_installers { + programs.push(crate::command_installers::programs(installer)); + } // Order by kind, then language or tool, then the full serialized // value as a total tie-breaker; duplicates (two servers needing the // same runtime) collapse to one entry. diff --git a/rust/crates/plugin-manifest/src/permissions.rs b/rust/crates/plugin-manifest/src/permissions.rs index ebe19969..c3e7558c 100644 --- a/rust/crates/plugin-manifest/src/permissions.rs +++ b/rust/crates/plugin-manifest/src/permissions.rs @@ -55,9 +55,14 @@ const PERMISSION_DEBUG_ATTACH: &str = "debug.attach"; /// (`lithe/host/debug/start`), a host-method permission of the backend. const PERMISSION_DEBUG_START: &str = "debug.start"; +/// Installing, after the user confirms each time, a command the plugin's +/// launches need with one of its required tools. +const PERMISSION_COMMAND_INSTALL: &str = "commands.install"; + const KNOWN_PERMISSIONS: &[&str] = &[ PERMISSION_BACKEND, PERMISSION_BUILD, + PERMISSION_COMMAND_INSTALL, PERMISSION_CREDENTIALS, PERMISSION_DEBUG_ATTACH, PERMISSION_DEBUG_LAUNCH, @@ -161,6 +166,18 @@ impl DeclarativePluginManifest { if !self.project_generators.is_empty() { required.insert(PERMISSION_PROJECT_GENERATE); } + if !self.command_installers.is_empty() { + required.insert(PERMISSION_COMMAND_INSTALL); + } else if self + .permissions + .iter() + .any(|p| p == PERMISSION_COMMAND_INSTALL) + { + return Err(invalid( + "permissions", + "commands.install is used by a command installer; declare one or remove the permission.", + )); + } if self.backend.is_some() { required.insert(PERMISSION_BACKEND); } else if self.permissions.iter().any(|p| p == PERMISSION_CREDENTIALS) { diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 2e54b6f5..9fe3f976 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -271,6 +271,9 @@ impl DeclarativePluginManifest { runtime_tools, })?; } + // Installers serve the launches above, so they are checked against + // the validated program list. + self.validate_command_installers(runtime_tools)?; self.validate_permissions()?; self.validate_activation_events()?; Ok(self) @@ -321,6 +324,10 @@ impl DeclarativePluginManifest { capabilities::DEBUG_ADAPTERS, !self.debug_adapters.is_empty(), ), + ( + capabilities::COMMAND_INSTALLERS, + !self.command_installers.is_empty(), + ), (capabilities::BACKEND, self.backend.is_some()), ( capabilities::TOOL_DEFINITIONS, diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 2237ca99..1a60c652 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -84,6 +84,11 @@ pub const PROJECT_GENERATORS: &str = "projectGenerators"; /// bindings; see `lithe_debug::adapters`. pub const DEBUG_ADAPTERS: &str = "debugAdapters"; +/// `commandInstallers[]`: how the host installs, after the user confirms, a +/// bare command that one of the plugin's `systemCommand` launches needs; see +/// `lithe_plugin_manifest::command_installers`. +pub const COMMAND_INSTALLERS: &str = "commandInstallers"; + /// Independent providers that translate external shortcut settings. pub const KEYMAP_IMPORT_PROVIDERS: &str = "keymapImportProviders"; /// `pluginFunctions`: functions exported to, and called from, other plugins; @@ -105,6 +110,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (BUILD_MODEL_INPUTS, &[0]), (BUILD_PROVIDERS, &[0]), (BUILD_SYSTEMS, &[0]), + (COMMAND_INSTALLERS, &[0]), (DEBUG_ADAPTERS, &[0]), (EXECUTION_PROVIDERS, &[0]), (KEYMAP_IMPORT_PROVIDERS, &[0]), diff --git a/rust/crates/plugin-model/src/lib.rs b/rust/crates/plugin-model/src/lib.rs index c0329822..635259e2 100644 --- a/rust/crates/plugin-model/src/lib.rs +++ b/rust/crates/plugin-model/src/lib.rs @@ -28,9 +28,10 @@ mod version; pub use icon::UIIcon; pub use manifest::PluginManifest; pub use names::{ - is_bare_command, is_function_id, is_identifier, is_language_tag, is_local_tool_id, - is_official_namespace, is_plugin_id, is_safe_relative_path, is_semantic_version, is_tool_id, - is_tool_namespace, sorted_unique, MAX_FUNCTION_ID_BYTES, OFFICIAL_PLUGIN_NAMESPACE, + is_bare_command, is_environment_name, is_function_id, is_identifier, is_language_tag, + is_local_tool_id, is_official_namespace, is_plugin_id, is_safe_relative_path, + is_semantic_version, is_tool_id, is_tool_namespace, sorted_unique, MAX_FUNCTION_ID_BYTES, + OFFICIAL_PLUGIN_NAMESPACE, }; pub use rejection::{ decode_payload, invalid, invalid_template, outcome, PluginRejection, Validation, diff --git a/rust/crates/plugin-model/src/names.rs b/rust/crates/plugin-model/src/names.rs index 749b62a9..0af146e0 100644 --- a/rust/crates/plugin-model/src/names.rs +++ b/rust/crates/plugin-model/src/names.rs @@ -1,5 +1,6 @@ //! The identifier alphabets of the manifest contract: plugin, function and -//! short IDs, package-relative paths, and bare command names. +//! short IDs, package-relative paths, bare command names, and environment +//! variable names. use std::collections::BTreeSet; @@ -26,6 +27,17 @@ pub fn is_bare_command(value: &str) -> bool { && !value.chars().any(char::is_whitespace) } +/// An environment variable name a manifest may set: uppercase letters, +/// digits and `_`, not starting with a digit, at most 64 bytes. +pub fn is_environment_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= 64 + && !value.starts_with(|character: char| character.is_ascii_digit()) + && value.chars().all(|character| { + character.is_ascii_uppercase() || character.is_ascii_digit() || character == '_' + }) +} + /// Language tag in the `language[-Script][-REGION]` form used by `.lproj` /// directories and `l10n/` files, e.g. `zh-Hans` or `en`. pub fn is_language_tag(tag: &str) -> bool { diff --git a/rust/crates/project-generators/src/manifest.rs b/rust/crates/project-generators/src/manifest.rs index fd73a5fd..3e78506c 100644 --- a/rust/crates/project-generators/src/manifest.rs +++ b/rust/crates/project-generators/src/manifest.rs @@ -3,7 +3,8 @@ use super::template::{self, Source, Variable}; use lithe_plugin_model::settings::is_setting_identifier; use lithe_plugin_model::{ - invalid, is_bare_command, is_safe_relative_path, TemplatePart, UIIcon, Validation, + invalid, is_bare_command, is_environment_name, is_safe_relative_path, TemplatePart, UIIcon, + Validation, }; use regex::Regex; use serde::{Deserialize, Serialize}; @@ -955,12 +956,3 @@ fn is_option_value(value: &str) -> bool { character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-') }) } - -fn is_environment_name(value: &str) -> bool { - !value.is_empty() - && value.len() <= 64 - && !value.starts_with(|character: char| character.is_ascii_digit()) - && value.chars().all(|character| { - character.is_ascii_uppercase() || character.is_ascii_digit() || character == '_' - }) -} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 4a56fb10..1d0c85e2 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -178,6 +178,7 @@ symbolic links. A host treats an installed package as read-only. | `settings` | User-adjustable plugin options. | | `ui` | Host-rendered tool windows and commands. | | `buildSystems` | Project-level build tools. | +| `commandInstallers` | How the host installs a bare command a `systemCommand` launch needs; requires `commandInstallers: 0` and `commands.install`; see [Command installers](#command-installers). | | `toolDefinitions` | Plugin-owned tool policy ([Core foundation](toolchains/README.md)); requires `toolDefinitions: 0`; a host may offer read-only discovery and resolve Build and run tools. | | `toolchainProviders` | Backend fact-provider declarations ([Core foundation](toolchains/README.md)); requires `toolchainProviders: 0`, `backend: 0` and `toolchains.provide`. | | `keymapImportProviders` | Independent shortcut import providers; requires `keymapImportProviders: 0`, `backend: 0` and `keymaps.provide`. A host provides access to explicitly selected sources. | @@ -789,6 +790,7 @@ belongs to one capability: | `debugAdapters` | [`debugAdapters[]`](#debug-adapters) | — | Starts the adapter and applies its [declared features and defaults](#adapter-features-and-defaults). | | `outputLinkMatchers` | [`outputLinkMatchers[]`](#output-link-matchers) | — | Turns Run and Test console text into links through the declared patterns. | | `projectGenerators` | [`projectGenerators[]`](#project-generators), including [`tool` fields](#tool-fields) | — | Lists the entries in the New Project window and generates the project. | +| `commandInstallers` | [`commandInstallers[]`](#command-installers) | — | Reports missing commands of `systemCommand` launches and installs them after the user confirms the command line, the network use and the target. | | `backend` | [`backend`](#plugin-backend): the plugin's own long-lived process | `litheFunctions` | Starts the backend with or without a page, serves the host services its permissions grant, and speaks `litheFunctions`. | | `toolDefinitions` | `toolDefinitions[]`: [tool identities, layouts, discovery and four-layer candidates](toolchains/README.md) | — | Resolves the definitions through the four layers. | | `toolchainProviders` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](toolchains/README.md) | toolchain provider protocol (`litheToolchains`) | Starts the provider and validates its answers. | @@ -1140,6 +1142,101 @@ A toolchain that resolves to a project file remains project code, including through a symlink, and native configuration requires explicit Read before running it. See [`build-toolchains.plugin.json`](fixtures/build-systems/build-toolchains.plugin.json). +## Command installers + +A [`systemCommand` launch](#process-start) names a bare command that the host +finds with its tool discovery. When the machine lacks it, `commandInstallers[]` +tells the host how to install it with a tool the plugin already requires, so +the user installs it from plugin management instead of a terminal. The section +requires `commandInstallers: 0` and the `commands.install` permission. + +```json +"requiresTools": ["go"], +"commandInstallers": [ + { + "id": "dlv", + "commands": ["dlv"], + "tool": "go", + "minimumVersion": "1.22", + "arguments": ["install", "github.com/go-delve/delve/cmd/dlv@latest"], + "mayUseNetwork": true, + "targets": { + "managed": { "environment": { "GOBIN": "${installDirectory}" } }, + "toolDefault": { + "directory": [ + { "arguments": ["env", "GOBIN"] }, + { "arguments": ["env", "GOPATH"], "pathList": true, "append": "bin" } + ] + } + } + } +] +``` + +| Field | Meaning | +| --- | --- | +| `id` | Lowercase letters, digits and `-`, at most 64 characters; unique within the plugin. | +| `commands` | 1 to 8 bare command names the installation provides. Each one is named by a `systemCommand` launch of this manifest (a language server, build provider, VCS provider, debug adapter or the backend) and by no other installer. | +| `tool` | The tool-definition ID, listed in `requiresTools`, whose executable runs the installation and the directory probes. | +| `minimumVersion` | Optional lowest version of `tool`: one to three dotted numbers. | +| `arguments` | Arguments after the tool's executable, used by a target that does not replace them. Literal: no template variables. | +| `mayUseNetwork` | Required: whether the installation may download. The host shows it before the user confirms. | +| `timeoutSeconds` | How long the host lets the installation run, 1 to 3600; 600 when absent. | +| `targets` | Where the commands may land: `managed`, `toolDefault`, or both. At least one. | + +The user chooses the target when installing: + +- **`managed`** installs into a directory the host owns for the plugin, in its + application data and never in the app bundle, the installation directory or + the plugin package; the host removes it with the plugin. `arguments` + (optional, replaces the installer's) and `environment` (variables set over + the tool's environment) may use `${installDirectory}`, the only template + variable of this section, and together must use it at least once. + `commandDirectory` is a package-style relative path, below the install + directory, of the directory the commands land in; the install directory + itself when absent. +- **`toolDefault`** installs wherever the tool installs when it is told + nothing. `arguments` and `environment` are literal. `directory` lists up to + 4 probes, tried in order: runs of the same tool with non-empty literal + `arguments` whose standard output names the directory the commands land in. + With `pathList: true` the first non-empty entry of a list in the host's path + separator counts; `append` is a package-style relative path added to the + printed directory. Without probes the host can say only that the tool + decides. + +At most 16 installers, 64 arguments per list, 16 environment variables per +target, and 4096 bytes per argument or value. An environment name is uppercase +letters, digits and `_`, not starting with a digit. Only `systemCommand` +launches are served: a build system's or execution provider's executable +resolved through `invocation.executables` is not. + +The host never installs on its own: + +1. `plugins.commandInstallers.requirements` lists each `systemCommand` launch + with its commands and their installer, `null` when none provides it. The + host looks each command up as the launch does and offers the installer of a + missing one. +2. For `toolDefault`, the host runs each probe with the resolved `tool` and + sends their outputs to `plugins.commandInstallers.defaultDirectory`, which + answers the directory, or `null` when no probe named an absolute one. +3. The host shows the tool, the expanded command line, whether it uses the + network and the directory of each target, and lets the user choose one. +4. `plugins.commandInstallers.plan` expands the chosen target. The host runs + `tool` with `arguments` and `environment` under `timeoutMilliseconds`, + shows the output, lets the user cancel, and then checks that every command + is in `commandDirectory` (`managed`) or in the default directory + (`toolDefault`). +5. Later launches of the plugin find the commands there: the host adds the + plugin's managed command directory and the default directories it recorded + to the lookup of that plugin's `systemCommand` launches. + +Every installer is a program of the [install review](#trust-and-install-review) +(`kind: "commandInstaller"` with its fields), so a change to what it runs is +approved again. See +[`command-installer.plugin.json`](fixtures/command-installers/command-installer.plugin.json) +and the golden cases in +[`command-installer-plans.json`](fixtures/command-installers/command-installer-plans.json). + ## Permissions and activation | Permission | Required when | @@ -1152,6 +1249,7 @@ before running it. See [`build-toolchains.plugin.json`](fixtures/build-systems/b | `debug.launch` | `debugAdapters` is not empty | | `debug.attach` | an adapter lists `attach` in `requests` (and only then); it also covers attaching to a remote host and port | | `project.generate` | `projectGenerators` is not empty | +| `commands.install` | `commandInstallers` is not empty (and only then); permits running the declared installations after the user confirms each, nothing else | | `ui.contribute` | `ui` is declared | | `ui.web` | a tool window shows [web content](#web-content) | | `backend.launch` | `backend` is declared | @@ -4075,6 +4173,14 @@ command payload is a Core `invalid_request` failure instead. | `plugin.download.failed` | Host | An index or archive could not be downloaded | | `plugin.signature.missing`, `plugin.signature.invalid`, `plugin.signature.untrusted` | Host | Package signature problems | | `plugin.launch.missing` | Host | The packaged language server is missing or not executable | +| `plugin.command.missing` | Host | None of the commands a `systemCommand` launch names is on `PATH`, in the plugin's managed command directory, or in a default directory the host recorded; the host offers the [command installer](#command-installers) when there is one | +| `plugin.commandInstaller.unknown` | Core | `installerID` names no command installer of the plugin | +| `plugin.commandInstaller.targetUndeclared` | Core | The installer does not declare the requested target (`field: "target"`), or has no `toolDefault` to read a default directory for (`field: "installerID"`) | +| `plugin.commandInstaller.directoryInvalid` | Core | A `managed` plan has no absolute `installDirectory` for this platform, or a `toolDefault` plan was sent one | +| `plugin.commandInstaller.probeOutputsInvalid` | Core | `outputs` does not hold one entry for each directory probe | +| `plugin.commandInstaller.failed` | Host | The installation exited unsuccessfully | +| `plugin.commandInstaller.timedOut` | Host | The installation ran past `timeoutMilliseconds` and was stopped | +| `plugin.commandInstaller.commandsMissing` | Host | The installation finished but a command it provides is not in its directory | | `plugin.runtime.missing` | Host | A tool a launch needs cannot be found, or is older than its `minimumVersion`, when the server starts | | `plugin.web.unknownMethod` | Host | A plugin page called a bridge method the host does not implement | | `plugin.web.invalidRequest` | Host | A bridge call has malformed parameters | diff --git a/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json b/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json new file mode 100644 index 00000000..227e214a --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json @@ -0,0 +1,299 @@ +{ + "description": "Golden results of plugins.commandInstallers.requirements, plan and defaultDirectory for command-installer.plugin.json. 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": [ + { + "name": "requirements list every systemCommand launch and its installer", + "operation": "requirements", + "payload": {}, + "expected": { + "status": "ok", + "requirements": { + "consumers": [ + { + "kind": "debugAdapter", + "id": "sample", + "commands": [{ "command": "sample-dap", "installer": "sample-dap" }] + }, + { + "kind": "languageServer", + "id": "sample", + "commands": [{ "command": "sample-ls", "installer": "sample-ls" }] + } + ], + "installers": [ + { + "id": "sample-dap", + "commands": ["sample-dap"], + "tool": "builder", + "minimumVersion": null, + "mayUseNetwork": true, + "targets": ["managed"] + }, + { + "id": "sample-ls", + "commands": ["sample-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "mayUseNetwork": true, + "targets": ["managed", "toolDefault"] + } + ] + } + } + }, + { + "name": "a command without an installer is listed with a null installer", + "operation": "requirements", + "payload": {}, + "manifestEdits": [ + { "path": "/debugAdapters/0/launch/process/launch/commands", "value": ["sample-dap", "other-dap"] } + ], + "expected": { + "status": "ok", + "requirements": { + "consumers": [ + { + "kind": "debugAdapter", + "id": "sample", + "commands": [ + { "command": "sample-dap", "installer": "sample-dap" }, + { "command": "other-dap", "installer": null } + ] + }, + { + "kind": "languageServer", + "id": "sample", + "commands": [{ "command": "sample-ls", "installer": "sample-ls" }] + } + ], + "installers": [ + { + "id": "sample-dap", + "commands": ["sample-dap"], + "tool": "builder", + "minimumVersion": null, + "mayUseNetwork": true, + "targets": ["managed"] + }, + { + "id": "sample-ls", + "commands": ["sample-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "mayUseNetwork": true, + "targets": ["managed", "toolDefault"] + } + ] + } + } + }, + { + "name": "a managed plan passes the install directory through the environment", + "operation": "plan", + "payload": { "installerID": "sample-ls", "target": "managed" }, + "platforms": { + "unix": { + "payload": { "installDirectory": "/data/lithe/commands/sample-ls" }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-ls", + "target": "managed", + "commands": ["sample-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "mayUseNetwork": true, + "timeoutMilliseconds": 300000, + "arguments": ["install", "example.org/sample-ls@latest"], + "environment": { "BUILDER_BIN": "/data/lithe/commands/sample-ls" }, + "commandDirectory": "/data/lithe/commands/sample-ls", + "directoryProbes": [] + } + } + }, + "windows": { + "payload": { "installDirectory": "C:\\Lithe\\commands\\sample-ls" }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-ls", + "target": "managed", + "commands": ["sample-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "mayUseNetwork": true, + "timeoutMilliseconds": 300000, + "arguments": ["install", "example.org/sample-ls@latest"], + "environment": { "BUILDER_BIN": "C:\\Lithe\\commands\\sample-ls" }, + "commandDirectory": "C:\\Lithe\\commands\\sample-ls", + "directoryProbes": [] + } + } + } + } + }, + { + "name": "a managed plan replaces the arguments and finds the commands below the directory", + "operation": "plan", + "payload": { "installerID": "sample-dap", "target": "managed" }, + "platforms": { + "unix": { + "payload": { "installDirectory": "/data/lithe/commands/sample-dap" }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-dap", + "target": "managed", + "commands": ["sample-dap"], + "tool": "builder", + "minimumVersion": null, + "mayUseNetwork": true, + "timeoutMilliseconds": 600000, + "arguments": ["install", "--prefix", "/data/lithe/commands/sample-dap", "example.org/sample-dap@latest"], + "environment": {}, + "commandDirectory": "/data/lithe/commands/sample-dap/bin", + "directoryProbes": [] + } + } + }, + "windows": { + "payload": { "installDirectory": "C:\\Lithe\\commands\\sample-dap" }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-dap", + "target": "managed", + "commands": ["sample-dap"], + "tool": "builder", + "minimumVersion": null, + "mayUseNetwork": true, + "timeoutMilliseconds": 600000, + "arguments": ["install", "--prefix", "C:\\Lithe\\commands\\sample-dap", "example.org/sample-dap@latest"], + "environment": {}, + "commandDirectory": "C:\\Lithe\\commands\\sample-dap\\bin", + "directoryProbes": [] + } + } + } + } + }, + { + "name": "a toolDefault plan lists the directory probes", + "operation": "plan", + "payload": { "installerID": "sample-ls", "target": "toolDefault" }, + "expected": { + "status": "ok", + "plan": { + "installer": "sample-ls", + "target": "toolDefault", + "commands": ["sample-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "mayUseNetwork": true, + "timeoutMilliseconds": 300000, + "arguments": ["install", "example.org/sample-ls@latest"], + "environment": {}, + "commandDirectory": null, + "directoryProbes": [ + { "arguments": ["env", "BUILDER_BIN"] }, + { "arguments": ["env", "BUILDER_HOME"] } + ] + } + } + }, + { + "name": "an undeclared installer is refused", + "operation": "plan", + "payload": { "installerID": "missing", "target": "toolDefault" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.unknown", "field": "installerID" } + }, + { + "name": "an undeclared target is refused", + "operation": "plan", + "payload": { "installerID": "sample-dap", "target": "toolDefault" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.targetUndeclared", "field": "target" } + }, + { + "name": "a managed plan without an install directory is refused", + "operation": "plan", + "payload": { "installerID": "sample-ls", "target": "managed" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.directoryInvalid", "field": "installDirectory" } + }, + { + "name": "a relative install directory is refused", + "operation": "plan", + "payload": { "installerID": "sample-ls", "target": "managed", "installDirectory": "commands/sample-ls" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.directoryInvalid", "field": "installDirectory" } + }, + { + "name": "a path of the other platform is not an install directory", + "operation": "plan", + "payload": { "installerID": "sample-ls", "target": "managed" }, + "platforms": { + "unix": { + "payload": { "installDirectory": "C:\\Lithe\\commands\\sample-ls" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.directoryInvalid", "field": "installDirectory" } + }, + "windows": { + "payload": { "installDirectory": "/data/lithe/commands/sample-ls" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.directoryInvalid", "field": "installDirectory" } + } + } + }, + { + "name": "a toolDefault plan takes no install directory", + "operation": "plan", + "payload": { "installerID": "sample-ls", "target": "toolDefault", "installDirectory": "/data/lithe/commands/sample-ls" }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.directoryInvalid", "field": "installDirectory" } + }, + { + "name": "the first probe that prints a directory decides", + "operation": "defaultDirectory", + "payload": { "installerID": "sample-ls" }, + "platforms": { + "unix": { + "payload": { "outputs": ["/home/me/bin\n", "/home/me/go\n"] }, + "expected": { "status": "ok", "directory": "/home/me/bin" } + }, + "windows": { + "payload": { "outputs": ["C:\\Users\\me\\bin\r\n", "C:\\Users\\me\\go\r\n"] }, + "expected": { "status": "ok", "directory": "C:\\Users\\me\\bin" } + } + } + }, + { + "name": "an empty probe falls through to the first entry of a path list", + "operation": "defaultDirectory", + "payload": { "installerID": "sample-ls" }, + "platforms": { + "unix": { + "payload": { "outputs": ["\n", "/home/me/go:/opt/go\n"] }, + "expected": { "status": "ok", "directory": "/home/me/go/bin" } + }, + "windows": { + "payload": { "outputs": ["\r\n", "C:\\Users\\me\\go;D:\\go\r\n"] }, + "expected": { "status": "ok", "directory": "C:\\Users\\me\\go\\bin" } + } + } + }, + { + "name": "no probe naming an absolute directory gives null", + "operation": "defaultDirectory", + "payload": { "installerID": "sample-ls", "outputs": [null, "go\n"] }, + "expected": { "status": "ok", "directory": null } + }, + { + "name": "one output is sent for each probe", + "operation": "defaultDirectory", + "payload": { "installerID": "sample-ls", "outputs": ["/home/me/bin\n"] }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.probeOutputsInvalid", "field": "outputs" } + }, + { + "name": "an installer without toolDefault has no default directory", + "operation": "defaultDirectory", + "payload": { "installerID": "sample-dap", "outputs": [] }, + "expected": { "status": "rejected", "code": "plugin.commandInstaller.targetUndeclared", "field": "installerID" } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/command-installers/command-installer.plugin.json b/shared/plugins/contract/v1/fixtures/command-installers/command-installer.plugin.json new file mode 100644 index 00000000..cf3160fc --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/command-installers/command-installer.plugin.json @@ -0,0 +1,100 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.command-installer", + "displayName": "Command Installer Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { + "commandInstallers": 0, + "debugAdapters": 0, + "languageServers": 0, + "languages": 0 + }, + "requiresTools": ["builder"], + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "commands.install", + "debug.launch", + "languageServer.launch" + ], + "activationEvents": [ + "onDebug:sample", + "onLanguage:sample" + ], + "languages": [ + { + "id": "sample", + "displayName": "Sample", + "fileExtensions": ["sample"] + } + ], + "languageServers": [ + { + "languageID": "sample", + "launch": { "kind": "systemCommand", "commands": ["sample-ls"] }, + "arguments": ["serve"], + "validationArguments": ["version"] + } + ], + "debugAdapters": [ + { + "id": "sample", + "displayName": "Sample Debugger", + "adapterID": "sample-dap", + "requests": ["launch"], + "selectors": [{ "targetKinds": ["file"], "languageIDs": ["sample"] }], + "configurationTypes": ["sample"], + "configurations": { + "launch": { + "targetBindings": { "program": "target.path", "cwd": "target.workingDirectory" } + } + }, + "launch": { + "process": { + "launch": { "kind": "systemCommand", "commands": ["sample-dap"] }, + "arguments": ["--stdio"] + }, + "transport": "stdio" + } + } + ], + "commandInstallers": [ + { + "id": "sample-ls", + "commands": ["sample-ls"], + "tool": "builder", + "minimumVersion": "1.2", + "arguments": ["install", "example.org/sample-ls@latest"], + "mayUseNetwork": true, + "timeoutSeconds": 300, + "targets": { + "managed": { + "environment": { "BUILDER_BIN": "${installDirectory}" } + }, + "toolDefault": { + "directory": [ + { "arguments": ["env", "BUILDER_BIN"] }, + { "arguments": ["env", "BUILDER_HOME"], "pathList": true, "append": "bin" } + ] + } + } + }, + { + "id": "sample-dap", + "commands": ["sample-dap"], + "tool": "builder", + "arguments": ["install", "example.org/sample-dap@latest"], + "mayUseNetwork": true, + "targets": { + "managed": { + "arguments": ["install", "--prefix", "${installDirectory}", "example.org/sample-dap@latest"], + "commandDirectory": "bin" + } + } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index fe63bf13..de08480f 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -903,6 +903,26 @@ {"name": "a tool field is pinned to a known scope", "base": "project-generator-tool-field.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/0/pinAs", "value": "workspace"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "the host chooses a tool field's initial installation", "base": "project-generator-tool-field.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/0/default", "value": "/usr/bin"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "only a tool field has an executable", "base": "project-generator-tool-field.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/steps/1/arguments/2", "value": "${field.venv.executable}"}], "expectedCode": "plugin.manifest.invalid"}, - {"name": "a tool property needs a tool field", "base": "project-generator-tool-field.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/1/tool", "value": "python"}], "expectedCode": "plugin.manifest.invalid"} + {"name": "a tool property needs a tool field", "base": "project-generator-tool-field.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/1/tool", "value": "python"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an installed command is one a systemCommand launch names", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/commands", "value": ["unknown-ls"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].commands[0]"}, + {"name": "an installed command is a bare command name", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/commands", "value": ["bin/sample-ls"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].commands[0]"}, + {"name": "one command has one installer", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/1/commands", "value": ["sample-ls"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[1].commands[0]"}, + {"name": "installer IDs are unique", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/1/id", "value": "sample-ls"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[1].id"}, + {"name": "the installing tool is listed in requiresTools", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/tool", "value": "other"}], "expectedCode": "plugin.runtime.undeclared", "expectedField": "commandInstallers[0].tool"}, + {"name": "an installer minimum version is dotted numbers", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/minimumVersion", "value": "latest"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "installer arguments are literal", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/arguments", "value": ["install", "${installDirectory}"]}], "expectedCode": "plugin.template.invalid", "expectedField": "commandInstallers[0].arguments[1]"}, + {"name": "an installer declares at least one target", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/1/targets", "value": {}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[1].targets"}, + {"name": "a managed target passes the install directory", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed", "value": {"environment": {"BUILDER_BIN": "/opt/builder/bin"}}}], "expectedCode": "plugin.template.invalid", "expectedField": "commandInstallers[0].targets.managed"}, + {"name": "a managed target uses only installDirectory", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed/environment/BUILDER_BIN", "value": "${workspaceFolder}"}], "expectedCode": "plugin.template.invalid", "expectedField": "commandInstallers[0].targets.managed.environment.BUILDER_BIN"}, + {"name": "an installer environment name is uppercase", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/managed/environment", "value": {"builder_bin": "${installDirectory}"}}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.managed.environment.builder_bin"}, + {"name": "the command directory stays inside the install directory", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/1/targets/managed/commandDirectory", "value": "../bin"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[1].targets.managed.commandDirectory"}, + {"name": "toolDefault values are literal", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/toolDefault/environment", "value": {"BUILDER_BIN": "${installDirectory}"}}], "expectedCode": "plugin.template.invalid", "expectedField": "commandInstallers[0].targets.toolDefault.environment.BUILDER_BIN"}, + {"name": "a directory probe passes arguments", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/toolDefault/directory/0/arguments", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.toolDefault.directory[0].arguments"}, + {"name": "an appended probe path stays below the printed directory", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/targets/toolDefault/directory/1/append", "value": "../bin"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].targets.toolDefault.directory[1].append"}, + {"name": "an installation times out within an hour", "base": "command-installer.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/timeoutSeconds", "value": 0}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].timeoutSeconds"}, + {"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"} ] } diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index d894f42a..69c61c79 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -9,6 +9,7 @@ "allOf": [ {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, + {"if": {"required": ["commandInstallers"]}, "then": {"required": ["permissions"], "properties": {"requires": {"required": ["commandInstallers"]}, "permissions": {"contains": {"const": "commands.install"}}}}}, {"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"]}}}}, {"if": {"required": ["keymapImportProviders"]}, "then": {"required": ["backend", "permissions"], "properties": {"requires": {"required": ["keymapImportProviders", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "keymaps.provide"}}, {"contains": {"const": "keymaps.readSelectedSources"}}, {"contains": {"const": "backend.launch"}}]}}}}, @@ -30,6 +31,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.", "enum": [0] }, "buildSystems": { "description": "Declarative build detection, models, and command plans, including the executable setting adapter, instance-scoped options, and declarative preparation roles; does not imply buildProviders support.", "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.", "enum": [0] }, "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] }, @@ -62,7 +64,7 @@ }, "permissions": { "type": "array", - "items": { "enum": ["backend.launch", "credentials.store", "debug.attach", "debug.launch", "languageServer.launch", "process.build", "process.run", "process.test", "process.vcs", "project.generate", "ui.contribute", "ui.web", "workspace.metadata", + "items": { "enum": ["backend.launch", "commands.install", "credentials.store", "debug.attach", "debug.launch", "languageServer.launch", "process.build", "process.run", "process.test", "process.vcs", "project.generate", "ui.contribute", "ui.web", "workspace.metadata", "workspace.files.read", "workspace.files.watch", "workspace.search", @@ -145,6 +147,12 @@ "maxItems": 16, "items": { "$ref": "#/$defs/debugAdapter" } }, + "commandInstallers": { + "description": "requires.commandInstallers: how the host installs bare commands that systemCommand launches of this manifest name. Requires the commands.install permission. Sorted by id when normalized.", + "type": "array", + "maxItems": 16, + "items": { "$ref": "#/$defs/commandInstaller" } + }, "projectGenerators": { "description": "requires.projectGenerators: entries of the New Project window. Requires the project.generate permission.", "type": "array", @@ -925,6 +933,87 @@ } } }, + "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.", + "type": "object", + "additionalProperties": false, + "required": ["id", "commands", "tool", "arguments", "mayUseNetwork", "targets"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9-]+$", "maxLength": 64 }, + "commands": { + "description": "Bare commands the installation provides. Each is named by a systemCommand launch of this manifest and by no other installer.", + "type": "array", + "minItems": 1, + "maxItems": 8, + "uniqueItems": true, + "items": { "type": "string", "pattern": "^[^/\\\\\\s]+$" } + }, + "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" }, + "timeoutSeconds": { "type": "integer", "minimum": 1, "maximum": 3600, "default": 600 }, + "targets": { + "description": "Where the commands may land; the user chooses one when installing.", + "type": "object", + "additionalProperties": false, + "minProperties": 1, + "properties": { + "managed": { + "description": "A directory the host owns for the plugin and removes with it. arguments or environment must use ${installDirectory}, the only template variable.", + "type": "object", + "additionalProperties": false, + "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" } + } + }, + "toolDefault": { + "description": "Wherever the tool installs when told nothing. Literal values.", + "type": "object", + "additionalProperties": false, + "properties": { + "arguments": { "description": "Replaces the installer's arguments.", "$ref": "#/$defs/commandInstallerArguments" }, + "environment": { "$ref": "#/$defs/commandInstallerEnvironment" }, + "directory": { + "description": "Probes, tried in order, whose standard output names the directory the commands land in.", + "type": "array", + "maxItems": 4, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["arguments"], + "properties": { + "arguments": { "allOf": [{ "$ref": "#/$defs/commandInstallerArguments" }, { "minItems": 1 }] }, + "pathList": { "description": "The output is a list in the host's path separator; its first non-empty entry counts.", "type": "boolean" }, + "append": { "description": "Package-style relative path appended to the printed directory.", "$ref": "#/$defs/commandInstallerRelativePath" } + } + } + } + } + } + } + } + } + }, + "commandInstallerArguments": { + "type": "array", + "maxItems": 64, + "items": { "type": "string", "maxLength": 4096 } + }, + "commandInstallerEnvironment": { + "description": "Variables set for the installation over the tool's environment.", + "type": "object", + "maxProperties": 16, + "propertyNames": { "pattern": "^[A-Z_][A-Z0-9_]{0,63}$" }, + "additionalProperties": { "type": "string", "maxLength": 4096 } + }, + "commandInstallerRelativePath": { + "type": "string", + "minLength": 1, + "pattern": "^(?!/)(?!.*(?:^|/)[.]{2}(?:/|$))[^\\\\\\u0000]+$" + }, "outputLinkMatcher": { "type": "object", "additionalProperties": false, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index a5708063..1651eb3a 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`) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `toolchainProviders` | [工具链](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`) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `toolchainProviders` 和 `commandInstallers` | [工具链](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` 的包内 Monarch 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration);[编辑器语言功能 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) | @@ -218,7 +218,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`) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `toolchainProviders` | [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`) | 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-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 Monarch grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration); [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 754c0829..9c185431 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -51,6 +51,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `buildModelInputs` `0` | `buildSystems[].modelSharing` 与 `modelInputs`:[已启用工作区插件之间共享的只读模型输入](../contract/v1/README.md#optional-read-only-model-inputs)(可选) | ✅ | 未声明 | [构建提供者](domains/build-providers.md) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers);说 `litheVcs` | ✅ | 未声明 | [版本控制提供者](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters):独立适配器、语言服务器内的适配器、[远程附加](../contract/v1/README.md#remote-attach)、参数和环境变量、[`features` 与 `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [调试适配器](domains/debug-adapters.md) | +| `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动缺的裸命令,装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | 未声明 | [工具链](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) | @@ -154,6 +155,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `buildModelInputs` `0` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](../contract/v1/README.md#optional-read-only-model-inputs) shared between enabled workspace plugins | ✅ | Not declared | [Build providers](domains/build-providers.md) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | Not declared | [VCS providers](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters): standalone adapters, adapters inside a language server, [remote attach](../contract/v1/README.md#remote-attach), arguments and environment, [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [Debug adapters](domains/debug-adapters.md) | +| `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 | ✅ | Not declared | [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 2a83a02e..ba426559 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -108,6 +108,20 @@ `toolchains.instantiateLaunch` 的 `executable` 必填;`home` 是解析出的工具主目录,`entry` 是绝对文件路径,`runtimeArguments` 和 `arguments` 是字符串列表。文本最多 4096 字节,列表最多 1024 项、每项最多 64 KiB,都不含 NUL。模板里的 `${executable}`、`${home}`、`${entry}`、`${runtimeArguments}`、`${arguments}` 被对应的值替换,列表原位展开;其他占位符原样保留。调用方给了模板带不动的值(给不启动入口的工具一个 `entry`,或给不接受参数的工具参数),或漏了模板需要的 `${home}`、`${entry}`,是 `plugin.toolchain.launchMismatch`;未知或已停用的 `tool` 是 `plugin.toolchain.invalidParams`,`field` 为 `tool`。这个命令不做任何本机 I/O:选可执行文件、探测版本、启动进程都由宿主完成。 +### 安装缺失的命令 + +`systemCommand` 启动只写裸命令名(如 `dlv`、`gopls`),机器上没有时启动失败。清单顶层 `commandInstallers[]` 告诉宿主怎样用插件已经依赖的工具(`requiresTools` 里的工具定义)安装它,用户在插件管理里点安装即可,不用开终端。需要能力 `commandInstallers` 0 和权限 `commands.install`。 + +| 项目 | 规则 | +| --- | --- | +| 声明 | `id`、`commands`(1–8 个本清单 `systemCommand` 启动用到的裸命令,一个命令只归一个安装)、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)、`targets` | +| `managed` 目标 | 装进宿主为插件管理的目录(应用数据目录,不在应用包、安装目录或插件包里,卸载插件时删除)。`arguments`(替换安装的参数)或 `environment` 必须用唯一的模板变量 `${installDirectory}`;`commandDirectory` 是命令所在的子目录 | +| `toolDefault` 目标 | 装到工具默认位置,值都是字面量。`directory` 最多 4 个探针,按顺序用同一工具运行,第一个输出绝对目录的探针决定位置;`pathList` 取路径列表第一项,`append` 拼接子目录 | +| 宿主做什么 | `plugins.commandInstallers.requirements` 列出每个启动缺哪些命令、由哪个安装提供;`toolDefault` 先运行探针,把输出交给 `defaultDirectory`;向用户展示工具、完整命令行、是否联网和每个目标的目录,用户选定后用 `plan` 展开并运行,显示输出、可取消、超时停止,结束后确认命令确实在目录里 | +| 之后的启动 | 宿主查找这个插件的 `systemCommand` 时,除 `PATH` 外还查插件的受管命令目录和记录下来的默认目录 | +| 不覆盖 | 构建系统和执行提供者通过 `invocation.executables` 解析的可执行文件 | +| 安装审查 | 每个安装都是审查里的程序(`kind: "commandInstaller"`),改了要运行的内容需要重新批准 | + ### 本机文档 `.lithe/toolchains/local.json` 的 `version` 仍为 `1`,这是 Core 当前校验的格式。`toolchains.resolvePins` 校验 `{version: 1, toolchains, pins?}`,`pins` 按目录记录 `{home, version, provider}`。这个文档只读取,不授予执行权限,也不写文件;保存固定尚未实现。 @@ -118,6 +132,7 @@ | --- | --- | | 工具定义(`toolDefinitions`) | 已声明。设置页的发现结果,以及构建和运行选择工具,都通过共享 Core 解析器完成 | | 工具链提供者(`toolchainProviders`) | 未声明。提供者查询路线不可用,需要它的插件不会被提供安装 | +| 安装缺失的命令(`commandInstallers`) | 未声明 | | 语言服务器的 `{kind: "tool"}` 启动应答 | 启动时被拒绝,因为工具还没有经过工具链注册表解析(见[语言](languages.md)) | | 保存固定(pin)、`toolchainConsumers`、通用运行时启动、提供者热激活 | 契约尚未提供 | @@ -139,6 +154,7 @@ | [Pins and snapshot resolution](../../contract/v1/toolchains/README.md#pins-and-snapshot-resolution) | `local.json`、`resolve`、四层选择、`checkVersion`、`discoveryPlan` | | [Settings candidates](../../contract/v1/toolchains/README.md#settings-candidates) | `candidates` 和两次调用的探测流程 | | [Executable resolution](../../contract/v1/README.md#executable-resolution) | 可执行文件候选的排序和严格选择 | +| [Command installers](../../contract/v1/README.md#command-installers) | `commandInstallers[]` 的字段、两个目标、三个 Core 命令和宿主步骤 | | [Provider backend negotiation](../../contract/v1/toolchains/README.md#provider-backend-negotiation) | `litheToolchains` 协商、`lsp.toolchainRequest`、超时 | ### 示例与用例 @@ -148,6 +164,7 @@ | [`toolchains/tool-definition.plugin.json`](../../contract/v1/fixtures/toolchains/tool-definition.plugin.json) | 生产形态的工具定义(`java`):项目和全局设置、工具链请求、`JAVA_HOME`、`java` 命令等候选,以及 macOS 的 `JavaVirtualMachines` 目录发现 | | [`toolchains/toolchain-provider.plugin.json`](../../contract/v1/fixtures/toolchains/toolchain-provider.plugin.json) | 生产形态的版本管理器提供者(`mise`):覆盖多个工具,监视项目版本文件(`.tool-versions` 用兼容读取器),后端是包内可执行文件 | | [`run/tool-reference-launch.plugin.json`](../../contract/v1/fixtures/run/tool-reference-launch.plugin.json) | 清单顶层 `requiresTools` 列出插件自己定义的 `interpreter`,语言服务器的 `runtime` 启动按这个工具定义 ID 引用运行时 | +| [`command-installers/command-installer.plugin.json`](../../contract/v1/fixtures/command-installers/command-installer.plugin.json)、[`command-installer-plans.json`](../../contract/v1/fixtures/command-installers/command-installer-plans.json) | 语言服务器和调试适配器缺的命令各有一个安装:一个两种目标都有、用环境变量传目录,一个只有 `managed`、替换参数并指定命令子目录;以及三个命令在 Unix 和 Windows 上的期望结果 | Core 的验收测试在主仓库的 [`toolchain_definitions.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/core/src/tests/toolchain_definitions.rs) 和同目录的 `toolchain_pins.rs`、`toolchain_queries.rs`、`toolchain_resolution.rs`。这三个测试共用的固定值文档、查询往返和每个稳定失败码的错误回复内联在 [`toolchain_vectors.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/core/src/tests/toolchain_vectors.rs) 里。 @@ -264,6 +281,20 @@ When a plugin starts a process by tool-definition ID (a launch plan with `launch `toolchains.instantiateLaunch` requires `executable`. `home` is the resolved tool home, `entry` an absolute file path, and `runtimeArguments` and `arguments` string lists. A text is at most 4096 bytes; a list has at most 1024 items of 64 KiB each; none may hold a NUL. `${executable}`, `${home}`, `${entry}`, `${runtimeArguments}`, and `${arguments}` are replaced by their values, lists expanding in place; other tokens are kept as written. A value the template cannot carry (an `entry` for a tool that launches none, or arguments for one that takes none), or a missing `${home}` or `${entry}`, is `plugin.toolchain.launchMismatch`. An unknown or disabled `tool` is `plugin.toolchain.invalidParams` with `field` `tool`. The command performs no native I/O: selecting the executable, probing its version, and starting the process are the host's work. +### 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. + +| 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` | +| `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 | +| 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 | + ### Local document `.lithe/toolchains/local.json` keeps `version` `1`, which is the format Core validates today. `toolchains.resolvePins` validates `{version: 1, toolchains, pins?}`, where `pins` maps directory keys to `{home, version, provider}`. The document is read, not written; it grants no execution authority; saving pins is not implemented. @@ -274,6 +305,7 @@ When a plugin starts a process by tool-definition ID (a launch plan with `launch | --- | --- | | Tool definitions (`toolDefinitions`) | Declared. Settings discovery results, and Build and Run tool selection, 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`) | Not declared | | Language server `{kind: "tool"}` launch answer | Refused at start, because the tool is not yet resolved through the toolchain registry (see [Languages](languages.md)) | | Saving pins, `toolchainConsumers`, generic runtime launches, live provider activation | Not provided by the contract yet | @@ -295,6 +327,7 @@ When a plugin starts a process by tool-definition ID (a launch plan with `launch | [Pins and snapshot resolution](../../contract/v1/toolchains/README.md#pins-and-snapshot-resolution) | `local.json`, `resolve`, the four layers, `checkVersion`, `discoveryPlan` | | [Settings candidates](../../contract/v1/toolchains/README.md#settings-candidates) | `candidates` and its two-call probe flow | | [Executable resolution](../../contract/v1/README.md#executable-resolution) | Ordering and strict selection of executable candidates | +| [Command installers](../../contract/v1/README.md#command-installers) | The fields of `commandInstallers[]`, the two targets, the three Core commands and the host steps | | [Provider backend negotiation](../../contract/v1/toolchains/README.md#provider-backend-negotiation) | `litheToolchains` negotiation, `lsp.toolchainRequest`, timeouts | ### Examples and cases @@ -304,6 +337,7 @@ When a plugin starts a process by tool-definition ID (a launch plan with `launch | [`toolchains/tool-definition.plugin.json`](../../contract/v1/fixtures/toolchains/tool-definition.plugin.json) | A production-shaped tool definition (`java`): candidates from project and global settings, toolchain requests, `JAVA_HOME`, the `java` command, and discovery of `*.jdk` under macOS's `JavaVirtualMachines` directory | | [`toolchains/toolchain-provider.plugin.json`](../../contract/v1/fixtures/toolchains/toolchain-provider.plugin.json) | A production-shaped version-manager provider (`mise`): several tools, watched project version files (`.tool-versions` through the compatible reader), with a packaged backend | | [`run/tool-reference-launch.plugin.json`](../../contract/v1/fixtures/run/tool-reference-launch.plugin.json) | `requiresTools` lists the plugin's own `interpreter` definition, and a language server's `runtime` launch references the runtime by that tool-definition ID | +| [`command-installers/command-installer.plugin.json`](../../contract/v1/fixtures/command-installers/command-installer.plugin.json), [`command-installer-plans.json`](../../contract/v1/fixtures/command-installers/command-installer-plans.json) | One installer each for the commands of a language server and a debug adapter: one with both targets that passes the directory through the environment, one with only `managed` that replaces the arguments and names a command subdirectory; and the expected results of the three commands on Unix and Windows | The Core acceptance tests are in [`toolchain_definitions.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/core/src/tests/toolchain_definitions.rs), with `toolchain_pins.rs`, `toolchain_queries.rs`, and `toolchain_resolution.rs` beside it. The fixture documents, query round trips, and the error reply for each stable failure code shared by these tests are inlined in [`toolchain_vectors.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/core/src/tests/toolchain_vectors.rs). diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 2f2f79d1..26a5af5e 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -38,6 +38,7 @@ | `buildModelInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildSystems` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `commandInstallers` | 0 | 2026-11-15 | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | | `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) | @@ -133,6 +134,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | **`commandInstallers` 0** | 新能力 `commandInstallers` 和权限 `commands.install`:清单顶层 `commandInstallers[]` 声明怎样用插件已依赖的工具(`requiresTools`)安装 `systemCommand` 启动缺的裸命令,例如用 `go install` 装 `dlv`。每个安装声明 `commands`、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)和至少一个目标:`managed` 装进宿主为插件管理的目录,参数或环境变量必须用唯一的模板变量 `${installDirectory}`,`commandDirectory` 指命令所在的子目录;`toolDefault` 装到工具默认位置,`directory` 最多 4 个探针,按顺序运行同一工具,从输出读目录(`pathList`、`append`)。新增宿主命令 `plugins.commandInstallers.requirements`、`plan`、`defaultDirectory` 和错误码 `plugin.commandInstaller.unknown`、`targetUndeclared`、`directoryInvalid`、`probeOutputsInvalid`(Core),以及宿主报告的 `plugin.command.missing`、`plugin.commandInstaller.failed`、`timedOut`、`commandsMissing`。安装声明进入安装审查(`kind: "commandInstaller"`)。宿主只在用户确认命令行、网络和目标后安装。 | | [#52](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/52) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | `toolDefinitions` 0 内的补充 | 工具定义的版本探针 `version.arguments` 第一个参数可以是子命令(如 Go 的 `go version` 写 `["version"]`),之后的参数仍然只能是选项,第一个之后出现裸词以 `plugin.manifest.invalid`(字段 `version.arguments`)拒绝;清单 schema 改用 `prefixItems` 并补上 `uniqueItems`。不需要新能力版本。 | | [#47](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/47) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.program` 新增来源 `target.directory`:`target.path` 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。新增宿主命令 `debug.adapters.readAnnouncement`,宿主把 `tcpAnnounced` 适配器的输出逐行交给它,第一行含 `prefix` 的输出是公告,前缀之后是 `port`(连 `127.0.0.1`)或带回环主机的 `host:port`,返回 `none`、`announced` 或 `invalid`(`malformed`、`notLoopback`);契约写明宿主怎样读公告、10 秒内没有公告就启动失败。清单格式只多了一个枚举值,不需要新能力版本。 | From dab270dc3d80e726d2433e3438664a3fef6fd869 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 15:33:09 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(diagnostics):=20=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E8=AE=B0=E4=B8=BA=E5=A3=B0=E6=98=8E=E5=BC=8F?= =?UTF-8?q?=E8=B4=A1=E7=8C=AE=20commandInstaller/install?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 宿主每次执行用户确认的安装,用 diagnostics.recordPluginOperation 记一条 commandInstaller/install(命令执行生命周期):计划、找工具、启动、超时、 非零退出各有阶段,正常退出但命令不在目录里记 decode。用户取消不记录。 CONTRIBUTIONS 加一行,契约 README、rust-core-api.md、日志 README 的贡献表 和协议更新记录同步更新;不新增事件、通道或错误码。 --- rust/contracts/rust-core-api.md | 1 + rust/crates/diagnostics/src/plugin_operations.rs | 10 ++++++++++ rust/logging/README.md | 3 ++- shared/plugins/contract/v1/README.md | 10 ++++++---- shared/plugins/reference/protocol-changelog.md | 2 +- 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 583483e4..3ebaf885 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -6026,6 +6026,7 @@ a code has one meaning across every contribution with that lifecycle: | `debugAdapter/start` | `debugAdapters[]` | process start | | `lithe/build/model` | `buildSystems[].model` command source | command run | | `lithe/build/dependencies` | `buildSystems[].dependencies` command source | command run | +| `commandInstaller/install` | `commandInstallers[]` installation the user confirmed; `decode` when a provided command is missing after a successful exit | command run | | `stage` | Process start | Command run | | --- | --- | --- | diff --git a/rust/crates/diagnostics/src/plugin_operations.rs b/rust/crates/diagnostics/src/plugin_operations.rs index 9d1dc21b..972aafb6 100644 --- a/rust/crates/diagnostics/src/plugin_operations.rs +++ b/rust/crates/diagnostics/src/plugin_operations.rs @@ -111,6 +111,14 @@ pub static BUILD_DEPENDENCIES: Contribution = Contribution { lifecycle: Lifecycle::CommandRun, }; +/// `commandInstallers[]`: one installation the user confirmed, from planning the +/// chosen target to finding every provided command in its directory. A command +/// still missing after a successful exit is the `decode` stage. +pub static COMMAND_INSTALLER_INSTALL: Contribution = Contribution { + operation: "commandInstaller/install", + lifecycle: Lifecycle::CommandRun, +}; + /// Every contribution kind this ingress accepts. Supporting a new declarative /// contract means adding its row here and reporting the same token from its owner. pub static CONTRIBUTIONS: &[&Contribution] = &[ @@ -118,6 +126,7 @@ pub static CONTRIBUTIONS: &[&Contribution] = &[ &DEBUG_ADAPTER_START, &BUILD_MODEL, &BUILD_DEPENDENCIES, + &COMMAND_INSTALLER_INSTALL, ]; impl Contribution { @@ -430,6 +439,7 @@ mod tests { ("debugAdapter/start", Lifecycle::ProcessStart), ("lithe/build/model", Lifecycle::CommandRun), ("lithe/build/dependencies", Lifecycle::CommandRun), + ("commandInstaller/install", Lifecycle::CommandRun), ]; let rows: Vec<_> = CONTRIBUTIONS .iter() diff --git a/rust/logging/README.md b/rust/logging/README.md index 2ab291fb..63189d5f 100644 --- a/rust/logging/README.md +++ b/rust/logging/README.md @@ -92,7 +92,7 @@ - Core 的 stderr 读取器(`rust/crates/lsp-engine/src/logging.rs`)限制每行 4 KiB、每秒 200 行,之后再走 `text` 的 1 KiB 脱敏规范化。与 v1 相比唯一的兼容变化是从任意 trim 的读取块改为逐行文本:保留行内空格,移除 LF 和末尾 CR,并应用已声明的长度上限和限流。 - 上游明确给出的严重度通过独立的目录事件保留:`window/logMessage` 和 `window/showMessage` 的 type 1/2/3/4 分别为 ERROR/WARN/INFO/DEBUG,未知类型为 DEBUG。未分类的 stderr 是 DEBUG 排障证据,流名称不表示警告;实际的进程或协议失败由 `*.session.failed` 记录 ERROR,正常关闭仍是生命周期状态。 - 插件自身使用独立协商的 `litheLogging` 0 和 `lithe/log`,由 Core 把四种受控事实映射到插件目录事件,不能再用 stderr 或任意自由消息代替。协议字段、op、限额和 fixture 以 [插件契约](../../shared/plugins/contract/v1/README.md#structured-plugin-diagnostics) 为准。 -- 声明式贡献没有插件进程,不能发 `lithe/log`。实际执行它的一方通过 `diagnostics.recordPluginOperation` 代记每次尝试的一条终态,事件和通道与 SDK 插件相同:`plugins.operation.finished` 或 `plugins.operation.failed`,写入 `plugins/{plugin}/host`。平台层只上报观察到的阶段和耗时,级别和 `host.*` 失败类别只由 Core 按阶段决定;取消、停止和过期结果不记录。宿主当前代记下表四种贡献,唯一来源是 `rust/crates/diagnostics/src/plugin_operations.rs` 的 `CONTRIBUTIONS`;输入、阶段到类别的对应和 -32064 见 [Rust Core API](../contracts/rust-core-api.md#engine-logging-v2-handoff-pr3)。 +- 声明式贡献没有插件进程,不能发 `lithe/log`。实际执行它的一方通过 `diagnostics.recordPluginOperation` 代记每次尝试的一条终态,事件和通道与 SDK 插件相同:`plugins.operation.finished` 或 `plugins.operation.failed`,写入 `plugins/{plugin}/host`。平台层只上报观察到的阶段和耗时,级别和 `host.*` 失败类别只由 Core 按阶段决定;取消、停止和过期结果不记录。宿主当前代记下表五种贡献,唯一来源是 `rust/crates/diagnostics/src/plugin_operations.rs` 的 `CONTRIBUTIONS`;输入、阶段到类别的对应和 -32064 见 [Rust Core API](../contracts/rust-core-api.md#engine-logging-v2-handoff-pr3)。 | operation | 声明来源 | 记录方 | 可能的失败阶段 | | --- | --- | --- | --- | @@ -100,6 +100,7 @@ | `debugAdapter/start` | `debugAdapters[]` | 桌面宿主;op 为调试会话 ID,用户停止和 Core 拒绝建会话不记录 | resolve、launch、exit、initialize、timeout | | `lithe/build/model` | `buildSystems[]` 的命令式模型 | 桌面宿主,op 为加载模型的操作;计划由插件后端提供时由 SDK 记录 | plan、resolve、launch、timeout、exit、decode | | `lithe/build/dependencies` | `buildSystems[]` 的命令式依赖树 | 桌面宿主,op 为加载依赖的操作;计划由插件后端提供时由 SDK 记录 | plan、resolve、launch、timeout、exit、decode | + | `commandInstaller/install` | `commandInstallers[]` | 桌面宿主,每次用户确认的安装记一条,op 为这次安装;用户取消不记录;安装正常退出但命令不在目录里记 decode | plan、resolve、launch、timeout、exit、decode | 新增一种声明式贡献时,在同一次改动里给 `CONTRIBUTIONS` 加一行,在执行方开始和结束一次 attempt,并更新本表;不新增事件、通道或错误码。Core 拒绝或无法入队一条代记结果时,桌面宿主记 `app.background.operation_failed`(`operation` 为 `plugin_operation_record`),不重试。 - 上游 trace 默认关闭。宿主通过 `lsp.setDetailedDiagnostics` 对活动会话和新会话显式开启,15 分钟后单次到期关闭。桌面端由写入器的详细诊断开关驱动:开关变化时通知插件后端的 runner,runner 把当前值发给它启动的每个活动会话,之后启动的会话也会收到;同一次选择只记录一次拒绝(`app.logging.diagnostics_failed`)。详细诊断类别与通道根的对应为 `lsp` → language、`vcs` → git、`plugins` → plugins。 diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 1d0c85e2..56069903 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -483,8 +483,10 @@ declarative plugin writes no logging code. Each start of a `languageServers[]` o `debugAdapters[]` entry is one `languageServer/start` or `debugAdapter/start` operation, from launch resolution until `initialize` succeeds. Each run of a `buildSystems[]` model or dependencies command source is one `lithe/build/model` or -`lithe/build/dependencies` operation, using the SDK request names. A failure -carries one `code`: +`lithe/build/dependencies` operation, using the SDK request names. Each +installation of a [command installer](#command-installers) the user confirmed is +one `commandInstaller/install` operation, from planning the chosen target until +every provided command is in its directory. A failure carries one `code`: | Code | Meaning | | --- | --- | @@ -494,8 +496,8 @@ carries one `code`: | `host.initializeFailed` | A started server or adapter failed its `initialize` handshake | | `host.timedOut` | The attempt exceeded its deadline | | `host.exitedEarly` | A server or adapter exited before `initialize` succeeded | -| `host.commandFailed` | A build command exited unsuccessfully | -| `host.outputInvalid` | A build command's output is not a valid document | +| `host.commandFailed` | A build command or an installation exited unsuccessfully | +| `host.outputInvalid` | A build command's output is not a valid document, or an installation that exited successfully did not provide its commands | User cancellation and superseded attempts record nothing. Plugin output, paths, and error text never appear in these facts. The executing owner and the diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 26a5af5e..04971b4f 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -134,7 +134,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | -| [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | **`commandInstallers` 0** | 新能力 `commandInstallers` 和权限 `commands.install`:清单顶层 `commandInstallers[]` 声明怎样用插件已依赖的工具(`requiresTools`)安装 `systemCommand` 启动缺的裸命令,例如用 `go install` 装 `dlv`。每个安装声明 `commands`、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)和至少一个目标:`managed` 装进宿主为插件管理的目录,参数或环境变量必须用唯一的模板变量 `${installDirectory}`,`commandDirectory` 指命令所在的子目录;`toolDefault` 装到工具默认位置,`directory` 最多 4 个探针,按顺序运行同一工具,从输出读目录(`pathList`、`append`)。新增宿主命令 `plugins.commandInstallers.requirements`、`plan`、`defaultDirectory` 和错误码 `plugin.commandInstaller.unknown`、`targetUndeclared`、`directoryInvalid`、`probeOutputsInvalid`(Core),以及宿主报告的 `plugin.command.missing`、`plugin.commandInstaller.failed`、`timedOut`、`commandsMissing`。安装声明进入安装审查(`kind: "commandInstaller"`)。宿主只在用户确认命令行、网络和目标后安装。 | +| [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | **`commandInstallers` 0** | 新能力 `commandInstallers` 和权限 `commands.install`:清单顶层 `commandInstallers[]` 声明怎样用插件已依赖的工具(`requiresTools`)安装 `systemCommand` 启动缺的裸命令,例如用 `go install` 装 `dlv`。每个安装声明 `commands`、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)和至少一个目标:`managed` 装进宿主为插件管理的目录,参数或环境变量必须用唯一的模板变量 `${installDirectory}`,`commandDirectory` 指命令所在的子目录;`toolDefault` 装到工具默认位置,`directory` 最多 4 个探针,按顺序运行同一工具,从输出读目录(`pathList`、`append`)。新增宿主命令 `plugins.commandInstallers.requirements`、`plan`、`defaultDirectory` 和错误码 `plugin.commandInstaller.unknown`、`targetUndeclared`、`directoryInvalid`、`probeOutputsInvalid`(Core),以及宿主报告的 `plugin.command.missing`、`plugin.commandInstaller.failed`、`timedOut`、`commandsMissing`。安装声明进入安装审查(`kind: "commandInstaller"`)。宿主只在用户确认命令行、网络和目标后安装,每次安装用 `diagnostics.recordPluginOperation` 记一条 `commandInstaller/install`(命令执行生命周期,安装后命令仍缺记 `decode`)。 | | [#52](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/52) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | `toolDefinitions` 0 内的补充 | 工具定义的版本探针 `version.arguments` 第一个参数可以是子命令(如 Go 的 `go version` 写 `["version"]`),之后的参数仍然只能是选项,第一个之后出现裸词以 `plugin.manifest.invalid`(字段 `version.arguments`)拒绝;清单 schema 改用 `prefixItems` 并补上 `uniqueItems`。不需要新能力版本。 | | [#47](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/47) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.program` 新增来源 `target.directory`:`target.path` 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。新增宿主命令 `debug.adapters.readAnnouncement`,宿主把 `tcpAnnounced` 适配器的输出逐行交给它,第一行含 `prefix` 的输出是公告,前缀之后是 `port`(连 `127.0.0.1`)或带回环主机的 `host:port`,返回 `none`、`announced` 或 `invalid`(`malformed`、`notLoopback`);契约写明宿主怎样读公告、10 秒内没有公告就启动失败。清单格式只多了一个枚举值,不需要新能力版本。 |