From d5e5d8ee737dd6fa73d55c820e85f22731826e4c Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 10:01:36 +0800 Subject: [PATCH 1/4] feat(sdk): add typed Rust toolchain providers --- .../workflows/plugins-release-rust-sdk.yml | 2 +- .../plugins/reference/domains/toolchains.md | 4 +- shared/plugins/sdk/e2e/plugin_sdk/mod.rs | 1 + .../plugins/sdk/e2e/plugin_sdk/toolchains.rs | 82 ++++++ shared/plugins/sdk/e2e/plugin_sdk_rust.rs | 8 + shared/plugins/sdk/rust/Cargo.lock | 2 + shared/plugins/sdk/rust/README.md | 30 +- .../rust/examples/sample-backend/src/main.rs | 11 + shared/plugins/sdk/rust/plugin-sdk/Cargo.toml | 1 + .../sdk/rust/plugin-sdk/src/backend.rs | 163 +++++++++++ shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 4 +- .../sdk/rust/plugin-sdk/src/toolchains.rs | 275 ++++++++++++++++++ .../sdk/rust/plugin-sdk/tests/toolchains.rs | 130 +++++++++ 13 files changed, 708 insertions(+), 5 deletions(-) create mode 100644 shared/plugins/sdk/e2e/plugin_sdk/toolchains.rs create mode 100644 shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs create mode 100644 shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs diff --git a/.github/workflows/plugins-release-rust-sdk.yml b/.github/workflows/plugins-release-rust-sdk.yml index c7cb0ef0..82495ff6 100644 --- a/.github/workflows/plugins-release-rust-sdk.yml +++ b/.github/workflows/plugins-release-rust-sdk.yml @@ -70,4 +70,4 @@ jobs: asset="lithe-plugin-sdk-rust-$VERSION.crate" gh release create "$TAG" "dist/$asset" "dist/$asset.sha256" \ --title "Rust plugin SDK $VERSION" \ - --notes "Official Rust plugin SDK $VERSION for Lithe plugin backends. Requires Rust 1.87 or newer and depends only on serde_json and base64. Depend on the tag through Git, or pin the archive by its SHA-256 (\`$asset.sha256\`) and vendor the unpacked crate; see shared/plugins/sdk/rust/README.md." + --notes "Official Rust plugin SDK $VERSION for Lithe plugin backends. Requires Rust 1.87 or newer and uses serde, serde_json and base64. Depend on the tag through Git, or pin the archive by its SHA-256 (\`$asset.sha256\`) and vendor the unpacked crate; see shared/plugins/sdk/rust/README.md." diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 4c999db3..aab204b2 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -16,7 +16,7 @@ | 激活事件 | 不需要。提供者由宿主的第一次查询唤起,不需要页面或启动事件 | | 后端启动 | 提供者的后端只能是包内可执行文件(`packaged`),或包内运行时(`runtime` 加 `packagedRuntime`),不能依赖需要发现的运行时 | | 桌面端 | 声明 `toolDefinitions`;未声明 `toolchainProviders`,见“桌面端现状” | -| 官方 SDK | 三个官方 SDK 都还没有实现 `litheToolchains`,提供者后端要自己处理 `toolchains/query` | +| 官方 SDK | [Rust SDK](../../sdk/rust/README.md#toolchain-providers) 提供类型化的 `toolchains/query`、能力协商和取消处理。Node 和 Java 后端自行处理该协议 | ### 两条安装来源 @@ -203,7 +203,7 @@ A plugin can tell Lithe what a tool (a JDK, Maven, Node, Go and so on) looks lik | Activation | None needed. The host's first query starts a provider; no page or startup event is needed | | Backend launch | The provider's backend must be `packaged`, or `runtime` with `packagedRuntime`, and must not depend on a discovered runtime | | Desktop | Declares `toolDefinitions`; does not declare `toolchainProviders`. See "Desktop status" | -| Official SDKs | None of the three official SDKs implements `litheToolchains` yet; a provider backend handles `toolchains/query` itself | +| Official SDKs | The [Rust SDK](../../sdk/rust/README.md#toolchain-providers) handles typed `toolchains/query`, negotiation, and cancellation. Node and Java backends handle the protocol directly | ### Two installation routes diff --git a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs index b32e15b8..7576a749 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs @@ -22,6 +22,7 @@ pub mod backend; pub mod keymap; pub mod native_build; +pub mod toolchains; pub mod vcs; use lithe_core::execute_json; diff --git a/shared/plugins/sdk/e2e/plugin_sdk/toolchains.rs b/shared/plugins/sdk/e2e/plugin_sdk/toolchains.rs new file mode 100644 index 00000000..0821b018 --- /dev/null +++ b/shared/plugins/sdk/e2e/plugin_sdk/toolchains.rs @@ -0,0 +1,82 @@ +//! Drives a Rust SDK toolchain query over Core's actual transport and decoder. + +use super::{core, Fixture, Session, WAIT}; +use serde_json::json; +use std::fs; + +pub fn run(executable: &str) { + let fixture = Fixture::new("rust-toolchain"); + let workspace = fixture.workspace(); + let state = fixture.root.join("state"); + fs::create_dir_all(&workspace).unwrap(); + fs::create_dir_all(&state).unwrap(); + let plugin_id = "org.example.sdk-toolchain"; + let manifest = json!({ + "schemaVersion": 0, "pluginAPIVersion": 0, + "id": plugin_id, "displayName": "SDK toolchain fixture", "version": "1.0.0", + "requires": {"backend": 0, "toolchainProviders": 0}, + "vendor": {"id": "org.example", "displayName": "Fixture publisher", "signatureRequirement": "publisherPackage"}, + "permissions": ["backend.launch", "toolchains.provide"], + "toolchainProviders": [{"id": "fixture", "displayName": "SDK fixture", "tools": ["fixture-runtime"]}], + "backend": {"launch": {"kind": "packaged", "path": "bin/sample-backend"}, "arguments": ["--state", "${stateDir}"]}, + }); + let registry = json!({"plugins": [{"manifest": manifest}]}); + let validated = core("toolchains.registry", registry.clone()); + assert_eq!(validated["status"], "ok", "{validated}"); + assert_eq!( + validated["registry"]["providers"][0]["provider"]["id"], + "fixture" + ); + let started = core( + "lsp.startServer", + json!({ + "providerId": format!("pluginBackend:{plugin_id}"), "pluginId": plugin_id, + "executablePath": executable, "arguments": ["--state", state], + "rootUri": format!("file://{}/", workspace.display()), "workingDirectory": workspace, + "toolchainProviders": ["fixture"], "initializeTimeoutMilliseconds": WAIT.as_millis() as u64, + "requestTimeoutMilliseconds": WAIT.as_millis() as u64, "shutdownTimeoutMilliseconds": 5000, + }), + ); + let mut session = Session { + id: started["sessionId"].as_str().expect("session ID").into(), + plugin_id: plugin_id.into(), + events: Vec::new(), + }; + let negotiated = session.await_event("toolchain provider negotiation", |event| { + event["type"] == "toolchainProviders" + }); + assert_eq!(negotiated["result"]["providers"], json!(["fixture"])); + session.await_event("session ready", |event| { + event["type"] == "stateChanged" && event["state"] == "ready" + }); + + let operation = "sdk-toolchain-query"; + let params = json!({ + "operationID": operation, "generation": 3, "providerID": "fixture", + "authority": {"kind": "local"}, "context": null, "workspace": null, + "tools": ["fixture-runtime"], + }); + core( + "lsp.toolchainRequest", + json!({ + "sessionId": session.id, "operationId": operation, "params": params, + "timeoutMilliseconds": 5000, + }), + ); + let completed = session.completion(operation); + assert!(completed.get("error").is_none(), "{completed}"); + let wire = &completed["result"]["value"]; + let decoded = core( + "toolchains.decodeReply", + json!({ + "registry": registry, "pluginID": plugin_id, "currentGeneration": 3, + "request": {"jsonrpc": "2.0", "id": wire["id"], "method": "toolchains/query", "params": params}, + "response": wire["response"], "platform": "macos", "filesystem": [], + }), + ); + assert_eq!(decoded["status"], "ok", "{decoded}"); + assert_eq!(decoded["snapshot"]["installations"], json!([])); + assert_eq!(decoded["snapshot"]["statements"], json!([])); + assert_eq!(decoded["snapshot"]["watch"], json!([])); + session.stop(); +} diff --git a/shared/plugins/sdk/e2e/plugin_sdk_rust.rs b/shared/plugins/sdk/e2e/plugin_sdk_rust.rs index 8600436b..9ee24015 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk_rust.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk_rust.rs @@ -8,6 +8,14 @@ mod plugin_sdk; +#[test] +fn the_rust_sdk_toolchain_provider_negotiates_and_answers_through_core() { + let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_RUST_SAMPLE") else { + return; + }; + plugin_sdk::toolchains::run(&executable.to_string_lossy()); +} + #[test] fn the_rust_sdk_import_provider_reads_a_selected_source_through_core() { let Some(executable) = std::env::var_os("LITHE_PLUGIN_SDK_RUST_SAMPLE") else { diff --git a/shared/plugins/sdk/rust/Cargo.lock b/shared/plugins/sdk/rust/Cargo.lock index 57d08c5f..9f4e727e 100644 --- a/shared/plugins/sdk/rust/Cargo.lock +++ b/shared/plugins/sdk/rust/Cargo.lock @@ -19,6 +19,7 @@ name = "lithe-plugin-sdk" version = "0.4.0" dependencies = [ "base64", + "serde", "serde_json", ] @@ -61,6 +62,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 3ddbc1d3..6145929d 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -20,11 +20,12 @@ next to the SDK and changes with it: relayed by Core, with the `Caller` a function called that way sees. - **`litheKeymapImport`**: independently negotiated shortcut import providers reading only explicitly selected source snapshots. +- **`litheToolchains`**: [typed toolchain discovery providers](#toolchain-providers). - **`litheLogging`**: typed diagnostics, required at initialization; see [Logging](#logging). The SDK owns the wire format, negotiation, cancellation, and error mapping. -Your code supplies only handlers. It depends on `serde_json` and `base64`, runs +Your code supplies only handlers. It depends on `serde`, `serde_json` and `base64`, runs every call on a thread of its own, and needs Rust 1.87 or newer. This SDK has no build provider or VCS provider API; write build providers with @@ -40,6 +41,33 @@ installation there, although the Core end-to-end tests still drive the protocol. Which host services a session may call is reported at run time; see [Host services](#host-services). +## Toolchain providers + +Declare the same provider ID in the manifest's +[`toolchainProviders`](../../contract/v1/toolchains/README.md#provider-backend-negotiation) +and via `Backend::toolchain_provider`. The host offers the IDs it recognizes at +initialization. The SDK selects registered IDs in the offer and routes each +query to that handler: + +```rust +use lithe_plugin_sdk::{toolchains::ToolchainQueryResult, Backend}; + +let mut backend = Backend::new("version-manager"); +backend.toolchain_provider("manager", |_query, cancellation| { + cancellation.check()?; + // Read this manager's own data for query.tools and query.workspace. + Ok(ToolchainQueryResult::default()) +}).expect("valid provider ID"); +``` + +Handlers return installations, version statements and watch paths. An empty +result is valid. Set a statement's `installation` to `None` for an unmet +requirement. Use `ToolchainQueryError` for a query failure and check the +cancellation token during potentially long scans. The host observes native +filesystem facts, and Core validates the returned candidates with those facts. +The desktop does not yet declare this capability. The Rust SDK end-to-end test +runs the protocol through Core. + ## Shortcut import providers Declare `keymap_import_provider(id, handler)` before listening. The host diff --git a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs index 825989fd..c2acb5cd 100644 --- a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs +++ b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs @@ -16,6 +16,7 @@ use lithe_plugin_sdk::{ BackendHandle, Cancelled, Context, FunctionError, PluginError, SdkError, Value, }; +use lithe_plugin_sdk::toolchains::{ToolchainQueryError, ToolchainQueryResult}; use serde_json::json; use std::fs; use std::path::{Path, PathBuf}; @@ -46,6 +47,16 @@ fn main() { Ok(json!({"bindings": [{"commandID": "find-next", "keys": [{"key": "f3", "modifiers": []}]}]})) }).expect("valid fixture provider"); + backend + .toolchain_provider("fixture", |query, cancellation| { + cancellation.check()?; + if query.tools != ["fixture-runtime"] { + return Err(ToolchainQueryError::InvalidParams); + } + Ok(ToolchainQueryResult::default()) + }) + .expect("valid toolchain fixture provider"); + let notes = Arc::clone(&state); backend .function("note.save", move |params, context| { diff --git a/shared/plugins/sdk/rust/plugin-sdk/Cargo.toml b/shared/plugins/sdk/rust/plugin-sdk/Cargo.toml index 7097aabb..a307b7be 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/Cargo.toml +++ b/shared/plugins/sdk/rust/plugin-sdk/Cargo.toml @@ -8,5 +8,6 @@ rust-version.workspace = true publish = false [dependencies] +serde = { version = "1", features = ["derive"] } serde_json.workspace = true base64 = "0.22" diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs index 596167e4..250f3c01 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs @@ -20,6 +20,7 @@ use crate::protocol::{ offers, FUNCTIONS_VERSION, KEYMAP_IMPORT_VERSION, LOGGING_VERSION, MAX_FUNCTIONS, MAX_MESSAGE_BYTES, MAX_RESULT_BYTES, }; +use crate::toolchains::{self, ToolchainQuery, ToolchainQueryError, ToolchainQueryResult}; use crate::view::{ViewEvent, ViewResult}; use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use serde_json::{json, Map, Value}; @@ -39,6 +40,11 @@ type ShutdownHook = Box; type CommandHandler = Arc) -> Result<(), FunctionError> + Send + Sync>; type NotificationHandler = Arc Result<(), FunctionError> + Send + Sync>; +type ToolchainHandler = Arc< + dyn Fn(&ToolchainQuery, &Cancellation) -> Result + + Send + + Sync, +>; type Answer = Result; /// Host request for one selected shortcut source; also the operation its diagnostic facts name. @@ -60,6 +66,8 @@ pub(crate) struct State { pub(crate) functions: BTreeMap, keymap_providers: BTreeMap, selected_keymap_providers: BTreeSet, + toolchain_providers: BTreeMap, + selected_toolchain_providers: BTreeSet, pub(crate) logging: bool, pub(crate) logging_ready: bool, pub(crate) early_diagnostics: Vec, @@ -149,6 +157,8 @@ impl Backend { functions: BTreeMap::new(), keymap_providers: BTreeMap::new(), selected_keymap_providers: BTreeSet::new(), + toolchain_providers: BTreeMap::new(), + selected_toolchain_providers: BTreeSet::new(), logging: false, logging_ready: false, early_diagnostics: Vec::new(), @@ -268,6 +278,38 @@ impl Backend { Ok(self) } + /// Registers a provider ID declared in the plugin manifest. The handler + /// receives typed inputs and a cancellation token. The SDK echoes the + /// query identity in the reply, while Core validates the returned facts. + pub fn toolchain_provider(&mut self, id: &str, handler: F) -> Result<&mut Self, SdkError> + where + F: Fn(&ToolchainQuery, &Cancellation) -> Result + + Send + + Sync + + 'static, + { + if !toolchains::provider_id(id) { + return Err(SdkError::new( + "sdk.toolchain.invalidID", + "Invalid toolchain provider ID.", + )); + } + let mut state = lock(&self.shared.state); + if state.toolchain_providers.contains_key(id) + || state.toolchain_providers.len() >= toolchains::MAX_PROVIDERS + { + return Err(SdkError::new( + "sdk.toolchain.invalidRegistration", + "Duplicate provider or provider limit exceeded.", + )); + } + state + .toolchain_providers + .insert(id.to_string(), Arc::new(handler)); + drop(state); + Ok(self) + } + /// Runs before the `initialize` answer. A hook may read the host's /// params and add functions; an error refuses `initialize`, mapped like /// a handler's. @@ -450,6 +492,9 @@ impl Backend { Phase::Ready if method == KEYMAP_IMPORT_METHOD => { Shared::invoke_keymap(&self.shared, id, ¶ms) } + Phase::Ready if method == toolchains::METHOD => { + Shared::invoke_toolchain(&self.shared, id, params) + } Phase::Ready => self.shared.respond( &id, Err(rpc_error( @@ -548,6 +593,9 @@ impl Backend { let keymap_offer = params .pointer("/capabilities/experimental/litheKeymapImport") .cloned(); + let toolchain_offer = params + .pointer("/capabilities/experimental/litheToolchains") + .cloned(); let logging = offers( params.pointer("/capabilities/experimental/litheLogging"), LOGGING_VERSION, @@ -619,6 +667,27 @@ impl Backend { } } } + if let Some(offer) = + toolchain_offer.filter(|offer| offers(Some(offer), toolchains::VERSION)) + { + if let Some(providers) = offer["providers"] + .as_array() + .filter(|ids| ids.len() <= toolchains::MAX_PROVIDERS) + { + state.selected_toolchain_providers = providers + .iter() + .filter_map(Value::as_str) + .filter(|id| state.toolchain_providers.contains_key(*id)) + .map(str::to_string) + .collect(); + if !state.selected_toolchain_providers.is_empty() { + experimental.insert( + toolchains::CAPABILITY.into(), + json!({"version": toolchains::VERSION, "providers": state.selected_toolchain_providers}), + ); + } + } + } match functions_version { Some(version) => { let functions: Vec<_> = state @@ -869,6 +938,100 @@ impl Shared { } } + fn invoke_toolchain(shared: &Arc, id: Value, params: Value) { + let query = match ToolchainQuery::parse(¶ms) { + Ok(query) => query, + Err(error) => { + return shared.respond( + &id, + Err(error.response( + params["operationID"].as_str().unwrap_or_default(), + params["providerID"].as_str().unwrap_or_default(), + )), + ); + } + }; + let key = request_key(&id); + let cancellation = Cancellation::new(); + let handler = { + let mut state = lock(&shared.state); + let handler = if !state + .selected_toolchain_providers + .contains(&query.provider_id) + { + Err(ToolchainQueryError::MethodUnavailable) + } else if state.incoming.contains_key(&key) { + Err(ToolchainQueryError::InvalidParams) + } else { + let active = state + .incoming + .values() + .filter(|call| call.function_id == toolchains::METHOD) + .count(); + if active >= toolchains::MAX_RUNNING_QUERIES { + Err(ToolchainQueryError::LimitExceeded) + } else { + Ok(Arc::clone(&state.toolchain_providers[&query.provider_id])) + } + }; + if handler.is_ok() { + state.incoming.insert( + key.clone(), + Running { + function_id: toolchains::METHOD.to_string(), + cancellation: cancellation.clone(), + }, + ); + } + handler + }; + let handler = match handler { + Ok(handler) => handler, + Err(error) => { + return shared.respond( + &id, + Err(error.response(&query.operation_id, &query.provider_id)), + ) + } + }; + + let operation = query.operation_id.clone(); + let provider = query.provider_id.clone(); + let worker = Arc::clone(shared); + let thread_id = id.clone(); + let thread_key = key.clone(); + let spawned = thread::Builder::new() + .name("lithe-toolchain-query".into()) + .spawn(move || { + let outcome = catch_unwind(AssertUnwindSafe(|| handler(&query, &cancellation))) + .unwrap_or(Err(ToolchainQueryError::ProviderUnavailable)) + .and_then(|facts| query.answer(facts)) + .and_then(|result| { + if serde_json::to_vec(&result).map_or(usize::MAX, |bytes| bytes.len()) + > MAX_RESULT_BYTES + { + Err(ToolchainQueryError::LimitExceeded) + } else { + Ok(result) + } + }); + lock(&worker.state).incoming.remove(&thread_key); + let answer = cancellation + .check() + .map_err(ToolchainQueryError::from) + .and(outcome) + .map_err(|error| error.response(&query.operation_id, &query.provider_id)); + worker.respond(&thread_id, answer); + }); + if spawned.is_err() { + lock(&shared.state).incoming.remove(&key); + shared.respond( + &id, + Err(ToolchainQueryError::ProviderUnavailable.response(&operation, &provider)), + ); + } + } + fn invoke(shared: &Arc, id: Value, params: &Value) { let function_id = params["functionID"] .as_str() diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index 62ab19a4..8239f983 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -15,7 +15,8 @@ //! subscriptions, the commands and context changes the host notifies, and //! calls to the functions other plugins export through Core's relay //! ([`Functions`]) with the [`Caller`] of a function called that way; -//! - **`litheKeymapImport`**: shortcut import providers. +//! - **`litheKeymapImport`**: shortcut import providers; +//! - **`litheToolchains`**: [toolchain discovery providers](toolchains). //! //! The SDK requires `litheLogging` at initialization. //! @@ -37,6 +38,7 @@ mod host; mod panic_boundary; mod protocol; mod stdio; +pub mod toolchains; pub mod view; pub use backend::{ diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs b/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs new file mode 100644 index 00000000..668e6bba --- /dev/null +++ b/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs @@ -0,0 +1,275 @@ +//! Typed handler inputs and outputs for the version 0 toolchain provider protocol. + +use crate::Cancelled; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +pub(crate) const METHOD: &str = "toolchains/query"; +pub(crate) const CAPABILITY: &str = "litheToolchains"; +pub(crate) const VERSION: u64 = 0; +pub(crate) const MAX_PROVIDERS: usize = 8; +pub(crate) const MAX_RUNNING_QUERIES: usize = 8; +const MAX_INSTALLATIONS: usize = 512; +const MAX_STATEMENTS: usize = 256; +const MAX_WATCH_PATHS: usize = 256; + +/// A query routed to a provider selected during initialization. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ToolchainQuery { + #[serde(rename = "operationID")] + pub operation_id: String, + pub generation: u64, + #[serde(rename = "providerID")] + pub provider_id: String, + authority: Authority, + pub context: Option, + pub workspace: Option, + pub tools: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Authority { + kind: String, + id: Option, +} + +/// Identity and generation of the host workspace context. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ToolchainQueryContext { + #[serde(rename = "contextID")] + pub context_id: String, + pub generation: u64, +} + +/// The opened root and the workspace-relative directory being resolved. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ToolchainWorkspace { + #[serde(rename = "rootID")] + pub root_id: String, + pub root: String, + pub directory: String, +} + +/// Facts a provider reports. The host obtains its own filesystem observations +/// and Core validates them before using these facts for resolution. +#[derive(Debug, Default, Serialize)] +pub struct ToolchainQueryResult { + pub installations: Vec, + pub statements: Vec, + pub watch: Vec, +} + +/// A discovered installation, with a native home path. +#[derive(Debug, Serialize)] +pub struct ToolchainInstallation { + pub tool: String, + pub version: String, + pub home: String, +} + +/// An environment or version requirement. Use `installation: None` to report +/// a requirement that could not be satisfied. +#[derive(Debug, Serialize)] +pub struct ToolchainStatement { + pub tool: String, + pub scope: ToolchainScope, + pub source: String, + pub request: String, + pub installation: Option, + pub kind: ToolchainStatementKind, + pub reader: String, +} + +/// Scope of a version selection or declaration. +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ToolchainScope { + Project, + Global, +} + +/// Whether the provider read an environment selection or a version declaration. +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ToolchainStatementKind { + Environment, + Declaration, +} + +/// A toolchain query failure with the protocol's stable error code. Missing +/// installations and unmet versions belong in a successful query result. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ToolchainQueryError { + MethodUnavailable, + InvalidParams, + Cancelled, + PermissionDenied, + AuthorityUnsupported, + Timeout, + ProviderUnavailable, + InvalidReply, + LimitExceeded, + UnsafePath, + OperationExpired, +} + +impl From for ToolchainQueryError { + fn from(_: Cancelled) -> Self { + Self::Cancelled + } +} + +impl ToolchainQueryError { + pub(crate) fn response(self, operation: &str, provider: &str) -> Value { + let (number, code, message) = match self { + Self::MethodUnavailable => ( + -32601, + "methodUnavailable", + "The provider was not negotiated.", + ), + Self::InvalidParams => ( + -32602, + "invalidParams", + "Invalid toolchain query parameters.", + ), + Self::Cancelled => (-32800, "cancelled", "The toolchain query was cancelled."), + Self::PermissionDenied => ( + -32070, + "permissionDenied", + "The toolchain query was not permitted.", + ), + Self::AuthorityUnsupported => ( + -32071, + "authorityUnsupported", + "The provider accepts only local queries.", + ), + Self::Timeout => (-32072, "timeout", "The toolchain query timed out."), + Self::ProviderUnavailable => ( + -32073, + "providerUnavailable", + "The toolchain provider is unavailable.", + ), + Self::InvalidReply => (-32074, "invalidReply", "The toolchain response is invalid."), + Self::LimitExceeded => ( + -32075, + "limitExceeded", + "The toolchain query exceeded its limits.", + ), + Self::UnsafePath => (-32076, "unsafePath", "The toolchain path is unsafe."), + Self::OperationExpired => ( + -32077, + "operationExpired", + "The toolchain query is no longer current.", + ), + }; + json!({ + "code": number, + "message": message, + "data": { + "code": format!("plugin.toolchain.{code}"), + "operationID": identity(operation).then_some(operation), + "providerID": provider_id(provider).then_some(provider), + }, + }) + } +} + +impl ToolchainQuery { + pub(crate) fn parse(params: &Value) -> Result { + let query = Self::deserialize(params).map_err(|_| ToolchainQueryError::InvalidParams)?; + if !params + .as_object() + .is_some_and(|p| p.contains_key("context") && p.contains_key("workspace")) + || !identity(&query.operation_id) + || !provider_id(&query.provider_id) + || query.generation == 0 + || query.tools.is_empty() + || query.tools.len() > 64 + || !query.tools.iter().all(|tool| tool_id(tool)) + || !query.tools.windows(2).all(|pair| pair[0] < pair[1]) + || query.workspace.is_some() && query.context.is_none() + || query + .context + .as_ref() + .is_some_and(|context| context.generation == 0 || !identity(&context.context_id)) + { + return Err(ToolchainQueryError::InvalidParams); + } + if query.authority.kind == "remote" && query.authority.id.as_deref().is_some_and(identity) { + return Err(ToolchainQueryError::AuthorityUnsupported); + } + if query.authority.kind != "local" || params["authority"].get("id").is_some() { + return Err(ToolchainQueryError::InvalidParams); + } + if let Some(workspace) = &query.workspace { + let directory = &workspace.directory; + if !identity(&workspace.root_id) + || !bounded(&workspace.root, 4096) + || !bounded(directory, 2048) + || (directory != "." + && (directory.contains(['\\', ':']) + || directory + .split('/') + .any(|part| matches!(part, "" | "." | "..")))) + { + return Err(ToolchainQueryError::InvalidParams); + } + } + Ok(query) + } + + pub(crate) fn answer(&self, facts: ToolchainQueryResult) -> Result { + if facts.installations.len() > MAX_INSTALLATIONS + || facts.statements.len() > MAX_STATEMENTS + || facts.watch.len() > MAX_WATCH_PATHS + { + return Err(ToolchainQueryError::LimitExceeded); + } + let mut result = + serde_json::to_value(facts).map_err(|_| ToolchainQueryError::InvalidReply)?; + result["operationID"] = json!(self.operation_id); + result["generation"] = json!(self.generation); + result["providerID"] = json!(self.provider_id); + Ok(result) + } +} + +fn bounded(value: &str, maximum: usize) -> bool { + !value.is_empty() && value.len() <= maximum && !value.chars().any(char::is_control) +} + +fn identity(value: &str) -> bool { + bounded(value, 128) + && value.as_bytes()[0].is_ascii_alphanumeric() + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte)) +} + +pub(crate) fn provider_id(value: &str) -> bool { + bounded(value, 64) + && value.as_bytes()[0].is_ascii_lowercase() + && value + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') +} + +fn tool_id(value: &str) -> bool { + value.len() <= 192 + && match value.split_once(':') { + Some((namespace, local)) => { + provider_id(local) + && namespace.split(['.', '-']).all(|part| { + !part.is_empty() + && part + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) + }) + } + None => provider_id(value), + } +} diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs new file mode 100644 index 00000000..38941199 --- /dev/null +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs @@ -0,0 +1,130 @@ +//! Exercises toolchain queries over the SDK's actual framed transport. + +mod common; + +use common::Host; +use lithe_plugin_sdk::toolchains::{ + ToolchainInstallation, ToolchainQueryError, ToolchainQueryResult, +}; +use lithe_plugin_sdk::Backend; +use serde_json::{json, Value}; +use std::sync::mpsc; +use std::time::Duration; + +fn query(provider: &str) -> Value { + json!({ + "operationID": "query-1", "generation": 3, "providerID": provider, + "authority": {"kind": "local"}, "context": null, "workspace": null, + "tools": ["fixture"], + }) +} + +fn initialize(host: &mut Host, providers: Value, version: u64) -> Value { + host.request( + 0, + "initialize", + json!({"capabilities": {"experimental": { + "litheLogging": {"versions": [0]}, + "litheToolchains": {"versions": [version], "providers": providers} + }}}), + ); + host.answer(0).0["result"]["capabilities"]["experimental"]["litheToolchains"].clone() +} + +fn finish(mut host: Host) { + host.request("shutdown", "shutdown", Value::Null); + assert_eq!(host.answer("shutdown").0["result"], Value::Null); + host.notify("exit", Value::Null); + assert_eq!(host.exit_code(), 0); +} + +#[test] +fn negotiates_only_offered_providers_and_echoes_query_identity() { + let mut backend = Backend::new("test-backend"); + backend + .toolchain_provider("fixture", |request, cancellation| { + assert_eq!(request.tools, ["fixture"]); + cancellation.check()?; + Ok(ToolchainQueryResult { + installations: vec![ToolchainInstallation { + tool: "fixture".into(), + version: "2.0".into(), + home: "/example/install".into(), + }], + ..ToolchainQueryResult::default() + }) + }) + .unwrap(); + backend + .toolchain_provider("not-offered", |_, _| panic!("unoffered handler ran")) + .unwrap(); + let mut host = Host::start(backend); + assert_eq!( + initialize(&mut host, json!(["fixture", "unknown"]), 0), + json!({ + "version": 0, "providers": ["fixture"] + }) + ); + host.request("call-1", "toolchains/query", query("fixture")); + let reply = host.answer("call-1").0; + assert_eq!( + reply["result"], + json!({ + "operationID": "query-1", "generation": 3, "providerID": "fixture", + "installations": [{"tool": "fixture", "version": "2.0", "home": "/example/install"}], + "statements": [], "watch": [] + }) + ); + host.request(2, "toolchains/query", query("not-offered")); + assert_eq!( + host.answer(2).0["error"]["data"]["code"], + "plugin.toolchain.methodUnavailable" + ); + let mut malformed = query("fixture"); + malformed["tools"] = json!(["fixture", "fixture"]); + host.request(3, "toolchains/query", malformed); + assert_eq!(host.answer(3).0["error"]["code"], -32602); + finish(host); +} + +#[test] +fn declines_an_unoffered_protocol_version() { + let mut backend = Backend::new("test-backend"); + backend + .toolchain_provider("fixture", |_, _| panic!("unnegotiated handler ran")) + .unwrap(); + let mut host = Host::start(backend); + assert!(initialize(&mut host, json!(["fixture"]), 1).is_null()); + host.request(1, "toolchains/query", query("fixture")); + assert_eq!(host.answer(1).0["error"]["code"], -32601); + finish(host); +} + +#[test] +fn cancellation_returns_the_protocol_error_with_the_original_identity() { + let mut backend = Backend::new("test-backend"); + let (started, entered) = mpsc::channel(); + backend + .toolchain_provider("fixture", move |_, cancellation| { + started.send(()).unwrap(); + cancellation.wait_timeout(Duration::from_secs(3)); + cancellation.check()?; + Err(ToolchainQueryError::Timeout) + }) + .unwrap(); + let mut host = Host::start(backend); + initialize(&mut host, json!(["fixture"]), 0); + host.request("query-1", "toolchains/query", query("fixture")); + entered + .recv_timeout(Duration::from_secs(3)) + .expect("provider started"); + host.notify("$/cancelRequest", json!({"id": "query-1"})); + assert_eq!( + host.answer("query-1").0["error"], + json!({ + "code": -32800, "message": "The toolchain query was cancelled.", + "data": {"code": "plugin.toolchain.cancelled", "operationID": "query-1", "providerID": "fixture"} + }) + ); + finish(host); +} From a935eed9e688bb3ff89f88d507f89bd36519d865 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 10:05:00 +0800 Subject: [PATCH 2/4] style(sdk): format toolchain sample import --- shared/plugins/sdk/rust/examples/sample-backend/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs index c2acb5cd..1e132db9 100644 --- a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs +++ b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs @@ -13,10 +13,10 @@ //! (`files.nextChange`), answers its command with a message in the window //! it ran in, and lists the open workspaces when they change. +use lithe_plugin_sdk::toolchains::{ToolchainQueryError, ToolchainQueryResult}; use lithe_plugin_sdk::{ BackendHandle, Cancelled, Context, FunctionError, PluginError, SdkError, Value, }; -use lithe_plugin_sdk::toolchains::{ToolchainQueryError, ToolchainQueryResult}; use serde_json::json; use std::fs; use std::path::{Path, PathBuf}; From e56af624d3f615982f90c6249f7aa43c9b3b218e Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 14:14:02 +0800 Subject: [PATCH 3/4] fix(sdk): keep unregistered request names out of errors --- .../plugins/sdk/rust/plugin-sdk/src/backend.rs | 4 ++-- .../plugins/sdk/rust/plugin-sdk/tests/session.rs | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs index 250f3c01..c63962f9 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs @@ -499,7 +499,7 @@ impl Backend { &id, Err(rpc_error( error_codes::METHOD_NOT_FOUND, - format!("Unsupported method: {method}"), + "Unsupported method.", )), ), Phase::Idle | Phase::Listening | Phase::Initializing => self.shared.respond( @@ -1076,7 +1076,7 @@ impl Shared { &id, Err(rpc_error( error_codes::INVALID_PARAMS, - format!("Function {function_id} is not registered."), + "The requested function is not registered.", )), ); }; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/session.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/session.rs index 3c0cb4df..da20ab7e 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/session.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/session.rs @@ -80,6 +80,22 @@ fn follows_the_lsp_lifecycle() { assert_eq!(host.exit_code(), 0); } +#[test] +fn unknown_request_names_are_not_reflected_in_errors() { + let mut host = Host::start(echo_backend()); + host.initialize(json!([0])); + const REQUEST_TEXT: &str = "unregistered/fixture-request-text"; + host.request(1, REQUEST_TEXT, Value::Null); + host.invoke(2, REQUEST_TEXT, json!({})); + for (id, code) in [(1, -32601), (2, -32602)] { + let (reply, notifications) = host.answer(id); + assert_eq!(reply["error"]["code"], code); + assert!(!reply.to_string().contains(REQUEST_TEXT)); + assert!(notifications.is_empty(), "{notifications:?}"); + } + host.close(); +} + #[test] fn exit_without_shutdown_and_a_broken_frame_end_with_a_failure() { let mut host = Host::start(echo_backend()); From a19319558b1cd0cd3c9b865067fde05346550d74 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 16:56:57 +0800 Subject: [PATCH 4/4] fix(sdk): count the full toolchain reply against the limit --- .../sdk/rust/plugin-sdk/src/backend.rs | 25 +++++++---- .../sdk/rust/plugin-sdk/src/toolchains.rs | 1 + .../sdk/rust/plugin-sdk/tests/toolchains.rs | 41 +++++++++++++++++++ 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs index c63962f9..44a90a45 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs @@ -47,6 +47,10 @@ type ToolchainHandler = Arc< >; type Answer = Result; +fn success_response(id: &Value, result: Value) -> Value { + json!({ "jsonrpc": "2.0", "id": id, "result": result }) +} + /// Host request for one selected shortcut source; also the operation its diagnostic facts name. const KEYMAP_IMPORT_METHOD: &str = "lithe/keymap/import"; @@ -841,7 +845,7 @@ impl Shared { fn respond(&self, id: &Value, answer: Answer) { self.write(&match answer { - Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }), + Ok(result) => success_response(id, result), Err(error) => json!({ "jsonrpc": "2.0", "id": id, "error": error }), }); } @@ -1007,21 +1011,28 @@ impl Shared { .unwrap_or(Err(ToolchainQueryError::ProviderUnavailable)) .and_then(|facts| query.answer(facts)) .and_then(|result| { - if serde_json::to_vec(&result).map_or(usize::MAX, |bytes| bytes.len()) - > MAX_RESULT_BYTES + // Core counts the complete response, including its JSON-RPC ID. + let response = success_response(&thread_id, result); + if serde_json::to_vec(&response).map_or(usize::MAX, |bytes| bytes.len()) + > toolchains::MAX_REPLY_BYTES { Err(ToolchainQueryError::LimitExceeded) } else { - Ok(result) + Ok(response) } }); lock(&worker.state).incoming.remove(&thread_key); - let answer = cancellation + match cancellation .check() .map_err(ToolchainQueryError::from) .and(outcome) - .map_err(|error| error.response(&query.operation_id, &query.provider_id)); - worker.respond(&thread_id, answer); + { + Ok(response) => worker.write(&response), + Err(error) => worker.respond( + &thread_id, + Err(error.response(&query.operation_id, &query.provider_id)), + ), + } }); if spawned.is_err() { lock(&shared.state).incoming.remove(&key); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs b/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs index 668e6bba..28169cca 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/toolchains.rs @@ -9,6 +9,7 @@ pub(crate) const CAPABILITY: &str = "litheToolchains"; pub(crate) const VERSION: u64 = 0; pub(crate) const MAX_PROVIDERS: usize = 8; pub(crate) const MAX_RUNNING_QUERIES: usize = 8; +pub(crate) const MAX_REPLY_BYTES: usize = 1024 * 1024; const MAX_INSTALLATIONS: usize = 512; const MAX_STATEMENTS: usize = 256; const MAX_WATCH_PATHS: usize = 256; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs index 38941199..dc23c29a 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/toolchains.rs @@ -87,6 +87,47 @@ fn negotiates_only_offered_providers_and_echoes_query_identity() { finish(host); } +#[test] +fn reply_budget_includes_the_json_rpc_envelope() { + const LIMIT: usize = 1024 * 1024; + let empty_reply = json!({ + "jsonrpc": "2.0", "id": "ok", "result": { + "operationID": "query-1", "generation": 3, "providerID": "fixture", + "installations": [], "statements": [], "watch": ["/fixture/"] + } + }); + let watch_path = format!( + "/fixture/{}", + "x".repeat(LIMIT - empty_reply.to_string().len()) + ); + let mut backend = Backend::new("test-backend"); + backend + .toolchain_provider("fixture", move |_, _| { + Ok(ToolchainQueryResult { + watch: vec![watch_path.clone()], + ..ToolchainQueryResult::default() + }) + }) + .unwrap(); + let mut host = Host::start(backend); + initialize(&mut host, json!(["fixture"]), 0); + + host.request("ok", "toolchains/query", query("fixture")); + let at_limit = host.answer("ok").0; + assert!(at_limit.get("result").is_some()); + assert_eq!(at_limit.to_string().len(), LIMIT); + + // The same result with a longer request ID crosses the reply limit. + host.request("big", "toolchains/query", query("fixture")); + let over_limit = host.answer("big").0; + assert_eq!(over_limit["error"]["code"], -32075); + assert_eq!( + over_limit["error"]["data"], + json!({"code": "plugin.toolchain.limitExceeded", "operationID": "query-1", "providerID": "fixture"}) + ); + finish(host); +} + #[test] fn declines_an_unoffered_protocol_version() { let mut backend = Backend::new("test-backend");