diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 67ed5cdf..19ac0e3e 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1310,6 +1310,8 @@ dependencies = [ "lithe-vcs", "serde", "serde_json", + "sha2", + "url", ] [[package]] diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 4c698c41..ba07bf9a 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -69,7 +69,7 @@ this lifecycle protection; actual symbol computation remains upstream-owned. | GitHub | remote parsing, trusted request plans, normalized branch comparisons and pull requests/reviews/comments, deterministic ordering, and stable errors | OAuth configuration, HTTPS, browser opening, and operating-system credential storage | | [AI commit messages](ai-commit.md) | provider configuration parsing, commit rules, bounded diff evidence, request plans, and response text | local configuration discovery, credentials, HTTP, cancellation, and draft UI | | [IDE capability API / MCP](ide-api/v1.md) | canonical tool schemas, narrowing host selection, permission/argument validation, stable execution IDs, bounded output cursors and errors | implemented workflow inventory, explicit project authorization, live environment/Build/Run application actions, helper discovery and writable connection storage | -| Runtime | tool requirements, normalized candidates, and effective toolchain references | tool probing and executable paths | +| Runtime | tool requirements, normalized candidates, effective toolchain references, pinned managed-runtime plans and bounded resolver answers | tool probing, executable paths, approved HTTPS downloads, safe archive extraction, native integrity, interprocess cache locks and atomic set publication | | Language tooling | provider catalog, local fallback results, complete LSP process/session runtime, capabilities, diagnostics, UTF-16 edits, and normalized feature results | executable/environment discovery and UI provider routing | | Run/Debug | versioned configuration documents, three-layer resolution, diagnostics, platform-neutral launch plans, DAP framing/state, reverse terminal requests, breakpoint relocation, stepping filters, threads, stacks, variables, and events | project and preference persistence, native edit reporting, adapter discovery, PTY/ConPTY debuggee launch, child processes, sockets, native termination, and UI | | Terminal | input bytes, output bytes, lifecycle; [shell selection semantics](terminal-profiles.md) | PTY/ConPTY, shell discovery, native profile preferences, and environment | diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2aca1f14..493a6136 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -462,6 +462,8 @@ or removing a command fails until the table changes in the same commit. | `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.managedRuntimes.plan` | Validate pinned dependencies and select exact platform artifacts with plugin-version-independent cache identities | +| `plugins.managedRuntimes.decodeResolution` | Validate a plugin resolver's complete partition of qualified native homes and missing dependency IDs | | `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 | @@ -3124,6 +3126,9 @@ optional `pluginId` of the plugin that owns the process, its optional `workspaceConfiguration` (an object, plugin-owned sessions only), its optional `hostServices` (the launch plan's `backend.hostServices`; plugin-owned sessions only; legacy service grants or full public host-method names Core defines), +optional `functionRelayEnabled` (defaults to `true`; `false` keeps direct +host-to-session function calls but excludes the session from incoming and outgoing +cross-plugin routing, including the corresponding host service grants), its optional `hostOptions` (plugin-owned sessions only; `editor:{actionIcons, actionSourceBytes, providerTypes}` declares the icons, collector source bound and provider types the host implements, reported through `lithe/host/getCapabilities` @@ -4631,7 +4636,8 @@ function, timeoutMilliseconds }` (30000 when absent) and `resolveParams` is the params the host sends to that backend function, `{ serverID, platform: { os, arch }, stateDirectory, workspaceStateDirectory, logDirectory, temporaryDirectory, settings }`; the host adds `context` and, when the plugin -declares tool definitions, `tools`. The request must carry all four of +declares tool definitions, `tools`, and after managed-runtime preparation the +optional read-only `runtimes: {:{home,version}}` map. The request must carry all four of `stateDirectory`, `workspaceStateDirectory`, `logDirectory`, and `temporaryDirectory`, and the plan lists them in `requiredDirectories`. Every language-server plan carries a `sessionPolicy` (`serverID`, `requestMethods`, `commands`, `serializedCommands`, @@ -4689,6 +4695,33 @@ runs on. Refusals are `plugin.commandInstaller.unknown`, `plugin.commandInstaller.probeOutputsInvalid`; the golden cases are `shared/plugins/contract/v1/fixtures/command-installers/command-installer-plans.json`. +The `plugins.managedRuntimes.*` commands implement +[Managed runtimes](../../shared/plugins/contract/v1/README.md#managed-runtimes). +`plan` accepts `{manifest, platform:{os,arch}}` and returns +`{status:"ok", plan:{resolve, dependencies:[{id,version,tool?,os,arch,url, +sha256,archive,stripPrefix,home,executable,cacheKey}]}}`. The resolver is +`{function,timeoutMilliseconds}`. No declaration produces an empty dependencies +array without a resolver. Targets are exact (`macos|windows|linux`, +`arm64|x86_64`); `cacheKey` is an opaque lowercase SHA-256 of the normalized +selected dependency identity, excluding plugin version. A host uses it as given. +`decodeResolution` accepts `{manifest, platform:{os,arch}, result}` and returns +`{status:"ok", resolution:{runtimes:[{id,home,version}],missing:[id]}}` with +both arrays sorted by ID. The arrays must partition every declared ID exactly +once; homes are bounded absolute paths for the supplied OS. Neither command +performs I/O or decides tool-specific compatibility. Refusals are +`plugin.managedRuntime.unavailable` for unsupported targets or absent artifacts, +`plugin.managedRuntime.invalidResolution` for hook output, and standard +manifest errors for declarations. The inert shared fixture is +`rust/fixtures/plugins/managed-runtimes.json`. + +Hosts run the approved packaged resolver before install/update publication and +again for missing-state repair. Hooks qualify external and staged homes; native +adapters own downloads, hashing, safe extraction, process locks, integrity and +atomic publication. A backend-resolved server launch may receive the host-added +read-only `runtimes: {:{home,version}}` map, and a declared tool binding is +selected only for that plugin's server session. This does not change project +toolchains or add an arbitrary absolute executable kind. + `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/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index deb6ace3..b70eb2cd 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -244,6 +244,10 @@ pub enum PluginsCommand { CommandInstallersPlan, /// Reads where a `toolDefault` installation puts its commands (`plugins.commandInstallers.defaultDirectory`). CommandInstallersDefaultDirectory, + /// Selects pinned runtime artifacts for one target (`plugins.managedRuntimes.plan`). + ManagedRuntimesPlan, + /// Validates the plugin resolver's complete runtime partition (`plugins.managedRuntimes.decodeResolution`). + ManagedRuntimesDecodeResolution, /// Checks a plugin content provider's answer (`plugins.contentProviders.decode`). ContentProvidersDecode, /// Merges a plugin's stored setting layers into effective values (`plugins.declarative.resolveSettings`). @@ -1065,6 +1069,12 @@ impl CoreCommand { "plugins.commandInstallers.defaultDirectory" => Some(Self::Plugins( PluginsCommand::CommandInstallersDefaultDirectory, )), + "plugins.managedRuntimes.plan" => { + Some(Self::Plugins(PluginsCommand::ManagedRuntimesPlan)) + } + "plugins.managedRuntimes.decodeResolution" => Some(Self::Plugins( + PluginsCommand::ManagedRuntimesDecodeResolution, + )), "plugins.contentProviders.decode" => { Some(Self::Plugins(PluginsCommand::ContentProvidersDecode)) } @@ -1725,6 +1735,8 @@ mod tests { "plugins.commandInstallers.requirements", "plugins.commandInstallers.plan", "plugins.commandInstallers.defaultDirectory", + "plugins.managedRuntimes.plan", + "plugins.managedRuntimes.decodeResolution", "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 abbcbe62..264308cb 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -78,6 +78,16 @@ pub(super) fn dispatch( payload, lithe_plugin_manifest::command_installer_default_directory_command, ), + PluginsCommand::ManagedRuntimesPlan => plugin_response( + id, + payload, + lithe_plugin_manifest::managed_runtime_plan_command, + ), + PluginsCommand::ManagedRuntimesDecodeResolution => plugin_response( + id, + payload, + lithe_plugin_manifest::managed_runtime_resolution_command, + ), PluginsCommand::ContentProvidersDecode => plugin_response( id, payload, diff --git a/rust/crates/core/src/tests/managed_runtimes.rs b/rust/crates/core/src/tests/managed_runtimes.rs new file mode 100644 index 00000000..5541db8a --- /dev/null +++ b/rust/crates/core/src/tests/managed_runtimes.rs @@ -0,0 +1,35 @@ +//! Managed-runtime plans and resolver answers through the public JSON boundary. + +use serde_json::{json, Value}; + +fn execute(command: &str, payload: Value) -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"command":command,"payload":payload}).to_string(), + )) + .unwrap() +} + +#[test] +fn managed_runtime_fixture_crosses_the_public_command_boundary() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/plugins/managed-runtimes.json" + ))) + .unwrap(); + let plan = execute( + "plugins.managedRuntimes.plan", + json!({"manifest":fixture["manifest"],"platform":fixture["platform"]}), + ); + assert_eq!(plan["ok"], true, "{plan}"); + assert_eq!(plan["data"]["status"], "ok", "{plan}"); + assert_eq!(plan["data"]["plan"]["dependencies"][0]["id"], "engine"); + let resolved = execute( + "plugins.managedRuntimes.decodeResolution", + json!({"manifest":fixture["manifest"],"platform":fixture["platform"],"result":fixture["resolution"]}), + ); + assert_eq!(resolved["ok"], true, "{resolved}"); + assert_eq!(resolved["data"]["resolution"], fixture["resolution"]); + let malformed = execute("plugins.managedRuntimes.plan", json!({})); + assert_eq!(malformed["ok"], false, "{malformed}"); + assert_eq!(malformed["error"]["code"], "invalid_request"); +} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index d4a3f32c..7619c281 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -43,6 +43,7 @@ mod installed_versions; mod keymap_import; mod language_server_sessions; mod lsp_policy; +mod managed_runtimes; mod marketplace_plugins; mod notification_read; mod plugin_editor_resources; diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index 3ed5ede7..cfc01a72 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -198,6 +198,7 @@ impl LspEngine { ), provider_id: request.provider_id, plugin_id: request.plugin_id, + function_relay_enabled: request.function_relay_enabled, workspace_host: lithe_workspace::current(), plugin_configuration: Mutex::new(workspace_configuration.map(Arc::new)), indexing_exclusions, @@ -208,7 +209,19 @@ impl LspEngine { state: Mutex::new(SessionState { lifecycle: LspLifecycleState::Created, client: LspClientState { - host_services: request.host_services.into_iter().collect(), + host_services: request + .host_services + .into_iter() + .filter(|service| { + request.function_relay_enabled + || !matches!( + service.as_str(), + lithe_plugin_rpc::HOST_SERVICE_FUNCTIONS + | lithe_plugin_rpc::FUNCTIONS_PROVIDERS + | lithe_plugin_rpc::FUNCTIONS_INVOKE + ) + }) + .collect(), host_options: request.host_options, ..initialize.state }, diff --git a/rust/crates/lsp-engine/src/function_relay_tests.rs b/rust/crates/lsp-engine/src/function_relay_tests.rs index 9330d4c3..8a4991a3 100644 --- a/rust/crates/lsp-engine/src/function_relay_tests.rs +++ b/rust/crates/lsp-engine/src/function_relay_tests.rs @@ -99,6 +99,7 @@ impl Fixture { request.plugin_id = Some(launch.plugin_id.to_string()); request.root_uri = launch.root_uri.to_string(); request.host_services = launch.host_services.clone(); + request.function_relay_enabled = launch.function_relay_enabled; let started = self .engine .start_server(request) @@ -135,6 +136,7 @@ struct Launch { root_uri: &'static str, functions: Vec<&'static str>, host_services: Vec, + function_relay_enabled: bool, } impl Launch { @@ -146,6 +148,7 @@ impl Launch { root_uri: "file:///workspace", functions: Vec::new(), host_services: vec!["functions".to_string()], + function_relay_enabled: true, } } @@ -164,6 +167,11 @@ impl Launch { self } + fn without_relay(mut self) -> Self { + self.function_relay_enabled = false; + self + } + fn capabilities(&self) -> Value { let functions: Vec = self .functions @@ -513,6 +521,55 @@ fn a_call_the_host_starts_carries_no_caller() { assert!(received.get("caller").is_none(), "{received}"); } +#[test] +fn preparation_session_is_private_even_when_its_plugin_has_an_installed_backend() { + const OWNER: &str = "dev.lithe.fixture.runtime-owner"; + const CALLER: &str = "dev.lithe.fixture.runtime-caller"; + let fixture = Fixture::new(); + let private = fixture.start(Launch::new(OWNER).serving(&[FORMAT]).without_relay()); + let installed = fixture.start(Launch::new(OWNER).serving(&[FORMAT]).at("file:///other")); + let caller = fixture.start(Launch::new(CALLER)); + fixture.configure(snapshot( + vec![ + plugin(CALLER, &[], &[(FORMAT, 1)]), + plugin(OWNER, &[(FORMAT, 1)], &[(FORMAT, 1)]), + ], + "local", + )); + + // The private session shares the caller's root and was registered first. + // Neither affinity is allowed to route a call to a staged package. + caller.call("installed-call", OWNER, FORMAT); + let (wire_id, _) = installed.await_invoke(); + installed.answer(&wire_id, json!({"installed":true})); + assert_eq!( + caller.reply("installed-call")["result"]["value"], + json!({"installed":true}) + ); + private.assert_not_invoked(); + + for (id, method, params) in [ + ( + "private-providers", + PROVIDERS, + json!({"functionID": FORMAT}), + ), + ("private-call", INVOKE, call_params(OWNER, FORMAT)), + ] { + private.ask(id, method, params); + assert_error(&private.reply(id), "plugin.host.permissionDenied", -32010); + } + private.ask( + "private-capabilities", + "lithe/host/getCapabilities", + json!({}), + ); + assert!(private.reply("private-capabilities")["result"].is_object()); + private.host_call("qualification", OWNER, FORMAT).unwrap(); + let (_, received) = private.await_invoke(); + assert!(received.get("caller").is_none()); +} + #[test] fn a_failing_callee_keeps_its_own_error_code() { let fixture = Fixture::new(); diff --git a/rust/crates/lsp-engine/src/relay_hub.rs b/rust/crates/lsp-engine/src/relay_hub.rs index f6b4f671..ca1e30bb 100644 --- a/rust/crates/lsp-engine/src/relay_hub.rs +++ b/rust/crates/lsp-engine/src/relay_hub.rs @@ -87,6 +87,15 @@ impl RelayHub { ) -> Result, CoreError> { let rpc_id = request.get("id").cloned().unwrap_or(Value::Null); let params = request.get("params").unwrap_or(&Value::Null); + if !session.function_relay_enabled { + return Ok(vec![reply_message( + &rpc_id, + &Err(RelayFailure::new( + codes::HOST_UNAVAILABLE, + "This session is isolated from cross-plugin function routing.", + )), + )?]); + } // Only a plugin's own session can negotiate the protocol, so a // session without a plugin should never get here. let Some(caller_plugin) = session.plugin_id.as_deref() else { @@ -477,7 +486,9 @@ fn find_provider( let sessions = sessions.lock().unwrap_or_else(PoisonError::into_inner); let candidates: Vec> = sessions .values() - .filter(|session| session.plugin_id.as_deref() == Some(plugin_id)) + .filter(|session| { + session.function_relay_enabled && session.plugin_id.as_deref() == Some(plugin_id) + }) .cloned() .collect(); let caller_root = sessions @@ -631,6 +642,9 @@ pub(super) fn observe_lifecycle(session: &RuntimeSession, lifecycle: LspLifecycl /// Tells the relay that `session` may now serve functions it did not before. pub(super) fn observe_functions_changed(session: &RuntimeSession) { + if !session.function_relay_enabled { + return; + } if let Some(plugin_id) = session.plugin_id.as_deref() { session.relay.provider_changed(plugin_id); } diff --git a/rust/crates/lsp-engine/src/requests.rs b/rust/crates/lsp-engine/src/requests.rs index 43c87764..2b0a1099 100644 --- a/rust/crates/lsp-engine/src/requests.rs +++ b/rust/crates/lsp-engine/src/requests.rs @@ -38,6 +38,11 @@ pub struct StartServerRequest { /// host-owned servers leave it out. #[serde(default)] pub plugin_id: Option, + /// Whether this session participates in cross-plugin function routing. + /// False isolates an approved preparation backend before its package is + /// committed; direct host calls to this session's private functions remain. + #[serde(default = "default_function_relay_enabled")] + pub function_relay_enabled: bool, /// Declarative `languageServer/start` attempt the host began; Core records its /// result. Absent for v1 hosts and SDK-owned backend processes. #[serde(default)] @@ -620,6 +625,10 @@ pub struct LspRuntimeError { pub details: Option, } +fn default_function_relay_enabled() -> bool { + true +} + fn default_initialize_timeout() -> u64 { DEFAULT_INITIALIZE_TIMEOUT_MS } diff --git a/rust/crates/lsp-engine/src/state.rs b/rust/crates/lsp-engine/src/state.rs index 610d8647..3a228919 100644 --- a/rust/crates/lsp-engine/src/state.rs +++ b/rust/crates/lsp-engine/src/state.rs @@ -111,6 +111,9 @@ pub(crate) struct RuntimeSession { pub(crate) provider_id: String, /// Plugin that owns the process, if any; see `StartServerRequest::plugin_id`. pub(crate) plugin_id: Option, + /// Native preparation sessions can serve host calls but never enter the + /// installed-plugin function relay, even when their owner IDs are equal. + pub(crate) function_relay_enabled: bool, pub(crate) log_identity: SessionLogIdentity, /// Fixed workspace host, inherited by protocol workers; never a global selection. pub(crate) workspace_host: Option, diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index b503563c..190cfbe6 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -18,6 +18,7 @@ pub(super) fn start_request(server: &ScriptedServer) -> StartServerRequest { role: SessionRole::LanguageServer, log_subject: None, plugin_id: None, + function_relay_enabled: true, startup_operation: None, host_services: Vec::new(), host_options: Default::default(), diff --git a/rust/crates/plugin-language-servers/src/lib.rs b/rust/crates/plugin-language-servers/src/lib.rs index 99f82f25..96ad0c85 100644 --- a/rust/crates/plugin-language-servers/src/lib.rs +++ b/rust/crates/plugin-language-servers/src/lib.rs @@ -347,9 +347,9 @@ fn is_within(path: &str, directory: &str) -> bool { } } -/// Params of the launch function, apart from `context` and `tools`, which -/// the host attaches: the server, the machine, the writable directories, -/// and the plugin's effective settings. +/// Params of the launch function, apart from `context`, `tools`, and the +/// optional read-only `runtimes` map, which the host attaches: the server, +/// the machine, the writable directories, and the plugin's effective settings. pub fn resolve_params( server_id: &str, architecture: &str, diff --git a/rust/crates/plugin-manifest/Cargo.toml b/rust/crates/plugin-manifest/Cargo.toml index 0794fdd9..8bad6e70 100644 --- a/rust/crates/plugin-manifest/Cargo.toml +++ b/rust/crates/plugin-manifest/Cargo.toml @@ -24,3 +24,5 @@ lithe-toolchain = { path = "../toolchain" } lithe-vcs = { path = "../vcs" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } +sha2 = "0.10" +url = "2.5" diff --git a/rust/crates/plugin-manifest/src/lib.rs b/rust/crates/plugin-manifest/src/lib.rs index 7b370b42..66a287a7 100644 --- a/rust/crates/plugin-manifest/src/lib.rs +++ b/rust/crates/plugin-manifest/src/lib.rs @@ -35,6 +35,7 @@ mod command_installers; mod commands; mod declarations; mod launch; +mod managed_runtimes; mod manifest; mod permissions; mod provider_launch; @@ -52,6 +53,7 @@ pub use command_installers::{ }; pub use commands::*; pub use launch::*; +pub use managed_runtimes::{managed_runtime_plan_command, managed_runtime_resolution_command}; pub use manifest::*; use permissions::*; pub use provider_launch::*; diff --git a/rust/crates/plugin-manifest/src/managed_runtimes.rs b/rust/crates/plugin-manifest/src/managed_runtimes.rs new file mode 100644 index 00000000..93edfb51 --- /dev/null +++ b/rust/crates/plugin-manifest/src/managed_runtimes.rs @@ -0,0 +1,430 @@ +//! Pinned runtime declarations and deterministic installation plans. Plugins own +//! tool-specific qualification; hosts own downloads, filesystem evidence and +//! atomic publication outside immutable plugin packages. + +use super::*; +use lithe_platform::{paths, Platform}; +use lithe_plugin_model::is_function_id; +use sha2::{Digest, Sha256}; +use url::Url; + +const MAX_DEPENDENCIES: usize = 16; +const MAX_ARTIFACTS: usize = 6; +const DEFAULT_RESOLVE_TIMEOUT: u64 = 30_000; +const MAX_RESOLVE_TIMEOUT: u64 = 120_000; +const MAX_PATH_BYTES: usize = 4096; + +/// A plugin-owned dependency set. One resolver qualifies both user installations +/// and newly staged archives without publishing or downloading anything itself. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ManagedRuntimes { + resolve: RuntimeResolver, + dependencies: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RuntimeResolver { + /// The existing plugin backend function invoked through litheFunctions. + function: String, + #[serde(default = "default_resolve_timeout")] + timeout_milliseconds: u64, +} + +fn default_resolve_timeout() -> u64 { + DEFAULT_RESOLVE_TIMEOUT +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RuntimeDependency { + id: String, + /// Opaque upstream identity, independent of the plugin's own version. + version: String, + /// An optional plugin-owned tool used only by this plugin's server launch. + #[serde(default, skip_serializing_if = "Option::is_none")] + tool: Option, + artifacts: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RuntimeArtifact { + /// Exact target: macos, windows or linux, and arm64 or x86_64. + os: String, + arch: String, + url: String, + sha256: String, + /// zip or tar.gz; the host never infers a format from a URL suffix. + archive: String, + /// Exact archive root removed while extracting; empty removes nothing. + #[serde(default)] + strip_prefix: String, + /// Runtime home relative to the stripped extraction root; empty is its root. + #[serde(default)] + home: String, + /// Tool executable relative to home. Required exactly when tool is declared. + #[serde(default)] + executable: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RuntimePlatform { + os: String, + arch: String, +} + +impl RuntimePlatform { + fn validate(&self) -> Validation<()> { + if !["macos", "windows", "linux"].contains(&self.os.as_str()) + || !KNOWN_ARCHITECTURES.contains(&self.arch.as_str()) + { + return Err(PluginRejection::at( + "plugin.managedRuntime.unavailable", + "platform", + "Managed runtimes require a supported operating system and architecture.", + )); + } + Ok(()) + } + + fn native_paths(&self) -> Platform { + if self.os == "windows" { + Platform::Windows + } else { + Platform::Unix + } + } +} + +fn bounded_text(value: &str, maximum: usize) -> bool { + !value.is_empty() + && value.len() <= maximum + && value.trim() == value + && !value.chars().any(char::is_control) +} + +/// These paths have the same portable meaning on every host. Native extraction +/// additionally checks filesystem aliases and symlink targets before writing. +fn relative_runtime_path(value: &str) -> bool { + value.is_empty() + || (bounded_text(value, 512) + && !value.contains(['\\', ':']) + && value + .split('/') + .all(|part| !part.is_empty() && part != "." && part != "..")) +} + +impl DeclarativePluginManifest { + pub(crate) fn validate_managed_runtimes(&mut self) -> Validation<()> { + let Some(runtimes) = &mut self.managed_runtimes else { + return Ok(()); + }; + let Some(backend) = &self.backend else { + return Err(invalid( + "managedRuntimes.resolve", + "A managed-runtime resolver needs the plugin's backend.", + )); + }; + // Preflight runs before installation is committed. Its backend cannot + // itself depend on one of the runtimes that preflight is preparing. + if !matches!( + backend.process.launch, + LanguageServerLaunch::Packaged { .. } + | LanguageServerLaunch::Runtime { + packaged_runtime: Some(_), + .. + } + ) || !backend.process.runtime_requirements().is_empty() + { + return Err(invalid( + "managedRuntimes.resolve", + "The resolver backend must carry its executable and any runtime it needs.", + )); + } + if !is_function_id(&runtimes.resolve.function) + || runtimes.resolve.function.len() > 128 + || !(100..=MAX_RESOLVE_TIMEOUT).contains(&runtimes.resolve.timeout_milliseconds) + { + return Err(invalid( + "managedRuntimes.resolve", + "A resolver names a function and a timeout from 100 to 120000 milliseconds.", + )); + } + if !(1..=MAX_DEPENDENCIES).contains(&runtimes.dependencies.len()) { + return Err(invalid( + "managedRuntimes.dependencies", + "A managed runtime set contains from 1 to 16 dependencies.", + )); + } + let tool_ids: BTreeSet<&str> = self + .tool_definitions + .iter() + .filter_map(|definition| definition["id"].as_str()) + .collect(); + let mut ids = BTreeSet::new(); + let mut bound_tools = BTreeSet::new(); + for (index, dependency) in runtimes.dependencies.iter_mut().enumerate() { + let field = format!("managedRuntimes.dependencies[{index}]"); + if !is_identifier(&dependency.id) + || dependency.id.len() > 64 + || !ids.insert(dependency.id.clone()) + { + return Err(invalid( + format!("{field}.id"), + "Runtime IDs are unique lowercase letters, digits and hyphens, at most 64 bytes.", + )); + } + if !bounded_text(&dependency.version, 128) { + return Err(invalid( + format!("{field}.version"), + "A runtime version is a nonempty upstream identity of at most 128 bytes.", + )); + } + if let Some(tool) = &dependency.tool { + if !tool_ids.contains(tool.as_str()) + || !self.requires_tools.contains(tool) + || !bound_tools.insert(tool.clone()) + { + return Err(invalid( + format!("{field}.tool"), + "A runtime binds one unique tool declared and required by this plugin.", + )); + } + } + if !(1..=MAX_ARTIFACTS).contains(&dependency.artifacts.len()) { + return Err(invalid( + format!("{field}.artifacts"), + "A dependency declares from 1 to 6 platform artifacts.", + )); + } + let mut targets = BTreeSet::new(); + for (index, artifact) in dependency.artifacts.iter_mut().enumerate() { + let field = format!("{field}.artifacts[{index}]"); + if !["macos", "windows", "linux"].contains(&artifact.os.as_str()) + || !KNOWN_ARCHITECTURES.contains(&artifact.arch.as_str()) + || !targets.insert((artifact.os.clone(), artifact.arch.clone())) + { + return Err(invalid( + &field, + "Artifacts have unique supported operating-system and architecture pairs.", + )); + } + let url = Url::parse(&artifact.url).map_err(|_| { + invalid( + format!("{field}.url"), + "A runtime archive needs an HTTPS URL.", + ) + })?; + if !bounded_text(&artifact.url, 4096) + || url.scheme() != "https" + || url.host_str().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + { + return Err(invalid( + format!("{field}.url"), + "Runtime archive URLs use HTTPS without credentials or fragments.", + )); + } + if artifact.sha256.len() != 64 + || !artifact.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + return Err(invalid( + format!("{field}.sha256"), + "A runtime archive pins its complete SHA-256 digest.", + )); + } + artifact.sha256.make_ascii_lowercase(); + if !["zip", "tar.gz"].contains(&artifact.archive.as_str()) { + return Err(invalid( + format!("{field}.archive"), + "A runtime archive format is zip or tar.gz.", + )); + } + for (name, path) in [ + ("stripPrefix", &artifact.strip_prefix), + ("home", &artifact.home), + ("executable", &artifact.executable), + ] { + if !relative_runtime_path(path) { + return Err(invalid( + format!("{field}.{name}"), + "Runtime paths are bounded relative paths without traversal.", + )); + } + } + if dependency.tool.is_some() == artifact.executable.is_empty() { + return Err(invalid( + format!("{field}.executable"), + "An executable relative to home is required exactly for a tool-bound runtime.", + )); + } + } + dependency + .artifacts + .sort_by(|left, right| (&left.os, &left.arch).cmp(&(&right.os, &right.arch))); + } + runtimes + .dependencies + .sort_by(|left, right| left.id.cmp(&right.id)); + Ok(()) + } +} + +impl ManagedRuntimes { + pub(crate) fn programs(&self) -> Vec { + self.dependencies + .iter() + .map(|dependency| { + json!({ + "kind": "managedRuntime", + "dependency": dependency, + "resolve": self.resolve, + }) + }) + .collect() + } + + fn plan(&self, platform: &RuntimePlatform) -> Validation { + let mut dependencies = Vec::new(); + for dependency in &self.dependencies { + let Some(artifact) = dependency + .artifacts + .iter() + .find(|artifact| artifact.os == platform.os && artifact.arch == platform.arch) + else { + return Err(PluginRejection::at( + "plugin.managedRuntime.unavailable", + format!("managedRuntimes.dependencies.{}", dependency.id), + "A required runtime has no artifact for this operating system and architecture.", + )); + }; + let mut selected = json!({ + "id": dependency.id, + "version": dependency.version, + "os": artifact.os, + "arch": artifact.arch, + "url": artifact.url, + "sha256": artifact.sha256, + "archive": artifact.archive, + "stripPrefix": artifact.strip_prefix, + "home": artifact.home, + "executable": artifact.executable, + }); + if let Some(tool) = &dependency.tool { + selected["tool"] = json!(tool); + } + // Serialize this explicitly constructed object, not input field order. + // Package versions are absent, so a plugin-only update reuses bytes. + let identity = Sha256::digest(selected.to_string().as_bytes()); + selected["cacheKey"] = json!(format!("{identity:x}")); + dependencies.push(selected); + } + Ok(json!({"resolve": self.resolve, "dependencies": dependencies})) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PlanRequest { + manifest: Value, + platform: RuntimePlatform, +} + +/// `plugins.managedRuntimes.plan` validates the manifest and selects exact pinned +/// artifacts. It performs no I/O and does not choose a tool-specific installation. +pub fn managed_runtime_plan_command(payload: Value) -> Result { + let request: PlanRequest = decode_payload(payload, "plugins.managedRuntimes.plan")?; + Ok(outcome(validate_manifest_value(request.manifest).and_then( + |manifest| { + request.platform.validate()?; + let plan = match manifest.managed_runtimes { + Some(runtimes) => runtimes.plan(&request.platform)?, + None => json!({"dependencies": []}), + }; + Ok(("plan", plan)) + }, + ))) +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ResolvedRuntime { + id: String, + /// A qualified external or staged native home; the host never writes into + /// an external home or replaces the user's project toolchain with it. + home: String, + version: String, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RuntimeResolution { + runtimes: Vec, + missing: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ResolutionRequest { + manifest: Value, + platform: RuntimePlatform, + result: Value, +} + +fn invalid_resolution(message: impl Into) -> PluginRejection { + PluginRejection::at("plugin.managedRuntime.invalidResolution", "result", message) +} + +/// `plugins.managedRuntimes.decodeResolution` binds a resolver's answer to the +/// declared dependency IDs. Compatibility remains the plugin's responsibility; +/// the host verifies native evidence before publishing the complete set. +pub fn managed_runtime_resolution_command(payload: Value) -> Result { + let request: ResolutionRequest = + decode_payload(payload, "plugins.managedRuntimes.decodeResolution")?; + Ok(outcome(validate_manifest_value(request.manifest).and_then(|manifest| { + request.platform.validate()?; + let Some(declaration) = manifest.managed_runtimes else { + return Err(invalid_resolution("The plugin declares no managed runtime resolver.")); + }; + declaration.plan(&request.platform)?; + let mut result: RuntimeResolution = serde_json::from_value(request.result) + .map_err(|_| invalid_resolution("The runtime resolver answer has an invalid shape."))?; + let expected: BTreeSet<&str> = declaration + .dependencies + .iter() + .map(|dependency| dependency.id.as_str()) + .collect(); + if result.runtimes.len() + result.missing.len() != expected.len() { + return Err(invalid_resolution("The answer must account for every declared runtime exactly once.")); + } + let mut seen = BTreeSet::new(); + for runtime in &result.runtimes { + if !expected.contains(runtime.id.as_str()) || !seen.insert(runtime.id.as_str()) { + return Err(invalid_resolution("The answer contains an undeclared or repeated runtime ID.")); + } + if !bounded_text(&runtime.home, MAX_PATH_BYTES) + || !paths::is_absolute_path(&runtime.home, request.platform.native_paths()) + || runtime.home.split(['/', '\\']).any(|part| part == "." || part == "..") + || !bounded_text(&runtime.version, 128) + { + return Err(invalid_resolution("A resolved runtime needs an absolute native home and a bounded nonempty version.")); + } + } + for id in &result.missing { + if !expected.contains(id.as_str()) || !seen.insert(id.as_str()) { + return Err(invalid_resolution("The answer contains an undeclared or repeated missing runtime ID.")); + } + } + result.runtimes.sort_by(|left, right| left.id.cmp(&right.id)); + result.missing.sort(); + Ok(("resolution", json!(result))) + }))) +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/plugin-manifest/src/managed_runtimes/tests.rs b/rust/crates/plugin-manifest/src/managed_runtimes/tests.rs new file mode 100644 index 00000000..09ad06ed --- /dev/null +++ b/rust/crates/plugin-manifest/src/managed_runtimes/tests.rs @@ -0,0 +1,251 @@ +//! Deterministic contract checks for runtime selection and resolver answers. +//! Native download, archive and filesystem evidence belong to host tests. + +use super::*; + +fn fixture() -> Value { + serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/plugins/managed-runtimes.json" + ))) + .unwrap() +} + +fn plan(manifest: Value) -> Value { + managed_runtime_plan_command(json!({"manifest": manifest, "platform": fixture()["platform"]})) + .unwrap() +} + +fn resolution(result: Value, os: &str) -> Value { + managed_runtime_resolution_command(json!({ + "manifest": fixture()["manifest"], + "platform": {"os": os, "arch": "x86_64"}, + "result": result + })) + .unwrap() +} + +#[test] +fn selects_exact_artifacts_and_normalizes_defaults() { + let result = plan(fixture()["manifest"].clone()); + assert_eq!(result["status"], "ok", "{result}"); + let dependencies = result["plan"]["dependencies"].as_array().unwrap(); + assert_eq!(dependencies.len(), 2); + assert_eq!(dependencies[0]["os"], "linux"); + assert_eq!(dependencies[0]["sha256"], "a".repeat(64)); + assert_eq!(dependencies[0]["home"], ""); + assert_eq!(dependencies[0]["tool"], "fixture-runtime"); + assert_eq!(dependencies[1]["id"], "server"); + assert_eq!(dependencies[1]["executable"], ""); + assert_eq!(result["plan"]["resolve"]["timeoutMilliseconds"], 30_000); + assert!(dependencies[0]["cacheKey"] + .as_str() + .unwrap() + .bytes() + .all(|byte| byte.is_ascii_hexdigit())); + assert_eq!(dependencies[0]["cacheKey"].as_str().unwrap().len(), 64); +} + +#[test] +fn plugin_updates_and_declaration_order_preserve_cache_identity() { + let mut manifest = fixture()["manifest"].clone(); + let original = plan(manifest.clone()); + manifest["version"] = json!("2.0.0"); + manifest["managedRuntimes"]["dependencies"] + .as_array_mut() + .unwrap() + .reverse(); + for dependency in manifest["managedRuntimes"]["dependencies"] + .as_array_mut() + .unwrap() + { + dependency["artifacts"].as_array_mut().unwrap().reverse(); + } + assert_eq!(plan(manifest)["plan"], original["plan"]); +} + +#[test] +fn upstream_identity_digest_target_and_layout_change_cache_identity() { + let manifest = fixture()["manifest"].clone(); + let original = plan(manifest.clone())["plan"]["dependencies"][0]["cacheKey"].clone(); + for (pointer, value) in [ + ("/managedRuntimes/dependencies/0/version", json!("26.0.0")), + ( + "/managedRuntimes/dependencies/0/artifacts/1/sha256", + json!("d".repeat(64)), + ), + ( + "/managedRuntimes/dependencies/0/artifacts/1/home", + json!("Contents/Home"), + ), + ( + "/managedRuntimes/dependencies/0/artifacts/1/url", + json!("https://example.invalid/rebuilt.tar.gz"), + ), + ] { + let mut changed = manifest.clone(); + if pointer.ends_with("/home") { + changed["managedRuntimes"]["dependencies"][0]["artifacts"][1]["home"] = value; + } else { + *changed.pointer_mut(pointer).unwrap() = value; + } + let result = plan(changed); + assert_eq!(result["status"], "ok", "{pointer}: {result}"); + assert_ne!(result["plan"]["dependencies"][0]["cacheKey"], original); + } + let windows = managed_runtime_plan_command(json!({ + "manifest": manifest, "platform": {"os": "windows", "arch": "x86_64"} + })) + .unwrap(); + assert_ne!(windows["plan"]["dependencies"][0]["cacheKey"], original); +} + +#[test] +fn absent_capability_preserves_old_manifests_and_old_hosts_refuse_new_ones() { + let mut manifest = fixture()["manifest"].clone(); + let rejected = validate_command(json!({ + "manifest": manifest, + "hostCapabilities": {"backend": [0], "toolDefinitions": [0]} + })) + .unwrap(); + assert_eq!(rejected["error"]["code"], "plugin.api.unsupported"); + assert_eq!(rejected["error"]["field"], "requires.managedRuntimes"); + manifest.as_object_mut().unwrap().remove("managedRuntimes"); + manifest["requires"] + .as_object_mut() + .unwrap() + .remove("managedRuntimes"); + manifest["permissions"] = json!(["backend.launch"]); + manifest["activationEvents"] = json!(["onWorkspaceOpen"]); + assert_eq!(plan(manifest)["plan"], json!({"dependencies": []})); +} + +#[test] +fn declarations_require_approval_and_self_contained_resolver() { + for (pointer, value) in [ + ("/permissions", json!(["backend.launch"])), + ( + "/backend/launch", + json!({"kind":"systemCommand", "commands":["resolver"]}), + ), + ("/managedRuntimes/resolve/function", json!("")), + ("/managedRuntimes/resolve/timeoutMilliseconds", json!(0)), + ] { + let mut manifest = fixture()["manifest"].clone(); + if pointer.ends_with("timeoutMilliseconds") { + manifest["managedRuntimes"]["resolve"]["timeoutMilliseconds"] = value; + } else { + *manifest.pointer_mut(pointer).unwrap() = value; + } + assert_eq!(plan(manifest)["status"], "rejected", "{pointer}"); + } +} + +#[test] +fn rejects_unsafe_archives_and_ambiguous_dependency_bindings() { + for (field, value) in [ + ("url", json!("http://example.invalid/runtime.zip")), + ( + "url", + json!("https://user:password@example.invalid/runtime.zip"), + ), + ("url", json!("https://example.invalid/runtime.zip#fragment")), + ("sha256", json!("abc")), + ("archive", json!("exe")), + ("stripPrefix", json!("../root")), + ("home", json!("C:/outside")), + ("home", json!("/outside")), + ("executable", json!("bin\\runtime")), + ("executable", json!("")), + ] { + let mut manifest = fixture()["manifest"].clone(); + manifest["managedRuntimes"]["dependencies"][0]["artifacts"][1][field] = value; + assert_eq!( + plan(manifest)["error"]["code"], + "plugin.manifest.invalid", + "{field}" + ); + } + let mut manifest = fixture()["manifest"].clone(); + manifest["managedRuntimes"]["dependencies"][1]["id"] = json!("engine"); + assert_eq!(plan(manifest)["status"], "rejected"); + let mut manifest = fixture()["manifest"].clone(); + manifest["managedRuntimes"]["dependencies"][0]["tool"] = json!("undeclared"); + assert_eq!(plan(manifest)["status"], "rejected"); +} + +#[test] +fn unsupported_platform_is_an_explicit_unavailable_outcome() { + for platform in [ + json!({"os":"linux", "arch":"arm64"}), + json!({"os":"freebsd", "arch":"x86_64"}), + ] { + let result = managed_runtime_plan_command( + json!({"manifest":fixture()["manifest"], "platform":platform}), + ) + .unwrap(); + assert_eq!(result["error"]["code"], "plugin.managedRuntime.unavailable"); + } +} + +#[test] +fn resolver_partitions_are_complete_and_use_native_absolute_homes() { + let fixture = fixture(); + for (key, os) in [("resolution", "linux"), ("windowsResolution", "windows")] { + let result = resolution(fixture[key].clone(), os); + assert_eq!(result["status"], "ok", "{result}"); + assert_eq!(result["resolution"], fixture[key]); + } + for result in [ + json!({"runtimes":[], "missing":["engine"]}), + json!({"runtimes":[], "missing":["engine", "engine"]}), + json!({"runtimes":[], "missing":["engine", "other"]}), + json!({"runtimes":[{"id":"engine", "home":"relative", "version":"25"}], "missing":["server"]}), + json!({"runtimes":[{"id":"engine", "home":"/opt/../runtime", "version":"25"}], "missing":["server"]}), + json!({"runtimes":[{"id":"engine", "home":"/opt/runtime", "version":""}], "missing":["server"]}), + json!({"runtimes":[], "missing":["engine", "server"], "executable":"/arbitrary"}), + ] { + assert_eq!( + resolution(result, "linux")["error"]["code"], + "plugin.managedRuntime.invalidResolution" + ); + } + assert_eq!( + resolution(fixture["windowsResolution"].clone(), "linux")["status"], + "rejected" + ); + assert_eq!( + resolution(fixture["resolution"].clone(), "windows")["status"], + "rejected" + ); +} + +#[test] +fn review_programs_include_every_origin_digest_and_resolver() { + let manifest = fixture()["manifest"].clone(); + let programs = validate_manifest_value(manifest.clone()) + .unwrap() + .programs(); + let runtimes: Vec<&Value> = programs + .iter() + .filter(|program| program["kind"] == "managedRuntime") + .collect(); + assert_eq!(runtimes.len(), 2); + assert_eq!( + runtimes[0]["dependency"]["artifacts"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert_eq!( + runtimes[0]["resolve"]["function"], + "fixture.resolveRuntimes" + ); + let mut changed = manifest; + changed["managedRuntimes"]["resolve"]["function"] = json!("fixture.newResolver"); + assert_ne!( + validate_manifest_value(changed).unwrap().programs(), + programs + ); +} diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index 324b85d7..6977e16e 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -66,6 +66,10 @@ pub struct DeclarativePluginManifest { /// launches need; see `command_installers`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) command_installers: Vec, + /// Pinned runtime archives managed outside the installed package, with a + /// backend resolver that owns tool-specific discovery and validation. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) managed_runtimes: Option, /// Entries of the New Project window. The shape and its validation live /// in `lithe_project_generators`. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -463,6 +467,9 @@ impl DeclarativePluginManifest { for installer in &self.command_installers { programs.push(crate::command_installers::programs(installer)); } + if let Some(runtimes) = &self.managed_runtimes { + programs.extend(runtimes.programs()); + } // 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 c3e7558c..9f915189 100644 --- a/rust/crates/plugin-manifest/src/permissions.rs +++ b/rust/crates/plugin-manifest/src/permissions.rs @@ -59,6 +59,10 @@ const PERMISSION_DEBUG_START: &str = "debug.start"; /// launches need with one of its required tools. const PERMISSION_COMMAND_INSTALL: &str = "commands.install"; +/// Downloading and installing the manifest's pinned runtime archives after +/// approval of the plugin installation or update. +const PERMISSION_RUNTIME_INSTALL: &str = "runtimes.install"; + const KNOWN_PERMISSIONS: &[&str] = &[ PERMISSION_BACKEND, PERMISSION_BUILD, @@ -71,6 +75,7 @@ const KNOWN_PERMISSIONS: &[&str] = &[ PERMISSION_KEYMAP_SOURCES, PERMISSION_PROJECT_GENERATE, PERMISSION_RUN, + PERMISSION_RUNTIME_INSTALL, PERMISSION_TEST, PERMISSION_TOOLCHAINS, PERMISSION_UI, @@ -178,6 +183,18 @@ impl DeclarativePluginManifest { "commands.install is used by a command installer; declare one or remove the permission.", )); } + if self.managed_runtimes.is_some() { + required.insert(PERMISSION_RUNTIME_INSTALL); + } else if self + .permissions + .iter() + .any(|p| p == PERMISSION_RUNTIME_INSTALL) + { + return Err(invalid( + "permissions", + "runtimes.install requires managedRuntimes.", + )); + } 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 fe1bf27e..ac3e5729 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -287,6 +287,7 @@ impl DeclarativePluginManifest { .any(|action| action.source_editor.is_some()) || !self.toolchain_providers.is_empty() || !self.keymap_import_providers.is_empty() + || self.managed_runtimes.is_some() || self .language_servers .iter() @@ -300,6 +301,7 @@ impl DeclarativePluginManifest { // Installers serve the launches above, so they are checked against // the validated program list. self.validate_command_installers(runtime_tools)?; + self.validate_managed_runtimes()?; self.validate_permissions()?; self.validate_activation_events()?; Ok(self) @@ -366,6 +368,10 @@ impl DeclarativePluginManifest { capabilities::COMMAND_INSTALLERS, !self.command_installers.is_empty(), ), + ( + capabilities::MANAGED_RUNTIMES, + self.managed_runtimes.is_some(), + ), (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 45738575..b9e44e12 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -97,6 +97,10 @@ pub const DEBUG_ADAPTERS: &str = "debugAdapters"; /// `lithe_plugin_manifest::command_installers`. pub const COMMAND_INSTALLERS: &str = "commandInstallers"; +/// `managedRuntimes`: pinned archives, isolated runtime storage, and the +/// plugin-owned discovery and validation hook invoked before publication. +pub const MANAGED_RUNTIMES: &str = "managedRuntimes"; + /// Independent providers that translate external shortcut settings. pub const KEYMAP_IMPORT_PROVIDERS: &str = "keymapImportProviders"; /// `pluginFunctions`: functions exported to, and called from, other plugins; @@ -124,6 +128,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (KEYMAP_IMPORT_PROVIDERS, &[0]), (LANGUAGE_SERVERS, &[0]), (LANGUAGES, &[0]), + (MANAGED_RUNTIMES, &[0]), (OUTPUT_LINK_MATCHERS, &[0]), (PACKAGE_TRUST, &[0]), (PLUGIN_FUNCTIONS, &[0]), diff --git a/rust/fixtures/plugins/managed-runtimes.json b/rust/fixtures/plugins/managed-runtimes.json new file mode 100644 index 00000000..68a6ee9d --- /dev/null +++ b/rust/fixtures/plugins/managed-runtimes.json @@ -0,0 +1,54 @@ +{ + "manifest": { + "schemaVersion": 0, + "id": "dev.lithe.fixture.managed-runtime", + "displayName": "Managed Runtime Fixture", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"backend": 0, "managedRuntimes": 0, "toolDefinitions": 0}, + "vendor": {"id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage"}, + "permissions": ["backend.launch", "runtimes.install"], + "backend": {"launch": {"kind": "packaged", "path": "bin/resolver"}}, + "requiresTools": ["fixture-runtime"], + "toolDefinitions": [{ + "id": "fixture-runtime", + "displayName": "Fixture Runtime", + "executableLayouts": [{"path": "bin/runtime"}], + "executables": [{"id": "shell", "kind": "command", "command": "fixture-runtime"}], + "version": {"arguments": ["--version"], "pattern": "([0-9]+(?:\\.[0-9]+)*)"}, + "commands": ["fixture-runtime"], + "launch": ["${executable}", "${arguments}"] + }], + "managedRuntimes": { + "resolve": {"function": "fixture.resolveRuntimes"}, + "dependencies": [ + { + "id": "engine", + "version": "25.0.1+2", + "tool": "fixture-runtime", + "artifacts": [ + {"os": "windows", "arch": "x86_64", "url": "https://example.invalid/engine-25-windows.zip", "sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "archive": "zip", "stripPrefix": "engine-25", "executable": "bin/runtime.exe"}, + {"os": "linux", "arch": "x86_64", "url": "https://example.invalid/engine-25-linux.tar.gz", "sha256": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "archive": "tar.gz", "stripPrefix": "engine-25", "executable": "bin/runtime"} + ] + }, + { + "id": "server", + "version": "4.2.0", + "artifacts": [ + {"os": "linux", "arch": "x86_64", "url": "https://example.invalid/server-4.2.zip", "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", "archive": "zip", "home": "server"}, + {"os": "windows", "arch": "x86_64", "url": "https://example.invalid/server-4.2.zip", "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", "archive": "zip", "home": "server"} + ] + } + ] + } + }, + "platform": {"os": "linux", "arch": "x86_64"}, + "resolution": { + "runtimes": [{"id": "engine", "home": "/opt/fixture/runtime", "version": "25.0.2"}], + "missing": ["server"] + }, + "windowsResolution": { + "runtimes": [{"id": "engine", "home": "C:\\Tools\\Fixture Runtime", "version": "25.0.2"}], + "missing": ["server"] + } +} diff --git a/shared/plugins/README.md b/shared/plugins/README.md index 9ab03b2a..efdca8be 100644 --- a/shared/plugins/README.md +++ b/shared/plugins/README.md @@ -42,7 +42,7 @@ Lithe 读取并校验 `plugin.json`,然后自己启动其中声明的外部进 1. **复制模板。** 以 [Lua 插件](https://github.com/Lithe-IDEA/lithe-plugin-lua) 为起点,它是 Lithe Store 的示例和模板。 2. **改 `plugin.json`。** 换成你自己的 ID、名称、语言和语言服务器,并按[下面](#清单里的版本号)的规则写版本号和 `requires`。先按[后面一节](#在编辑器里校验-pluginjson)配置编辑器,写错字段时会直接提示。 -3. **在构建阶段准备好所有文件。** 语言服务器、后端都在打包时放进插件包,运行时不下载任何东西。详见 [LSP 插件完整生命周期教程](guides/lsp-plugin-lifecycle.md)。 +3. **在构建阶段准备插件代码。** 后端及其运行时随包提供;语言服务器可随包提供,或通过 [`managedRuntimes`](contract/v1/README.md#managed-runtimes) 声明固定下载与校验,由支持该能力的宿主在安装审查后准备、跨插件版本复用。详见 [LSP 插件完整生命周期教程](guides/lsp-plugin-lifecycle.md)。 4. **在 Lithe 里试装。** 开发时可以用“从磁盘安装插件…”选择 zip 或目录(同样要确认安装审查;Lithe 安装的是一份快照,改完要重新安装)。发布前在自己仓库发一个 Release,并在仓库根目录放 `lithe-plugin-index.json`,然后在“管理插件仓库…”里加入你的仓库地址,走一遍用户的真实安装流程。 5. **发布。** 想让所有 Lithe 用户在插件市场看到,按 [Lithe Store 发布指南](https://github.com/Lithe-IDEA/Lithe-store/blob/main/docs/publishing.md) 收录;收录后新版本会被自动追踪。 @@ -118,7 +118,7 @@ lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", tag SDK 的源码都在本目录的 `sdk/` 下,发布在 [Core 仓库的 Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) 里(标签 `sdk-node-v<版本>`、`sdk-java-v<版本>`、`sdk-rust-v<版本>`),不在 npm、Maven 或 crates.io 上。Rust SDK 只实现插件后端(`backend`):插件函数和宿主服务;构建后端请用 Node.js 或 Java SDK,VCS 后端请用 Node.js SDK。各 SDK 的 README 有 “What the Lithe desktop serves” 一节,说明 Lithe 桌面端提供哪些协议;各协议的版本见[进程协议版本](reference/capabilities-and-versions.md#进程协议版本)。以上三个版本说的是版本 `0` 的协议;已退役的 `lithe-plugin-docs` 仓库发布过更早的 SDK,它们说的是旧协议,Lithe 桌面端不接受用它们写的插件,请只使用 Core 仓库发布的版本。 -规则只有一条:**在构建时下载,并按你锁定的 SHA-256(或 Git commit)校验;运行时不下载任何东西。** 插件包安装后没有 `npm install` 步骤,也必须能离线运行。 +SDK 与插件后端在构建时下载,并按锁定的 SHA-256(或 Git commit)校验;插件包安装后没有 `npm install` 步骤。独立的大型依赖可声明 [`managedRuntimes`](contract/v1/README.md#managed-runtimes):宿主在用户批准安装后校验并准备,完整缓存可离线复用;插件自身不能用启动脚本绕过这项声明或自行改写包。 [Maven 插件](https://github.com/Lithe-IDEA/lithe-plugin-maven) 的 `sdk.lock.json` 是锁定 Java SDK 的现成例子。 @@ -252,7 +252,7 @@ Community plugins must follow these rules: 1. **Copy the template.** Start from the [Lua plugin](https://github.com/Lithe-IDEA/lithe-plugin-lua), Lithe Store's example and template. 2. **Edit `plugin.json`.** Use your own ID, name, language, and language server, and write the version numbers and `requires` by the rules [below](#version-numbers-in-the-manifest). Set up your editor as in the [section after that](#validate-pluginjson-in-your-editor) first, so mistyped fields are flagged as you write. -3. **Prepare every file at build time.** Language servers and backends go into the package when you build it; nothing is downloaded at run time. See the [LSP plugin lifecycle guide](guides/lsp-plugin-lifecycle.md). +3. **Prepare plugin code at build time.** Package the backend and its own runtime. Ship language servers in the package, or declare pinned dependencies through [`managedRuntimes`](contract/v1/README.md#managed-runtimes) for a supporting host to prepare after install review and reuse across plugin versions. See the [LSP plugin lifecycle guide](guides/lsp-plugin-lifecycle.md). 4. **Try it in Lithe.** During development, use "Install Plugin from Disk…" with a zip or directory (you still confirm the install review; Lithe installs a snapshot, so reinstall after each change). Before publishing, create a Release in your repository, put `lithe-plugin-index.json` at the repository root, and add your repository under "Manage Plugin Repositories…" to walk through the real user install flow. 5. **Publish.** To list the plugin in every Lithe user's marketplace, follow the [Lithe Store publishing guide](https://github.com/Lithe-IDEA/Lithe-store/blob/main/docs/publishing.md); new versions are tracked automatically once listed. @@ -328,7 +328,7 @@ lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", tag All SDK sources live under `sdk/` in this directory and are published in the [Core repository's Releases](https://github.com/Lithe-IDEA/Lithe-core-rust/releases) (tags `sdk-node-v`, `sdk-java-v`, `sdk-rust-v`), not on npm, Maven, or crates.io. The Rust SDK implements only the plugin backend (`backend`): plugin functions and host services; write build backends with the Node.js or Java SDK and VCS backends with the Node.js SDK. Each SDK's README has a "What the Lithe desktop serves" section naming the protocols the Lithe desktop client provides; the version of each protocol is in [Process protocol versions](reference/capabilities-and-versions.md#process-protocol-versions). The three versions above speak the version `0` protocols; the retired `lithe-plugin-docs` repository published earlier SDKs that speak an older protocol, and the Lithe desktop client does not accept plugins written with them, so use only versions released from the Core repository. -There is one rule: **download at build time and verify against the SHA-256 (or Git commit) you pinned; download nothing at run time.** An installed package has no `npm install` step and must run offline. +Download SDKs and plugin backends at build time and verify against the SHA-256 (or Git commit) you pinned. An installed package has no `npm install` step. Large independent dependencies can declare [`managedRuntimes`](contract/v1/README.md#managed-runtimes): the host verifies and prepares them after approved installation, and complete cached sets work offline. Plugin launch scripts must not bypass this declaration or rewrite the package. The [Maven plugin](https://github.com/Lithe-IDEA/lithe-plugin-maven)'s `sdk.lock.json` is a ready example of pinning the Java SDK. diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index fb1c3410..5e689337 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -181,6 +181,7 @@ symbolic links. A host treats an installed package as read-only. | `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). | +| `managedRuntimes` | Pinned dependencies qualified by a packaged backend and installed in host-owned storage independent of plugin version; requires `managedRuntimes: 0` and `runtimes.install`; see [Managed runtimes](#managed-runtimes). | | `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. | @@ -974,6 +975,7 @@ belongs to one capability: | `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. | +| `managedRuntimes` | [`managedRuntimes`](#managed-runtimes) | Existing backend functions | Qualifies external and cached dependencies before committing an approved install/update, downloads only missing pinned artifacts, and repairs missing state before a server starts. | | `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. | @@ -1137,7 +1139,7 @@ process does not use `${workspaceStateDir}`; otherwise the request is | `requiredDirectories` | `state`, `workspaceState`, `log`, and/or `temporary`: the directories the host must create before starting the server. | | `requiredPackagePaths` | Sorted package-relative paths the launch points at. The host verifies each is inside the package and not a symbolic link before starting the server. | | `settings` | Effective value of every declared setting that produced this plan; absent when the plugin declares none. | -| `resolveParams` | Present only for a backend-resolved launch: the params of the launch function, without the `context` and the optional `tools` the host adds. | +| `resolveParams` | Present only for a backend-resolved launch: the params of the launch function, without the `context`, optional `tools`, and optional read-only `runtimes` map the host adds. | | `environment`, `writablePaths` | Present only in the plan `decodeLaunch` returns: the variables of the process, and the paths it writes. | | `sessionPolicy` | Present for a language server that declares session fields: the [session policy](#plugin-owned-sessions) the host passes to `lsp.startServer` unchanged. | | `buildProvider` | Present only for a `buildSystemID` selection: `{buildSystemID, executesProjectCode, mayUseNetwork, languageServer?}`. `languageServer` names the language whose server is the provider; the rest of the plan is then that server's plan, and the host reuses its running session instead of starting a second process. | @@ -1420,6 +1422,174 @@ approved again. See and the golden cases in [`command-installer-plans.json`](fixtures/command-installers/command-installer-plans.json). +## Managed runtimes + +`managedRuntimes: 0` lets a plugin qualify existing native installations and ask +the host to install only its missing, pinned dependencies. Dependencies live +outside the immutable plugin package and its versioned state directory. Their +identity is independent of `manifest.version`, so an update that changes only +plugin code reuses an already qualified runtime without another download. +No dependency path changes the user's project compiler or global tool selection. + +```json +"requires": {"backend": 0, "managedRuntimes": 0}, +"permissions": ["backend.launch", "runtimes.install"], +"managedRuntimes": { + "resolve": {"function": "runtime.resolve", "timeoutMilliseconds": 30000}, + "dependencies": [{ + "id": "engine", "version": "4.2.0", + "artifacts": [{ + "os": "linux", "arch": "x86_64", + "url": "https://example.invalid/engine-4.2.0.tar.gz", + "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "archive": "tar.gz", "stripPrefix": "engine-4.2.0", "home": "" + }] + }] +} +``` + +The illustration's digest and domain are inert examples, not downloadable assets. +The backend and any runtime needed to execute that backend must be packaged +(`packaged`, or `runtime` with `packagedRuntime`, without external runtime +dependencies). This prevents a bootstrap cycle: the resolver runs before the +dependency set or the new package version is committed. Declaring the resolver +is itself a backend activation trigger; it needs no workspace or UI contribution. + +| Field | Contract | +| --- | --- | +| `resolve` | Required `{function, timeoutMilliseconds?}`. A private backend function ID; timeout 100–120000 milliseconds, default 30000. It uses the existing `litheFunctions` protocol and requires no export. | +| `dependencies` | 1–16 entries, sorted by `id` on normalization. IDs are unique lowercase letters, digits and hyphens, at most 64 bytes. | +| `version` | Required nonempty opaque upstream identity, at most 128 bytes, without controls or surrounding whitespace. It is not the plugin version and is not compared as semver by Core. | +| `tool` | Optional unique tool binding. The plugin must own that `toolDefinitions` ID and list it in `requiresTools`. It is available only in this plugin's language-server session. | +| `artifacts` | 1–6 entries, one per distinct exact `os`/`arch` pair. OS is `macos`, `windows` or `linux`; architecture is `arm64` or `x86_64`. No target fallback or wildcard. | +| `url`, `sha256`, `archive` | HTTPS URL without credentials or fragments, at most 4096 bytes; complete SHA-256 normalized to lowercase; explicit `zip` or `tar.gz`. The host verifies bytes before extracting. | +| `stripPrefix` | Exact archive root removed by extraction, default empty. | +| `home` | Relative to the stripped extraction root, default empty for the root itself. | +| `executable` | Relative to `home`; required and nonempty exactly when `tool` is present. The host derives the executable from the qualified home and this path. | + +The three layout paths are empty or portable `/`-separated relative paths of at +most 512 bytes, with no empty, `.` or `..` component, backslash, colon, control +character or surrounding whitespace. They contain no template variables. Native +extraction also rejects escaping links, duplicate/aliased entries, oversized +archives and nonregular payload types; Core does not inspect a filesystem. +The desktop extraction budgets are 512 MiB compressed, 4 GiB expanded, 50,000 +entries and a 32 MiB completion inventory. Permission bits are preserved where +the native filesystem supports them, and safe archive links are created last. + +### Runtime qualification + +The host calls the resolver with this typed input: + +```json +{ + "platform": {"os": "linux", "arch": "x86_64"}, + "dependencies": [{"id": "engine", "version": "4.2.0", "os": "linux", "arch": "x86_64", "url": "https://example.invalid/engine.tar.gz", "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "archive": "tar.gz", "stripPrefix": "engine", "home": "", "executable": "", "cacheKey": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}], + "candidates": {"engine": "/host/managed/engine"}, + "tools": {}, + "settings": {} +} +``` + +`dependencies` is the selected plan from Core, including an optional `tool`. +`candidates` maps dependency IDs to existing or newly staged managed homes; +the hook can be called repeatedly during preparation. `tools`, when available, +maps tool IDs to `{executable, home, version}` discovered by the host, with +optional `provider` and `layer` facts copied unchanged from Core's toolchain +resolution. The plugin can use those facts to distinguish an explicit selection +from automatic discovery without duplicating selection policy in the host. Settings +are the effective declared plugin settings. Optional `language` is the host UI's +BCP 47 language tag (for example `en-US` or `zh-Hans`) for localized qualification +errors; plugins fall back to English when it is absent or unsupported. +No workspace is required for install +preflight; no candidate or external home is a writable state directory. + +The plugin owns compatibility: it inspects required files, probes the actual +runtime, checks extension compatibility and rejects broken explicit settings. +Explicit user paths take precedence. Otherwise it tries qualified candidates, +then eligible external installations, and reports only unmet dependencies as +missing. A configured but unusable explicit path is an error, never a request +to silently download a replacement. The host must not implement language names, +version rules, layout probes or discovery heuristics for a particular plugin. + +The response has exactly `runtimes` and `missing`: + +```json +{"runtimes": [{"id": "engine", "home": "/opt/engine", "version": "4.2.1"}], "missing": []} +``` + +Every declared dependency occurs exactly once across the two arrays. Unknown or +duplicate IDs are rejected. A returned home is an absolute path for the requested +native OS, at most 4096 bytes, without controls or dot/parent components; version +is a bounded nonempty identity under the same rules as the declaration. Core +validates structure and identity; the plugin qualifies compatibility and the host +checks native evidence. The host never writes into an external home. + +### Runtime preparation, approval and reuse + +Installation review includes `runtimes.install`, explaining network downloads +and installation of executable dependencies, plus one program of kind +`managedRuntime` per dependency. That program contains the complete normalized +dependency, all platform URLs and hashes, and the resolver declaration. Changing +any of them is a changed reviewed program. Package content integrity binds this +manifest as it does other program declarations. Preparation starts only after +the normal installation/update review succeeds. + +The native preparation backend starts with no host-service grants and +`lsp.startServer.functionRelayEnabled: false`. This optional native flag defaults +to true for existing sessions. False excludes the temporary backend from both +incoming and outgoing cross-plugin routing, even if an installed backend shares +its plugin ID. Direct host-to-session resolver calls, capability discovery and +structured logging still work. The preparation process is stopped and disposed +before its private state is removed; it never replaces the normal backend in +the host's installed-session registry. + +The host qualifies external/cached homes before downloading. It downloads only +missing dependencies into private staging, verifies pinned content and safe +extraction, and calls the resolver again with staged homes. It serializes cache +publication across windows and processes. The complete newly qualified set is +published before the approved package installation is committed; failures or +cancellation retain the previously usable package and set. Existing sessions +keep their selected homes. A failed dependency cannot produce a partially active +set or launch the new language server. The host can retry this preparation when +a declared managed dependency is absent or damaged before launch. + +Storage is under a host-managed plugin directory independent of plugin version. +`cacheKey` is an opaque 64-character lowercase SHA-256 of Core's normalized +selected dependency identity (including platform, upstream version, URL, digest +and layout), excluding plugin version. Hosts use that key without reconstructing +it. Cached content must pass native integrity checks and plugin qualification; +existence alone is insufficient. A verified unchanged set works offline. A new +or damaged dependency that cannot be downloaded produces an actionable failure; +it does not destroy the prior set. Updating a plugin never clears all runtime +caches. Removal/reclamation must not remove a home used by a live session. + +After preparation the host adds optional `runtimes: {: {home, version}}` +to a backend-resolved language server's `resolveParams`. It is read-only launch +information, not a writable directory grant. A tool binding supplies +`tools[tool]` and the corresponding `{kind: "tool", tool}` launch from the +qualified home in that session only. Global toolchain catalogs, project pins and +project runtime selection remain independent. There is no absolute executable +answer kind and no runtime directory template variable. + +### Managed runtime Core commands + +`plugins.managedRuntimes.plan` accepts `{manifest, platform:{os,arch}}` and +returns `{status:"ok", plan:{resolve, dependencies:[...]}}`. Each selected +dependency contains `id`, `version`, optional `tool`, `os`, `arch`, `url`, +`sha256`, `archive`, `stripPrefix`, `home`, `executable` and `cacheKey`. +Without a declaration it returns `plan:{dependencies:[]}` without `resolve`. + +`plugins.managedRuntimes.decodeResolution` accepts +`{manifest, platform:{os,arch}, result}` and returns +`{status:"ok", resolution:{runtimes,missing}}`, sorted by dependency ID. +Both commands revalidate the manifest and perform no native I/O. A target without +all required artifacts is `plugin.managedRuntime.unavailable`; invalid resolver +output is `plugin.managedRuntime.invalidResolution`; malformed declarations use +`plugin.manifest.invalid`. Malformed command envelopes use `invalid_request`. +The shared inert fixture is `rust/fixtures/plugins/managed-runtimes.json`. +Older hosts that do not advertise this capability reject +`requires.managedRuntimes` precisely, while existing manifests are unchanged. + ## Permissions and activation | Permission | Required when | @@ -1433,6 +1603,7 @@ and the golden cases in | `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 | +| `runtimes.install` | `managedRuntimes` is present (and only then); permits the host to download and install its pinned archives after normal plugin install/update review, and repair their managed storage | | `ui.contribute` | `ui` is declared | | `ui.web` | a tool window shows [web content](#web-content) | | `backend.launch` | `backend` is declared | diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 480c59ff..429cf2aa 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -11,6 +11,7 @@ {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["runConfigurationTypes"]}}}}, "then": {"properties": {"requires": {"required": ["runConfigurationTypes"]}}}}, {"if": {"required": ["commandInstallers"]}, "then": {"required": ["permissions"], "properties": {"requires": {"required": ["commandInstallers"]}, "permissions": {"contains": {"const": "commands.install"}}}}}, + {"if": {"required": ["managedRuntimes"]}, "then": {"required": ["backend", "permissions"], "properties": {"requires": {"required": ["managedRuntimes", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "runtimes.install"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["toolchainProviders"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["toolchainProviders", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "toolchains.provide"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["pluginFunctions"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["pluginFunctions", "backend"]}}}}, {"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"}}]}}}}, @@ -37,6 +38,7 @@ "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] }, "languages": { "description": "Required exactly when languages is non-empty. Covers languages[].grammar, a TextMate grammar, and languages[].configuration.", "enum": [0] }, + "managedRuntimes": { "description": "Required exactly when managedRuntimes is present: approved pinned runtime archives, plugin-owned qualification and host-owned installation outside versioned packages.", "enum": [0] }, "outputLinkMatchers": { "description": "Required exactly when outputLinkMatchers is non-empty.", "enum": [0] }, "packageTrust": { "description": "Required exactly when vendor.bundledSignatureRequirement is present.", "enum": [0] }, "projectGenerators": { "description": "Entries of the New Project window: fields, requirements, and steps, with tool fields that pick tool installations.", "enum": [0] }, @@ -72,7 +74,7 @@ }, "permissions": { "type": "array", - "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", + "items": { "enum": ["backend.launch", "commands.install", "credentials.store", "debug.attach", "debug.launch", "languageServer.launch", "process.build", "process.run", "process.test", "process.vcs", "project.generate", "runtimes.install", "ui.contribute", "ui.web", "workspace.metadata", "workspace.files.read", "workspace.files.watch", "workspace.search", @@ -161,6 +163,7 @@ "maxItems": 16, "items": { "$ref": "#/$defs/commandInstaller" } }, + "managedRuntimes": { "$ref": "#/$defs/managedRuntimes" }, "projectGenerators": { "description": "requires.projectGenerators: entries of the New Project window. Requires the project.generate permission.", "type": "array", @@ -953,6 +956,55 @@ } } }, + "managedRuntimes": { + "description": "A dependency set qualified by the plugin backend before install/update commit and repaired lazily before launch. Requires runtimes.install and a backend that carries its own executable/runtime.", + "type": "object", + "additionalProperties": false, + "required": ["resolve", "dependencies"], + "properties": { + "resolve": { + "type": "object", + "additionalProperties": false, + "required": ["function"], + "properties": { + "function": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[a-z][A-Za-z0-9]*(?:\\.[a-z][A-Za-z0-9]*)*$" }, + "timeoutMilliseconds": { "type": "integer", "minimum": 100, "maximum": 120000, "default": 30000 } + } + }, + "dependencies": { + "type": "array", "minItems": 1, "maxItems": 16, + "items": { + "type": "object", "additionalProperties": false, + "required": ["id", "version", "artifacts"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z0-9-]+$", "maxLength": 64 }, + "version": { "type": "string", "minLength": 1, "maxLength": 128 }, + "tool": { "description": "One unique tool this plugin defines and lists in requiresTools. Selected only for this plugin's server session.", "$ref": "#/$defs/toolchainToolID" }, + "artifacts": { "type": "array", "minItems": 1, "maxItems": 6, "items": { "$ref": "#/$defs/managedRuntimeArtifact" } } + } + } + } + } + }, + "managedRuntimeArtifact": { + "type": "object", "additionalProperties": false, + "required": ["os", "arch", "url", "sha256", "archive"], + "properties": { + "os": { "enum": ["macos", "windows", "linux"] }, + "arch": { "enum": ["arm64", "x86_64"] }, + "url": { "type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^https://", "description": "HTTPS without credentials or fragments; semantic URL validation is performed by Core." }, + "sha256": { "type": "string", "pattern": "^[A-Fa-f0-9]{64}$" }, + "archive": { "enum": ["zip", "tar.gz"] }, + "stripPrefix": { "$ref": "#/$defs/managedRuntimePath", "default": "" }, + "home": { "$ref": "#/$defs/managedRuntimePath", "default": "" }, + "executable": { "$ref": "#/$defs/managedRuntimePath", "default": "", "description": "Relative to home, required and nonempty exactly when the dependency binds a tool." } + } + }, + "managedRuntimePath": { + "description": "Empty or a portable relative path, without empty, dot or parent components; no backslash, colon, control character or surrounding whitespace.", + "type": "string", "maxLength": 512, + "pattern": "^(?:[^/\\\\:]+(?:/[^/\\\\:]+)*)?$" + }, "commandInstaller": { "description": "One way to install bare commands. The host shows the tool, the expanded command line, the network use and the target directory, and runs it only after the user confirms.", "type": "object", diff --git a/shared/plugins/guides/lsp-plugin-lifecycle.md b/shared/plugins/guides/lsp-plugin-lifecycle.md index 73035cc3..117d9f0f 100644 --- a/shared/plugins/guides/lsp-plugin-lifecycle.md +++ b/shared/plugins/guides/lsp-plugin-lifecycle.md @@ -54,6 +54,8 @@ LSP(Language Server Protocol,语言服务器协议)让编辑器通过独 成熟后端提供。不要为了“接上 LSP”再复制一套工程模型。LSP 支持的具体功能仍取决于服务器 能力与宿主支持;安装服务器不会自动带来构建、测试、DAP 调试或自定义界面。 +大型依赖还可使用 [`managedRuntimes`](../contract/v1/README.md#managed-runtimes)。插件后端先检查显式配置、已缓存和外部安装,仅报告未满足的依赖;宿主在安装审查通过后下载固定归档、校验并原子准备,跨插件版本复用。后端和它自己的运行时仍随包提供,项目的编译工具链不受影响。下文 Lua 模板演示随包分发方案。 + ### 2. 跑通原版模板,再改成自己的插件 本地需要 Git、Node.js 22+、`tar`、`zip` 和 `unzip`。打包工具使用 Node.js, @@ -426,7 +428,7 @@ print(greet("Lithe")) | 编辑、保存、关闭/重开文件 | 文档同步和诊断正常,没有重复会话 | | 快速切换两个项目/工作区 | 旧结果不串到新项目,索引与锁不互相占用 | | 服务器异常退出或初始化失败 | 宿主能显示可定位的失败;恢复操作不会留下重复进程 | -| 缺少 Node.js/Go/Java 或版本不足 | 给出可操作的运行时错误,不在启动时自行下载 | +| 缺少 Node.js/Go/Java 或版本不足 | 给出可操作的运行时错误;已声明 `managedRuntimes` 的依赖由宿主准备,插件不自行下载 | | 修改默认会重启服务器的设置 | 新会话使用新值,旧进程退出 | | 禁用插件、关闭工作区、退出 Lithe | 相应会话与进程被停止,启动器/辅助子进程不残留 | | 卸载与重新安装 | 卸载先停用,再删除包和宿主管理的插件状态;自定义缓存有明确说明 | @@ -535,6 +537,8 @@ Pick a mature language server whose license allows redistribution. Project impor the language's mature backend wherever possible. Do not duplicate a project model just to "hook up LSP". What LSP features you get still depends on the server's capabilities and on host support; installing a server does not bring build, test, DAP debugging, or custom UI. +Large dependencies may also use [`managedRuntimes`](../contract/v1/README.md#managed-runtimes). The plugin backend qualifies explicit settings, cached homes and external installations, reporting only unmet dependencies. After install approval the host downloads pinned archives, verifies and atomically prepares them, reusing them across plugin versions. The backend and its own runtime still ship in the package; project toolchains remain independent. The Lua example below demonstrates packaging dependencies. + ### 2. Run the original template, then make it your own plugin You need Git, Node.js 22+, `tar`, `zip`, and `unzip`. The packaging tool uses Node.js; @@ -909,7 +913,7 @@ not guarantees you get by declaring something. | Edit, save, close and reopen files | Document sync and diagnostics work, with no duplicate sessions | | Switch quickly between two projects or workspaces | Old results do not leak into the new project; indexes and locks do not collide | | The server exits unexpectedly or fails to initialize | The host shows a failure you can trace; recovery leaves no duplicate processes | -| Node.js, Go, or Java missing or too old | An actionable runtime error, with no download at launch | +| Node.js, Go, or Java missing or too old | An actionable runtime error; the host prepares declared managed runtimes, while plugins do not download them themselves | | Change a setting whose default restarts the server | New sessions use the new value, and the old process exits | | Disable the plugin, close the workspace, quit Lithe | The sessions and processes stop, with no launcher or helper child left behind | | Uninstall and reinstall | Uninstall deactivates first, then removes the package and host-managed plugin state; custom caches are documented | diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 62a7aacc..368e2b89 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -46,7 +46,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-20 | 存储 | 部分完成 | 插件级 `${stateDir}`、后端和工作区的可写目录(`stateDirectory`)、网页状态;语言服务器按工作区的状态目录,按声明的 [`state.retention`](../contract/v1/README.md#plugin-owned-sessions) 由宿主在后台回收(Core 决定) | 统一的键值存储、配额;用户可见的状态重置入口 | [插件后端](domains/backend.md) | | API-21 | 凭据 | 既有能力 | [`credentials/get`、`set`、`delete`](../contract/v1/README.md#host-services),按插件隔离 | — | [插件后端](domains/backend.md) | | API-22 | 输出、日志、进度 | 部分完成 | [插件函数的进度和取消](../contract/v1/README.md#progress);面向开发者的[结构化诊断日志 `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics);[`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) 在宿主状态界面显示插件自己的语言服务器准备状态(只有消息和百分比,没有 actions);[`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers):插件声明的匹配器让 Run 与测试控制台的输出出现链接 | 独立的输出面板、面向用户的日志和进度 API | [插件后端](domains/backend.md) | -| API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `toolchainProviders` 和 `commandInstallers` | [工具链](domains/toolchains.md) | +| API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`);[受管运行时](../contract/v1/README.md#managed-runtimes)(`managedRuntimes`,权限 `runtimes.install`,Core 计划与应答校验,无新增宿主 RPC) | 后端可调用的通用工具链和进程服务;保存固定(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`); [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-23 | Toolchains and managed processes | Partial | [Process start](../contract/v1/README.md#process-start), runtime resolution, [shared executable candidates](../contract/v1/README.md#executable-resolution), tool definitions, toolchain providers (`toolchainProviders`); [references to runtimes by tool-definition ID](../contract/v1/README.md#tool-references) (manifest `requiresTools`); backend-started [`run/start`, `run/stop`, and the `run/didExit` notification](../contract/v1/README.md#run-and-debug-sessions), where the host owns the Run session (permission `run.start`; a tool that resolves to no executable returns `plugin.host.toolUnresolved`); [installing missing commands](../contract/v1/README.md#command-installers) (`commandInstallers`, permission `commands.install`); [managed runtimes](../contract/v1/README.md#managed-runtimes) (`managedRuntimes`, permission `runtimes.install`, Core plans and reply validation with no new host RPC) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `toolchainProviders` or `commandInstallers` | [Toolchains](domains/toolchains.md) | | API-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 035f1069..94ec6a61 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -55,6 +55,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `runConfigurationTypes` `0` | `buildSystems[].runConfigurationTypes`:插件声明的运行配置类型(如 Go Build、Go Test),宿主按声明的字段画编辑器,Core 用 `build.runConfigurationPlan` 把保存的配置展开成命令行;所有运行配置共用“允许多个实例”开关 | ✅ | ✅¹ | [Run configuration types](../contract/v1/README.md#run-configuration-types) | | `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) | +| `managedRuntimes` `0` | 固定归档、插件后端资格检查、跨版本缓存与安装前准备;权限 `runtimes.install` | ✅ | 配套宿主接入后声明 | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `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) | @@ -166,6 +167,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `runConfigurationTypes` `0` | `buildSystems[].runConfigurationTypes`: run configuration types a plugin declares (such as Go Build and Go Test); the host draws the editor from the declared fields and Core expands a saved configuration into a command line with `build.runConfigurationPlan`; every run configuration shares the Allow multiple instances switch | ✅ | ✅¹ | [Run configuration types](../contract/v1/README.md#run-configuration-types) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | ✅¹ | [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) | +| `managedRuntimes` `0` | Pinned archives, plugin-owned qualification, version-independent cache and install preflight; permission `runtimes.install` | ✅ | Declared with companion host integration | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | | `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch lacks with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | ✅ | [Toolchains](domains/toolchains.md#installing-missing-commands) | | `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) | diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 7c41869f..9c816b91 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -122,6 +122,14 @@ | 不覆盖 | 构建系统和执行提供者通过 `invocation.executables` 解析的可执行文件 | | 安装审查 | 每个安装都是审查里的程序(`kind: "commandInstaller"`),改了要运行的内容需要重新批准 | +### 独立于插件版本的受管运行时 + +[`managedRuntimes`](../../contract/v1/README.md#managed-runtimes) 0 为固定归档提供安装前准备与缓存复用。清单声明 `resolve` 后端函数和 `dependencies`,每个依赖固定版本、平台、HTTPS URL、SHA-256、解压格式与布局;可选 `tool` 只供本插件语言服务器会话使用。权限 `runtimes.install` 和全部下载来源参与正常安装审查。 + +宿主把显式配置、工具发现信息和已缓存候选交给插件函数;函数检查兼容性,返回完整划分 `{runtimes:[{id,home,version}],missing:[id]}`。宿主仅下载未满足项,在暂存目录校验摘要、安全解压,再交插件检查,完整成功后原子发布。外部安装只读复用,无效的显式配置须报错。缓存键不含插件版本,依赖未变的插件更新不重复下载;缺失状态可在启动前修复。插件后端及其自身运行时必须随包提供。 + +Core 的 `plugins.managedRuntimes.plan` 选择准确平台并生成缓存键,`plugins.managedRuntimes.decodeResolution` 校验应答身份和路径;它们没有文件或网络 I/O。语言服务器启动可收到只读 `runtimes: {id:{home,version}}` 映射。平台宿主负责下载、文件锁、完整性和原子发布,不判断特定工具的版本;全局与项目工具链不随之改变。该能力需要配套宿主接入并声明后才能安装使用。 + ### 本机文档 `.lithe/toolchains/local.json` 的 `version` 为 `1`,`toolchains.resolvePins` / `editPins` / `editPinSources` 校验并按条件更新目录级固定 `{home, version, provider}`,不授予项目代码执行权限。本机应用存储目录下的 `toolchains/global.json`(经 `toolchains.catalogState` / `editCatalog` 管理)保存本机注册的 SDK 目录、全局默认以及显式信任的工作区根路径 `trustedWorkspaces`(绝不写进工作区 `.lithe/`)。 @@ -295,6 +303,14 @@ A `systemCommand` launch names only a bare command (such as `dlv` or `gopls`), a | 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 | +### Managed runtimes independent of plugin version + +[`managedRuntimes`](../../contract/v1/README.md#managed-runtimes) 0 provides install preflight and reuse of pinned archives. A manifest declares a `resolve` backend function and `dependencies`; each dependency pins a version, exact platform, HTTPS URL, SHA-256, archive format and layout. An optional `tool` binding serves only this plugin's language-server session. `runtimes.install` and every download origin participate in normal install review. + +The host supplies effective settings, discovered tools and cached candidates to the plugin function, which qualifies compatibility and returns the complete partition `{runtimes:[{id,home,version}],missing:[id]}`. The host downloads only missing items, verifies bytes and safe extraction in staging, and asks the plugin to qualify them before atomic publication of the complete set. External installations are reused read-only; invalid explicit settings are errors. Cache keys omit plugin version, so unchanged dependencies survive updates without downloads. Missing state can be repaired before launch. The backend and its own runtime must be packaged. + +Core's `plugins.managedRuntimes.plan` selects the exact platform and generates cache identities; `plugins.managedRuntimes.decodeResolution` validates reply identity and paths. Neither performs file or network I/O. Server launch may receive a read-only `runtimes: {id:{home,version}}` map. Native hosts own downloads, locking, integrity and atomic publication without tool-specific rules; global and project toolchains stay independent. A companion host must implement and advertise the capability before plugins can require it. + ### Local document `.lithe/toolchains/local.json` keeps `version` `1`; `toolchains.resolvePins`, `editPins`, and `editPinSources` validate and conditionally update directory pins `{home, version, provider}`, granting no execution authority over project code. Machine-local `toolchains/global.json` under the application preference directory (managed through `toolchains.catalogState` and `editCatalog`) stores registered SDK homes, global defaults, and explicitly trusted workspace roots `trustedWorkspaces` (never written inside `.lithe/`). diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 907c0fb4..b8cc6223 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -12,6 +12,10 @@ - **API 编号**:这个 PR 涉及的 API-01–44 规划编号,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md),和协议版本、能力版本分开记录。— 表示没有改到具体 API,例如清单、市场、包信任、SDK 或契约文档整理。 - **协议 / 能力**:**加粗**的是这个 PR 新增的版本号;没有加粗的,是同一版本内的补充、宿主接入或说明修正。 +## 待合入 + +- `managedRuntimes` 0(API-23):新增固定 HTTPS 归档与 SHA-256、平台选择、与插件版本无关的缓存身份,以及插件后端对外部/暂存依赖的资格检查契约。新增权限 `runtimes.install`、审查程序 `managedRuntime`、Core 命令 `plugins.managedRuntimes.plan` 与 `plugins.managedRuntimes.decodeResolution`;正常语言服务器启动可接收只读 `runtimes` 映射。原生 `lsp.startServer` 新增可选 `functionRelayEnabled`(默认 true),准备会话设为 false 隔离跨插件调用但保留宿主直接调用。无新增宿主 RPC 或 SDK 版本。实现见 [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96)(lithe-support[bot]);合入日期在合并后补入下方时间线。宿主须先发布对应能力,插件才可要求它。 + ## 按协议查首次出现 所有版本都从 `0` 开始。以后一个 PR 给某个能力加版本 `1` 时,在对应的表里为它加一行。